text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import merge from 'lodash.merge'; import get from 'lodash.get'; import fs from 'fs-extra'; import Metalsmith from 'metalsmith'; import inquirer from 'inquirer'; import match from 'minimatch'; import consolidate from 'consolidate'; import Handlebars from 'handlebars'; import multimatch from 'multimatch'; import simpleGit from 'simple-git'; import { log as leoLog } from '@jdfed/leo-utils'; import { IFiles, IMetaData, IFilterFilesMap, IHelper } from './interface'; const log = leoLog.scope('generator'); // 这个库没有@types发布接口 const downloadGitRepo = require('download-git-repo'); type metalsmithCB = (files: IFiles, metalsmith: Metalsmith, done: Function) => void; class Generator { // 虚拟目录路径,在linux中一般都是 ~/.leo/templates cachePath: string; // ~/.leo/templates/${templateName} localTemplatePath: string; // 远程模板地址 repoRemoteAddress: string; // 当前虚拟目录模板下的template文件夹 currentTemplatePath: string; // 当前虚拟目录模板下的meta.js currentMetaPath: string; templateName: string; projectName: string; projectPath: string; answer: Record<string, any>; officialEnv: Record<string, any>; metalsmith: Metalsmith; // 默认编译文件 defaultCompileFiles: string[]; leoRC: { [key: string]: any }; leoConfig: { [key: string]: any }; metaConfig: { [key: string]: any }; hooks: { // 返回true表示接管构建任务,不再执行原有逻辑。发生在下载模板完成后。 beforeGenerate: (generator: Generator) => Promise<boolean>; afterGenerate: (generator: Generator) => Promise<void>; /** * 参考项目https://github.com/segmentio/metalsmith * 以及@types/metalsmith * 渲染占位符时的hook,如果实现讲自己接管渲染占位符 */ renderTemplatePlaceholder: ( generator: Generator, ) => (files: IFiles, metalsmith: Metalsmith, done: Function) => void; /** * 最终渲染文件的hook,理论上可以做任何事包括渲染占位符 */ renderTemplateFile: ( generator: Generator, ) => (files: IFiles, metalsmith: Metalsmith, done: Function) => void; } = { beforeGenerate: null, afterGenerate: null, renderTemplatePlaceholder: null, renderTemplateFile: null, }; options: { useCache: false; repo: ''; }; constructor(params: { templateName: string; projectName: string; leoConfig: { [key: string]: any }; options: { [key: string]: any }; cachePath: string; // 缓存文件存放的路径 }) { this.templateName = params.templateName; this.projectName = params.projectName; this.cachePath = params.cachePath; this.leoConfig = params.leoConfig; // 模版的git地址 this.repoRemoteAddress = `${this.leoConfig.gitTemplateGroupURL}/${this.templateName}-template.git`; // 本地模版的地址 this.localTemplatePath = `${this.cachePath}/${this.templateName}-template`; this.currentTemplatePath = `${this.localTemplatePath}/template`; this.currentMetaPath = `${this.localTemplatePath}/meta.js`; this.defaultCompileFiles = ['package.json', this.leoConfig.rcFileName]; // 默认是 leorc.js this.answer = {}; this.officialEnv = {}; this.metalsmith = null; // 合并命令行设置的参数 this.options = merge({}, this.options, params.options); } async start() { try { await this.prepare(); this.answer = await this.askQuestions(get(this.metaConfig, 'prompts', [])); this.officialEnv = await this.getGeneratorEnv(); // 若beforeGenerate为true直接return,相当于模版方自己接管 if (this.hooks.beforeGenerate && (await this.hooks.beforeGenerate(this)) === true) { return; } await this.generate(); await this.initGitRepo(this.options.repo); // 构建结束之后执行afterGenerate this.hooks.afterGenerate && (await this.hooks.afterGenerate(this)); } catch (e) { log.error('generator', (e as Error).message); process.exit(1); } } async getGeneratorEnv(): Promise<{ [key: string]: any }> { // 官方系统环境变量 return { $projectName: this.projectName, }; } async prepare() { const isUseCache = await this.useLocalCacheTemplate(); if (!isUseCache) { await this.downloadTemplate(); } // 判断是否有template的文件夹 const hasCurTemplateFolder = await fs.pathExists(this.currentTemplatePath); if (!hasCurTemplateFolder) { throw new Error('模版下不存在template目录'); } const projectPath = `${process.cwd()}/${this.projectName}`; const currentHasProject = await fs.pathExists(projectPath); if (this.leoConfig.isDebugger) { log.debug('generator.start', 'projectPath:', projectPath); } if (currentHasProject) { throw new Error('当前目录下已存在相同目录名'); } this.projectPath = projectPath; // 不再获取leorc,改为获取模版的 meta.js 的配置 this.metaConfig = await this.getTemplateMetaConfig(); // 从 meta.js 中获取配置的 hooks merge(this.hooks, get(this.metaConfig, 'hooks', {})); } async generate(): Promise<any> { this.metalsmith = Metalsmith(this.currentTemplatePath); // 获取并注册用户的自定义handlebars的helper函数 const customHelpers = get(this.metaConfig, 'helpers', {}); if (Object.keys(customHelpers).length > 0) { this.registerCustomHelper(customHelpers); } Object.assign(this.metalsmith.metadata(), this.officialEnv, this.answer, customHelpers); const filterFilesMap = get(this.metaConfig, 'filterFilesMap', null); if (filterFilesMap) { this.metalsmith = this.metalsmith.use(this.filterFiles(filterFilesMap)); // 删除文件 } const compileWhiteList = get(this.metaConfig, 'compileWhiteList', null); let renderTemplatePlaceholder = this.renderTemplatePlaceholder(compileWhiteList); if (this.hooks.renderTemplatePlaceholder) { renderTemplatePlaceholder = this.hooks.renderTemplatePlaceholder(this); } this.metalsmith = this.metalsmith.use(renderTemplatePlaceholder); // 渲染占位符 if (this.hooks.renderTemplateFile) { this.metalsmith = this.metalsmith.use(this.hooks.renderTemplateFile(this)); } return new Promise((resolve, reject) => { this.metalsmith .source('.') .destination(this.projectPath) .clean(false) .build(async (err: Error) => { if (err) { reject(err); return; } log.success('Generator构建完成'); resolve(0); }); }); } /** * 询问用户 * @params prompts * @return {Promise} 保存用户回答的答案 */ async askQuestions(prompts: any[]): Promise<{ [key: string]: any }> { return inquirer.prompt(prompts); } /** * 根据用户的回答的结果过滤相关文件 * @params {IFilterFilesMap} filterFilesMap * @return {metalsmithCB} 执行done()回调表示执行完毕 */ filterFiles(filterFilesMap: IFilterFilesMap): metalsmithCB { /* eslint no-param-reassign: "error" */ return (files: IFiles, metalsmith: Metalsmith, done: Function) => { // 如果不需要过滤文件直接终止 if (!filterFilesMap) { return done(); } const metaData: IMetaData = metalsmith.metadata(); const fileNameList = Object.keys(files); const filtersList = Object.keys(filterFilesMap); if (this.leoConfig.isDebugger) { log.debug('generator.filterFiles.before', Object.keys(files)); } // 根据用户所选择的配置所对应的文件名或文件夹名进行匹配 filtersList.forEach((filter) => { fileNameList.forEach((filename) => { // 匹配filtersList里面需要过滤的文件,(文件夹及文件的匹配需要通过minimatch库进行匹配,无法直接通过数组的方法直接匹配) // 例如src/router/**/*/代表匹配router下所有文件 // dot为true表示可以匹配.开头的文件,例如.eslintrc.js等 if (match(filename, filter, { dot: true })) { const conditionKey = filterFilesMap[filter]; // 对用户不需要的配置的文件进行删除处理 if (!metaData[conditionKey]) { delete files[filename]; } } }); }); if (this.leoConfig.isDebugger) { log.debug('generator.filterFiles.after', Object.keys(files)); } // 终止回掉 done(); }; } /** * 渲染template文件, 若有renderTemplatePlaceholder钩子函数则不执行官方的渲染 * @return {metalsmithCB} 执行done()回调表示执行完毕 */ renderTemplatePlaceholder(compileWhiteList: string[] | null): metalsmithCB { /* eslint no-param-reassign: "error" */ return (files: IFiles, metalsmith: Metalsmith, done: Function) => { const keys = Object.keys(files); const metalsmithMetadata = metalsmith.metadata(); // 判断模版是否有白名单 const hasWhiteList = this.existCompileWhiteList(compileWhiteList); // 循环查询有模版语法的的文件,替换相关handlebars语法的地方,然后生成新的文件 keys.forEach((fileName) => { const str = files[fileName].contents.toString(); const shouldCompileFile = this.isDefaultCompileFile(fileName) || this.matchCompileFile(hasWhiteList, fileName, compileWhiteList); // 匹配有handlebars语法的文件 if (shouldCompileFile && /{{([^{}]+)}}/g.test(str)) { consolidate.handlebars.render(str, metalsmithMetadata, (err: Error, res: string) => { if (err) { throw new Error(`模版文件${fileName}渲染出现异常`); } files[fileName].contents = Buffer.from(res); }); } }); done(); }; } /** * 初始化 git 并关联远程仓库(如传入仓库地址) * @params * @return {Promise<any>} */ async initGitRepo(repo: string): Promise<any> { if (!repo) { return; } const git = simpleGit(this.projectPath); log.await(`正在关联远程仓库:${repo}`); await git.init(); await git.addRemote('origin', repo); await git.add(['.']); await git.commit(`leo init from ${this.templateName}-template`); await git.push('origin', 'master', ['--set-upstream']); log.success('关联成功'); } /** * 判断是否使用缓存模版,若使用需判断是否存在,不存在则抛出异常 * @params * @return {Promise<boolean>} */ private async useLocalCacheTemplate(): Promise<boolean> { if (!this.options.useCache) { return false; } const templatePath = `${this.localTemplatePath}`; const hasTemplatePath = await fs.pathExists(templatePath); if (!hasTemplatePath) { throw new Error(`${templatePath} 不存在,无法使用缓存模版`); } else { return true; } } /** * 下载远程模板 * @return {Promise} */ private async downloadTemplate(): Promise<void> { log.await('generator', `下载远程模板: ${this.templateName}-template`); const gitPath = this.repoRemoteAddress; const target = this.localTemplatePath; if (this.leoConfig.isDebugger) { log.debug('generator.downloadTemplate', `gitPath:${gitPath} target:${target}`); } // 删除本地缓存文件后创建一个新的空文件 await fs.remove(target); await fs.ensureDir(target); // 下载仓库中的模板至缓存文件夹 return new Promise((resolve, reject) => { downloadGitRepo( `direct:${gitPath}`, target, { clone: true, headers: this.leoConfig.gitTemplateLikeQueryHeader || {} }, (err: Error) => { if (err) { return reject(new Error(`下载模板错误:${err}`)); } log.success('generator', '模板下载成功'); return resolve(); }, ); }); } /** * 获取模版的 meta.js 文件 * @return Promise<null | Object> meta.js的值 */ private async getTemplateMetaConfig(): Promise<null | Object> { const templateMetaPath = `${this.localTemplatePath}/meta.js`; const templatePackagePath = `${this.localTemplatePath}/package.json`; const hasMeta = await fs.pathExists(templateMetaPath); const hasPackage = await fs.pathExists(templatePackagePath); if (hasPackage) { log.await('====安装template的依赖===='); await this.installTemplatePkg(); } if (hasMeta) { const metaConfig = require(templateMetaPath); if (this.leoConfig.isDebugger) { log.debug('generator.getTemplateMetaConfig', JSON.stringify(metaConfig)); } return metaConfig; } return null; } /** * 判断metaConfig是否存在编译白名单 * @return {boolean} */ private existCompileWhiteList(compileWhiteList: string[] | null): boolean { return !!compileWhiteList && Array.isArray(compileWhiteList) && compileWhiteList.length > 0; } /** * 判断当前文件是否需要编译 * @return {boolean} */ private matchCompileFile( hasWhiteList: boolean, fileName: string, compileWhiteList: string[] | null, ): boolean { return ( !hasWhiteList || (hasWhiteList && multimatch([fileName], compileWhiteList, { dot: true }).length > 0) ); } /** * 默认自动编译的文件 * @return {boolean} */ private isDefaultCompileFile(fileName: string): boolean { return this.defaultCompileFiles.indexOf(fileName) >= 0; } /** * 自动安装模版需要的package.json * @return {Promise<void>} */ private async installTemplatePkg(): Promise<void> { const npmi = require('npminstall'); try { await npmi({ production: true, root: this.localTemplatePath, registry: 'http://registry.m.jd.com/', }); } catch (e) { log.warn('template依赖包安装存在问题', e); } log.success('installTemplatePkg', '安装成功'); } /** * 注册用户自定义handlebars的helper函数 * https://handlebarsjs.com/api-reference/runtime.html#handlebars-registerhelper-name-helper * @return {void} */ private registerCustomHelper(helpers: IHelper): void { Object.keys(helpers).forEach((key: string) => { Handlebars.registerHelper(key, helpers[key]); }); } } export default Generator;
the_stack
import { Options, normalizeOptions, UniqueKey, OptionsNormalized, } from './optionUtils'; import { generateAST, BlockNode, FieldNode, TextNode, EntryNode, RootNode, } from './bibtex-parser'; import { titleCase, escapeSpecialCharacters, alphaNum, wrapText, convertCRLF, unwrapText, addEnclosingBraces, escapeURL, removeEnclosingBraces, limitAuthors, formatPageRange, } from './utils'; type SortIndex = Map<string, string>; export type Warning = { code: 'MISSING_KEY' | 'DUPLICATE_KEY' | 'DUPLICATE_ENTRY'; message: string; }; export type BibTeXTidyResult = { bibtex: string; warnings: Warning[]; count: number; }; //prettier-ignore const MONTHS: Set<string> = new Set([ 'jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec' ]); export function tidy(input: string, options_: Options = {}): BibTeXTidyResult { const options = normalizeOptions(options_); const { omit, tab, align, sortFields: fieldOrder, merge, space, duplicates, trailingCommas, removeDuplicateFields, removeEmptyFields, lowercase, } = options; const indent: string = tab ? '\t' : ' '.repeat(space); const uniqCheck: Map<UniqueKey, boolean> = new Map(); if (duplicates) { for (const key of duplicates) { uniqCheck.set(key, !!merge); } } if (!uniqCheck.has('key')) { // always check key uniqueness uniqCheck.set('key', false); } const omitFields: Set<string> = new Set(omit); input = convertCRLF(input); // Parse the bibtex and retrieve the items (includes comments, entries, strings, preambles) const ast = generateAST(input); // Set of entry keys, used to check for duplicate key warnings const keys: Map<string, EntryNode> = new Map(); const dois: Map<string, EntryNode> = new Map(); const citations: Map<string, EntryNode> = new Map(); const abstracts: Map<string, EntryNode> = new Map(); // Warnings to be output at the end const warnings: Warning[] = []; const duplicateEntries = new Set<EntryNode>(); const entries: EntryNode[] = ast.children.flatMap((node) => node.type !== 'text' && node.block?.type === 'entry' ? [node.block] : [] ); const valueLookup = generateValueLookup(entries, options); for (const entry of entries) { if (!entry.key) { warnings.push({ code: 'MISSING_KEY', message: `${entry.type} entry does not have an entry key.`, }); } const entryValues = valueLookup.get(entry)!; for (const [key, doMerge] of uniqCheck) { let duplicateOf: EntryNode | undefined; switch (key) { case 'key': if (!entry.key) continue; duplicateOf = keys.get(entry.key); if (!duplicateOf) keys.set(entry.key, entry); break; case 'doi': const doi = alphaNum(entryValues.get('doi') ?? ''); if (!doi) continue; duplicateOf = dois.get(doi); if (!duplicateOf) dois.set(doi, entry); break; case 'citation': const ttl = entryValues.get('title'); const aut = entryValues.get('author'); if (!ttl || !aut) continue; const cit: string = alphaNum(aut.split(/,| and/)[0]) + ':' + alphaNum(ttl); duplicateOf = citations.get(cit); if (!duplicateOf) citations.set(cit, entry); break; case 'abstract': const abstract = alphaNum(entryValues.get('abstract') ?? ''); const abs = abstract?.slice(0, 100); if (!abs) continue; duplicateOf = abstracts.get(abs); if (!duplicateOf) abstracts.set(abs, entry); break; } if (duplicateOf) { if (doMerge) { duplicateEntries.add(entry); warnings.push({ code: 'DUPLICATE_ENTRY', message: `${entry.key} appears to be a duplicate of ${duplicateOf.key} and was removed.`, }); switch (merge) { case 'last': duplicateOf.key = entry.key; duplicateOf.fields = entry.fields; break; case 'combine': case 'overwrite': for (const field of entry.fields) { const existing = duplicateOf.fields.find( (f) => f.name.toLocaleLowerCase() === field.name.toLocaleLowerCase() ); if (!existing) { duplicateOf.fields.push(field); } else if (merge === 'overwrite') { existing.value = field.value; } } break; // TODO: case 'keep-both' } } else { warnings.push({ code: 'DUPLICATE_KEY', message: `${entry.key} is a duplicate entry key.`, }); } } } } // sort needs to happen after merging all entries is complete sortEntries(ast, valueLookup, options); // output the tidied bibtex let bibtex: string = ''; for (const child of ast.children) { if (child.type === 'text') { bibtex += formatComment(child.text, options); } else { if (!child.block) throw new Error('FATAL!'); switch (child.block.type) { case 'preamble': case 'string': // keep preambles as they were bibtex += `${child.block.raw}\n`; break; case 'comment': bibtex += formatComment(child.block.raw, options); break; case 'entry': if (duplicateEntries.has(child.block)) continue; const itemType = lowercase ? child.command.toLocaleLowerCase() : child.command; bibtex += `@${itemType}{`; if (child.block.key) bibtex += `${child.block.key},`; if (fieldOrder) sortFields(child.block.fields, fieldOrder); const fieldSeen = new Set<string>(); for (let i = 0; i < child.block.fields.length; i++) { const field = child.block.fields[i]; const nameLowerCase = field.name.toLocaleLowerCase(); const name = lowercase ? nameLowerCase : field.name; if (field.name === '') continue; if (omitFields.has(nameLowerCase)) continue; if (removeDuplicateFields && fieldSeen.has(nameLowerCase)) continue; fieldSeen.add(nameLowerCase); if (field.value.concat.length === 0) { if (removeEmptyFields) continue; bibtex += `\n${indent}${name}`; } else { const value = formatValue(field, options); if (removeEmptyFields && (value === '{}' || value === '""')) continue; bibtex += `\n${indent}${name .trim() .padEnd(align - 1)} = ${value}`; } if (i < child.block.fields.length - 1 || trailingCommas) bibtex += ','; } bibtex += `\n}\n`; break; } } } if (!bibtex.endsWith('\n')) bibtex += '\n'; return { bibtex, warnings, count: entries.length }; } function sortFields(fields: FieldNode[], fieldOrder: string[]): void { fields.sort((a, b) => { const orderA = fieldOrder.indexOf(a.name.toLocaleLowerCase()); const orderB = fieldOrder.indexOf(b.name.toLocaleLowerCase()); if (orderA === -1 && orderB === -1) return 0; if (orderA === -1) return 1; if (orderB === -1) return -1; if (orderB < orderA) return 1; if (orderB > orderA) return -1; return 0; }); } function generateValueLookup( entries: EntryNode[], options: OptionsNormalized ): Map<EntryNode, Map<string, string | undefined>> { return new Map( entries.map((entry) => [ entry, new Map( entry.fields.map((field) => [ field.name.toLocaleLowerCase(), formatValue(field, options), ]) ), ]) ); } function sortEntries( ast: RootNode, fieldMaps: Map<EntryNode, Map<string, string | undefined>>, { sort }: OptionsNormalized ): void { if (!sort) return; // Map of items to sort values e.g. { year: 2009, author: 'West', ... } const sortIndexes: Map<TextNode | BlockNode, SortIndex> = new Map(); // comments, preambles, and strings which should be kept with an entry const precedingMeta: (TextNode | BlockNode)[] = []; // first, create sort indexes for (const item of ast.children) { if (item.type === 'text' || item.block?.type !== 'entry') { // if string, preamble, or comment, then use sort index of previous entry precedingMeta.push(item); continue; } const sortIndex: SortIndex = new Map(); for (let key of sort) { // dash prefix indicates descending order, deal with this later if (key.startsWith('-')) key = key.slice(1); let val: string; if (key === 'key') { val = item.block.key ?? ''; } else if (key === 'type') { val = item.command; } else { val = fieldMaps.get(item.block)?.get(key) ?? ''; } sortIndex.set(key, val.toLowerCase()); } sortIndexes.set(item, sortIndex); // update comments above to this index while (precedingMeta.length > 0) { sortIndexes.set(precedingMeta.pop()!, sortIndex); } } // Now iterate through sort keys and sort entries for (let i = sort.length - 1; i >= 0; i--) { const desc = sort[i].startsWith('-'); const key = desc ? sort[i].slice(1) : sort[i]; ast.children.sort((a, b) => { // if no value, then use \ufff0 so entry will be last const ia = sortIndexes.get(a)?.get(key) ?? '\ufff0'; const ib = sortIndexes.get(b)?.get(key) ?? '\ufff0'; return (desc ? ib : ia).localeCompare(desc ? ia : ib); }); } } function formatComment( comment: string, { stripComments, tidyComments }: OptionsNormalized ): string { if (stripComments) return ''; if (tidyComments) { // tidy comments by trimming whitespace and ending with one newline const trimmed = comment.trim(); if (trimmed === '') return ''; return trimmed + '\n'; } else { // make sure that comment whitespace does not flow into the first line of an entry return comment.replace(/^[ \t]*\n|[ \t]*$/g, ''); } } function formatValue( field: FieldNode, options: OptionsNormalized ): string | undefined { const { curly, numeric, align, stripEnclosingBraces, dropAllCaps, escape, encodeUrls, wrap, maxAuthors, tab, space, enclosingBraces, } = options; const nameLowerCase = field.name.toLocaleLowerCase(); const indent: string = tab ? '\t' : ' '.repeat(space); const enclosingBracesFields: Set<string> = new Set( (enclosingBraces || []).map((field) => field.toLocaleLowerCase()) ); return field.value.concat .map(({ type, value }) => { const isNumeric = value.match(/^[1-9][0-9]*$/); if (isNumeric && curly) { type = 'braced'; } if (type === 'literal' || (numeric && isNumeric)) { return value; } const dig3 = value.slice(0, 3).toLowerCase(); if (!curly && numeric && nameLowerCase === 'month' && MONTHS.has(dig3)) { return dig3; } value = unwrapText(value); // if a field's value has double braces {{blah}}, lose the inner brace if (stripEnclosingBraces) { value = removeEnclosingBraces(value); } // if a field's value is all caps, convert it to title case if (dropAllCaps && !value.match(/[a-z]/)) { value = titleCase(value); } // url encode must happen before escape special characters if (nameLowerCase === 'url' && encodeUrls) { value = escapeURL(value); } // escape special characters like % if (escape) { value = escapeSpecialCharacters(value); } if (nameLowerCase === 'pages') { value = formatPageRange(value); } if (nameLowerCase === 'author' && maxAuthors) { value = limitAuthors(value, maxAuthors); } // if the user requested, wrap the value in braces (this forces bibtex // compiler to preserve case) if ( enclosingBracesFields.has(nameLowerCase) && (type === 'braced' || curly) ) { value = addEnclosingBraces(value, true); } value = value.trim(); if (type === 'braced' || curly) { const lineLength = `${indent}${align}{${value}}`.length; const multiLine = value.includes('\n\n'); // If the value contains multiple paragraphs, then output the value at a separate indent level, e.g. // abstract = { // Paragraph 1 // // Paragraph 2 // } if ((wrap && lineLength > wrap) || multiLine) { let paragraphs = value.split('\n\n'); const valIndent = indent.repeat(2); if (wrap) { const wrapCol = wrap; paragraphs = paragraphs.map((paragraph) => wrapText(paragraph, wrapCol - valIndent.length).join( '\n' + valIndent ) ); } value = '\n' + valIndent + paragraphs.join(`\n\n${valIndent}`) + '\n' + indent; } return addEnclosingBraces(value); } else { return `"${value}"`; } }) .join(' # '); } export default { tidy };
the_stack
'use strict'; import {Dimension, Builder, Box} from 'vs/base/browser/builder'; import {Part} from 'vs/workbench/browser/part'; import {QuickOpenController} from 'vs/workbench/browser/parts/quickopen/quickOpenController'; import {Sash, ISashEvent, IVerticalSashLayoutProvider, IHorizontalSashLayoutProvider, Orientation} from 'vs/base/browser/ui/sash/sash'; import {IWorkbenchEditorService} from 'vs/workbench/services/editor/common/editorService'; import {IPartService, Position} from 'vs/workbench/services/part/common/partService'; import {IViewletService} from 'vs/workbench/services/viewlet/common/viewletService'; import {IStorageService, StorageScope} from 'vs/platform/storage/common/storage'; import {IContextViewService} from 'vs/platform/contextview/browser/contextView'; import {IEventService} from 'vs/platform/event/common/event'; import {IThemeService} from 'vs/workbench/services/themes/common/themeService'; import {IDisposable, dispose} from 'vs/base/common/lifecycle'; import {IEditorGroupService} from 'vs/workbench/services/group/common/groupService'; const DEFAULT_MIN_PART_WIDTH = 170; const DEFAULT_MIN_PANEL_PART_HEIGHT = 77; const DEFAULT_MIN_EDITOR_PART_HEIGHT = 170; const HIDE_SIDEBAR_WIDTH_THRESHOLD = 50; const HIDE_PANEL_HEIGHT_THRESHOLD = 50; export class LayoutOptions { public margin: Box; constructor() { this.margin = new Box(0, 0, 0, 0); } public setMargin(margin: Box): LayoutOptions { this.margin = margin; return this; } } interface ComputedStyles { activitybar: { minWidth: number; }; sidebar: { minWidth: number; }; panel: { minHeight: number; }; editor: { minWidth: number; }; statusbar: { height: number; }; } /** * The workbench layout is responsible to lay out all parts that make the Workbench. */ export class WorkbenchLayout implements IVerticalSashLayoutProvider, IHorizontalSashLayoutProvider { private static sashXWidthSettingsKey = 'workbench.sidebar.width'; private static sashYHeightSettingsKey = 'workbench.panel.height'; private parent: Builder; private workbenchContainer: Builder; private activitybar: Part; private editor: Part; private sidebar: Part; private panel: Part; private statusbar: Part; private quickopen: QuickOpenController; private options: LayoutOptions; private toUnbind: IDisposable[]; private computedStyles: ComputedStyles; private workbenchSize: Dimension; private sashX: Sash; private sashY: Sash; private startSidebarWidth: number; private sidebarWidth: number; private sidebarHeight: number; private startPanelHeight: number; private panelHeight: number; private panelWidth: number; // Take parts as an object bag since instatation service does not have typings for constructors with 9+ arguments constructor( parent: Builder, workbenchContainer: Builder, parts: { activitybar: Part, editor: Part, sidebar: Part, panel: Part, statusbar: Part }, quickopen: QuickOpenController, options: LayoutOptions, @IStorageService private storageService: IStorageService, @IEventService eventService: IEventService, @IContextViewService private contextViewService: IContextViewService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IPartService private partService: IPartService, @IViewletService private viewletService: IViewletService, @IThemeService themeService: IThemeService ) { this.parent = parent; this.workbenchContainer = workbenchContainer; this.activitybar = parts.activitybar; this.editor = parts.editor; this.sidebar = parts.sidebar; this.panel = parts.panel; this.statusbar = parts.statusbar; this.quickopen = quickopen; this.options = options || new LayoutOptions(); this.toUnbind = []; this.computedStyles = null; this.sashX = new Sash(this.workbenchContainer.getHTMLElement(), this, { baseSize: 5 }); this.sashY = new Sash(this.workbenchContainer.getHTMLElement(), this, { baseSize: 4, orientation: Orientation.HORIZONTAL }); this.sidebarWidth = this.storageService.getInteger(WorkbenchLayout.sashXWidthSettingsKey, StorageScope.GLOBAL, -1); this.panelHeight = this.storageService.getInteger(WorkbenchLayout.sashYHeightSettingsKey, StorageScope.GLOBAL, 0); this.toUnbind.push(themeService.onDidColorThemeChange(_ => this.relayout())); this.toUnbind.push(editorGroupService.onEditorsChanged(() => this.onEditorsChanged())); this.registerSashListeners(); } private registerSashListeners(): void { let startX: number = 0; let startY: number = 0; this.sashX.addListener2('start', (e: ISashEvent) => { this.startSidebarWidth = this.sidebarWidth; startX = e.startX; }); this.sashY.addListener2('start', (e: ISashEvent) => { this.startPanelHeight = this.panelHeight; startY = e.startY; }); this.sashX.addListener2('change', (e: ISashEvent) => { let doLayout = false; let sidebarPosition = this.partService.getSideBarPosition(); let isSidebarHidden = this.partService.isSideBarHidden(); let newSashWidth = (sidebarPosition === Position.LEFT) ? this.startSidebarWidth + e.currentX - startX : this.startSidebarWidth - e.currentX + startX; // Sidebar visible if (!isSidebarHidden) { // Automatically hide side bar when a certain threshold is met if (newSashWidth + HIDE_SIDEBAR_WIDTH_THRESHOLD < this.computedStyles.sidebar.minWidth) { let dragCompensation = DEFAULT_MIN_PART_WIDTH - HIDE_SIDEBAR_WIDTH_THRESHOLD; this.partService.setSideBarHidden(true); startX = (sidebarPosition === Position.LEFT) ? Math.max(this.computedStyles.activitybar.minWidth, e.currentX - dragCompensation) : Math.min(e.currentX + dragCompensation, this.workbenchSize.width - this.computedStyles.activitybar.minWidth); this.sidebarWidth = this.startSidebarWidth; // when restoring sidebar, restore to the sidebar width we started from } // Otherwise size the sidebar accordingly else { this.sidebarWidth = Math.max(this.computedStyles.sidebar.minWidth, newSashWidth); // Sidebar can not become smaller than MIN_PART_WIDTH doLayout = newSashWidth >= this.computedStyles.sidebar.minWidth; } } // Sidebar hidden else { if ((sidebarPosition === Position.LEFT && e.currentX - startX >= this.computedStyles.sidebar.minWidth) || (sidebarPosition === Position.RIGHT && startX - e.currentX >= this.computedStyles.sidebar.minWidth)) { this.startSidebarWidth = this.computedStyles.sidebar.minWidth - (sidebarPosition === Position.LEFT ? e.currentX - startX : startX - e.currentX); this.sidebarWidth = this.computedStyles.sidebar.minWidth; this.partService.setSideBarHidden(false); } } if (doLayout) { this.layout(); } }); this.sashY.addListener2('change', (e: ISashEvent) => { let doLayout = false; let isPanelHidden = this.partService.isPanelHidden(); let isStatusbarHidden = this.partService.isStatusBarHidden(); let newSashHeight = this.startPanelHeight - (e.currentY - startY); // Panel visible if (!isPanelHidden) { // Automatically hide panel when a certain threshold is met if (newSashHeight + HIDE_PANEL_HEIGHT_THRESHOLD < this.computedStyles.panel.minHeight) { let dragCompensation = DEFAULT_MIN_PANEL_PART_HEIGHT - HIDE_PANEL_HEIGHT_THRESHOLD; this.partService.setPanelHidden(true); let statusbarHeight = isStatusbarHidden ? 0 : this.computedStyles.statusbar.height; startY = Math.min(this.sidebarHeight - statusbarHeight, e.currentY + dragCompensation); this.panelHeight = this.startPanelHeight; // when restoring panel, restore to the panel height we started from } // Otherwise size the panel accordingly else { this.panelHeight = Math.max(this.computedStyles.panel.minHeight, newSashHeight); // Panel can not become smaller than MIN_PART_HEIGHT doLayout = newSashHeight >= this.computedStyles.panel.minHeight; } } // Panel hidden else { if (startY - e.currentY >= this.computedStyles.panel.minHeight) { this.startPanelHeight = 0; this.panelHeight = this.computedStyles.panel.minHeight; this.partService.setPanelHidden(false); } } if (doLayout) { this.layout(); } }); this.sashX.addListener2('end', () => { this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL); }); this.sashY.addListener2('end', () => { this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL); }); this.sashY.addListener2('reset', () => { this.panelHeight = DEFAULT_MIN_PANEL_PART_HEIGHT; this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL); this.partService.setPanelHidden(false); this.layout(); }); this.sashX.addListener2('reset', () => { let activeViewlet = this.viewletService.getActiveViewlet(); let optimalWidth = activeViewlet && activeViewlet.getOptimalWidth(); this.sidebarWidth = Math.max(DEFAULT_MIN_PART_WIDTH, optimalWidth || 0); this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL); this.partService.setSideBarHidden(false); this.layout(); }); } private onEditorsChanged(): void { // Make sure that we layout properly in case we detect that the sidebar is large enought to cause // multiple opened editors to go below minimal size. The fix is to trigger a layout for any editor // input change that falls into this category. if (this.workbenchSize && this.sidebarWidth) { let visibleEditors = this.editorService.getVisibleEditors().length; if (visibleEditors > 1 && this.workbenchSize.width - this.sidebarWidth < visibleEditors * DEFAULT_MIN_PART_WIDTH) { this.layout(); } } } private relayout(): void { // Recompute Styles this.computeStyle(); this.editor.getLayout().computeStyle(); this.sidebar.getLayout().computeStyle(); this.panel.getLayout().computeStyle(); // Trigger Layout this.layout(); } private computeStyle(): void { const sidebarStyle = this.sidebar.getContainer().getComputedStyle(); const panelStyle = this.panel.getContainer().getComputedStyle(); const editorStyle = this.editor.getContainer().getComputedStyle(); const activitybarStyle = this.activitybar.getContainer().getComputedStyle(); const statusbarStyle = this.statusbar.getContainer().getComputedStyle(); this.computedStyles = { activitybar: { minWidth: parseInt(activitybarStyle.getPropertyValue('min-width'), 10) || 0 }, sidebar: { minWidth: parseInt(sidebarStyle.getPropertyValue('min-width'), 10) || DEFAULT_MIN_PART_WIDTH }, panel: { minHeight: parseInt(panelStyle.getPropertyValue('min-height'), 10) || DEFAULT_MIN_PANEL_PART_HEIGHT }, editor: { minWidth: parseInt(editorStyle.getPropertyValue('min-width'), 10) || DEFAULT_MIN_PART_WIDTH }, statusbar: { height: parseInt(statusbarStyle.getPropertyValue('height'), 10) || 18 } }; } public layout(forceStyleReCompute?: boolean): void { if (forceStyleReCompute) { this.computeStyle(); this.editor.getLayout().computeStyle(); this.sidebar.getLayout().computeStyle(); this.panel.getLayout().computeStyle(); } if (!this.computedStyles) { this.computeStyle(); } this.workbenchSize = this.getWorkbenchArea(); const isSidebarHidden = this.partService.isSideBarHidden(); const isPanelHidden = this.partService.isPanelHidden(); const sidebarPosition = this.partService.getSideBarPosition(); const isStatusbarHidden = this.partService.isStatusBarHidden(); // Sidebar let sidebarWidth: number; if (isSidebarHidden) { sidebarWidth = 0; } else if (this.sidebarWidth !== -1) { sidebarWidth = Math.max(this.computedStyles.sidebar.minWidth, this.sidebarWidth); } else { sidebarWidth = this.workbenchSize.width / 5; this.sidebarWidth = sidebarWidth; } let statusbarHeight = isStatusbarHidden ? 0 : this.computedStyles.statusbar.height; this.sidebarHeight = this.workbenchSize.height - statusbarHeight; let sidebarSize = new Dimension(sidebarWidth, this.sidebarHeight); // Activity Bar let activityBarMinWidth = this.computedStyles.activitybar.minWidth; let activityBarSize = new Dimension(activityBarMinWidth, sidebarSize.height); // Panel part let panelHeight: number; if (isPanelHidden) { panelHeight = 0; } else if (this.panelHeight > 0) { panelHeight = Math.min(sidebarSize.height - DEFAULT_MIN_EDITOR_PART_HEIGHT, Math.max(this.computedStyles.panel.minHeight, this.panelHeight)); } else { panelHeight = sidebarSize.height * 0.4; } const panelDimension = new Dimension(this.workbenchSize.width - sidebarSize.width - activityBarSize.width, panelHeight); this.panelWidth = panelDimension.width; // Editor let editorSize = { width: 0, height: 0, remainderLeft: 0, remainderRight: 0 }; let editorDimension = new Dimension(panelDimension.width, sidebarSize.height - panelDimension.height); editorSize.width = editorDimension.width; editorSize.height = editorDimension.height; // Sidebar hidden if (isSidebarHidden) { editorSize.width = Math.min(this.workbenchSize.width - activityBarSize.width, this.workbenchSize.width - activityBarMinWidth); if (sidebarPosition === Position.LEFT) { editorSize.remainderLeft = Math.round((this.workbenchSize.width - editorSize.width + activityBarSize.width) / 2); editorSize.remainderRight = this.workbenchSize.width - editorSize.width - editorSize.remainderLeft; } else { editorSize.remainderRight = Math.round((this.workbenchSize.width - editorSize.width + activityBarSize.width) / 2); editorSize.remainderLeft = this.workbenchSize.width - editorSize.width - editorSize.remainderRight; } } // Assert Sidebar and Editor Size to not overflow let editorMinWidth = this.computedStyles.editor.minWidth; let visibleEditorCount = this.editorService.getVisibleEditors().length; if (visibleEditorCount > 1) { editorMinWidth *= visibleEditorCount; } if (editorSize.width < editorMinWidth) { let diff = editorMinWidth - editorSize.width; editorSize.width = editorMinWidth; panelDimension.width = editorMinWidth; sidebarSize.width -= diff; sidebarSize.width = Math.max(DEFAULT_MIN_PART_WIDTH, sidebarSize.width); } if (!isSidebarHidden) { this.sidebarWidth = sidebarSize.width; this.storageService.store(WorkbenchLayout.sashXWidthSettingsKey, this.sidebarWidth, StorageScope.GLOBAL); } if (!isPanelHidden) { this.panelHeight = panelDimension.height; this.storageService.store(WorkbenchLayout.sashYHeightSettingsKey, this.panelHeight, StorageScope.GLOBAL); } // Workbench this.workbenchContainer .position(this.options.margin.top, this.options.margin.right, this.options.margin.bottom, this.options.margin.left, 'relative') .size(this.workbenchSize.width, this.workbenchSize.height); // Bug on Chrome: Sometimes Chrome wants to scroll the workbench container on layout changes. The fix is to reset scrollTop in this case. if (this.workbenchContainer.getHTMLElement().scrollTop > 0) { this.workbenchContainer.getHTMLElement().scrollTop = 0; } // Editor Part and Panel part this.editor.getContainer().size(editorSize.width, editorSize.height); this.panel.getContainer().size(panelDimension.width, panelDimension.height); const editorBottom = statusbarHeight + panelDimension.height; if (isSidebarHidden) { this.editor.getContainer().position(0, editorSize.remainderRight, editorBottom, editorSize.remainderLeft); this.panel.getContainer().position(editorDimension.height, editorSize.remainderRight, statusbarHeight, editorSize.remainderLeft); } else if (sidebarPosition === Position.LEFT) { this.editor.getContainer().position(0, 0, editorBottom, sidebarSize.width + activityBarSize.width); this.panel.getContainer().position(editorDimension.height, 0, statusbarHeight, sidebarSize.width + activityBarSize.width); } else { this.editor.getContainer().position(0, sidebarSize.width, editorBottom, 0); this.panel.getContainer().position(editorDimension.height, sidebarSize.width, statusbarHeight, 0); } // Activity Bar Part this.activitybar.getContainer().size(null, activityBarSize.height); if (sidebarPosition === Position.LEFT) { this.activitybar.getContainer().getHTMLElement().style.right = ''; this.activitybar.getContainer().position(0, null, 0, 0); } else { this.activitybar.getContainer().getHTMLElement().style.left = ''; this.activitybar.getContainer().position(0, 0, 0, null); } // Sidebar Part this.sidebar.getContainer().size(sidebarSize.width, sidebarSize.height); if (sidebarPosition === Position.LEFT) { this.sidebar.getContainer().position(0, editorSize.width, 0, activityBarSize.width); } else { this.sidebar.getContainer().position(0, null, 0, editorSize.width); } // Statusbar Part this.statusbar.getContainer().position(this.workbenchSize.height - statusbarHeight); // Quick open this.quickopen.layout(this.workbenchSize); // Sashes this.sashX.layout(); this.sashY.layout(); // Propagate to Part Layouts this.editor.layout(new Dimension(editorSize.width, editorSize.height)); this.sidebar.layout(sidebarSize); this.panel.layout(panelDimension); // Propagate to Context View this.contextViewService.layout(); } private getWorkbenchArea(): Dimension { // Client Area: Parent let clientArea = this.parent.getClientArea(); // Workbench: Client Area - Margins return clientArea.substract(this.options.margin); } public getVerticalSashTop(sash: Sash): number { return 0; } public getVerticalSashLeft(sash: Sash): number { let isSidebarHidden = this.partService.isSideBarHidden(); let sidebarPosition = this.partService.getSideBarPosition(); let activitybarWidth = this.computedStyles.activitybar.minWidth; if (sidebarPosition === Position.LEFT) { return !isSidebarHidden ? this.sidebarWidth + activitybarWidth : activitybarWidth; } return !isSidebarHidden ? this.workbenchSize.width - this.sidebarWidth - activitybarWidth : this.workbenchSize.width - activitybarWidth; } public getVerticalSashHeight(sash: Sash): number { return this.sidebarHeight; } public getHorizontalSashTop(sash: Sash): number { return 2 + (this.partService.isPanelHidden() ? this.sidebarHeight : this.sidebarHeight - this.panelHeight); // Horizontal sash should be a bit lower than the editor area, thus add 2px #5524 } public getHorizontalSashLeft(sash: Sash): number { return this.partService.getSideBarPosition() === Position.LEFT ? this.getVerticalSashLeft(sash) : 0; } public getHorizontalSashWidth(sash: Sash): number { return this.panelWidth; } public dispose(): void { if (this.toUnbind) { dispose(this.toUnbind); this.toUnbind = null; } } }
the_stack
import {config} from '../core/utils'; import * as Sequelize from "sequelize"; import Q = require('q'); import {IEntityService} from '../core/interfaces/entity-service'; import {MetaUtils} from "../core/metadata/utils"; import {pathRepoMap, getEntity} from '../core/dynamic/model-entity'; import {QueryOptions} from '../core/interfaces/queryOptions'; import {Decorators as CoreDecorators, Decorators} from '../core/constants'; //import {pathRepoMap} from './schema'; import * as schema from "./schema"; import * as Enumerable from 'linq'; import { MetaData } from '../core/metadata/metadata'; import { IAssociationParams } from '../core/decorators/interfaces'; import { PrincipalContext } from '../security/auth/principalContext'; import {ConstantKeys} from '../core/constants/constantKeys'; class SequelizeService implements IEntityService { private sequelize: any; private _schemaCollection = {}; private _relationCollection = []; constructor() { } init(force?: boolean): Promise<any> { force = force || false; return this.sequelize.sync({ force: force, logging: true }); } connect() { if (config().SqlConfig.isSqlEnabled == false) return; this.sequelize = new Sequelize(config().SqlConfig.database, config().SqlConfig.username, config().SqlConfig.password, config().SqlConfig.sequlizeSetting); } getSqlContext(): any { return this.sequelize; } startTransaction(param?:any):Q.Promise<any>{ return this.sequelize.transaction(); } commitTransaction(param?:any):Q.Promise<any>{ return param.commit(); } rollbackTransaction(param?:any):Q.Promise<any>{ return param.rollback(); } getCustomResult(databaseName: string, query) { if (config().SqlConfig.isSqlEnabled == false) return; var dynamicSequelize = new Sequelize(databaseName, config().SqlConfig.username, config().SqlConfig.password, config().SqlConfig.sequlizeSetting); return dynamicSequelize.query(query); } addScheam(name: string, schema: any, detail: any) { var newSchema = this.sequelize.define(name, schema, detail); this._schemaCollection[name] = newSchema; return newSchema; } addRelationInSchema(fromSchema: any, toSchema: any, relationType:string, metaData:IAssociationParams) { let path = metaData.propertyKey; if (relationType == CoreDecorators.ONETOMANY) fromSchema.hasMany(toSchema, { as: path}); if (relationType == CoreDecorators.MANYTOONE) fromSchema.belongsTo(toSchema, { as: path, foreignKey:metaData.foreignKey}); if (relationType == CoreDecorators.ONETOONE) fromSchema.has(toSchema, { as: path}); let relationToDictionary: any = {}; relationToDictionary.metaData = metaData; relationToDictionary.type = relationType; relationToDictionary["relation"] = metaData.rel; relationToDictionary.fromSchema = fromSchema; relationToDictionary.toSchema = toSchema; relationToDictionary.path = path; this._relationCollection.push(relationToDictionary); } parseProperties(props,schemaModel){ let config = {} props.forEach(prop=>{ if(prop.indexOf('.')<0){ config['attributes']=config['attributes']?config['attributes']:[]; config['attributes'].push(prop); } else{ let foreignKeys = prop.split('.'); this.insertForeignKey(config, foreignKeys,schemaModel); } }) return config; } insertForeignKey(config, foreignKeys,schemaModel){ let modelConfig = config; foreignKeys.forEach((x, i)=>{ if(foreignKeys.length-1 == i){ modelConfig['attributes']=modelConfig['attributes']?modelConfig['attributes']:[]; let relSchemas = this._relationCollection.filter(schema => (schema.relation == schemaModel.name)); if(relSchemas.length >0 && relSchemas[0].toSchema.primaryKeyAttribute!=x){ modelConfig['attributes'].push(x); } } else{ modelConfig['include']=modelConfig['include']?modelConfig['include']:[]; let filterConfig = modelConfig.include.filter(p=>p.as==x); if(!filterConfig.length){ let relSchemas = this._relationCollection.filter(schema => (schema.fromSchema.name == schemaModel.name) && (schema.type == Decorators.MANYTOONE) && (schema.path == x)); if(relSchemas.length>0){ schemaModel = relSchemas[0].toSchema; let tempConfig = { model: relSchemas[0].toSchema, as :relSchemas[0].path,attributes:[relSchemas[0].toSchema.primaryKeyAttribute]} modelConfig.include.push(tempConfig); modelConfig = tempConfig; } } else{ let relSchemas = this._relationCollection.filter(schema => (schema.fromSchema.name == schemaModel.name) && (schema.type == Decorators.MANYTOONE) && (schema.path == x)); if(relSchemas.length>0){ schemaModel = relSchemas[0].toSchema; } modelConfig = filterConfig[0]; } } }) } getAllForeignKeyAssocationsForFindWhere(inputArr, schemaModel) { let parseProperties = this.parseProperties(inputArr,schemaModel); return parseProperties; } getAllForeignKeyAssocations(schemaModel, properties:Array<string>){ let includes = []; let relSchemas = this._relationCollection.filter(x=>(x.fromSchema.name == schemaModel.name) && (x.type == Decorators.MANYTOONE)); if(relSchemas.length){ relSchemas.forEach(x=>{ if(!properties || !properties.length || properties.indexOf(x.path)>=0){ if(x.metaData.eagerLoading){ let model = { model: x.toSchema, as: x.path, attributes:[x.toSchema.primaryKeyAttribute] }; if (x.metaData.properties) { model['attributes'] = x.metaData.properties; let properties=x.metaData.properties; let indexofPrimaryKey=properties.indexOf(x.toSchema.primaryKeyAttribute); if(indexofPrimaryKey>-1){ properties.splice(indexofPrimaryKey,1) } model['attributes'] = properties; } let childModel = this.getAllForeignKeyAssocations(x.toSchema, x.metaData.properties); if(childModel.length){ model['include']= childModel; } includes.push(model); } } }); } return includes; } getModel(repoPath: string, dynamicName?: string) { try { var schemaNamefromPathRepomap = pathRepoMap[repoPath].schemaName; return this._schemaCollection[schemaNamefromPathRepomap]; } catch (e) { throw e; } } appendTransaction(options){ let trans = PrincipalContext.get(ConstantKeys.transaction); if(trans){ options['transaction'] = trans; } return options; } bulkPost(repoPath: string, objArr: Array<any>, batchSize?: number): Q.Promise<any> { let options = {individualHooks: true} options = this.appendTransaction(options); return this.getModel(repoPath).bulkCreate(objArr, options); } bulkPutMany(repoPath: string, objIds: Array<any>, obj: any): Q.Promise<any> { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {} cond[primaryKey] = objIds let options = { where: cond }; options = this.appendTransaction(options); return this.getModel(repoPath).update(obj, options).then(result=>{ if(result[0]){ return this.findMany(repoPath, objIds, false); } else{ throw 'failed to update'; } }); } bulkDel(repoPath: string, objArr: Array<any>): Q.Promise<any> { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {} cond[primaryKey] = objArr.map(x=>x[primaryKey]); let options = { where: cond } options = this.appendTransaction(options); return this.getModel(repoPath).destroy(options).then(result=>{ return {success:result}; }) } bulkPut(repoPath: string, objArr: Array<any>,batchSize?: number): Q.Promise<any> { let asyncalls=[]; let primaryKey = this.getModel(repoPath).primaryKeyAttribute; objArr.forEach(obj=>{ let cond = {} cond[primaryKey] = obj[primaryKey]; let options = { where: cond } options = this.appendTransaction(options); asyncalls.push(this.getModel(repoPath).update(obj, options)); }); return Q.allSettled(asyncalls).then(result=>{ return this.findMany(repoPath, objArr.map(x=>x[primaryKey]), false); }); } bulkPatch(repoPath: string, objArr: Array<any>): Q.Promise<any> { return this.bulkPut(repoPath, objArr); } findAll(repoPath: string): Q.Promise<any> { return this.getModel(repoPath).findAll({raw: true}).then(result => { if (!result) return null; //var finalOutput = Enumerable.from(result).select((x:any) => x.dataValues).toArray();// result.forEach(x => x.dataValues).toArray(); return result; }); } findWhere(repoPath: string, query, selectedFields?: Array<string>, queryOptions?: QueryOptions, toLoadChilds?: boolean): Q.Promise<any> { let schemaModel = this.getModel(repoPath); let cond = {}; if (selectedFields && selectedFields.length > 0) { cond = this.getAllForeignKeyAssocationsForFindWhere(selectedFields, schemaModel); } else { cond['include'] = this.getAllForeignKeyAssocations(schemaModel, []); } cond["where"] = query return schemaModel.findAll(cond).then(result => { if (!result) return null; return result.map(x => x.dataValues); }); } //This is not testest yet //TODO: add test case for this countWhere(repoPath: string, query): Q.Promise<any> { return this.getModel(repoPath).findAndCountAll({ where: query }).then(result => { return result; }); } //This is not testest yet //TODO: add test case for this distinctWhere(repoPath: string, query): Q.Promise<any> { if (!query) { query = {}; } query.distinct = true; return this.getModel(repoPath).findAndCountAll(query).then(result => { return result; }); } findOne(repoPath: string, id, donotLoadChilds?: boolean): Q.Promise<any> { let schemaModel = this.getModel(repoPath); let primaryKey = schemaModel.primaryKeyAttribute; var cond = {}; cond[primaryKey] = id; let include = donotLoadChilds? [] : this.getAllForeignKeyAssocations(schemaModel, null); return schemaModel.find({ include: include, where: cond }).then(result => { return result.dataValues; }); } findByField(repoPath: string, fieldName, value): Q.Promise<any> { return this.getModel(repoPath).find({ where: { fieldName: value } }); } findMany(repoPath: string, ids: Array<any>, toLoadEmbeddedChilds?: boolean) { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {}; cond[primaryKey] = ids; return this.findWhere(repoPath,cond, [], null, toLoadEmbeddedChilds); } findChild(repoPath: string, id, prop): Q.Promise<any> { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {}; cond[primaryKey] = id; return this.getModel(repoPath).find({ where: cond, include: [ { model: this.getModel(prop), as: prop } ] }).then( function (entity) { return entity[prop]; }); } /** * case 1: all new - create main item and child separately and embed if true * case 2: some new, some update - create main item and update/create child accordingly and embed if true * @param obj */ post(repoPath: string, obj: any): Q.Promise<any> { let options = {}; options = this.appendTransaction(options); return this.getModel(repoPath).create(obj, options); } put(repoPath: string, id: any, obj: any): Q.Promise<any> { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {}; cond[primaryKey] = id; let options = { where: cond } options = this.appendTransaction(options); return this.getModel(repoPath).update(obj, options).then(result=>{ if(result[0]){ return this.findOne(repoPath, id); } else{ throw 'Failed to update'; } }) } del(repoPath: string, id: any): Q.Promise<any> { let primaryKey = this.getModel(repoPath).primaryKeyAttribute; let cond = {}; cond[primaryKey] = id; let options = { where: cond }; options = this.appendTransaction(options); return this.getModel(repoPath).destroy(options).then(result=>{ return {success:result}; }) } patch(repoPath: string, id: any, obj): Q.Promise<any> { return this.put(repoPath, id, obj) } private getAssociationForSchema(model: any, schema: any) { Enumerable.from(this._relationCollection) .where(relationSchema => relationSchema.fromSchema == schema).forEach(relation1 => { model.dataValues[relation1.path] = model[relation1.toSchema.name + "s"]; }); } } export var sequelizeService = new SequelizeService(); //export var connect = sequelizeService.connect;
the_stack
export enum PaymentDueTime { /** Payments due at the beginning of a period (1) */ Begin = 'begin', // 1 /** Payments are due at the end of a period (0) */ End = 'end' // 0 } /** * Compute the future value. * * @param rate - Rate of interest as decimal (not per cent) per period * @param nper - Number of compounding periods * @param pmt - A fixed payment, paid either at the beginning or ar the end (specified by `when`) * @param pv - Present value * @param when - When payment was made * * @returns The value at the end of the `nper` periods * * @since v0.0.12 * * ## Examples * * What is the future value after 10 years of saving $100 now, with * an additional monthly savings of $100. Assume the interest rate is * 5% (annually) compounded monthly? * * ```javascript * import { fv } from 'financial' * * fv(0.05 / 12, 10 * 12, -100, -100) // 15692.928894335748 * ``` * * By convention, the negative sign represents cash flow out (i.e. money not * available today). Thus, saving $100 a month at 5% annual interest leads * to $15,692.93 available to spend in 10 years. * * ## Notes * * The future value is computed by solving the equation: * * ``` * fv + pv * (1+rate) ** nper + pmt * (1 + rate * when) / rate * ((1 + rate) ** nper - 1) == 0 * ``` * * or, when `rate == 0`: * * ``` * fv + pv + pmt * nper == 0 * ``` * * ## References * * [Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May)](http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt). */ export function fv (rate: number, nper: number, pmt: number, pv: number, when : PaymentDueTime = PaymentDueTime.End) : number { const isRateZero = rate === 0 if (isRateZero) { return -(pv + pmt * nper) } const temp = (1 + rate) ** nper const whenMult = when === PaymentDueTime.Begin ? 1 : 0 return (-pv * temp - pmt * (1 + rate * whenMult) / rate * (temp - 1)) } /** * Compute the payment against loan principal plus interest. * * @param rate - Rate of interest (per period) * @param nper - Number of compounding periods (e.g., number of payments) * @param pv - Present value (e.g., an amount borrowed) * @param fv - Future value (e.g., 0) * @param when - When payments are due * * @returns the (fixed) periodic payment * * @since v0.0.12 * * ## Examples * * What is the monthly payment needed to pay off a $200,000 loan in 15 * years at an annual interest rate of 7.5%? * * ```javascript * import { pmt } from 'financial' * * pmt(0.075/12, 12*15, 200000) // -1854.0247200054619 * ``` * * In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained * today, a monthly payment of $1,854.02 would be required. Note that this * example illustrates usage of `fv` having a default value of 0. * * ## Notes * * The payment is computed by solving the equation: * * ``` * fv + pv * (1 + rate) ** nper + pmt * (1 + rate*when) / rate * ((1 + rate) ** nper - 1) == 0 * ``` * * or, when `rate == 0`: * * ``` * fv + pv + pmt * nper == 0 * ``` * * for `pmt`. * * Note that computing a monthly mortgage payment is only * one use for this function. For example, `pmt` returns the * periodic deposit one must make to achieve a specified * future balance given an initial deposit, a fixed, * periodically compounded interest rate, and the total * number of periods. * * ## References * * [Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May)](http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt). */ export function pmt (rate: number, nper: number, pv: number, fv = 0, when = PaymentDueTime.End): number { const isRateZero = rate === 0 const temp = (1 + rate) ** nper const whenMult = when === PaymentDueTime.Begin ? 1 : 0 const maskedRate = isRateZero ? 1 : rate const fact = isRateZero ? nper : (1 + maskedRate * whenMult) * (temp - 1) / maskedRate return -(fv + pv * temp) / fact } /** * Compute the number of periodic payments. * * @param rate - Rate of interest (per period) * @param pmt - Payment * @param pv - Present value * @param fv - Future value * @param when - When payments are due * * @returns The number of periodic payments * * @since v0.0.12 * * ## Examples * * If you only had $150/month to pay towards the loan, how long would it take * to pay-off a loan of $8,000 at 7% annual interest? * * ```javascript * import { nper } from 'financial' * * Math.round(nper(0.07/12, -150, 8000), 5) // 64.07335 * ``` * * So, over 64 months would be required to pay off the loan. * * ## Notes * * The number of periods `nper` is computed by solving the equation: * * ``` * fv + pv * (1+rate) ** nper + pmt * (1+rate * when) / rate * ((1+rate) ** nper-1) = 0 * ``` * * but if `rate = 0` then: * * ``` * fv + pv + pmt * nper = 0 * ``` */ export function nper (rate: number, pmt: number, pv: number, fv = 0, when = PaymentDueTime.End) : number { const isRateZero = rate === 0 if (isRateZero) { return -(fv + pv) / pmt } const whenMult = when === PaymentDueTime.Begin ? 1 : 0 const z = pmt * (1 + rate * whenMult) / rate return Math.log((-fv + z) / (pv + z)) / Math.log(1 + rate) } /** * Compute the interest portion of a payment. * * @param rate - Rate of interest as decimal (not per cent) per period * @param per - Interest paid against the loan changes during the life or the loan. The `per` is the payment period to calculate the interest amount * @param nper - Number of compounding periods * @param pv - Present value * @param fv - Future value * @param when - When payments are due * * @returns Interest portion of payment * * @since v0.0.12 * * ## Examples * * What is the amortization schedule for a 1 year loan of $2500 at * 8.24% interest per year compounded monthly? * * ```javascript * const principal = 2500 * const periods = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] * const ipmts = periods.map((per) => f.ipmt(0.0824 / 12, per, 1 * 12, principal)) * expect(ipmts).toEqual([ * -17.166666666666668, * -15.789337457350777, * -14.402550587464257, * -13.006241114404524, * -11.600343649629737, * -10.18479235559687, * -8.759520942678298, * -7.324462666057678, * -5.879550322604295, * -4.424716247725826, * -2.9598923121998877, * -1.4850099189833388 * ]) * const interestpd = ipmts.reduce((a, b) => a + b, 0) * expect(interestpd).toBeCloseTo(-112.98308424136215, 6) * ``` * * The `periods` variable represents the periods of the loan. Remember that financial equations start the period count at 1! * * ## Notes * * The total payment is made up of payment against principal plus interest. * * ``` * pmt = ppmt + ipmt * ``` */ export function ipmt (rate: number, per: number, nper: number, pv: number, fv = 0, when = PaymentDueTime.End) : number { // Payments start at the first period, so payments before that // don't make any sense. if (per < 1) { return Number.NaN } // If payments occur at the beginning of a period and this is the // first period, then no interest has accrued. if (when === PaymentDueTime.Begin && per === 1) { return 0 } const totalPmt = pmt(rate, nper, pv, fv, when) let ipmtVal = _rbl(rate, per, totalPmt, pv, when) * rate // If paying at the beginning we need to discount by one period if (when === PaymentDueTime.Begin && per > 1) { ipmtVal = ipmtVal / (1 + rate) } return ipmtVal } /** * Compute the payment against loan principal. * * @param rate - Rate of interest (per period) * @param per - Amount paid against the loan changes. The `per` is the period of interest. * @param nper - Number of compounding periods * @param pv - Present value * @param fv - Future value * @param when - When payments are due * * @returns the payment against loan principal * * @since v0.0.14 */ export function ppmt (rate: number, per: number, nper: number, pv: number, fv = 0, when = PaymentDueTime.End) : number { const total = pmt(rate, nper, pv, fv, when) return total - ipmt(rate, per, nper, pv, fv, when) } /** * Calculates the present value of an annuity investment based on constant-amount * periodic payments and a constant interest rate. * * @param rate - Rate of interest (per period) * @param nper - Number of compounding periods * @param pmt - Payment * @param fv - Future value * @param when - When payments are due * * @returns the present value of a payment or investment * * @since v0.0.15 * * ## Examples * * What is the present value (e.g., the initial investment) * of an investment that needs to total $15692.93 * after 10 years of saving $100 every month? Assume the * interest rate is 5% (annually) compounded monthly. * * ```javascript * import { pv } from 'financial' * * pv(0.05/12, 10*12, -100, 15692.93) // -100.00067131625819 * ``` * * By convention, the negative sign represents cash flow out * (i.e., money not available today). Thus, to end up with * $15,692.93 in 10 years saving $100 a month at 5% annual * interest, one's initial deposit should also be $100. * * ## Notes * * The present value is computed by solving the equation: * * ``` * fv + pv * (1 + rate) ** nper + pmt * (1 + rate * when) / rate * ((1 + rate) ** nper - 1) = 0 * ``` * * or, when `rate = 0`: * * ``` * fv + pv + pmt * nper = 0 * ``` * * for `pv`, which is then returned. * * ## References * * [Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May)](http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt). */ export function pv (rate: number, nper: number, pmt: number, fv = 0, when = PaymentDueTime.End): number { const whenMult = when === PaymentDueTime.Begin ? 1 : 0 const isRateZero = rate === 0 const temp = (1 + rate) ** nper const fact = isRateZero ? nper : (1 + rate * whenMult) * (temp - 1) / rate return -(fv + pmt * fact) / temp } /** * Compute the rate of interest per period * * @param nper - Number of compounding periods * @param pmt - Payment * @param pv - Present value * @param fv - Future value * @param when - When payments are due ('begin' or 'end') * @param guess - Starting guess for solving the rate of interest * @param tol - Required tolerance for the solution * @param maxIter - Maximum iterations in finding the solution * * @returns the rate of interest per period (or `NaN` if it could * not be computed within the number of iterations provided) * * @since v0.0.16 * * ## Notes * * Use Newton's iteration until the change is less than 1e-6 * for all values or a maximum of 100 iterations is reached. * Newton's rule is: * * ``` * r_{n+1} = r_{n} - g(r_n)/g'(r_n) * ``` * * where: * * - `g(r)` is the formula * - `g'(r)` is the derivative with respect to r. * * * The rate of interest is computed by iteratively solving the * (non-linear) equation: * * ``` * fv + pv * (1+rate) ** nper + pmt * (1+rate * when) / rate * ((1+rate) ** nper - 1) = 0 * ``` * * for `rate. * * ## References * * [Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May)](http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt). */ export function rate (nper: number, pmt: number, pv: number, fv: number, when = PaymentDueTime.End, guess = 0.1, tol = 1e-6, maxIter = 100) : number { let rn = guess let iterator = 0 let close = false while (iterator < maxIter && !close) { const rnp1 = rn - _gDivGp(rn, nper, pmt, pv, fv, when) const diff = Math.abs(rnp1 - rn) close = diff < tol iterator++ rn = rnp1 } // if exausted all the iterations and the result is not // close enough, returns `NaN` if (!close) { return Number.NaN } return rn } /** * Return the Internal Rate of Return (IRR). * * This is the "average" periodically compounded rate of return * that gives a net present value of 0.0; for a more complete * explanation, see Notes below. * * @param values - Input cash flows per time period. * By convention, net "deposits" * are negative and net "withdrawals" are positive. Thus, for * example, at least the first element of `values`, which represents * the initial investment, will typically be negative. * @param guess - Starting guess for solving the Internal Rate of Return * @param tol - Required tolerance for the solution * @param maxIter - Maximum iterations in finding the solution * * @returns Internal Rate of Return for periodic input values * * @since v0.0.17 * * ## Notes * * The IRR is perhaps best understood through an example (illustrated * using `irr` in the Examples section below). * * Suppose one invests 100 * units and then makes the following withdrawals at regular (fixed) * intervals: 39, 59, 55, 20. Assuming the ending value is 0, one's 100 * unit investment yields 173 units; however, due to the combination of * compounding and the periodic withdrawals, the "average" rate of return * is neither simply 0.73/4 nor (1.73)^0.25-1. * Rather, it is the solution (for `r`) of the equation: * * ``` * -100 + 39/(1+r) + 59/((1+r)^2) + 55/((1+r)^3) + 20/((1+r)^4) = 0 * ``` * * In general, for `values` = `[0, 1, ... M]`, * `irr` is the solution of the equation: * * ``` * \\sum_{t=0}^M{\\frac{v_t}{(1+irr)^{t}}} = 0 * ``` * * ## Example * * ```javascript * import { irr } from 'financial' * * irr([-100, 39, 59, 55, 20]) // 0.28095 * irr([-100, 0, 0, 74]) // -0.0955 * irr([-100, 100, 0, -7]) // -0.0833 * irr([-100, 100, 0, 7]) // 0.06206 * irr([-5, 10.5, 1, -8, 1]) // 0.0886 * ``` * * ## References * * - L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed., * Addison-Wesley, 2003, pg. 348. */ export function irr (values: number[], guess = 0.1, tol = 1e-6, maxIter = 100): number { // Based on https://gist.github.com/ghalimi/4591338 by @ghalimi // ASF licensed (check the link for the full license) // Credits: algorithm inspired by Apache OpenOffice // Initialize dates and check that values contains at // least one positive value and one negative value const dates : number[] = [] let positive = false let negative = false for (let i = 0; i < values.length; i++) { dates[i] = (i === 0) ? 0 : dates[i - 1] + 365 if (values[i] > 0) { positive = true } if (values[i] < 0) { negative = true } } // Return error if values does not contain at least one positive // value and one negative value if (!positive || !negative) { return Number.NaN } // Initialize guess and resultRate let resultRate = guess // Implement Newton's method let newRate, epsRate, resultValue let iteration = 0 let contLoop = true do { resultValue = _irrResult(values, dates, resultRate) newRate = resultRate - resultValue / _irrResultDeriv(values, dates, resultRate) epsRate = Math.abs(newRate - resultRate) resultRate = newRate contLoop = (epsRate > tol) && (Math.abs(resultValue) > tol) } while (contLoop && (++iteration < maxIter)) if (contLoop) { return Number.NaN } // Return internal rate of return return resultRate } /** * Returns the NPV (Net Present Value) of a cash flow series. * * @param rate - The discount rate * @param values - The values of the time series of cash flows. The (fixed) time * interval between cash flow "events" must be the same as that for * which `rate` is given (i.e., if `rate` is per year, then precisely * a year is understood to elapse between each cash flow event). By * convention, investments or "deposits" are negative, income or * "withdrawals" are positive; `values` must begin with the initial * investment, thus `values[0]` will typically be negative. * @returns The NPV of the input cash flow series `values` at the discount `rate`. * * @since v0.0.18 * * ## Warnings * * `npv considers a series of cashflows starting in the present (t = 0). * NPV can also be defined with a series of future cashflows, paid at the * end, rather than the start, of each period. If future cashflows are used, * the first cashflow `values[0]` must be zeroed and added to the net * present value of the future cashflows. This is demonstrated in the * examples. * * ## Notes * * Returns the result of: * * ``` * \\sum_{t=0}^{M-1}{\\frac{values_t}{(1+rate)^{t}}} * ``` * * ## Examples * * Consider a potential project with an initial investment of $40 000 and * projected cashflows of $5 000, $8 000, $12 000 and $30 000 at the end of * each period discounted at a rate of 8% per period. To find the project's * net present value: * * ```javascript * import {npv} from 'financial' * * const rate = 0.08 * const cashflows = [-40_000, 5000, 8000, 12000, 30000] * npv(rate, cashflows) // 3065.2226681795255 * ``` * * It may be preferable to split the projected cashflow into an initial * investment and expected future cashflows. In this case, the value of * the initial cashflow is zero and the initial investment is later added * to the future cashflows net present value: * * ```javascript * const initialCashflow = cashflows[0] * cashflows[0] = 0 * * npv(rate, cashflows) + initialCashflow // 3065.2226681795255 * ``` * * ## References * * L. J. Gitman, "Principles of Managerial Finance, Brief," * 3rd ed., Addison-Wesley, 2003, pg. 346. */ export function npv (rate: number, values: number[]) : number { return values.reduce( (acc, curr, i) => acc + (curr / (1 + rate) ** i), 0 ) } /** * Calculates the Modified Internal Rate of Return. * * @param values - Cash flows (must contain at least one positive and one negative * value) or nan is returned. The first value is considered a sunk * cost at time zero. * @param financeRate - Interest rate paid on the cash flows * @param reinvestRate - Interest rate received on the cash flows upon reinvestment * * @returns Modified internal rate of return * * @since v0.1.0 */ export function mirr (values: number[], financeRate: number, reinvestRate: number): number { let positive = false let negative = false for (let i = 0; i < values.length; i++) { if (values[i] > 0) { positive = true } if (values[i] < 0) { negative = true } } // Return error if values does not contain at least one // positive value and one negative value if (!positive || !negative) { return Number.NaN } const numer = Math.abs(npv(reinvestRate, values.map((x) => x > 0 ? x : 0))) const denom = Math.abs(npv(financeRate, values.map(x => x < 0 ? x : 0))) return (numer / denom) ** (1 / (values.length - 1)) * (1 + reinvestRate) - 1 } /** * This function is here to simply have a different name for the 'fv' * function to not interfere with the 'fv' keyword argument within the 'ipmt' * function. It is the 'remaining balance on loan' which might be useful as * it's own function, but is easily calculated with the 'fv' function. * * @private */ function _rbl (rate: number, per: number, pmt: number, pv: number, when: PaymentDueTime) { return fv(rate, (per - 1), pmt, pv, when) } /** * Evaluates `g(r_n)/g'(r_n)`, where: * * ``` * g = fv + pv * (1+rate) ** nper + pmt * (1+rate * when)/rate * ((1+rate) ** nper - 1) * ``` * * @private */ function _gDivGp (r: number, n: number, p: number, x: number, y: number, when: PaymentDueTime): number { const w = when === PaymentDueTime.Begin ? 1 : 0 const t1 = (r + 1) ** n const t2 = (r + 1) ** (n - 1) const g = y + t1 * x + p * (t1 - 1) * (r * w + 1) / r const gp = (n * t2 * x - p * (t1 - 1) * (r * w + 1) / (r ** 2) + n * p * t2 * (r * w + 1) / r + p * (t1 - 1) * w / r) return g / gp } /** * Calculates the resulting amount. * * Based on https://gist.github.com/ghalimi/4591338 by @ghalimi * ASF licensed (check the link for the full license) * * @private */ function _irrResult (values: number[], dates: number[], rate: number): number { const r = rate + 1 let result = values[0] for (let i = 1; i < values.length; i++) { result += values[i] / Math.pow(r, (dates[i] - dates[0]) / 365) } return result } /** * Calculates the first derivation * * Based on https://gist.github.com/ghalimi/4591338 by @ghalimi * ASF licensed (check the link for the full license) * * @private */ function _irrResultDeriv (values: number[], dates: number[], rate: number) : number { const r = rate + 1 let result = 0 for (let i = 1; i < values.length; i++) { const frac = (dates[i] - dates[0]) / 365 result -= frac * values[i] / Math.pow(r, frac + 1) } return result }
the_stack
import { Band, BandBorder, BandLayerSpec, BandLineMap, ColumnGroupMap, DomainLabel, LatestIndexMap, LineData, Table, } from '../types' import {createGroupIDColumn, getBandColorScale} from './' import {FILL, LOWER, RESULT, TIME, UPPER} from '../constants/columnKeys' import {BAND_COLOR_SCALE_CONSTANT} from '../constants' import {isDefined} from '../utils/isDefined' import {isFiniteNumber} from '../utils/isFiniteNumber' import {isNumber} from '../utils/isNumber' import {createLatestBandIndices} from '../utils/legend/band' export const getBands = ( lineData: LineData, bandLineMap: BandLineMap ): Band[] => { const {upperLines = [], rowLines = [], lowerLines = []} = bandLineMap const bands: Band[] = [] rowLines.forEach((rowIndex, i) => { // Each band must have a "main column" which creates a row index // Any non-main column not associated with a "main" is not a band // Only bands get rendered if (!isFiniteNumber(rowIndex)) { return } const upperIndex = upperLines[i] const upperIsFinite = isFiniteNumber(upperIndex) const upper = upperIsFinite ? lineData[upperIndex] : {fill: ''} const lowerIndex = lowerLines[i] const lowerIsFinite = isFiniteNumber(lowerIndex) const lower = lowerIsFinite ? lineData[lowerIndex] : {fill: ''} const row = lineData[rowIndex] upper.fill = row.fill lower.fill = row.fill const result: Band = {...row} if (upperIsFinite) { result.upper = upper as BandBorder } if (lowerIsFinite) { result.lower = lower as BandBorder } bands.push(result) }) return bands } export const getBandLineMap = ( fillColumnMap: ColumnGroupMap, lowerColumnName: string, rowColumnName: string, upperColumnName: string ): BandLineMap => { const bandIndices = { rowLines: [], lowerLines: [], upperLines: [], } const bands = Object.values( groupLineIndicesIntoBands( fillColumnMap, lowerColumnName, rowColumnName, upperColumnName ) ) if (Array.isArray(bands)) { bands.forEach(band => { bandIndices.rowLines.push(isDefined(band.row) ? band.row : null) bandIndices.lowerLines.push(isDefined(band.lower) ? band.lower : null) bandIndices.upperLines.push(isDefined(band.upper) ? band.upper : null) }) } return bandIndices } export const groupLineIndicesIntoBands = ( fill: ColumnGroupMap, lowerColumnName: string, rowColumnName: string, upperColumnName: string ) => { const {columnKeys, mappings} = fill const columnKeysWithoutResult = Array.isArray(columnKeys) ? columnKeys.filter(key => key !== RESULT) : [] const bandLineIndexMap = {} if (Array.isArray(mappings)) { mappings.forEach((line, index) => { const lineName = columnKeysWithoutResult.reduce((accum, current) => { return `${accum}${line[current]}` }, '') if (!bandLineIndexMap[lineName]) { bandLineIndexMap[lineName] = { lower: null, upper: null, row: null, } } if (line[RESULT] === lowerColumnName) { bandLineIndexMap[lineName][LOWER] = index } else if (line[RESULT] === upperColumnName) { bandLineIndexMap[lineName][UPPER] = index } else if (line[RESULT] === rowColumnName) { bandLineIndexMap[lineName].row = index } }) } return bandLineIndexMap } export const alignMinMaxWithBand = ( lineData: LineData, bandLineMap: BandLineMap ): LineData => { const {rowLines, upperLines, lowerLines} = bandLineMap const alignedData = {} for (let i = 0; i < rowLines.length; i += 1) { let bandXs = [] let bandYs = [] let upperXs = [] let upperYs = [] let lowerXs = [] let lowerYs = [] const bandId = rowLines[i] const upperId = upperLines[i] const lowerId = lowerLines[i] if (lineData[upperId]) { alignedData[upperId] = { fill: lineData[upperId].fill, xs: [], ys: [], } upperXs = lineData[upperId].xs upperYs = lineData[upperId].ys } if (lineData[lowerId]) { alignedData[lowerId] = { fill: lineData[lowerId].fill, xs: [], ys: [], } lowerXs = lineData[lowerId].xs lowerYs = lineData[lowerId].ys } if (lineData[bandId]) { alignedData[bandId] = { fill: lineData[bandId].fill, xs: [], ys: [], } bandXs = lineData[bandId].xs bandYs = lineData[bandId].ys } let bandIterator = 0 let upperIterator = 0 let lowerIterator = 0 while ( bandIterator < bandXs.length || upperIterator < upperXs.length || lowerIterator < lowerXs.length ) { const bandTime = bandXs[bandIterator] const bandValue = bandYs[bandIterator] const upperTime = upperXs[upperIterator] const upperValue = upperYs[upperIterator] const lowerTime = lowerXs[lowerIterator] const lowerValue = lowerYs[lowerIterator] // 1. All three are equal if (bandTime === upperTime && bandTime === lowerTime) { if (isDefined(bandTime)) { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) bandIterator += 1 } if (isDefined(upperTime)) { alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) upperIterator += 1 } if (isDefined(lowerTime)) { alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) lowerIterator += 1 } } // 2. Lower is not equal to the other two else if (bandTime === upperTime) { if (bandTime > lowerTime || !isDefined(bandTime)) { if (isDefined(bandId)) { alignedData[bandId].xs.push(lowerTime) alignedData[bandId].ys.push(lowerValue) } if (isDefined(upperId)) { alignedData[upperId].xs.push(lowerTime) alignedData[upperId].ys.push(lowerValue) } alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) lowerIterator += 1 } else if (bandTime < lowerTime || !isDefined(lowerTime)) { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) if (isDefined(lowerId)) { alignedData[lowerId].xs.push(bandTime) alignedData[lowerId].ys.push(bandValue) } bandIterator += 1 upperIterator += 1 } } // 3. Upper is not equal to the other two else if (bandTime === lowerTime) { if (bandTime > upperTime || !isDefined(bandTime)) { if (isDefined(bandId)) { alignedData[bandId].xs.push(upperTime) alignedData[bandId].ys.push(upperValue) } if (isDefined(lowerId)) { alignedData[lowerId].xs.push(upperTime) alignedData[lowerId].ys.push(upperValue) } alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) upperIterator += 1 } else if (bandTime < upperTime || !isDefined(upperTime)) { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) if (isDefined(upperId)) { alignedData[upperId].xs.push(bandTime) alignedData[upperId].ys.push(bandValue) } alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) bandIterator += 1 lowerIterator += 1 } } // 4. Band is not equal to the other two else if (upperTime === lowerTime) { if (upperTime > bandTime || !isDefined(upperTime)) { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) if (isDefined(upperId)) { alignedData[upperId].xs.push(bandTime) alignedData[upperId].ys.push(bandValue) } if (isDefined(lowerId)) { alignedData[lowerId].xs.push(bandTime) alignedData[lowerId].ys.push(bandValue) } bandIterator += 1 } else if (upperTime < bandTime || !isDefined(bandTime)) { if (isDefined(bandId)) { alignedData[bandId].xs.push(upperTime) alignedData[bandId].ys.push(upperValue) } alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) upperIterator += 1 lowerIterator += 1 } } // 5. They are all different else { if (!isDefined(bandTime)) { if (upperTime > lowerTime) { if (isDefined(bandId)) { alignedData[bandId].xs.push(lowerTime) alignedData[bandId].ys.push(lowerValue) } alignedData[upperId].xs.push(lowerTime) alignedData[upperId].ys.push(lowerValue) alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) lowerIterator += 1 } else { if (isDefined(bandId)) { alignedData[bandId].xs.push(upperTime) alignedData[bandId].ys.push(upperValue) } alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) alignedData[lowerId].xs.push(upperTime) alignedData[lowerId].ys.push(upperValue) upperIterator += 1 } } else if (!isDefined(upperTime)) { if (bandTime > lowerTime) { alignedData[bandId].xs.push(lowerTime) alignedData[bandId].ys.push(lowerValue) if (isDefined(upperId)) { alignedData[upperId].xs.push(lowerTime) alignedData[upperId].ys.push(lowerValue) } alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) lowerIterator += 1 } else { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) if (isDefined(upperId)) { alignedData[upperId].xs.push(bandTime) alignedData[upperId].ys.push(bandValue) } alignedData[lowerId].xs.push(bandTime) alignedData[lowerId].ys.push(bandValue) bandIterator += 1 } } else if (!isDefined(lowerTime)) { if (bandTime > upperTime) { alignedData[bandId].xs.push(upperTime) alignedData[bandId].ys.push(upperValue) alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) if (isDefined(lowerId)) { alignedData[lowerId].xs.push(upperTime) alignedData[lowerId].ys.push(upperValue) } upperIterator += 1 } else { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) alignedData[upperId].xs.push(bandTime) alignedData[upperId].ys.push(bandValue) if (isDefined(lowerId)) { alignedData[lowerId].xs.push(bandTime) alignedData[lowerId].ys.push(bandValue) } bandIterator += 1 } } else { const lowest = Math.min(bandTime, upperTime, lowerTime) if (lowest === lowerTime) { alignedData[bandId].xs.push(lowerTime) alignedData[bandId].ys.push(lowerValue) alignedData[upperId].xs.push(lowerTime) alignedData[upperId].ys.push(lowerValue) alignedData[lowerId].xs.push(lowerTime) alignedData[lowerId].ys.push(lowerValue) lowerIterator += 1 } else if (lowest === upperTime) { alignedData[bandId].xs.push(upperTime) alignedData[bandId].ys.push(upperValue) alignedData[upperId].xs.push(upperTime) alignedData[upperId].ys.push(upperValue) alignedData[lowerId].xs.push(upperTime) alignedData[lowerId].ys.push(upperValue) upperIterator += 1 } else { alignedData[bandId].xs.push(bandTime) alignedData[bandId].ys.push(bandValue) alignedData[upperId].xs.push(bandTime) alignedData[upperId].ys.push(bandValue) alignedData[lowerId].xs.push(bandTime) alignedData[lowerId].ys.push(bandValue) bandIterator += 1 } } } } } return alignedData } export const bandTransform = ( inputTable: Table, xColumnKey: string, yColumnKey: string, fillColKeys: string[], colors: string[], lowerColumnName: string, rowColumnName: string, upperColumnName: string ): BandLayerSpec => { const [fillColumn, fillColumnMap] = createGroupIDColumn( inputTable, fillColKeys ) const table = inputTable.addColumn(FILL, 'system', 'number', fillColumn) const xCol = table.getColumn(xColumnKey, 'number') const yCol = table.getColumn(yColumnKey, 'number') const bandLineMap = getBandLineMap( fillColumnMap, lowerColumnName || '', rowColumnName, upperColumnName || '' ) const fillScale = range => getBandColorScale(bandLineMap, colors)(range * BAND_COLOR_SCALE_CONSTANT) const lineData: LineData = {} let xMin = Infinity let xMax = -Infinity let yMin = Infinity let yMax = -Infinity for (let i = 0; i < table.length; i++) { const groupID = fillColumn[i] const x = xCol[i] const y = yCol[i] if (!lineData[groupID]) { lineData[groupID] = {xs: [], ys: [], fill: ''} // 'fill' is set temporarily to no color // it will be updated with another loop later, // because it is faster to walk bandLineMap once // than to search for the indices of many lines } lineData[groupID].xs.push(x) lineData[groupID].ys.push(y) xMin = Math.min(x, xMin) xMax = Math.max(x, xMax) yMin = Math.min(y, yMin) yMax = Math.max(y, yMax) } // remember the latest (most recent) index for each group const bandDimension = yColumnKey === TIME ? DomainLabel.Y : DomainLabel.X const latestIndices: LatestIndexMap = createLatestBandIndices( lineData, bandLineMap, bandDimension ) Object.keys(bandLineMap).forEach(indexType => { bandLineMap[indexType].forEach((groupID, index) => { if (isNumber(groupID)) { lineData[groupID].fill = fillScale(index) } }) }) return { type: 'band', bandLineMap, bandName: rowColumnName, upperColumnName, lowerColumnName, inputTable, table, lineData, xDomain: [xMin, xMax], yDomain: [yMin, yMax], xColumnKey, yColumnKey, xColumnType: table.getColumnType(xColumnKey), yColumnType: table.getColumnType(yColumnKey), scales: {fill: fillScale}, columnGroupMaps: {fill: fillColumnMap, latestIndices}, } }
the_stack
import { RepeatWrapping, Mesh, PlaneBufferGeometry, Vector2, Color, MeshPhongMaterial, AddOperation, WebGLRenderTarget, DepthTexture, RGBFormat, NearestFilter, DepthFormat, UnsignedShortType, Texture, ShaderChunk, EquirectangularReflectionMapping, sRGBEncoding, TextureLoader } from 'three' import { TGALoader } from '../../assets/loaders/tga/TGALoader' import { Updatable } from '../interfaces/Updatable' const vertexUniforms = `uniform float time; uniform sampler2D distortionMap; uniform float bigWaveScale; uniform vec2 bigWaveUVScale; uniform vec2 bigWaveSpeed; ` const pannerFunction = `vec2 panner(const in vec2 uv, const in float time, const in vec2 speed) { return uv + speed * time; }` const vertexFunctions = pannerFunction + ` float getWaveHeight(const in vec2 uv) { return texture( distortionMap, uv ).y * bigWaveScale; } vec3 calculateNormal(const in vec2 p) { const float eps = .05; const vec2 h = vec2(eps,0.0); float height = getWaveHeight(p); return normalize(vec3( getWaveHeight(p+h.xy) - height, getWaveHeight(p+h.yx) - height, 2.0 )); }` const fragUniforms = `uniform sampler2D depthMap; uniform sampler2D distortionMap; uniform vec2 viewportSize; uniform vec2 cameraNearFar; uniform vec3 shallowWaterColor; uniform vec2 opacityRange; uniform float time; uniform float shallowToDeepDistance; uniform float opacityFadeDistance; uniform float waveUVFactor; uniform float waveDistortionFactor; uniform vec2 waveDistortionSpeed; uniform vec2 waveSpeed; uniform vec3 foamColor; uniform vec2 foamSpeed; uniform float foamScale; ` const fragmentFunctions = pannerFunction + ` float getViewZ(const in float depth) { return perspectiveDepthToViewZ(depth, cameraNearFar.x, cameraNearFar.y); } float depthDiff() { vec2 depthUv = gl_FragCoord.xy / viewportSize; float sceneDepth = getViewZ( texture2D(depthMap, depthUv).x ); float pixelDepth = getViewZ( gl_FragCoord.z ); return pixelDepth - sceneDepth; } float depthFade(const in float fadeDistance) { float diff = depthDiff(); return saturate(diff / max(fadeDistance, EPSILON)); } vec3 foam( const in vec3 waterColor ) { float diff = saturate( depthDiff() ); vec2 displacement = texture2D( distortionMap, panner( foamScale * vUv, time, foamSpeed ) ).bb; displacement = ( displacement * 2.0 ) - 1.0 ; diff += displacement.x; return mix( foamColor, waterColor, step( 0.1 , diff ) ); } ` const pixelData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=' function insertBeforeString(source, searchTerm, addition) { const position = source.indexOf(searchTerm) return [source.slice(0, position), addition, source.slice(position)].join('\n') } function insertAfterString(source, searchTerm, addition) { const position = source.indexOf(searchTerm) return [source.slice(0, position + searchTerm.length), addition, source.slice(position + searchTerm.length)].join( '\n' ) } function addImageProcess(src: string): Promise<HTMLImageElement> { return new Promise((resolve, reject) => { let img = new Image() img.onload = () => resolve(img) img.onerror = reject img.src = src }) } function loadTexture(src): Promise<Texture> { const loader = src.endsWith('tga') ? new TGALoader() : new TextureLoader() return new Promise((resolve, reject) => { loader.load(src, resolve, null, (error) => reject(error)) }) } export class Ocean extends Mesh implements Updatable { depthMap: WebGLRenderTarget shouldResize: boolean _shallowWaterColor: Color _opacityRange: Vector2 shallowToDeepDistance: number opacityFadeDistance: number bigWaveHeight: number _bigWaveTiling: Vector2 _bigWaveSpeed: Vector2 // Small wave _waveScale: Vector2 _waveDistortionSpeed: Vector2 waveDistortionTiling: number waveTiling: number _waveSpeed: Vector2 //Foam _foamColor: Color _foamSpeed: Vector2 foamTiling: number // Maps _envMap: string _normalMap: string _distortionMap: string _distortionTexture: Texture constructor() { const planeGeometry = new PlaneBufferGeometry(10, 10, 100, 100) super(planeGeometry, new MeshPhongMaterial({ color: 'red' })) this.rotation.x = -Math.PI * 0.5 this.shouldResize = true this._shallowWaterColor = new Color() this._opacityRange = new Vector2() this._waveScale = new Vector2() this._bigWaveTiling = new Vector2() this._bigWaveSpeed = new Vector2() this._waveDistortionSpeed = new Vector2() this._waveSpeed = new Vector2() this._foamColor = new Color() this._foamSpeed = new Vector2() this.setupMaterial() this.setupRenderTarget() window.addEventListener('resize', () => { this.shouldResize = true }) } async setupMaterial() { // To make the three shader compiler insert vUv varying const pixel = await addImageProcess(pixelData) const tempTexture = new Texture(pixel) const material = this.material as MeshPhongMaterial material.normalMap = tempTexture material.normalScale = this._waveScale material.transparent = true material.combine = AddOperation material.needsUpdate = true material.onBeforeCompile = (shader) => { const viewportSize = new Vector2(window.innerWidth, window.innerHeight) shader.uniforms.time = { value: 0 } shader.uniforms.distortionMap = { value: null } shader.uniforms.depthMap = { value: null } shader.uniforms.viewportSize = { value: viewportSize } shader.uniforms.cameraNearFar = { value: new Vector2(0.1, 100) } shader.uniforms.shallowWaterColor = { value: this._shallowWaterColor } shader.uniforms.opacityRange = { value: this._opacityRange } shader.uniforms.bigWaveUVScale = { value: this._bigWaveTiling } shader.uniforms.bigWaveSpeed = { value: this._bigWaveSpeed } shader.uniforms.bigWaveScale = { value: 0.7 } shader.uniforms.shallowToDeepDistance = { value: 0.1 } shader.uniforms.opacityFadeDistance = { value: 0.1 } shader.uniforms.waveDistortionFactor = { value: 7.0 } shader.uniforms.waveUVFactor = { value: 12.0 } shader.uniforms.waveDistortionSpeed = { value: this._waveDistortionSpeed } shader.uniforms.waveSpeed = { value: this._waveSpeed } shader.uniforms.foamColor = { value: this._foamColor } shader.uniforms.foamSpeed = { value: this._foamSpeed } shader.uniforms.foamScale = { value: 2.0 } shader.vertexShader = insertBeforeString(shader.vertexShader, 'varying vec3 vViewPosition;', vertexUniforms) shader.vertexShader = insertBeforeString(shader.vertexShader, 'void main()', vertexFunctions) shader.vertexShader = insertBeforeString( shader.vertexShader, '#include <defaultnormal_vertex>', ` vec2 waveUv = panner( bigWaveUVScale * uv, time, bigWaveSpeed ); float waveHeight = getWaveHeight( waveUv ); objectNormal = calculateNormal(waveUv); ` ) // Transform vertex shader.vertexShader = shader.vertexShader.replace( '#include <project_vertex>', ` vec4 mvPosition = vec4( transformed, 1.0 ); mvPosition = modelMatrix * mvPosition; mvPosition.y += waveHeight; mvPosition = viewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition; ` ) shader.fragmentShader = insertBeforeString(shader.fragmentShader, 'uniform vec3 diffuse;', fragUniforms) shader.fragmentShader = insertBeforeString(shader.fragmentShader, 'void main()', fragmentFunctions) shader.fragmentShader = insertAfterString( shader.fragmentShader, 'vec4 diffuseColor = vec4( diffuse, opacity );', `float colorFade = depthFade(shallowToDeepDistance); diffuseColor.rgb = mix(shallowWaterColor, diffuse, colorFade); diffuseColor.rgb = foam(diffuseColor.rgb); float opacityFade = depthFade(opacityFadeDistance); diffuseColor.a = clamp(opacityFade, opacityRange.x, opacityRange.y); ` ) // Small wave normal map let normal_fragment_maps = ShaderChunk.normal_fragment_maps normal_fragment_maps = normal_fragment_maps.replace( 'vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;', `float waveDist = texture( distortionMap, panner( waveDistortionFactor * vUv, time, waveDistortionSpeed ) ).y * 0.05; vec3 mapN = texture( normalMap, panner( waveUVFactor * vUv, time, waveSpeed ) + waveDist ).xyz * 2.0 - 1.0; ` ) shader.fragmentShader = shader.fragmentShader.replace('#include <normal_fragment_maps>', normal_fragment_maps) ;(this.material as any).userData.shader = shader } } setupRenderTarget() { const size = new Vector2(window.innerWidth, window.innerHeight) this.depthMap = new WebGLRenderTarget(size.x, size.y) this.depthMap.texture.format = RGBFormat this.depthMap.texture.minFilter = NearestFilter this.depthMap.texture.magFilter = NearestFilter this.depthMap.texture.generateMipmaps = false this.depthMap.stencilBuffer = false this.depthMap.depthBuffer = true this.depthMap.depthTexture = new DepthTexture(size.x, size.y) this.depthMap.depthTexture.format = DepthFormat this.depthMap.depthTexture.type = UnsignedShortType } onBeforeRender = (renderer, scene, camera) => { const shader = (this.material as any).userData.shader shader?.uniforms.cameraNearFar.value.set(camera.near, camera.far) if (this.shouldResize) { shader?.uniforms.viewportSize.value.set(window.innerWidth, window.innerHeight) const dpr = renderer.getPixelRatio() this.depthMap.setSize(window.innerWidth * dpr, window.innerHeight * dpr) this.shouldResize = false } // render scene into target // Depth texture update this.visible = false const currentRenderTarget = renderer.getRenderTarget() renderer.setRenderTarget(this.depthMap) renderer.state.buffers.depth.setMask(true) if (renderer.autoClear === false) renderer.clear() renderer.render(scene, camera) renderer.setRenderTarget(currentRenderTarget) this.visible = true } update(dt: number) { const shader = (this.material as any).userData.shader if (!shader) return shader.uniforms.distortionMap.value = this._distortionTexture shader.uniforms.foamScale.value = this.foamTiling shader.uniforms.waveDistortionFactor.value = this.waveDistortionTiling shader.uniforms.waveUVFactor.value = this.waveTiling shader.uniforms.bigWaveScale.value = this.bigWaveHeight shader.uniforms.opacityFadeDistance.value = this.opacityFadeDistance shader.uniforms.shallowToDeepDistance.value = this.shallowToDeepDistance shader.uniforms.depthMap.value = this.depthMap.depthTexture shader.uniforms.time.value += dt } copy(source: this, recursive = true) { super.copy(source, recursive) return this } get _material(): MeshPhongMaterial { return this.material as MeshPhongMaterial } get distortionMap(): string { return this._distortionMap } set distortionMap(path: string) { this._distortionMap = path loadTexture(path) .then((texture) => { texture.wrapS = RepeatWrapping texture.wrapT = RepeatWrapping this._distortionTexture = texture }) .catch(console.error) } get envMap(): string { return this._envMap } // Equirectangular set envMap(path: string) { this._envMap = path loadTexture(path) .then((texture) => { texture.mapping = EquirectangularReflectionMapping texture.encoding = sRGBEncoding this._material.envMap = texture }) .catch(console.error) } get normalMap(): string { return this._normalMap } set normalMap(path: string) { this._normalMap = path loadTexture(path) .then((texture) => { texture.wrapS = RepeatWrapping texture.wrapT = RepeatWrapping this._material.normalMap = texture }) .catch(console.error) } set shininess(value: number) { this._material.shininess = value } get shininess() { return this._material.shininess } set reflectivity(value: number) { this._material.reflectivity = value } get reflectivity() { return this._material.reflectivity } get color(): Color { return this._material.color } set color(value) { if (typeof value === 'string') this._material.color.set(value) else this._material.color.copy(value) } get shallowWaterColor(): Color { return this._shallowWaterColor } set shallowWaterColor(value: Color) { if (typeof value === 'string') this._shallowWaterColor.set(value) else this._shallowWaterColor.copy(value) } get opacityRange(): Vector2 { return this._opacityRange } set opacityRange(value: Vector2) { this._opacityRange.copy(value).clampScalar(0.0, 1.0) } get foamColor(): Color { return this._foamColor } set foamColor(value: Color) { this._foamColor.copy(value) } get foamSpeed(): Vector2 { return this._foamSpeed } set foamSpeed(value: Vector2) { this._foamSpeed.copy(value) } get bigWaveTiling(): Vector2 { return this._bigWaveTiling } set bigWaveTiling(value: Vector2) { this._bigWaveTiling.copy(value) } get bigWaveSpeed(): Vector2 { return this._bigWaveSpeed } set bigWaveSpeed(value: Vector2) { this._bigWaveSpeed.copy(value) } get waveScale(): Vector2 { return this._waveScale } set waveScale(value: Vector2) { this._waveScale.copy(value) } get waveDistortionSpeed(): Vector2 { return this._waveDistortionSpeed } set waveDistortionSpeed(value: Vector2) { this._waveDistortionSpeed.copy(value) } get waveSpeed(): Vector2 { return this._waveSpeed } set waveSpeed(value: Vector2) { this._waveSpeed.copy(value) } }
the_stack
module Kiwi { /** * The State Manager handles the starting, parsing, looping and swapping of game States within a Kiwi Game * There is only ever one State Manager per game, but a single Game can contain multiple States. * * @class StateManager * @namespace Kiwi * @constructor * @param game {Kiwi.Game} The game that this statemanager belongs to. * @return {Kiwi.StateMananger} * */ export class StateManager { constructor(game: Kiwi.Game) { this._game = game; this._states = []; } /** * The type of object this is. * @method objType * @return {string} "StateManager" * @public */ public objType() { return "StateManager"; } /** * The game that this manager belongs to. * @property _game * @type Kiwi.Game * @private */ private _game: Kiwi.Game; /** * An array of all of the states that are contained within this manager. * @property _states * @type Array * @private */ private _states: Kiwi.State[]; /** * The current State that the game is at. * @property current * @type Kiwi.State * @default null * @public */ public current: Kiwi.State = null; /** * The name of the new State that is to be switched to. * @property _newStateKey * @type string * @default null * @private */ private _newStateKey: string = null; /** * Checks to see if a key exists. Internal use only. * @method checkKeyExists * @param key {String} * @return {boolean} * @private */ private checkKeyExists(key: string): boolean { for (var i = 0; i < this._states.length; i++) { if (this._states[i].config.name === key) { return true; } } return false; } /** * Checks to see if the State passed is valid or not. * @method checkValidState * @param state {Kiwi.State} * @return {boolean} * @private */ private checkValidState(state: Kiwi.State): boolean { if (!state['game'] || !state['config']) { return false; } return true; } /** * Adds the given State to the StateManager. * The State must have a unique key set on it, or it will fail to be added to the manager. * Returns true if added successfully, otherwise false (can happen if State is already in the StateManager) * * @method addState * @param state {Any} The Kiwi.State instance to add. * @param [switchTo=false] {boolean} If set to true automatically switch to the given state after adding it * @return {boolean} true if the State was added successfully, otherwise false * @public */ public addState(state: any, switchTo:boolean = false): boolean { Kiwi.Log.log('Kiwi.StateManager: Adding state.', '#state'); var tempState; //What type is the state that was passed. if (typeof state === 'function') { tempState = new state(); } else if (typeof state === 'string') { tempState = window[state]; } else { tempState = state; } //Does a state with that name already exist? if (tempState.config.name && this.checkKeyExists(tempState.config.name) === true) { Kiwi.Log.error(' Kiwi.StateManager: Could not add ' + tempState.config.name + ' as a State with that name already exists.', '#state'); return false; } tempState.game = this._game; //Is it a valid state? if (this.checkValidState(tempState) === false) { Kiwi.Log.error(' Kiwi.StateManager: ' + tempState.config.name + ' isn\'t a valid state. Make sure you are using the Kiwi.State class!', '#state'); return false; } else { this._states.push(tempState); Kiwi.Log.log(' Kiwi.StateManager: ' + tempState.config.name + ' was successfully added.', '#state'); if (switchTo === true) { this.switchState( tempState.config.name ); } return true; } } /** * Is executed once the DOM has finished loading. * This is an INTERNAL Kiwi method. * @method boot * @public */ boot() { } /** * Switches to the name (key) of the state that you pass. * Does not work if the state you are switching to is already the current state OR if that state does not exist yet. * @method setCurrentState * @param key {String} * @return {boolean} * @private */ private setCurrentState(key: string): boolean { // Bail out if they are trying to switch to the already current state if (this.current !== null && this.current.config.name === key || this.checkKeyExists(key) === false) { return false; } Kiwi.Log.log('Kiwi.StateManager: Switching to "' + key + '" State.', '#state'); this._newStateKey = key; return true; } /** * Actually switches to a state that is stored in the 'newStateKey' property. This method is executed after the update loops have been executed to help prevent developer errors. * @method bootNewState * @private */ private bootNewState() { // Destroy the current if there is one. if (this.current !== null) { this.current.shutDown(); this._game.input.reset(); //Reset the input component this.current.destroy(true); //Destroy ALL IChildren ever created on that state. this._game.fileStore.removeStateFiles(this.current); //Clear the fileStore of not global files. this.current.config.reset(); //Reset the config setting this._game.cameras.zeroAllCameras(); // Reset cameras } //Set the current state, reset the key this.current = this.getState(this._newStateKey); this._newStateKey = null; //Initalise the state and execute the preload method? this.checkInit(); this.checkPreload(); } /** * Swaps the current state. * If the state has already been loaded (via addState) then you can just pass the key. * Otherwise you can pass the state object as well and it will load it then swap to it. * * @method switchState * @param key {String} The name/key of the state you would like to switch to. * @param [state=null] {Any} The state that you want to switch to. This is only used to create the state if it doesn't exist already. * @param [initParams=null] {Object} Any parameters that you would like to pass to the init method of that new state. * @param [createParams=null] {Object} Any parameters that you would like to pass to the create method of that new state. * @param [preloadParams=null] {Object} Any parameters that you would like to pass to the preload method. Since 1.3.0 of Kiwi.JS * @return {boolean} Whether the State is going to be switched to or not. * @public */ public switchState(key: string, state: any = null, initParams = null, createParams = null, preloadParams=null): boolean { // If we have a current state that isn't yet ready (preload hasn't finished) then abort now if (this.current !== null && this.current.config.isReady === false) { Kiwi.Log.error('Kiwi.StateManager: Cannot change to a new state till the current state has finished loading!', '#state'); return false; } // If state key doesn't exist then lets add it. if (this.checkKeyExists(key) === false && state !== null) { if (this.addState(state, false) === false) { return false; } } // Store the parameters (if any) if (initParams !== null || createParams !== null || preloadParams !== null) { var newState = this.getState(key); newState.config.initParams = []; newState.config.createParams = []; newState.config.preloadParams = []; for (var initParameter in initParams) { newState.config.initParams.push(initParams[initParameter]); } for (var createParameter in createParams) { newState.config.createParams.push(createParams[createParameter]); } for (var preloadParameter in preloadParams) { newState.config.preloadParams.push(preloadParams[preloadParameter]); } } return this.setCurrentState(key); } /** * Gets a state by the key that is passed. * @method getState * @param key {String} * @return {Kiwi.State} * @private */ private getState(key: string): Kiwi.State { for (var i = 0; i < this._states.length; i++) { if (this._states[i].config.name === key) { return this._states[i]; } } return null; } /* *---------------- * Check Methods *---------------- */ /** * Checks to see if the state that is being switched to needs to load some files or not. * If it does it loads the file, if it does not it runs the create method. * @method checkPreload * @private */ private checkPreload() { //Rebuild the Libraries before the preload is executed this.rebuildLibraries(); this._game.loader.onQueueProgress.add(this.onLoadProgress, this); this._game.loader.onQueueComplete.add(this.onLoadComplete, this); this.current.preload.apply(this.current, this.current.config.preloadParams); this._game.loader.start(); } /** * Checks to see if the state being switched to contains a create method. * If it does then it calls the create method. * @method callCreate * @private */ private callCreate() { Kiwi.Log.log("Kiwi.StateManager: Calling " + this.current.name + ":Create", '#state'); this.current.create.apply(this.current, this.current.config.createParams); this.current.config.runCount++; this.current.config.isCreated = true; } /** * Checks to see if the state has a init method and then executes that method if it is found. * @method checkInit * @private */ private checkInit() { //Has the state already been initialised? if (this.current.config.isInitialised === false) { //Boot the state. this.current.boot(); //Execute the Init method with params this.current.init.apply(this.current, this.current.config.initParams); this.current.config.isInitialised = true; } } /** * Is execute whilst files are being loaded by the state. * @method onLoadProgress * @param percent {Number} The current percentage of files that have been loaded. Ranging from 0 - 1. * @param bytesLoaded {Number} The number of bytes that have been loaded so far. * @param file {Kiwi.Files.File} The last file that has been loaded. * @private */ private onLoadProgress(percent: number, bytesLoaded: number, file: Kiwi.Files.File) { this.current.loadProgress(percent, bytesLoaded, file); } /** * Executed when the preloading has completed. Then executes the loadComplete and create methods of the new State. * @method onLoadComplete * @private */ private onLoadComplete() { this.current.loadComplete(); this._game.loader.onQueueProgress.remove(this.onLoadProgress, this); this._game.loader.onQueueComplete.remove(this.onLoadComplete, this); //Rebuild the Libraries again to have access the new files that were loaded. this.rebuildLibraries(); this.current.config.isReady = true; this.callCreate(); } /** * Rebuilds the texture, audio and data libraries that are on the current state. Thus updating what files the user has access to. * @method rebuildLibraries * @public */ public rebuildLibraries() { this.current.audioLibrary.rebuild(this._game.fileStore, this.current); this.current.dataLibrary.rebuild(this._game.fileStore, this.current); this.current.textureLibrary.rebuild(this._game.fileStore, this.current); if (this._game.renderOption == Kiwi.RENDERER_WEBGL) { this._game.renderer.initState(this.current); } } /** * The update loop that is accessible on the StateManager. * @method update * @public */ public update() { if (this.current !== null) { //Is the state ready? if (this.current.config.isReady === true) { this.current.preUpdate(); this.current.update(); this.current.postUpdate(); } else { this.current.loadUpdate(); } } //Do we need to switch states? if (this._newStateKey !== null) { this.bootNewState(); } } /** * PostRender - Called after all of the rendering has been executed in a frame. * @method postRender * @public */ public postRender() { if (this.current !== null) { if (this.current.config.isReady === true) { this.current.postRender(); } } } } }
the_stack
import * as DOMExtension from '../../core/dom_extension/dom_extension.js'; import * as Helpers from '../components/helpers/helpers.js'; import {Constraints, Size} from './Geometry.js'; import * as Utils from './utils/utils.js'; import {XWidget} from './XWidget.js'; export class WidgetElement extends HTMLDivElement { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention, rulesdir/no_underscored_properties __widget!: Widget|null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/naming-convention, rulesdir/no_underscored_properties __widgetCounter!: number|null; constructor() { super(); } } export class Widget { element!: WidgetElement; contentElement: HTMLDivElement; private shadowRoot: ShadowRoot|undefined; private readonly isWebComponent: boolean|undefined; protected visibleInternal: boolean; private isRoot: boolean; private isShowingInternal: boolean; private readonly childrenInternal: Widget[]; private hideOnDetach: boolean; private notificationDepth: number; private invalidationsSuspended: number; defaultFocusedChild: Widget|null; private parentWidgetInternal: Widget|null; private registeredCSSFiles: boolean; private defaultFocusedElement?: Element|null; private cachedConstraints?: Constraints; private constraintsInternal?: Constraints; private invalidationsRequested?: boolean; private externallyManaged?: boolean; constructor(isWebComponent?: boolean, delegatesFocus?: boolean) { this.contentElement = document.createElement('div'); this.contentElement.classList.add('widget'); if (isWebComponent) { this.element = (document.createElement('div') as WidgetElement); this.element.classList.add('vbox'); this.element.classList.add('flex-auto'); this.shadowRoot = Utils.createShadowRootWithCoreStyles(this.element, { cssFile: undefined, delegatesFocus, }); this.shadowRoot.appendChild(this.contentElement); } else { this.element = (this.contentElement as WidgetElement); } this.isWebComponent = isWebComponent; this.element.__widget = this; this.visibleInternal = false; this.isRoot = false; this.isShowingInternal = false; this.childrenInternal = []; this.hideOnDetach = false; this.notificationDepth = 0; this.invalidationsSuspended = 0; this.defaultFocusedChild = null; this.parentWidgetInternal = null; this.registeredCSSFiles = false; } private static incrementWidgetCounter(parentElement: WidgetElement, childElement: WidgetElement): void { const count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); if (!count) { return; } let currentElement: (WidgetElement|null)|WidgetElement = parentElement; while (currentElement) { currentElement.__widgetCounter = (currentElement.__widgetCounter || 0) + count; currentElement = parentWidgetElementOrShadowHost(currentElement); } } private static decrementWidgetCounter(parentElement: WidgetElement, childElement: WidgetElement): void { const count = (childElement.__widgetCounter || 0) + (childElement.__widget ? 1 : 0); if (!count) { return; } let currentElement: (WidgetElement|null)|WidgetElement = parentElement; while (currentElement) { if (currentElement.__widgetCounter) { currentElement.__widgetCounter -= count; } currentElement = parentWidgetElementOrShadowHost(currentElement); } } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/naming-convention private static assert(condition: any, message: string): void { if (!condition) { throw new Error(message); } } markAsRoot(): void { Widget.assert(!this.element.parentElement, 'Attempt to mark as root attached node'); this.isRoot = true; } parentWidget(): Widget|null { return this.parentWidgetInternal; } children(): Widget[] { return this.childrenInternal; } childWasDetached(_widget: Widget): void { } isShowing(): boolean { return this.isShowingInternal; } shouldHideOnDetach(): boolean { if (!this.element.parentElement) { return false; } if (this.hideOnDetach) { return true; } for (const child of this.childrenInternal) { if (child.shouldHideOnDetach()) { return true; } } return false; } setHideOnDetach(): void { this.hideOnDetach = true; } private inNotification(): boolean { return Boolean(this.notificationDepth) || Boolean(this.parentWidgetInternal && this.parentWidgetInternal.inNotification()); } private parentIsShowing(): boolean { if (this.isRoot) { return true; } return this.parentWidgetInternal !== null && this.parentWidgetInternal.isShowing(); } protected callOnVisibleChildren(method: (this: Widget) => void): void { const copy = this.childrenInternal.slice(); for (let i = 0; i < copy.length; ++i) { if (copy[i].parentWidgetInternal === this && copy[i].visibleInternal) { method.call(copy[i]); } } } private processWillShow(): void { this.callOnVisibleChildren(this.processWillShow); this.isShowingInternal = true; } private processWasShown(): void { if (this.inNotification()) { return; } this.restoreScrollPositions(); this.notify(this.wasShown); this.callOnVisibleChildren(this.processWasShown); } private processWillHide(): void { if (this.inNotification()) { return; } this.storeScrollPositions(); this.callOnVisibleChildren(this.processWillHide); this.notify(this.willHide); this.isShowingInternal = false; } private processWasHidden(): void { this.callOnVisibleChildren(this.processWasHidden); } private processOnResize(): void { if (this.inNotification()) { return; } if (!this.isShowing()) { return; } this.notify(this.onResize); this.callOnVisibleChildren(this.processOnResize); } private notify(notification: (this: Widget) => void): void { ++this.notificationDepth; try { notification.call(this); } finally { --this.notificationDepth; } } wasShown(): void { } willHide(): void { } onResize(): void { } onLayout(): void { } async ownerViewDisposed(): Promise<void> { } show(parentElement: Element, insertBefore?: Node|null): void { Widget.assert(parentElement, 'Attempt to attach widget with no parent element'); if (!this.isRoot) { // Update widget hierarchy. let currentParent: (WidgetElement|null) = (parentElement as WidgetElement | null); while (currentParent && !currentParent.__widget) { currentParent = parentWidgetElementOrShadowHost(currentParent); } if (!currentParent || !currentParent.__widget) { throw new Error('Attempt to attach widget to orphan node'); } this.attach(currentParent.__widget); } this.showWidgetInternal((parentElement as WidgetElement), insertBefore); } private attach(parentWidget: Widget): void { if (parentWidget === this.parentWidgetInternal) { return; } if (this.parentWidgetInternal) { this.detach(); } this.parentWidgetInternal = parentWidget; this.parentWidgetInternal.childrenInternal.push(this); this.isRoot = false; } showWidget(): void { if (this.visibleInternal) { return; } if (!this.element.parentElement) { throw new Error('Attempt to show widget that is not hidden using hideWidget().'); } this.showWidgetInternal((this.element.parentElement as WidgetElement), this.element.nextSibling); } private showWidgetInternal(parentElement: WidgetElement, insertBefore?: Node|null): void { let currentParent: (WidgetElement|null)|WidgetElement = parentElement; while (currentParent && !currentParent.__widget) { currentParent = parentWidgetElementOrShadowHost(currentParent); } if (this.isRoot) { Widget.assert(!currentParent, 'Attempt to show root widget under another widget'); } else { Widget.assert( currentParent && currentParent.__widget === this.parentWidgetInternal, 'Attempt to show under node belonging to alien widget'); } const wasVisible = this.visibleInternal; if (wasVisible && this.element.parentElement === parentElement) { return; } this.visibleInternal = true; if (!wasVisible && this.parentIsShowing()) { this.processWillShow(); } this.element.classList.remove('hidden'); // Reparent if (this.element.parentElement !== parentElement) { if (!this.externallyManaged) { Widget.incrementWidgetCounter(parentElement, this.element); } if (insertBefore) { DOMExtension.DOMExtension.originalInsertBefore.call(parentElement, this.element, insertBefore); } else { DOMExtension.DOMExtension.originalAppendChild.call(parentElement, this.element); } } if (!wasVisible && this.parentIsShowing()) { this.processWasShown(); } if (this.parentWidgetInternal && this.hasNonZeroConstraints()) { this.parentWidgetInternal.invalidateConstraints(); } else { this.processOnResize(); } } hideWidget(): void { if (!this.visibleInternal) { return; } this.hideWidgetInternal(false); } private hideWidgetInternal(removeFromDOM: boolean): void { this.visibleInternal = false; const parentElement = (this.element.parentElement as WidgetElement); if (this.parentIsShowing()) { this.processWillHide(); } if (removeFromDOM) { // Force legal removal Widget.decrementWidgetCounter(parentElement, this.element); DOMExtension.DOMExtension.originalRemoveChild.call(parentElement, this.element); } else { this.element.classList.add('hidden'); } if (this.parentIsShowing()) { this.processWasHidden(); } if (this.parentWidgetInternal && this.hasNonZeroConstraints()) { this.parentWidgetInternal.invalidateConstraints(); } } detach(overrideHideOnDetach?: boolean): void { if (!this.parentWidgetInternal && !this.isRoot) { return; } // hideOnDetach means that we should never remove element from dom - content // has iframes and detaching it will hurt. // // overrideHideOnDetach will override hideOnDetach and the client takes // responsibility for the consequences. const removeFromDOM = overrideHideOnDetach || !this.shouldHideOnDetach(); if (this.visibleInternal) { this.hideWidgetInternal(removeFromDOM); } else if (removeFromDOM && this.element.parentElement) { const parentElement = (this.element.parentElement as WidgetElement); // Force kick out from DOM. Widget.decrementWidgetCounter(parentElement, this.element); DOMExtension.DOMExtension.originalRemoveChild.call(parentElement, this.element); } // Update widget hierarchy. if (this.parentWidgetInternal) { const childIndex = this.parentWidgetInternal.childrenInternal.indexOf(this); Widget.assert(childIndex >= 0, 'Attempt to remove non-child widget'); this.parentWidgetInternal.childrenInternal.splice(childIndex, 1); if (this.parentWidgetInternal.defaultFocusedChild === this) { this.parentWidgetInternal.defaultFocusedChild = null; } this.parentWidgetInternal.childWasDetached(this); this.parentWidgetInternal = null; } else { Widget.assert(this.isRoot, 'Removing non-root widget from DOM'); } } detachChildWidgets(): void { const children = this.childrenInternal.slice(); for (let i = 0; i < children.length; ++i) { children[i].detach(); } } elementsToRestoreScrollPositionsFor(): Element[] { return [this.element]; } storeScrollPositions(): void { const elements = this.elementsToRestoreScrollPositionsFor(); for (const container of elements) { storedScrollPositions.set(container, {scrollLeft: container.scrollLeft, scrollTop: container.scrollTop}); } } restoreScrollPositions(): void { const elements = this.elementsToRestoreScrollPositionsFor(); for (const container of elements) { const storedPositions = storedScrollPositions.get(container); if (storedPositions) { container.scrollLeft = storedPositions.scrollLeft; container.scrollTop = storedPositions.scrollTop; } } } doResize(): void { if (!this.isShowing()) { return; } // No matter what notification we are in, dispatching onResize is not needed. if (!this.inNotification()) { this.callOnVisibleChildren(this.processOnResize); } } doLayout(): void { if (!this.isShowing()) { return; } this.notify(this.onLayout); this.doResize(); } registerRequiredCSS(cssFile: string): void { if (this.isWebComponent) { Utils.appendStyle((this.shadowRoot as DocumentFragment), cssFile); } else { Utils.appendStyle(this.element, cssFile); } } registerCSSFiles(cssFiles: CSSStyleSheet[]): void { let root: ShadowRoot|Document; if (this.isWebComponent && this.shadowRoot !== undefined) { root = this.shadowRoot; } else { root = Helpers.GetRootNode.getRootNode(this.contentElement); } root.adoptedStyleSheets = root.adoptedStyleSheets.concat(cssFiles); this.registeredCSSFiles = true; } printWidgetHierarchy(): void { const lines: string[] = []; this.collectWidgetHierarchy('', lines); console.log(lines.join('\n')); // eslint-disable-line no-console } private collectWidgetHierarchy(prefix: string, lines: string[]): void { lines.push(prefix + '[' + this.element.className + ']' + (this.childrenInternal.length ? ' {' : '')); for (let i = 0; i < this.childrenInternal.length; ++i) { this.childrenInternal[i].collectWidgetHierarchy(prefix + ' ', lines); } if (this.childrenInternal.length) { lines.push(prefix + '}'); } } setDefaultFocusedElement(element: Element|null): void { this.defaultFocusedElement = element; } setDefaultFocusedChild(child: Widget): void { Widget.assert(child.parentWidgetInternal === this, 'Attempt to set non-child widget as default focused.'); this.defaultFocusedChild = child; } focus(): void { if (!this.isShowing()) { return; } const element = (this.defaultFocusedElement as HTMLElement | null); if (element) { if (!element.hasFocus()) { element.focus(); } return; } if (this.defaultFocusedChild && this.defaultFocusedChild.visibleInternal) { this.defaultFocusedChild.focus(); } else { for (const child of this.childrenInternal) { if (child.visibleInternal) { child.focus(); return; } } let child = this.contentElement.traverseNextNode(this.contentElement); while (child) { if (child instanceof XWidget) { child.focus(); return; } child = child.traverseNextNode(this.contentElement); } } } hasFocus(): boolean { return this.element.hasFocus(); } calculateConstraints(): Constraints { return new Constraints(); } constraints(): Constraints { if (typeof this.constraintsInternal !== 'undefined') { return this.constraintsInternal; } if (typeof this.cachedConstraints === 'undefined') { this.cachedConstraints = this.calculateConstraints(); } return this.cachedConstraints; } setMinimumAndPreferredSizes(width: number, height: number, preferredWidth: number, preferredHeight: number): void { this.constraintsInternal = new Constraints(new Size(width, height), new Size(preferredWidth, preferredHeight)); this.invalidateConstraints(); } setMinimumSize(width: number, height: number): void { this.constraintsInternal = new Constraints(new Size(width, height)); this.invalidateConstraints(); } private hasNonZeroConstraints(): boolean { const constraints = this.constraints(); return Boolean( constraints.minimum.width || constraints.minimum.height || constraints.preferred.width || constraints.preferred.height); } suspendInvalidations(): void { ++this.invalidationsSuspended; } resumeInvalidations(): void { --this.invalidationsSuspended; if (!this.invalidationsSuspended && this.invalidationsRequested) { this.invalidateConstraints(); } } invalidateConstraints(): void { if (this.invalidationsSuspended) { this.invalidationsRequested = true; return; } this.invalidationsRequested = false; const cached = this.cachedConstraints; delete this.cachedConstraints; const actual = this.constraints(); if (!actual.isEqual(cached || null) && this.parentWidgetInternal) { this.parentWidgetInternal.invalidateConstraints(); } else { this.doLayout(); } } // Excludes the widget from being tracked by its parents/ancestors via // widgetCounter because the widget is being handled by external code. // Widgets marked as being externally managed are responsible for // finishing out their own lifecycle (i.e. calling detach() before being // removed from the DOM). This is e.g. used for CodeMirror. // // Also note that this must be called before the widget is shown so that // so that its ancestor's widgetCounter is not incremented. markAsExternallyManaged(): void { Widget.assert( !this.parentWidgetInternal, 'Attempt to mark widget as externally managed after insertion to the DOM'); this.externallyManaged = true; } } const storedScrollPositions = new WeakMap<Element, { scrollLeft: number, scrollTop: number, }>(); export class VBox extends Widget { constructor(isWebComponent?: boolean, delegatesFocus?: boolean) { super(isWebComponent, delegatesFocus); this.contentElement.classList.add('vbox'); } calculateConstraints(): Constraints { let constraints: Constraints = new Constraints(); function updateForChild(this: Widget): void { const child = this.constraints(); constraints = constraints.widthToMax(child); constraints = constraints.addHeight(child); } this.callOnVisibleChildren(updateForChild); return constraints; } } export class HBox extends Widget { constructor(isWebComponent?: boolean) { super(isWebComponent); this.contentElement.classList.add('hbox'); } calculateConstraints(): Constraints { let constraints: Constraints = new Constraints(); function updateForChild(this: Widget): void { const child = this.constraints(); constraints = constraints.addWidth(child); constraints = constraints.heightToMax(child); } this.callOnVisibleChildren(updateForChild); return constraints; } } export class VBoxWithResizeCallback extends VBox { private readonly resizeCallback: () => void; constructor(resizeCallback: () => void) { super(); this.resizeCallback = resizeCallback; } onResize(): void { this.resizeCallback(); } } export class WidgetFocusRestorer { private widget: Widget|null; private previous: HTMLElement|null; constructor(widget: Widget) { this.widget = widget; this.previous = (widget.element.ownerDocument.deepActiveElement() as HTMLElement | null); widget.focus(); } restore(): void { if (!this.widget) { return; } if (this.widget.hasFocus() && this.previous) { this.previous.focus(); } this.previous = null; this.widget = null; } } function parentWidgetElementOrShadowHost(element: WidgetElement): WidgetElement|null { return element.parentElementOrShadowHost() as WidgetElement | null; }
the_stack
import { CliCommand, CliExitData, cli, cliCommandToString, WatchProcess } from './cli'; import { TreeItemCollapsibleState, Terminal, workspace } from 'vscode'; import { WindowUtil } from './util/windowUtils'; import * as path from 'path'; import { ToolsConfig } from './tools'; import { TknPipelineResource, TknTask, PipelineRunData, TaskRunStatus, ConditionCheckStatus, PipelineTaskRunData } from './tekton'; import { kubectl } from './kubectl'; import { pipelineExplorer } from './pipeline/pipelineExplorer'; import { RunState } from './yaml-support/tkn-yaml'; import { getStderrString } from './util/stderrstring'; import { ContextType } from './context-type'; import { TektonNode, TektonNodeImpl } from './tree-view/tekton-node'; import { TaskRun } from './tree-view/task-run-node'; import { PipelineRun } from './tree-view/pipelinerun-node'; import { MoreNode } from './tree-view/expand-node'; import { Command } from './cli-command'; import { getPipelineList } from './util/list-tekton-resource'; import { telemetryLog, telemetryLogError } from './telemetry'; import { checkClusterStatus } from './util/check-cluster-status'; import { treeRefresh } from './util/watchResources'; const tektonResourceCount = {}; interface NameId { name: string; uid: string; } export function getPipelineRunTaskState(status: TaskRunStatus | ConditionCheckStatus): RunState { let result: RunState = 'Unknown'; if (!status) { return result; // default state } const startTime = status.startTime; if (startTime) { result = 'Started'; } const conditionStatus = status.conditions; if (conditionStatus) { const status = conditionStatus[0]?.status; if (status) { if (status === 'True') { result = 'Finished'; } else if (status === 'False') { const reason = conditionStatus[0]?.reason; if (reason === 'TaskRunCancelled') { result = 'Cancelled'; } else { result = 'Failed'; } } else if (status === 'Unknown') { result = 'Unknown'; } } } return result; } export interface Tkn { getPipelineNodes(): Promise<TektonNode[]>; restartPipeline(pipeline: TektonNode): Promise<void>; getPipelines(pipeline?: TektonNode): Promise<TektonNode[]>; getPipelineRuns(pipelineRun?: TektonNode): Promise<TektonNode[]>; getPipelineResources(pipelineResources?: TektonNode): Promise<TektonNode[]>; getTasks(task?: TektonNode): Promise<TektonNode[]>; getRawTasks(): Promise<TknTask[]>; getClusterTasks(clustertask?: TektonNode): Promise<TektonNode[]>; getRawClusterTasks(): Promise<TknTask[]>; execute(command: CliCommand, cwd?: string, fail?: boolean): Promise<CliExitData>; executeWatch(command: CliCommand, opts?: {}): WatchProcess; executeInTerminal(command: CliCommand, resourceName?: string, cwd?: string): void; getTaskRunsForTasks(task: TektonNode): Promise<TektonNode[]>; getTaskRunsForClusterTasks(task: TektonNode): Promise<TektonNode[]>; getTriggerTemplates(triggerTemplates?: TektonNode): Promise<TektonNode[]>; getTriggerBinding(triggerBinding?: TektonNode): Promise<TektonNode[]>; getClusterTriggerBinding(clusterTriggerBinding: TektonNode): Promise<TektonNode[]>; getEventListener(EventListener?: TektonNode): Promise<TektonNode[]>; getConditions(conditions?: TektonNode): Promise<TektonNode[]>; getPipelineRunsList(pipelineRun?: TektonNode): Promise<TektonNode[]>; getTaskRunList(taskRun?: TektonNode): Promise<TektonNode[]>; getRawPipelineRun(name: string): Promise<PipelineRunData | undefined>; getLatestPipelineRun(pipelineName: string): Promise<TektonNode[]> | undefined; clearCache?(): void; } function compareNodes(a, b): number { if (!a.contextValue) { return -1; } if (!b.contextValue) { return 1; } const t = a.contextValue.localeCompare(b.contextValue); return t ? t : a.label.localeCompare(b.label); } export function compareTimeNewestFirst(a: TektonNode, b: TektonNode): number { const aTime = Date.parse(a.creationTime); const bTime = Date.parse(b.creationTime); return aTime < bTime ? 1 : -1; } const nodeToRefresh = ['TaskRuns', 'ClusterTasks', 'Tasks']; export class TknImpl implements Tkn { public static ROOT: TektonNode = new TektonNodeImpl(undefined, 'root', undefined, undefined); // Get page size from configuration, in case configuration is not present(dev mode) use hard coded value defaultPageSize: number = workspace.getConfiguration('vs-tekton').has('treePaginationLimit') ? workspace.getConfiguration('vs-tekton').get('treePaginationLimit') : 5; async getPipelineNodes(): Promise<TektonNode[]> { const clusterInfo = await checkClusterStatus(); if (clusterInfo !== null) return clusterInfo; treeRefresh.set('treeRefresh', true); return this._getPipelineNodes(); } public _getPipelineNodes(): TektonNode[] { const pipelineTree: TektonNode[] = []; const pipelineNode = new TektonNodeImpl(TknImpl.ROOT, 'Pipelines', ContextType.PIPELINENODE, this, TreeItemCollapsibleState.Collapsed); const pipelineRunNode = new TektonNodeImpl(TknImpl.ROOT, 'PipelineRuns', ContextType.PIPELINERUNNODE, this, TreeItemCollapsibleState.Collapsed); const taskNode = new TektonNodeImpl(TknImpl.ROOT, 'Tasks', ContextType.TASKNODE, this, TreeItemCollapsibleState.Collapsed); const clustertaskNode = new TektonNodeImpl(TknImpl.ROOT, 'ClusterTasks', ContextType.CLUSTERTASKNODE, this, TreeItemCollapsibleState.Collapsed); const taskRunNode = new TektonNodeImpl(TknImpl.ROOT, 'TaskRuns', ContextType.TASKRUNNODE, this, TreeItemCollapsibleState.Collapsed); const pipelineResourceNode = new TektonNodeImpl(TknImpl.ROOT, 'PipelineResources', ContextType.PIPELINERESOURCENODE, this, TreeItemCollapsibleState.Collapsed); const triggerTemplatesNode = new TektonNodeImpl(TknImpl.ROOT, 'TriggerTemplates', ContextType.TRIGGERTEMPLATESNODE, this, TreeItemCollapsibleState.Collapsed); const triggerBindingNode = new TektonNodeImpl(TknImpl.ROOT, 'TriggerBinding', ContextType.TRIGGERBINDINGNODE, this, TreeItemCollapsibleState.Collapsed); const eventListenerNode = new TektonNodeImpl(TknImpl.ROOT, 'EventListener', ContextType.EVENTLISTENERNODE, this, TreeItemCollapsibleState.Collapsed); const clusterTriggerBindingNode = new TektonNodeImpl(TknImpl.ROOT, 'ClusterTriggerBinding', ContextType.CLUSTERTRIGGERBINDINGNODE, this, TreeItemCollapsibleState.Collapsed); const conditionsNode = new TektonNodeImpl(TknImpl.ROOT, 'Conditions', ContextType.CONDITIONSNODE, this, TreeItemCollapsibleState.Collapsed); pipelineTree.push(pipelineNode, pipelineRunNode, taskNode, clustertaskNode, taskRunNode, pipelineResourceNode, triggerTemplatesNode, triggerBindingNode, eventListenerNode, conditionsNode, clusterTriggerBindingNode); TknImpl.ROOT.getChildren = () => pipelineTree; // TODO: fix me return pipelineTree; } async refreshPipelineRun(tknResource: TektonNode, resourceName: string): Promise<void> { await kubectl.watchRunCommand(Command.watchResources(resourceName, tknResource.getName()), () => { if (tknResource.contextValue === 'pipelinerun') { pipelineExplorer.refresh(tknResource); for (const item of TknImpl.ROOT.getChildren() as TektonNodeImpl[]) { if (nodeToRefresh.includes(item.getName())) { pipelineExplorer.refresh(item); } } } }); (tknResource.contextValue === 'taskrun') ? pipelineExplorer.refresh(tknResource.getParent()) : pipelineExplorer.refresh(); // refresh all tree } async getPipelineStatus(listOfResources: TektonNode[]): Promise<void> { for (const tknResource of listOfResources) { if (tknResource.state === 'Unknown') { this.refreshPipelineRun(tknResource, tknResource.contextValue); } } } async limitView(context: TektonNode, tektonNode: TektonNode[]): Promise<TektonNode[]> { if (!context) return tektonNode; const currentRuns = tektonNode.slice(0, Math.min(context.visibleChildren, tektonNode.length)) if (context.visibleChildren < tektonNode.length) { let nextPage = this.defaultPageSize; if (context.visibleChildren + this.defaultPageSize > tektonNode.length) { nextPage = tektonNode.length - context.visibleChildren; } currentRuns.push(new MoreNode(nextPage, tektonNode.length, context)); } return currentRuns; } async getPipelineRunsList(pipelineRun: TektonNode): Promise<TektonNode[]> { if (pipelineRun && !pipelineRun.visibleChildren) { pipelineRun.visibleChildren = this.defaultPageSize; } const pipelineRunList = await this._getPipelineRunsList(pipelineRun); return this.limitView(pipelineRun, pipelineRunList); } async _getPipelineRunsList(pipelineRun: TektonNode): Promise<TektonNode[]> | undefined { const result = await this.execute(Command.listPipelineRun()); if (result.error) { console.log(result + ' Std.err when processing pipelines'); return [new TektonNodeImpl(pipelineRun, getStderrString(result.error), ContextType.PIPELINERUNNODE, this, TreeItemCollapsibleState.None)]; } let data: PipelineRunData[] = []; try { const r = JSON.parse(result.stdout); data = r.items ? r.items : data; // eslint-disable-next-line no-empty } catch (ignore) { } if (tektonResourceCount['pipelineRun'] !== data.length) { telemetryLog('tekton.list.pipelineRun', `Total number of pipelineRun: ${data.length}`); tektonResourceCount['pipelineRun'] = data.length } return data.map((value) => new PipelineRun(pipelineRun, value.metadata.name, this, value, TreeItemCollapsibleState.None)).sort(compareTimeNewestFirst); } async getPipelineRuns(pipeline: TektonNode): Promise<TektonNode[]> { if (!pipeline.visibleChildren) { pipeline.visibleChildren = this.defaultPageSize; } const pipelineRuns = await this._getPipelineRuns(pipeline); this.getPipelineStatus(pipelineRuns); return this.limitView(pipeline, pipelineRuns); } async getLatestPipelineRun(pipelineName: string): Promise<TektonNode[]> { return await this._getPipelineRuns(null, pipelineName); } async _getPipelineRuns(pipeline: TektonNode, pipelineName?: string): Promise<TektonNode[]> | undefined { const result = await this.execute(Command.listPipelineRuns(pipelineName ?? pipeline.getName())); if (result.error) { console.log(result + ' Std.err when processing pipelines'); if (!pipelineName) return [new TektonNodeImpl(pipeline, getStderrString(result.error), ContextType.PIPELINERUN, this, TreeItemCollapsibleState.None)]; } let data: PipelineRunData[] = []; try { const r = JSON.parse(result.stdout); data = r.items ? r.items : data; // eslint-disable-next-line no-empty } catch (ignore) { } return data .map((value) => new PipelineRun(pipeline, value.metadata.name, this, value, TreeItemCollapsibleState.Collapsed)) .sort(compareTimeNewestFirst); } async getTaskRunsForTasks(task: TektonNode): Promise<TektonNode[]> { if (!task.visibleChildren) { task.visibleChildren = this.defaultPageSize; } const taskRun = await this._getTaskRunsForTasks(task); this.getPipelineStatus(taskRun); return this.limitView(task, taskRun); } async _getTaskRunsForTasks(task: TektonNode): Promise<TektonNode[]> { const result = await this.execute(Command.listTaskRunsForTasks(task.getName())); if (result.error) { console.log(result + ' Std.err when processing taskruns for ' + task.getName()); return [new TektonNodeImpl(task, getStderrString(result.error), ContextType.TASKRUN, this, TreeItemCollapsibleState.None)]; } return this.getSupportedTaskRunTreeView(result, task); } async getTaskRunsForClusterTasks(clusterTask: TektonNode): Promise<TektonNode[]> { if (!clusterTask.visibleChildren) { clusterTask.visibleChildren = this.defaultPageSize; } const taskRun = await this._getTaskRunsForClusterTasks(clusterTask); this.getPipelineStatus(taskRun); return this.limitView(clusterTask, taskRun); } async _getTaskRunsForClusterTasks(clusterTask: TektonNode): Promise<TektonNode[]> { const result = await this.execute(Command.listTaskRunsForClusterTasks(clusterTask.getName())); if (result.error) { console.log(result + ' Std.err when processing taskruns for ' + clusterTask.getName()); return [new TektonNodeImpl(clusterTask, getStderrString(result.error), ContextType.TASKRUN, this, TreeItemCollapsibleState.None)]; } return this.getSupportedTaskRunTreeView(result, clusterTask); } async getSupportedTaskRunTreeView(result: CliExitData, taskRef: TektonNode): Promise<TektonNode[]> { let data: PipelineTaskRunData[] = []; try { data = JSON.parse(result.stdout).items; // eslint-disable-next-line no-empty } catch (ignore) { } return data .map((value) => new TaskRun(taskRef, value.metadata.name, this, value)) .sort(compareTimeNewestFirst); } async getTaskRunList(taskRun: TektonNode): Promise<TektonNode[]> { if (taskRun && !taskRun.visibleChildren) { taskRun.visibleChildren = this.defaultPageSize; } const taskRunList = await this._getTaskRunList(taskRun); return this.limitView(taskRun, taskRunList); } async _getTaskRunList(taskRun: TektonNode): Promise<TektonNode[]> | undefined { const result = await this.execute(Command.listTaskRun()); if (result.error) { return [new TektonNodeImpl(taskRun, getStderrString(result.error), ContextType.TASKRUNNODE, this, TreeItemCollapsibleState.None)]; } let data: PipelineTaskRunData[] = []; try { const r = JSON.parse(result.stdout); data = r.items ? r.items : data; // eslint-disable-next-line no-empty } catch (ignore) { } if (tektonResourceCount['taskRun'] !== data.length) { telemetryLog('tekton.list.taskRun', `Total number of taskRun: ${data.length}`); tektonResourceCount['taskRun'] = data.length } return data.map((value) => new TaskRun(taskRun, value.metadata.name, this, value)).sort(compareTimeNewestFirst); } async getPipelines(pipeline: TektonNode): Promise<TektonNode[]> { return this._getPipelines(pipeline); } async _getPipelines(pipeline: TektonNode): Promise<TektonNode[]> { const pipelineList = await getPipelineList(); let pipelines: NameId[] = pipelineList.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); pipelines = [...new Set(pipelines)]; if (tektonResourceCount['pipeline'] !== pipelineList.length) { telemetryLog('tekton.list.pipeline', `Total number of Pipeline: ${pipelineList.length}`); tektonResourceCount['pipeline'] = pipelineList.length } return pipelines.map<TektonNode>((value) => new TektonNodeImpl(pipeline, value.name, ContextType.PIPELINE, this, TreeItemCollapsibleState.Collapsed, value.uid)).sort(compareNodes); } async getPipelineResources(pipelineResources: TektonNode): Promise<TektonNode[]> { return this._getPipelineResources(pipelineResources); } private async _getPipelineResources(pipelineResource: TektonNode): Promise<TektonNode[]> { let data: TknPipelineResource[] = []; const result = await this.execute(Command.listPipelineResources(), process.cwd(), false); if (result.error) { console.log(result + ' Std.err when processing pipelines'); return [new TektonNodeImpl(pipelineResource, getStderrString(result.error), ContextType.PIPELINERESOURCE, this, TreeItemCollapsibleState.Expanded)]; } try { data = JSON.parse(result.stdout).items; } catch (ignore) { //show no pipelines if output is not correct json } const pipelineResources: NameId[] = data.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); if (tektonResourceCount['pipelineResource'] !== pipelineResources.length) { telemetryLog('tekton.list.pipelineresource', `Total number of PipelineResource: ${pipelineResources.length}`); tektonResourceCount['pipelineResource'] = pipelineResources.length; } return pipelineResources.map<TektonNode>((value) => new TektonNodeImpl(pipelineResource, value.name, ContextType.PIPELINERESOURCE, this, TreeItemCollapsibleState.None, value.uid)).sort(compareNodes); } async getConditions(conditionsNode: TektonNode): Promise<TektonNode[]> { return this._getConditions(conditionsNode, Command.listConditions(), ContextType.CONDITIONS); } private async _getConditions(conditionResource: TektonNode, command: CliCommand, conditionContextType: ContextType): Promise<TektonNode[]> { let data: TknPipelineResource[] = []; const result = await this.execute(command, process.cwd(), false); if (result.error) { return [new TektonNodeImpl(conditionResource, getStderrString(result.error), conditionContextType, this, TreeItemCollapsibleState.Expanded)]; } try { data = JSON.parse(result.stdout).items; } catch (ignore) { //show no pipelines if output is not correct json } let condition: NameId[] = data.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); if (tektonResourceCount['condition'] !== condition.length) { telemetryLog('tekton.list.condition', `Total number of Condition: ${condition.length}`); tektonResourceCount['condition'] = condition.length; } condition = [...new Set(condition)]; return condition.map<TektonNode>((value) => new TektonNodeImpl(conditionResource, value.name, conditionContextType, this, TreeItemCollapsibleState.None, value.uid)).sort(compareNodes); } async getTriggerTemplates(triggerTemplatesNode: TektonNode): Promise<TektonNode[]> { return this._getTriggerResource(triggerTemplatesNode, Command.listTriggerTemplates(), ContextType.TRIGGERTEMPLATES, 'TriggerTemplates'); } async getTriggerBinding(triggerBindingNode: TektonNode): Promise<TektonNode[]> { return this._getTriggerResource(triggerBindingNode, Command.listTriggerBinding(), ContextType.TRIGGERBINDING, 'TriggerBinding'); } async getEventListener(eventListenerNode: TektonNode): Promise<TektonNode[]> { return this._getTriggerResource(eventListenerNode, Command.listEventListener(), ContextType.EVENTLISTENER, 'EventListener'); } async getClusterTriggerBinding(clusterTriggerBindingNode: TektonNode): Promise<TektonNode[]> { return this._getTriggerResource(clusterTriggerBindingNode, Command.listClusterTriggerBinding(), ContextType.CLUSTERTRIGGERBINDING, 'ClusterTriggerBinding'); } private async _getTriggerResource(trigerResource: TektonNode, command: CliCommand, triggerContextType: ContextType, triggerType: string): Promise<TektonNode[]> { let data: TknPipelineResource[] = []; const result = await this.execute(command, process.cwd(), false); const triggerCheck = RegExp('undefinederror: the server doesn\'t have a resource type'); if (triggerCheck.test(getStderrString(result.error))) { telemetryLogError(`tekton.list.${triggerType}`, result.error); return; } try { data = JSON.parse(result.stdout).items; } catch (ignore) { //show no pipelines if output is not correct json } let trigger: NameId[] = data.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); trigger = [...new Set(trigger)]; if (tektonResourceCount[triggerType] !== trigger.length) { telemetryLog(`tekton.list.${triggerType}`, `Total number of ${triggerType}: ${trigger.length}`); tektonResourceCount[triggerType] = trigger.length; } return trigger.map<TektonNode>((value) => new TektonNodeImpl(trigerResource, value.name, triggerContextType, this, TreeItemCollapsibleState.None, value.uid)).sort(compareNodes); } public async getTasks(task: TektonNode): Promise<TektonNode[]> { return this._getTasks(task); } async _getTasks(task: TektonNode): Promise<TektonNode[]> { let data: TknTask[] = []; const result = await this.execute(Command.listTasks()); if (result.error) { telemetryLogError('tekton.list.task', result.error); console.log(result + 'Std.err when processing tasks'); return [new TektonNodeImpl(task, getStderrString(result.error), ContextType.TASK, this, TreeItemCollapsibleState.Expanded)]; } try { data = JSON.parse(result.stdout).items; // eslint-disable-next-line no-empty } catch (ignore) { } let tasks: NameId[] = data.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); if (tektonResourceCount['task'] !== tasks.length) { telemetryLog('tekton.list.task', `Total number of Task: ${tasks.length}`); tektonResourceCount['task'] = tasks.length; } tasks = [...new Set(tasks)]; return tasks.map<TektonNode>((value) => new TektonNodeImpl(task, value.name, ContextType.TASK, this, TreeItemCollapsibleState.Collapsed, value.uid)).sort(compareNodes); } async getRawTasks(): Promise<TknTask[]> { let data: TknTask[] = []; const result = await this.execute(Command.listTasks()); if (result.error) { console.error(result + 'Std.err when processing tasks'); return data; } try { data = JSON.parse(result.stdout).items; // eslint-disable-next-line no-empty } catch (ignore) { } return data; } async getRawPipelineRun(name: string): Promise<PipelineRunData | undefined> { const result = await this.execute(Command.getPipelineRun(name)); let data: PipelineRunData; if (result.error) { console.error(result + 'Std.err when processing tasks'); return undefined; } try { data = JSON.parse(result.stdout); // eslint-disable-next-line no-empty } catch (ignore) { } return data; } async getClusterTasks(clustertask: TektonNode): Promise<TektonNode[]> { return this._getClusterTasks(clustertask); } async _getClusterTasks(clustertask: TektonNode): Promise<TektonNode[]> { let data: TknTask[] = []; try { const result = await this.execute(Command.listClusterTasks()); data = JSON.parse(result.stdout).items; // eslint-disable-next-line no-empty } catch (ignore) { } let tasks: NameId[] = data.map((value) => { return { name: value.metadata.name, uid: value.metadata.uid } }); if (tektonResourceCount['ClusterTask'] !== tasks.length) { telemetryLog('tekton.list.clusterTask', `Total number of ClusterTask: ${tasks.length}`); tektonResourceCount['ClusterTask'] = tasks.length; } tasks = [...new Set(tasks)]; return tasks.map<TektonNode>((value) => new TektonNodeImpl(clustertask, value.name, ContextType.CLUSTERTASK, this, TreeItemCollapsibleState.Collapsed, value.uid)).sort(compareNodes); } async getRawClusterTasks(): Promise<TknTask[]> { let data: TknTask[] = []; const result = await this.execute(Command.listClusterTasks()); if (result.error) { console.log(result + 'Std.err when processing tasks'); return data; } try { data = JSON.parse(result.stdout).items; // eslint-disable-next-line no-empty } catch (ignore) { } return data; } async restartPipeline(pipeline: TektonNode): Promise<void> { await this.executeInTerminal(Command.restartPipeline(pipeline.getName())); } async getRawTask(name: string, type: 'Task' | 'ClusterTask' = 'Task'): Promise<TknTask | undefined> { let data: TknTask; const result = await this.execute(Command.getTask(name, type === 'Task' ? 'task.tekton' : 'clustertask')); if (result.error) { console.log(result + 'Std.err when processing tasks'); return data; } try { data = JSON.parse(result.stdout); // eslint-disable-next-line no-empty } catch (ignore) { } return data; } async executeInTerminal(command: CliCommand, resourceName?: string, cwd: string = process.cwd(), name = 'Tekton'): Promise<void> { let toolLocation = await ToolsConfig.detectOrDownload(command.cliCommand); if (toolLocation) { toolLocation = path.dirname(toolLocation); } let terminal: Terminal; if (resourceName) { terminal = WindowUtil.createTerminal(`${name}:${resourceName}`, cwd, toolLocation); } else { terminal = WindowUtil.createTerminal(name, cwd, toolLocation); } terminal.sendText(cliCommandToString(command), true); terminal.show(); } async execute(command: CliCommand, cwd?: string, fail = true): Promise<CliExitData> { if (command.cliCommand.indexOf('tkn') >= 0) { const toolLocation = ToolsConfig.getTknLocation('tkn'); if (toolLocation) { // eslint-disable-next-line require-atomic-updates command.cliCommand = command.cliCommand.replace('tkn', `"${toolLocation}"`).replace(new RegExp('&& tkn', 'g'), `&& "${toolLocation}"`); } } else { const toolLocation = await ToolsConfig.detectOrDownload(command.cliCommand); if (toolLocation) { // eslint-disable-next-line require-atomic-updates command.cliCommand = command.cliCommand.replace(command.cliCommand, `"${toolLocation}"`).replace(new RegExp(`&& ${command.cliCommand}`, 'g'), `&& "${toolLocation}"`); } } return cli.execute(command, cwd ? { cwd } : {}) .then(async (result) => result.error && fail ? Promise.reject(result.error) : result) .catch((err) => fail ? Promise.reject(err) : Promise.resolve({ error: null, stdout: '', stderr: '' })); } executeWatch(command: CliCommand, cwd?: string): WatchProcess { const toolLocation = ToolsConfig.getTknLocation(command.cliCommand); if (toolLocation) { // eslint-disable-next-line require-atomic-updates command.cliCommand = command.cliCommand.replace(command.cliCommand, `"${toolLocation}"`).replace(new RegExp(`&& ${command.cliCommand}`, 'g'), `&& "${toolLocation}"`); } return cli.executeWatch(command, cwd ? { cwd } : {}); } } export const tkn = new TknImpl();
the_stack
import vscode = require('vscode'); var fs = require('fs'); var path = require('path'); var os = require('os'); import child_process = require('child_process'); import { getConfigDir } from "../../Common" // import { StatisticsMain,StatisticsEvent } from "../../luatool/statistics/StatisticsMain" import { UserInfo } from "../ex/UserInfo" import { ConstInfo } from "../../ConstInfo"; import { UserLoginCount } from "../UserLoginCount"; export class LuaIdeConfigManager { private macroConfig: Map<string, string>; //模板文件夹路径 public luaTemplatesDir: string; public luaOperatorCheck: boolean; public luaFunArgCheck: boolean; public extensionPath: string; public maxFileSize: number; private userInfo: UserInfo; private isShowDest: boolean; public changeTextCheck: boolean; public moduleFunNestingCheck: boolean; public requireFunNames:Array<string>; // private statisticsMain:StatisticsMain; public scriptRoots: Array<string>; public showOnLine:boolean; public isInit :boolean = false constructor() { this.requireFunNames = new Array<string>(); this.requireFunNames.push("require") this.requireFunNames.push("import") this.extensionPath = vscode.extensions.getExtension(ConstInfo.extensionConfig).extensionPath try{ this.configInit(); this.copyConfig(); this.readUserInfo(); // this.statisticsMain = new StatisticsMain(this.userInfo) this.showRecharge(); this.showIndex(); this.isInit= true; }catch(err){ vscode.window.showInformationMessage(ConstInfo.extensionName + "启动失败,请检查"+err.path +"的写入权限"); console.log(err) } } public showIndex() { if (this.userInfo.showIndex == 0 || this.isShowDest) { var extensionPath = path.join(this.extensionPath, "images", "index.html") var previewUri = vscode.Uri.file(extensionPath); // var previewUri = vscode.Uri.parse("www.baidu.com") vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.Three, "LuaIde介绍").then(value => { }) this.userInfo.showIndex = 1 this.writeUserInfo(); } } public configInit() { var luaideConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("luaide") var macroListConfig: Array<any> = luaideConfig.get<Array<any>>("macroList"); this.luaOperatorCheck = luaideConfig.get<boolean>("luaOperatorCheck") this.luaFunArgCheck = luaideConfig.get<boolean>("luaFunArgCheck") this.isShowDest = luaideConfig.get<boolean>("isShowDest") this.changeTextCheck = luaideConfig.get<boolean>("changeTextCheck") this.moduleFunNestingCheck = luaideConfig.get<boolean>("moduleFunNestingCheck") this.maxFileSize = luaideConfig.get<number>("maxFileSize") this.showOnLine = luaideConfig.get<boolean>("showOnLine"); var scriptRoots: Array<string> = luaideConfig.get<Array<string>>("scriptRoots"); this.scriptRoots = new Array<string>(); scriptRoots.forEach(rootpath => { var scriptRoot = rootpath.replace(/\\/g, "/"); scriptRoot = scriptRoot.replace(new RegExp("/", "gm"), ".") scriptRoot = scriptRoot.toLowerCase(); this.scriptRoots.push(scriptRoot) }) if(this.scriptRoots.length == 0){ vscode.window.showInformationMessage("请在 文件->首选项->设置->工作区设置 添加 luaide.scriptRoots 的配置,否则无法获得最好的提示代码联想效果!",{ title: "配置项文档", isCloseAffordance: true, id: 1 }).then(value => { if (value != null && value.id == 1) { var previewUri = vscode.Uri.parse("http://www.jianshu.com/p/f850e5276977#") vscode.commands.executeCommand('vscode.open', previewUri) } }) } this.isShowDest == this.isShowDest == null ? false : this.isShowDest if (this.luaOperatorCheck == null) { this.luaOperatorCheck = true; } if (this.luaFunArgCheck == null) { this.luaFunArgCheck = true } if(this.showOnLine){ new UserLoginCount(); } this.macroConfig = new Map<string, string>(); if (macroListConfig != null) { macroListConfig.forEach(element => { this.macroConfig.set(element.name, element.value) }); //console.log(this.macroConfig) } var luaTemplatesDir: string = luaideConfig.get<string>("luaTemplatesDir") if (luaTemplatesDir) { this.luaTemplatesDir = luaTemplatesDir; } else { this.luaTemplatesDir = null; } } public readUserInfo() { var userPath = getConfigDir() if (!fs.existsSync(userPath)) { fs.mkdirSync(userPath, '0755'); } var userInfoPath = path.join(userPath, "userInfo") if (fs.existsSync(userInfoPath)) { var contentText = fs.readFileSync(path.join(userInfoPath), 'utf-8'); this.userInfo = new UserInfo(JSON.parse(contentText)) } else { this.userInfo = new UserInfo(null); this.writeUserInfo(); } } public writeUserInfo() { var userPath = getConfigDir() if (!fs.existsSync(userPath)) { fs.mkdirSync(userPath, '0755'); } var userInfoPath = path.join(userPath, "userInfo") fs.writeFileSync(userInfoPath, this.userInfo.toString()); } public showRecharge() { var date: Date = new Date(); var day = date.getDate(); if ( (day >= 11 && day <= 13) || (day >= 25 && day <= 27) ) { var extensionPath = this.extensionPath if (date.getMonth() + "" == this.userInfo.donateShowMonth) { if (day >= 11 && day <= 13 && this.userInfo.donateInfo[0] ) { return } else if (day >= 25 && day <= 27 && this.userInfo.donateInfo[1] ) { return } } this.userInfo.donateShowMonth = date.getMonth() + "" if (day >= 11 && day <= 13){ this.userInfo.donateInfo[0] = true }else if(day >= 25 && day <= 27) { this.userInfo.donateInfo[1] = true } this.writeUserInfo(); vscode.window.showInformationMessage("您愿意为luaIde捐献吗?", true, { title: "支持一个", isCloseAffordance: true, id: 1 }, { title: "用用再说", isCloseAffordance: true, id: 2 }).then(value => { if (value != null && value.id == 1) { var extensionPath = this.extensionPath extensionPath = path.join(extensionPath, "images", "donate.html") var previewUri = vscode.Uri.file(extensionPath); vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.One, "谢谢您的支持").then(value => { // this.statisticsMain.sendMsg(StatisticsEvent.C2S_OpenRechrage) }) } }) } } public replaceConfigValue(text: string, moduleName: string) { if (moduleName) { text = text.replace(new RegExp("{moduleName}", "gm"), moduleName) } var date: Date = new Date(); var dateStr: string = this.datepattern(date, "yyyy-MM-dd hh:mm:ss") text = text.replace(new RegExp("{time}", "gm"), dateStr) this.macroConfig.forEach((v, k) => { text = text.replace(new RegExp("{" + k + "}", "gm"), v) }) return text; } /** * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 */ public datepattern(date: Date, fmt) { var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时 "H+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; var week = { "0": "/u65e5", "1": "/u4e00", "2": "/u4e8c", "3": "/u4e09", "4": "/u56db", "5": "/u4e94", "6": "/u516d" }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); } } return fmt; } private copyConfig() { //这里只生成一些配置信息放入文件夹用于debug 调试时获取 //获取插件的路径 var extensionPath = this.extensionPath var userPath = getConfigDir() userPath = userPath.replace(/\\/g, "/"); if (!fs.existsSync(userPath)) { fs.mkdirSync(userPath, '0755'); } var configFile = path.join(userPath, "luaideConfig") if (!fs.existsSync(configFile)) { fs.writeFileSync(configFile, extensionPath); } else { var contentText = fs.readFileSync(path.join(configFile), 'utf-8'); if (contentText != extensionPath) { fs.writeFileSync(configFile, extensionPath); } } } }
the_stack
import { tsquery } from "@phenomnomnominal/tsquery"; import * as Lint from "tslint"; import * as tsutils from "tsutils"; import * as ts from "typescript"; import * as peer from "../support/peer"; import { couldBeType, isThis } from "../support/util"; type Options = { alias: string[]; checkDestroy: boolean; checkDecorators: string[]; }; export class Rule extends Lint.Rules.TypedRule { public static metadata: Lint.IRuleMetadata = { deprecationMessage: peer.v5 ? peer.v5NotSupportedMessage : undefined, description: Lint.Utils.dedent` Enforces the application of the takeUntil operator when calling subscribe within Angular components (and, optionally, within services, directives, and pipes).`, options: { properties: { alias: { type: "array", items: { type: "string" } }, checkDecorators: { type: "array", items: { type: "string" } }, checkDestroy: { type: "boolean" }, }, type: "object", }, optionsDescription: Lint.Utils.dedent` An optional object with optional \`alias\`, \`checkDecorators\` and \`checkDestroy\` properties. The \`alias\` property is an array containing the names of operators that aliases for \`takeUntil\`. The \`checkDecorators\` property is an array containing the names of the decorators that determine whether or not a class is checked. The \`checkDestroy\` property is a boolean that determines whether or not a \`Subject\`-based \`ngOnDestroy\` must be implemented.`, requiresTypeInfo: true, ruleName: "rxjs-prefer-angular-takeuntil", type: "functionality", typescriptOnly: true, }; public static FAILURE_STRING_NO_TAKEUNTIL = "Subscribing without takeUntil is forbidden"; public static FAILURE_STRING_NO_DESTROY = "ngOnDestroy not implemented"; /*tslint:disable:semicolon*/ public static FAILURE_MESSAGE_NOT_CALLED = (name: string, method: string) => `'${name}.${method}()' not called`; public static FAILURE_MESSAGE_NOT_DECLARED = (name: string) => `Subject '${name}' not a class property`; /*tslint:enable:semicolon*/ public applyWithProgram( sourceFile: ts.SourceFile, program: ts.Program ): Lint.RuleFailure[] { const failures: Lint.RuleFailure[] = []; const { ruleArguments: [options], } = this.getOptions(); // If an alias is specified, check for the subject-based destroy only if // it's explicitly configured. It's extremely unlikely a subject-based // destroy mechanism will be used in conjunction with an alias. const { alias = [], checkDestroy = alias.length === 0, checkDecorators = ["Component"], }: Options = options || {}; // find all classes with given decorators const decoratorQuery = `/^(${checkDecorators.join("|")})$/`; const classDeclarations = tsquery( sourceFile, `ClassDeclaration:has(Decorator[expression.expression.name=${decoratorQuery}])` ) as ts.ClassDeclaration[]; classDeclarations.forEach((classDeclaration) => { failures.push( ...this.checkClassDeclaration( sourceFile, program, { alias, checkDestroy, checkDecorators }, classDeclaration ) ); }); return failures; } /** * Checks a class for occurrences of .subscribe() and corresponding takeUntil() requirements */ private checkClassDeclaration( sourceFile: ts.SourceFile, program: ts.Program, options: Options, classDeclaration: ts.ClassDeclaration ): Lint.RuleFailure[] { const failures: Lint.RuleFailure[] = []; const typeChecker = program.getTypeChecker(); const destroySubjectNamesBySubscribes = new Map< ts.Identifier | ts.PrivateIdentifier, Set<string> >(); // find observable.subscribe() call expressions const subscribePropertyAccessExpressions = tsquery( classDeclaration, `CallExpression > PropertyAccessExpression[name.name="subscribe"]` ) as ts.PropertyAccessExpression[]; // check whether it is an observable and check the takeUntil is applied subscribePropertyAccessExpressions.forEach((propertyAccessExpression) => { const type = typeChecker.getTypeAtLocation( propertyAccessExpression.expression ); if (couldBeType(type, "Observable")) { failures.push( ...this.checkSubscribe( sourceFile, options, propertyAccessExpression, (name) => { let names = destroySubjectNamesBySubscribes.get( propertyAccessExpression.name ); if (!names) { names = new Set<string>(); destroySubjectNamesBySubscribes.set( propertyAccessExpression.name, names ); } names.add(name); } ) ); } }); // check the ngOnDestroyMethod if (options.checkDestroy && destroySubjectNamesBySubscribes.size > 0) { failures.push( ...this.checkNgOnDestroy( sourceFile, classDeclaration, destroySubjectNamesBySubscribes ) ); } return failures; } /** * Checks whether a .subscribe() is preceded by a .pipe(<...>, takeUntil(<...>)) */ private checkSubscribe( sourceFile: ts.SourceFile, options: Options, subscribe: ts.PropertyAccessExpression, addDestroySubjectName: (name: string) => void ): Lint.RuleFailure[] { const failures: Lint.RuleFailure[] = []; const subscribeContext = subscribe.expression; let takeUntilFound = false; // check whether subscribeContext.expression is <something>.pipe() if ( tsutils.isCallExpression(subscribeContext) && tsutils.isPropertyAccessExpression(subscribeContext.expression) && subscribeContext.expression.name.text === "pipe" ) { const pipedOperators = subscribeContext.arguments; pipedOperators.forEach((pipedOperator) => { if (tsutils.isCallExpression(pipedOperator)) { const { found, name } = this.checkOperator(options, pipedOperator); takeUntilFound = takeUntilFound || found; if (name) { addDestroySubjectName(name); } } }); } // add failure if there is no takeUntil() in the .pipe() if (!takeUntilFound) { failures.push( new Lint.RuleFailure( sourceFile, subscribe.name.getStart(), subscribe.name.getStart() + subscribe.name.getWidth(), Rule.FAILURE_STRING_NO_TAKEUNTIL, this.ruleName ) ); } return failures; } /** * Checks whether the operator given is takeUntil and uses an expected destroy subject name */ private checkOperator( options: Options, operator: ts.CallExpression ): { found: boolean; name?: string; } { if (!tsutils.isIdentifier(operator.expression)) { return { found: false }; } if ( operator.expression.text === "takeUntil" || options.alias.includes(operator.expression.text) ) { const [arg] = operator.arguments; if (arg) { if (ts.isPropertyAccessExpression(arg) && isThis(arg.expression)) { return { found: true, name: arg.name.text }; } else if (arg && ts.isIdentifier(arg)) { return { found: true, name: arg.text }; } } if (!options.checkDestroy) { return { found: true }; } } return { found: false }; } /** * Checks whether the class implements an ngOnDestroy method and invokes .next() and .complete() on the destroy subjects */ private checkNgOnDestroy( sourceFile: ts.SourceFile, classDeclaration: ts.ClassDeclaration, destroySubjectNamesBySubscribes: Map< ts.Identifier | ts.PrivateIdentifier, Set<string> > ): Lint.RuleFailure[] { const failures: Lint.RuleFailure[] = []; const ngOnDestroyMethod = classDeclaration.members.find( (member) => member.name && member.name.getText() === "ngOnDestroy" ); // check whether the ngOnDestroy method is implemented // and contains invocations of .next() and .complete() on destroy subjects if (ngOnDestroyMethod) { // If a subscription to a .pipe() has at least one takeUntil that has no // failures, the subscribe call is fine. Callers should be able to use // secondary takUntil operators. However, there must be at least one // takeUntil operator that conforms to the pattern that this rule enforces. const destroySubjectNames = new Set<string>(); destroySubjectNamesBySubscribes.forEach((names) => names.forEach((name) => destroySubjectNames.add(name)) ); const destroySubjectResultsByName = new Map< string, { failures: Lint.RuleFailure[]; report: boolean } >(); destroySubjectNames.forEach((name) => { destroySubjectResultsByName.set(name, { failures: [ ...this.checkDestroySubjectDeclaration( sourceFile, classDeclaration, name ), ...this.checkDestroySubjectMethodInvocation( sourceFile, ngOnDestroyMethod, name, "next" ), ...this.checkDestroySubjectMethodInvocation( sourceFile, ngOnDestroyMethod, name, "complete" ), ], report: false, }); }); destroySubjectNamesBySubscribes.forEach((names) => { const report = [...names].every( (name) => destroySubjectResultsByName.get(name).failures.length > 0 ); if (report) { names.forEach( (name) => (destroySubjectResultsByName.get(name).report = true) ); } }); destroySubjectResultsByName.forEach((result) => { if (result.report) { failures.push(...result.failures); } }); } else { failures.push( new Lint.RuleFailure( sourceFile, classDeclaration.name.getStart(), classDeclaration.name.getStart() + classDeclaration.name.getWidth(), Rule.FAILURE_STRING_NO_DESTROY, this.ruleName ) ); } return failures; } private checkDestroySubjectDeclaration( sourceFile: ts.SourceFile, classDeclaration: ts.ClassDeclaration, destroySubjectName: string ) { const failures: Lint.RuleFailure[] = []; const propertyDeclarations = tsquery( classDeclaration, `PropertyDeclaration[name.text="${destroySubjectName}"]` ) as ts.PropertyDeclaration[]; if (propertyDeclarations.length === 0) { const { name } = classDeclaration; failures.push( new Lint.RuleFailure( sourceFile, name.getStart(), name.getStart() + name.getWidth(), Rule.FAILURE_MESSAGE_NOT_DECLARED(destroySubjectName), this.ruleName ) ); } return failures; } /** * Checks whether all <destroySubjectNameUsed>.<methodName>() are invoked in the ngOnDestroyMethod */ private checkDestroySubjectMethodInvocation( sourceFile: ts.SourceFile, ngOnDestroyMethod: ts.ClassElement, destroySubjectName: string, methodName: string ) { const failures: Lint.RuleFailure[] = []; const destroySubjectMethodInvocations = tsquery( ngOnDestroyMethod, `CallExpression > PropertyAccessExpression[name.name="${methodName}"]` ) as ts.PropertyAccessExpression[]; // check whether there is one invocation of <destroySubjectName>.<methodName>() if ( !destroySubjectMethodInvocations.some( (methodInvocation) => (tsutils.isPropertyAccessExpression(methodInvocation.expression) && isThis(methodInvocation.expression.expression) && methodInvocation.expression.name.text === destroySubjectName) || (tsutils.isIdentifier(methodInvocation.expression) && methodInvocation.expression.text === destroySubjectName) ) ) { failures.push( new Lint.RuleFailure( sourceFile, ngOnDestroyMethod.name.getStart(), ngOnDestroyMethod.name.getStart() + ngOnDestroyMethod.name.getWidth(), Rule.FAILURE_MESSAGE_NOT_CALLED(destroySubjectName, methodName), this.ruleName ) ); } return failures; } }
the_stack
import * as strings from "LeadAssistDashboardWebPartStrings"; import { Providers } from "@microsoft/mgt-spfx"; import { IList, sp } from "@pnp/sp/presets/all"; import { IListField } from "./IListField"; import { IValueListItem } from "./IValueListItem"; import { ISaleListItem } from "./ISaleListItem"; export default class DataService { // Lists names public static ActivityCallsListName: string = strings.ActivityCallsListName; public static ActivityEmailsListName: string = strings.ActivityEmailsListName; public static ActivityTextsListName: string = strings.ActivityTextsListName; public static ProgressListName: string = strings.ProgressListName; public static RecentlyDoneSalesContractsListName: string = strings.RecentlyDoneSalesContractsListName; // Fields titles public static FieldTitleName: string = "Title"; public static FieldValueName: string = "DemoValue"; public static FieldDescriptionName: string = "DemoDescription"; public static FieldMonthName: string = "DemoMonth"; public static FieldGroupName: string = "Demo Group"; // Fields types public static FieldTypeText: string = "SP.FieldText"; public static FieldTypeTextKindId: number = 2; public static FieldTypeNumber: string = "SP.FieldNumber"; public static FieldTypeNumberKindId: number = 9; public static MonthNames: string[] = [ strings.January, strings.February, strings.March, strings.April, strings.May, strings.June, strings.July ]; // Value field definition private static ValueField: IListField = { fieldName: DataService.FieldValueName, fieldType: DataService.FieldTypeNumber, fieldTypeKindId: DataService.FieldTypeNumberKindId }; // Description field definition private static DescriptionField: IListField = { fieldName: DataService.FieldDescriptionName, fieldType: DataService.FieldTypeText, fieldTypeKindId: DataService.FieldTypeTextKindId }; // Month field definition private static MonthField: IListField = { fieldName: DataService.FieldMonthName, fieldType: DataService.FieldTypeText, fieldTypeKindId: DataService.FieldTypeTextKindId }; /** * Format the specific date in a short locale string * @param date The date to be formatted * @returns The formatted date in string format */ public static getTime(date: Date): string { const timeOptions = { timeStyle: 'short', hour12: true }; return date.toLocaleTimeString([], timeOptions); } /** * Format the specific date in a short locale string * @param date The date to be formatted * @returns The formatted date in string format */ public static getDate(date: Date): string { return date.toLocaleDateString([], { day: 'numeric', month: 'short' }); } /** * Generate an array of number for demo data * @param length Length of the numeric array * @returns Numeric array of demo data */ public static generateNumericDemoData(length: number): number[] { let demoData = [...Array(length)].map(() => { let n = Math.floor(Math.random() * 9); return n; }); return demoData; } /** * Generate the demo fields and lists */ public static async generateDemoLists(): Promise<void> { if (confirm(strings.ConfirmCreateDemoLists) == true) { // Ensure fields await this.ensureWebField(DataService.FieldValueName, DataService.FieldTypeNumber, DataService.FieldTypeNumberKindId); await this.ensureWebField(DataService.FieldDescriptionName, DataService.FieldTypeText, DataService.FieldTypeTextKindId); await this.ensureWebField(DataService.FieldMonthName, DataService.FieldTypeText, DataService.FieldTypeTextKindId); // Ensure lists await this.ensureList(DataService.ActivityCallsListName, [this.ValueField]); await this.ensureList(DataService.ActivityEmailsListName, [this.ValueField]); await this.ensureList(DataService.ActivityTextsListName, [this.ValueField]); await this.ensureList(DataService.ProgressListName, [this.ValueField]); await this.ensureList(DataService.RecentlyDoneSalesContractsListName, [this.DescriptionField]); alert(strings.DemoListsCreated); } } /** * Generate the demo data for the SharePoint lists */ public static async generateListsDemoData(): Promise<void> { if (confirm(strings.ConfirmAddDemoData) == true) { // Get all the lists references const activityCallsList = await sp.web.lists.getByTitle(DataService.ActivityCallsListName); const activityEmailsList = await sp.web.lists.getByTitle(DataService.ActivityEmailsListName); const activityTextsList = await sp.web.lists.getByTitle(DataService.ActivityTextsListName); const progressList = await sp.web.lists.getByTitle(DataService.ProgressListName); const recentContractsList = await sp.web.lists.getByTitle(DataService.RecentlyDoneSalesContractsListName); // Generate sales products list demo data DataService.generateNumericDemoData(7).forEach((p, i) => { activityCallsList.items.add({ Title: strings.DemoActivityCallTitle + " " + i, DemoValue: p * 10 }); }); // Generate sales services list demo data DataService.generateNumericDemoData(7).forEach((p, i) => { activityEmailsList.items.add({ Title: strings.DemoActivityEmailTitle + " " + i, DemoValue: p * 10 }); }); // Generate activity text list demo data DataService.generateNumericDemoData(7).forEach((p, i) => { activityTextsList.items.add({ Title: strings.DemoActivityTextTitle + " " + i, DemoValue: p * 10 }); }); // Generate progress list demo data DataService.generateNumericDemoData(9).forEach(p => { progressList.items.add({ Title: p.toString(), DemoValue: p }); }); // Generate recently list demo data [...Array(5)].map((v, i) => { return { title: strings.DemoDocumentTitle + " " + i, description: strings.DemoDocumentDescription + " " + i }; }).forEach(r => { recentContractsList.items.add({ Title: r.title, DemoDescription: r.description }); }); alert(strings.DemoDataGenerated); } } /** * Generate demo data using Graph */ public static async generateGraphDemoData(): Promise<void> { if (confirm(strings.ConfirmAddGraphDemoData) == true) { let provider = Providers.globalProvider; if (provider) { // Get the Graph client let graphClient = provider.graph.client; // Add new task let taskLists = await graphClient.api("me/todo/lists").get(); // Simple task await graphClient.api(`me/todo/lists/${taskLists.value[0].id}/tasks`).create({ "title": strings.DemoEventTitle, "linkedResources": [ { "webUrl": "https://aka.ms/m365pnp", "applicationName": strings.DemoApplicationName, "displayName": strings.DemoDisplayName } ] }); // Task with due date let taskDate = new Date(); taskDate.setDate(taskDate.getDate() + 1); await graphClient.api(`me/todo/lists/${taskLists.value[0].id}/tasks`).create({ "title": strings.DemoTaskWithDateTitle, "dueDateTime": { "dateTime": taskDate.toISOString(), "timeZone": "UTC" }, "linkedResources":[ { "webUrl": "https://aka.ms/m365pnp", "applicationName": strings.DemoApplicationName, "displayName": strings.DemoDisplayName } ] }); // Start and end date for events let startDate = new Date(); let endDate = new Date(); // Set the start and end date to tomorrow startDate.setDate(startDate.getDate() + 1); endDate.setDate(endDate.getDate() + 1); // Add one hour to the end date endDate.setHours(endDate.getHours() + 1); // Event with location await graphClient.api("me/events").create({ "subject": strings.DemoEventTitle, "body": { "contentType": "HTML", "content": strings.DemoEventContent }, "start": { "dateTime": startDate.toISOString(), "timeZone": "UTC" }, "end": { "dateTime": endDate.toISOString(), "timeZone": "UTC" }, "location":{ "displayName": strings.DemoEventLocation } }); // Change date for the next event startDate.setDate(startDate.getDate() + 1); endDate.setDate(endDate.getDate() + 1); // Online event await graphClient.api("me/events").create({ "subject": strings.DemoEventOnlineTitle, "body": { "contentType": "HTML", "content": strings.DemoEventOnlineContent }, "start": { "dateTime": startDate.toISOString(), "timeZone": "Pacific Standard Time" }, "end": { "dateTime": endDate.toISOString(), "timeZone": "Pacific Standard Time" }, "isOnlineMeeting": "true" }); } alert(strings.GraphDemoDataGenerated); } } /** * Delete the SharePoint lists */ public static async deleteSharePointDemoLists(): Promise<void> { if (confirm(strings.ConfirmDeleteSharePointDemoLists) == true) { // Get all the lists references const activityCallsList = await sp.web.lists.getByTitle(DataService.ActivityCallsListName); const activityEmailsList = await sp.web.lists.getByTitle(DataService.ActivityEmailsListName); const activityTextsList = await sp.web.lists.getByTitle(DataService.ActivityTextsListName); const progressList = await sp.web.lists.getByTitle(DataService.ProgressListName); const recentContractsList = await sp.web.lists.getByTitle(DataService.RecentlyDoneSalesContractsListName); // Delete the lists await activityCallsList.delete(); await activityEmailsList.delete(); await activityTextsList.delete(); await progressList.delete(); await recentContractsList.delete(); alert(strings.SharePointDemoListsDeleted); } } /** * Get items with values from a specific SharePoint list * @param listTitle Title of the list * @param mappingFunction Function to map every items of the list * @returns An array of the mapped items */ public static async getItemsWithValueFromList(listTitle: string, mappingFunction: (value: any, index: number) => IValueListItem): Promise<IValueListItem[]> { return await this.getItemsFromList(listTitle, mappingFunction); } /** * Get sales items from a specific SharePoint list * @param listTitle Title of the list * @param mappingFunction Function to map every items of the list * @returns An array of the mapped items */ public static async getSalesItemsFromList(listTitle: string, mappingFunction: (value: any, index: number) => ISaleListItem): Promise<ISaleListItem[]> { return await this.getItemsFromList(listTitle, mappingFunction); } /** * Get items from a specific SharePoint list * @param listTitle Title of the list * @param mappingFunction Function to map every items of the list * @returns An array of the mapped items */ private static async getItemsFromList<T>(listTitle: string, mappingFunction: (value: T, index: number) => T): Promise<T[]> { // Get the items from the list const items = await sp.web.lists.getByTitle(listTitle).items.getAll(); // Map the items with the specified function const mappedItems = items.map((v, i) => mappingFunction(v, i)); return mappedItems; } /** * Ensure that a field on a SharePoint site exists, otherwise create it * @param fieldName Name of the field * @param fieldType Type of the field * @param typeKindId Type kind id of the field */ private static async ensureWebField(fieldName: string, fieldType: string, typeKindId: number) { var existingField = (await sp.web.fields.get()).filter(f => f.StaticName == fieldName); // If the field has not been added yet create it if (existingField && existingField.length == 0) { await sp.web.fields.add(fieldName, fieldType, { FieldTypeKind: typeKindId, Group: DataService.FieldGroupName }); } } /** * Add a specific field to the target SharePoint list * @param targetList Name of the target SharePoint list * @param fieldName Name of the field * @param fieldType Type of the field * @param typeKindId Type kind id of the field */ private static async addFieldToList(targetList: IList, fieldName: string, fieldType: string, fieldTypeKindId: number) { await targetList.fields.add(fieldName, fieldType, { FieldTypeKind: fieldTypeKindId, Group: DataService.FieldGroupName }); } /** * Ensure that a SharePoint list exists, otherwise create it * @param listName Name of the SharePoint list * @param fieldsToAdd Fields to add to the SharePoint list */ private static async ensureList(listName: string, fieldsToAdd: IListField[]) { // Ensure the existence of the demo list const listExists = await sp.web.lists.ensure(listName); // If the list exists and there are fields specified if (listExists.created == true && fieldsToAdd != undefined) { // Cycle through fields to add for (let i = 0; i < fieldsToAdd.length; i++) { await this.addFieldToList(listExists.list, fieldsToAdd[i].fieldName, fieldsToAdd[i].fieldType, fieldsToAdd[i].fieldTypeKindId); } } } }
the_stack
import type { Logger } from '@island.is/logging' import { LOGGER_PROVIDER } from '@island.is/logging' import { BadRequestException, Inject, Injectable } from '@nestjs/common' import { InjectModel } from '@nestjs/sequelize' import { ClientDTO } from '../entities/dto/client.dto' import { ClientUpdateDTO } from '../entities/dto/client-update.dto' import { ClientIdpRestrictionDTO } from '../entities/dto/client-idp-restriction.dto' import { ClientAllowedCorsOrigin } from '../entities/models/client-allowed-cors-origin.model' import { ClientAllowedScope } from '../entities/models/client-allowed-scope.model' import { ClientClaim } from '../entities/models/client-claim.model' import { ClientGrantType } from '../entities/models/client-grant-type.model' import { ClientIdpRestrictions } from '../entities/models/client-idp-restrictions.model' import { ClientPostLogoutRedirectUri } from '../entities/models/client-post-logout-redirect-uri.model' import { ClientRedirectUri } from '../entities/models/client-redirect-uri.model' import { ClientSecret } from '../entities/models/client-secret.model' import { Client } from '../entities/models/client.model' import { ClientAllowedCorsOriginDTO } from '../entities/dto/client-allowed-cors-origin.dto' import { ClientRedirectUriDTO } from '../entities/dto/client-redirect-uri.dto' import { ClientGrantTypeDTO } from '../entities/dto/client-grant-type.dto' import { ClientAllowedScopeDTO } from '../entities/dto/client-allowed-scope.dto' import { ClientClaimDTO } from '../entities/dto/client-claim.dto' import { ClientPostLogoutRedirectUriDTO } from '../entities/dto/client-post-logout-redirect-uri.dto' import { ClientSecretDTO } from '../entities/dto/client-secret.dto' import sha256 from 'crypto-js/sha256' import Base64 from 'crypto-js/enc-base64' import { IdentityResource } from '../entities/models/identity-resource.model' import { ApiScope } from '../entities/models/api-scope.model' import { IdpProvider } from '../entities/models/idp-provider.model' @Injectable() export class ClientsService { constructor( @InjectModel(Client) private clientModel: typeof Client, @InjectModel(ClientAllowedCorsOrigin) private clientAllowedCorsOrigin: typeof ClientAllowedCorsOrigin, @InjectModel(ClientIdpRestrictions) private clientIdpRestriction: typeof ClientIdpRestrictions, @InjectModel(ClientSecret) private clientSecret: typeof ClientSecret, @InjectModel(ClientRedirectUri) private clientRedirectUri: typeof ClientRedirectUri, @InjectModel(ClientGrantType) private clientGrantType: typeof ClientGrantType, @InjectModel(ClientAllowedScope) private clientAllowedScope: typeof ClientAllowedScope, @InjectModel(ClientClaim) private clientClaim: typeof ClientClaim, @InjectModel(IdpProvider) private idpProvider: typeof IdpProvider, @InjectModel(ClientPostLogoutRedirectUri) private clientPostLogoutUri: typeof ClientPostLogoutRedirectUri, @InjectModel(ApiScope) private apiScopeModel: typeof ApiScope, @InjectModel(IdentityResource) private identityResourceModel: typeof IdentityResource, @Inject(LOGGER_PROVIDER) private logger: Logger, ) {} /** Gets all clients */ async findAll(): Promise<Client[] | null> { return this.clientModel.findAll({ include: [ ClientAllowedScope, ClientAllowedCorsOrigin, ClientRedirectUri, ClientIdpRestrictions, ClientSecret, ClientPostLogoutRedirectUri, ClientGrantType, ClientClaim, ], }) } /** Gets all clients with paging */ async findAndCountAll( page: number, count: number, ): Promise<{ rows: Client[]; count: number } | null> { page-- const offset = page * count return this.clientModel.findAndCountAll({ limit: count, offset: offset, distinct: true, }) } /** Gets a client by it's id */ async findClientById(id: string): Promise<Client | null> { this.logger.debug(`Finding client for id - "${id}"`) if (!id) { throw new BadRequestException('Id must be provided') } const client = await this.clientModel.findByPk(id, { raw: true }) if (client) { await this.findAssociations(client) .then<any, never>((result: any) => { client.allowedScopes = result[0] client.allowedCorsOrigins = result[1] client.redirectUris = result[2] client.identityProviderRestrictions = result[3] client.clientSecrets = result[4] client.postLogoutRedirectUris = result[5] client.allowedGrantTypes = result[6] client.claims = result[7] }) .catch((error) => this.logger.error(`Error in findAssociations: ${error}`), ) } return client } /** Find clients by searh string and returns with paging */ async findClients(searchString: string, page: number, count: number) { if (!searchString) { throw new BadRequestException('Search String must be provided') } searchString = searchString.trim() if (isNaN(+searchString)) { return this.findAllClientsById(searchString, page, count) } else { return this.findAllClientsByNationalId(searchString, page, count) } } /** Find clients by National Id */ async findAllClientsByNationalId( searchString: string, page: number, count: number, ) { page-- const offset = page * count return this.clientModel.findAndCountAll({ limit: count, where: { nationalId: searchString }, offset: offset, distinct: true, }) } /** Finds client by client Id with paging return type */ async findAllClientsById(searchString: string, page: number, count: number) { page-- const offset = page * count return this.clientModel.findAndCountAll({ limit: count, where: { clientId: searchString }, offset: offset, distinct: true, }) } /** Gets all associations for Client */ private findAssociations(client: Client): Promise<any> { return Promise.all([ this.clientAllowedScope.findAll({ where: { clientId: client.clientId }, raw: true, }), // 0 this.clientAllowedCorsOrigin.findAll({ where: { clientId: client.clientId }, raw: true, }), // 1 this.clientRedirectUri.findAll({ where: { clientId: client.clientId }, raw: true, }), // 2 this.clientIdpRestriction.findAll({ where: { clientId: client.clientId }, raw: true, }), // 3 this.clientSecret.findAll({ where: { clientId: client.clientId }, raw: true, }), // 4 this.clientPostLogoutUri.findAll({ where: { clientId: client.clientId }, raw: true, }), // 5 this.clientGrantType.findAll({ where: { clientId: client.clientId }, raw: true, }), // 6 this.clientClaim.findAll({ where: { clientId: client.clientId }, raw: true, }), // 7 ]) } /** Creates a new client */ async create(client: ClientDTO): Promise<Client> { this.logger.debug('Creating a new client') return await this.clientModel.create({ ...client }) } /** Updates an existing client */ async update(client: ClientUpdateDTO, id: string): Promise<Client | null> { this.logger.debug('Updating client with id: ', id) if (!id) { throw new BadRequestException('id must be provided') } await this.clientModel.update( { ...client }, { where: { clientId: id }, }, ) return await this.findClientById(id) } /** Soft delete on a client by id */ async delete(id: string): Promise<number> { this.logger.debug('Soft deleting a client with id: ', id) if (!id) { throw new BadRequestException('id must be provided') } const result = await this.clientModel.update( { archived: new Date(), enabled: false }, { where: { clientId: id }, }, ) return result[0] } /** Finds allowed cors origins by origin */ async findAllowedCorsOrigins( origin: string, ): Promise<ClientAllowedCorsOrigin[]> { this.logger.debug( `Finding client allowed CORS origins for origin - "${origin}"`, ) if (!origin) { throw new BadRequestException('Origin must be provided') } return this.clientAllowedCorsOrigin.findAll({ where: { origin: origin }, }) } /** Adds IDP restriction to client */ async addIdpRestriction( clientIdpRestriction: ClientIdpRestrictionDTO, ): Promise<ClientIdpRestrictions> { this.logger.debug( `Creating IDP restriction for client - "${clientIdpRestriction.clientId}" with restriction - "${clientIdpRestriction.name}"`, ) if (!clientIdpRestriction) { throw new BadRequestException('ClientIdpRestriction must be provided') } return await this.clientIdpRestriction.create({ ...clientIdpRestriction }) } /** Removes an IDP restriction for a client */ async removeIdpRestriction(clientId: string, name: string): Promise<number> { this.logger.debug( `Removing IDP restriction for client - "${clientId}" with restriction - "${name}"`, ) if (!name || !clientId) { throw new BadRequestException( 'IdpRestriction name and clientId must be provided', ) } return await this.clientIdpRestriction.destroy({ where: { clientId: clientId, name: name }, }) } /** Adds Allowed CORS origin for client */ async addAllowedCorsOrigin( corsOrigin: ClientAllowedCorsOriginDTO, ): Promise<ClientAllowedCorsOrigin> { this.logger.debug( `Adding allowed cors origin for client - "${corsOrigin.clientId}" with origin - "${corsOrigin.origin}"`, ) if (!corsOrigin) { throw new BadRequestException('Cors origin object must be provided') } return await this.clientAllowedCorsOrigin.create({ ...corsOrigin }) } /** Removes an allowed cors origin for client */ async removeAllowedCorsOrigin( clientId: string, origin: string, ): Promise<number> { this.logger.debug( `Removing cors origin for client - "${clientId}" with origin - "${origin}"`, ) if (!clientId || !origin) { throw new BadRequestException('origin and clientId must be provided') } return await this.clientAllowedCorsOrigin.destroy({ where: { clientId: clientId, origin: origin }, }) } /** Adds an redirect uri for client */ async addRedirectUri( redirectObject: ClientRedirectUriDTO, ): Promise<ClientRedirectUri> { this.logger.debug( `Adding redirect uri for client - "${redirectObject.clientId}" with uri - "${redirectObject.redirectUri}"`, ) if (!redirectObject) { throw new BadRequestException('Redirect object must be provided') } return await this.clientRedirectUri.create({ ...redirectObject }) } /** Removes an redirect uri for client */ async removeRedirectUri( clientId: string, redirectUri: string, ): Promise<number> { this.logger.debug( `Removing redirect uri for client - "${clientId}" with uri - "${redirectUri}"`, ) if (!clientId || !redirectUri) { throw new BadRequestException('redirectUri and clientId must be provided') } return await this.clientRedirectUri.destroy({ where: { clientId: clientId, redirectUri: redirectUri }, }) } /** Adds a grant type to client */ async addGrantType( grantTypeObj: ClientGrantTypeDTO, ): Promise<ClientGrantType> { this.logger.debug( `Adding grant type - "${grantTypeObj.grantType}" to client - "${grantTypeObj.clientId}"`, ) if (!grantTypeObj) { throw new BadRequestException('Grant Type object must be provided') } return await this.clientGrantType.create({ ...grantTypeObj }) } /** Removes a grant type for client */ async removeGrantType(clientId: string, grantType: string): Promise<number> { this.logger.debug( `Removing grant type "${grantType}" for client - "${clientId}"`, ) if (!clientId || !grantType) { throw new BadRequestException('grantType and clientId must be provided') } return await this.clientGrantType.destroy({ where: { clientId: clientId, grantType: grantType }, }) } /** Adds an allowed scope to client */ async addAllowedScope( clientAllowedScope: ClientAllowedScopeDTO, ): Promise<ClientAllowedScope> { this.logger.debug( `Adding allowed scope - "${clientAllowedScope.scopeName}" to client - "${clientAllowedScope.clientId}"`, ) if (!clientAllowedScope) { throw new BadRequestException( 'clientAllowedScope object must be provided', ) } return await this.clientAllowedScope.create({ ...clientAllowedScope }) } /** Removes an allowed scope from client */ async removeAllowedScope( clientId: string, scopeName: string, ): Promise<number> { this.logger.debug( `Removing scope - "${scopeName}" from client - "${clientId}"`, ) if (!clientId || !scopeName) { throw new BadRequestException('scopeName and clientId must be provided') } return await this.clientAllowedScope.destroy({ where: { clientId: clientId, scopeName: scopeName }, }) } /** Adds an claim to client */ async addClaim(claim: ClientClaimDTO): Promise<ClientClaim> { this.logger.debug( `Adding claim of type - "${claim.type}", with value - "${claim.value}" to client - "${claim.clientId}"`, ) if (!claim) { throw new BadRequestException('claim object must be provided') } return await this.clientClaim.create({ ...claim }) } /** Removes an claim from client */ async removeClaim( clientId: string, claimType: string, claimValue: string, ): Promise<number> { this.logger.debug( `Removing claim of type - "${claimType}", with value - "${claimValue}" from client - "${clientId}"`, ) if (!clientId || !claimType || !claimValue) { throw new BadRequestException( 'claimType, claimValue and clientId must be provided', ) } return await this.clientClaim.destroy({ where: { clientId: clientId, type: claimType, value: claimValue }, }) } /** Adds an post logout uri to client */ async addPostLogoutRedirectUri( postLogoutUri: ClientPostLogoutRedirectUriDTO, ): Promise<ClientPostLogoutRedirectUri> { this.logger.debug( `Adding post logout uri - "${postLogoutUri.redirectUri}", to client - "${postLogoutUri.clientId}"`, ) if (!postLogoutUri) { throw new BadRequestException('postLogoutUri object must be provided') } return await this.clientPostLogoutUri.create({ ...postLogoutUri }) } /** Removes an post logout uri from client */ async removePostLogoutRedirectUri( clientId: string, redirectUri: string, ): Promise<number> { this.logger.debug( `Removing post logout uri - "${redirectUri}" from client - "${clientId}"`, ) if (!clientId || !redirectUri) { throw new BadRequestException('clientId and uri must be provided') } return await this.clientPostLogoutUri.destroy({ where: { clientId: clientId, redirectUri: redirectUri }, }) } /** Add secret to Client */ async addClientSecret(clientSecret: ClientSecretDTO): Promise<ClientSecret> { const words = sha256(clientSecret.value) const secret = Base64.stringify(words) return this.clientSecret.create({ clientId: clientSecret.clientId, value: secret, description: clientSecret.description, type: clientSecret.type, }) } /** Remove a secret from Client */ async removeClientSecret(clientSecret: ClientSecretDTO): Promise<number> { return this.clientSecret.destroy({ where: { clientId: clientSecret.clientId, value: clientSecret.value, }, }) } /** Finds available scopes for AdminUI to select allowed scopes */ async FindAvailabeScopes(): Promise<ApiScope[]> { const identityResources = (await this.identityResourceModel.findAll({ where: { archived: null }, })) as unknown const apiScopes = await this.apiScopeModel.findAll({ where: { archived: null, }, }) const arrJoined: ApiScope[] = [] arrJoined.push(...apiScopes) arrJoined.push(...(identityResources as ApiScope[])) return arrJoined.sort((a, b) => a.name.localeCompare(b.name)) } /** Finds available idp restrictions */ async findAllIdpRestrictions(): Promise<IdpProvider[] | null> { const idpRestrictions = await this.idpProvider.findAll() return idpRestrictions } }
the_stack
import * as fs from "fs-extra"; import * as path from "path"; import { ArgumentParser } from "argparse"; import { appendFilesSync, spawnSync, fail, pathLooksLikeDirectory, endsWith, writeEMConfig, flatten, wasdkPath, pathFromRoot, downloadFileSync, decompressFileSync, deleteFileSync, ensureDirectoryCreatedSync } from "./shared"; import { WASDK_DEBUG, EMCC, JS, ASSEMBLER, DISASSEMBLER, WEBIDL_BINDER, TMP_DIR, EMSCRIPTEN_ROOT, LLVM_ROOT, BINARYEN_ROOT, SPIDERMONKEY_ROOT, EM_CONFIG } from "./shared"; import { WebIDLWasmGen, parseModuleOperations } from "wasdk-idl"; var colors = require('colors'); var parser = new ArgumentParser({ version: '0.0.1', addHelp: true, description: 'WebAssembly SDK' }); let subparsers = parser.addSubparsers({ title: 'Commands', dest: "command" }); let sdkParser = subparsers.addParser('sdk', { addHelp: true }); sdkParser.addArgument(['--install'], { action: 'storeTrue', help: 'Install SDK' }); sdkParser.addArgument(['--test'], { action: 'storeTrue', help: 'Test SDK' }); sdkParser.addArgument(['--clean'], { action: 'storeTrue', help: 'Clean SDK' }); let ezParser = subparsers.addParser('ez', { help: "Compile .c/.cpp files.", addHelp: true }); ezParser.addArgument(['-o', '--output'], { help: 'Output file.' }); ezParser.addArgument(['--idl'], { help: 'WebIDL file.' }); ezParser.addArgument(['--debuginfo', '-g'], { action: 'storeTrue', help: 'Emit names section and debug info' }); ezParser.addArgument(['input'], { help: 'Input file(s).' }); let idlGenerator = subparsers.addParser('idl', { help: "Generate idl-based project: .j/.c/.cpp files.", addHelp: true }); idlGenerator.addArgument(['input'], { help: 'Input .idl file.' }); idlGenerator.addArgument(['-o', '--output'], { help: 'Output directory.' }); idlGenerator.addArgument(['-n', '--namespace'], {help: 'C++ namespace'}); idlGenerator.addArgument(['-p', '--prefix'], {help: 'Filename prefix for .js/.h/.cpp'}); let smParser = subparsers.addParser('disassemble', { help: "Disassemble files.", addHelp: true }); smParser.addArgument(['input'], { help: 'Input .wast/.wasm file.' }); let emccParser = subparsers.addParser('emcc', { help: "Emscripten Compiler", addHelp: true }); emccParser.addArgument(['args'], { nargs: '...' }); let jsParser = subparsers.addParser('js', { help: "SpiderMonkey Shell", addHelp: true }); jsParser.addArgument(['args'], { nargs: '...' }); let dumpParser = subparsers.addParser('dump', { help: "Print WebAssembly text", addHelp: true }); dumpParser.addArgument(['input'], { help: 'Input .wasm file.' }); let asParser = subparsers.addParser('as', { help: "WebAssembly text-to-binary", addHelp: true }); asParser.addArgument(['input'], { help: 'Input .wast file.' }); asParser.addArgument(['output'], { help: 'Output .wasm file.' }); var cliArgs = parser.parseArgs(); WASDK_DEBUG && console.dir(cliArgs); if (cliArgs.command === "emcc") emcc(); if (cliArgs.command === "js") js(); if (cliArgs.command === "sdk") sdk(); if (cliArgs.command === "idl") idl(); if (cliArgs.command === "ez") ezCompile(); if (cliArgs.command === "disassemble") disassemble(); if (cliArgs.command === "dump") dump(); if (cliArgs.command === "as") assemble(); function section(name) { console.log(name.bold.green.underline); } function js() { let args = cliArgs.args; let res = spawnSync(JS, flatten(args), { stdio: [0, 1, 2] }); } function emcc() { let args = ["--em-config", EM_CONFIG].concat(cliArgs.args); let res = spawnSync(EMCC, flatten(args), { stdio: [0, 1, 2] }); } function sdk() { if (cliArgs.clean) clean(); if (cliArgs.install) install(); if (cliArgs.test) test(); } function patchEM() { let emscriptenPath = path.join(EMSCRIPTEN_ROOT, 'emscripten.py'); // Fixing asm2wasm compilation, see https://github.com/kripken/emscripten/issues/4715 let s = fs.readFileSync(emscriptenPath).toString(); s = s.replace(/if\ssettings\[\'ALLOW_MEMORY_GROWTH\'\]:(\s+exported_implemented_functions\.)/, "if not settings['ONLY_MY_CODE'] and settings['ALLOW_MEMORY_GROWTH']:$1"); fs.writeFileSync(emscriptenPath, s); } function install() { var thirdpartyConfigPath = process.env.WASDK_3PARTY || path.join(__dirname, "..", "thirdparty.json"); let thirdpartyConfig = JSON.parse(fs.readFileSync(thirdpartyConfigPath).toString()); let url, filename; let platform = process.platform; if (platform !== "darwin" && platform !== "linux" && platform !== "win32") fail(`Platform ${process.platform} not supported.`); section("Installing Emscripten"); url = thirdpartyConfig.all.emscripten; filename = downloadFileSync(url, TMP_DIR); decompressFileSync(filename, EMSCRIPTEN_ROOT, 1); url = thirdpartyConfig.all.emscriptenpatch; filename = downloadFileSync(url, TMP_DIR); decompressFileSync(filename, EMSCRIPTEN_ROOT, 0); patchEM(); section("Installing LLVM"); url = thirdpartyConfig[platform].llvm; filename = downloadFileSync(url, TMP_DIR); decompressFileSync(filename, LLVM_ROOT, 1); section("Installing Binaryen"); url = thirdpartyConfig[platform].binaryen; filename = downloadFileSync(url, TMP_DIR); decompressFileSync(filename, BINARYEN_ROOT, 0); section("Installing Spidermonkey"); url = thirdpartyConfig[platform].spidermonkey; filename = downloadFileSync(url, TMP_DIR); decompressFileSync(filename, SPIDERMONKEY_ROOT, 0); writeEMConfig(); } function clean() { deleteFileSync(TMP_DIR); deleteFileSync(LLVM_ROOT); deleteFileSync(EMSCRIPTEN_ROOT); } function updateHFile(hFilePath: string, gen: WebIDLWasmGen) { if (!fs.existsSync(hFilePath)) { fs.writeFileSync(hFilePath, gen.getHCode()); return; } var old = fs.readFileSync(hFilePath).toString(); fs.writeFileSync(hFilePath + '.bak', old); var combined = gen.updateHCode(old); fs.writeFileSync(hFilePath, combined); } function updateCxxFile(cxxFilePath: string, gen: WebIDLWasmGen) { if (!fs.existsSync(cxxFilePath)) { fs.writeFileSync(cxxFilePath, gen.getCxxCode()); return; } var old = fs.readFileSync(cxxFilePath).toString(); fs.writeFileSync(cxxFilePath + '.bak', old); var combined = gen.updateCxxCode(old); fs.writeFileSync(cxxFilePath, combined); } function idl() { var idlPath = cliArgs.input; var basename = path.basename(idlPath, path.extname(idlPath)); var outputDir = cliArgs.output || basename; ensureDirectoryCreatedSync(outputDir); var fileprefix = cliArgs.prefix || basename; var namespace = cliArgs.namespace || (fileprefix[0].toUpperCase() + fileprefix.slice(1)); if (!/^\w+$/.test(namespace)) throw new Error('Invalid C++ namespace: ' + namespace); var gen = new WebIDLWasmGen(namespace, fileprefix); var idlContent = fs.readFileSync(idlPath).toString(); gen.parse(idlContent); fs.writeFileSync(path.join(outputDir, fileprefix + '.js'), gen.getJSCode()); fs.writeFileSync(path.join(outputDir, fileprefix + '.json'), gen.getJsonCode()); updateHFile(path.join(outputDir, fileprefix + '.h'), gen); updateCxxFile(path.join(outputDir, fileprefix + '.cpp'), gen); } interface Config { files: string []; dependencies?: string [], interface?: string; output?: string; options: { EXPORTED_RUNTIME_METHODS: string [], EXPORTED_FUNCTIONS: string [], SIDE_MODULE: number, ALLOW_MEMORY_GROWTH: number, RELOCATABLE: number, VERBOSE: number } } function resolveConfig(config: Config, configPath: string = null) { let configRoot = null; if (configPath) { configRoot = path.resolve(path.dirname(configPath)); } function resolvePath(p: string) { if (!p) return null; if (path.isAbsolute(p)) return p; if (configRoot) return path.resolve(path.join(configRoot, p)); return path.resolve(p); } config.files = config.files.map(resolvePath); config.interface = resolvePath(config.interface); if (config.output) { config.output = resolvePath(config.output); } if (config.interface) { let members = parseModuleOperations( fs.readFileSync(config.interface).toString()); if (!members) fail("WebIDL file must declare a Module interface."); config.options.EXPORTED_FUNCTIONS = config.options.EXPORTED_FUNCTIONS.concat(members.map(m => "_" + m)); config.options.EXPORTED_FUNCTIONS.push("__growWasmMemory"); } } function dumpWasm(wasmPath: string): string { let res = spawnSync(DISASSEMBLER, [wasmPath]); if (res.status !== 0) fail("Disassembly error:\n" + res.stderr); return res.stdout.toString(); } function dump() { console.log(dumpWasm(cliArgs.input)); } function assemble() { let res = spawnSync(ASSEMBLER, [cliArgs.input, '-o', cliArgs.output], { stdio: [0, 1, 2] }); if (res.status !== 0) fail("Wasm assembly error:\n" + res.stderr); } function quoteStringArray(a: string []): string { return `[${a.map(x => `'${x}'`).join(", ")}]`; } function mergeConfigs(base: any, delta: any) { for (var name in delta) { var value = delta[name]; if (typeof value === 'object' && value !== null) { if (!base[name]) base[name] = {}; mergeConfigs(base[name], value); } else { base[name] = value; } } } function ezCompile() { let config: Config = { files: [], dependencies: [], options: { EXPORTED_RUNTIME_METHODS: [], EXPORTED_FUNCTIONS: [], ALLOW_MEMORY_GROWTH: 0, SIDE_MODULE: 1, RELOCATABLE: 1, VERBOSE: 0 } }; if (path.extname(cliArgs.input) === ".json") { mergeConfigs(config, JSON.parse(fs.readFileSync(cliArgs.input, 'utf8'))); resolveConfig(config, cliArgs.input); } else { mergeConfigs(config, {files: [cliArgs.input]}); resolveConfig(config); } let inputFiles = config.files.map(file => path.resolve(file)); let isCpp = config.files.some(file => /\.cpp$/i.test(file)); let res, args, glueFile; args = ["--em-config", EM_CONFIG, "-s", "BINARYEN=1", "-O3"]; args.push(["-s", "NO_FILESYSTEM=1"]); args.push(["-s", "NO_EXIT_RUNTIME=1"]); args.push(["-s", "DISABLE_EXCEPTION_CATCHING=1"]); args.push(["-s", "BINARYEN_IMPRECISE=1"]); args.push(["-s", `VERBOSE=${config.options.VERBOSE}`]); args.push(["-s", `ALLOW_MEMORY_GROWTH=${config.options.ALLOW_MEMORY_GROWTH}`]); args.push(["-s", `SIDE_MODULE=${config.options.SIDE_MODULE}`]); args.push(["-s", `RELOCATABLE=${config.options.RELOCATABLE}`]); args.push(["-s", `EXPORTED_RUNTIME_METHODS=${quoteStringArray(config.options.EXPORTED_RUNTIME_METHODS)}`]); args.push(["-s", `EXPORTED_FUNCTIONS=${quoteStringArray(config.options.EXPORTED_FUNCTIONS)}`]); if (config.dependencies) { config.dependencies.forEach(dependency => { var jsWrapperPath = require.resolve(dependency); args.push("-I" + path.dirname(jsWrapperPath)); }); } if (isCpp) args.push("--std=c++11"); if (cliArgs.debuginfo) args.push("-g 3"); args.push(inputFiles); let outputFile = cliArgs.output ? path.resolve(cliArgs.output) : path.resolve(config.output || "a.wasm"); let extension = path.extname(outputFile) || '.wasm'; let removeUnneedOutput = extension.toLowerCase() !== '.js'; let baseOutputName = path.join(path.dirname(outputFile), (removeUnneedOutput ? "~tmp." : "") + path.basename(outputFile, extension)); args.push(["-o", baseOutputName + ".js"]); args = flatten(args); if (WASDK_DEBUG) console.log(EMCC + " " + args.join(" ")); res = spawnSync(EMCC, args, { stdio: [0, 1, 2] }); if (res.status !== 0) fail("Compilation error: " + res.error.toString()); let postfixes = [".wasm"]; if (!config.options.SIDE_MODULE) postfixes.push(".asm.js", ".js"); let outputFiles = postfixes.map(postfix => baseOutputName + postfix); if (!outputFiles.every(file => fs.existsSync(file))) fail("Compilation error."); if (removeUnneedOutput) { switch (extension.toLowerCase()) { case '.wasm': fs.renameSync(baseOutputName + '.wasm', outputFile); break; case '.wast': fs.writeFileSync(outputFile, dumpWasm(baseOutputName + '.wasm')); break; } postfixes.forEach(postfix => { if (fs.existsSync(baseOutputName + postfix)) fs.unlinkSync(baseOutputName + postfix); }); } } function getWasmSMCommandArgs(input) { var smAsNode = path.resolve(__dirname, '..', 'sm_as_node.js'); return flatten(['-f', smAsNode, path.join(__dirname, "wasm-sm.js"), input]); } function disassemble() { let input = path.resolve(cliArgs.input); let args = getWasmSMCommandArgs(input); let res = spawnSync(JS, args, { stdio: [0, 1, 2] }); if (res.status !== 0) fail("Disassembly error."); } function test() { let input = path.resolve("test/universe.wast"); let args = getWasmSMCommandArgs(input); let res = spawnSync(JS, args); if (res.status !== 0) fail("Disassembly error."); let out = res.stdout.toString(); if (out.indexOf("0x2a") < 0) fail("Can't find 42."); }
the_stack
import {Component, HostListener, OnDestroy, OnInit} from "@angular/core"; import {ActivatedRoute, Params} from "@angular/router"; import {ReportsService} from "./reports.service"; import {AppEvent, AppEventCode, AppService} from "../app.service"; import {TopNavService} from "../topnav.service"; import {ElasticSearchService} from "../elasticsearch.service"; import {loadingAnimation} from "../animations"; import {EveboxSubscriptionTracker} from "../subscription-tracker"; import {ApiService, ReportAggOptions} from "../api.service"; import {EveBoxProtoPrettyPrinter} from "../pipes/proto-pretty-printer.pipe"; import * as chartjs from "../shared/chartjs"; import * as moment from "moment"; import {finalize} from "rxjs/operators"; import {Observable} from "rxjs"; declare var Chart: any; @Component({ template: ` <div class="content" [@loadingState]="(loading > 0) ? 'true' : 'false'"> <br/> <loading-spinner [loading]="loading > 0"></loading-spinner> <div class="row"> <div class="col-md-6 col-sm-6"> <button type="button" class="btn btn-secondary" (click)="refresh()"> Refresh </button> </div> <div class="col-md-6 col-sm-6"> <evebox-filter-input [queryString]="queryString"></evebox-filter-input> </div> </div> <br/> <div class="row"> <div class="col"> <div *ngIf="showCharts" style="height: 250px;"> <canvas id="eventsOverTimeChart" style="padding-top: 0px;"></canvas> </div> <div *ngIf="interval != ''" class="dropdown" style="text-align:center;"> <span class="mx-auto" data-toggle="dropdown"> <small><a href="#">{{interval}} intervals</a></small> </span> <div class="dropdown-menu"> <a class="dropdown-item" href="#" (click)="changeHistogramInterval(item.value)" *ngFor="let item of histogramIntervals">{{item.msg}}</a> </div> </div> </div> </div> <br/> <div *ngIf="showCharts" class="row mb-4"> <div class="col-lg mb-4 mb-lg-0"> <div class="card"> <div class="card-header">Traffic ID</div> <div class="card-body"> <canvas id="trafficIdChart"></canvas> </div> </div> </div> <div class="col-lg"> <div class="card"> <div class="card-header">Traffic Labels</div> <div class="card-body"> <canvas id="trafficLabelChart"></canvas> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <report-data-table *ngIf="topClientsByFlows" title="Top Clients By Flow Count" [rows]="topClientsByFlows" [headers]="['Flows', 'Client IP']"></report-data-table> </div> <div class="col-md-6"> <report-data-table *ngIf="topServersByFlows" title="Top Servers By Flow Count" [rows]="topServersByFlows" [headers]="['Flows', 'Server IP']"></report-data-table> </div> </div> <br/> <div *ngIf="topFlowsByAge" class="card"> <div class="card-header"> <b>Top Flows by Age</b> </div> <eveboxEventTable2 [rows]="topFlowsByAge" [showEventType]="false" [showActiveEvent]="false"></eveboxEventTable2> </div> <br/> </div>`, animations: [ loadingAnimation, ] }) export class FlowReportComponent implements OnInit, OnDestroy { topClientsByFlows: any[]; topServersByFlows: any[]; topFlowsByAge: any[]; loading = 0; queryString = ""; subTracker: EveboxSubscriptionTracker = new EveboxSubscriptionTracker(); private charts: any = {}; histogramIntervals: any[] = [ {value: "1s", msg: "1 second"}, {value: "1m", msg: "1 minute"}, {value: "5m", msg: "5 minute"}, {value: "15m", msg: "15 minutes"}, {value: "1h", msg: "1 hour"}, {value: "6h", msg: "6 hours"}, {value: "12h", msg: "12 hours"}, {value: "1d", msg: "1 day (24 hours)"}, ]; public interval: string = null; private range: number = null; // A boolean to toggle to remove that chart elements and re-add them // to fix issues with ChartJS resizing. showCharts = true; constructor(private appService: AppService, private route: ActivatedRoute, private reportsService: ReportsService, private topNavService: TopNavService, private api: ApiService, private elasticsearch: ElasticSearchService, private protoPrettyPrinter: EveBoxProtoPrettyPrinter) { } ngOnInit() { this.range = this.topNavService.getTimeRangeAsSeconds(); this.subTracker.subscribe(this.route.queryParams, (params: Params) => { this.queryString = params["q"] || ""; this.refresh(); }); this.subTracker.subscribe(this.appService, (event: AppEvent) => { if (event.event == AppEventCode.TIME_RANGE_CHANGED) { this.range = this.topNavService.getTimeRangeAsSeconds(); this.interval = null; this.refresh(); } }); } ngOnDestroy() { this.subTracker.unsubscribe(); } load(fn: any) { this.loading++; fn().then(() => { }).catch((_) => { }).then(() => { this.loading--; }); } private renderChart(id: string, options: any) { let element = document.getElementById(id); if (!element) { console.log(`No element with ID ${id}`); return; } let ctx = (<HTMLCanvasElement>element).getContext("2d"); if (this.charts[id]) { this.charts[id].chart.destroy(); } this.charts[id] = { chart: new Chart(ctx, options), id: id, options: options, } } @HostListener("window:resize", ["$event"]) private onResize(event) { this.showCharts = false; setTimeout(() => { this.showCharts = true; setTimeout(() => { for (const key of Object.keys(this.charts)) { this.renderChart(this.charts[key].id, this.charts[key].options); } }) }, 0); } private refreshEventsOverTime() { let displayUnit = "minute"; if (!this.interval) { this.interval = "1d"; if (this.range == 0) { displayUnit = "day"; } else if (this.range <= 60) { this.interval = "1s"; displayUnit = "second"; } else if (this.range <= 3600) { this.interval = "1m"; displayUnit = "minute"; } else if (this.range <= (3600 * 3)) { this.interval = "5m"; displayUnit = "minute"; } else if (this.range <= 3600 * 24) { this.interval = "15m"; displayUnit = "hour"; } else if (this.range <= 3600 * 24 * 3) { this.interval = "1h"; displayUnit = "hour"; } else if (this.range <= 3600 * 24 * 7) { this.interval = "1h"; displayUnit = "hour"; } } console.log(`interval: ${this.interval}, displayUnit: ${displayUnit}`); let histogramOptions: any = { appProto: true, queryString: this.queryString, interval: this.interval, }; if (this.range > 0) { histogramOptions.timeRange = `${this.range}s`; } this.wrap(this.api.flowHistogram(histogramOptions)) .subscribe((response) => { let labels = []; let eventCounts = []; let protos = []; response.data.forEach((elem) => { for (let proto in elem.app_proto) { if (protos.indexOf(proto) < 0) { protos.push(proto); } } }); let data = {}; let colours = chartjs.getColourPalette(protos.length + 1); let totals = []; response.data.forEach((elem) => { let proto_sum = 0; for (let proto of protos) { if (!data[proto]) { data[proto] = []; } if (proto in elem.app_proto) { let val = elem.app_proto[proto]; data[proto].push(val); proto_sum += val; } else { data[proto].push(0); } } labels.push(moment(elem.key).toDate()); totals.push(elem.events); eventCounts.push(elem.events - proto_sum); }); let datasets: any[] = [{ label: "Other", backgroundColor: colours[0], borderColor: colours[0], data: eventCounts, fill: false, }]; let i = 1; for (let proto of protos) { let label = proto; if (proto === "failed") { label = "Unknown"; } else { label = this.protoPrettyPrinter.transform(proto, null); } datasets.push({ label: label, backgroundColor: colours[i], borderColor: colours[i], fill: false, data: data[proto], }); i += 1; } let chartOptions = { type: "bar", data: { labels: labels, datasets: datasets, }, options: { title: { display: true, text: "Flow Events Over Time", padding: 0, }, legend: { position: "right", }, scales: { xAxes: [ { display: true, type: "time", stacked: true, time: { unit: displayUnit, } } ], yAxes: [ { gridLines: false, stacked: true, ticks: { padding: 5, } } ] }, maintainAspectRatio: false, responsive: true, tooltips: { callbacks: { footer: function (a, b) { let index = a[0].index; return `Total: ${totals[index]}`; } } } } }; this.renderChart("eventsOverTimeChart", chartOptions); }); } changeHistogramInterval(interval) { this.interval = interval; this.refreshEventsOverTime(); } refresh() { this.refreshEventsOverTime(); let aggOptions: ReportAggOptions = { timeRange: this.range, eventType: "flow", size: 10, queryString: this.queryString, }; this.load(() => { return this.api.reportAgg("src_ip", aggOptions) .then((response: any) => { this.topClientsByFlows = response.data; }); }); this.load(() => { return this.api.reportAgg("dest_ip", aggOptions) .then((response: any) => { this.topServersByFlows = response.data; }); }); this.load(() => { return this.api.reportAgg("traffic.id", aggOptions) .then((response: any) => { let labels = response.data.map((e) => e.key); let data = response.data.map((e) => e.count); if (response.missing && response.missing > 0) { labels.push("<no-id>"); data.push(response.missing); } if (response.other && response.other > 0) { labels.push("<other>"); data.push(response.other); } let colours = chartjs.getColourPalette(labels.length + 1); let config = { type: "pie", data: { datasets: [ { data: data, backgroundColor: colours, } ], labels: labels, }, options: { responsive: true, } }; this.renderChart("trafficIdChart", config); }); }); this.load(() => { return this.api.reportAgg("traffic.label", aggOptions) .then((response: any) => { let labels = response.data.map((e) => e.key); let data = response.data.map((e) => e.count); if (response.missing && response.missing > 0) { labels.push("<unlabeled>"); data.push(response.missing); } if (response.other && response.other > 0) { labels.push("<other>"); data.push(response.other); } let colours = chartjs.getColourPalette(labels.length + 1); let options = { type: "pie", data: { datasets: [ { data: data, backgroundColor: colours, } ], labels: labels, }, }; this.renderChart("trafficLabelChart", options); }); }); this.wrap(this.api.eventQuery({ queryString: this.queryString, eventType: "flow", size: 10, timeRange: this.range, sortBy: "flow.age", sortOrder: "desc", })).subscribe((response) => { this.topFlowsByAge = response.data; }); } private wrap(observable: Observable<any>) { this.loading++; return observable.pipe(finalize(() => { this.loading--; })); } }
the_stack
import * as React from 'react'; import { IAnalysisDialogContentProps } from './IAnalysisDialogContentProps'; import { IAnalysisDialogContentState } from './IAnalysisDialogContentState'; import styles from './AnalysisDialogContent.module.scss'; import { css } from "@uifabric/utilities/lib/css"; // Used for localized text import * as strings from 'ProfilePhotoEditorWebPartStrings'; import { Text } from '@microsoft/sp-core-library'; // Used to determine if we should be making real calls to APIs or just mock calls import { Environment, EnvironmentType } from '@microsoft/sp-core-library'; // Stuff we use for the dialog import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { MessageBar, MessageBarType } from 'office-ui-fabric-react'; import { Image, ImageFit } from 'office-ui-fabric-react/lib/Image'; import { Panel } from 'office-ui-fabric-react/lib/Panel'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Shimmer } from 'office-ui-fabric-react/lib/Shimmer'; import { ProgressIndicator } from 'office-ui-fabric-react/lib/ProgressIndicator'; // Stuff we use for analysis results import { IAnalysisService, AnalysisService, MockAnalysisService } from '../../../../services/AnalysisServices'; import { AnalyzeImageInStreamResponse, ImageTag } from '@azure/cognitiveservices-computervision/esm/models'; import AnalysisChecklist from '../AnalysisChecklist/AnalysisChecklist'; // This is used if you use the graph client to update pictures import { MSGraphClient } from '@microsoft/sp-http'; export class AnalysisDialogContent extends React.Component<IAnalysisDialogContentProps, IAnalysisDialogContentState> { constructor(props: IAnalysisDialogContentProps) { super(props); this.state = { isAnalyzing: true, analysis: undefined, isValid: false, isSubmitted: false }; } /** * When the dialog is loaded, perform the analysis */ public async componentDidMount() { if (this.state.isAnalyzing) { const { azureKey, azureEndpoint, photoRequirements } = this.props; // Get the analysis service let service: IAnalysisService = undefined; if (Environment.type === EnvironmentType.Local || Environment.type === EnvironmentType.Test) { //Running on Unit test environment or local workbench service = new MockAnalysisService(azureKey, azureEndpoint); } else if (Environment.type === EnvironmentType.SharePoint) { //Modern SharePoint page service = new AnalysisService(azureKey, azureEndpoint); } // Perform the analysis const analysis: AnalyzeImageInStreamResponse = await service.AnalyzeImage(this.props.imageUrl); // Evaluate analysis against requirements // Is this a portrait? const isPortrait: boolean = analysis && analysis.categories && analysis.categories.filter(c => c.name === "people_portrait").length > 0; // If the portrait valid? const isPortraitValid: boolean = photoRequirements.requirePortrait ? isPortrait : true; // is there only one person in the photo? const onlyOnePersonValid: boolean = analysis.faces.length === 1; // Is this a clipart? const isClipartValid: boolean = photoRequirements.allowClipart ? true : analysis.imageType.clipArtType === 0; // Is this a line drawing? const isLinedrawingValid: boolean = photoRequirements.allowLinedrawing ? true : analysis.imageType.lineDrawingType === 0; // Are we looking at naughty pictures? const isAdultValid: boolean = photoRequirements.allowAdult ? true : !analysis.adult.isAdultContent; const isRacyValid: boolean = photoRequirements.allowRacy ? true : !analysis.adult.isRacyContent; const isGoryValid: boolean = photoRequirements.allowGory ? true : !analysis.adult.isGoryContent; // Verify against all forbidden keywords let invalidKeywords: string[] = []; if (photoRequirements.forbiddenKeywords && photoRequirements.forbiddenKeywords.length > 0) { photoRequirements.forbiddenKeywords.forEach((keyword: string) => { if (analysis.tags.filter((tag: ImageTag) => { return keyword.toLowerCase() === tag.name; }).length > 0) { invalidKeywords.push(keyword); } }); } // Did we find forbidden keywords const keywordsValid: boolean = invalidKeywords.length < 1; // Look for celebrities let celebName: string = undefined; const categories = analysis && analysis.categories && analysis.categories.filter(c => c.detail !== undefined && c.detail.celebrities !== undefined); if (categories && categories.length > 0) { // Get the first celebrity celebName = categories[0] && categories[0].detail && categories[0].detail.celebrities[0] && categories[0].detail.celebrities[0].name; } // Photo is valid if it meets all requirements const isValid: boolean = isPortraitValid && onlyOnePersonValid && isClipartValid && isLinedrawingValid && isAdultValid && isRacyValid && isGoryValid && keywordsValid; // Set the state so we can refresh the status this.setState({ isAnalyzing: false, analysis, isValid, isPortrait, isPortraitValid, onlyOnePersonValid, isClipartValid, isLinedrawingValid, isAdultValid, isRacyValid, isGoryValid, keywordsValid, invalidKeywords, celebrity: celebName }); } } public render(): JSX.Element { const { analysis, isAnalyzing, isValid, isPortrait, isPortraitValid, isAdultValid, isRacyValid, isGoryValid, isClipartValid, isLinedrawingValid, onlyOnePersonValid, invalidKeywords, keywordsValid, celebrity } = this.state; if (analysis !== undefined) { console.log("Analysis", analysis); } return ( <Panel className={styles.analysisDialog} isOpen={true} onDismiss={(ev?: React.SyntheticEvent<HTMLElement, Event>) => this.onDismiss(ev)} isLightDismiss={true} onRenderFooterContent={this.onRenderFooterContent} > <h1 className={styles.panelHeader}>{strings.PanelTitle}</h1> <Image className={styles.thumbnailImg} imageFit={ImageFit.centerContain} src={this.props.imageUrl} /> {isAnalyzing && <div className={styles.diode}> <div className={styles.laser}></div> </div> } {isAnalyzing && <ProgressIndicator label={strings.AnalyzingLabel} /> } <div className={styles.analysisOutcome}> <div className={styles.section}> <Label><strong>{strings.DescriptionLabel}</strong></Label> {isAnalyzing ? <Shimmer /> : analysis.description && analysis.description.captions && analysis.description.captions.length > 0 && <span>{analysis.description.captions[0].text}</span>} </div> <div className={styles.section}><Label><strong>{strings.EstimatedAgeLabel}</strong></Label> {isAnalyzing ? <Shimmer width="10%" /> : analysis.faces.length > 0 && <span>{analysis.faces[0].age}</span>} </div> <div className={styles.section}><Label><strong>{strings.GenderLabel}</strong></Label> {isAnalyzing ? <Shimmer width="20%" /> : analysis.faces.length > 0 && <span>{analysis.faces[0].gender}</span>} </div> </div> {!isAnalyzing && <div className={styles.iconContainer} ><Icon iconName={isValid ? "CheckMark" : "StatusCircleErrorX"} className={css(styles.icon, isValid ? styles.iconGood : styles.iconBad)} /></div> } {!isAnalyzing && celebrity !== undefined && <div><p>{Text.format(strings.YouLookLikeACelebrity, celebrity)}</p></div> } {!isAnalyzing && isValid && <div>{strings.AnalysisGoodLabel}</div> } {!isAnalyzing && !isValid && <div>{strings.AnalysisBadLabel}</div> } {!isAnalyzing && <div className={styles.section}> <ul className={styles.analysisChecklist}> <AnalysisChecklist title={strings.PortraitLabel} value={isPortrait ? strings.YesLabel : strings.NoLabel} isValid={isPortraitValid} /> <AnalysisChecklist title={strings.NumberOfFacesDetectedLabel} value={`${analysis.faces.length}`} isValid={onlyOnePersonValid} /> <AnalysisChecklist title={strings.ClipartLabel} value={analysis.imageType.clipArtType > 0 ? strings.YesLabel : strings.NoLabel} isValid={isClipartValid} /> <AnalysisChecklist title={strings.LineDrawingLabel} value={analysis.imageType.lineDrawingType > 0 ? strings.YesLabel : strings.NoLabel} isValid={isLinedrawingValid} /> <AnalysisChecklist title={strings.RacyLabel} value={analysis.adult.isRacyContent ? strings.YesLabel : strings.NoLabel} isValid={isRacyValid} /> <AnalysisChecklist title={strings.AdultLabel} value={analysis.adult.isAdultContent ? strings.YesLabel : strings.NoLabel} isValid={isAdultValid} /> <AnalysisChecklist title={strings.GoryLabel} value={analysis.adult.isGoryContent ? strings.YesLabel : strings.NoLabel} isValid={isGoryValid} /> <AnalysisChecklist title={strings.ForbiddenKeywordsLabel} value={keywordsValid ? strings.NoKeywords : invalidKeywords.join(', ')} isValid={keywordsValid} /> </ul> </div> } {!isAnalyzing && isValid && <div>{strings.PanelInstructionsLabel}<strong>{strings.UpdateButtonLabel}</strong>.</div> } {this.state.isSubmitted && <MessageBar messageBarType={MessageBarType.success} isMultiline={false} > {strings.SuccessMessage} </MessageBar> } </Panel> ); } private onRenderFooterContent = (): JSX.Element => { return ( <div> <PrimaryButton onClick={(_ev) => this.onUpdateProfilePhoto()} style={{ marginRight: '8px' }} disabled={this.state.isValid !== true}> {strings.UpdateButtonLabel} </PrimaryButton> <DefaultButton onClick={(_ev) => this.onDismiss()}>{strings.CancelButtonLabel}</DefaultButton> </div> ); } private onUpdateProfilePhoto = async (_ev?: React.SyntheticEvent<HTMLElement, Event>) => { // Get image array buffer const profileBlob: Blob = this.props.blob; // Submit using the approach you want this.updateProfilePicUsingGraph(profileBlob); //this.updateProfilePicUsingPnP(profileBlob); } // private async updateProfilePicUsingPnP(blob: Blob) { // pnpSetup({ // spfxContext: this.props.context // }); // console.log("Update profile pic using PnP", blob); // const response = await sp.profiles.setMyProfilePic(blob); // console.log("Profile property Updated", response); // this.setState({ // isSubmitted: true // }); // } // Update photo using Graph. // See https://docs.microsoft.com/en-us/graph/api/profilephoto-update?view=graph-rest-1.0&tabs=http private async updateProfilePicUsingGraph(blob: Blob) { this.props.context.msGraphClientFactory .getClient().then((client: MSGraphClient) => { client .api("me/photo/$value") .version("v1.0").header("Content-Type", blob.type).put(blob, (error, _res) => { if (error) { console.log("Error updating profile", error); } else { console.log("Profile property Updated"); this.setState({ isSubmitted: true }); } }); }); } private onDismiss = (_ev?: React.SyntheticEvent<HTMLElement, Event>) => { this.props.onDismiss(); } }
the_stack
import * as _ from 'lodash'; import * as ui_constants from '../../interfaces/ui'; import * as background_ui from './background_ui'; import CoreConnector from './core_connector'; import * as uproxy_core_api from '../../interfaces/uproxy_core_api'; import * as browser_api from '../../interfaces/browser_api'; import ProxyAccessMode = browser_api.ProxyAccessMode; import BrowserAPI = browser_api.BrowserAPI; import ProxyDisconnectInfo = browser_api.ProxyDisconnectInfo; import * as net from '../../lib/net/net.types'; import * as user_module from './user'; import User = user_module.User; import * as social from '../../interfaces/social'; import * as Constants from './constants'; import * as translator_module from './translator'; import * as network_options from '../../generic/network-options'; import * as model from './model'; import * as dialogs from './dialogs'; import * as jsurl from 'jsurl'; // TODO: remove uparams as it doesn't work with ES6 imports and TypeScript, // see https://github.com/uProxy/uproxy/issues/2782 import uparams = require('uparams'); import * as crypto from 'crypto'; import * as jdenticon from 'jdenticon'; var NETWORK_OPTIONS = network_options.NETWORK_OPTIONS; // Filenames for icons. // Two important things about using these strings: // 1) When updating the icon strings below, default values in the Chrome // manifests and Firefox main.js should also be changed to match. // 2) These are only the suffixes of the icon names. Because we have // different sizes of icons, the actual filenames have the dimension // as a prefix. E.g. "19_online.gif" for the 19x19 pixel version. export interface UserCategories { getTab :string; shareTab :string; } export interface NotificationData { mode :string; network :string; user :string; unique ?:string; } interface PromiseCallbacks { fulfill :Function; reject :Function; } export function getImageData(userId: string, oldImageData: string, newImageData: string): string { if (newImageData) { return newImageData; } else if (oldImageData) { // This case is hit when we've already generated a jdenticon for a user // who doesn't have any image in uProxy core. return oldImageData; } // Extra single-quotes are needed for CSS/Polymer parsing. This is safe // as long as jdenticon only uses '"' in the generated code... // The size is arbitrarily set to 100 pixels. SVG is scalable and our CSS // scales the image to fit the space, so this parameter has no effect. // We must also replace # with %23 for Firefox support. const userIdHash = crypto.createHash('md5').update(userId).digest('hex'); return '\'data:image/svg+xml;utf8,' + jdenticon.toSvg(userIdHash, 100).replace(/#/g, '%23') + '\''; } /* Suppress `error TS2339: Property 'languages' does not exist on type * 'Navigator'` triggered by `navigator.languages` reference below. */ declare var navigator :any; /** * The User Interface class. * * Keeps persistent state between the popup opening and closing. * Manipulates the payloads received from UPDATES from the Core in preparation * for UI interaction. * Any COMMANDs from the UI should be directly called from the 'core' object. */ export class UserInterface implements ui_constants.UiApi { public view :ui_constants.View; public model = new model.Model(); /* Instance management */ // Instance you are getting access from. Null if you are not getting access. public instanceTryingToGetAccessFrom :string = null; private instanceGettingAccessFrom_ :string = null; // The instances you are giving access to. // Remote instances to add to this set are received in messages from Core. public instancesGivingAccessTo :{[instanceId :string] :boolean} = {}; private mapInstanceIdToUser_ :{[instanceId :string] :User} = {}; // If non-null, the ID of the instance from which we are presently // disconnected. Set by syncDisconnectedState_ public disconnectedWhileProxying :string = null; /* Getting and sharing */ public isSharingDisabled :boolean = false; // Set by syncUser. Used to identify sessions in failure logs. public lastFailedProxyingId: string; /* Translation */ public i18n_t = translator_module.i18n_t; public i18n_setLng = translator_module.i18n_setLng; public i18nSanitizeHtml = translator_module.i18nSanitizeHtml; /* About this uProxy installation */ public availableVersion :string = null; // Please note that this value is updated periodically so may not reflect current reality. private isConnectedToCellular_ :boolean = false; // User-initiated proxy access mode. Set when starting the proxy in order to // stop it accordingly, and to automatically restart proxying in case of a // disconnect. private proxyAccessMode_: ProxyAccessMode = ProxyAccessMode.NONE; /** * UI must be constructed with hooks to Notifications and Core. * Upon construction, the UI installs update handlers on core. */ constructor( public core :CoreConnector, public browserApi :BrowserAPI, public backgroundUi: background_ui.BackgroundUi) { this.updateView_(); var firefoxMatches = navigator.userAgent.match(/Firefox\/(\d+)/); if (firefoxMatches) { if (parseInt(firefoxMatches[1], 10) === 37) { this.isSharingDisabled = true; } } core.on('core_connect', () => { this.updateView_(); core.getFullState() .then(this.updateInitialState); }); core.on('core_disconnect', () => { // When disconnected from the app, we should show the browser specific page // that shows the "app missing" message. this.view = ui_constants.View.BROWSER_ERROR; if (this.isGettingAccess()) { this.stoppedGetting({instanceId: null, error: true}); } }); // Add or update the online status of a network. core.onUpdate(uproxy_core_api.Update.NETWORK, this.syncNetwork_); // Attach handlers for USER updates. core.onUpdate(uproxy_core_api.Update.USER_SELF, this.syncUserSelf_); core.onUpdate(uproxy_core_api.Update.USER_FRIEND, this.syncUser); core.onUpdate(uproxy_core_api.Update.REMOVE_FRIEND, this.removeFriend); var checkConnectivityIntervalId: NodeJS.Timer; core.onUpdate(uproxy_core_api.Update.START_GIVING_TO_FRIEND, (instanceId :string) => { // TODO (lucyhe): Update instancesGivingAccessTo before calling // startGivingInUi so that isGiving() is updated as early as possible. if (!this.isGivingAccess()) { this.startGivingInUi(); } this.instancesGivingAccessTo[instanceId] = true; this.updateSharingStatusBar_(); var user = this.mapInstanceIdToUser_[instanceId]; user.isGettingFromMe = true; this.showNotification(translator_module.i18n_t('STARTED_PROXYING', { name: user.name }), { mode: 'share', network: user.network.name, user: user.userId }); checkConnectivityIntervalId = setInterval( this.notifyUserIfConnectedToCellular_, 5 * 60 * 1000); }); core.onUpdate(uproxy_core_api.Update.STOP_GIVING_TO_FRIEND, (instanceId :string) => { var isGettingFromMe = false; var user = this.mapInstanceIdToUser_[instanceId]; // only show a notification if we knew we were prokying if (typeof this.instancesGivingAccessTo[instanceId] !== 'undefined') { this.showNotification(translator_module.i18n_t('STOPPED_PROXYING', { name: user.name }), { mode: 'share', network: user.network.name, user: user.userId }); } delete this.instancesGivingAccessTo[instanceId]; if (!this.isGivingAccess()) { this.stopGivingInUi(); } // Update user.isGettingFromMe for (var i = 0; i < user.allInstanceIds.length; ++i) { if (this.instancesGivingAccessTo[user.allInstanceIds[i]]) { isGettingFromMe = true; break; } } user.isGettingFromMe = isGettingFromMe; this.updateSharingStatusBar_(); if (checkConnectivityIntervalId && Object.keys(this.instancesGivingAccessTo).length === 0) { clearInterval(checkConnectivityIntervalId); checkConnectivityIntervalId = undefined; this.isConnectedToCellular_ = false; } }); core.onUpdate(uproxy_core_api.Update.FAILED_TO_GIVE, (info:uproxy_core_api.FailedToGetOrGive) => { console.error('proxying attempt ' + info.proxyingId + ' failed (giving)'); let toastMessage = translator_module.i18n_t('UNABLE_TO_SHARE_WITH', { name: info.name }); this.backgroundUi.showToast(toastMessage, false, true); this.lastFailedProxyingId = info.proxyingId; }); core.onUpdate(uproxy_core_api.Update.CORE_UPDATE_AVAILABLE, this.coreUpdateAvailable_); core.onUpdate( uproxy_core_api.Update.REFRESH_GLOBAL_SETTINGS, (globalSettings: uproxy_core_api.GlobalSettings) => { this.model.updateGlobalSettings(globalSettings); }); core.onUpdate(uproxy_core_api.Update.REPROXY_ERROR, () => { this.model.reproxyError = true; var intervalId = setInterval(() => { if (!this.model.reproxyError) { // Reproxy fixed clearInterval(intervalId); return; } // Check reproxy this.core.checkReproxy(this.model.globalSettings.reproxy.socksEndpoint.port) .then((check :uproxy_core_api.ReproxyCheck) => { if (check === uproxy_core_api.ReproxyCheck.TRUE) { this.model.reproxyError = false; } }); }, 10000); }); core.onUpdate(uproxy_core_api.Update.REPROXY_WORKING, () => { this.model.reproxyError = false; }); browserApi.on('inviteUrlData', this.handleInvite); browserApi.on('notificationClicked', this.handleNotificationClick); browserApi.on('proxyDisconnected', this.proxyDisconnected); browserApi.on('promoIdDetected', this.setActivePromoId); browserApi.on('translationsRequest', this.handleTranslationsRequest); browserApi.on('globalSettingsRequest', this.handleGlobalSettingsRequest); browserApi.on('backbutton', () => { this.fireSignal('backbutton'); }); backgroundUi.registerAsFakeBackground(this.panelMessageHandler); core.getFullState() .then(this.updateInitialState) .then(this.browserApi.handlePopupLaunch); } public panelMessageHandler = (name: string, data: any) => { /* * This will handle a subset of the signals for the actual background UI, * we will try to handle most of the signals in the actual background * though */ switch(name) { /* holding for more operations as needed */ } } private notifyUserIfConnectedToCellular_ = () => { this.browserApi.isConnectedToCellular().then((isConnectedToCellular) => { if (isConnectedToCellular && !this.isConnectedToCellular_) { this.showNotification('Your friend is proxying through your cellular network which could' + ' incur charges.'); } this.isConnectedToCellular_ = isConnectedToCellular; }, function(reason) { console.log('Could not check if connected to cellular or not. reason: ' + reason); }); } public fireSignal = (signalName :string, data ?:Object) => { this.backgroundUi.fireSignal(signalName, data); } public getConfirmation(heading :string, text :string, dismissButtonText ?:string, fulfillButtonText ?:string): Promise<void> { return this.backgroundUi.openDialog(dialogs.getConfirmationDialogDescription( heading, text, dismissButtonText, fulfillButtonText)); } public getUserInput(heading :string, message :string, placeholderText :string, defaultValue :string, buttonText :string) : Promise<string> { return this.backgroundUi.openDialog(dialogs.getInputDialogDescription( heading, message, placeholderText, defaultValue, buttonText)); } public showDialog(heading :string, message :string, buttonText ?:string, displayData ?:string) { return this.backgroundUi.openDialog(dialogs.getMessageDialogDescription( heading, message, buttonText, displayData)); } public showNotification = (text :string, data ?:NotificationData) => { data = data ? data : { mode: '', network: '', user: '' }; // non-uniqu but existing tags prevent the notification from displaying in some cases data.unique = Math.floor(Math.random() * 1E10).toString(); try { var tag = JSON.stringify(data); } catch (e) { console.error('Could not encode data to tag'); tag = data.unique; } this.browserApi.showNotification(text, tag); } public handleNotificationClick = (tag :string) => { // we want to bring uProxy to the front regardless of the info this.bringUproxyToFront(); try { var data = JSON.parse(tag); if (data.network && data.user) { var network = this.model.getNetwork(data.network); if (network) { var contact = this.model.getUser(network, data.user); } } if (data.mode === 'get') { this.updateGlobalSetting('mode', ui_constants.Mode.GET); if (contact) { contact.getExpanded = true; } } else if (data.mode === 'share' && !this.isSharingDisabled) { this.updateGlobalSetting('mode', ui_constants.Mode.SHARE); if (contact) { contact.shareExpanded = true; } } } catch (e) { console.warn('error getting information from notification tag'); } } private updateGettingStatusBar_ = () => { var gettingStatus: string = null; if (this.instanceGettingAccessFrom_) { gettingStatus = this.i18n_t('GETTING_ACCESS_FROM', { name: this.mapInstanceIdToUser_[this.instanceGettingAccessFrom_].name }); } this.fireSignal('update-getting-status', gettingStatus); } private updateSharingStatusBar_ = () => { // TODO: localize this - may require simpler formatting to work // in all languages. var sharingStatus: string = null; var instanceIds = Object.keys(this.instancesGivingAccessTo); if (instanceIds.length === 1) { sharingStatus = this.i18n_t('SHARING_ACCESS_WITH_ONE', { name: this.mapInstanceIdToUser_[instanceIds[0]].name }); } else if (instanceIds.length === 2) { sharingStatus = this.i18n_t('SHARING_ACCESS_WITH_TWO', { name1: this.mapInstanceIdToUser_[instanceIds[0]].name, name2: this.mapInstanceIdToUser_[instanceIds[1]].name }); } else if (instanceIds.length > 2) { sharingStatus = this.i18n_t('SHARING_ACCESS_WITH_MANY', { name: this.mapInstanceIdToUser_[instanceIds[0]].name, numOthers: (instanceIds.length - 1) }); } this.fireSignal('update-sharing-status', sharingStatus); } private addUser_ = (tokenObj :social.InviteTokenData, showConfirmation :boolean) : Promise<void> => { try { var userName = tokenObj.userName; var networkName = tokenObj.networkName; } catch(e) { return Promise.reject('Error parsing invite token'); } var getConfirmation = Promise.resolve(); if (showConfirmation) { if (networkName === 'Cloud') { userName = this.i18n_t('CLOUD_VIRTUAL_MACHINE'); } var confirmationMessage = this.i18n_t('ACCEPT_INVITE_CONFIRMATION', { name: userName }); getConfirmation = this.getConfirmation('', confirmationMessage); } return getConfirmation.then(() => { var socialNetworkInfo :social.SocialNetworkInfo = { name: networkName, userId: '' /* The current user's ID will be determined by the core. */ }; return this.core.acceptInvitation( {network: socialNetworkInfo, tokenObj: tokenObj}); }).catch((e) => { // The user did not confirm adding their friend, not an error. return; }) } private parseInviteUrl_ = (invite :string) : social.InviteTokenData => { try { var params = uparams(invite); if (params && params['networkName']) { // New style invite using URL params. var permission :any; if (params['permission']) { permission = jsurl.parse(params['permission']); } return { v: parseInt(params['v'], 10), networkData: jsurl.parse(params['networkData']), networkName: params['networkName'], userName: params['userName'], permission: permission, userId: params['userId'], // undefined if no permission instanceId: params['instanceId'], // undefined if no permission } } else { // Old v1 invites are base64 encoded JSON var lastNonCodeCharacter = Math.max(invite.lastIndexOf('/'), invite.lastIndexOf('#')); var token = invite.substring(lastNonCodeCharacter + 1); // Removes any non base64 characters that may appear, e.g. "%E2%80%8E" token = token.match('[A-Za-z0-9+/=_]+')[0]; var parsedObj = JSON.parse(atob(token)); var networkData = parsedObj.networkData; if (typeof networkData === 'object' && networkData.networkData) { // Firebase invites have a nested networkData string within a // networkData object. TODO: move Firebase to use v2 invites. networkData = networkData.networkData; } return { v: 1, networkData: networkData, networkName: parsedObj.networkName, userName: parsedObj.userName, permission: parsedObj.permission, userId: parsedObj.userId, instanceId: parsedObj.instanceId, }; } } catch(e) { return null; } } public handleInvite = (invite :string) : Promise<void> => { var showTokenError = () => { this.showDialog('', this.i18n_t('INVITE_ERROR')); }; var tokenObj = this.parseInviteUrl_(invite); if (!tokenObj) { showTokenError(); return; } var userName = tokenObj.userName; var networkName = tokenObj.networkName; if (networkName == 'Cloud') { // Log into cloud if needed. let loginPromise = Promise.resolve(); if (!this.model.getNetwork('Cloud')) { loginPromise = this.login('Cloud'); } return loginPromise.then(() => { // Cloud contacts only appear on the GET tab. this.setMode(ui_constants.Mode.GET); // Don't show an additional confirmation for Cloud. return this.addUser_(tokenObj, false).catch(showTokenError); }); } if (this.model.getNetwork(networkName)) { // User is already logged into the right network (other than Cloud). return this.addUser_(tokenObj, true).catch(showTokenError); } // loginPromise should resolve when the use is logged into networkName. let loginPromise :Promise<void>; if (networkName == 'Quiver') { // Show user confirmation for Quiver login, where they can enter their // Quiver user name. var message = this.i18n_t('UPROXY_NETWORK_INVITE_LOGIN_MESSAGE', {name: userName }); loginPromise = this.loginToQuiver(message); } else { // All networks other than Quiver and Cloud. var confirmationTitle = this.i18n_t('LOGIN_REQUIRED_TITLE'); var confirmationMessage = this.i18n_t('LOGIN_REQUIRED_MESSAGE', { network: this.getNetworkDisplayName(networkName), name: userName }); loginPromise = this.getConfirmation(confirmationTitle, confirmationMessage) .then(() => { return this.login(networkName).then(() => { // For networks other than Quiver and Cloud, login will open an // OAuth tab. We need to return to the roster and re-open the uProxy // popup. this.view = ui_constants.View.ROSTER; this.bringUproxyToFront(); }); }); } return loginPromise.then(() => { // User already saw a confirmation when they logged into the network, // don't show an additional confirmation. return this.addUser_(tokenObj, false).catch(showTokenError); }); } public loginToQuiver = (message ?:string) : Promise<void> => { if (message) { message += '<p>' + this.i18n_t('QUIVER_LOGIN_TEXT') + '</p>'; } else { message = this.i18n_t('QUIVER_LOGIN_TEXT'); } return this.getUserInput( this.i18n_t('UPROXY_NETWORK_LOGIN_TITLE'), message || '', this.i18n_t('UPROXY_NETWORK_CHOOSE_A_USER_NAME'), this.model.globalSettings.quiverUserName, this.i18n_t('UPROXY_NETWORK_SIGN_IN')) .then((quiverUserName :string) => { this.updateGlobalSetting('quiverUserName', quiverUserName); return this.login('Quiver', quiverUserName); }); } public proxyDisconnected = (info?:ProxyDisconnectInfo) => { if (this.isGettingAccess()) { this.stopGettingFromInstance(this.instanceGettingAccessFrom_); if (info && info.deliberate) { return; } this.fireSignal('open-proxy-error'); this.bringUproxyToFront(); } } public handleTranslationsRequest = (keys :string[], callback ?:Function) => { var vals :{[s :string]: string;} = {}; for (let key of keys) { vals[key] = this.i18n_t(key); } this.browserApi.respond(vals, callback, 'translations'); } public handleGlobalSettingsRequest = (callback ?:Function) => { this.browserApi.respond(this.model.globalSettings, callback, 'globalSettings'); } public setActivePromoId = (promoId :string) => { this.updateGlobalSetting('activePromoId', promoId); } /** * Takes all actions required when getting stops, including removing proxy * indicators from the UI. * If user didn't end proxying, so if proxy session ended because of some * unexpected reason, user should be asked before reverting proxy settings. * if data.instanceId is null, it means to stop active proxying. */ public stoppedGetting = (data :social.StopProxyInfo) => { var instanceId = data.instanceId || this.instanceGettingAccessFrom_; if (instanceId === this.instanceGettingAccessFrom_) { this.instanceGettingAccessFrom_ = null; } if (instanceId) { this.mapInstanceIdToUser_[instanceId].isSharingWithMe = false; } if (data.error) { if (!instanceId) { console.error('Received error on getting without a current instance'); } // regardless, let the user know this.bringUproxyToFront(); } else if (this.instanceGettingAccessFrom_ === null && this.instanceTryingToGetAccessFrom === null) { // Clear the browser proxy settings only if there is no active connection. // Otherwise, this is a connection handover and clearing the proxy // settings will interrupt the active session. // This is necessary in case the proxy was stopped when the user was // signed out of the social network. In the case where the user clicked // stop, this will have no effect (this function is idempotent). this.browserApi.stopUsingProxy(); } this.updateGettingStatusBar_(); this.updateIcon_(); } private onGetFailed_ = (instanceId:string, proxyingId:string) => { console.error('proxying attempt ' + proxyingId + ' failed (getting)'); if (!this.disconnectedWhileProxying) { // This is an immediate failure, i.e. failure of a connection attempt // that never connected. It is not a retry. // Show the error toast indicating that a get attempt failed. let toastMessage = translator_module.i18n_t('UNABLE_TO_GET_FROM', { name: instanceId }); this.backgroundUi.showToast(toastMessage, true, false); } this.bringUproxyToFront(); } /** * Undoes proxy configuration (e.g. chrome.proxy settings). */ public stopUsingProxy = () => { this.browserApi.stopUsingProxy(); this.updateIcon_(); // revertProxySettings might call stopUsingProxy while a reconnection is // still being attempted. In that case, we also want to terminate the // in-progress connection. if (this.instanceTryingToGetAccessFrom) { this.stopGettingFromInstance(this.instanceTryingToGetAccessFrom); } else if (this.disconnectedWhileProxying) { this.stopGettingFromInstance(this.disconnectedWhileProxying); } } private getInstancePath_ = (instanceId :string) => { var user = this.mapInstanceIdToUser_[instanceId]; return <social.InstancePath>{ network: { name: user.network.name, userId: user.network.userId }, userId: user.userId, instanceId: instanceId }; } public restartProxying = () => { this.startGettingFromInstance(this.disconnectedWhileProxying, this.proxyAccessMode_); } public startGettingFromInstance = (instanceId :string, accessMode: ProxyAccessMode): Promise<void> => { if (this.instanceTryingToGetAccessFrom !== null) { // Cancel the existing proxying attempt before starting a new connection. this.core.stop(this.getInstancePath_(this.instanceTryingToGetAccessFrom)); } return this.core.start(this.getInstancePath_(instanceId)) .then((endpoint :net.Endpoint) => { // If we were getting access from some other instance // turn down the connection. if (this.instanceGettingAccessFrom_ && this.instanceGettingAccessFrom_ != instanceId) { this.core.stop(this.getInstancePath_(this.instanceGettingAccessFrom_)); } // Remember access mode in case of reconnect. this.proxyAccessMode_ = accessMode; this.startGettingInUiAndConfig(instanceId, endpoint, accessMode); }); } public stopGettingFromInstance = (instanceId :string) :void => { if (instanceId !== this.instanceTryingToGetAccessFrom && instanceId !== this.instanceGettingAccessFrom_) { // we have no idea what's going on console.error('Attempting to stop getting from unknown instance'); } this.core.stop(this.getInstancePath_(instanceId)); } public startGettingInUi = () => { this.updateIcon_(true); } /** * Sets extension icon to default and undoes proxy configuration. */ public startGettingInUiAndConfig = (instanceId :string, endpoint :net.Endpoint, accessMode: ProxyAccessMode) => { if (instanceId) { this.instanceGettingAccessFrom_ = instanceId; this.mapInstanceIdToUser_[instanceId].isSharingWithMe = true; } if (!accessMode || accessMode === ProxyAccessMode.NONE) { console.error('Cannot start using proxy: unknown proxy acccess mode.'); return; } this.startGettingInUi(); this.updateGettingStatusBar_(); this.browserApi.startUsingProxy(endpoint, this.model.globalSettings.proxyBypass, {accessMode: accessMode}); } /** * Set extension icon to the 'giving' icon. */ public startGivingInUi = () => { this.updateIcon_(null, true); } private updateIcon_ = (isGetting?:boolean, isGiving?:boolean) => { if (isGetting === null || typeof isGetting === 'undefined') { isGetting = this.isGettingAccess(); } if (isGiving === null || typeof isGiving === 'undefined') { isGiving = this.isGivingAccess(); } if (this.disconnectedWhileProxying) { this.browserApi.setIcon(Constants.ERROR_ICON); } else if (isGetting && isGiving) { this.browserApi.setIcon(Constants.GETTING_SHARING_ICON); } else if (isGetting) { this.browserApi.setIcon(Constants.GETTING_ICON); } else if (isGiving) { this.browserApi.setIcon(Constants.SHARING_ICON); } else if (this.model.onlineNetworks.length > 0 || !this.browserApi.hasInstalledThenLoggedIn) { this.browserApi.setIcon(Constants.DEFAULT_ICON); this.updateBadgeNotification_(); return; } else { this.browserApi.setIcon(Constants.LOGGED_OUT_ICON); } // For all icons except the default icon, do not show notifications. this.browserApi.setBadgeNotification(''); } /** * Set extension icon to the default icon. */ public stopGivingInUi = () => { this.updateIcon_(null, false); } public isGettingAccess = () => { return this.instanceGettingAccessFrom_ != null; } public isGivingAccess = () => { return Object.keys(this.instancesGivingAccessTo).length > 0; } /** * Synchronize a new network to be visible on this UI. */ private syncNetwork_ = (networkMsg :social.NetworkMessage) => { var existingNetwork = this.model.getNetwork(networkMsg.name, networkMsg.userId); var displayName = this.getNetworkDisplayName(networkMsg.name); if (networkMsg.online) { if (!existingNetwork) { existingNetwork = { name: networkMsg.name, userId: networkMsg.userId, roster: {}, logoutExpected: false, userName: networkMsg.userName, imageData: getImageData(networkMsg.userId, null, networkMsg.imageData) }; this.model.onlineNetworks.push(existingNetwork); } } else { if (existingNetwork) { this.model.removeNetwork(networkMsg.name, networkMsg.userId); if (!existingNetwork.logoutExpected && this.supportsReconnect_(networkMsg.name) && !this.disconnectedWhileProxying && !this.instanceGettingAccessFrom_) { console.warn('Unexpected logout, reconnecting to ' + networkMsg.name); this.reconnect_(networkMsg.name); } else { this.showNotification( this.i18n_t('LOGGED_OUT', { network: displayName })); if (!this.model.onlineNetworks.length) { this.view = ui_constants.View.SPLASH; } } } } this.updateView_(); this.updateIcon_(); } private syncUserSelf_ = (payload :social.UserData) => { var network = this.model.getNetwork(payload.network); if (!network) { console.error('uproxy_core_api.Update.USER_SELF message for invalid network', payload.network); return; } var profile :social.UserProfileMessage = payload.user; network.userId = profile.userId; network.userName = profile.name; network.imageData = getImageData(network.userId, network.imageData, profile.imageData); } /** * Synchronize data about some friend. */ public syncUser = (payload :social.UserData) => { var network = this.model.getNetwork(payload.network); if (!network) { return; } // Construct a UI-specific user object. var profile = payload.user; // Update / create if necessary a user, both in the network-specific // roster and the global roster. var user :User; user = this.model.getUser(network, profile.userId); var oldUserCategories :UserCategories = { getTab: null, shareTab: null }; if (!user) { // New user. user = new User(profile.userId, network, this); network.roster[profile.userId] = user; } else { // Existing user, get the category before modifying any properties. oldUserCategories = user.getCategories(); } user.update(payload); for (let i = 0; i < payload.allInstanceIds.length; ++i) { this.mapInstanceIdToUser_[payload.allInstanceIds[i]] = user; } for (let i = 0; i < payload.offeringInstances.length; i++) { let instance = payload.offeringInstances[i]; this.syncGettingState_(instance); this.syncTryingToGetState_(instance); this.syncDisconnectedState_(instance); } this.updateGettingStatusBar_(); for (let i = 0; i < payload.instancesSharingWithLocal.length; i++) { this.instancesGivingAccessTo[payload.instancesSharingWithLocal[i]] = true; user.isGettingFromMe = true; } var newUserCategories = user.getCategories(); // Update the user's category in both get and share tabs. model.categorizeUser(user, this.model.contacts.getAccessContacts, oldUserCategories.getTab, newUserCategories.getTab); if (user.status != social.UserStatus.CLOUD_INSTANCE_SHARED_WITH_LOCAL) { model.categorizeUser(user, this.model.contacts.shareAccessContacts, oldUserCategories.shareTab, newUserCategories.shareTab); } this.updateBadgeNotification_(); console.log('Synchronized user.', user); }; // Updates this.instanceGettingAccessFrom_ and related state variables. private syncGettingState_ = (instance:social.InstanceData) => { let gettingState = instance.localGettingFromRemote; let instanceId = instance.instanceId; if (gettingState === social.GettingState.GETTING_ACCESS) { // Sets this.instanceGettingAccessFrom_ this.startGettingInUiAndConfig( instanceId, instance.activeEndpoint, this.proxyAccessMode_); } else if (this.instanceGettingAccessFrom_ === instanceId && gettingState !== social.GettingState.TRYING_TO_GET_ACCESS) { let error = false; if (gettingState !== social.GettingState.NONE) { error = true; this.lastFailedProxyingId = instance.proxyingId; } // Unsets this.instanceGettingAccessFrom_ this.stoppedGetting({ instanceId: instanceId, error: error }); } } // Updates this.instanceTryingToGetAccessFrom and related state variables. private syncTryingToGetState_ = (instance:social.InstanceData) => { let gettingState = instance.localGettingFromRemote; let instanceId = instance.instanceId; let proxyingId = instance.proxyingId if (gettingState === social.GettingState.TRYING_TO_GET_ACCESS || gettingState === social.GettingState.RETRYING) { this.instanceTryingToGetAccessFrom = instanceId; } else if (this.instanceTryingToGetAccessFrom === instanceId) { this.lastFailedProxyingId = proxyingId; this.instanceTryingToGetAccessFrom = null; if (gettingState === social.GettingState.NONE) { // Initial connection attempt failed, so we went straight to NONE. this.onGetFailed_(instanceId, proxyingId); } } } // Updates this.disconnectedWhileProxying and related state variables. private syncDisconnectedState_ = (instance:social.InstanceData) => { let gettingState = instance.localGettingFromRemote; let instanceId = instance.instanceId; if (gettingState === social.GettingState.FAILED || gettingState === social.GettingState.RETRYING) { // This instance is in a failure state. this.disconnectedWhileProxying = instanceId; } else if (this.disconnectedWhileProxying === instanceId) { // Not in a failure state anymore. this.disconnectedWhileProxying = null; } } /** * Remove a friend from the friend list by removing it from * model.contacts */ public removeFriend = (args:{ networkName: string, userId: string }) => { var network = this.model.getNetwork(args.networkName); var user = this.model.getUser(network, args.userId); this.model.removeContact(user); console.log('Removed user from contacts', user); } public openTab = (url: string) => { this.browserApi.openTab(url); } public bringUproxyToFront = () => { this.browserApi.bringUproxyToFront(); } public login = (network :string, userName ?:string) : Promise<void> => { return this.core.login({ network: network, loginType: uproxy_core_api.LoginType.INITIAL, userName: userName }).then(() => { this.browserApi.hasInstalledThenLoggedIn = true; }).catch((e :Error) => { this.showNotification(this.i18n_t( 'ERROR_SIGNING_IN', {network: this.getNetworkDisplayName(network)})); throw e; }); } private reconnect_ = (network :string) => { this.model.reconnecting = true; // TODO: add wechat, quiver, github URLs var pingUrl = network == 'Facebook-Firebase-V2' ? 'https://graph.facebook.com' : 'https://www.googleapis.com'; this.core.pingUntilOnline(pingUrl).then(() => { // Ensure that the user is still attempting to reconnect (i.e. they // haven't clicked to stop reconnecting while we were waiting for the // ping response). // TODO: this doesn't work quite right if the user is signed into multiple social networks if (this.model.reconnecting) { this.core.login({network: network, loginType: uproxy_core_api.LoginType.RECONNECT}).then(() => { // TODO: we don't necessarily want to hide the reconnect screen, as we might only be reconnecting to 1 of multiple disconnected networks this.stopReconnect(); }).catch((e) => { // Reconnect failed, give up. // TODO: this may have only failed for 1 of multiple networks this.stopReconnect(); this.showNotification( this.i18n_t('LOGGED_OUT', { network: network })); this.updateView_(); }); } }); } public stopReconnect = () => { this.model.reconnecting = false; } public sendFeedback = (feedback :uproxy_core_api.UserFeedback) : Promise<void> => { var logsPromise :Promise<string>; if (feedback.logs) { logsPromise = this.core.getLogs().then((logs) => { var browserInfo = 'Browser Info: ' + feedback.browserInfo + '\n\n'; return browserInfo + logs; }); } else { logsPromise = Promise.resolve(''); } return logsPromise.then((logs) => { var payload = { email: feedback.email, feedback: feedback.feedback, logs: logs, feedbackType: uproxy_core_api.UserFeedbackType[feedback.feedbackType], proxyingId: this.lastFailedProxyingId }; return this.core.postReport({payload: payload, path: 'submit-feedback'}); }); } public setMode = (mode :ui_constants.Mode) => { this.updateGlobalSetting('mode', mode); } public updateLanguage = (newLanguage :string) => { this.updateGlobalSetting('language', newLanguage); this.i18n_setLng(newLanguage); this.model.globalSettings.language = newLanguage; } public updateInitialState = (state :uproxy_core_api.InitialState) => { console.log('Received uproxy_core_api.Update.INITIAL_STATE:', state); this.model.networkNames = state.networkNames; this.availableVersion = state.availableVersion; if (!state.globalSettings.language) { // Set state.globalSettings.language based on browser settings: // Choose the first language in navigator.languages we have available. let lang :string; try { lang = _(navigator.languages).map((langCode :string) => { return langCode.substring(0, 2).toLowerCase(); // Normalize }).find((langCode :string) => { // Return first lang we have available. return _.includes(translator_module.i18n_languagesAvailable, langCode); }); } catch (e) { lang = 'en'; } state.globalSettings.language = lang || 'en'; } if (state.globalSettings.language !== this.model.globalSettings.language) { this.updateLanguage(state.globalSettings.language); } this.model.updateGlobalSettings(state.globalSettings); while (this.model.onlineNetworks.length > 0) { var toRemove = this.model.onlineNetworks[0]; this.model.removeNetwork(toRemove.name, toRemove.userId); } for (var network in state.onlineNetworks) { this.addOnlineNetwork_(state.onlineNetworks[network]); } // plenty of state may have changed, update it this.updateView_(); this.updateSharingStatusBar_(); this.updateIcon_(); } private addOnlineNetwork_ = (networkState :social.NetworkState) => { var profile = networkState.profile; this.model.onlineNetworks.push({ name: networkState.name, userId: profile.userId, userName: profile.name, imageData: getImageData(profile.userId, null, profile.imageData), logoutExpected: false, roster: {} }); for (var userId in networkState.roster) { this.syncUser(networkState.roster[userId]); } } private coreUpdateAvailable_ = (data :{version :string}) => { this.availableVersion = data.version; } private updateBadgeNotification_ = () => { // Don't show notifications if the user is giving or getting access. if (this.isGivingAccess() || this.isGettingAccess()) { this.browserApi.setBadgeNotification(''); return; } var numOfNotifications = this.model.contacts.getAccessContacts.pending.length + this.model.contacts.shareAccessContacts.pending.length; if (numOfNotifications === 0) { this.browserApi.setBadgeNotification(''); } else { this.browserApi.setBadgeNotification(numOfNotifications.toString()); } } public getNetworkDisplayName = (networkName :string) : string => { return this.getProperty_<string>(networkName, 'displayName') || networkName; } private supportsReconnect_ = (networkName :string) : boolean => { return this.getProperty_<boolean>(networkName, 'supportsReconnect') || false; } private getProperty_ = <T>(networkName :string, propertyName :string) : T => { if (NETWORK_OPTIONS[networkName]) { return (<any>(NETWORK_OPTIONS[networkName]))[propertyName]; } return undefined; } // this takes care of updating the view (given the assumuption that we are // connected to the core) private updateView_ = () => { if (this.model.onlineNetworks.length > 0 || this.model.globalSettings.hasSeenWelcome) { this.view = ui_constants.View.ROSTER; } else { this.view = ui_constants.View.SPLASH; } } public cloudUpdate = (args :uproxy_core_api.CloudOperationArgs) :Promise<void> => { return this.core.cloudUpdate(args); } public removeContact = (args:uproxy_core_api.RemoveContactArgs): Promise<void> => { return this.core.removeContact(args); } public startVerifying = (inst :social.InstanceData) :Promise<void> => { console.log('ui:startVerifying on ' + JSON.stringify(inst) + ' started.'); // TODO: when doing the final UI, we need something that we can // cancel. For user cancellation, peer cancellation, and timeout. return this.getConfirmation( 'Verify this User', 'Please contact them personally, live. Preferably on a voice ' + 'or video chat. Then press Next', 'Do this later', 'I\'m Ready').then( () => { // TODO: this really just needs a cancel button. this.getUserInput( 'Verify this User', 'Please type in the SAS code that they see for you. Any other ' + 'value cancels.', 'SAS:', '', 'Next').then( (sas:string) => { console.log('Got SAS: ' + sas + ', against desired: ' + inst.verifySAS); this.finishVerifying(inst, parseInt(inst.verifySAS) === parseInt(sas)); }); return this.core.verifyUser(this.getInstancePath_(inst.instanceId)); }); } public finishVerifying = (inst :social.InstanceData, sameSAS: boolean) :Promise<void> => { var args :uproxy_core_api.FinishVerifyArgs = { 'inst': this.getInstancePath_(inst.instanceId), 'sameSAS': sameSAS }; console.log('VERIFYING SAS AS ' + sameSAS); return this.core.finishVerifyUser(args); }; private updateGlobalSetting = (setting: string, value: Object) => { (<any>this.model.globalSettings)[setting] = value; this.core.updateGlobalSetting({ name: setting, value: value }); } } // class UserInterface
the_stack
import { testHelpers } from "@fromjs/core"; const { instrumentAndRun, server } = testHelpers; import { traverse as _traverse, TraversalStep } from "./traverse"; import { numericLiteral } from "@fromjs/core/src/OperationTypes"; const traverse = async function (firstStep, options = {}) { options = Object.assign({ optimistic: false }, options); const steps: TraversalStep[] = (await _traverse.call( null, firstStep, [], server, options )) as any; return steps; }; function getStepTypeList(traversalResult) { return traversalResult.map((t) => t.operationLog.operation); } test("Can track concatenation of 'a' and 'b' - (simple)", async () => { const { normal, tracking, code } = await instrumentAndRun("return 'a' + 'b'"); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); expect(t1[0].operationLog.result.primitive).toBe("ab"); var t1LastStep = t1[t1.length - 1]; var t2LastStep = t2[t2.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("b"); }); test("Can track concatenation of 'a' and 'b' in an add function", async () => { const { normal, tracking, code } = await instrumentAndRun(` function add(arg1, arg2) { return arg1 + arg2 } return add('a', 'b') `); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); var t1LastStep = t1[t1.length - 1]; var t2LastStep = t2[t2.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("b"); expect(getStepTypeList(t1)).toEqual([ "callExpression", // add() "returnStatement", // return "binaryExpression", // + "identifier", // arg1 "stringLiteral", // "a" ]); }); test("Can traverse concatenation of a string and a number", async () => { const { normal, tracking, code } = await instrumentAndRun(` const num = 100 return num + "x" `); expect(normal).toBe("100x"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); var t2 = await traverse({ operationLog: tracking, charIndex: 4 }); var t1LastStep = t1[t1.length - 1]; var t2LastStep = t2[t2.length - 1]; expect(t1LastStep.operationLog.operation).toBe("numericLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe(100); expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("x"); }); test("Can traverse concatenation of a number and a string", async () => { const { normal, tracking, code } = await instrumentAndRun(` const num = 100 return "x" + num `); expect(normal).toBe("x100"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); var t2 = await traverse({ operationLog: tracking, charIndex: 4 }); var t1LastStep = t1[t1.length - 1]; var t2LastStep = t2[t2.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("x"); expect(t2LastStep.operationLog.operation).toBe("numericLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe(100); }); describe("Assignment Expressions", () => { test("Can track values through object assignments", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {} obj.a = "x" return obj.a `); var t = await traverse({ operationLog: tracking, charIndex: 0 }); expect(getStepTypeList(t)).toEqual([ "memberExpression", "assignmentExpression", "stringLiteral", ]); }); test("Can track used return values of assignment expressions (to variables)", async () => { const { normal, tracking, code } = await instrumentAndRun(` var str = "a" return (str += "b") `); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); expect(t1[0].operationLog.result.primitive).toBe("ab"); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("b"); }); test("Can traverse += operation for object assignments", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = { a: "a" } obj.a += "b" return obj.a `); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("b"); }); test("Can traverse return value of object assignments", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = { a: "a" } return (obj.a += "b") `); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1[0].operationLog.result.primitive).toBe("ab"); expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("b"); }); test("Can traverse results of assignment expression", async () => { const { normal, tracking, code } = await instrumentAndRun(` var v return v = "a" `); expect(normal).toBe("a"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); expect(t1LastStep.charIndex).toBe(0); }); test("Can traverse results of assignment expression if assigning to an object", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {} return obj.a = "a" `); expect(normal).toBe("a"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); expect(t1LastStep.charIndex).toBe(0); }); test("Can traverse if the previous value of a function argument was undefined", async () => { const { normal, tracking, code } = await instrumentAndRun(` function fn(a,b) { if (!b) { b = a } return a } return fn("a") `); expect(normal).toBe("a"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); expect(t1LastStep.charIndex).toBe(0); }); test("Works in strict mode when assigning a value to something without a tracking identifier", async () => { const { normal, tracking, code } = await instrumentAndRun( ` "use strict" function fn() {} function fn2() {} // neither fn___tv nor fv2___tv exist here fn2 = fn return "ok" `, {}, { logCode: false } ); expect(normal).toBe("ok"); }); }); test("Can track values through object literals", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {a: "x"} return obj.a `); var t = await traverse({ operationLog: tracking, charIndex: 0 }); expect(getStepTypeList(t)).toEqual([ "memberExpression", "objectProperty", "stringLiteral", ]); }); test("Can traverse String.prototype.slice", async () => { const { normal, tracking, code } = await instrumentAndRun(` var str = "abcde" str = str.slice(2,4) return str `); expect(normal).toBe("cd"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var lastStep = t[t.length - 1]; expect(lastStep.charIndex).toBe(2); expect(getStepTypeList(t)).toEqual([ "identifier", "assignmentExpression", "callExpression", "identifier", "stringLiteral", ]); }); describe("Array.prototype.splice", () => { test("Can traverse Array.prototype.splice return value", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = [1,2,3,4] return arr.splice(1,2).join("") `); expect(normal).toBe("23"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("numericLiteral"); }); }); describe("Object.entries", () => { test("Return value of Object.entries is tracked", async () => { const { normal, tracking, code } = await instrumentAndRun(` const entries = Object.entries({a:"A",b:"B"}) return entries[0][0] + entries[0][1] + entries[1][0] + entries[1][1] `); expect(normal).toBe("aAbB"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("a"); step = await traverseAndGetLastStep(tracking, 3); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("B"); }); }); test("Traverse str[n] character access", async () => { const { normal, tracking, code } = await instrumentAndRun(` var str = "abcde" return str[2] `); expect(normal).toBe("c"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var lastStep = t[t.length - 1]; expect(lastStep.charIndex).toBe(2); expect(lastStep.operationLog.operation).toBe("stringLiteral"); }); test("Traversing += assignment expressions", async () => { const { normal, tracking, code } = await instrumentAndRun(` var a = "a" a += "b" return a `); expect(normal).toBe("ab"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); expect(t[0].operationLog.result.primitive).toBe("ab"); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.result.primitive).toBe("a"); }); test("Can track values through conditional expression", async () => { const { normal, tracking, code } = await instrumentAndRun(` var b = false ? "a" : "b" return b `); expect(normal).toBe("b"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); expect(getStepTypeList(t)).toEqual([ "identifier", "conditionalExpression", "stringLiteral", ]); }); describe("Can traverse string replacement calls", () => { test("works for simple replacements using regexes", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "ababab".replace(/b/g, "cc") // => "accaccacc" return ret `); expect(normal).toBe("accaccacc"); var t = await traverse({ operationLog: tracking, charIndex: 5 }); expect(getStepTypeList(t)).toEqual([ "identifier", "callExpression", "stringLiteral", ]); const lastStep = t[t.length - 1]; expect(lastStep.charIndex).toBe(1); expect(lastStep.operationLog.result.primitive).toBe("cc"); }); test("works for simple replacements using strings", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "Hello {{name}}!".replace("{{name}}", "Susan") return ret `); expect(normal).toBe("Hello Susan!"); var t1 = await traverse({ operationLog: tracking, charIndex: 2 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(2); var t2 = await traverse({ operationLog: tracking, charIndex: 6 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(0); }); test("works for non-match locations behind a match", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "abc".replace("a", "12345") return ret `); expect(normal).toBe("12345bc"); var t1 = await traverse({ operationLog: tracking, charIndex: 6 }); // "c" const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(2); }); test("Works for $n substitutions", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "abbbxy".replace(/(b+)/, "$1<>") return ret `); expect(normal).toBe("abbb<>xy"); var t1 = await traverse({ operationLog: tracking, charIndex: "abbb<>xy".indexOf("y"), }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe("abbbxy".indexOf("y")); }); test("Can handle numbers after a dollar sign that don't identify the submatch", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "_abc#_".replace(/([a-z]+)#/g, '$1' + 123) return ret `); expect(normal).toBe("_abc123_"); var t1 = await traverse({ operationLog: tracking, charIndex: "abbb<>xy".indexOf("y"), }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe("abbbxy".indexOf("y")); }); test("Doesn't break replace with numbers after dollar sign if there's a subgroup but no submatch", async () => { const { normal, tracking, code } = await instrumentAndRun(` var ret = "# insecure requests found".replace(/(^|[^\\\\])#/g, '$1' + 555) return ret `); expect(normal).toBe("555 insecure requests found"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("numericLiteral"); }); }); describe("JSON.parse", () => { it("Can traverse JSON.parse", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '{"a": {"b": "xyz"}}'; var obj = JSON.parse(json); return obj.a.b `); var t = await traverse({ operationLog: tracking, charIndex: 2 }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(15); }); it("Can traverse JSON.parse when using keys", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '{"a":"abc", "b": "bcd"}'; var obj = JSON.parse(json); return Object.keys(obj)[1] `); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var lastStep = t[t.length - 1]; expect(normal).toBe("b"); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(13); }); it("Can traverse JSON.parse with JSON containing arrays", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '{"a": {"b": ["one", "two"]}}'; var obj = JSON.parse(json); return obj.a.b[1] `); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var lastStep = t[t.length - 1]; expect(normal).toBe("two"); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(21); }); it("Returns the correct character index for longer strings", async () => { const text = `{"a": {"b": "Hello"}}`; const { normal, tracking, code } = await instrumentAndRun(` var json = '${text}'; var obj = JSON.parse(json); return obj.a.b `); var t = await traverse({ operationLog: tracking, charIndex: "Hello".indexOf("l"), }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(text.indexOf("l")); }); it("Can find property names in the JSON", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = JSON.parse('{"a": {"b": 5}}'); let ret for (var name in obj) { ret = name } return ret `); expect(normal).toBe("a"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(2); expect(getStepTypeList(t)).toContain("jsonParseResult"); }); it("Can handle character mapping if the JSON contains an escaped line break", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '{"a": "\\\\nHello"}'; var obj = JSON.parse(json); return obj.a + "|" + json `); const json = normal.split("|")[1]; var t = await traverse({ operationLog: tracking, charIndex: normal.indexOf("l"), }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(json.indexOf("l")); }); it("Can handle character mapping if the JSON contains an unicode escape sequence ", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '{"a": "\\\\u003cHello"}'; var obj = JSON.parse(json); return obj.a + "|" + json `); const json = normal.split("|")[1]; var t = await traverse({ operationLog: tracking, charIndex: normal.indexOf("l"), }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(json.indexOf("l")); }); it("Can handle JSON that just contains a string", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '"abc"'; var str = JSON.parse(json); return str `); var t = await traverse({ operationLog: tracking, charIndex: normal.indexOf("b"), }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe('"abc"'.indexOf("b")); }); it("Can handle JSON that just contains a number", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = '5'; var str = JSON.parse(json); return str `); expect(normal).toBe(5); var t = await traverse({ operationLog: tracking, charIndex: 0, }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("stringLiteral"); }); }); describe("JSON.stringify", () => { it("Can traverse a JSON.stringify result", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {greeting: "Hello ", name: {first: "w", last: "orld"}} var str = JSON.stringify(obj, null, 4); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("Hello") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("Hello "); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("orld") ); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("orld"); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("first") ); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("first"); }); it("Can traverse JSON.stringify result that's not prettified", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {greeting: "Hello ", name: {first: "w", last: "orld"}} var str = JSON.stringify(obj); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("orld") + 2 ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(2); expect(lastStep.operationLog.result.primitive).toBe("orld"); }); it("Can traverse JSON.stringify correctly when looking at keys", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {greeting: "Hello "}; var str = JSON.stringify(obj); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("greeting") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("greeting"); }); it("Can traverse JSON.stringify result where keys are used multiple times", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = { one: {hello: 123}, two: {} } obj.two["he" + "llo"] = 456 var str = JSON.stringify(obj); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.lastIndexOf("hello") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("he"); }); it("Can handle arrays", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["one", "two"] var str = JSON.stringify(arr); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("two") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("two"); }); it("Can handle nested arrays", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["one", ["two", "three"]] var str = JSON.stringify(arr); return str `); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("three") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("three"); }); it("Doesn't break if property names contain dots", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {"a.b": "c"} var str = JSON.stringify(obj); return str `); var lastStep = await traverseAndGetLastStep(tracking, normal.indexOf("c")); expect(lastStep.operationLog.operation).toBe("stringLiteral"); expect(lastStep.charIndex).toBe(0); expect(lastStep.operationLog.result.primitive).toBe("c"); }); it("Doesn't break if there are undefiend properties", async () => { const { normal, tracking, code } = await instrumentAndRun(` var obj = {"a": undefined, "b": 5} var str = JSON.stringify(obj); return str `); var lastStep = await traverseAndGetLastStep(tracking, normal.indexOf("5")); expect(lastStep.operationLog.operation).toBe("numericLiteral"); }); it("Can handle JSON that just contains a string", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = "abc"; var str = JSON.stringify(json); return str `); expect(normal).toBe('"abc"'); var lastStep = await traverseAndGetLastStep( tracking, normal.indexOf("abc") ); expect(lastStep.operationLog.operation).toBe("stringLiteral"); }); it("Can handle JSON that just contains a number", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = 5; var str = JSON.stringify(json); return str `); expect(normal).toBe("5"); var t = await traverse({ operationLog: tracking, charIndex: 0, }); var lastStep = t[t.length - 1]; expect(lastStep.operationLog.operation).toBe("numericLiteral"); }); it("Can handle values that are Symbols", async () => { const { normal, tracking, code } = await instrumentAndRun(` var json = {a: Symbol("sth")}; var str = JSON.stringify(json); return str `); expect(normal).toBe("{}"); }); }); it("Can traverse arguments for a function expression (rather than a function declaration)", async () => { const { normal, tracking, code } = await instrumentAndRun(` var fn = function(a) { return a } return fn("a") `); expect(normal).toBe("a"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); const tLastStep = t[t.length - 1]; expect(getStepTypeList(t)).toEqual([ "callExpression", "returnStatement", "identifier", "stringLiteral", ]); }); describe("String.prototype.substr", () => { it("Works in when passing a positive start and length", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcde".substr(2, 2) `); expect(normal).toBe("cd"); var t = await traverse({ operationLog: tracking, charIndex: 1 }); // char "d" const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(3); }); it("Works in when passing a start argument only", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcde".substr(2) `); expect(normal).toBe("cde"); var t = await traverse({ operationLog: tracking, charIndex: 1 }); // char "c" const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(3); }); it("Works in when passing a negative start argument", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcde".substr(-2, 1) `); expect(normal).toBe("d"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); // char "d" const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(3); }); }); describe("String.prototype.trim", () => { it("Adjusts char index based on amount of whitespace removed", async () => { const { normal, tracking, code } = await instrumentAndRun(` const str = String.fromCharCode(10) + " ab cd" return str.trim() `); expect(normal).toBe("ab cd"); var t = await traverse({ operationLog: tracking, charIndex: 3 }); // char "c" const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(8); }); it("Doesn't break if there's no whitespace at the start", async () => { const { normal, tracking, code } = await instrumentAndRun(` const str = "abc" return str.trim() `); expect(normal).toBe("abc"); var t = await traverse({ operationLog: tracking, charIndex: 2 }); // char "c" const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(2); }); it("Doesn't break when called with apply", async () => { const { normal, tracking, code } = await instrumentAndRun(` var str = " a" return String.prototype.trim.apply(str, []) `); expect(normal).toBe("a"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); const tLastStep = t[t.length - 1]; expect(tLastStep.charIndex).toBe(1); }); }); describe("call/apply", () => { it("Correctly traverses argument values when they are passed in with apply", async () => { const { normal, tracking, code } = await instrumentAndRun(` function fn(str1, str2, str3) { return str3 } return fn.apply(null, ["a", "b", "c"]) `); expect(normal).toBe("c"); var t = await traverseAndGetLastStep(tracking, 0); expect(t.operationLog.operation).toBe("stringLiteral"); }); it("Correctly traverses argument values when they are passed in with call", async () => { const { normal, tracking, code } = await instrumentAndRun(` function fn(str1, str2, str3) { return str3 } return fn.call(null, "a", "b", "c") `); expect(normal).toBe("c"); var t = await traverseAndGetLastStep(tracking, 0); expect(t.operationLog.operation).toBe("stringLiteral"); }); }); describe("It can traverse logical expressions", () => { it("Can traverse ||", async () => { const { normal, tracking, code } = await instrumentAndRun( ` function fn(a, b) { b = b || a return b } return fn("a") + fn("x", "y") `, {}, { logCode: false } ); expect(normal).toBe("ay"); var t = await traverseAndGetLastStep(tracking, 0); console.log(JSON.stringify(t, null, 2)); // I disabled the scopeHasIdentifierWithTrackingIdentifier check it broke when injecting // the code of a function into the browser – we assumed that var__tv is in scope // but it's not in the browser // Disabling this means that we check if b___tv is typeof undefined, and it is // but that's not because the value isn't in scope but because it's actually undefined // expect(t.operationLog.operation).toBe("stringLiteral"); expect(t.operationLog.result.primitive).toBe("a"); var t = await traverseAndGetLastStep(tracking, 1); // expect(t.operationLog.operation).toBe("stringLiteral"); expect(t.operationLog.result.primitive).toBe("y"); }); it("Doesn't break the execution logic of || expressions", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let str = "a"; function setStrToB() { str = "b" } ("a" || setStrToB()) return str ` // {}, // { logCode: true } ); expect(normal).toBe("a"); }); it("Doesn't break the execution logic of nested || expressions", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let str = "a"; function setStrToB() { str = "b" } function setStrToC() { str = "c" return true } (null || setStrToC() || setStrToB()) return str ` // {}, // { logCode: true } ); expect(normal).toBe("c"); }); it("Doesn't break the execution logic of && expressions", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let str = "a"; function setStrToB() { str = "b" } false && setStrToB() return str ` // {}, // { logCode: true } ); expect(normal).toBe("a"); }); }); it("Can traverse arguments fn.apply(this, arguments)", async () => { const { normal, tracking, code } = await instrumentAndRun(` function f1() { return f2.apply(this, arguments) } function f2(a) { return a + a } return f1("a") `); expect(normal).toBe("aa"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); const tLastStep = t[t.length - 1]; expect(tLastStep.operationLog.operation).toBe("stringLiteral"); }); describe("Arrays", () => { it("Can traverse values in array literals", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["a", "b"] return arr[1] `); expect(normal).toBe("b"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); const tLastStep = t[t.length - 1]; expect(tLastStep.operationLog.operation).toBe("stringLiteral"); }); it("Can traverse pushed values", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = [] arr.push("a", "b") return arr[1] `); expect(normal).toBe("b"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); const tLastStep = t[t.length - 1]; expect(tLastStep.operationLog.operation).toBe("stringLiteral"); }); it("Can traverse shifted/unshifted values", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = ["a", "c"] const v = arr.shift() arr.unshift("b") return v + arr[0] + arr[1] `); expect(normal).toBe("abc"); var t = await traverse({ operationLog: tracking, charIndex: 0 }); var tLastStep = t[t.length - 1]; expect(tLastStep.operationLog.operation).toBe("stringLiteral"); expect(tLastStep.operationLog.result.primitive).toBe("a"); var t = await traverse({ operationLog: tracking, charIndex: 1 }); var tLastStep = t[t.length - 1]; expect(tLastStep.operationLog.operation).toBe("stringLiteral"); expect(tLastStep.operationLog.result.primitive).toBe("b"); var t = await traverse({ operationLog: tracking, charIndex: 2 }); var tLastStep = t[t.length - 1]; console.log(JSON.stringify(tLastStep, null, 2)); expect(tLastStep.operationLog.operation).toBe("stringLiteral"); expect(tLastStep.operationLog.result.primitive).toBe("c"); }); describe("Array.prototype.join", () => { it("Can traverse basic join call", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["ab", "cd"] return arr.join("-#-") `); expect(normal).toBe("ab-#-cd"); var t1 = await traverse({ operationLog: tracking, charIndex: 6 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(1); expect(t1LastStep.operationLog.result.primitive).toBe("cd"); var t2 = await traverse({ operationLog: tracking, charIndex: 3 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(1); expect(t2LastStep.operationLog.result.primitive).toBe("-#-"); }); }); it("Can traverse join calls with the default separator (,)", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["a", "b"] return arr.join() `); expect(normal).toBe("a,b"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(0); expect(t1LastStep.operationLog.result.primitive).toBe(","); }); it("Can traverse join calls with undefined/null values", async () => { const { normal, tracking, code } = await instrumentAndRun(` return [null, undefined].join("-") `); expect(normal).toBe("-"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(0); expect(t1LastStep.operationLog.result.primitive).toBe("-"); }); it("Can traverse join called with .call", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Array.prototype.join.call(["a","b"], "-") `); expect(normal).toBe("a-b"); var t1 = await traverse({ operationLog: tracking, charIndex: 2 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(0); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); it("Works on array like objects", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Array.prototype.join.call({0: "a", 1: "b", length: 2}) `); expect(normal).toBe("a,b"); var t1 = await traverse({ operationLog: tracking, charIndex: 2 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.charIndex).toBe(0); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); }); it("Tracks Object.keys", async () => { const { normal, tracking, code } = await instrumentAndRun(` const obj = {} obj["a"] = 100 return Object.keys(obj)[0] `); expect(normal).toBe("a"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Can traverse Object.assign", async () => { const { normal, tracking, code } = await instrumentAndRun(` let obj = {a: "a"} let obj2 = {b: "b"} obj = Object.assign(obj, obj2) return obj.b `); expect(normal).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); describe("Array.slice", () => { it("Supports traversal of normal usage", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3"] return arr.slice(1,3)[1] `); expect(normal).toBe("3"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports traversal with negative start index", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3", "4"] return arr.slice(-3, 3)[1] `); expect(normal).toBe("3"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports traversal with negative start index and no end index", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3", "4"] return arr.slice(-2)[1] `); expect(normal).toBe("4"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports traversal with positive start index and no end index", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3", "4"] return arr.slice(1)[2] `); expect(normal).toBe("4"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports traversal with positive start index and negative end index", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3", "4"] return arr.slice(1, -1)[1] `); expect(normal).toBe("3"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports being called with .call and arguments object", async () => { const { normal, tracking, code } = await instrumentAndRun(` const slice = Array.prototype.slice function fn() { const arr = slice.call(arguments) return arr[0] } return fn("Hi") `); expect(normal).toBe("Hi"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); }); describe("Array.prototype.map", () => { it("Passes values through to mapping function", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2"] return arr.map(function(value){ return value })[1] `); expect(normal).toBe("2"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Supports all callback arguments and thisArg", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2"] return arr.map(function(value, index, array){ return value + index + array.length + this }, "x")[0] `); expect(normal).toBe("102x"); }); it("When invoked with .apply, still supports all callback arguments and thisArg", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2"] const map = arr.map var arr2 = map.apply(arr, [function(value, index, array){ return value + index + array.length + this }, "x"]) return arr2[0] `); expect(normal).toBe("102x"); }); it("When invoked with .call, still supports all callback arguments and thisArg", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2"] const map = arr.map var arr2 = map.call(arr, function(value, index, array){ return value + index + array.length + this }, "x") return arr2[0] `); expect(normal).toBe("102x"); }); }); describe("Array.prototype.filter", () => { it("Passes values through to filter function and tracks result values", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1", "2", "3", "4"] let v const greaterThan2 = arr.filter(function(value){ v = value return parseFloat(value) > 2 }) return v + "-" + greaterThan2[0] `); expect(normal).toBe("4-3"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); var t2 = await traverse({ operationLog: tracking, charIndex: 2 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); }); it("Doesn't break this argument", async () => { const { normal, tracking, code } = await instrumentAndRun(` let arr = ["1","2","3","4"] let t arr = arr.filter(function(value){ t = this.toString() return value > parseFloat(this) }, "2") return arr[0] + t `); expect(normal).toBe("32"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); }); }); describe("Array.concat", () => { it("Works when calling .concat with an array argument", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1"].concat(["2"]) return arr[0] + arr[1] `); expect(normal).toBe("12"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("1"); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("2"); }); it("Works when calling .concat with an non-array argument", async () => { const { normal, tracking, code } = await instrumentAndRun(` var arr = ["1"].concat("2") return arr[0] + arr[1] `); expect(normal).toBe("12"); var t2 = await traverse({ operationLog: tracking, charIndex: 1 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.operationLog.result.primitive).toBe("2"); }); }); describe("encodeURICompoennt", () => { it("Can traverse encodeURIComponent", async () => { const { normal, tracking, code } = await instrumentAndRun(` return encodeURIComponent("a@b#c") `); expect(normal).toBe("a%40b%23c"); var t1 = await traverse({ operationLog: tracking, charIndex: 7 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(3); var t2 = await traverse({ operationLog: tracking, charIndex: 9 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(5); }); it("Can traverse encodeURIComponent when called with .call", async () => { const { normal, tracking, code } = await instrumentAndRun(` return encodeURIComponent.call(null, "a@b#c") `); expect(normal).toBe("a%40b%23c"); var t1 = await traverse({ operationLog: tracking, charIndex: 7 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(3); var t2 = await traverse({ operationLog: tracking, charIndex: 9 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(5); }); }); it("Can traverse decodeURIComponent", async () => { const { normal, tracking, code } = await instrumentAndRun(` return decodeURIComponent("a%40b%23c") `); expect(normal).toBe("a@b#c"); var t1 = await traverse({ operationLog: tracking, charIndex: 3 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(5); var t2 = await traverse({ operationLog: tracking, charIndex: 4 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(8); }); describe("String.prototype.match", () => { test("Can traverse String.prototype.match results", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = "a4c89a".match(/[0-9]+/g) return arr[0] + arr[1] `); expect(normal).toBe("489"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(1); var t2 = await traverse({ operationLog: tracking, charIndex: 2 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(4); }); // not technically a traversal test but it makes sense to have .match tests in one place // ... maybe we should just merge core.test.ts with traverse.test.ts // ... or move them next to the relevant files, like callexpression.ts it("Doesn't break on non-global regexes with multiple match groups", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = "zzabc".match(/(a)(b)/) return arr[0] + arr[1] + arr[2] `); expect(normal).toBe("abab"); }); it("Tries to not get confused with same matched characters in mutliple groups", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = "zzaba".match(/(a)(b)(a)/) return arr[1] + arr[2] + arr[3] `); expect(normal).toBe("aba"); var t2 = await traverse({ operationLog: tracking, charIndex: 2 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.charIndex).toBe(4); }); it("Works when some match groups don't have a match", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = "ac".match(/(a)(b)?(c)/) return arr[3] `); expect(normal).toBe("c"); var t2 = await traverse({ operationLog: tracking, charIndex: 0 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.charIndex).toBe(1); }); it("Works somewhat when using nested groups in a non global regex", async () => { // Easier to construct here than escaping it in the string const re = /^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/; const { normal, tracking, code } = await instrumentAndRun( ` // Example based on angular todomvc const str = "todo in todos | filter:statusFilter track by $index" const re = outsideArgs.re const arr = str.match(re); return arr[0] `, { re } ); expect(normal).toBe("todo in todos | filter:statusFilter track by $index"); var t2 = await traverse({ operationLog: tracking, charIndex: 2 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.charIndex).toBe(2); }); }); describe("regexp exec", () => { it("can traverse simple regexp exec result", async () => { const { normal, tracking, code } = await instrumentAndRun(` const re = /[bd]/g const str = "abcd" re.exec(str) return re.exec(str)[0] `); expect(normal).toBe("d"); var t2 = await traverse({ operationLog: tracking, charIndex: 0 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.charIndex).toBe(3); }); it("can traverse regexp exec result with groups", async () => { const { normal, tracking, code } = await instrumentAndRun(` const re = /a(b)c(d)/ const str = "abcd" return re.exec(str)[2] `); expect(normal).toBe("d"); var t2 = await traverse({ operationLog: tracking, charIndex: 0 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.operation).toBe("stringLiteral"); expect(t2LastStep.charIndex).toBe(3); }); }); describe("Array.prototype.reduce", () => { it("Passes values through to reducer function", async () => { const { normal, tracking, code } = await instrumentAndRun(` return ["aa", "bb", "cc"].reduce(function(ret, param){ return ret + param }, "") `); expect(normal).toBe("aabbcc"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("aa"); var t2 = await traverse({ operationLog: tracking, charIndex: 5 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.result.primitive).toBe("cc"); expect(t2LastStep.charIndex).toBe(1); }); it("It works when not passing in an initial value", async () => { const { normal, tracking, code } = await instrumentAndRun(` return ["a", "b", "c"].reduce(function(ret, param){ return ret + param }) `); expect(normal).toBe("abc"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("a"); var t2 = await traverse({ operationLog: tracking, charIndex: 2 }); const t2LastStep = t2[t2.length - 1]; expect(t2LastStep.operationLog.result.primitive).toBe("c"); expect(t2LastStep.charIndex).toBe(0); }); }); describe("String.prototype.split", () => { it("Can traverse string split result array ", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "hello--world".split("--")[1] `); expect(normal).toBe("world"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(8); }); it("Can traverse string split result array when called with apply", async () => { const { normal, tracking, code } = await instrumentAndRun(` return String.prototype.split.apply("hello--world", ["--"])[1] `); expect(normal).toBe("world"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(8); }); it("Can traverse string split result array when called without a separator", async () => { const { normal, tracking, code } = await instrumentAndRun(` return String.prototype.split.apply("ab", [])[0] `); expect(normal).toBe("ab"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(1); }); it("Can traverse string split result when passing in an object with a Symbol.split function ", async () => { const { normal, tracking, code } = await instrumentAndRun(` const separator = { [Symbol.split]: function(str){ return [str.slice(0,1), str.slice(1)] } } return "something".split(separator)[1] `); expect(normal).toBe("omething"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(2); }); it("It doesn't break when Symbol.split function doesn't return an array", async () => { const { normal, tracking, code } = await instrumentAndRun(` const separator = { [Symbol.split]: function(str){ return 123 } } return "something".split(separator) `); expect(normal).toBe(123); }); it("Can traverse if split argument is a regular expression", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "a|b".split(/|/)[2] `); expect(normal).toBe("b"); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(2); expect(step.operationLog.result.primitive).toBe("a|b"); }); }); describe("Array.prototype.shift", () => { it("Traverses array correctly after calling shift on it", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = ["a", "b"] arr.shift() return arr[0] `); expect(normal).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); it("Traverses arguments array correctly after calling shift arguments", async () => { const { normal, tracking, code } = await instrumentAndRun(` function fn() { const shift = Array.prototype.shift shift.call(arguments) return arguments[0] } return fn("a", "b", "c") `); expect(normal).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); it("Traverses return value from arr.shift", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = ["a", "b"] arr.shift() return arr.shift() `); expect(normal).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); }); describe("Array.prototype.pop", () => { it("Traverses value after retrieving it with arr.pop", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = ["a", "b"] return arr.pop() `); expect(normal).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("b"); }); }); describe("Array.prototype.unshift", () => { it("Traverses value inserted with array.unshift", async () => { const { normal, tracking, code } = await instrumentAndRun(` const arr = ["c"] arr.unshift("a","b") return arr[1] + arr[2] `); expect(normal).toBe("bc"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); var t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("b"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); var t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.operationLog.result.primitive).toBe("c"); }); }); describe("String.prototype.substring", () => { it("Traverses substring call with indexStart and indexEnd being strings", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcd".substring("1", "3") // str args should also work `); expect(normal).toBe("bc"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(2); }); it("Traverses substring call with indexEnd being less than indexStart", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcde".substring(3,2) `); expect(normal).toBe("c"); var t1 = await traverse({ operationLog: tracking, charIndex: 0 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(2); }); it("Traverses substring when invoked with .call", async () => { const { normal, tracking, code } = await instrumentAndRun(` const substring = String.prototype.substring return substring.call("abcd", 1, 3) `); expect(normal).toBe("bc"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(2); }); it("Traverses substring when invoked with .apply", async () => { const { normal, tracking, code } = await instrumentAndRun(` const substring = String.prototype.substring return substring.apply("abcd", [1, 3]) `); expect(normal).toBe("bc"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(2); }); }); describe("String.prototype.toString", () => { it("Traverses toString call", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "abcd".toString() `); expect(normal).toBe("abcd"); var t1 = await traverse({ operationLog: tracking, charIndex: 1 }); const t1LastStep = t1[t1.length - 1]; expect(t1LastStep.operationLog.operation).toBe("stringLiteral"); expect(t1LastStep.charIndex).toBe(1); }); }); async function traverseAndGetLastStep( operationLog, charIndex, options = {} ): Promise<TraversalStep> { var t1: any = await traverse({ operationLog, charIndex }, options); const t1LastStep = t1[t1.length - 1]; return t1LastStep; } // describe("Can handle object destructuring in function parameters", () => { // it("Object destructuring with default parameters", async () => { // const { normal, tracking, code } = await instrumentAndRun(` // function concat({a="Hello ",b}){ // console.log("aaa", a___tv) // return a + b // } // return concat({b: "World"}) // `); // expect(normal).toBe("Hello World"); // let step; // step = await traverseAndGetLastStep(tracking, 1); // console.log(step); // expect(step.operationLog.operation).toBe("stringLiteral"); // step = await traverseAndGetLastStep(tracking, 6); // expect(step.operationLog.operation).toBe("stringLiteral"); // }); // it("Object destructuring with default params depending on other params", async () => { // const { normal, tracking, code } = await instrumentAndRun(` // function fn({a,b=a + "_"}){ // return b // } // return fn({a: "z"}) // `); // expect(normal).toBe("z_"); // let step; // step = await traverseAndGetLastStep(tracking, 0); // expect(step.operationLog.result.primitive).toBe("z"); // expect(step.operationLog.operation).toBe("stringLiteral"); // }); // }); it("Supports arrow functions with a full body", async () => { const { normal, tracking, code } = await instrumentAndRun(` const concat = (a,b) => {return a + b}; return concat("Hello ", "World") `); expect(normal).toBe("Hello World"); let step; step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(1); step = await traverseAndGetLastStep(tracking, 6); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); }); it("Supports arrow functions with a single expression", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const concat = (a,b) => a + b; return concat("Hello ", "World") ` ); expect(normal).toBe("Hello World"); let step; step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(1); step = await traverseAndGetLastStep(tracking, 6); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); }); describe("Array destructuring", () => { it("Works for a basic example", async () => { const { normal, tracking, code } = await instrumentAndRun(` const [one, two] = ["one", "two"] return one + two `); expect(normal).toBe("onetwo"); let step; step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); step = await traverseAndGetLastStep(tracking, 3); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); }); it("Works for an object pattern in the array expression", async () => { const { normal, tracking, code } = await instrumentAndRun(` const [{a}] = [{a: "a"}] return a `); expect(normal).toBe("a"); // Traversal not supported yet // let step; // step = await traverseAndGetLastStep(tracking, 0); // expect(step.operationLog.operation).toBe("stringLiteral"); // expect(step.charIndex).toBe(0); }); it("Works for function parameters", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const concat = ([a, b], [{c, d}]) => { console.log({a, b,c,d}) return a + b + c + d } return concat(["a", "b"], [{c: "c", d: "d"}]) `, {}, { logCode: false } ); expect(normal).toBe("abcd"); let step; step = await traverseAndGetLastStep(tracking, 0); // traversla doesn't work yet... expect(step.operationLog.operation).toBe("emptyTrackingInfo"); expect(step.charIndex).toBe(0); }); }); describe("getters/setters", () => { it("It can traverse member expression result that came from a getter", async () => { const { normal, tracking, code } = await instrumentAndRun(` const obj = {} Object.defineProperty(obj, "test", { get: function() { return "Hello" } }) return obj.test `); expect(normal).toBe("Hello"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); }); }); it("Can traverse array expressions that contain array patterns", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const arr1 = ["x", "y"] const arr2 = ["a", "b", ...arr1] return arr2[3] `, {}, { logCode: false } ); expect(normal).toBe("y"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); }); describe("Template literals", () => { it("Has basic support", async () => { const { normal, tracking, code } = await instrumentAndRun( "return `a${'b'}c\n${'d'}`", {}, { logCode: false } ); expect(normal).toBe("abc\nd"); let step = await traverseAndGetLastStep(tracking, normal.indexOf("b")); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("b"); expect(step.charIndex).toBe(0); step = await traverseAndGetLastStep(tracking, normal.indexOf("d")); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("d"); expect(step.charIndex).toBe(0); }); it("Can handle nested template literals", async () => { const { normal, tracking, code } = await instrumentAndRun( ` function getChar(char) { return ${"`${char}`"} } return ${'`${getChar("a")}${getChar("b")}`'} `, {}, { logCode: false } ); expect(normal).toBe("ab"); let step = await traverseAndGetLastStep(tracking, normal.indexOf("b")); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("b"); expect(step.charIndex).toBe(0); }); }); it("Can traverse Number.prototype.toString", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return (5).toString() `, {}, { logCode: false } ); expect(normal).toBe("5"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(5); expect(step.charIndex).toBe(0); }); it("Can traverse Math.round", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return Math.round(2.5) `, {}, { logCode: false } ); expect(normal).toBe(3); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(2.5); expect(step.charIndex).toBe(0); }); it("Can traverse Math.floor", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return Math.floor(2.5) `, {}, { logCode: false } ); expect(normal).toBe(2); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(2.5); expect(step.charIndex).toBe(0); }); it("Can traverse a Number constructor call", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return Number(2) `, {}, { logCode: false } ); expect(normal).toBe(2); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(2); expect(step.charIndex).toBe(0); }); it("Can traverse String constructor call", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return String("str") `, {}, { logCode: false } ); expect(normal).toBe("str"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); }); describe("optimistic", () => { it("If not optimistic, does not traverse binary expression even if one is a numeric literal and the other isn't", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const complexVal = 0.656 return complexVal * 100 `, {}, { logCode: false } ); let step = await traverseAndGetLastStep(tracking, 0, false); expect(!!step.isOptimistic).toBe(false); expect(step.operationLog.operation).toBe("binaryExpression"); }); it("If optimistic, does not traverse binary expression even if one is a numeric literal and the other isn't", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const complexVal = 0.656 return complexVal * 100 `, {}, { logCode: false } ); let step = await traverseAndGetLastStep(tracking, 0, { optimistic: true }); expect(step.operationLog.operation).toBe("numericLiteral"); // expect(step.operationLog.operation).toBe(0.656); expect(step.isOptimistic).toBe(true); }); }); describe("Math.min/max", () => { it("Can traverse Math.min", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Math.min(5,2) `); expect(normal).toBe(2); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(2); }); it("Can traverse Math.max", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Math.max(5,2) `); expect(normal).toBe(5); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(5); }); it("Can traverse Math.max called with many arguments", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Math.max(5,2, 10, 4) `); expect(normal).toBe(10); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); expect(step.operationLog.result.primitive).toBe(10); }); }); it("Can traverse parseFloat", async () => { const { normal, tracking, code } = await instrumentAndRun(` return parseFloat("25") `); expect(normal).toBe(25); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("25"); }); it("Can traverse new Date calls", async () => { const { normal, tracking, code } = await instrumentAndRun(` return new Date(1234567890123).getTime() `); expect(normal).toBe(1234567890123); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); }); it("Can traverse Math.abs", async () => { const { normal, tracking, code } = await instrumentAndRun(` return Math.abs(10) `); expect(normal).toBe(10); const step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); }); it("Can traverse String toLowerCase/toUpperCase", async () => { const { normal, tracking, code } = await instrumentAndRun(` return "A".toLowerCase() + "b".toUpperCase() `); expect(normal).toBe("aB"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); }); it("Can traverse this arguments", async () => { const { normal, tracking, code } = await instrumentAndRun( ` String.prototype.appendA = function() { return String(this) + "a" } return "b".appendA() ` ); expect(normal).toBe("ba"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); }); it("Can traverse Number.prototype.toFixed calls", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return (5).toFixed(2) ` ); expect(normal).toBe("5.00"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); }); test("Can handle function expressions", async () => { const { normal, tracking, code } = await instrumentAndRun(` var fn = function sth(a,b){} return fn `); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("fn"); }); describe("object spread", () => { it("Can traverse object spread parameter", async () => { const { normal, tracking, code } = await instrumentAndRun(` const obj = {sth: "abc"} const obj2 = {...obj} let key = Object.keys(obj2)[0] return key + "->"+ obj2.sth `); expect(normal).toBe("sth->abc"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("sth"); step = await traverseAndGetLastStep(tracking, "sth->abc".indexOf("a")); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("abc"); }); it("Doesn't crash if destructuring undefined in object", async () => { const { normal, tracking, code } = await instrumentAndRun(` const obj = {a: "a", ...undefined} return obj.a `); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("a"); }); }); it("Can traverse array pattern destructuring with empty elements", async () => { const { normal, tracking, code } = await instrumentAndRun( ` function x(a,b,...c){} const [,a, ...others] = ["a","b", "c", "d"] return a + others[0] + others[1] `, {}, { logCode: false } ); expect(normal).toBe("bcd"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("b"); step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("c"); step = await traverseAndGetLastStep(tracking, 2); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("d"); }); describe("Object patterns / destructuring", () => { it("Can traverse simple object patterns", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const {a} = {a: "a"} return a `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("a"); }); it("Doesn't break object pattern if properites aren't own properties", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const {round} = Math; const num = round(5.9); return num === 6 ? "ok" : "wrong result" `, {}, { logCode: false } ); expect(normal).toBe("ok"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("ok"); }); it("Can traverse deeper object patterns with renaming", async () => { const { normal, tracking, code } = await instrumentAndRun( ` const {a:{b: c}} = {a: {b: "b"}} return c `, {}, { logCode: false } ); expect(normal).toBe("b"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("b"); }); it("Doesn't modify any objects used by the instrumented app", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let obj = {a: {b: {c: "c"}}}; const {a:{b}} = obj; if (obj.a.b !== b) { throw Error("not equal") } if (Object.keys(obj.a).length > 1) { throw Error("too many keys, probably object was modified and tv added: " + Object.keys(obj.a).join(",")) } return b.c `, {}, { logCode: false } ); expect(normal).toBe("c"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("c"); }); it("Doesn't break default values", async () => { const { normal, tracking, code } = await instrumentAndRun( ` var {a="a"}= {}; return a `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); // not supported for now expect(step.operationLog.operation).toBe("emptyTrackingInfo"); expect(step.operationLog.result.primitive).toBe(undefined); }); it("Doesn't break rest spread", async () => { const { normal, tracking, code } = await instrumentAndRun( ` var {a: {b:c, ...xyz}, ...more} = {a: {b:"c", x: "x", y: "y",z:"z"}, one: "1"} return c + xyz.x + xyz.y + xyz.z + more.one + xyz.b `, {}, { logCode: false } ); expect(normal).toBe("cxyz1undefined"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("c"); }); it("Doesn't break with objects with circular nesting", async () => { const { normal, tracking, code } = await instrumentAndRun( ` var obj = {a: "a", b: "b"} obj.self = obj var {self, a} = obj return a + self.b `, {}, { logCode: false } ); expect(normal).toBe("ab"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("a"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("b"); }); it("Supports inherited properties", async () => { const { normal, tracking, code } = await instrumentAndRun( ` function K() {} K.prototype.x = "x" let k = new K() const {x} = k return x `, {}, { logCode: false } ); expect(normal).toBe("x"); var step = await traverseAndGetLastStep(tracking, 0); // prorotype info not supported right now expect(step.operationLog.operation).toBe("emptyTrackingInfo"); }); it("Supports non enumerable properties", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let obj = {} Object.defineProperty(obj, "x", { value: "x", enumerable: false }) const {x} = obj return x `, {}, { logCode: false } ); expect(normal).toBe("x"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("emptyTrackingInfo"); }); }); it("Can traverse charAt calls", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return "ab".charAt(1) `, {}, { logCode: false } ); expect(normal).toBe("b"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(1); expect(step.operationLog.result.primitive).toBe("ab"); }); describe("Supports promises", () => { it("Works when creating a promise with new Promise()", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() const p = new Promise(function(resolve){ setTimeout(() => { resolve("a" + "b") }, 50) }).then(function(res){ console.log("resT",__fromJSGetTrackingIndex(res)) finishAsyncTest(res) }) `, {}, { logCode: false } ); expect(normal).toBe("ab"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("b"); }); it("Supports async functions that return a value right away", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() async function fn() { return "x" + "y" } fn().then(function(res){ finishAsyncTest(res) }) `, {}, { logCode: false } ); expect(normal).toBe("xy"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("y"); }); it("Supports async functions that use await and then return", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() function fn2() { return new Promise(resolve => { setTimeout(() => resolve("abc"), 100) }) } async function fn() { let val = await fn2() console.log("tv val", __fromJSGetTrackingIndex(val)) return val } fn().then(function(res){ console.log("tv res", __fromJSGetTrackingIndex(res)) finishAsyncTest(res) }) `, {}, { logCode: false } ); expect(normal).toBe("abc"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(1); expect(step.operationLog.result.primitive).toBe("abc"); }); it("Supports using await for promises", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() async function fn() { return "x" + "y" } (async () => { const res = await fn() console.log("res", res) finishAsyncTest(res) })(); `, {}, { logCode: false } ); expect(normal).toBe("xy"); var step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("y"); }); it("Supports nested async/await/Promises", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() async function getRes() { return "abc" } (async () => { var p = new Promise(async resolve => { let retP = getRes() let p2 = Promise.resolve("xyz") resolve(await retP + await p2) }); const res = await p finishAsyncTest(res) })() `, {}, { logCode: false } ); expect(normal).toBe("abcxyz"); var step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("abc"); var step = await traverseAndGetLastStep(tracking, 3); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("xyz"); }); it("Supports Promise.resolve", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() Promise.resolve("a").then(res => { finishAsyncTest(res) }) `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("a"); }); it("Supports resolving a promise with another promise", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() let p = new Promise(resolve => { const p2 = new Promise(resolve => setTimeout(() => { const p3 = new Promise(resolve => { resolve(Promise.resolve(new Promise(resolve => { setTimeout(() => resolve("a"), 10) }))) }) resolve(p3) },10)) resolve(p2) }) p.then(res => { console.log("user code then") finishAsyncTest(res) }) `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("a"); }); it("Supports returning a promise from a then handler", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() Promise.resolve("a").then(r => new Promise(resolve => { setTimeout(() => resolve(r), 10) }) ).then(r => { finishAsyncTest(r) }) `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("a"); }); it("Supports returning a resolved promise from a then handler", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() Promise.resolve("a").then(r => new Promise(resolve => { resolve(r) }) ).then(r => { finishAsyncTest(r) }) `, {}, { logCode: false } ); expect(normal).toBe("a"); var step = await traverseAndGetLastStep(tracking, 0); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("a"); }); it("Supports returning a value promise from a then handler", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() Promise.resolve("a").then(r => r + "x").then(r => { finishAsyncTest(r) }) `, {}, { logCode: false } ); expect(normal).toBe("ax"); var step = await traverseAndGetLastStep(tracking, 1); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("x"); }); it("Supports Promise.all", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() Promise.all([ Promise.resolve("a"), Promise.resolve("b") ]).then(arr => { const str = arr.join("") finishAsyncTest(str) }) `, {}, { logCode: false } ); expect(normal).toBe("ab"); var step = await traverseAndGetLastStep(tracking, 1); console.log(JSON.stringify(step, null, 2)); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.charIndex).toBe(0); expect(step.operationLog.result.primitive).toBe("b"); }); it("Doesn't break Promise.reject", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest(); (async function(){ await Promise.reject("x") })().catch(r => { const ret = r === "x" ? "ok" : "wrong value"; finishAsyncTest(ret) }) `, {}, { logCode: false } ); expect(normal).toBe("ok"); // don't worry about traversing rejections for now }); it("Doesn't break async function promise rejected by exception", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() const p = (async function(){ throw "x" })(); p.catch(r => { const ret = r === "x" ? "ok" : "wrong value"; finishAsyncTest(ret) }) `, {}, { logCode: false } ); expect(normal).toBe("ok"); // don't worry about traversing rejections for now }); it("Doesn't break await async function without return value", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let finishAsyncTest = asyncTest() async function sleep(ms) { await new Promise(resolve => setTimeout(resolve, ms)) } (async function(){ const ret = await sleep(10) finishAsyncTest(ret) })(); `, {}, { logCode: false } ); expect(normal).toBe(undefined); // don't worry about traversing rejections for now }); }); describe("URL", () => { it("Can traverse new URL().href", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return new URL("http://example.com").href `, {}, { logCode: false } ); expect(normal).toBe("http://example.com/"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("http://example.com"); expect(step.charIndex).toBe(0); }); it("Can traverse new URL().pathname", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return new URL("http://example.com/a/b").pathname `, {}, { logCode: false } ); expect(normal).toBe("/a/b"); let step = await traverseAndGetLastStep(tracking, 2); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("http://example.com/a/b"); expect(step.charIndex).toBe("http://example.com/a/b".indexOf("/a/b") + 2); }); it("Can traverse new URL().origin", async () => { const { normal, tracking, code } = await instrumentAndRun( ` return new URL("http://example.com/a/b").origin `, {}, { logCode: false } ); expect(normal).toBe("http://example.com"); let step = await traverseAndGetLastStep(tracking, 2); expect(step.operationLog.operation).toBe("stringLiteral"); expect(step.operationLog.result.primitive).toBe("http://example.com/a/b"); expect(step.charIndex).toBe(2); }); }); it("Can traverse Intl.NumberFormat().format", async () => { const { normal, tracking, code } = await instrumentAndRun( ` let num = 10000 return new Intl.NumberFormat().format(num) `, {}, { logCode: false } ); expect(normal).toBe("10,000"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("numericLiteral"); }); describe("Doesn't really test traversal", () => { it("Includes object path for string literal in Object Expression", async () => { const { normal, tracking, code, logServer } = await instrumentAndRun( ` const obj = { somekey: { something: { key: "xyz" } } } return obj.somekey.something.key; `, {}, { logCode: false } ); expect(normal).toBe("xyz"); let step = await traverseAndGetLastStep(tracking, 0); expect(step.operationLog.operation).toBe("stringLiteral"); const loc = await logServer!._locStore.getLocAwaitable( step.operationLog.loc ); expect(loc.objectPath).toEqual(["obj", "somekey", "something", "key"]); }); }); describe("Function default values", () => { it("stores value even if it can't traverse the default value", async () => { const { normal, tracking, code, logServer } = await instrumentAndRun( ` function concat(a, b="b") { return a + b } return concat("a") `, {}, { logCode: false } ); expect(normal).toBe("ab"); let step = await traverseAndGetLastStep(tracking, 1); expect(step.operationLog.operation).toBe("emptyTrackingInfo"); expect(step.operationLog.runtimeArgs.type).toBe( "assignmentPatternInFunction" ); expect(step.operationLog._result).toBe("b"); }); });
the_stack
* @packageDocumentation * @module std.ranges */ //================================================================ import * as base from "../../algorithm/modifiers"; import { IBidirectionalContainer } from "../container/IBidirectionalContainer"; import { IForwardContainer } from "../container/IForwardContainer"; import { IRandomAccessContainer } from "../container/IRandomAccessContainer"; import { IBidirectionalIterator } from "../../iterator/IBidirectionalIterator"; import { IForwardIterator } from "../../iterator/IForwardIterator"; import { IPointer } from "../../functional/IPointer"; import { BinaryPredicator } from "../../internal/functional/BinaryPredicator"; import { UnaryPredicator } from "../../internal/functional/UnaryPredicator"; import { Writeonly } from "../../internal/functional/Writeonly"; import { Temporary } from "../../internal/functional/Temporary"; import { begin, end } from "../../iterator/factory"; import { equal_to } from "../../functional/comparators"; type UnaryOperatorInferrer< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> = (val: IForwardContainer.ValueType<Range>) => IPointer.ValueType<OutputIterator>; type BinaryOperatorInferrer< Range1 extends Array<any> | IForwardContainer<any>, Range2 extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> = (x: IForwardContainer.ValueType<Range1>, y: IForwardContainer.ValueType<Range2>) => IPointer.ValueType<OutputIterator>; /* --------------------------------------------------------- FILL --------------------------------------------------------- */ /** * Copy elements in range. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> (range: Range, output: OutputIterator): OutputIterator { return base.copy(begin(range), end(range), output); } /** * Copy *n* elements. * * @param range An iterable ranged container. * @param n Number of elements to copy. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy_n< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> (range: Range, n: number, output: OutputIterator): OutputIterator { return base.copy_n(begin(range), n, output); } /** * Copy specific elements by a condition. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * @param pred A function predicates the specific condition. * * @return Output Iterator of the last position by advancing. */ export function copy_if< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> (range: Range, output: OutputIterator, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): OutputIterator { return base.copy_if(begin(range), end(range), output, pred); } /** * Copy elements reversely. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function copy_backward< Range extends Array<any> | IBidirectionalContainer<any, any>, OutputIterator extends Writeonly<IBidirectionalIterator<IBidirectionalContainer.ValueType<Range>, OutputIterator>>> (range: Range, output: OutputIterator): OutputIterator { return base.copy_backward(begin(range), end(range), <Temporary>output); } /** * Fill range elements * * @param range An iterable ranged container. * @param val The value to fill. * * @return Output Iterator of the last position by advancing. */ export function fill<Range extends Array<any> | IForwardContainer<any>> (range: Range, value: IForwardContainer.ValueType<Range>): void { return base.fill(begin(range), end(range), value); } /** * Fill *n* elements. * * @param range An iterable ranged container. * @param n Number of elements to fill. * @param val The value to fill. * * @return Output Iterator of the last position by advancing. */ export function fill_n<Range extends Array<any> | IForwardContainer<any>> (range: Range, n: number, value: IForwardContainer.ValueType<Range>): IForwardContainer.IteratorType<Range> { return base.fill_n(begin(range), n, value); } /** * Transform elements. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * @param op Unary function determines the transform. * * @return Output Iterator of the last position by advancing. */ export function transform< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> (range: Range, result: OutputIterator, op: UnaryOperatorInferrer<Range, OutputIterator>): OutputIterator; /** * Transform elements. * * @param range1 The 1st iterable ranged container. * @param range2 The 2nd iterable ranged container. * @param output Output iterator of the first position. * @param op Binary function determines the transform. * * @return Output Iterator of the last position by advancing. */ export function transform< Range1 extends Array<any> | IForwardContainer<any>, Range2 extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<OutputIterator>, OutputIterator>>> (range: Range1, first: Range2, result: OutputIterator, op: BinaryOperatorInferrer<Range1, Range2, OutputIterator>): OutputIterator; export function transform<Range1 extends Array<any> | IForwardContainer<any>> (range1: Range1, ...args: any[]): any { const fn: Function = base.transform.bind(undefined, begin(range1), end(range1)); if (args.length === 3) return fn(...args); else // args: #4 return fn(end(args[1]), args[2], args[3]); } /** * Generate range elements. * * @param range An iterable ranged container. * @param gen The generator function. */ export function generate<Range extends Array<any> | IForwardContainer<any>> (range: Range, gen: () => IForwardContainer.ValueType<Range>): void { return base.generate(begin(range), end(range), gen); } /** * Generate *n* elements. * * @param range An iterable ranged container. * @param n Number of elements to generate. * @param gen The generator function. * * @return Forward Iterator to the last position by advancing. */ export function generate_n<Range extends Array<any> | IForwardContainer<any>> ( range: Range, n: number, gen: () => IForwardContainer.ValueType<Range> ): IForwardContainer.IteratorType<Range> { return base.generate_n(begin(range), n, gen); } /* --------------------------------------------------------- REMOVE --------------------------------------------------------- */ /** * Test whether elements are unique in sorted range. * * @param range An iterable ranged container. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @returns Whether unique or not. */ export function is_unique<Range extends Array<any> | IForwardContainer<any>> (range: Range, pred: BinaryPredicator<IForwardContainer.ValueType<Range>> = equal_to): boolean { return base.is_unique(begin(range), end(range), pred); } /** * Remove duplicated elements in sorted range. * * @param range An iterable ranged container. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Input iterator to the last element not removed. */ export function unique<Range extends Array<any> | IForwardContainer<any>> (range: Range, pred: BinaryPredicator<IForwardContainer.ValueType<Range>> = equal_to): IForwardContainer.IteratorType<Range> { return base.unique(begin(range), end(range), pred); } /** * Copy elements in range without duplicates. * * @param range An iterable ranged container. * @param output Output iterator of the last position. * @param pred A binary function predicates two arguments are equal. Default is {@link equal_to}. * * @return Output Iterator of the last position by advancing. */ export function unique_copy< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, output: OutputIterator, pred: BinaryPredicator<IForwardContainer.ValueType<Range>> = equal_to ): OutputIterator { return base.unique_copy(begin(range), end(range), output, pred); } /** * Remove specific value in range. * * @param range An iterable ranged container. * @param val The specific value to remove. * * @return Iterator tho the last element not removed. */ export function remove<Range extends Array<any> | IForwardContainer<any>> (range: Range, val: IForwardContainer.ValueType<Range>): IForwardContainer.IteratorType<Range> { return base.remove(begin(range), end(range), val); } /** * Remove elements in range by a condition. * * @param range An iterable ranged container. * @param pred An unary function predicates remove. * * @return Iterator tho the last element not removed. */ export function remove_if<Range extends Array<any> | IForwardContainer<any>> (range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>): IForwardContainer.IteratorType<Range> { return base.remove_if(begin(range), end(range), pred); } /** * Copy range removing specific value. * * @param range An iterable ranged container. * @param output Output iterator of the last position. * @param val The condition predicates remove. * * @return Output Iterator of the last position by advancing. */ export function remove_copy< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, output: OutputIterator, val: IForwardContainer.ValueType<Range> ): OutputIterator { return base.remove_copy(begin(range), end(range), output, val); } /** * Copy range removing elements by a condition. * * @param range An iterable ranged container. * @param output Output iterator of the last position. * @param pred An unary function predicates remove. * * @return Output Iterator of the last position by advancing. */ export function remove_copy_if< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, output: OutputIterator, pred: UnaryPredicator<IForwardContainer.ValueType<Range>> ): OutputIterator { return base.remove_copy_if(begin(range), end(range), output, pred); } /* --------------------------------------------------------- REPLACE & SWAP --------------------------------------------------------- */ /** * Replace specific value in range. * * @param range An iterable ranged container. * @param old_val Specific value to change * @param new_val Specific value to be changed. */ export function replace<Range extends Array<any> | IForwardContainer<any>> ( range: Range, old_val: IForwardContainer.ValueType<Range>, new_val: IForwardContainer.ValueType<Range> ): void { return base.replace(begin(range), end(range), old_val, new_val); } /** * Replace specific condition in range. * * @param range An iterable ranged container. * @param pred An unary function predicates the change. * @param new_val Specific value to be changed. */ export function replace_if<Range extends Array<any> | IForwardContainer<any>> ( range: Range, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>, new_val: IForwardContainer.ValueType<Range> ): void { return base.replace_if(begin(range), end(range), pred, new_val); } /** * Copy range replacing specific value. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * @param old_val Specific value to change * @param new_val Specific value to be changed. * * @return Output Iterator of the last position by advancing. */ export function replace_copy< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, output: OutputIterator, old_val: IForwardContainer.ValueType<Range>, new_val: IForwardContainer.ValueType<Range> ): OutputIterator { return base.replace_copy(begin(range), end(range), output, old_val, new_val); } /** * Copy range replacing specfic condition. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * @param pred An unary function predicates the change. * @param new_val Specific value to be changed. * * @return Output Iterator of the last position by advancing. */ export function replace_copy_if< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, output: OutputIterator, pred: UnaryPredicator<IForwardContainer.ValueType<Range>>, new_val: IForwardContainer.ValueType<Range> ): OutputIterator { return base.replace_copy_if(begin(range), end(range), output, pred, new_val); } /** * Swap values of two ranges. * * @param range1 The 1st iterable ranged container. * @param range2 The 2nd iterable ranged container. * * @return Forward Iterator of the last position of the 2nd range by advancing. */ export function swap_ranges< Range1 extends Array<any> | IForwardContainer<any>, Range2 extends IForwardContainer.SimilarType<Range1>> (range1: Range1, range2: Range2): IForwardContainer.IteratorType<Range2> { return base.swap_ranges(begin(range1), end(range1), <Temporary>begin(range2)); } /* --------------------------------------------------------- RE-ARRANGEMENT --------------------------------------------------------- */ /** * Reverse elements in range. * * @param range An iterable ranged container. */ export function reverse<Range extends Array<any> | IBidirectionalContainer<any, any>> (range: Range): void { return base.reverse(begin(range), end(range)); } /** * Copy reversed elements in range. * * @param range An iterable ranged container. * @param output Output iterator of the first position. * * @return Output Iterator of the last position by advancing. */ export function reverse_copy< Range extends Array<any> | IBidirectionalContainer<any, any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> (range: Range, output: OutputIterator): OutputIterator { return base.reverse_copy(begin(range), end(range), output); } export function shift_left<Range extends Array<any> | IForwardContainer<any>> (range: Range, n: number): void { return base.shift_left(begin(range), end(range), n); } export function shift_right<Range extends Array<any> | IBidirectionalContainer<any, any>> (range: Range, n: number): void { return base.shift_right(begin(range), end(range), n); } /** * Rotate elements in range. * * @param range An iterable ranged container. * @param middle Input iteartor of the initial position of the right side. * * @return Input iterator of the final position in the left side; *middle*. */ export function rotate<Range extends Array<any> | IForwardContainer<any>> (range: Range, middle: IForwardContainer.IteratorType<Range>): IForwardContainer.IteratorType<Range> { return base.rotate(begin(range), middle, end(range)); } /** * Copy rotated elements in range. * * @param range An iterable ranged container. * @param middle Input iteartor of the initial position of the right side. * @param output Output iterator of the last position. * * @return Output Iterator of the last position by advancing. */ export function rotate_copy< Range extends Array<any> | IForwardContainer<any>, OutputIterator extends Writeonly<IForwardIterator<IForwardContainer.ValueType<Range>, OutputIterator>>> ( range: Range, middle: IForwardContainer.IteratorType<Range>, output: OutputIterator ): OutputIterator { return base.rotate_copy(begin(range), middle, end(range), output); } /** * Shuffle elements in range. * * @param range An iterable ranged container. */ export function shuffle<Range extends Array<any> | IRandomAccessContainer<any>> (range: Range): void { return base.shuffle(begin(range), end(range)); }
the_stack
import LexicalModelCompiler from '../dist/lexical-model-compiler/lexical-model-compiler'; import {assert} from 'chai'; import 'mocha'; import path = require('path'); import { compileModelSourceCode } from './helpers'; describe('LexicalModelCompiler - pseudoclosure compilation + use', function () { const MODEL_ID = 'example.qaa.trivial'; const PATH = path.join(__dirname, 'fixtures', MODEL_ID); describe('specifying custom methods: applyCasing and searchTermToKey', function () { let casingWithPrependedSymbols: CasingFunction = function(casingName: CasingForm, text: string, defaultApplyCasing: CasingFunction) { switch(casingName) { // Use of symbols, and of the `casingName` name, exist to serve as regex targets. case 'lower': return '-' + defaultApplyCasing(casingName, text); case 'upper': return '+' + defaultApplyCasing(casingName, text); case 'initial': return '^' + defaultApplyCasing(casingName, text); default: return defaultApplyCasing(casingName, text); } }; it('variant 1: applyCasing prepends symbols, searchTermToKey removes them', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'], languageUsesCasing: true, // applyCasing won't appear without this! applyCasing: casingWithPrependedSymbols, // Parameter name `rawSearchTerm` selected for uniqueness, regex matching test target. searchTermToKey: function(rawSearchTerm: string, applyCasing: CasingFunction) { // Strips any applyCasing symbols ('-', '+', '^') out of the compiled Trie. // We should be able to test that they do _not_ occur within internal nodes of the Trie. return applyCasing('lower', rawSearchTerm) // We replace all prepended applyCasing symbols with a separate symbol not // otherwise seen within the model. .replace(/^-/, '§') .replace(/^\+/, '§') .replace(/^\^/, '§'); } }, PATH) as string; // Check that pseudoclosure forwarding is set up correctly. assert.match(code, /\.model\.searchTermToKey/); assert.match(code, /\.model\.applyCasing/); // Check that the methods actually made into the code; use our custom parameter names: assert.match(code, /casingName/); assert.match(code, /rawSearchTerm/); // Check that the prepended symbols from applyCasing also appear in the code: assert.match(code, /'-'/); assert.match(code, /'\+'/); assert.match(code, /'\^'/); assert.match(code, /§/); let modelInitIndex = code.indexOf('LMLayerWorker.loadModel'); let modelInitCode = code.substring(modelInitIndex); // Chop off the IIFE terminator. Not strictly necessary, but whatever. modelInitCode = modelInitCode.substring(0, modelInitCode.lastIndexOf('\n})();')) // Check that the prepended symbols from applyCasing do not appear in the Trie. assert.notMatch(modelInitCode, /['"]-['"]/); assert.notMatch(modelInitCode, /['"]\+['"]/); assert.notMatch(modelInitCode, /['"]\^['"]/); // Instead, our custom keyer should ensure that the following symbol DOES appear. // Verifies that the compiler uses the custom searchTermToKey definition. assert.match(modelInitCode, /['"]§['"]/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); it('variant 2: applyCasing prepends symbols, searchTermToKey keeps them', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'], languageUsesCasing: true, // applyCasing won't appear without this! applyCasing: casingWithPrependedSymbols, // Parameter name `rawSearchTerm` selected for uniqueness, regex matching test target. searchTermToKey: function(rawSearchTerm: string, applyCasing: CasingFunction) { // Strips any applyCasing symbols ('-', '+', '^') out of the compiled Trie. // We should be able to test that they do _not_ occur within internal nodes of the Trie. return applyCasing('lower', rawSearchTerm); } }, PATH) as string; // Check that pseudoclosure forwarding is set up correctly. assert.match(code, /\.model\.searchTermToKey/); assert.match(code, /\.model\.applyCasing/); // Check that the methods actually made into the code; use our custom parameter names: assert.match(code, /casingName/); assert.match(code, /rawSearchTerm/); // Check that the prepended symbols from applyCasing also appear in the code: assert.match(code, /'-'/); assert.match(code, /'\+'/); assert.match(code, /'\^'/); let modelInitIndex = code.indexOf('LMLayerWorker.loadModel'); let modelInitCode = code.substring(modelInitIndex); // Chop off the IIFE terminator. Not strictly necessary, but whatever. modelInitCode = modelInitCode.substring(0, modelInitCode.lastIndexOf('\n})();')) // Check that the prepended lowercase "-" DOES appear within the Trie, as keying // does not remove it in this variant. Verifies that the compiler actually // used the custom applyCasing definition! assert.match(modelInitCode, /['"]-['"]/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); it('variant 3: applyCasing prepends symbols, default searchTermToKey', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'], languageUsesCasing: true, // applyCasing won't appear without this! applyCasing: casingWithPrependedSymbols }, PATH) as string; // Check that pseudoclosure forwarding is set up correctly. assert.match(code, /\.model\.searchTermToKey/); assert.match(code, /\.model\.applyCasing/); // Check that the methods actually made into the code; use our custom parameter names: assert.match(code, /casingName/); assert.match(code, /function defaultCasedSearchTermToKey/); // Check that the prepended symbols from applyCasing also appear in the code: assert.match(code, /'-'/); assert.match(code, /'\+'/); assert.match(code, /'\^'/); let modelInitIndex = code.indexOf('LMLayerWorker.loadModel'); let modelInitCode = code.substring(modelInitIndex); // Chop off the IIFE terminator. Not strictly necessary, but whatever. modelInitCode = modelInitCode.substring(0, modelInitCode.lastIndexOf('\n})();')) // Check that the prepended lowercase "-" DOES appear within the Trie, as keying // does not remove it in this variant. Verifies that the compiler actually // used the custom applyCasing definition! assert.match(modelInitCode, /['"]-['"]/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); }); describe('relying on default applyCasing + searchTermToKey', function() { it('languageUsesCasing: true', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'], languageUsesCasing: true, // applyCasing should appear! }, PATH) as string; // Does the cased version of the search-term default appear? assert.match(code, /function defaultCasedSearchTermToKey/); assert.match(code, /\.model\.searchTermToKey/); // Does the default casing function appear? assert.match(code, /function defaultApplyCasing/); assert.match(code, /\.defaults\.applyCasing/); assert.match(code, /languageUsesCasing/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); it('languageUsesCasing: false', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'], languageUsesCasing: false, // applyCasing should not appear! }, PATH) as string; // Does the cased version of the search-term default appear? assert.match(code, /function defaultSearchTermToKey/); assert.match(code, /\.model\.searchTermToKey/); // Does the default casing function appear? // Since `languageUsesCasing` is explicitly `false`, there should be no usage. assert.notMatch(code, /function defaultApplyCasing/); assert.notMatch(code, /\.defaults\.applyCasing/); assert.match(code, /languageUsesCasing/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); it('languageUsesCasing: undefined', function() { let compiler = new LexicalModelCompiler; let code = compiler.generateLexicalModelCode(MODEL_ID, { format: 'trie-1.0', sources: ['wordlist.tsv'] // languageUsesCasing: undefined }, PATH) as string; // Does the cased version of the search-term default appear? // Needed to match 14.0 defaults. assert.match(code, /function defaultCasedSearchTermToKey/); assert.match(code, /\.model\.searchTermToKey/); // Does the default casing function appear? assert.match(code, /function defaultApplyCasing/); assert.match(code, /\.defaults\.applyCasing/); // Did the compilation process explictly leave `languageUsesCasing` undefined? assert.notMatch(code, /languageUsesCasing/); // Make sure it compiles! let compilation = compileModelSourceCode(code); assert.isFalse(compilation.hasSyntaxError); assert.isNotNull(compilation.exportedModel); }); }) });
the_stack
import { copy, defineConfig, generateId, isFunction, isValidObject, normalizeArray, } from '@agile-ts/utils'; import { logCodeManager } from '../logCodeManager'; import { Agile } from '../agile'; import { PatchOptionConfigInterface } from '../state'; import { ComputedTracker } from '../computed'; import { Item } from './item'; import { SelectorConfigInterface, Selector, SelectorKey } from './selector'; import { Group, GroupAddConfigInterface, GroupConfigInterface, GroupKey, TrackedChangeMethod, } from './group'; import { GroupIngestConfigInterface } from './group/group.observer'; import { CreatePersistentConfigInterface, StorageKey } from '../storages'; import { CollectionPersistent } from './collection.persistent'; export class Collection<DataType extends DefaultItem = DefaultItem> { // Agile Instance the Collection belongs to public agileInstance: () => Agile; public config: CollectionConfigInterface; private initialConfig: CreateCollectionConfigImpl; // Key/Name identifier of the Collection public _key?: CollectionKey; // Amount of the Items stored in the Collection public size = 0; // Items stored in the Collection public data: { [key: string]: Item<DataType> } = {}; // Whether the Collection is persisted in an external Storage public isPersisted = false; // Manages the permanent persistent in external Storages public persistent: CollectionPersistent<DataType> | undefined; // Registered Groups of Collection public groups: { [key: string]: Group<DataType> } = {}; // Registered Selectors of Collection public selectors: { [key: string]: Selector<DataType> } = {}; // Whether the Collection was instantiated correctly public isInstantiated = false; // Helper property to check whether an unknown instance is a Collection, // without importing the Collection itself for using 'instanceof' (Treeshaking support) public isCollection = true; /** * A Collection manages a reactive set of Information * that we need to remember globally at a later point in time. * While providing a toolkit to use and mutate this set of Information. * * It is designed for arrays of data objects following the same pattern. * * Each of these data object must have a unique `primaryKey` to be correctly identified later. * * You can create as many global Collections as you need. * * [Learn more..](https://agile-ts.org/docs/core/collection/) * * @public * @param agileInstance - Instance of Agile the Collection belongs to. * @param config - Configuration object */ constructor( agileInstance: Agile, config: CreateCollectionConfig<DataType> = {} ) { this.agileInstance = () => agileInstance; let _config = typeof config === 'function' ? config(this) : config; _config = defineConfig(_config, { primaryKey: 'id', groups: {}, selectors: {}, defaultGroupKey: 'default', }); this._key = _config.key; this.config = { defaultGroupKey: _config.defaultGroupKey as any, primaryKey: _config.primaryKey as any, }; this.initialConfig = _config; this.initGroups(_config.groups as any); this.initSelectors(_config.selectors as any); this.isInstantiated = true; // Add 'initialData' to Collection // (after 'isInstantiated' to add them properly to the Collection) if (_config.initialData) this.collect(_config.initialData); // Reselect Selector Items // Necessary because the selection of an Item // hasn't worked with a not correctly 'instantiated' Collection before for (const key in this.selectors) this.selectors[key].reselect(); // Rebuild of Groups // Not necessary because if Items are added to the Collection, // (after 'isInstantiated = true') // the Groups which contain these added Items get rebuilt. // for (const key in this.groups) this.groups[key].rebuild(); } /** * Updates the key/name identifier of the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/properties#key) * * @public * @param value - New key/name identifier. */ public set key(value: CollectionKey | undefined) { this.setKey(value); } /** * Returns the key/name identifier of the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/properties#key) * * @public */ public get key(): CollectionKey | undefined { return this._key; } /** * Updates the key/name identifier of the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#setkey) * * @public * @param value - New key/name identifier. */ public setKey(value: CollectionKey | undefined) { const oldKey = this._key; // Update Collection key this._key = value; // Update key in Persistent (only if oldKey is equal to persistentKey // because otherwise the persistentKey is detached from the Collection key // -> not managed by Collection anymore) if (value != null && this.persistent?._key === oldKey) this.persistent?.setKey(value); return this; } /** * Creates a new Group without associating it to the Collection. * * This way of creating a Group is intended for use in the Collection configuration object, * where the `constructor()` takes care of the binding. * * After a successful initiation of the Collection we recommend using `createGroup()`, * because it automatically connects the Group to the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#group) * * @public * @param initialItems - Key/Name identifiers of the Items to be clustered by the Group. * @param config - Configuration object */ public Group( initialItems?: Array<ItemKey>, config: GroupConfigInterface = {} ): Group<DataType> { if (this.isInstantiated) { const key = config.key ?? generateId(); logCodeManager.log('1B:02:00'); return this.createGroup(key, initialItems); } return new Group<DataType>(this, initialItems, config); } /** * Creates a new Selector without associating it to the Collection. * * This way of creating a Selector is intended for use in the Collection configuration object, * where the `constructor()` takes care of the binding. * * After a successful initiation of the Collection we recommend using `createSelector()`, * because it automatically connects the Group to the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#selector) * * @public * @param initialKey - Key/Name identifier of the Item to be represented by the Selector. * @param config - Configuration object */ public Selector( initialKey: ItemKey | null, config: SelectorConfigInterface = {} ): Selector<DataType> { if (this.isInstantiated) { const key = config.key ?? generateId(); logCodeManager.log('1B:02:01'); return this.createSelector(key, initialKey); } return new Selector<DataType>(this, initialKey, config); } /** * Sets up the specified Groups or Group keys * and assigns them to the Collection if they are valid. * * It also instantiates and assigns the default Group to the Collection. * The default Group reflects the default pattern of the Collection. * * @internal * @param groups - Entire Groups or Group keys to be set up. */ public initGroups(groups: { [key: string]: Group<any> } | string[]): void { if (!groups) return; let groupsObject: { [key: string]: Group<DataType> } = {}; // If groups is Array of Group keys/names, create the Groups based on these keys if (Array.isArray(groups)) { groups.forEach((groupKey) => { groupsObject[groupKey] = new Group<DataType>(this, [], { key: groupKey, }); }); } else groupsObject = groups; // Add default Group groupsObject[this.config.defaultGroupKey] = new Group<DataType>(this, [], { key: this.config.defaultGroupKey, }); // Assign missing key/name to Group based on the property key for (const key in groupsObject) if (groupsObject[key]._key == null) groupsObject[key].setKey(key); this.groups = groupsObject; } /** * Sets up the specified Selectors or Selector keys * and assigns them to the Collection if they are valid. * * @internal * @param selectors - Entire Selectors or Selector keys to be set up. */ public initSelectors(selectors: { [key: string]: Selector<any> } | string[]) { if (!selectors) return; let selectorsObject: { [key: string]: Selector<DataType> } = {}; // If selectors is Array of Selector keys/names, create the Selectors based on these keys if (Array.isArray(selectors)) { selectors.forEach((selectorKey) => { selectorsObject[selectorKey] = new Selector<DataType>( this, selectorKey, { key: selectorKey, } ); }); } else selectorsObject = selectors; // Assign missing key/name to Selector based on the property key for (const key in selectorsObject) if (selectorsObject[key]._key == null) selectorsObject[key].setKey(key); this.selectors = selectorsObject; } /** * Appends new data objects following the same pattern to the end of the Collection. * * Each collected `data object` requires a unique identifier at the primaryKey property (by default 'id') * to be correctly identified later. * * For example, if we collect some kind of user object, * it must contain such unique identifier at 'id' * to be added to the Collection. * ``` * MY_COLLECTION.collect({id: '1', name: 'jeff'}); // valid * MY_COLLECTION.collect({name: 'frank'}); // invalid * ``` * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#collect) * * @public * @param data - Data objects or entire Items to be added. * @param groupKeys - Group/s to which the specified data objects or Items are to be added. * @param config - Configuration object */ public collect( data: DataType | Item<DataType> | Array<DataType | Item<DataType>>, groupKeys?: GroupKey | Array<GroupKey>, config: CollectConfigInterface<DataType> = {} ): this { const _data = normalizeArray<DataType | Item<DataType>>(data); const _groupKeys = normalizeArray<GroupKey>(groupKeys); const defaultGroupKey = this.config.defaultGroupKey; const primaryKey = this.config.primaryKey; config = defineConfig(config, { method: 'push', background: false, patch: false, select: false, }); // Add default groupKey, since all Items are added to the default Group if (!_groupKeys.includes(defaultGroupKey)) _groupKeys.push(defaultGroupKey); // Create not existing Groups _groupKeys.forEach( (key) => this.groups[key] == null && this.createGroup(key) ); _data.forEach((data, index) => { let itemKey; let success = false; // Assign Data or Item to Collection if (data instanceof Item) { success = this.assignItem(data, { background: config.background, }); itemKey = data._key; } else { success = this.assignData(data, { patch: config.patch, background: config.background, }); itemKey = data[primaryKey]; } // Add itemKey to provided Groups and create corresponding Selector if (success) { _groupKeys.forEach((groupKey) => { this.getGroup(groupKey)?.add(itemKey, { method: config.method, background: config.background, }); }); if (config.select) this.createSelector(itemKey, itemKey); } if (config.forEachItem) config.forEachItem(data, itemKey, success, index); }); return this; } /** * Updates the Item `data object` with the specified `object with changes`, if the Item exists. * By default the `object with changes` is merged into the Item `data object` at top level. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#update) * * @public * @param itemKey - Key/Name identifier of the Item to be updated. * @param changes - Object with changes to be merged into the Item data object. * @param config - Configuration object */ public update( itemKey: ItemKey, changes: DefaultItem | DataType, config: UpdateConfigInterface = {} ): Item<DataType> | undefined { const item = this.getItem(itemKey, { notExisting: true }); const primaryKey = this.config.primaryKey; config = defineConfig(config, { patch: true, background: false, }); // Check if the given conditions are suitable for a update action if (item == null) { logCodeManager.log('1B:03:00', { replacers: [itemKey, this._key] }); return undefined; } if (!isValidObject(changes)) { logCodeManager.log('1B:03:01', { replacers: [itemKey, this._key] }); return undefined; } const oldItemKey = item._value[primaryKey]; const newItemKey = changes[primaryKey] || oldItemKey; // Update itemKey if the new itemKey differs from the old one if (oldItemKey !== newItemKey) this.updateItemKey(oldItemKey, newItemKey, { background: config.background, }); // Patch changes into Item data object if (config.patch) { // Delete primaryKey property from 'changes object' because if it has changed, // it is correctly updated in the above called 'updateItemKey()' method if (changes[primaryKey]) delete changes[primaryKey]; let patchConfig: { addNewProperties?: boolean } = typeof config.patch === 'object' ? config.patch : {}; patchConfig = { addNewProperties: true, ...patchConfig, }; item.patch(changes as any, { background: config.background, addNewProperties: patchConfig.addNewProperties, }); } // Apply changes to Item data object else { // Ensure that the current Item identifier isn't different from the 'changes object' itemKey if (changes[this.config.primaryKey] !== itemKey) { (changes as any)[this.config.primaryKey] = itemKey; logCodeManager.log('1B:02:02', {}, changes); } item.set(changes as any, { background: config.background, }); } return item; } /** * Creates a new Group and associates it to the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#createGroup) * * @public * @param groupKey - Unique identifier of the Group to be created. * @param initialItems - Key/Name identifiers of the Items to be clustered by the Group. */ public createGroup( groupKey: GroupKey, initialItems: Array<ItemKey> = [] ): Group<DataType> { let group = this.getGroup(groupKey, { notExisting: true }); if (!this.isInstantiated) logCodeManager.log('1B:02:03'); // Check if Group already exists if (group != null) { if (!group.isPlaceholder) { logCodeManager.log('1B:03:02', { replacers: [groupKey] }); return group; } group.set(initialItems, { overwrite: true }); return group; } // Create new Group group = new Group<DataType>(this, initialItems, { key: groupKey }); this.groups[groupKey] = group; return group; } /** * Returns a boolean indicating whether a Group with the specified `groupKey` * exists in the Collection or not. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#hasgroup) * * @public * @param groupKey - Key/Name identifier of the Group to be checked for existence. * @param config - Configuration object */ public hasGroup( groupKey: GroupKey | undefined, config: HasConfigInterface = {} ): boolean { return !!this.getGroup(groupKey, config); } /** * Retrieves a single Group with the specified key/name identifier from the Collection. * * If the to retrieve Group doesn't exist, `undefined` is returned. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getgroup) * * @public * @param groupKey - Key/Name identifier of the Group. * @param config - Configuration object */ public getGroup( groupKey: GroupKey | undefined | null, config: HasConfigInterface = {} ): Group<DataType> | undefined { config = defineConfig(config, { notExisting: false, }); // Retrieve Group const group = groupKey ? this.groups[groupKey] : undefined; // Check if retrieved Group exists if (group == null || (!config.notExisting && !group.exists)) return undefined; ComputedTracker.tracked(group.observers['value']); return group; } /** * Retrieves the default Group from the Collection. * * Every Collection should have a default Group, * which represents the default pattern of the Collection. * * If the default Group, for what ever reason, doesn't exist, `undefined` is returned. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getdefaultgroup) * * @public */ public getDefaultGroup(): Group<DataType> | undefined { return this.getGroup(this.config.defaultGroupKey); } /** * Retrieves a single Group with the specified key/name identifier from the Collection. * * If the to retrieve Group doesn't exist, a reference Group is returned. * This has the advantage that Components that have the reference Group bound to themselves * are rerenderd when the original Group is created. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getgroupwithreference) * * @public * @param groupKey - Key/Name identifier of the Group. */ public getGroupWithReference(groupKey: GroupKey): Group<DataType> { let group = this.getGroup(groupKey, { notExisting: true }); // Create dummy Group to hold reference if (group == null) { group = new Group<DataType>(this, [], { key: groupKey, isPlaceholder: true, }); this.groups[groupKey] = group; } ComputedTracker.tracked(group.observers['value']); return group; } /** * Removes a Group with the specified key/name identifier from the Collection, * if it exists in the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#removegroup) * * @public * @param groupKey - Key/Name identifier of the Group to be removed. */ public removeGroup(groupKey: GroupKey): this { if (this.groups[groupKey] != null) delete this.groups[groupKey]; return this; } /** * Returns the count of registered Groups in the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getgroupcount) * * @public */ public getGroupCount(): number { let size = 0; Object.keys(this.groups).map(() => size++); return size; } /** * Creates a new Selector and associates it to the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#createSelector) * * @public * @param selectorKey - Unique identifier of the Selector to be created. * @param itemKey - Key/Name identifier of the Item to be represented by the Selector. */ public createSelector( selectorKey: SelectorKey, itemKey: ItemKey | null ): Selector<DataType> { let selector = this.getSelector(selectorKey, { notExisting: true }); if (!this.isInstantiated) logCodeManager.log('1B:02:04'); // Check if Selector already exists if (selector != null) { if (!selector.isPlaceholder) { logCodeManager.log('1B:03:03', { replacers: [selectorKey] }); return selector; } selector.select(itemKey, { overwrite: true }); return selector; } // Create new Selector selector = new Selector<DataType>(this, itemKey, { key: selectorKey, }); this.selectors[selectorKey] = selector; return selector; } /** * Creates a new Selector and associates it to the Collection. * * The specified `itemKey` is used as the unique identifier key of the new Selector. * ``` * MY_COLLECTION.select('1'); * // is equivalent to * MY_COLLECTION.createSelector('1', '1'); * ``` * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#select) * * @public * @param itemKey - Key/Name identifier of the Item to be represented by the Selector * and used as unique identifier of the Selector. */ public select(itemKey: ItemKey): Selector<DataType> { return this.createSelector(itemKey, itemKey); } /** * Returns a boolean indicating whether a Selector with the specified `selectorKey` * exists in the Collection or not. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#hasselector) * * @public * @param selectorKey - Key/Name identifier of the Selector to be checked for existence. * @param config - Configuration object */ public hasSelector( selectorKey: SelectorKey | undefined, config: HasConfigInterface = {} ): boolean { return !!this.getSelector(selectorKey, config); } /** * Retrieves a single Selector with the specified key/name identifier from the Collection. * * If the to retrieve Selector doesn't exist, `undefined` is returned. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getselector) * * @public * @param selectorKey - Key/Name identifier of the Selector. * @param config - Configuration object */ public getSelector( selectorKey: SelectorKey | undefined | null, config: HasConfigInterface = {} ): Selector<DataType> | undefined { config = defineConfig(config, { notExisting: false, }); // Get Selector const selector = selectorKey ? this.selectors[selectorKey] : undefined; // Check if Selector exists if (selector == null || (!config.notExisting && !selector.exists)) return undefined; ComputedTracker.tracked(selector.observers['value']); return selector; } /** * Retrieves a single Selector with the specified key/name identifier from the Collection. * * If the to retrieve Selector doesn't exist, a reference Selector is returned. * This has the advantage that Components that have the reference Selector bound to themselves * are rerenderd when the original Selector is created. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getselectorwithreference) * * @public * @param selectorKey - Key/Name identifier of the Selector. */ public getSelectorWithReference( selectorKey: SelectorKey ): Selector<DataType> { let selector = this.getSelector(selectorKey, { notExisting: true }); // Create dummy Selector to hold reference if (selector == null) { selector = new Selector<DataType>(this, null, { key: selectorKey, isPlaceholder: true, }); this.selectors[selectorKey] = selector; } ComputedTracker.tracked(selector.observers['value']); return selector; } /** * Removes a Selector with the specified key/name identifier from the Collection, * if it exists in the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#removeselector) * * @public * @param selectorKey - Key/Name identifier of the Selector to be removed. */ public removeSelector(selectorKey: SelectorKey): this { if (this.selectors[selectorKey] != null) { this.selectors[selectorKey].unselect(); delete this.selectors[selectorKey]; } return this; } /** * Returns the count of registered Selectors in the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getselectorcount) * * @public */ public getSelectorCount(): number { let size = 0; Object.keys(this.selectors).map(() => size++); return size; } /** * Returns a boolean indicating whether a Item with the specified `itemKey` * exists in the Collection or not. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#hasitem) * * @public * @param itemKey - Key/Name identifier of the Item. * @param config - Configuration object */ public hasItem( itemKey: ItemKey | undefined, config: HasConfigInterface = {} ): boolean { return !!this.getItem(itemKey, config); } /** * Retrieves a single Item with the specified key/name identifier from the Collection. * * If the to retrieve Item doesn't exist, `undefined` is returned. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getitem) * * @public * @param itemKey - Key/Name identifier of the Item. * @param config - Configuration object */ public getItem( itemKey: ItemKey | undefined | null, config: HasConfigInterface = {} ): Item<DataType> | undefined { config = defineConfig(config, { notExisting: false, }); // Get Item const item = itemKey != null ? this.data[itemKey] : undefined; // Check if Item exists if (item == null || (!config.notExisting && !item.exists)) return undefined; ComputedTracker.tracked(item.observers['value']); return item; } /** * Retrieves a single Item with the specified key/name identifier from the Collection. * * If the to retrieve Item doesn't exist, a reference Item is returned. * This has the advantage that Components that have the reference Item bound to themselves * are rerenderd when the original Item is created. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getitemwithreference) * * @public * @param itemKey - Key/Name identifier of the Item. */ public getItemWithReference(itemKey: ItemKey): Item<DataType> { let item = this.getItem(itemKey, { notExisting: true }); // Create dummy Item to hold reference if (item == null) item = this.createPlaceholderItem(itemKey, true); ComputedTracker.tracked(item.observers['value']); return item; } /** * Creates a placeholder Item * that can be used to hold a reference to a not existing Item. * * @internal * @param itemKey - Unique identifier of the to create placeholder Item. * @param addToCollection - Whether to add the Item to be created to the Collection. */ public createPlaceholderItem( itemKey: ItemKey, addToCollection = false ): Item<DataType> { // Create placeholder Item const item = new Item<DataType>( this, { [this.config.primaryKey]: itemKey, // Setting primaryKey of the Item to passed itemKey dummy: 'item', } as any, { isPlaceholder: true } ); // Add placeholder Item to Collection if ( addToCollection && !Object.prototype.hasOwnProperty.call(this.data, itemKey) ) this.data[itemKey] = item; ComputedTracker.tracked(item.observers['value']); return item; } /** * Retrieves the value (data object) of a single Item * with the specified key/name identifier from the Collection. * * If the to retrieve Item containing the value doesn't exist, `undefined` is returned. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getitemvalue) * * @public * @param itemKey - Key/Name identifier of the Item. * @param config - Configuration object */ public getItemValue( itemKey: ItemKey | undefined, config: HasConfigInterface = {} ): DataType | undefined { const item = this.getItem(itemKey, config); if (item == null) return undefined; return item.value; } /** * Retrieves all Items from the Collection. * ``` * MY_COLLECTION.getAllItems(); * // is equivalent to * MY_COLLECTION.getDefaultGroup().items; * ``` * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getallitems) * * @public * @param config - Configuration object */ public getAllItems(config: HasConfigInterface = {}): Array<Item<DataType>> { config = defineConfig(config, { notExisting: false, }); const defaultGroup = this.getDefaultGroup(); let items: Array<Item<DataType>> = []; // If config.notExisting transform the data object into array since it contains all Items, // otherwise return the default Group Items if (config.notExisting) { for (const key in this.data) items.push(this.data[key]); } else { // Why default Group Items and not all '.exists === true' Items? // Because the default Group keeps track of all existing Items. // It also does control the Collection output in binding methods like 'useAgile()' // and therefore should do it here too. items = defaultGroup?.getItems() || []; } return items; } /** * Retrieves the values (data objects) of all Items from the Collection. * ``` * MY_COLLECTION.getAllItemValues(); * // is equivalent to * MY_COLLECTION.getDefaultGroup().output; * ``` * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getallitemvalues) * * @public * @param config - Configuration object */ public getAllItemValues(config: HasConfigInterface = {}): Array<DataType> { const items = this.getAllItems(config); return items.map((item) => item.value); } /** * Preserves the Collection `value` in the corresponding external Storage. * * The Collection key/name is used as the unique identifier for the Persistent. * If that is not desired or the Collection has no unique identifier, * please specify a separate unique identifier for the Persistent. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#persist) * * @public * @param config - Configuration object */ public persist(config: CreatePersistentConfigInterface = {}): this { config = defineConfig(config, { key: this.key, }); // Check if Collection is already persisted if (this.persistent != null && this.isPersisted) return this; // Create Persistent (-> persist value) this.persistent = new CollectionPersistent<DataType>(this, config); return this; } /** * Fires immediately after the persisted `value` * is loaded into the Collection from a corresponding external Storage. * * Registering such callback function makes only sense * when the Collection is [persisted](https://agile-ts.org/docs/core/collection/methods/#persist) in an external Storage. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#onload) * * @public * @param callback - A function to be executed after the externally persisted `value` was loaded into the Collection. */ public onLoad(callback: (success: boolean) => void): this { if (!this.persistent) return this; if (!isFunction(callback)) { logCodeManager.log('00:03:01', { replacers: ['OnLoad Callback', 'function'], }); return this; } // Register specified callback this.persistent.onLoad = callback; // If Collection is already persisted ('isPersisted') fire specified callback immediately if (this.isPersisted) callback(true); return this; } /** * Removes all Items from the Collection * and resets all Groups and Selectors of the Collection. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#reset) * * @public */ public reset(): this { // Reset data this.data = {}; this.size = 0; // Reset Groups for (const key in this.groups) this.getGroup(key)?.reset(); // Reset Selectors for (const key in this.selectors) this.getSelector(key)?.reset(); return this; } /** * Puts `itemKeys/s` into Group/s. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#put) * * @public * @param itemKeys - `itemKey/s` to be put into the specified Group/s. * @param groupKeys - Key/Name Identifier/s of the Group/s the specified `itemKey/s` are to put in. * @param config - Configuration object */ public put( itemKeys: ItemKey | Array<ItemKey>, groupKeys: GroupKey | Array<GroupKey>, config: GroupAddConfigInterface = {} ): this { const _itemKeys = normalizeArray(itemKeys); const _groupKeys = normalizeArray(groupKeys); // Assign itemKeys to Groups _groupKeys.forEach((groupKey) => { this.getGroup(groupKey)?.add(_itemKeys, config); }); return this; } /** * Moves specified `itemKey/s` from one Group to another Group. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#move) * * @public * @param itemKeys - `itemKey/s` to be moved. * @param oldGroupKey - Key/Name Identifier of the Group the `itemKey/s` are moved from. * @param newGroupKey - Key/Name Identifier of the Group the `itemKey/s` are moved in. * @param config - Configuration object */ public move( itemKeys: ItemKey | Array<ItemKey>, oldGroupKey: GroupKey, newGroupKey: GroupKey, config: GroupAddConfigInterface = {} ): this { const _itemKeys = normalizeArray(itemKeys); // Remove itemKeys from old Group this.getGroup(oldGroupKey)?.remove(_itemKeys, config); // Assign itemKeys to new Group this.getGroup(newGroupKey)?.add(_itemKeys, config); return this; } /** * Updates the key/name identifier of the Item * and returns a boolean indicating * whether the Item identifier was updated successfully. * * @internal * @param oldItemKey - Old key/name Item identifier. * @param newItemKey - New key/name Item identifier. * @param config - Configuration object */ public updateItemKey( oldItemKey: ItemKey, newItemKey: ItemKey, config: UpdateItemKeyConfigInterface = {} ): boolean { const item = this.getItem(oldItemKey, { notExisting: true }); config = defineConfig(config, { background: false, }); if (item == null || oldItemKey === newItemKey) return false; // Check if Item with newItemKey already exists if (this.hasItem(newItemKey)) { logCodeManager.log('1B:03:04', { replacers: [oldItemKey, newItemKey, this._key], }); return false; } // Update itemKey in data object delete this.data[oldItemKey]; this.data[newItemKey] = item; // Update key/name of the Item item.setKey(newItemKey, { background: config.background, }); // Update Persistent key of the Item if it follows the Item Storage Key pattern // and therefore differs from the actual Item key // (-> isn't automatically updated when the Item key is updated) if ( item.persistent != null && item.persistent._key === CollectionPersistent.getItemStorageKey(oldItemKey, this._key) ) item.persistent?.setKey( CollectionPersistent.getItemStorageKey(newItemKey, this._key) ); // Update itemKey in Groups for (const groupKey in this.groups) { const group = this.getGroup(groupKey, { notExisting: true }); if (group == null || !group.has(oldItemKey)) continue; group.replace(oldItemKey, newItemKey, { background: config.background }); } // Update itemKey in Selectors for (const selectorKey in this.selectors) { const selector = this.getSelector(selectorKey, { notExisting: true }); if (selector == null) continue; // Reselect Item in Selector that has selected the newItemKey. // Necessary because potential reference placeholder Item got overwritten // with the new (renamed) Item // -> has to find the new Item at selected itemKey // since the placeholder Item got overwritten if (selector.hasSelected(newItemKey, false)) { selector.reselect({ force: true, // Because itemKeys are the same (but not the Items at this itemKey anymore) background: config.background, }); } // Select newItemKey in Selector that has selected the oldItemKey if (selector.hasSelected(oldItemKey, false)) selector.select(newItemKey, { background: config.background, }); } return true; } /** * Returns all key/name identifiers of the Group/s containing the specified `itemKey`. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#getgroupkeysthathaveitemkey) * * @public * @param itemKey - `itemKey` to be contained in Group/s. */ public getGroupKeysThatHaveItemKey(itemKey: ItemKey): Array<GroupKey> { const groupKeys: Array<GroupKey> = []; for (const groupKey in this.groups) { const group = this.groups[groupKey]; if (group?.has(itemKey)) groupKeys.push(groupKey); } return groupKeys; } /** * Removes Item/s from: * * - `.everywhere()`: * Removes Item/s from the entire Collection and all its Groups and Selectors (i.e. from everywhere) * ``` * MY_COLLECTION.remove('1').everywhere(); * // is equivalent to * MY_COLLECTION.removeItems('1'); * ``` * - `.fromGroups()`: * Removes Item/s only from specified Groups. * ``` * MY_COLLECTION.remove('1').fromGroups(['1', '2']); * // is equivalent to * MY_COLLECTION.removeFromGroups('1', ['1', '2']); * ``` * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#remove) * * @public * @param itemKeys - Item/s with identifier/s to be removed. */ public remove( itemKeys: ItemKey | Array<ItemKey> ): { fromGroups: (groups: Array<ItemKey> | ItemKey) => Collection<DataType>; everywhere: (config?: RemoveItemsConfigInterface) => Collection<DataType>; } { return { fromGroups: (groups: Array<ItemKey> | ItemKey) => this.removeFromGroups(itemKeys, groups), everywhere: (config) => this.removeItems(itemKeys, config || {}), }; } /** * Remove Item/s from specified Group/s. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#removefromgroups) * * @public * @param itemKeys - Key/Name Identifier/s of the Item/s to be removed from the Group/s. * @param groupKeys - Key/Name Identifier/s of the Group/s the Item/s are to remove from. */ public removeFromGroups( itemKeys: ItemKey | Array<ItemKey>, groupKeys: GroupKey | Array<GroupKey> ): this { const _itemKeys = normalizeArray(itemKeys); const _groupKeys = normalizeArray(groupKeys); _itemKeys.forEach((itemKey) => { let removedFromGroupsCount = 0; // Remove itemKey from the Groups _groupKeys.forEach((groupKey) => { const group = this.getGroup(groupKey, { notExisting: true }); if (!group?.has(itemKey)) return; group.remove(itemKey); removedFromGroupsCount++; }); // If the Item was removed from each Group representing the Item, // remove it completely if ( removedFromGroupsCount >= this.getGroupKeysThatHaveItemKey(itemKey).length ) this.removeItems(itemKey); }); return this; } /** * Removes Item/s from the entire Collection and all the Collection's Groups and Selectors. * * [Learn more..](https://agile-ts.org/docs/core/collection/methods/#removeitems) * * @public * @param itemKeys - Key/Name identifier/s of the Item/s to be removed from the entire Collection. * @param config - Configuration object */ public removeItems( itemKeys: ItemKey | Array<ItemKey>, config: RemoveItemsConfigInterface = {} ): this { config = defineConfig(config, { notExisting: false, removeSelector: false, }); const _itemKeys = normalizeArray<ItemKey>(itemKeys); _itemKeys.forEach((itemKey) => { const item = this.getItem(itemKey, { notExisting: config.notExisting }); if (item == null) return; const wasPlaceholder = item.isPlaceholder; // Remove Item from the Groups for (const groupKey in this.groups) { const group = this.getGroup(groupKey, { notExisting: true }); if (group?.has(itemKey)) group?.remove(itemKey); } // Remove Item from Storage item.persistent?.removePersistedValue(); // Remove Item from Collection delete this.data[itemKey]; // Reselect or remove Selectors which have represented the removed Item for (const selectorKey in this.selectors) { const selector = this.getSelector(selectorKey, { notExisting: true }); if (selector != null && selector.hasSelected(itemKey, false)) { if (config.removeSelector) { // Remove Selector this.removeSelector(selector._key ?? 'unknown'); } else { // Reselect Item in Selector // in order to create a new dummyItem // to hold a reference to the now not existing Item selector.reselect({ force: true }); } } } if (!wasPlaceholder) this.size--; }); return this; } /** * Assigns the provided `data` object to an already existing Item * with specified key/name identifier found in the `data` object. * If the Item doesn't exist yet, a new Item with the `data` object as value * is created and assigned to the Collection. * * Returns a boolean indicating * whether the `data` object was assigned/updated successfully. * * @internal * @param data - Data object * @param config - Configuration object */ public assignData( data: DataType, config: AssignDataConfigInterface = {} ): boolean { config = defineConfig(config, { patch: false, background: false, }); const _data = copy(data); // Copy data object to get rid of reference const primaryKey = this.config.primaryKey; if (!isValidObject(_data)) { logCodeManager.log('1B:03:05', { replacers: [this._key] }); return false; } // Check if data object contains valid itemKey, // otherwise add random itemKey to Item if (!Object.prototype.hasOwnProperty.call(_data, primaryKey)) { logCodeManager.log('1B:02:05', { replacers: [this._key, primaryKey] }); (_data as any)[primaryKey] = generateId(); } const itemKey = _data[primaryKey]; const item = this.getItem(itemKey, { notExisting: true }); const wasPlaceholder = item?.isPlaceholder || false; // Create new Item or update existing Item if (item != null) { if (config.patch) { item.patch(_data, { background: config.background }); } else { item.set(_data, { background: config.background }); } } else { this.assignItem(new Item<DataType>(this, _data), { background: config.background, }); } // Increase size of Collection if Item was previously a placeholder // (-> hasn't officially existed in Collection before) if (wasPlaceholder) this.size++; return true; } /** * Assigns the specified Item to the Collection * at the key/name identifier of the Item. * * And returns a boolean indicating * whether the Item was assigned successfully. * * @internal * @param item - Item to be added. * @param config - Configuration object */ public assignItem( item: Item<DataType>, config: AssignItemConfigInterface = {} ): boolean { config = defineConfig(config, { overwrite: false, background: false, rebuildGroups: true, }); const primaryKey = this.config.primaryKey; let itemKey = item._value[primaryKey]; let increaseCollectionSize = true; // Check if Item has valid itemKey, // otherwise add random itemKey to Item if (!Object.prototype.hasOwnProperty.call(item._value, primaryKey)) { logCodeManager.log('1B:02:05', { replacers: [this._key, primaryKey] }); itemKey = generateId(); item.patch( { [this.config.primaryKey]: itemKey }, { background: config.background } ); item._key = itemKey; } // Check if Item belongs to this Collection if (item.collection() !== this) { logCodeManager.log('1B:03:06', { replacers: [this._key, item.collection()._key], }); return false; } // Check if Item already exists if (this.getItem(itemKey, { notExisting: true }) != null) { if (!config.overwrite) { this.assignData(item._value); return true; } else increaseCollectionSize = false; } // Assign/add Item to Collection this.data[itemKey] = item; // Rebuild Groups that include itemKey // after adding Item with itemKey to the Collection // (because otherwise it can't find the Item as it isn't added yet) if (config.rebuildGroups) this.rebuildGroupsThatIncludeItemKey(itemKey, { background: config.background, }); if (increaseCollectionSize) this.size++; return true; } /** * Rebuilds all Groups that contain the specified `itemKey`. * * @internal * @itemKey - `itemKey` Groups must contain to be rebuilt. * @config - Configuration object */ public rebuildGroupsThatIncludeItemKey( itemKey: ItemKey, config: GroupIngestConfigInterface = {} ): void { // Rebuild Groups that include itemKey for (const groupKey of Object.keys(this.groups)) { const group = this.getGroup(groupKey); if (group != null && group.has(itemKey)) { const index = group._preciseItemKeys.findIndex((ik) => itemKey === ik); // Update Group output at index if (index !== -1) { group.rebuild( [ { key: itemKey, index: index, method: TrackedChangeMethod.UPDATE, }, ], config ); } // Add Item to the Group output if it isn't yet represented there to be updated else { const indexOfBeforeItemKey = group.nextStateValue.findIndex((ik) => itemKey === ik) - 1; group.rebuild( [ { key: itemKey, index: indexOfBeforeItemKey >= 0 ? group._preciseItemKeys.findIndex( (ik) => group.nextStateValue[indexOfBeforeItemKey] === ik ) + 1 : 0, method: TrackedChangeMethod.ADD, }, ], config ); } } } } } export type DefaultItem = Record<string, any>; // same as { [key: string]: any }; export type CollectionKey = string | number; export type ItemKey = string | number; export interface CreateCollectionConfigImpl< DataType extends DefaultItem = DefaultItem > { /** * Initial Groups of the Collection. * @default [] */ groups?: { [key: string]: Group<any> } | string[]; /** * Initial Selectors of the Collection * @default [] */ selectors?: { [key: string]: Selector<any> } | string[]; /** * Key/Name identifier of the Collection. * @default undefined */ key?: CollectionKey; /** * Key/Name of the property * which represents the unique Item identifier * in collected data objects. * @default 'id' */ primaryKey?: string; /** * Key/Name identifier of the default Group that is created shortly after instantiation. * The default Group represents the default pattern of the Collection. * @default 'default' */ defaultGroupKey?: GroupKey; /** * Initial data objects of the Collection. * @default [] */ initialData?: Array<DataType>; } export type CreateCollectionConfig< DataType extends DefaultItem = DefaultItem > = | CreateCollectionConfigImpl<DataType> | (( collection: Collection<DataType> ) => CreateCollectionConfigImpl<DataType>); export interface CollectionConfigInterface { /** * Key/Name of the property * which represents the unique Item identifier * in collected data objects. * @default 'id' */ primaryKey: string; /** * Key/Name identifier of the default Group that is created shortly after instantiation. * The default Group represents the default pattern of the Collection. * @default 'default' */ defaultGroupKey: ItemKey; } export interface CollectConfigInterface<DataType = any> extends AssignDataConfigInterface { /** * In which way the collected data should be added to the Collection. * - 'push' = at the end * - 'unshift' = at the beginning * https://www.tutorialspoint.com/what-are-the-differences-between-unshift-and-push-methods-in-javascript * @default 'push' */ method?: 'push' | 'unshift'; /** * Performs the specified action for each collected data object. * @default undefined */ forEachItem?: ( data: DataType | Item<DataType>, key: ItemKey, success: boolean, index: number ) => void; /** * Whether to create a Selector for each collected data object. * @default false */ select?: boolean; } export interface UpdateConfigInterface { /** * Whether to merge the data object with changes into the existing Item data object * or overwrite the existing Item data object entirely. * @default true */ patch?: boolean | PatchOptionConfigInterface; /** * Whether to update the data object in background. * So that the UI isn't notified of these changes and thus doesn't rerender. * @default false */ background?: boolean; } export interface UpdateItemKeyConfigInterface { /** * Whether to update the Item key/name identifier in background * So that the UI isn't notified of these changes and thus doesn't rerender. * @default false */ background?: boolean; } export interface HasConfigInterface { /** * Whether Items that do not officially exist, * such as placeholder Items, can be found * @default true */ notExisting?: boolean; } export interface RemoveItemsConfigInterface { /** * Whether to remove not officially existing Items (such as placeholder Items). * Keep in mind that sometimes it won't remove an Item entirely * as another Instance (like a Selector) might need to keep reference to it. * https://github.com/agile-ts/agile/pull/152 * @default false */ notExisting?: boolean; /** * Whether to remove Selectors that have selected an Item to be removed. * @default false */ removeSelector?: boolean; } export interface AssignDataConfigInterface { /** * When the Item identifier of the to assign data object already exists in the Collection, * whether to merge the newly assigned data into the existing one * or overwrite the existing one entirely. * @default true */ patch?: boolean; /** * Whether to assign the data object to the Collection in background. * So that the UI isn't notified of these changes and thus doesn't rerender. * @default false */ background?: boolean; } export interface AssignItemConfigInterface { /** * If an Item with the Item identifier already exists, * whether to overwrite it entirely with the new one. * @default false */ overwrite?: boolean; /** * Whether to assign the Item to the Collection in background. * So that the UI isn't notified of these changes and thus doesn't rerender. * @default false */ background?: boolean; /** * Whether to rebuild all Groups that include the itemKey of the to assign Item. * @default true */ rebuildGroups?: boolean; }
the_stack
import { PluginOptions } from '@/typings/config/plugin'; import { Emitter } from '@/typings/event'; const pluginOptions: PluginOptions = { bus(): void {}, dir: 'foo', }; beforeEach((): void => { jest.resetModules(); }); describe('@modus/gimbal-plugin-last-value/storage', (): void => { describe('getLastReport', (): void => { it('should handle no last report', async (): Promise<void> => { const report = { success: true }; const fire = jest.fn().mockResolvedValue({ rets: [] }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no child data', async (): Promise<void> => { const report = { success: true }; const fire = jest.fn().mockResolvedValue({ rets: [{ report: {} }], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no parent data', async (): Promise<void> => { const report = { data: [ { label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Bar', rawLabel: 'Bar', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle no matched child data', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Bar', rawLabel: 'Bar', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).not.toHaveBeenCalled(); }); it('should handle not changing success', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], success: false, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({}), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should apply last values on report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: (1 / 3) * 100, lastValueDiff: 1, rawLabel: 'Foo', rawLastValue: 2, rawValue: 3, success: true, type: 'size', value: '3', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should apply last values on report as a string that fails', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: 80, lastValueDiff: 8, rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry'], ['module/registry']]); }); it('should handle unknown threshold type', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ getMeta: (): void => undefined, }); const { getLastReport } = await import('./storage'); await getLastReport('command/size', { ...pluginOptions, bus }, config, report, EventEmitter); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus.mock.calls).toEqual([['module/registry'], ['module/registry']]); }); it('should allow threshold breach failure', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const fire = jest.fn().mockResolvedValue({ rets: [ { report: JSON.stringify({ data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 2, success: true, type: 'size', value: '2', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }), }, ], }); const config = { failOnBreach: false, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const bus = jest.fn().mockResolvedValue({ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ getMeta: (): any => ({ thresholdLimit: 'upper', thresholdType: 'number', }), }); const { getLastReport } = await import('./storage'); await getLastReport( 'command/size', { ...pluginOptions, bus, }, config, report, EventEmitter, ); expect(report).toEqual({ data: [ { data: [ { label: 'Foo', lastValue: '2', lastValueChange: 80, lastValueDiff: 8, rawLabel: 'Foo', rawLastValue: 2, rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/get', { command: 'size', }); expect(bus).toHaveBeenCalledWith('module/registry'); }); }); describe('saveReport', (): void => { it('should save successful report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/save', { command: 'size', report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: true, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: true, type: 'size', }, }); }); it('should not save failed report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: true, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).not.toHaveBeenCalled(); }); it('should save failed report', async (): Promise<void> => { const report = { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }; const config = { failOnBreach: true, saveOnlyOnSuccess: false, thresholds: { diffPercentage: 50, number: 1, percentage: 1, size: 1, }, }; const fire = jest.fn(); const EventEmitter: Emitter = { /* eslint-disable-next-line @typescript-eslint/no-explicit-any */ on(): any {}, fire, }; const { saveReport } = await import('./storage'); await saveReport('command/size', config, report, EventEmitter); expect(fire).toHaveBeenCalledWith('plugin/last-value/report/save', { command: 'size', report: { data: [ { data: [ { label: 'Foo', rawLabel: 'Foo', rawValue: 10, success: false, type: 'size', value: '10', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, ], label: 'Foo', rawLabel: 'Foo', success: false, type: 'size', }, }); }); }); });
the_stack
import * as assert from "assert"; import { testContext, disposeTestDocumentStore } from "../../Utils/TestUtil"; import { DeleteDocumentCommand, GetStatisticsOperation, IDocumentSession, IDocumentStore, PutAttachmentOperation } from "../../../src"; import { User } from "../../Assets/Entities"; import { CONSTANTS } from "../../../src/Constants"; describe("AttachmentsRevisions", function () { let store: IDocumentStore; beforeEach(async function () { store = await testContext.getDocumentStore(); }); afterEach(async () => await disposeTestDocumentStore(store)); it("can put attachments", async () => { await testContext.setupRevisions(store, false, 4); const names = await createDocumentWithAttachments(); await assertRevisions(names, (session, revisions) => { assertRevisionAttachments(names, 3, revisions[0], session); assertRevisionAttachments(names, 2, revisions[1], session); assertRevisionAttachments(names, 1, revisions[2], session); assertNoRevisionAttachment(revisions[3], session, false); }, 9); // Delete document should delete all the attachments await store.getRequestExecutor().execute(new DeleteDocumentCommand("users/1")); await assertRevisions(names, (session, revisions) => { assertNoRevisionAttachment(revisions[0], session, true); assertRevisionAttachments(names, 3, revisions[1], session); assertRevisionAttachments(names, 2, revisions[2], session); assertRevisionAttachments(names, 1, revisions[3], session); }, 6, 0, 3); // Create another revision which should delete old revision { // This will delete the revision #1 which is without attachment const session = store.openSession(); const user = new User(); user.name = "Fitzchak 2"; await session.store(user, "users/1"); await session.saveChanges(); } await assertRevisions(names, (session, revisions) => { // This will delete the revision #2 which is with attachment assertNoRevisionAttachment(revisions[0], session, false); assertNoRevisionAttachment(revisions[1], session, true); assertRevisionAttachments(names, 3, revisions[2], session); assertRevisionAttachments(names, 2, revisions[3], session); }, 5, 1, 3); { // This will delete the revision #2 which is with attachment const session = store.openSession(); const user = new User(); user.name = "Fitzchak 3"; await session.store(user, "users/1"); await session.saveChanges(); } await assertRevisions(names, (session, revisions) => { // This will delete the revision #2 which is with attachment assertNoRevisionAttachment(revisions[0], session, false); assertNoRevisionAttachment(revisions[1], session, false); assertNoRevisionAttachment(revisions[2], session, true); assertRevisionAttachments(names, 3, revisions[3], session); }, 3, 1, 3); { // This will delete the revision #3 which is with attachment const session = store.openSession(); const user = new User(); user.name = "Fitzchak 4"; await session.store(user, "users/1"); await session.saveChanges(); } await assertRevisions(names, (session, revisions) => { // This will delete the revision #3 which is with attachment assertNoRevisionAttachment(revisions[0], session, false); assertNoRevisionAttachment(revisions[1], session, false); assertNoRevisionAttachment(revisions[2], session, false); assertNoRevisionAttachment(revisions[3], session, true); }, 0, 1, 0); { // This will delete the revision #4 which is with attachment const session = store.openSession(); const user = new User(); user.name = "Fitzchak 5"; await session.store(user, "users/1"); await session.saveChanges(); } await assertRevisions(names, (session, revisions) => { // This will delete the revision #3 which is with attachment assertNoRevisionAttachment(revisions[0], session, false); assertNoRevisionAttachment(revisions[1], session, false); assertNoRevisionAttachment(revisions[2], session, false); assertNoRevisionAttachment(revisions[3], session, false); }, 0, 1, 0); }); it("attachment revision", async () => { await testContext.setupRevisions(store, false, 4); const names = await createDocumentWithAttachments(); { const session = store.openSession(); const stream = Buffer.from([5, 4, 3, 2, 1]); session.advanced.attachments.store("users/1", "profile.png", stream); await session.saveChanges(); } { const session = store.openSession(); const revisions = await session.advanced.revisions.getFor<User>("users/1"); const changeVector = session.advanced.getChangeVectorFor(revisions[1]); const revision = await session.advanced.attachments.getRevision("users/1", "profile.png", changeVector); try { const data = revision.data.read(3); assert.strictEqual(data[0], 1); assert.strictEqual(data[1], 2); assert.strictEqual(data[2], 3); } finally { revision.dispose(); } } }); const createDocumentWithAttachments = async () => { { const session = store.openSession(); const user = new User(); user.name = "Fitzchak"; await session.store(user, "users/1"); await session.saveChanges(); } const names = ["profile.png", "background-photo.jpg", "fileNAME_#$1^%_בעברית.txt"]; const profileStream = Buffer.from([1, 2, 3]); let result = await store.operations.send( new PutAttachmentOperation("users/1", names[0], profileStream, "image/png")); assert.ok(result.changeVector.includes("A:3")); assert.strictEqual(result.name, names[0]); assert.strictEqual(result.documentId, "users/1"); assert.strictEqual(result.contentType, "image/png"); const backgroundStream = Buffer.from([10, 20, 30, 40, 50]); result = await store.operations.send( new PutAttachmentOperation("users/1", names[1], backgroundStream, "ImGgE/jPeG")); assert.ok(result.changeVector.includes("A:7")); assert.strictEqual(result.name, names[1]); assert.strictEqual(result.documentId, "users/1"); assert.strictEqual(result.contentType, "ImGgE/jPeG"); const fileStream = Buffer.from([1, 2, 3, 4, 5]); result = await store.operations.send( new PutAttachmentOperation("users/1", names[2], fileStream, null)); assert.ok(result.changeVector.includes("A:12")); assert.strictEqual(result.name, names[2]); assert.strictEqual(result.documentId, "users/1"); assert.ok(!result.contentType); return names; }; const assertRevisions = async (names: string[], assertAction: (session: IDocumentSession, users: User[]) => void, expectedCountOfAttachments: number, expectedCountOfDocuments = 1, expectedCountOfUniqueAttachments = 3) => { const statistics = await store.maintenance.send(new GetStatisticsOperation()); assert.strictEqual(statistics.countOfAttachments, expectedCountOfAttachments); assert.strictEqual(statistics.countOfUniqueAttachments, expectedCountOfUniqueAttachments); assert.strictEqual(statistics.countOfRevisionDocuments, 4); assert.strictEqual(statistics.countOfDocuments, expectedCountOfDocuments); assert.strictEqual(statistics.countOfIndexes, 0); { const session = store.openSession(); const revisions: User[] = await session.advanced.revisions.getFor<User>("users/1"); assert.strictEqual(revisions.length, 4); assertAction(session, revisions); } }; const assertNoRevisionAttachment = (revision: User, session: IDocumentSession, isDeleteRevision: boolean) => { const metadata = session.advanced.getMetadataFor(revision); if (isDeleteRevision) { const flags = metadata[CONSTANTS.Documents.Metadata.FLAGS] as string; assert.ok(flags.includes("HasRevisions")); assert.ok(flags.includes("DeleteRevision")); } else { const flags = metadata[CONSTANTS.Documents.Metadata.FLAGS] as string; assert.ok(flags.includes("HasRevisions")); assert.ok(flags.includes("Revision")); } assert.ok(!metadata[CONSTANTS.Documents.Metadata.ATTACHMENTS]); }; const assertRevisionAttachments = (names: string[], expectedCount: number, revision: User, session: IDocumentSession) => { const metadata = session.advanced.getMetadataFor(revision); const flags = metadata["@flags"]; assert.ok(flags.includes("HasRevisions")); assert.ok(flags.includes("Revision")); assert.ok(flags.includes("HasAttachments")); const attachments = metadata["@attachments"]; assert.strictEqual(attachments.length, expectedCount); const orderedNames = names.slice(0); if (orderedNames.length > expectedCount) { orderedNames.length = expectedCount; } orderedNames.sort(); for (let i = 0; i < expectedCount; i++) { const name = orderedNames[i]; const attachment = attachments[i]; assert.strictEqual(attachment.name, name); } }; });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormAnnotation_Information { interface tab_general_Sections { account_information: DevKit.Controls.Section; attachment_information: DevKit.Controls.Section; content_information: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Unique identifier of the user who created the note. */ CreatedBy: DevKit.Controls.Lookup; /** Date and time when the note was created. */ CreatedOn: DevKit.Controls.DateTime; filenameattachment: DevKit.Controls.ActionCards; /** File size of the note. */ FileSize: DevKit.Controls.Integer; /** Specifies whether the note is an attachment. */ IsDocument: DevKit.Controls.Boolean; /** Unique identifier of the user who last modified the note. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the note was last modified. */ ModifiedOn: DevKit.Controls.DateTime; notetext: DevKit.Controls.ActionCards; /** Unique identifier of the user or team who owns the note. */ OwnerId: DevKit.Controls.Lookup; regardingobject: DevKit.Controls.ActionCards; } } class FormAnnotation_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Annotation_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 Annotation_Information */ Body: DevKit.FormAnnotation_Information.Body; } namespace FormNote_Quick_Create_Form { interface tab_general_Sections { notes_information: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Text of the note. */ NoteText: DevKit.Controls.String; /** Subject associated with the note. */ Subject: DevKit.Controls.String; } } class FormNote_Quick_Create_Form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Note_Quick_Create_Form * @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 Note_Quick_Create_Form */ Body: DevKit.FormNote_Quick_Create_Form.Body; } class AnnotationApi { /** * DynamicsCrm.DevKit AnnotationApi * @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 note. */ AnnotationId: DevKit.WebApi.GuidValue; /** Unique identifier of the user who created the note. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the note was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the annotation. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Contents of the note's attachment. */ DocumentBody: DevKit.WebApi.StringValue; /** File name of the note. */ FileName: DevKit.WebApi.StringValue; /** File pointer of the attachment. */ FilePointer: DevKit.WebApi.StringValueReadonly; /** File size of the note. */ FileSize: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Specifies whether the note is an attachment. */ IsDocument: DevKit.WebApi.BooleanValue; IsPrivate: DevKit.WebApi.BooleanValueReadonly; /** Language identifier for the note. */ LangId: DevKit.WebApi.StringValue; /** MIME type of the note's attachment. */ MimeType: DevKit.WebApi.StringValue; /** Unique identifier of the user who last modified the note. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the note was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the annotation. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Text of the note. */ NoteText: DevKit.WebApi.StringValue; /** Unique identifier of the object with which the note is associated. */ objectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_calendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ channelaccessprofile_annotations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_profileruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_convertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_duplicaterule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_email: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_emailserverprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_mailbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_routingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_routingruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_sharepointdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_sla: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the note is associated. */ objectid_workflow: 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 of the business unit that owns the note. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the note. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the note. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Prefix of the file pointer in blob storage. */ Prefix: DevKit.WebApi.StringValueReadonly; /** workflow step id associated with the note. */ StepId: DevKit.WebApi.StringValue; /** Storage pointer. */ StoragePointer: DevKit.WebApi.StringValueReadonly; /** Subject associated with the note. */ Subject: DevKit.WebApi.StringValue; /** Version number of the note. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Annotation { enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Quick Create Form'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
//-------------------------------------------------------------------- // Javascript DSL for writing Eve programs //-------------------------------------------------------------------- import {RawValue, Change, RawEAV, RawEAVC, Register, isRegister, GlobalInterner, ID, concatArray} from "./runtime"; import * as Runtime from "./runtime"; import * as indexes from "./indexes"; import {Watcher, Exporter, DiffConsumer, ObjectConsumer, RawRecord} from "../watchers/watcher"; import * as Parser from "../parser/parser"; import "./stdlib"; import {SumAggregate} from "./stdlib"; import {v4 as uuid} from "uuid"; import * as falafel from "falafel"; const UNASSIGNED = -1; const operators:any = { "+": "math['+']", "-": "math['-']", "*": "math['*']", "/": "math['/']", ">": "compare['>']", ">=": "compare['>=']", "<": "compare['<']", "<=": "compare['<=']", "!=": "compare['!=']", "==": "compare['==']", "concat": "eve.internal.concat", } // There don't seem to be TypeScript definitions for these by default, // so here we are. declare var Proxy:new (obj:any, proxy:any) => any; function isArray<T>(v:any): v is Array<T> { return v && v.constructor === Array; } function isASTString(thing:any) { return thing.value && typeof thing.value === "string"; } function macro<FuncType extends Function>(func:FuncType, transform:(code:string, args:string[], name:string) => string):FuncType { let code = func.toString(); // trim the function(...) { from the start and capture the arg names let name:string = ""; code = code.replace(/function\s*(\w*)\s*/, (str:string, funcName:string) => { name = funcName; return ""; }) let functionArgs:string[] = []; code = code.replace(/\((.*)\)\s*\{/m, function(str:string, args:string) { functionArgs.push.apply(functionArgs, args.split(",").map((str) => str.trim())); return ""; }); // trim the final } since we removed the function bit code = code.substring(0, code.length - 1); code = transform(code, functionArgs, name); let neueFunc = (new Function(` return function ${name}(${functionArgs.join(", ")}) { ${code} }; `))() as FuncType; return neueFunc; } //-------------------------------------------------------------------- // Reference //-------------------------------------------------------------------- export type Value = Reference|RawValue; export type ProxyReference = any; function isRawValue(v:any): v is RawValue { return (typeof v === "string" || typeof v === "number"); } function isReference(v:any): v is Reference { return (v instanceof Reference); } export type Owner = any; export class Reference { static ReferenceID = 0; static create(context:ReferenceContext, value?:Owner|RawValue) { if(typeof value !== "object") { let neue = new Reference(context); if(value !== undefined) context.equality(neue, value); return neue; } return new Reference(context, value); } __ID = Reference.ReferenceID++; __forceRegister = false; constructor(public __context:ReferenceContext, public __owner?:Owner) { let proxied = this.__proxy(); __context.register(proxied); this.__owner = __owner || null; return proxied; } add(attrMap:{[attr:string]:Value|Value[]}):Reference; add(attribute:Value, value:Value|Value[]):Reference; add(attrMapOrAttr:Value|{[attr:string]:Value|Value[]}, value?:Value|Value[]):Reference { if(!this.__owner) { this.__owner = new Record(this.__context, [], {}, this); } if(this.__owner instanceof Record) { // we only allow you to call add at the root context if(this.__context.parent) throw new Error("Add can't be called in a sub-block"); if(isRawValue(attrMapOrAttr) || isReference(attrMapOrAttr)) { let attribute = attrMapOrAttr; if(value === undefined) throw new Error("Can't call add without a value."); this.__owner.add(this.__context, attribute, value); } else { for(let attribute of Object.keys(attrMapOrAttr)) { let value = attrMapOrAttr[attribute]; this.__owner.add(this.__context, attribute, value); } } return this; } else { throw new Error("Can't call add on a non-record"); } } // @TODO: allow free A's and V's here remove(attribute?:Value, value?:Value|Value[]):Reference { if(!this.__owner) { this.__owner = new Record(this.__context, [], {}, this); } if(this.__owner instanceof Record) { // we only allow you to call remove at the root context if(this.__context.parent) throw new Error("Add can't be called in a sub-block"); this.__owner.remove(this.__context, attribute as any, value as any); return this; } else { throw new Error("Can't call add on a non-record"); } } toString() { return `${this.__context.ID}.${this.__ID}`; } __proxy() { return new Proxy(this, { get: (obj:any, prop:string) => { if(obj[prop] !== undefined) return obj[prop]; if(typeof prop === "symbol") return () => { return "uh oh"; } let active = this.__context.getActive(); if(!active) { return; } if(!this.__owner) { this.__owner = new Record(active, [], {}, this); } return this.__owner.access(this.__context, active, prop); }, set: (obj:any, prop:string, value:any) => { if(obj[prop] !== undefined) { obj[prop] = value; return true; } throw new Error("Cannot set a value on a reference") } }); } } //-------------------------------------------------------------------- // ReferenceContext //-------------------------------------------------------------------- export class ReferenceContext { static IDs = 0; static stack:ReferenceContext[] = []; static push(context:ReferenceContext) { ReferenceContext.stack.push(context); } static pop() { ReferenceContext.stack.pop(); } ID:number; flow: LinearFlow; references:Reference[] = []; equalities:Value[][] = []; forcedMoves:Value[][] = []; referenceValues: (Register|RawValue)[] = []; totalRegisters = 0; maxRegisters = 0; constructor(public parent?:ReferenceContext, flow?:LinearFlow) { this.ID = ReferenceContext.IDs++; this.flow = flow || new LinearFlow((x:LinearFlow) => []); } register(ref:Reference) { // if this reference is not owned by this context, we have to walk up the context // stack and register this for our parents until we find a layer that *does* own it // so that it can be considered an input to that context. let {parent} = this; if(!this.owns(ref) && parent) { while(parent && parent !== ref.__context) { parent.register(ref); parent = parent.parent; } } if(!this.owns(ref) && parent !== ref.__context) { console.error("Reference with no owner in the parent stack: ", ref); throw new Error("Reference with no owner in the parent stack") } if(!this.references[ref.__ID]) this.references[ref.__ID] = ref; } equality(a:Value, b:Value) { if(a instanceof Reference) { this.register(a); } if(b instanceof Reference) { this.register(b); } this.equalities.push([a,b]); } getActive():ReferenceContext { return ReferenceContext.stack[ReferenceContext.stack.length - 1]; } owns(ref:Reference) { return ref.__context === this; } getValue(ref:Reference|RawValue, orGenerateRegister?:boolean):Register|RawValue { if(isRawValue(ref)) return ref; let val = this.referenceValues[ref.__ID]; if(val === undefined) { if(!this.owns(ref) && this.parent) return this.parent.getValue(ref); if(orGenerateRegister) { val = new Register(UNASSIGNED); this.referenceValues[ref.__ID] = val; } } if(val === undefined) throw new Error("Unable to resolve reference: " + ref.__ID); return val; } interned(ref:Reference|RawValue):Register|ID { let value = this.getValue(ref); if(isRawValue(value)) return GlobalInterner.intern(value); return value; } maybeInterned(ref:Reference|RawValue|undefined):Register|ID|undefined { if(ref === undefined) return; let value = this.getValue(ref); if(isRawValue(value)) return GlobalInterner.intern(value); return value; } selectReference(refIds:any, ref:Reference, ref2:Reference) { let refID = refIds[ref.__ID] || ref.__ID; let ref2ID = refIds[ref2.__ID] || ref2.__ID; if(!this.owns(ref) && !this.owns(ref2)) { if(ref2ID < refID) return ref2; return ref; } if(!this.owns(ref)) return ref; if(!this.owns(ref2)) return ref2; if(ref2ID < refID) return ref2; return ref; } unify() { let {equalities} = this; let values:(Register | RawValue)[] = this.referenceValues; let forcedMoves = []; let changed = equalities.length > 0; let refIds:any = {}; let round = 0; let maxRound = Math.pow(this.equalities.length + 1, 2); for(let ref of this.references) { if(!ref) continue; this.getValue(ref, true); } while(changed && round < maxRound) { round++; changed = false; for(let [a, b] of equalities) { let aValue = isReference(a) ? this.getValue(a, true) : a; let bValue = isReference(b) ? this.getValue(b, true) : b; let neueA = aValue; let neueB = bValue; if((a as Reference).__forceRegister || (b as Reference).__forceRegister) { forcedMoves.push([a,b]); } else if(!isRegister(neueB) && !isRegister(neueA) && neueA != neueB) { throw new Error(`Attempting to unify two disparate static values: \`${neueA}\` and \`${neueB}\``); } else if(isReference(a) && !isRegister(neueB)) { neueA = bValue; } else if(isReference(b) && !isRegister(neueA)) { neueB = aValue; } else if(isReference(a) && isReference(b)) { if(this.selectReference(refIds, a, b) === b) { neueA = bValue; refIds[a.__ID] = refIds[b.__ID] || b.__ID } else { neueB = aValue; refIds[b.__ID] = refIds[a.__ID] || a.__ID } } else if(isReference(a)) { neueA = bValue; } else if(isReference(b)) { neueB = aValue; } else if(a !== b) { throw new Error(`Attempting to unify two disparate static values: \`${a}\` and \`${b}\``); } if(aValue !== neueA) { // console.log("Unifying A", a.toString(), b.toString(), neueA, neueB); values[(a as Reference).__ID] = neueA; changed = true; } if(bValue !== neueB) { // console.log("Unifying B", a.toString(), b.toString(), neueA, neueB); values[(b as Reference).__ID] = neueB; changed = true; } } } if(round >= maxRound) { throw new Error("Unable to unify variables. This is almost certainly an implementation error."); } this.assignRegisters() this.forcedMoves = forcedMoves; } getMoves() { let moves = []; for(let [a,b] of this.forcedMoves) { let to = isReference(a) ? a : b; let from = to === a ? b : a; moves.push(new Move(this, from, to as Reference)); } for(let ref of this.references) { if(ref === undefined || this.owns(ref)) continue; let local = this.getValue(ref); let parent = ref.__context.getValue(ref); if(local !== parent) { moves.push(new Move(this, ref)); } } return moves; } getInputReferences():Reference[] { let refs = []; for(let reference of this.references) { if(!reference || this.owns(reference)) continue; refs.push(reference); } return refs; } getInputRegisters():Register[] { return this.getInputReferences().map((v) => this.getValue(v)).filter(isRegister) as Register[]; } updateMaxRegisters(maybeMax:number) { let parent:ReferenceContext|undefined = this; while(parent) { parent.maxRegisters = Math.max(parent.maxRegisters, maybeMax); parent = parent.parent; } } assignRegisters() { let startIx = this.parent ? this.parent.totalRegisters : 0; for(let ref of this.references) { if(ref === undefined) continue; let local = this.getValue(ref); if(isRegister(local)) { if(local.offset >= startIx) throw new Error("Trying to assign a register that already has a higher offset"); if(local.offset === UNASSIGNED) { local.offset = startIx++; } } } this.totalRegisters = startIx; this.updateMaxRegisters(startIx); } } //-------------------------------------------------------------------- // Linear Flow //-------------------------------------------------------------------- export type Node = Record | Insert | Fn | Not | Choose | Union | Aggregate | Lookup | Move; export type LinearFlowFunction = (self:LinearFlow) => (Value|Value[]) export type RecordAttributes = {[key:string]:Value|Value[]} export type FlowRecordArg = string | RecordAttributes export class FlowLevel { records:Record[] = []; lookups:Lookup[] = []; functions:Fn[] = []; aggregates:Aggregate[] = []; inserts:Insert[] = []; nots:Not[] = []; chooses:Choose[] = []; unions:Union[] = []; moves:Move[] = []; collect(node:Node) { if(node instanceof Insert) { this.inserts.push(node); } else if(node instanceof Record) { this.records.push(node); } else if(node instanceof Lookup) { this.lookups.push(node); } else if(node instanceof Fn) { this.functions.push(node); } else if(node instanceof Aggregate) { this.aggregates.push(node); } else if(node instanceof Not) { this.nots.push(node); } else if(node instanceof Choose) { this.chooses.push(node); } else if(node instanceof Union) { this.unions.push(node); } else if(node instanceof Move) { if(!this.moves.some((v) => v.toKey() == node.toKey())) { this.moves.push(node); } } else { console.error("Don't know how to collect this type of node: ", node); throw new Error("Unknown node type sent to collect"); } } findReference(node:any) { let ref = node.reference(); let items; if(node instanceof Record) { items = this.records; } else { console.error("Don't know how to lookup a: ", node); throw new Error("Unknown node type sent to findReference"); } for(let item of items) { if(item.reference() === ref) return item; } } toConstraints(injections:Node[]) { let items:(Record|Fn|Lookup)[] = []; concatArray(items, injections); concatArray(items, this.functions); concatArray(items, this.records); concatArray(items, this.lookups); concatArray(items, this.moves); return items; } compile(nodes:Runtime.Node[], injections:Node[], toPass:Node[]):Runtime.Node[] { let items = this.toConstraints(injections); let seen:any = {}; let constraints:Runtime.Constraint[] = []; for(let toCompile of items) { let compiled = toCompile.compile(); for(let item of compiled) { if(!(item instanceof Runtime.Scan)) { constraints.push(item as Runtime.Constraint); } else { let key = item.toKey(); if(!seen[key]) { seen[key] = true; constraints.push(item as Runtime.Constraint); } } } } let join:Runtime.Node; if(!nodes.length && constraints.length) { join = new Runtime.JoinNode(constraints); if(!this.records.length && !this.lookups.length && !this.moves.length) { (join as Runtime.JoinNode).isStatic = true; } } else if(constraints.length) { join = new Runtime.DownstreamJoinNode(constraints); } else if(nodes.length) { join = nodes.pop() as Runtime.Node; } else { join = new Runtime.NoopJoinNode([]); } // @NOTE: We need to unify all of our sub-blocks along with ourselves // before the root node can allocate registers. for(let not of this.nots) { // All sub blocks take their parents' items and embed them into // the sub block. This is to make sure that the sub only computes the // results that might actually join with the parent instead of the possibly // very large set of unjoined results. This isn't guaranteed to be optimal // and may very well cause us to do more work than necessary. For example if // the results of the inner join with many outers, we'll still enumerate the // whole set. This *may* be necessary for getting the correct multiplicities // anyways, so this is what we're doing. let notNodes = not.compile(toPass.concat(items)); // @TODO: once we have multiple nodes in a not (e.g. aggs, or recursive not/choose/union) // this won't be sufficient. let notJoinNode = notNodes[0]; join = new Runtime.AntiJoin(join, notJoinNode, not.getInputRegisters()) } for(let choose of this.chooses) { // For why we pass items down, see the comment about not join = choose.compile(join); } for(let union of this.unions) { // For why we pass items down, see the comment about not join = union.compile(join); } for(let aggregate of this.aggregates) { let aggregateNode = aggregate.compile(); join = new Runtime.MergeAggregateFlow(join, aggregateNode, aggregate.getJoinRegisters(), aggregate.getOutputRegisters()); } nodes.push(join); return nodes; } split(context:ReferenceContext):FlowLevel[] { let maxLevel = 0; // if a register can be filled from the database, it doesn't need to be up-leveled, // since we always have a value for it from the beginning. Let's find all of those // registers so we can ignore them in our functions let databaseSupported = concatArray([], this.records); concatArray(databaseSupported, this.lookups); let supported:boolean[] = []; for(let item of this.records) { let registers = item.getRegisters(); for(let register of registers) { supported[register.offset] = true; } } // Every register that's an input to this level is supported by the outer context, // so we don't need to level its output. for(let register of context.getInputRegisters()) { supported[register.offset] = true; } // Any move whose `from` is supported, has their `to` supported as well for(let move of this.moves) { let from = move.getInputRegisters()[0]; let to = move.getOutputRegisters()[0]; if(from && supported[from.offset]) { supported[to.offset] = true; } } // choose, union, and aggregates can cause us to need multiple levels // if there's something that relies on an output from one of those, it // has to come in a level after that thing is computed. let changed = false; let leveledRegisters:{[offset:number]: {level:number, providers:any[]}} = {}; let providerToLevel:{[id:number]: number} = {}; let items = concatArray([], this.chooses); concatArray(items, this.unions); concatArray(items, this.aggregates); for(let item of items) { for(let result of item.getOutputRegisters()) { let offset = result.offset; if(!supported[offset]) { let found = leveledRegisters[offset]; if(!found) { found = leveledRegisters[offset] = {level: 1, providers: []}; } leveledRegisters[offset].providers.push(item); providerToLevel[item.ID] = 0; changed = true; maxLevel = 1; } } } // go through all the functions, nots, chooses, and unions to see if they rely on // a register that has been leveled, if so, they need to move to a level after // the provider's heighest concatArray(items, this.functions); concatArray(items, this.nots); concatArray(items, this.moves); let remaining = items.length * items.length; while(changed && remaining > -1) { changed = false; for(let item of items) { remaining--; if(!item) continue; let changedProvider = false; let providerLevel = providerToLevel[item.ID] || 0; let regs = item.getInputRegisters(); for(let input of regs) { let inputInfo = leveledRegisters[input.offset]; if(inputInfo && inputInfo.level > providerLevel) { changedProvider = true; providerLevel = inputInfo.level; } } if(changedProvider) { providerToLevel[item.ID] = providerLevel; // level my outputs if(item.getOutputRegisters) { for(let output of item.getOutputRegisters()) { if(supported[output.offset]) continue; let outputInfo = leveledRegisters[output.offset]; if(!outputInfo) { outputInfo = leveledRegisters[output.offset] = {level: 0, providers: []}; } if(outputInfo.providers.indexOf(item) === -1) { outputInfo.providers.push(item); } if(outputInfo.level <= providerLevel) { outputInfo.level = providerLevel + 1; } } } maxLevel = Math.max(maxLevel, providerLevel); changed = true; } } } if(remaining === -1) { // we couldn't stratify throw new Error("Unstratifiable program: cyclic dependency"); } // now we put all our children into a series of objects that // represent each level let levels:FlowLevel[] = []; for(let ix = 0; ix <= maxLevel; ix++) { levels[ix] = new FlowLevel(); } // @FIXME: An implementation issue in 0.3.0 causes stratified subblocks (nots, unions, and chooses) to // break in several edge cases. To prevent foot-shootiness until we've resolved the problem, we disallow // any orderings which are potentially dangerous. let dangerousOrdering = false; // all database scans are at the first level for(let record of this.records) { levels[0].records.push(record); } for(let lookup of this.lookups) { levels[0].lookups.push(lookup); } // functions/nots/chooses/unions can all be in different levels for(let func of this.functions) { if(!func) continue; let level = providerToLevel[func.ID] || 0; levels[level].functions.push(func); } for(let not of this.nots) { let level = providerToLevel[not.ID] || 0; if(level > 0) dangerousOrdering = true; levels[level].nots.push(not); } for(let choose of this.chooses) { let level = providerToLevel[choose.ID] || 0; if(level > 0) dangerousOrdering = true; levels[level].chooses.push(choose); } for(let union of this.unions) { let level = providerToLevel[union.ID] || 0; if(level > 0) dangerousOrdering = true; levels[level].unions.push(union); } for(let aggregate of this.aggregates) { let level = providerToLevel[aggregate.ID] || 0; levels[level].aggregates.push(aggregate); } for(let move of this.moves) { let level = providerToLevel[move.ID] || 0; levels[level].moves.push(move); } if(dangerousOrdering) throw new Error(`Refusing to compile potentially dangerous ordering with stratified subblock(s). This is avoids an implementation issue in the 0.3 runtime. Until it's lifted, you can work around it by splitting any subblocks (nots, unions, or chooses) that depend directly on other subblocks into separate blocks. Please contact the Eve team on the mailing list for further assistance.`); return levels; } } export class DSLBase { static CurrentID = 1; ID = DSLBase.CurrentID++; } export class LinearFlow extends DSLBase { context:ReferenceContext; collector:FlowLevel = new FlowLevel(); levels:FlowLevel[] = []; results:Value[]; parent:LinearFlow|undefined; constructor(func:LinearFlowFunction, parent?:LinearFlow) { super(); let parentContext = parent ? parent.context : undefined; this.parent = parent; this.createLib(); this.context = new ReferenceContext(parentContext, this); let transformed = func; if(!parent) { transformed = this.transform(func); } ReferenceContext.push(this.context); let results = transformed.call(func, this) as Value[]; if(isArray(results)) this.results = results; else if(results === undefined) this.results = []; else this.results = [results]; for(let result of this.results) { if(isReference(result)) { this.context.register(result); } } ReferenceContext.pop(); } //------------------------------------------------------------------ // Create lib //------------------------------------------------------------------ lib: any; createLib() { let lib:any = {}; let registered = Runtime.FunctionConstraint.registered; for(let name in registered) { let parts = name.replace(/\/\//gi, "/slash").split("/").map((v) => v === "slash" ? "/" : v); let final = parts.pop(); let found = lib; for(let part of parts) { let next = found[part]; if(!next) next = found[part] = {}; found = next; } found[final!] = (...args:any[]) => { let fn = new Fn(this.context.getActive(), name, args); return fn.reference(); } } lib.compare["=="] = (a:any, b:any) => { this.context.getActive().equality(a, b); return b; } this.lib = lib; } //------------------------------------------------------------------ // Collector interactions //------------------------------------------------------------------ collect(node:Node) { this.collector.collect(node); } findReference(node:Node) { this.collector.findReference(node); } //------------------------------------------------------------------ // Inputs/outputs //------------------------------------------------------------------ getInputRegisters() { return this.context.getInputRegisters(); } //------------------------------------------------------------------ // End user API //------------------------------------------------------------------ find = (...args:FlowRecordArg[]):ProxyReference => { let tags = args; let attributes = tags.pop(); if(typeof attributes === "string") { tags.push(attributes); attributes = undefined; } let active = this.context.getActive(); let record = new Record(active, tags as string[], attributes); return record.reference(); } lookup = (record:Value): {attribute:ProxyReference, value:ProxyReference} => { let active = this.context.getActive(); let lookup = new Lookup(active, record); return lookup.output(); } record = (...args:FlowRecordArg[]):ProxyReference => { let tags = args; let attributes = tags.pop(); if(typeof attributes === "string") { tags.push(attributes); attributes = undefined; } let active = this.context.getActive(); let insert = new Insert(active, tags as string[], attributes); return insert.reference(); } not = (func:Function):void => { let active = this.context.getActive(); let not = new Not(func as LinearFlowFunction, active.flow.parent || this); return; } union = (...branches:Function[]):ProxyReference[] => { let active = this.context.getActive(); let union = new Union(active, branches, active.flow.parent || this); return union.results.slice(); } choose = (...branches:Function[]):ProxyReference[] => { let active = this.context.getActive(); let choose = new Choose(active, branches, active.flow.parent || this); return choose.results.slice(); } gather = (...projection:Reference[]) => { let active = this.context.getActive(); return new AggregateBuilder(active, projection); } //------------------------------------------------------------------ // Compile //------------------------------------------------------------------ unify() { this.context.unify(); } compile(_:Node[] = []):Runtime.Node[] { let items:Node[] = [] this.unify(); let nodes:Runtime.Node[] = []; for(let move of this.context.getMoves()) { this.collect(move); } // Split our collector into levels let levels = this.collector.split(this.context); let localItems = items.slice(); for(let level of levels) { nodes = level.compile(nodes, items, localItems); concatArray(localItems, level.toConstraints([])); } // all the inputs end up at the end let outputs:Runtime.OutputNode[] = []; for(let record of this.collector.inserts) { let compiled = record.compile(); for(let node of compiled) { if(node instanceof Runtime.WatchNode) { nodes.push(node); } else { outputs.push(node as any); // @FIXME: types } } } if(outputs.length) { nodes.push(new Runtime.OutputWrapperNode(outputs)); } this.levels = levels; return nodes; } //------------------------------------------------------------------ // Function transformation //------------------------------------------------------------------ transform(func:LinearFlowFunction) { return macro(func, this.transformCode); } transformCode = (code:string, functionArgs:string[]):string => { if(!functionArgs[0]) throw new Error(`Trying to create a block that has no args with code:\n\n\`\`\`\n${code}\n\`\`\``); var output = falafel(`function f() { var $___eve_block$ = ${functionArgs[0]}; ${code} }`, function (node:any) { if (node.type === 'BinaryExpression') { let func = operators[node.operator] as string; if(node.operator === "+" && (isASTString(node.left) || isASTString(node.right))) { func = operators["concat"]; } if(func) { node.update(`$___eve_block$.lib.${func}(${node.left.source()}, ${node.right.source()})`) } } }); let updated = output.toString(); updated = updated.replace("function f() {", ""); updated = updated.substring(0, updated.length - 1); return updated; } } //-------------------------------------------------------------------- // WatchFlow //-------------------------------------------------------------------- export class WatchFlow extends LinearFlow { collect(node:Node) { if(!(node instanceof Watch) && node instanceof Insert) { node = node.toWatch(); return; } super.collect(node); } } //-------------------------------------------------------------------- // CommitFlow //-------------------------------------------------------------------- export class CommitFlow extends LinearFlow { collect(node:Node) { if(!(node instanceof CommitInsert) && !(node instanceof CommitRemove) && node instanceof Insert) { node = node.toCommit(); return; } super.collect(node); } } //-------------------------------------------------------------------- // DSL runtime types //-------------------------------------------------------------------- //-------------------------------------------------------------------- // Record //-------------------------------------------------------------------- export class Record extends DSLBase { attributes:Value[]; constructor(public context:ReferenceContext, tags:string[] = [], attributes:RecordAttributes = {}, public record?:Reference) { super(); if(!record) { this.record = this.createReference(); } else { context.register(record); } let attrs:Value[] = []; for(let tag of tags) { attrs.push("tag", tag); } let keys = Object.keys(attributes).sort(); for(let attr of keys) { let value = attributes[attr]; if(isArray(value)) { for(let current of value) { if(isReference(current)) context.register(current as Reference); attrs.push(attr, current); } } else { if(isReference(value)) context.register(value as Reference); attrs.push(attr, value); } } this.attributes = attrs; context.flow.collect(this); } createReference() { return Reference.create(this.context, this); } createSub(context:ReferenceContext, record?:Reference):Record { return new Record(context, undefined, undefined, record); } reference() { return this.record!; } add(context:ReferenceContext, attribute:Value, value:Value|Value[]) { let insert = new Insert(context, [], {}, this.reference()); if(!isArray(value)) { insert.add(context, attribute, value); } else { for(let v of value) { insert.add(context, attribute, v); } } } remove(context:ReferenceContext, attribute:Value, value:Value|Value[]) { let insert = new Insert(context, [], {}, this.reference()); if(!isArray(value)) { insert.remove(context, attribute, value); } else { for(let v of value) { insert.remove(context, attribute, v); } } } copyToContext(activeContext:ReferenceContext) { let found = activeContext.flow.findReference(this); if(found) return found; let neue = this.createSub(activeContext, this.record); activeContext.register(this.record!); return neue; } findAttribute(name:string):Reference|undefined { let {attributes} = this; for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let attrName = attributes[ix]; let value = attributes[ix + 1]; if(attrName === name && isReference(value)) return value; } } access(refContext:ReferenceContext, activeContext:ReferenceContext, prop:string) { let record:Record = this; if(refContext !== activeContext) { record = this.copyToContext(activeContext); } let found = record.findAttribute(prop); if(found) return found; // we need to add this attribute to us and return that let attrRecord = this.createSub(activeContext); let attrRef = attrRecord.reference(); record.attributes.push(prop, attrRef); return attrRef; } getRegisters():Register[] { let values:Value[] = [this.record!]; let {attributes} = this; for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; values.push(a,v); } return values.map((v) => this.context.getValue(v)).filter(isRegister) as Register[]; } compile():(Runtime.Node|Runtime.Scan)[] { let {attributes, context} = this; let constraints = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id constraints.push(new Runtime.Scan(e, context.interned(a), context.interned(v), Runtime.IGNORE_REG)) } return constraints; } } //-------------------------------------------------------------------- // Lookup //-------------------------------------------------------------------- export class Lookup extends DSLBase { attribute:Reference; value:Reference; constructor(public context:ReferenceContext, public record:Value) { super(); if(isReference(record)) { context.register(record); } let attribute = new Record(context); let value = new Record(context); this.attribute = attribute.reference(); this.value = value.reference(); context.flow.collect(this); } reference():Reference { return this.record as Reference; } output() { return {attribute: this.attribute, value: this.value}; } compile():Runtime.Scan[] { let scans = []; let {context} = this; scans.push(new Runtime.Scan(context.interned(this.record), context.interned(this.attribute), context.interned(this.value), Runtime.IGNORE_REG)); return scans; } } //-------------------------------------------------------------------- // Move //-------------------------------------------------------------------- export class Move extends DSLBase { public to:Reference; constructor(public context:ReferenceContext, public from:Value, to?:Reference) { super(); if(isReference(from)) { context.register(from); } if(!to) { if(!isReference(from)) throw new Error("Move where the to is not a reference"); this.to = from; } else { this.to = to; } } toKey() { let from:any = isReference(this.from) ? `[${this.from.__ID}]` : this.from; let to:any = isReference(this.to) ? `[${this.to.__ID}]` : this.to; return `${from}|${to}` } getInputRegisters():Register[] { let value = this.context.getValue(this.from); if(isRegister(value)) { return [value]; } return []; } getOutputRegisters():Register[] { let {to} = this; let parent = to.__context.getValue(to) as Register; return [parent]; } compile():Runtime.Constraint[] { let {from, to} = this; let local = this.context.interned(from); let parent = to.__context.getValue(to) as Register; return [new Runtime.MoveConstraint(local, parent)]; } } //-------------------------------------------------------------------- // Insert //-------------------------------------------------------------------- export class Insert extends Record { constructor(public context:ReferenceContext, tags:string[] = [], attributes:RecordAttributes = {}, record?:Reference) { super(context, tags, attributes, record); if(!record) { // we have to make our ID generation function let args = []; for(let ix = 0, len = this.attributes.length; ix < len; ix += 2) { let a = this.attributes[ix]; let v = this.attributes[ix + 1]; args.push(a,v); } let genId = new Fn(context, "eve/internal/gen-id", args, this.reference()); } } createReference() { // @TODO: create an InsertReference type and return that here return Reference.create(this.context, this); } createSub(context:ReferenceContext, record?:Reference):Record { return new Insert(context, undefined, undefined, record); } add(context:ReferenceContext, attribute:Value, value:Value|Value[]) { if(!isArray(value)) { this.attributes.push(attribute, value); } else { for(let v of value) { this.attributes.push(attribute, v); } } return this.reference(); } remove(context:ReferenceContext, attribute:Value, value:Value|Value[]) { let remove = new Remove(context, [], {}, this.record); if(!isArray(value)) { remove.attributes.push(attribute, value); } else { for(let v of value) { remove.attributes.push(attribute, v); } } return this.reference(); } toWatch() { let watch = new Watch(this.context, [], {}, this.record); watch.attributes = this.attributes; return watch; } toCommit() { let commit = new CommitInsert(this.context, [], {}, this.record); commit.attributes = this.attributes; return commit; } compile():any[] { let {attributes, context} = this; let nodes = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id let n = uuid(); nodes.push(new Runtime.InsertNode(e, context.interned(a), context.interned(v), context.interned(n))) } return nodes; } } //-------------------------------------------------------------------- // Remove //-------------------------------------------------------------------- export class Remove extends Insert { toCommit() { let commit = new CommitRemove(this.context, [], {}, this.record); commit.attributes = this.attributes; return commit; } compile():any[] { let {attributes, context} = this; let nodes = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id let n = uuid(); let internedV:any = context.maybeInterned(v); // @FIXME internedV = internedV !== undefined ? internedV : Runtime.IGNORE_REG; let internedA:any = context.maybeInterned(a); // @FIXME internedA = internedA !== undefined ? internedA : Runtime.IGNORE_REG; nodes.push(new Runtime.RemoveNode(e, internedA, internedV, context.interned(n))); } return nodes; } } //-------------------------------------------------------------------- // Watch //-------------------------------------------------------------------- export class Watch extends Insert { compile():(Runtime.Node|Runtime.Scan)[] { let {attributes, context} = this; let nodes = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id let n = uuid(); nodes.push(new Runtime.WatchNode(e, context.interned(a), context.interned(v), context.interned(n), context.flow.ID)); } return nodes; } } //-------------------------------------------------------------------- // CommitInsert //-------------------------------------------------------------------- export class CommitInsert extends Insert { compile():any[] { let {attributes, context} = this; let nodes = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id let n = uuid(); nodes.push(new Runtime.CommitInsertNode(e, context.interned(a), context.interned(v), context.interned(n))); } return nodes; } } //-------------------------------------------------------------------- // CommitRemove //-------------------------------------------------------------------- export class CommitRemove extends Remove { compile():any[] { let {attributes, context} = this; let nodes = []; let e = context.interned(this.record!); for(let ix = 0, len = attributes.length; ix < len; ix += 2) { let a = attributes[ix]; let v = attributes[ix + 1]; // @TODO: get a real node id let n = uuid(); let internedV:any = context.maybeInterned(v); // @FIXME internedV = internedV !== undefined ? internedV : Runtime.IGNORE_REG; let internedA:any = context.maybeInterned(a); // @FIXME internedA = internedA !== undefined ? internedA : Runtime.IGNORE_REG; nodes.push(new Runtime.CommitRemoveNode(e, internedA, internedV, context.interned(n))); } return nodes; } } //-------------------------------------------------------------------- // Fn //-------------------------------------------------------------------- export class Fn extends DSLBase { output:Value; constructor(public context:ReferenceContext, public name:string, public args:Value[], output?:Reference) { super(); let {filter} = Runtime.FunctionConstraint.fetchInfo(name) if(output) { this.output = output; } else if(filter) { this.output = args[args.length - 1]; } else { this.output = Reference.create(context, this); } for(let arg of args) { if(isReference(arg)) { context.register(arg); } } context.flow.collect(this); } reference():Value { return this.output; } access(refContext:ReferenceContext, activeContext:ReferenceContext, prop:string) { throw new Error("Implement me!"); } getInputRegisters() { let {context} = this; return this.args.map((v) => context.getValue(v)).filter(isRegister); } getOutputRegisters() { let registers = []; let value = this.context.getValue(this.output); if(isRegister(value)) { registers.push(value); } return registers; } compile():Runtime.Constraint[] { let constraints:Runtime.FunctionConstraint[] = []; let {context, name} = this; let values = this.args.map((v) => context.interned(v)) let {variadic, filter} = Runtime.FunctionConstraint.fetchInfo(name) let returns:any = {}; if(!filter) { returns.result = context.interned(this.output); } let constraint; if(variadic) { constraint = Runtime.FunctionConstraint.create(name, returns, values)! } else { constraint = Runtime.FunctionConstraint.create(name, returns, [])! let ix = 0; for(let arg of constraint.argNames) { constraint.fields[arg] = values[ix]; ix++; } } constraints.push(constraint); return constraints; } } //-------------------------------------------------------------------- // Aggregate //-------------------------------------------------------------------- export class Aggregate extends DSLBase { output: Reference; constructor(public context:ReferenceContext, public aggregate:any, public projection:Reference[], public group:Reference[], public args:Value[], output?:Reference) { super(); if(output) { this.output = output; } else { this.output = Reference.create(context, this); } this.output.__forceRegister = true; // add all of our args to our projection for(let arg of args) { if(isReference(arg)) { projection.push(arg); } } context.flow.collect(this); } getJoinRegisters():Register[] { let {context} = this; let items = [] as any[]; //concatArray([], this.args); if(this.aggregate === Runtime.SortNode) { concatArray(items, this.projection); } concatArray(items, this.group); return items.map((v) => context.getValue(v)).filter(isRegister) as Register[]; } getInputRegisters():Register[] { let {context} = this; let items = concatArray([], this.args); concatArray(items, this.projection); concatArray(items, this.group); return items.map((v) => context.getValue(v)).filter(isRegister) as Register[]; } getOutputRegisters():Register[] { // @TODO: should this blow up if it doesn't resolve to a register? let value = this.context.getValue(this.output); return [value as Register]; } compile() { let {context} = this; let groupRegisters = this.group.map((v) => context.getValue(v)).filter(isRegister); let projectRegisters = this.projection.map((v) => context.getValue(v)).filter(isRegister); let inputs = this.args.map((v) => context.interned(v)); let agg = new this.aggregate(groupRegisters, projectRegisters, inputs, this.getOutputRegisters()); return agg; } reference():Reference { return this.output; } per(...args:Reference[]) { for(let arg of args) { this.group.push(arg); } } } export class AggregateBuilder { group:Reference[] = []; constructor(public context:ReferenceContext, public projection:Reference[]) { } per(...args:Reference[]) { for(let arg of args) { this.group.push(arg); } return this; } checkBlock() { let active = this.context.getActive(); if(active !== this.context) throw new Error("Cannot gather in one scope and aggregate in another"); } sum(value:Reference):any { this.checkBlock(); let agg = new Aggregate(this.context, SumAggregate, this.projection, this.group, [value]); return agg.reference(); } count():any { this.checkBlock(); let agg = new Aggregate(this.context, SumAggregate, this.projection, this.group, [1]); return agg.reference(); } sort(...directions:Value[]):any { this.checkBlock(); let agg = new Aggregate(this.context, Runtime.SortNode, this.projection, this.group, directions); return agg.reference(); } } //-------------------------------------------------------------------- // Not //-------------------------------------------------------------------- export class Not extends LinearFlow { constructor(func:LinearFlowFunction, parent:LinearFlow) { super(func, parent); parent.collect(this); } } //-------------------------------------------------------------------- // Union //-------------------------------------------------------------------- export class Union extends DSLBase { branches:LinearFlow[] = []; results:Reference[] = []; inputs:Reference[] = []; branchInputs:Reference[][] = []; constructor(public context:ReferenceContext, branchFunctions: Function[], parent:LinearFlow, existingResults?:Reference[]) { super(); let {branches, results} = this; let resultCount:number|undefined; if(existingResults) { resultCount = existingResults.length; this.results = existingResults.slice(); results = this.results; for(let result of results) { if(isReference(result)) { result.__forceRegister = true; } else { throw new Error("Non-reference choose/union result"); } } } let ix = 0; for(let branch of branchFunctions) { let flow = new LinearFlow(branch as LinearFlowFunction, parent); let branchResultCount = this.resultCount(flow.results); if(resultCount === undefined) { resultCount = branchResultCount; for(let resultIx = 0; resultIx < resultCount; resultIx++) { let ref = Reference.create(context); ref.__forceRegister = true; results.push(ref); } } else if(resultCount !== branchResultCount) { throw new Error(`Choose branch ${ix} doesn't have the right number of returns. I expected ${resultCount}, but got ${branchResultCount}`); } this.setBranchInputs(ix, flow.context.getInputReferences()); let resultIx = 0; for(let result of results) { flow.collect(new Move(flow.context, flow.results[resultIx], result)); resultIx++; } branches.push(flow); ix++; } context.flow.collect(this); } setBranchInputs(branchIx:number, inputs:Reference[]) { let branchInputs:Reference[] = this.branchInputs[branchIx] = []; for(let ref of inputs) { if(this.inputs.indexOf(ref) === -1) { this.inputs.push(ref); } branchInputs.push(ref); } } getInputRegisters() { let {context} = this; let inputs = this.inputs.map((v) => context.getValue(v)).filter(isRegister) as Register[]; return inputs; } getOutputRegisters() { let {context} = this; return this.results.map((v) => context.getValue(v)).filter(isRegister) as Register[]; } resultCount(result:any):number { if(result && result.constructor === Array) { return result.length; } else if(result) { return 1; } return 0; } build(left: Runtime.Node, nodes:Runtime.Node[], inputs:Register[][], outputs:Register[], extraOuterJoins:Register[]):Runtime.Node { return new Runtime.UnionFlow(left, nodes, inputs, outputs, extraOuterJoins); } compile(join:Runtime.Node) { let {context, branchInputs} = this; let nodes:Runtime.Node[] = []; let inputs:Register[][] = []; let outputs = this.getOutputRegisters(); let ix = 0; for(let flow of this.branches) { if(flow.collector.chooses.length > 0 || flow.collector.unions.length > 0) { throw new Error("Nested chooses and unions are not currently supported"); } let compiled = flow.compile(); // @NOTE: Not sure why TS isn't correctly pegging this as filtered to only Registers already. let flowInputs = branchInputs[ix].map((v) => context.getValue(v)).filter(isRegister) as Register[]; if(compiled.length > 1) { // if this branch has an aggregate in it, we need to do some surgery to make sure that // the JoinNode gets wrapped in an AggregateOuterLookup. For the motivation see the // comment about the definition for AggregateOuterLookup. if(flow.collector.aggregates.length > 0) { let aggMerge = compiled[0] as Runtime.MergeAggregateFlow; // we have to make sure that the outer lookup fields are actually used in the join node for // the aggregate merge otherwise they will never join. For example if you have: // // board = [#board size: N, not(winner)] // winner = if N = gather/count[for: cell, per: col] // cell = [#bar board col player] // then player // // N is both the input to the branch as well as the output of the aggregate, but it won't // be available when doing the join *before* the aggregate. If it's included in the outer // lookup we'll join the board size with undefined every time and always fail. let outerLookupInputs = flowInputs.filter((v:Register) => { let next = aggMerge.left; if(next instanceof Runtime.JoinNode) { return next.registerLookup[v.offset]; } else { throw new Error("Don't know how to handle multi-node aggregates that don't start with a join"); } }); aggMerge.left = new Runtime.AggregateOuterLookup(join, aggMerge.left, outerLookupInputs) } nodes.push(new Runtime.LinearFlow(compiled)); } else { nodes.push(compiled[0]); } inputs.push(flowInputs); ix++; } let extraJoins:Register[] = []; for(let result of this.results) { if(result.__owner && result.__owner instanceof Record && result.__owner.attributes.length) { let maybeReg = context.getValue(result); if(isRegister(maybeReg)) { extraJoins.push(maybeReg); } } } return this.build(join, nodes, inputs, this.getOutputRegisters(), extraJoins); } } //-------------------------------------------------------------------- // Choose //-------------------------------------------------------------------- export class Choose extends Union { build(left: Runtime.Node, nodes:Runtime.Node[], inputs:Register[][], outputs:Register[], extraOuterJoins:Register[]):Runtime.Node { return new Runtime.ChooseFlow(left, nodes, inputs, outputs, extraOuterJoins); } } //-------------------------------------------------------------------- // Program //-------------------------------------------------------------------- // You can specify changes as either [e,a,v] or [e,a,v,round,count]; export type EAVTuple = [RawValue, RawValue, RawValue]; export type EAVRCTuple = [RawValue, RawValue, RawValue, number, number]; export type TestChange = EAVTuple | EAVRCTuple; export class Program { context:Runtime.EvaluationContext; blocks:Runtime.Block[] = []; flows:LinearFlow[] = []; index:indexes.Index; nodeCount = 0; nextTransactionId = 0; protected exporter = new Exporter(); protected lastWatch?:number; protected watchers:{[id:string]: Watcher|undefined} = {}; protected _constants?:{[key:string]: RawValue}; constructor(public name:string) { this.index = new indexes.HashIndex(); this.context = new Runtime.EvaluationContext(this.index); } constants(obj:{[key:string]: RawValue}) { if(!this._constants) this._constants = {}; for(let constant in obj) { if(this._constants[constant] && this._constants[constant] !== obj[constant]) { // throw new Error("Unable to rebind existing constant"); } this._constants[constant] = obj[constant]; } return this; } injectConstants(func:LinearFlowFunction):LinearFlowFunction { if(!this._constants) return func; return macro(func, (code) => { let constants = this._constants!; for(let constant in constants) { code = code.replace(new RegExp(`{{${constant}}}`, "gm"), "" + constants[constant]); } return code; }); } clear() { this.index = new indexes.HashIndex(); this.context = new Runtime.EvaluationContext(this.index); } _bind(name:string, flow:LinearFlow) { let nodes = flow.compile(); let block = new Runtime.Block(name, nodes, flow.context.maxRegisters); this.flows.push(flow); this.blocks.push(block); return block; } bind(name:string, func:LinearFlowFunction) { let flow = new LinearFlow(this.injectConstants(func)); this._bind(name, flow); return this; } blockChangeTransaction(added:Runtime.Block[], removed:Runtime.Block[]) { for(let remove of removed) { let ix = this.blocks.indexOf(remove) this.blocks.splice(ix, 1); } // console.time("input"); let trans = new Runtime.BlockChangeTransaction(this.context, this.nextTransactionId++, added, removed, this.blocks, this.lastWatch ? this.exporter.handle : undefined); trans.exec(this.context); // console.timeEnd("input"); // console.info(trans.changes.map((change, ix) => ` <- ${change}`).join("\n")); return trans; } input(changes:Runtime.Change[]) { // console.time("input"); if(changes[0].transaction >= this.nextTransactionId) this.nextTransactionId = changes[0].transaction + 1; let trans = new Runtime.Transaction(this.context, changes[0].transaction, this.blocks, this.lastWatch ? this.exporter.handle : undefined); for(let change of changes) { trans.output(this.context, change); } trans.exec(this.context); // console.timeEnd("input"); // console.info(trans.changes.map((change, ix) => ` <- ${change}`).join("\n")); // let g:any = global; // let filterPrefix = "eve/compiler/"; // let filteredIds = g.filteredIds = g.filteredIds || []; // for(let change of trans.changes) { // if(change.a == GlobalInterner.get("tag") && (""+GlobalInterner.reverse(change.v)).indexOf(filterPrefix) == 0) { // filteredIds.push(change.e); // } // } // let filtered = trans.changes.filter((c) => filteredIds.indexOf(c.e) !== -1); // if(filtered.length) { // console.log("---------------INPUT-----------") // console.log(filtered.map((change, ix) => ` <- ${change}`).join("\n")); // } return trans; } inputEAVs(eavcs:(RawEAVC|RawEAV)[]) { let changes:Change[] = []; let transactionId = this.nextTransactionId++; for(let [e, a, v, c = 1] of eavcs as RawEAVC[]) { changes.push(Change.fromValues(e, a, v, "input", transactionId, 0, c)); } return this.input(changes); } test(transaction:number, eavns:TestChange[]) { if("group" in console) console.group(this.name + " test " + transaction); if(transaction >= this.nextTransactionId) this.nextTransactionId = transaction + 1; let trans = new Runtime.Transaction(this.context, transaction, this.blocks, this.lastWatch ? this.exporter.handle : undefined); for(let [e, a, v, round = 0, count = 1] of eavns as EAVRCTuple[]) { let change = Runtime.Change.fromValues(e, a, v, "input", transaction, round, count); trans.output(this.context, change); } trans.exec(this.context); console.info(trans.changes.map((change, ix) => ` <- ${change}`).join("\n")); if("group" in console) console.groupEnd(); return this; } _commit(name:string, flow:LinearFlow) { let nodes = flow.compile(); let block = new Runtime.Block(name, nodes, flow.context.maxRegisters); this.flows.push(flow); this.blocks.push(block); return block; } commit(name:string, func:LinearFlowFunction) { let flow = new CommitFlow(this.injectConstants(func)); this._commit(name, flow); return this; } attach(id:string) { let WatcherConstructor = Watcher.get(id); if(!WatcherConstructor) throw new Error(`Unable to attach unknown watcher '${id}'.`); if(this.watchers[id]) return this.watchers[id]; let watcher = new WatcherConstructor(this); this.watchers[id] = watcher; return watcher; } _watch(name:string, flow:WatchFlow) { let nodes = flow.compile(); let block = new Runtime.Block(name, nodes, flow.context.maxRegisters); this.lastWatch = flow.ID; this.flows.push(flow); this.blocks.push(block); return block; } watch(name:string, func:LinearFlowFunction) { let flow = new WatchFlow(this.injectConstants(func)); this._watch(name, flow); return this; } asDiffs(handler:DiffConsumer) { if(!this.lastWatch) throw new Error("Must have at least one watch block to export as diffs."); this.exporter.triggerOnDiffs(this.lastWatch, handler); return this; } asObjects<Pattern extends RawRecord>(handler:ObjectConsumer<Pattern>) { if(!this.exporter || !this.lastWatch) throw new Error("Must have at least one watch block to export as diffs."); this.exporter.triggerOnObjects(this.lastWatch, handler); return this; } load(str:string) { let results = Parser.parseDoc(str); this.attach("ui"); this.attach("html"); this.attach("compiler"); if(results.results.eavs.length) { this.inputEAVs(results.results.eavs); } } }
the_stack
import fm from "front-matter"; import mustache from "mustache"; import { micromark } from "micromark"; import { TASK_TYPE, TASK_STATE } from "./taskrunner"; import { Node, Parent, visit } from "unist-util-visit"; import { parse as svelteParse } from "svelte/compiler"; import { parsePanel } from "./myst"; import { taskScriptSource } from "./templates"; import type { CodeNode, CodeNodeAttributes, ParsedDocument, ScriptNode, MystCard, } from "./types"; // remark plugin: extracts `{code-cell}` and other MyST chunks, removing them from the // markdown unless they are inline code chunks (actual processing of code chunks is handled // in ./parseMd.ts) export const processMyst = () => { return (tree: Node): void => { let unlabeledIdCounter = 0; const getAnonymousNode = () => { return { type: "html", value: `<CellResults value={__cell${unlabeledIdCounter++}} />`, }; }; visit(tree, ["code"], (node, _index, parent) => { const { lang, meta, value } = node as CodeNode; const index = _index as number; if (lang && lang.startsWith("{") && lang.endsWith("}")) { // myst directives are embedded in code chunks, with squiggly braces const mystType = lang.substr(1, lang.length - 2); if (mystType === "code-cell") { // FIXME: assumption that language is the only metadata // (should also validate) const lang = meta; const nodeAttributes = fm(value).attributes as CodeNodeAttributes; const isInline = nodeAttributes.inline; const anonymousNode = !nodeAttributes.id; if (isInline) { // inline node: take out the code cell parts, make them a // standard ""```foo" code chunk (node as CodeNode).lang = lang; (node as CodeNode).meta = undefined; // if it's an anonymous node, then put its output immediately after // and return if (anonymousNode) { parent && parent.children.splice(index + 1, 0, getAnonymousNode()); return index; } } else if (anonymousNode) { // a non-inline anonymous node should just replace the code chunk (parent as Parent).children[index] = getAnonymousNode(); return index; } else { // non-inline node with an id, take it out, we only want to execute // it and store the results, not see it (parent as Parent).children.splice(index, 1); return index; } } else if (mystType === "note" || mystType === "warning") { // a note! we want to replace the code chunk with a svelte component const newNode = { type: "html", value: `<Admonition type={"${mystType}"}>${micromark( value )}</Admonition>`, }; (parent as Parent).children[index] = newNode; return index; } else if (mystType === "panels") { const mdCards = parsePanel(value); const htmlCards = mdCards.map((card: MystCard) => { let k: keyof MystCard; for (k in card) { card[k] = micromark(card[k]); } return card; }); // create dummy object to access array properties with mustache const cards = { cards: htmlCards }; // parse each card const newNode = { type: "html", value: mustache.render( `<Panels> {{#cards}} <Card> {{#header}} <div slot="header"> {{{header}}} </div> {{/header}} <div slot="body"> {{{body}}} </div> {{#footer}} <div slot="footer"> {{{footer}}} </div> {{/footer}} </Card> {{/cards}} </Panels>`, cards ), }; (parent as Parent).children[index] = newNode; return index; } else { // the "language" of this code cell is something we don't yet support // (e.g. one of the many things in MyST that we don't handle) -- convert // it to a normal code cell with no language, at least that way we won't // confuse svelte downstream (since tokens with curly braces have special // meaning) (node as CodeNode).lang = undefined; } } }); }; }; function createJSTask(id: string, code: string, inputs: Array<string> = []) { return { id, type: TASK_TYPE.JS, state: TASK_STATE.PENDING, payload: `async (${inputs.join(",")}) => { ${code}\n }`, inputs: JSON.stringify([inputs].flat()), }; } // rehype plugin: reconstitutes `{code-cell}` chunks, inserting them inside // the script block that mdsvex generates (or creating one, in the case // of a document without one) export const augmentSvx = ({ codeCells, scripts, frontMatter, }: ParsedDocument) => { return () => { return function transformer(tree: Node): void { // we allow a top-level "scripts" to load arbitrary javascript let tasks = scripts.length ? [ { id: "scripts", type: TASK_TYPE.LOAD_SCRIPTS, state: TASK_STATE.PENDING, payload: JSON.stringify(scripts), inputs: JSON.stringify([]), }, ] : []; // turn data blocks into async tasks tasks = tasks.concat( (frontMatter.data || []) .map((datum) => { return Object.entries(datum).map(([id, url]) => { return { id: id, type: TASK_TYPE.DOWNLOAD, state: TASK_STATE.PENDING, payload: JSON.stringify(url), inputs: JSON.stringify([]), }; }); }) .flat() ); // variables should likewise get processed as their own type of "task" // (FIXME: duplication with ^^^) tasks = tasks.concat( (frontMatter.variables || []) .map((variable) => { return Object.entries(variable).map(([id, value]) => { return { id, type: TASK_TYPE.VARIABLE, state: TASK_STATE.PENDING, payload: JSON.stringify(value), inputs: JSON.stringify([]), }; }); }) .flat() ); // turn js code cells into async tasks tasks = tasks.concat( codeCells .filter((cn) => cn.lang === "js") .map((cn) => { const inputs = cn.attributes.inputs || []; const deps = []; // if there are any scripts, we want to load them // before running any code cells if (scripts.length) { inputs.push("scripts"); } // code cells can have scripts dependencies which apply just to that cell // we can assume that we have an id by this point (since they should have // been given that property in the initial parsing stage) if (cn.attributes.scripts) { const id = cn.attributes.id as string; const scriptsId = `${id}_scripts`; deps.push({ id: scriptsId, type: TASK_TYPE.LOAD_SCRIPTS, state: TASK_STATE.PENDING, payload: JSON.stringify([cn.attributes.scripts].flat()), inputs: JSON.stringify([]), }); inputs.push(scriptsId); } return [ ...deps, createJSTask(cn.attributes.id, cn.body, [inputs].flat()), ]; }) .flat() ); // // other cells need to be processed through language plugins // const langPlugins = codeCells.filter( (cn) => cn.attributes.type === "language-plugin" ); const customLangCells = codeCells.filter( (cn) => !["js", "svelte"].includes(cn.lang) ); // bail if there are any non-js cells without an associated language plugins const supportedLanguages = new Set( langPlugins.map((cn) => cn.attributes.id) ); customLangCells.forEach((cn) => { if (!supportedLanguages.has(cn.lang)) { throw new Error(`Unsupported language: ${cn.lang}`); } }); tasks = [ ...tasks, ...Object.values(langPlugins) .map((langPlugin) => { return customLangCells .filter((cn) => cn.lang === langPlugin.attributes.id) .map((cn) => { // we can assume a code cell has an id property by this point // language plugins should always have an id const id = cn.attributes.id as string; const langPluginId = langPlugin.attributes.id as string; return createJSTask( id, `return ${langPluginId}([${(cn.attributes.inputs || []).join( ", " )}], \`${cn.body}\`)`, [...(cn.attributes.inputs || []), langPluginId] ); }); }) .flat(), ]; const extraScript = codeCells .filter((cn) => cn.lang === "svelte") .map((svelteCell): string => { // we *know* this cell has an id (we check for it earlier) const id = svelteCell.attributes.id as string; return `import ${id} from "./${id}.svelte";`; }) .join("\n") + 'import Admonition from "./Admonition.svelte";\n' + 'import Panels from "./Panels.svelte";\n' + 'import Card from "./Card.svelte";\n' + 'import CellResults from "./CellResults.svelte";\n' + mustache.render(taskScriptSource, { taskVariables: tasks .map((task) => task.id) .filter( (taskVariable) => !Object.keys(frontMatter).includes(taskVariable) ), tasks, }); visit(tree, "root", (node: Parent) => { const moduleIndex = node.children .filter((n) => n.type === "raw") .findIndex((n: ScriptNode) => { return svelteParse(n.value).module; }); const scriptIndex = node.children .filter((n) => n.type === "raw") .findIndex((n: ScriptNode) => { const parsed = svelteParse(n.value); return parsed.instance && parsed.instance.type === "Script"; }); let scriptNodes, remainderNodes; if (scriptIndex >= 0) { const script = node.children[scriptIndex] as ScriptNode; // if we have a script tag already, append our stuff to the end script.value = script.value.replace( new RegExp("(</script>)$"), `\n${extraScript}$1` ); scriptNodes = node.children.slice(0, scriptIndex + 1); remainderNodes = node.children.slice(scriptIndex + 1); } else { // we need a new script block, but it must come after the module // if it exists if (moduleIndex >= 0) { scriptNodes = node.children.slice(0, moduleIndex + 1).concat([ { type: "raw", value: `<script>\n${extraScript}\n</script>`, } as ScriptNode, ]) as Array<ScriptNode>; remainderNodes = node.children.slice(moduleIndex + 1); } else { // neither a script nor a module block scriptNodes = [ { type: "raw", value: `<script>\n${extraScript}\n</script>`, }, ]; remainderNodes = node.children; } } // we want to wait for everything to resolve before rendering anything // inside the component node.children = scriptNodes .concat([{ type: "raw", value: "\n{#await __taskPromise}" }]) .concat([{ type: "raw", value: "\n<p>Loading...</p>\n" }]) .concat([{ type: "raw", value: "{:then}\n" }]) .concat(remainderNodes) .concat([{ type: "raw", value: "{/await}" }]); }); }; }; };
the_stack
import * as React from 'react'; import * as _ from 'lodash'; import * as errors from '../../shared/utils/errors'; import EventEmitter, { Listener, Hook } from './utils/eventEmitter'; import logger, { Logger } from '../../shared/utils/logger'; import { registerMode, deregisterMode, ModeMetadata } from './modes'; import Document from './document'; import Cursor from './cursor'; import Session from './session'; import Config from './config'; import { HotkeyMapping } from './keyMappings'; import KeyBindings from './keyBindings'; import { Row, ModeId } from './types'; import { KeyDefinitions, Action, Motion, ActionDefinition, MotionDefinition, ActionMetadata } from './keyDefinitions'; type PluginMetadata = { name: string; version?: number; author?: string; description?: string | React.ReactNode; dependencies?: Array<string>; }; type PluginEnableFn<V = void> = (api: PluginApi) => Promise<V> | V; type PluginDisableFn<V = void> = (api: PluginApi, value: V) => Promise<void> | void; type RegisteredPlugin<V = void> = { name: string; version?: number; author?: string; description?: string | React.ReactNode; dependencies?: Array<string>; enable: PluginEnableFn<V>; disable: PluginDisableFn<V>; }; // global set of registered plugins const PLUGINS: {[pluginName: string]: RegisteredPlugin<any>} = {}; export enum PluginStatus { UNREGISTERED = 0, DISABLING = 1, DISABLED = 2, ENABLING = 3, ENABLED = 4, } type Emitter = 'document' | 'session'; // class for exposing plugin API export class PluginApi { public session: Session; public metadata: PluginMetadata; private pluginManager: PluginsManager; private name: string; private document: Document; public cursor: Cursor; public logger: Logger; private bindings: KeyBindings; private definitions: KeyDefinitions; private config: Config; private registrations: Array<() => void>; constructor(config: Config, session: Session, bindings: KeyBindings, metadata: PluginMetadata, pluginManager: PluginsManager) { this.session = session; this.config = config; this.metadata = metadata; this.pluginManager = pluginManager; this.name = this.metadata.name; this.document = this.session.document; this.cursor = this.session.cursor; // TODO: Add subloggers and prefix all log messages with the plugin name this.logger = logger; this.bindings = bindings; this.definitions = this.bindings.definitions; this.registrations = []; } // get the API for another plugin public getPlugin(name: string): any { let found = false; for (let dependency of (this.metadata.dependencies || [])) { if (dependency === name) { found = true; } } if (!found) { throw new errors.GenericError(`Plugin ${this.metadata.name} asked for plugin ${name} but did not list it as a dependency`); } const info = this.pluginManager.getInfo(name); if (info.status !== PluginStatus.ENABLED) { throw new errors.GenericError(`Plugin ${name} was not enabled but required by ${this.metadata.name}??`); } // return (info.api as PluginApi); return (info.value as any); } public async setData(key: string, value: any) { return await this.document.store.setPluginData(this.name, key, value); } public async getData(key: string, default_value: any = null) { return await this.document.store.getPluginData(this.name, key, default_value); } // marks row for re-rendering public async updatedDataForRender(row: Row) { // this is sort of a weird implementation, // but it causes the cachedRowInfo to get updated // and also updates pluginData, which is the typical use case await this.document.updateCachedPluginData(row); } public registerMode(metadata: ModeMetadata) { const mode = registerMode(metadata); this.registrations.push(() => { this.deregisterMode(metadata); }); return mode; } public deregisterMode(metadata: ModeMetadata) { deregisterMode(metadata); } public registerDefaultMappings(mode: ModeId, mappings: HotkeyMapping) { this.config.defaultMappings.registerModeMappings(mode, mappings); this.registrations.push(() => { this.deregisterDefaultMappings(mode, mappings); }); } public deregisterDefaultMappings(mode: ModeId, mappings: HotkeyMapping) { this.config.defaultMappings.deregisterModeMappings(mode, mappings); } public registerMotion(name: string, desc: string, def: MotionDefinition) { const motion = new Motion(name, desc, def); this.definitions.registerMotion(motion); this.registrations.push(() => { this.deregisterMotion(motion.name); }); return motion; } public deregisterMotion(name: string) { this.definitions.deregisterMotion(name); } public registerAction(name: string, desc: string, def: ActionDefinition, metadata: ActionMetadata = {}) { const action = new Action(name, desc, def, metadata); this.definitions.registerAction(action); this.registrations.push(() => { this.deregisterAction(action.name); }); return action; } public deregisterAction(name: string) { this.definitions.deregisterAction(name); } private _getEmitter(who: Emitter): Document | Session { if (who === 'document') { return this.document; } else if (who === 'session') { return this.session; } else { throw new errors.GenericError(`Unknown hook listener ${who}`); } } public registerListener(who: Emitter, event: string, listener: Listener) { const emitter = this._getEmitter(who); emitter.on(event, listener); this.registrations.push(() => { this.deregisterListener(who, event, listener); }); } public deregisterListener(who: Emitter, event: string, listener: Listener) { const emitter = this._getEmitter(who); emitter.off(event, listener); } // TODO: type this better public registerHook(who: Emitter, event: string, transform: Hook) { const emitter = this._getEmitter(who); emitter.addHook(event, transform); this.registrations.push(() => { this.deregisterHook(who, event, transform); }); // pluginData can change for all rows (also could be render-related hook) this.document.cache.clear(); } public deregisterHook(who: Emitter, event: string, transform: Hook) { const emitter = this._getEmitter(who); emitter.removeHook(event, transform); // pluginData can change for all rows (also could be render-related hook) this.document.cache.clear(); } public deregisterAll() { this.registrations.reverse().forEach((deregisterFn) => { deregisterFn(); }); this.registrations = []; } public async panic() { this.pluginManager.disable(this.name); // Fire and forget throw new Error( `Plugin '${this.name}' has encountered a major problem. Please report this problem to the plugin author.` ); } } export class PluginsManager extends EventEmitter { private session: Session; private config: Config; private bindings: KeyBindings; private plugin_infos: { [key: string]: { api?: PluginApi, value?: any, status?: PluginStatus, } }; constructor(session: Session, config: Config, bindings: KeyBindings) { super(); this.session = session; this.config = config; this.bindings = bindings; this.plugin_infos = {}; } public getInfo(name: string) { return this.plugin_infos[name]; } public getStatus(name: string): PluginStatus { if (!PLUGINS[name]) { return PluginStatus.UNREGISTERED; } return (this.plugin_infos[name] && this.plugin_infos[name].status) || PluginStatus.DISABLED; } public setStatus(name: string, status: PluginStatus) { logger.debug(`Plugin ${name} status: ${status}`); if (!PLUGINS[name]) { throw new Error(`Plugin ${name} was not registered`); } const plugin_info = this.plugin_infos[name] || {}; plugin_info.status = status; this.plugin_infos[name] = plugin_info; this.emit('status'); } public updateEnabledPlugins() { const enabled: Array<string> = []; for (const name in this.plugin_infos) { if ((this.getStatus(name)) === PluginStatus.ENABLED) { enabled.push(name); } } this.emit('enabledPluginsChange', enabled); } public async enable(name: string) { const status = this.getStatus(name); if (status === PluginStatus.UNREGISTERED) { logger.error(`No plugin registered as ${name}`); return; } if (status === PluginStatus.ENABLING) { throw new errors.GenericError(`Already enabling plugin ${name}`); } if (status === PluginStatus.DISABLING) { throw new errors.GenericError(`Still disabling plugin ${name}`); } if (status === PluginStatus.ENABLED) { throw new errors.GenericError(`Plugin ${name} is already enabled`); } const plugin = PLUGINS[name]; for (let dependency of plugin.dependencies || []) { const dependency_status = this.getStatus(dependency); if (dependency_status !== PluginStatus.ENABLED) { throw new errors.GenericError(`Plugin ${name} requires ${dependency} to be enabled`); } } errors.assert(status === PluginStatus.DISABLED); this.setStatus(name, PluginStatus.ENABLING); const api = new PluginApi(this.config, this.session, this.bindings, plugin, this); const value = await plugin.enable(api); this.plugin_infos[name] = { api, value }; this.setStatus(name, PluginStatus.ENABLED); this.updateEnabledPlugins(); } public async disable(name: string) { const status = this.getStatus(name); if (status === PluginStatus.UNREGISTERED) { throw new errors.GenericError(`No plugin registered as ${name}`); } if (status === PluginStatus.ENABLING) { throw new errors.GenericError(`Still enabling plugin ${name}`); } if (status === PluginStatus.DISABLING) { throw new errors.GenericError(`Already disabling plugin ${name}`); } if (status === PluginStatus.DISABLED) { throw new errors.GenericError(`Plugin ${name} already disabled`); } for (const other_plugin_name in this.plugin_infos) { if ((this.getStatus(other_plugin_name)) === PluginStatus.ENABLED) { const other_plugin = (this.plugin_infos[other_plugin_name].api as PluginApi).metadata; for (let dependency of other_plugin.dependencies || []) { if (name === dependency) { throw new errors.GenericError(`Cannot disable ${name} because ${other_plugin_name} requires it`); } } } } // TODO: require that no other plugin has this as a dependency, notify user otherwise errors.assert(status === PluginStatus.ENABLED); this.setStatus(name, PluginStatus.DISABLING); const plugin_info = this.plugin_infos[name]; if (!plugin_info) { throw new Error(`Enabled plugin ${name} missing from info?`); } if (!plugin_info.api) { throw new Error(`Enabled plugin ${name} missing api?`); } const plugin = PLUGINS[name]; if (!plugin) { throw new Error(`Enabled plugin ${name} missing from registration?`); } await plugin.disable(plugin_info.api, plugin_info.value); delete this.plugin_infos[name]; this.updateEnabledPlugins(); } } export const registerPlugin = function<V = void>( plugin_metadata: PluginMetadata, enable: PluginEnableFn<V>, disable: PluginDisableFn<V>, ) { plugin_metadata.version = plugin_metadata.version || 1; plugin_metadata.author = plugin_metadata.author || 'anonymous'; // Create the plugin object // Plugin stores all data about a plugin, including metadata // plugin.value contains the actual resolved value const plugin: RegisteredPlugin<V> = { ..._.cloneDeep(plugin_metadata), enable, disable: disable || _.once(function(api: PluginApi) { api.deregisterAll(); throw new Error( `The plugin '${plugin.name}' was disabled but doesn't support online disable functionality. Refresh to disable.` ); }), }; PLUGINS[plugin.name] = plugin; }; // exports export function all() { return PLUGINS; } export function getPlugin(name: string) { return PLUGINS[name]; } export function names() { return (_.keys(PLUGINS)).sort(); }
the_stack
import fetch from 'node-fetch'; import ExpoClient, { ExpoPushMessage } from '../ExpoClient'; afterEach(() => { (fetch as any).reset(); }); test('limits the number of concurrent requests', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { data: [] }); expect((fetch as any).calls().length).toBe(0); const client = new ExpoClient({ maxConcurrentRequests: 1 }); const sendPromise1 = client.sendPushNotificationsAsync([]); const sendPromise2 = client.sendPushNotificationsAsync([]); expect((fetch as any).calls().length).toBe(1); await sendPromise1; expect((fetch as any).calls().length).toBe(2); await sendPromise2; expect((fetch as any).calls().length).toBe(2); }); describe('sending push notification messages', () => { test('sends requests to the Expo API server without a supplied access token', async () => { const mockTickets = [ { status: 'ok', id: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, { status: 'ok', id: 'YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY' }, ]; (fetch as any).mock('https://exp.host/--/api/v2/push/send', { data: mockTickets }); const client = new ExpoClient(); const tickets = await client.sendPushNotificationsAsync([{ to: 'a' }, { to: 'b' }]); expect(tickets).toEqual(mockTickets); const [, options] = (fetch as any).lastCall('https://exp.host/--/api/v2/push/send'); expect(options.headers.get('accept')).toContain('application/json'); expect(options.headers.get('accept-encoding')).toContain('gzip'); expect(options.headers.get('content-type')).toContain('application/json'); expect(options.headers.get('user-agent')).toMatch(/^expo-server-sdk-node\//); expect(options.headers.get('Authorization')).toBeNull(); }); test('sends requests to the Expo API server with a supplied access token', async () => { const mockTickets = [ { status: 'ok', id: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, { status: 'ok', id: 'YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY' }, ]; (fetch as any).mock('https://exp.host/--/api/v2/push/send', { data: mockTickets }); const client = new ExpoClient({ accessToken: 'foobar' }); const tickets = await client.sendPushNotificationsAsync([{ to: 'a' }, { to: 'b' }]); expect(tickets).toEqual(mockTickets); const [, options] = (fetch as any).lastCall('https://exp.host/--/api/v2/push/send'); expect(options.headers.get('accept')).toContain('application/json'); expect(options.headers.get('accept-encoding')).toContain('gzip'); expect(options.headers.get('content-type')).toContain('application/json'); expect(options.headers.get('user-agent')).toMatch(/^expo-server-sdk-node\//); expect(options.headers.get('Authorization')).toContain('Bearer foobar'); }); test('compresses request bodies over 1 KiB', async () => { const mockTickets = [{ status: 'ok', id: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }]; (fetch as any).mock('https://exp.host/--/api/v2/push/send', { data: mockTickets }); const client = new ExpoClient(); const messages = [{ to: 'a', body: new Array(1500).join('?') }]; expect(JSON.stringify(messages).length).toBeGreaterThan(1024); const tickets = await client.sendPushNotificationsAsync(messages); expect(tickets).toEqual(mockTickets); // Ensure the request body was compressed const [, options] = (fetch as any).lastCall('https://exp.host/--/api/v2/push/send'); expect(options.body.length).toBeLessThan(JSON.stringify(messages).length); expect(options.headers.get('content-encoding')).toContain('gzip'); }); test(`throws an error when the number of tickets doesn't match the number of messages`, async () => { const mockTickets = [ { status: 'ok', id: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' }, { status: 'ok', id: 'YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY' }, ]; (fetch as any).mock('https://exp.host/--/api/v2/push/send', { data: mockTickets }); const client = new ExpoClient(); await expect(client.sendPushNotificationsAsync([{ to: 'a' }])).rejects.toThrowError( `Expected Expo to respond with 1 ticket but got 2` ); await expect( client.sendPushNotificationsAsync([{ to: 'a' }, { to: 'b' }, { to: 'c' }]) ).rejects.toThrowError(`Expected Expo to respond with 3 tickets but got 2`); }); test('handles 200 HTTP responses with well-formed API errors', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 200, errors: [{ code: 'TEST_API_ERROR', message: `This is a test error` }], }); const client = new ExpoClient(); const rejection = expect(client.sendPushNotificationsAsync([])).rejects; await rejection.toThrowError(`This is a test error`); await rejection.toMatchObject({ code: 'TEST_API_ERROR' }); }); test('handles 200 HTTP responses with malformed JSON', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 200, body: '<!DOCTYPE html><body>Not JSON</body>', }); const client = new ExpoClient(); await expect(client.sendPushNotificationsAsync([])).rejects.toThrowError( `Expo responded with an error` ); }); test('handles non-200 HTTP responses with well-formed API errors', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 400, body: { errors: [{ code: 'TEST_API_ERROR', message: `This is a test error` }], }, }); const client = new ExpoClient(); const rejection = expect(client.sendPushNotificationsAsync([])).rejects; await rejection.toThrowError(`This is a test error`); await rejection.toMatchObject({ code: 'TEST_API_ERROR' }); }); test('handles non-200 HTTP responses with arbitrary JSON', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 400, body: { clowntown: true }, }); const client = new ExpoClient(); await expect(client.sendPushNotificationsAsync([])).rejects.toThrowError( `Expo responded with an error` ); }); test('handles non-200 HTTP responses with arbitrary text', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 400, body: '<!DOCTYPE html><body>Not JSON</body>', }); const client = new ExpoClient(); await expect(client.sendPushNotificationsAsync([])).rejects.toThrowError( `Expo responded with an error` ); }); test('handles well-formed API responses with multiple errors and extra details', async () => { (fetch as any).mock('https://exp.host/--/api/v2/push/send', { status: 400, body: { errors: [ { code: 'TEST_API_ERROR', message: `This is a test error`, details: { __debug: 'test debug information' }, stack: 'Error: This is a test error\n' + ' at SomeServerModule.method (SomeServerModule.js:131:20)', }, { code: 'SYSTEM_ERROR', message: `This is another error`, }, ], }, }); const client = new ExpoClient(); const rejection = expect(client.sendPushNotificationsAsync([])).rejects; await rejection.toThrowError(`This is a test error`); await rejection.toMatchObject({ code: 'TEST_API_ERROR', details: { __debug: 'test debug information' }, serverStack: expect.any(String), others: expect.arrayContaining([expect.any(Error)]), }); }); }); describe('retrieving push notification receipts', () => { test('gets receipts from the Expo API server', async () => { const mockReceipts = { 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX': { status: 'ok' }, 'YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY': { status: 'ok' }, }; (fetch as any).mock('https://exp.host/--/api/v2/push/getReceipts', { data: mockReceipts }); const client = new ExpoClient(); const receipts = await client.getPushNotificationReceiptsAsync([ 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY', ]); expect(receipts).toEqual(mockReceipts); const [, options] = (fetch as any).lastCall('https://exp.host/--/api/v2/push/getReceipts'); expect(options.headers.get('accept')).toContain('application/json'); expect(options.headers.get('accept-encoding')).toContain('gzip'); expect(options.headers.get('content-type')).toContain('application/json'); }); test('throws an error if the response is not a map', async () => { const mockReceipts = [{ status: 'ok' }]; (fetch as any).mock('https://exp.host/--/api/v2/push/getReceipts', { data: mockReceipts }); const client = new ExpoClient(); const rejection = expect( client.getPushNotificationReceiptsAsync(['XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX']) ).rejects; await rejection.toThrowError(`Expected Expo to respond with a map`); await rejection.toMatchObject({ data: mockReceipts }); }); }); describe('chunking push notification messages', () => { test('defines the push notification chunk size', () => { expect(ExpoClient.pushNotificationChunkSizeLimit).toBeDefined(); }); test('chunks lists of push notification messages', () => { const client = new ExpoClient(); const messages = new Array(999).fill({ to: '?' }); const chunks = client.chunkPushNotifications(messages); let totalMessageCount = 0; for (const chunk of chunks) { totalMessageCount += chunk.length; } expect(totalMessageCount).toBe(messages.length); }); test('can chunk small lists of push notification messages', () => { const client = new ExpoClient(); const messages = new Array(10).fill({ to: '?' }); const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(1); expect(chunks[0].length).toBe(10); }); test('chunks single push notification message with lists of recipients', () => { const messagesLength = 999; const client = new ExpoClient(); const messages = [{ to: new Array(messagesLength).fill('?') }]; const chunks = client.chunkPushNotifications(messages); for (const chunk of chunks) { // Each chunk should only contain a single message with 100 recipients expect(chunk.length).toBe(1); } const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(messagesLength); }); test('can chunk single push notification message with small lists of recipients', () => { const messagesLength = 10; const client = new ExpoClient(); const messages = [{ to: new Array(messagesLength).fill('?') }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(1); expect(chunks[0].length).toBe(1); expect(chunks[0][0].to.length).toBe(messagesLength); }); test('chunks push notification messages mixed with lists of recipients and single recipient', () => { const client = new ExpoClient(); const messages = [ { to: new Array(888).fill('?') }, ...new Array(999).fill({ to: '?', }), { to: new Array(90).fill('?') }, ...new Array(10).fill({ to: '?' }), ]; const chunks = client.chunkPushNotifications(messages); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(888 + 999 + 90 + 10); }); }); describe('chunking a single push notification message with multiple recipients', () => { const client = new ExpoClient(); test('one message with 100 recipients', () => { const messages = [{ to: new Array(100).fill('?') }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(1); expect(chunks[0].length).toBe(1); expect(chunks[0][0].to.length).toBe(100); }); test('one message with 101 recipients', () => { const messages = [{ to: new Array(101).fill('?') }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(2); expect(chunks[0].length).toBe(1); expect(chunks[1].length).toBe(1); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(101); }); test('one message with 99 recipients and two additional messages', () => { const messages = [{ to: new Array(99).fill('?') }, ...new Array(2).fill({ to: '?' })]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(2); expect(chunks[0].length).toBe(2); expect(chunks[1].length).toBe(1); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(99 + 2); }); test('one message with 100 recipients and two additional messages', () => { const messages = [{ to: new Array(100).fill('?') }, ...new Array(2).fill({ to: '?' })]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(2); expect(chunks[0].length).toBe(1); expect(chunks[1].length).toBe(2); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(100 + 2); }); test('99 messages and one additional message with with two recipients', () => { const messages = [...new Array(99).fill({ to: '?' }), { to: new Array(2).fill('?') }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(2); expect(chunks[0].length).toBe(100); expect(chunks[1].length).toBe(1); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(99 + 2); }); test('no message', () => { const messages: ExpoPushMessage[] = []; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(0); }); test('one message with no recipient', () => { const messages = [{ to: [] }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(0); }); test('two messages and one additional message with no recipient', () => { const messages = [...new Array(2).fill({ to: '?' }), { to: [] }]; const chunks = client.chunkPushNotifications(messages); expect(chunks.length).toBe(1); // The message with no recipient should be removed. expect(chunks[0].length).toBe(2); const totalMessageCount = countAndValidateMessages(chunks); expect(totalMessageCount).toBe(2); }); }); describe('chunking push notification receipt IDs', () => { test('defines the push notification receipt ID chunk size', () => { expect(ExpoClient.pushNotificationReceiptChunkSizeLimit).toBeDefined(); }); test('chunks lists of push notification receipt IDs', () => { const client = new ExpoClient(); const receiptIds = new Array(2999).fill('F5741A13-BCDA-434B-A316-5DC0E6FFA94F'); const chunks = client.chunkPushNotificationReceiptIds(receiptIds); let totalReceiptIdCount = 0; for (const chunk of chunks) { totalReceiptIdCount += chunk.length; } expect(totalReceiptIdCount).toBe(receiptIds.length); }); }); test('can detect an Expo push token', () => { expect(ExpoClient.isExpoPushToken('ExpoPushToken[xxxxxxxxxxxxxxxxxxxxxx]')).toBe(true); expect(ExpoClient.isExpoPushToken('ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]')).toBe(true); expect(ExpoClient.isExpoPushToken('F5741A13-BCDA-434B-A316-5DC0E6FFA94F')).toBe(true); // FCM expect( ExpoClient.isExpoPushToken( 'dOKpuo4qbsM:APA91bHkSmF84ROx7Y-2eMGxc0lmpQeN33ZwDMG763dkjd8yjKK-rhPtiR1OoIWNG5ZshlL8oyxsTnQ5XtahyBNS9mJAvfeE6aHzv_mOF_Ve4vL2po4clMIYYV2-Iea_sZVJF7xFLXih4Y0y88JNYULxFfz-XXXXX' ) ).toBe(false); // APNs expect( ExpoClient.isExpoPushToken('5fa729c6e535eb568g18fdabd35785fc60f41c161d9d7cf4b0bbb0d92437fda0') ).toBe(false); }); function countAndValidateMessages(chunks: ExpoPushMessage[][]): number { let totalMessageCount = 0; for (const chunk of chunks) { const chunkMessagesCount = ExpoClient._getActualMessageCount(chunk); expect(chunkMessagesCount).toBeLessThanOrEqual(ExpoClient.pushNotificationChunkSizeLimit); totalMessageCount += chunkMessagesCount; } return totalMessageCount; }
the_stack
import 'chrome-untrusted://personalization/polymer/v3_0/iron-list/iron-list.js'; import './setup.js'; import './styles.js'; import {afterNextRender, html, PolymerElement} from 'chrome-untrusted://personalization/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from 'chrome-untrusted://resources/js/load_time_data.m.js'; import {Events, EventType, kMaximumGooglePhotosPreviews, kMaximumLocalImagePreviews} from '../common/constants.js'; import {getLoadingPlaceholderAnimationDelay, getNumberOfGridItemsPerRow, isNullOrArray, isNullOrNumber, isSelectionEvent} from '../common/utils.js'; import {selectCollection, selectGooglePhotosCollection, selectLocalCollection, validateReceivedData} from '../untrusted/iframe_api.js'; /** * @fileoverview Responds to |SendCollectionsEvent| from trusted. Handles user * input and responds with |SelectCollectionEvent| when an image is selected. */ const kGooglePhotosCollectionId = 'google_photos_'; const kLocalCollectionId = 'local_'; /** Height in pixels of a tile. */ const kTileHeightPx = 136; enum TileType { LOADING = 'loading', IMAGE = 'image', FAILURE = 'failure', } /** mirror from mojom type, cannot use mojom type directly from untrusted. */ type Url = { url: string }; /** mirror from mojom type, cannot use mojom type directly from untrusted. */ type FilePath = { path: string }; /** mirror from mojom type, cannot use mojom type directly from untrusted. */ type WallpaperCollection = { id: string, name: string, preview?: Url, }; type LoadingTile = { type: TileType.LOADING }; /** * Type that represents a collection that failed to load. The preview image * is still displayed, but is grayed out and unclickable. */ type FailureTile = { type: TileType.FAILURE, id: string, name: string, preview: [], }; /** * A displayable type constructed from up to three LocalImages or a * WallpaperCollection. */ type ImageTile = { type: TileType.IMAGE, id: string, name: string, count: string, preview: Url[], }; type Tile = LoadingTile|FailureTile|ImageTile; interface RepeaterEvent extends CustomEvent { model: { item: Tile, }; } /** * Get the text to display for number of images. */ function getCountText(x: number|null|undefined): string { switch (x) { case undefined: case null: return ''; case 0: return loadTimeData.getString('zeroImages'); case 1: return loadTimeData.getString('oneImage'); default: if ('number' !== typeof x || x < 0) { console.error('Received an impossible value'); return ''; } return loadTimeData.getStringF('multipleImages', x); } } /** Returns the tile to display for the Google Photos collection. */ function getGooglePhotosTile( googlePhotos: Url[]|null, googlePhotosCount: number|null): ImageTile { return { name: loadTimeData.getString('googlePhotosLabel'), id: kGooglePhotosCollectionId, count: getCountText(googlePhotosCount ?? 0), preview: googlePhotos?.slice(0, kMaximumGooglePhotosPreviews) ?? [], type: TileType.IMAGE, }; } function getImages( localImages: FilePath[], localImageData: Record<string, string>): Url[] { if (!localImageData || !Array.isArray(localImages)) { return []; } const result = []; for (const {path} of localImages) { const data = {url: localImageData[path]}; if (!!data.url && data.url.length > 0) { result.push(data); } // Add at most |kMaximumLocalImagePreviews| thumbnail urls. if (result.length >= kMaximumLocalImagePreviews) { break; } } return result; } /** * A common display format between local images and WallpaperCollection. * Get the first displayable image with data from the list of possible images. */ function getLocalTile( localImages: FilePath[], localImageData: {[key: string]: string}): ImageTile|LoadingTile { const isMoreToLoad = localImages.some(({path}) => !localImageData.hasOwnProperty(path)); const imagesToDisplay = getImages(localImages, localImageData); if (imagesToDisplay.length < kMaximumLocalImagePreviews && isMoreToLoad) { // If there are more images to attempt loading thumbnails for, wait until // those are done. return {type: TileType.LOADING}; } // Count all images that failed to load and subtract them from "My Images" // count. const failureCount = Object.values(localImageData).reduce((result, next) => { return next === '' ? result + 1 : result; }, 0); return { name: loadTimeData.getString('myImagesLabel'), id: kLocalCollectionId, count: getCountText( Array.isArray(localImages) ? localImages.length - failureCount : 0), preview: imagesToDisplay, type: TileType.IMAGE, }; } export class CollectionsGrid extends PolymerElement { static get is() { return 'collections-grid'; } static get template() { return html`{__html_template__}`; } static get properties() { return { collections_: Array, /** * The list of Google Photos photos. */ googlePhotos_: Array, /** * The count of Google Photos photos. */ googlePhotosCount_: Number, /** * Mapping of collection id to number of images. Loads in progressively * after collections_. */ imageCounts_: Object, localImages_: Array, /** * Stores a mapping of local image id to thumbnail data. */ localImageData_: Object, /** * List of tiles to be displayed to the user. */ tiles_: { type: Array, value() { // Fill the view with loading tiles. Will be adjusted to the correct // number of tiles when collections are received. const x = getNumberOfGridItemsPerRow(); const y = Math.floor(window.innerHeight / kTileHeightPx); return Array.from({length: x * y}, () => ({type: TileType.LOADING})); } }, }; } private collections_: WallpaperCollection[]; private googlePhotos_: unknown[]|null; private googlePhotosCount_: number|null; private imageCounts_: {[key: string]: number|null}; private localImages_: FilePath[]; private localImageData_: {[key: string]: string}; private tiles_: Tile[]; static get observers() { return [ 'onLocalImagesLoaded_(localImages_, localImageData_)', 'onCollectionLoaded_(collections_, imageCounts_)', 'onGooglePhotosLoaded_(googlePhotos_, googlePhotosCount_)', ]; } constructor() { super(); this.onMessageReceived_ = this.onMessageReceived_.bind(this); } connectedCallback() { super.connectedCallback(); window.addEventListener('message', this.onMessageReceived_); } disconnectedCallback() { super.disconnectedCallback(); window.removeEventListener('message', this.onMessageReceived_); } getLoadingPlaceholderAnimationDelay(index: number): string { return getLoadingPlaceholderAnimationDelay(index); } /** * Called each time a new collection finishes loading. |imageCounts| contains * a mapping of collection id to the number of images in that collection. * A value of null indicates that the given collection id has failed to load. */ private onCollectionLoaded_( collections: WallpaperCollection[]|null, imageCounts: {[key: string]: number|null}) { if (!Array.isArray(collections) || !imageCounts) { return; } // The first tile in the collections grid is reserved for local images. The // second tile is reserved for Google Photos, provided that the integration // is enabled. The tile index of other collections must be `offset` so as // not to occupy reserved space. const offset = loadTimeData.getBoolean('isGooglePhotosIntegrationEnabled') ? 2 : 1; while (this.tiles_.length < collections.length + offset) { this.push('tiles_', {type: TileType.LOADING}); } while (this.tiles_.length > collections.length + offset) { this.pop('tiles_'); } collections.forEach((collection, i) => { const index = i + offset; const tile = this.tiles_[index]; // This tile failed to load completely. if (imageCounts[collection.id] === null && !this.isFailureTile_(tile)) { this.set(`tiles_.${index}`, { id: collection.id, name: collection.name, count: '', preview: [collection.preview], type: TileType.FAILURE, }); return; } // This tile loaded successfully. if (typeof imageCounts[collection.id] === 'number' && !this.isImageTile_(tile)) { this.set(`tiles_.${index}`, { id: collection.id, name: collection.name, count: getCountText(imageCounts[collection.id]), preview: [collection.preview], type: TileType.IMAGE, }); } }); } /** Invoked on changes to the list and count of Google Photos photos. */ private onGooglePhotosLoaded_( googlePhotos: Url[]|null|undefined, googlePhotosCount: number|null|undefined) { if (isNullOrArray(googlePhotos) && isNullOrNumber(googlePhotosCount)) { const tile = getGooglePhotosTile(googlePhotos, googlePhotosCount); this.set('tiles_.1', tile); } } /** * Called with updated local image list or local image thumbnail data when * either of those properties changes. */ private onLocalImagesLoaded_( localImages: FilePath[]|undefined, localImageData: {[key: string]: string}) { if (!Array.isArray(localImages) || !localImageData) { return; } const tile = getLocalTile(localImages, localImageData); this.set('tiles_.0', tile); } /** * Handler for messages from trusted code. Expects only SendImagesEvent and * will error on any other event. */ private onMessageReceived_(message: MessageEvent) { const event = message.data as Events; const isValid = validateReceivedData(event, message.origin); if (!isValid) { console.warn('Invalid event message received, event type: ' + event.type); } switch (event.type) { case EventType.SEND_COLLECTIONS: this.collections_ = isValid ? event.collections : []; break; case EventType.SEND_GOOGLE_PHOTOS_COUNT: if (isValid) { this.googlePhotosCount_ = event.count; } else { this.googlePhotos_ = null; this.googlePhotosCount_ = null; } break; case EventType.SEND_GOOGLE_PHOTOS_PHOTOS: if (isValid) { this.googlePhotos_ = event.photos; } else { this.googlePhotos_ = null; this.googlePhotosCount_ = null; } break; case EventType.SEND_IMAGE_COUNTS: this.imageCounts_ = event.counts; break; case EventType.SEND_LOCAL_IMAGES: if (isValid) { this.localImages_ = event.images; } else { this.localImages_ = []; this.localImageData_ = {}; } break; case EventType.SEND_LOCAL_IMAGE_DATA: if (isValid) { this.localImageData_ = event.data; } else { this.localImages_ = []; this.localImageData_ = {}; } break; case EventType.SEND_VISIBLE: if (!isValid) { return; } const visible = event.visible; if (visible) { // If iron-list items were updated while this iron-list was hidden, // the layout will be incorrect. Trigger another layout when iron-list // becomes visible again. Wait until |afterNextRender| completes // otherwise iron-list width may still be 0. afterNextRender(this, () => { // Trigger a layout now that iron-list has the correct width. this.shadowRoot!.querySelector('iron-list')!.fire('iron-resize'); }); } return; default: console.error(`Unexpected event type ${message.data.type}`); break; } } private getClassForImagesContainer_(tile: ImageTile): string { const numImages = Array.isArray(tile?.preview) ? tile.preview.length : 0; return `photo-images-container photo-images-container-${ Math.min(numImages, kMaximumLocalImagePreviews)}`; } getClassForEmptyTile_(tile: ImageTile): string { return `photo-inner-container ${ (this.isGooglePhotosTile_(tile) ? 'google-photos-empty' : 'photo-empty')}`; } getImageUrlForEmptyTile_(tile: ImageTile): string { return `//personalization/common/${ (this.isGooglePhotosTile_(tile) ? 'google_photos.svg' : 'no_images.svg')}`; } /** * Notify trusted code that a user selected a collection. */ private onCollectionSelected_(e: RepeaterEvent) { const tile = e.model.item; if (!isSelectionEvent(e) || !this.isSelectableTile_(tile)) { return; } switch (tile.id) { case kGooglePhotosCollectionId: selectGooglePhotosCollection(window.parent); return; case kLocalCollectionId: selectLocalCollection(window.parent); return; default: selectCollection(window.parent, tile.id); return; } } /** * Not using I18nBehavior because of chrome-untrusted:// incompatibility. */ private geti18n_(str: string): string { return loadTimeData.getString(str); } private isLoadingTile_(item: Tile|null): item is LoadingTile { return item?.type === TileType.LOADING; } private isFailureTile_(item: Tile|null): item is FailureTile { return item?.type === TileType.FAILURE; } private isEmptyTile_(item: Tile|null): item is ImageTile { return !!item && item.type === TileType.IMAGE && item.preview.length === 0; } private isGooglePhotosTile_(item: Tile|null): item is ImageTile|FailureTile { return !!item && (item.type !== TileType.LOADING) && (item?.id === kGooglePhotosCollectionId); } private isImageTile_(item: Tile|null): item is ImageTile { return item?.type === TileType.IMAGE && !this.isEmptyTile_(item); } private isSelectableTile_(item: Tile|null): item is ImageTile|FailureTile { return this.isGooglePhotosTile_(item) || this.isImageTile_(item); } /** * Make the text and background gradient visible again after the image has * finished loading. This is called for both on-load and on-error, as either * event should make the text visible again. */ private onImgLoad_(event: Event) { const self = event.currentTarget! as HTMLElement; const parent = self.closest('.photo-inner-container'); for (const elem of parent!.querySelectorAll('[hidden]')) { elem.removeAttribute('hidden'); } } } customElements.define(CollectionsGrid.is, CollectionsGrid);
the_stack
import { chatFilter, toxicityTest } from "../chatFilter" import { userDatabase } from "../userDatabase" import { getRandomEmptyResponse } from "../utils" import { addMessageToHistory, getResponse, onMessageResponseUpdated, updateMessage } from "./chatHistory" import { replacePlaceholders } from "./util" require('discord-inline-reply') require('discord-reply') export class discordPackerHandler { static getInstance: discordPackerHandler client constructor(client) { discordPackerHandler.getInstance = this this.client = client } async handlePing(message_id, chat_id, responses, addPing) { this.client.channels.fetch(chat_id).then(channel => { channel.messages.fetch(message_id).then(message => { Object.keys(responses).map(function(key, index) { console.log('response: ' + responses[key]) if (responses[key] !== undefined && responses[key].length <= 2000 && responses[key].length > 0) { let text = replacePlaceholders(responses[key]) if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response1: ' + text) message.channel.send(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } } else if (responses[key].length >= 2000) { let text: string = replacePlaceholders(responses[key]) if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response2: ' + text) } if (text.length > 0) { message.channel.send(text, { split: true }).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }) } } else { const emptyResponse = getRandomEmptyResponse() console.log('sending empty response: ' + emptyResponse) if (emptyResponse !== undefined && emptyResponse !== '' && emptyResponse.replace(/\s/g, '').length !== 0) { let text = emptyResponse if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response4: ' + text) message.channel.send(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } } } }); }).catch(err => console.log(err)) }); } async handleSlashCommand(chat_id, response) { this.client.channels.fetch(chat_id).then(channel => { channel.send(response) channel.stopTyping(); /*Object.keys(response.response).map(function(key, index) { console.log('response: ' + response.response[key]) if (response.response[key] !== undefined && response.response[key].length > 0) { let text = response.response[key] while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() sendSlashCommandResponse(client, interaction, chatId, text) } else { let emptyResponse = getRandomEmptyResponse() while (emptyResponse === undefined || emptyResponse === '' || emptyResponse.replace(/\s/g, '').length === 0) emptyResponse = getRandomEmptyResponse() sendSlashCommandResponse(client, interaction, chatId, emptyResponse) } }); */ }).catch(err => console.log(err)) } async handleUserUpdateEvent(response) { console.log('handleUserUpdateEvent: ' + response) } async handleGetAgents(chat_id, response) { this.client.channels.fetch(chat_id).then(channel => { channel.send(response) channel.stopTyping(); }).catch(err => console.log(err)) } async handleSetAgentsFields(chat_id, response) { this.client.channels.fetch(chat_id).then(channel => { channel.send(response) channel.stopTyping(); }).catch(err => console.log(err)) } async handlePingSoloAgent(chat_id, message_id, responses, addPing) { this.client.channels.fetch(chat_id).then(channel => { channel.messages.fetch(message_id).then(message => { Object.keys(responses).map(function(key, index) { console.log('response: ' + responses[key]) if (responses[key] !== undefined && responses[key].length <= 2000 && responses[key].length > 0) { let text = replacePlaceholders(responses[key]) if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response1: ' + text) message.channel.send(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } } else if (responses[key].length >= 2000) { let text: string = replacePlaceholders(responses[key]) if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response2: ' + text) } if (text.length > 0) { message.channel.send(text, { split: true }).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }) } } else { const emptyResponse = getRandomEmptyResponse() console.log('sending empty response: ' + emptyResponse) if (emptyResponse !== undefined && emptyResponse !== '' && emptyResponse.replace(/\s/g, '').length !== 0) { let text = emptyResponse if (addPing) { message.reply(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } else { while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response4: ' + text) message.channel.send(text).then(async function (msg) { onMessageResponseUpdated(channel.id, message.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }).catch(console.error) } } } }); }) }).catch(err => console.log(err)) } async handleMessageReactionAdd(response) { console.log('handleMessageReactionAdd: ' + response) } async handleMessageEdit(message_id, chat_id, responses, addPing) { this.client.channels.fetch(chat_id).then(async channel => { const oldResponse = getResponse(channel.id, message_id) if (oldResponse === undefined) { return } channel.messages.fetch(oldResponse).then(async msg => { channel.messages.fetch({limit: this.client.edit_messages_max_count}).then(async messages => { messages.forEach(async function(edited) { if (edited.id === message_id) { // Warn an offending user about their actions let warn_offender = function(_user, ratings) { edited.author.send(`You've got ${ratings} warnings and you will get blocked at 10!`) } // Ban an offending user let ban_offender = function (message, _user) { userDatabase.getInstance.banUser(edited.author.id, 'discord') // TODO doesn't work with both discord-inline-reply and discord-reply // message.lineReply('blocked') edited.author.send(`You've been blocked!`) } // Collect obscene words for further actions / rating let obscenities = chatFilter.getInstance.collectObscenities(edited.content, edited.author.id) // OpenAI obscenity detector let obscenity_count = obscenities.length if (parseInt(process.env.OPENAI_OBSCENITY_DETECTOR, 10) && !obscenity_count) { obscenity_count = await toxicityTest(edited.content) } // Process obscenities if (obscenity_count > 0) { chatFilter.getInstance.handleObscenities( edited, 'discord', obscenity_count, warn_offender, ban_offender ) } // Stop processing if there are obscenities if (obscenities.length > 0) { return } await updateMessage(channel.id, edited.id, edited.content) Object.keys(responses).map(async function(key, index) { console.log('response: ' + responses[key]) if (responses[key] !== undefined && responses[key].length <= 2000 && responses[key].length > 0) { let text = replacePlaceholders(responses[key]) while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response1: ' + text) msg.edit(text) onMessageResponseUpdated(channel.id, edited.id, msg.id) await updateMessage(channel.id, msg.id, msg.content) } else if (responses[key].length >= 2000) { let text = replacePlaceholders(responses[key]) while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response2: ' + text) if (text.length > 0) { edited.channel.send(text, { split: true }).then(async function (msg) { onMessageResponseUpdated(channel.id, edited.id, msg.id) addMessageToHistory(channel.id, msg.id, process.env.BOT_NAME, text,) }) } } else { const emptyResponse = getRandomEmptyResponse() console.log('sending empty response: ' + emptyResponse) if (emptyResponse !== undefined && emptyResponse !== '' && emptyResponse.replace(/\s/g, '').length !== 0) { let text = emptyResponse while (text === undefined || text === '' || text.replace(/\s/g, '').length === 0) text = getRandomEmptyResponse() console.log('response4: ' + text) msg.edit(text) onMessageResponseUpdated(channel.id, edited.id, msg.id) await updateMessage(channel.id, msg.id, msg.content) } } }); edited.channel.stopTyping(); } }) }).catch(err => console.log(err)) }) }) } }
the_stack
import { NgModule, Component, AfterViewInit, Input, ViewChild, ViewChildren, ContentChildren, QueryList, OnInit, ElementRef, Renderer, OnDestroy } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { CommonModule, Location } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Subscription } from 'rxjs' import { DynamicComponent } from './dynamic.component'; import { ComponentUtil } from '../utils/component'; import { SectionHelper } from './section.helper'; @Component({ selector: 'tabs', styles: [` .tab-nav { position: relative; width: 100%; padding: 0; margin: 0; margin-bottom: 30px; } .tab-nav li { cursor: pointer; text-transform: Capitalize; font-size: 15px; font-family: 'Segoe UI'; } .tabs { width: 100%; height: 28px; border-bottom-style: solid; border-bottom-width: 1px; } /* Same height as .tabs */ .tabs-container { overflow: hidden; max-height: 28px; } .tabs ul { list-style: none; display: inline-block; padding:0; padding-top: 5px; margin:0; height: 28px; } .tabs li { display: inline; padding-top: 2px; padding-bottom: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding-left: 5px; padding-right: 5px; border-style: solid; border-width: 1px; } .tabs li:not(.active) { border-color: transparent; } .tabs > ul > li:first-of-type { margin-left: 0; } .tabs li span { padding: 0; padding-bottom: 0; } .tabs li.active { border-style: solid; border-width: 1px; border-bottom-width: 2px; padding-bottom: 1px; } .tabs li:focus { outline-style: dashed; outline-color: #000; outline-width: 2px; outline-offset: -2px; text-decoration: underline; } .hider { margin-left: 10px; margin-top: 0; z-index: 10; display: inline-block; width: 75px; float:right; position: relative; cursor: default; padding-left: 40px; padding-bottom: 27px; border-bottom: none; } .menu-btn { display: inline-block; position: absolute; top: 1px; right: 0; cursor: pointer; z-index: 9; height: 25px; } .menu-btn span { display: inline-block; padding: 3px 8px; } .menu { position: absolute; top: 28px; right:0; max-width: 300px; z-index: 11; border-style: solid; border-width: 1px; } .menu ul { list-style: none; margin: 0; padding:0; } .menu li { padding: 10px; margin: 0; min-width: 150px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .tabs li.sticky { position: absolute; display: inline-flex; margin: 0; right: 27px; top: 1px; } .tabs li.sticky:before { content: '...'; padding-left: 5px; padding-right: 20px; } `], // In WAC mode, we can select feature when input-focus is changed. // In the site mode, we can't select the feature when input-focus is change. // That is because users are allowed to use only tab key, not arrow keys, unlike the WAC mode. template: ` <div class="tab-nav"> <div class="tabs-container"> <div class='tabs border-active'> <ul> <li #item tabindex="0" *ngFor="let tab of tabs; let i = index" class="border-active border-bottom-normal focusable" [ngClass]="{active: tab.active}" (keyup.space)="selectTab(i)" (keyup.enter)="selectTab(i)" (click)="selectTab(i)"> <span>{{tab.name}}</span> </li> <li *ngIf="_selectedIndex != -1" class="sticky background-normal border-active border-bottom-normal" [ngClass]="{active: !!'true', hidden: tabs[_selectedIndex].visible}" (click)="selectTab(_selectedIndex)"> <span class="border-active">{{tabs[_selectedIndex].name}}</span> </li> </ul> <div aria-hidden="true" class="hider background-normal" #menuBtnHider></div> </div> </div> <div class='menu-btn color-active background-normal' #menuBtn> <span tabindex="{{(isTabMenuHidden()) ? -1 : 0}}" (keyup.space)="onToggleMenu()" (keyup.enter)="onToggleMenu()" (click)="onToggleMenu()" title="{{ (_menuOn) ? 'Shrink' : 'Expand' }}" class="border-active hover-active color-normal focusable" [class.background-active]="_menuOn"> <i aria-hidden="true" class="fa fa-ellipsis-h"></i> </span> </div> <div class='menu border-active background-normal' [hidden]="!_menuOn"> <ul> <li tabindex="0" *ngFor="let tab of tabs; let i = index;" class="hover-active focusable" [ngClass]="{'background-active': tab.active}" (keyup.space)="selectTab(i)" (keyup.enter)="selectTab(i)" (click)="selectTab(i)" >{{tab.name}}</li> </ul> </div> <ng-content></ng-content> </div> `, host: { '(document:click)': 'dClick($event)', '(window:resize)': 'refresh()' } }) export class TabsComponent implements OnDestroy, AfterViewInit { @Input() markLocation: boolean; tabs: TabComponent[]; private _selectedIndex = -1; private _menuOn: boolean = false; private _default: string; private _tabsItems: Array<ElementRef>; private _hashCache: Array<string> = []; private _sectionHelper: SectionHelper; @ViewChild('menuBtn') menuBtn: ElementRef; @ViewChild('menuBtnHider') private _menuBtnHider: ElementRef; @ViewChildren('item') tabList: QueryList<ElementRef>; private _subscriptions: Array<Subscription> = []; constructor( private _elem: ElementRef, private _renderer: Renderer, private _activatedRoute: ActivatedRoute, private _location: Location, private _router: Router, ) { this.tabs = []; this._default = this._activatedRoute.snapshot.params["section"]; } public ngAfterViewInit() { this._sectionHelper = new SectionHelper(this.tabs.map(t => t.name), this._default, this.markLocation, this._location, this._router); this._subscriptions.push(this._sectionHelper.active.subscribe(sec => this.onSectionChange(sec))); this._tabsItems = this.tabList.toArray(); window.setTimeout(() => { this.refresh(); }, 1); } public ngOnDestroy() { this._subscriptions.forEach(sub => { (<any>sub).unsubscribe(); }); if (this._sectionHelper != null) { this._sectionHelper.dispose(); this._sectionHelper = null; } } public addTab(tab: TabComponent) { //// If a tab hasn't already been set as the active //// We default to the first added tab if no section is specified //// Otherwise we look for the tab who's name matches the section //// We have to set the tab as the selected index when it is added to prevent changing state during the angular2 change detection lifecycle if (this._selectedIndex === -1 && (this.tabs.length === 0 && !this._default || SectionHelper.normalize(tab.name) == this._default)) { tab.activate(); this._selectedIndex = this.tabs.length; } this.tabs.push(tab); } onToggleMenu() { this._menuOn = !this._menuOn; } selectTab(index: number) { if (this._menuOn) { this.showMenu(false); } this._sectionHelper.selectSection(this.tabs[index].name); } isTabMenuHidden() { // The hider element goes to the next line when the window size is reduced and that causes the previously hiden tabMenu button now visible. // So, when the tabMenu is not hidden, hiderTop is bigger than the menuBottom. let menuBottom = this.menuBtn.nativeElement.getBoundingClientRect().bottom; let hiderTop = this._menuBtnHider.nativeElement.getBoundingClientRect().top; return !(hiderTop > menuBottom); } private onSectionChange(section: string) { let index = this.tabs.findIndex(t => t.name === section); if (index == -1) { index = 0; } this.tabs.forEach(t => t.deactivate()); this.tabs[index].activate(); this._selectedIndex = index; this.refresh(); } private showMenu(show: boolean) { this._menuOn = show; } private dClick(evt) { if (!this._menuOn) { return; } var inside = ComponentUtil.isClickInsideComponent(evt, this.menuBtn); if (!inside) { this.showMenu(false); } } private blur() { this.showMenu(false); } private refresh() { if (!this._tabsItems || this._selectedIndex < 0) { return; } this.tabs.forEach(t => { t.visible = true }); // Accessing native elements causes animations to play that trigger when ngModels are set from undefined to a truthy state let rect: ClientRect = this._tabsItems[this._selectedIndex].nativeElement.getBoundingClientRect(); let rectBtn: ClientRect = this.menuBtn.nativeElement.getBoundingClientRect(); let diff: number = rectBtn.left - rect.right - 10; if (diff < 0) { this.tabs[this._selectedIndex].visible = false; } } } @Component({ selector: 'tab', styles: [` .tab-page { padding-top: 15px; } `], template: ` <div *ngIf="!(!active)" class="tab-page"> <ng-content></ng-content> </div> ` }) export class TabComponent implements OnInit, OnDestroy { @Input() name: string; @Input() visible: boolean = true; @Input() active: boolean; @ContentChildren(DynamicComponent) dynamicChildren: QueryList<DynamicComponent>; constructor(private _tabs: TabsComponent) { } public ngOnInit() { this._tabs.addTab(this); } public activate() { if (this.dynamicChildren) { this.dynamicChildren.forEach(child => child.activate()); } this.active = true; } public deactivate() { if (this.dynamicChildren) { this.dynamicChildren.forEach(child => child.deactivate()); } this.active = false; } public ngOnDestroy() { if (this.dynamicChildren) { this.dynamicChildren.forEach(child => child.deactivate()); this.dynamicChildren.forEach(child => child.destroy()); } } } export const TABS: any[] = [ TabsComponent, TabComponent ]; @NgModule({ imports: [ FormsModule, CommonModule ], exports: [ TABS ], declarations: [ TABS ] }) export class Module { }
the_stack
import * as Mousetrap from "mousetrap"; require("mousetrap/plugins/global-bind/mousetrap-global-bind"); import * as events from "../../common/events"; import * as utils from "../../common/utils"; import * as types from "../../common/types"; export enum CommandContext { Global, Editor, TreeView, } interface UICommandConfig { keyboardShortcut?: string; description: string; context: CommandContext; // only valid for editor commands // we use this to trigger the command on the editor editorCommandName?: string; /** allow the browser default to still happen */ allowDefault?: boolean; } /** * The command registry composed of commands that are keyboard only */ export let commandRegistry: UICommand[] = []; /** * A command is just an event emitter with some useful properties relevant to the front end command registry * such commands cannot have a payload */ export class UICommand extends events.TypedEvent<{}>{ constructor(public config: UICommandConfig) { super(); commandRegistry.push(this); } } /** * BAS */ // export const bas = new UICommand({ // description: "BAS: I map this to whatever command I am currently testing", // context: CommandContext.Global, // }); /** * General purpose UI escape */ export const esc = new UICommand({ keyboardShortcut: 'esc', // atom description: "Close any open dialogs and focus back to any open tab", context: CommandContext.Global, }); /** * Active list */ export const gotoNext = new UICommand({ keyboardShortcut: 'mod+f8', // atom description: "Main Panel : Goto next error in project", context: CommandContext.Global, }); export const gotoPrevious = new UICommand({ keyboardShortcut: 'mod+shift+f8', // atom description: "Main Panel : Goto previous error in project", context: CommandContext.Global, }); /** * Tabs */ export const nextTab = new UICommand({ keyboardShortcut: 'alt+k', description: "Tabs: Focus on the Next Tab", context: CommandContext.Global, }); export const prevTab = new UICommand({ keyboardShortcut: 'alt+j', description: "Tabs: Focus on the Previous Tab", context: CommandContext.Global, }); export const closeTab = new UICommand({ keyboardShortcut: 'alt+w', // c9 description: "Tabs: Close current tab", context: CommandContext.Global, }); export const undoCloseTab = new UICommand({ keyboardShortcut: 'shift+alt+w', // Couldn't find IDEs that do this. c9/ca have this bound to close all tabs description: "Tabs: Undo close tab", context: CommandContext.Global, }); export const saveTab = new UICommand({ keyboardShortcut: 'mod+s', // c9 description: "Tabs: Save current tab", context: CommandContext.Global, }); export const closeOtherTabs = new UICommand({ description: "Tabs: Close other tabs", context: CommandContext.Global, }); export const closeAllTabs = new UICommand({ description: "Tabs: Close all tabs", context: CommandContext.Global, }); export const jumpToTab = new UICommand({ keyboardShortcut: 'mod+shift+enter', description: "Tabs: Jump to tab", context: CommandContext.Global, }); export const duplicateTab = new UICommand({ description: "Tabs: Duplicate", context: CommandContext.Global, }); export const duplicateWindow = new UICommand({ description: "Window: Duplicate in a new browser window", context: CommandContext.Global, }); /** * Build / output js */ export const sync = new UICommand({ keyboardShortcut: 'shift+f6', description: "TypeScript: Sync", context: CommandContext.Global, }); export const build = new UICommand({ keyboardShortcut: 'f6', description: "TypeScript: Build", context: CommandContext.Global, }); export const toggleOutputJS = new UICommand({ keyboardShortcut: 'mod+shift+m', // atom description: "TypeScript: Toggle output js file", context: CommandContext.Global, }); export const enableLiveDemo = new UICommand({ description: "TypeScript: Demo file", context: CommandContext.Global, }); export const disableLiveDemo = new UICommand({ description: "TypeScript: Demo stop", context: CommandContext.Global, }); export const enableLiveDemoReact = new UICommand({ description: "TypeScript: Demo react file", context: CommandContext.Global, }); export const disableLiveDemoReact = new UICommand({ description: "TypeScript: Demo react stop", context: CommandContext.Global, }); /** * Tab indexing * // c9, chrome, atom */ export const gotoTab1 = new UICommand({ keyboardShortcut: 'mod+1', description: "Tabs: Goto Tab 1", context: CommandContext.Global, }); export const gotoTab2 = new UICommand({ keyboardShortcut: 'mod+2', description: "Tabs: Goto Tab 2", context: CommandContext.Global, }); export const gotoTab3 = new UICommand({ keyboardShortcut: 'mod+3', description: "Tabs: Goto Tab 3", context: CommandContext.Global, }); export const gotoTab4 = new UICommand({ keyboardShortcut: 'mod+4', description: "Tabs: Goto Tab 4", context: CommandContext.Global, }); export const gotoTab5 = new UICommand({ keyboardShortcut: 'mod+5', description: "Tabs: Goto Tab 5", context: CommandContext.Global, }); export const gotoTab6 = new UICommand({ keyboardShortcut: 'mod+6', description: "Tabs: Goto Tab 6", context: CommandContext.Global, }); export const gotoTab7 = new UICommand({ keyboardShortcut: 'mod+7', description: "Tabs: Goto Tab 7", context: CommandContext.Global, }); export const gotoTab8 = new UICommand({ keyboardShortcut: 'mod+8', description: "Tabs: Goto Tab 8", context: CommandContext.Global, }); export const gotoTab9 = new UICommand({ keyboardShortcut: 'mod+9', description: "Tabs: Goto Tab 9", context: CommandContext.Global, }); /** * OmniSearch */ export const omniFindFile = new UICommand({ keyboardShortcut: 'mod+o', // atom,sublime description: "Find a file in the working directory", context: CommandContext.Global, }); export const omniFindCommand = new UICommand({ keyboardShortcut: 'mod+shift+p', // atom,sublime description: "Find a command", context: CommandContext.Global, }); export const omniSelectProject = new UICommand({ keyboardShortcut: 'alt+shift+p', // atom:projectmanager package description: "Find and set active project", context: CommandContext.Global, }); export const omniProjectSymbols = new UICommand({ keyboardShortcut: 'mod+shift+h', description: "Find Symbols (Hieroglyphs) in active project", context: CommandContext.Global, }); export const omniProjectSourcefile = new UICommand({ keyboardShortcut: 'mod+p', // description: "Find Source File in active project", context: CommandContext.Global, }); /** * FAR find and replace */ export const findAndReplace = new UICommand({ keyboardShortcut: 'mod+f', // atom,sublime,c9 description: "Show find and replace dialog", context: CommandContext.Global, }); export const findAndReplaceMulti = new UICommand({ keyboardShortcut: 'mod+shift+f', // atom,sublime,c9 description: "Show find and replace in files", context: CommandContext.Global, }); export const findNext = new UICommand({ keyboardShortcut: 'f3', // atom,sublime description: "Find the next search result", context: CommandContext.Global, }); export const findPrevious = new UICommand({ keyboardShortcut: 'shift+f3', // atom,sublime description: "Find the previous search result", context: CommandContext.Global, }); export const replaceNext = new events.TypedEvent<{ newText: string }>(); export const replacePrevious = new events.TypedEvent<{ newText: string }>(); export const replaceAll = new events.TypedEvent<{ newText: string }>(); /** * Error panel */ export let toggleMessagePanel = new UICommand({ keyboardShortcut: 'mod+;', // description: "Toggle Message Panel", context: CommandContext.Global, }); export let cycleMessagesPanel = new UICommand({ keyboardShortcut: 'mod+shift+;', // description: "Cycle Message Panel", context: CommandContext.Global, }); /** * Documentation features */ export let toggleDoctor = new UICommand({ keyboardShortcut: "mod+'", // description: "Editor: Toggle Doctor", context: CommandContext.Global, }); export const toggleDocumentationBrowser = new UICommand({ keyboardShortcut: 'mod+shift+\'', // Same as doctor with Shift description: "Documentation Browser: Open", context: CommandContext.Global, }); export const doOpenUmlDiagram = new UICommand({ description: "UML Class diagram", context: CommandContext.Global, }); export const toggleSemanticView = new UICommand({ description: "Toggle Semantic View", context: CommandContext.Global, }); export const launchTsFlow = new UICommand({ description: "Launch TypeScript flow based programming", context: CommandContext.Global, }); export const doOpenTestResultsView = new UICommand({ description: "Test Results View", context: CommandContext.Global, }); /** * Cursor history */ export let previousCursorLocation = new UICommand({ keyboardShortcut: "mod+u", // CM undo cursor description: "Cursor: Previous Cursor Location", context: CommandContext.Global, }); export let nextCursorLocation = new UICommand({ keyboardShortcut: "mod+shift+u", // CM redo cursor description: "Cursor: Next Cursor Location", context: CommandContext.Global, }); /** * Clipboard Ring */ export const copy = new UICommand({ keyboardShortcut: 'mod+c', // atom description: "Copy", context: CommandContext.Global, allowDefault: true }); export const cut = new UICommand({ keyboardShortcut: 'mod+x', // atom description: "Cut", context: CommandContext.Global, allowDefault: true }); export const pasteFromRing = new UICommand({ keyboardShortcut: 'mod+shift+v', // VS description: "PasteFromRing", context: CommandContext.Global, allowDefault: false }); /** * Tree view */ export let treeViewToggle = new UICommand({ keyboardShortcut: 'mod+\\', // atom description: "Tree View: Toggle", context: CommandContext.Global, }); export let treeViewRevealActiveFile = new UICommand({ keyboardShortcut: 'mod+shift+\\', // atom description: "Tree View: Reveal Active File", context: CommandContext.Global, }); export let treeViewFocus = new UICommand({ keyboardShortcut: 'mod+0', // atom, code description: "Tree View: Focus", context: CommandContext.Global, }); export let treeAddFile = new UICommand({ keyboardShortcut: 'a', // atom description: "Tree View: Add File", context: CommandContext.TreeView, }); export let treeAddFolder = new UICommand({ keyboardShortcut: 'shift+a', // atom description: "Tree View: Add Folder", context: CommandContext.TreeView, }); export let treeDuplicateFile = new UICommand({ keyboardShortcut: 'd', // atom description: "Tree View: Duplicate File|Folder", context: CommandContext.TreeView, }); export let treeMoveFile = new UICommand({ keyboardShortcut: 'm', // atom description: "Tree View: Move File|Folder", context: CommandContext.TreeView, }); /** Rename is same as `move` but people want to search for it */ export let treeRenameFile = new UICommand({ keyboardShortcut: 'r', description: "Tree View: Rename File|Folder", context: CommandContext.TreeView, }); export let treeDeleteFile = new UICommand({ keyboardShortcut: 'del', // atom description: "Tree View: Delete File|Folder", context: CommandContext.TreeView, }); export let treeOpenInExplorerFinder = new UICommand({ keyboardShortcut: 'o', // natural description: "Tree View: Open folder in explorer / finder", context: CommandContext.TreeView, }); export let treeOpenInCmdTerminal = new UICommand({ keyboardShortcut: 'shift+o', // natural description: "Tree View: Open folder in cmd / terminal", context: CommandContext.TreeView, }); /** * General purpose file opening * These are handled in appTabsContainer at the moment */ export const doOpenFile = new events.TypedEvent<{ filePath: string, position?: EditorPosition }>(); export const doOpenOrFocusFile = new events.TypedEvent<{ filePath: string, position?: EditorPosition }>(); export const openFileFromDisk = new UICommand({ keyboardShortcut: 'mod+shift+o', description: 'Open a file present on server disk', context: CommandContext.Global, }); /** needed by cursor history */ export const doOpenOrFocusTab = new events.TypedEvent<{ tabId: string, tabUrl: string, position: EditorPosition }>(); /** needed by file tree */ export const closeFilesDirs = new events.TypedEvent<{ files: string[], dirs: string[] }>(); /** Needed by file tree, activates the tab but doesn't change focus away from tree view */ export const doOpenOrActivateFileTab = new events.TypedEvent<{ filePath: string }>(); /** Needed to toggle output js file. We toggle and also do not steal focus */ export const doToggleFileTab = new events.TypedEvent<{ filePath: string }>(); /** Needed to ensure that a demo view is open */ export const ensureLiveDemoTab = new events.TypedEvent<{ filePath: string }>(); export const closeDemoTab = new events.TypedEvent<{}>(); export const ensureLiveDemoReactTab = new events.TypedEvent<{ filePath: string }>(); export const closeDemoReactTab = new events.TypedEvent<{}>(); /** * Other tab types */ export const doOpenDependencyView = new UICommand({ description: 'Open Dependency View', context: CommandContext.Global, }); export const doOpenASTView = new UICommand({ description: 'Open AST View', context: CommandContext.Global, }); export const doOpenASTFullView = new UICommand({ description: 'Open AST-Full View', context: CommandContext.Global, }); /** * Common configuration file creations */ export const createEditorconfig = new UICommand({ description: 'Create a .editorconfig', context: CommandContext.Global, }); /** * Settings stuff */ export const openSettingsFile = new UICommand({ description: 'Open settings file', context: CommandContext.Global }) /** * Git */ export const gitAddAllCommitAndPush = new UICommand({ description: 'Git: Add all, Commit and Push', context: CommandContext.Global }) export const gitFetchLatestAndRebase = new UICommand({ description: 'Git: Fetch + Pull latest, and rebase any local commits', context: CommandContext.Global }) /** Whenever status might be invalid */ export const gitStatusNeedsRefresh = new events.TypedEvent<{}>(); /** * Registration */ export function register() { commandRegistry.forEach(c => { if (c.config.context == CommandContext.Global && c.config.keyboardShortcut) { Mousetrap.bindGlobal(c.config.keyboardShortcut, function() { c.emit({}); return !!c.config.allowDefault; }); } }); } /** * * CODE MIRROR * */ /** * Straight out of codemirror.js */ export const ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); export const mac = ios || /Mac/.test(navigator.platform); export const windows = /win/i.test(navigator.platform); /** Nice display name for the mod by user platform */ export const modName = mac ? '⌘' : 'Ctrl'; const mod = mac ? 'Cmd' : 'Ctrl'; /** Load editor actions + keymaps */ import { getActions } from "./monacoActionLoader"; const actions = getActions(); // console.log(actions); // DEBUG if (mac) { // TODO: mon // Prevent the browser from handling the CMD + SHIFT + [ (or ]) which monaco uses for fold / unfold } function addEditorMapToCommands(command: types.MonacoActionInformation) { new UICommand({ keyboardShortcut: command.kbd, description: `Editor: ${command.label}`, context: CommandContext.Editor, editorCommandName: command.id, }); } actions.forEach(addEditorMapToCommands) /** * This is a consolidation of the `file edited` and `file changed on disk` */ export const fileContentsChanged = new events.TypedEvent<{ filePath: string }>(); /** * Setup toasts to hide on esc * Note: this is done here instead of `ui` as some commands depend on `ui` and having depend on commands causes a circular dependency */ import * as toastr from "toastr"; esc.on(() => { toastr.clear(); }); /* DEBUG console.table( commandRegistry .filter(c=>c.config.context == CommandContext.Editor) .map(c=>({cmd:c.config.description, shortcut:c.config.keyboardShortcut})) ); /* DEBUG */ /** * Mac (the chrome browser in mac) doesn't have *cmd + y* (common redo). * Instead it opens the browser history by mistake. * So we redirect it to redo for any open editor :) */ Mousetrap.bindGlobal('mod+y', function(event: any) { // If the focus is on editor than monaco already handles it // If we made it till here .... then .... // Prevent default return false; }); /** * Mac: Cmd + H at the wrong place hides the window. */ Mousetrap.bindGlobal('mod+h', function(event: any) { // If the focus is on editor than monaco already handles it // If we made it till here .... then .... // Prevent default return false; });
the_stack
import React, {useEffect, useState} from 'react'; import {useDebounce} from 'react-use'; import {Button, Input, Select} from 'antd'; import {DeleteOutlined} from '@ant-design/icons'; import _ from 'lodash'; import styled from 'styled-components'; import {v4 as uuidv4} from 'uuid'; import {DEFAULT_EDITOR_DEBOUNCE} from '@constants/constants'; const Option = Select.Option; const {TextArea} = Input; const FormContainer = styled.div` width: 100%; margin-top: 16px; `; const DynamicKeyValueContainer = styled.div` display: flex; align-items: space-between; width: 100%; margin-top: 16px; `; const DynamicKeyValueItem = styled.div` width: 40%; margin-left: 0.33%; `; const DynamicKeyValueActionItem = styled.div` width: 19%; margin-left: 0.33%; `; const ButtonContainer = styled.div` width: 100%; display: flex; align-items: center; justify-content: center; `; const StyledSpanTitle = styled.span` display: block; margin-bottom: 4px; margin-top: 6px; `; const StyledSpanToggler = styled.span` cursor: pointer; text-decoration: underline; float: right; text-transform: uppercase; font-size: 9px; font-weight: 700; margin-top: 4px; `; const secretTypes = [ 'Opaque', 'kubernetes.io/service-account-token', 'kubernetes.io/dockercfg', 'kubernetes.io/dockerconfigjson', 'kubernetes.io/basic-auth', 'kubernetes.io/ssh-auth', 'kubernetes.io/tls', 'bootstrap.kubernetes.io/token', ]; export const SecretKindResourceForm = ({onChange, formData, disabled}: any) => { const [dataKeyValuePairs, setDataKeyValuePairs] = useState<{id: string; key: string; value: string}[]>([]); const [stringDataKeyValuePairs, setStringDataKeyValuePairs] = useState<{id: string; key: string; value: string}[]>( [] ); const handleTypeChange = (value: any) => { if (formData.type !== value) { onChange({...formData, type: value, data: undefined, stringData: undefined}); setDataKeyValuePairs([]); setStringDataKeyValuePairs([]); } }; useEffect(() => { if (formData.data && _.isObject(formData.data)) { const newDataKeyValuePairs = Object.keys(formData.data).map(key => ({ key, value: formData.data[key], })); if ( !_.isEqual( _.sortBy( dataKeyValuePairs.map(p => ({key: p.key, value: p.value})), 'key' ), _.sortBy(newDataKeyValuePairs, 'key') ) ) { setDataKeyValuePairs(newDataKeyValuePairs.map(p => ({...p, id: uuidv4()}))); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formData.data, formData.metadata?.name]); useEffect(() => { if (formData.stringData && _.isObject(formData.stringData)) { const newStringDataKeyValuePairs = Object.keys(formData.stringData).map(key => ({ key, value: formData.stringData[key], })); if ( !_.isEqual( _.sortBy( stringDataKeyValuePairs.map(p => ({key: p.key, value: p.value})), 'key' ), _.sortBy(newStringDataKeyValuePairs, 'key') ) ) { setStringDataKeyValuePairs(newStringDataKeyValuePairs.map(p => ({...p, id: uuidv4()}))); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [formData.stringData, formData.metadata?.name]); useEffect(() => { const emptyObject: any = {}; const data = dataKeyValuePairs.reduce((object, value) => { object[value.key] = value.value; return object; }, emptyObject); if (!_.isEqual(formData.data, data)) { onChange({ ...formData, stringData: undefined, data: data || undefined, }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [dataKeyValuePairs]); useEffect(() => { const emptyObject: any = {}; const stringData = stringDataKeyValuePairs.reduce((object, value) => { object[value.key] = value.value; return object; }, emptyObject); if (!_.isEqual(formData.stringData, stringData)) { onChange({ ...formData, data: undefined, stringData: stringData || undefined, }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [stringDataKeyValuePairs]); const handleKeyValuePairFormChange = (key: string, value: {id: string; key: string; value: string}) => { if (key === 'stringData') { const keyValuePairIndex = stringDataKeyValuePairs.findIndex(pair => pair.id === value.id); if (keyValuePairIndex > -1) { stringDataKeyValuePairs[keyValuePairIndex].key = value.key; stringDataKeyValuePairs[keyValuePairIndex].value = value.value; setStringDataKeyValuePairs([...stringDataKeyValuePairs]); } else { setStringDataKeyValuePairs([...stringDataKeyValuePairs, {id: value.id, key: value.key, value: value.value}]); } } if (key === 'data') { const keyValuePairIndex = dataKeyValuePairs.findIndex(pair => pair.id === value.id); if (keyValuePairIndex > -1) { dataKeyValuePairs[keyValuePairIndex].key = value.key; dataKeyValuePairs[keyValuePairIndex].value = value.value; setDataKeyValuePairs([...dataKeyValuePairs]); } else { setDataKeyValuePairs([...dataKeyValuePairs, {id: value.id, key: value.key, value: value.value}]); } } }; const handleKeyValuePairFormDelete = (key: string, value: {id: string; key: string; value: string}) => { if (key === 'stringData') { setStringDataKeyValuePairs(stringDataKeyValuePairs.filter(pair => pair.id !== value.id)); } if (key === 'data') { setDataKeyValuePairs(dataKeyValuePairs.filter(pair => pair.id !== value.id)); } }; const handleTextAreaFormChange = (key: string, value: string) => { onChange({...formData, data: {[key]: value}, stringData: undefined}); }; const handleTokenFormChange = (key: string, value: string) => { onChange({...formData, data: {...formData.data, [key]: value}, stringData: undefined}); }; const handleTLSFormChange = (key: string, value: string) => { onChange({...formData, data: {...formData.data, [key]: value}, stringData: undefined}); }; return ( <FormContainer> <div> <StyledSpanTitle>Type</StyledSpanTitle> <Select value={formData.type} style={{width: '100%'}} onChange={handleTypeChange} disabled={disabled}> {secretTypes.map(secretType => ( <Option key={secretType} value={secretType}> {secretType} </Option> ))} </Select> </div> <div> {formData.type === 'Opaque' && ( <KeyValuePairForm values={dataKeyValuePairs} onChange={(value: {id: string; key: string; value: string}) => handleKeyValuePairFormChange('data', value)} onDelete={(value: {id: string; key: string; value: string}) => handleKeyValuePairFormDelete('data', value)} disabled={disabled} /> )} {formData.type === 'kubernetes.io/service-account-token' && ( <TextAreaForm value={formData.data && formData.data['extra']} onChange={(value: string) => handleTextAreaFormChange('extra', value)} disabled={disabled} /> )} {formData.type === 'kubernetes.io/dockercfg' && ( <TextAreaForm value={formData.data && formData.data['.dockercfg']} onChange={(value: string) => handleTextAreaFormChange('.dockercfg', value)} disabled={disabled} /> )} {formData.type === 'kubernetes.io/dockerconfigjson' && ( <TextAreaForm value={formData.data && formData.data['.dockerconfigjson']} onChange={(value: string) => handleTextAreaFormChange('.dockerconfigjson', value)} disabled={disabled} /> )} {formData.type === 'kubernetes.io/basic-auth' && ( <KeyValuePairForm values={stringDataKeyValuePairs} onChange={(value: {id: string; key: string; value: string}) => handleKeyValuePairFormChange('stringData', value) } onDelete={(value: {id: string; key: string; value: string}) => handleKeyValuePairFormDelete('stringData', value) } disabled={disabled} /> )} {formData.type === 'kubernetes.io/ssh-auth' && ( <TextAreaForm value={formData.data && formData.data['ssh-privatekey']} onChange={(value: string) => handleTextAreaFormChange('ssh-privatekey', value)} disabled={disabled} /> )} {formData.type === 'kubernetes.io/tls' && ( <TLSForm tlscrt={formData.data && formData.data['tls.crt']} tlskey={formData.data && formData.data['tls.key']} onChange={(key: string, value: string) => handleTLSFormChange(key, value)} disabled={disabled} /> )} {formData.type === 'bootstrap.kubernetes.io/token' && ( <TokenForm authExtraGroups={formData.data && formData.data['auth-extra-groups']} expiration={formData.data && formData.data['expiration']} tokenId={formData.data && formData.data['token-id']} tokenSecret={formData.data && formData.data['token-secret']} usageBootstrapAuthentication={formData.data && formData.data['usage-bootstrap-authentication']} usageBootstrapSigning={formData.data && formData.data['usage-bootstrap-signing']} onChange={(key: string, value: string) => handleTokenFormChange(key, value)} disabled={disabled} /> )} </div> </FormContainer> ); }; const KeyValuePairForm = ({ values, onChange, onDelete, disabled, }: { values: {id: string; key: string; value: string}[]; disabled: boolean; onChange: Function; onDelete: Function; }) => { const [localValues, setLocalValues] = useState(values); useEffect(() => { setLocalValues(values); }, [values]); const handleDynamicValueChange = (keyValuePair: {key: string; value: string}) => { if (onChange) { onChange(keyValuePair); } }; const handleDynamicValueDelete = (keyValuePair: {key: string; value: string}) => { if (onDelete) { onDelete(keyValuePair); } }; const handleAddNewValue = () => { setLocalValues([...values, {id: 'NEW_ITEM', key: '', value: ''}]); }; return ( <FormContainer> <StyledSpanTitle>Data</StyledSpanTitle> {localValues.map(value => ( <DynamicKeyValue key={value.id} value={value} onChange={handleDynamicValueChange} onDelete={handleDynamicValueDelete} disabled={disabled} /> ))} <div style={{marginTop: '12px'}}> <Button onClick={handleAddNewValue} disabled={disabled}> Add New </Button> </div> </FormContainer> ); }; const TextAreaForm = ({value, onChange, disabled}: {value: string; onChange: Function; disabled: boolean}) => { const [localValue, setLocalValue] = useState<string | undefined>(value); const handleValueChange = (propertyValue: string) => { setLocalValue(propertyValue || undefined); }; useEffect(() => { if (_.isEqual(localValue, value)) { return; } if (onChange) { onChange(localValue); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [localValue]); return ( <FormContainer> <StyledSpanTitle>Data</StyledSpanTitle> <Base64Input type="TEXT_AREA" value={localValue} onChange={(emittedValue: string) => handleValueChange(emittedValue)} disabled={disabled} /> </FormContainer> ); }; const TLSForm = ({ tlscrt, tlskey, onChange, disabled, }: { tlscrt: string; tlskey: string; onChange: Function; disabled: boolean; }) => { const handleValueChange = (key: string, value: string) => { if (onChange) { onChange(key, value); } }; return ( <FormContainer> <StyledSpanTitle>Data</StyledSpanTitle> <div> <StyledSpanTitle>CRT</StyledSpanTitle> <Base64Input type="TEXT_AREA" value={tlscrt} onChange={(emittedValue: string) => handleValueChange('tls.crt', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Key</StyledSpanTitle> <Base64Input type="TEXT_AREA" value={tlskey} onChange={(emittedValue: string) => handleValueChange('tls.key', emittedValue)} disabled={disabled} /> </div> </FormContainer> ); }; const TokenForm = ({ authExtraGroups, expiration, tokenId, tokenSecret, usageBootstrapAuthentication, usageBootstrapSigning, onChange, disabled, }: { authExtraGroups: string; expiration: string; tokenId: string; tokenSecret: string; usageBootstrapAuthentication: string; usageBootstrapSigning: string; disabled: boolean; onChange: Function; }) => { const handleValueChange = (key: string, value: string) => { if (onChange) { onChange(key, value); } }; return ( <FormContainer> <StyledSpanTitle>Data</StyledSpanTitle> <div> <StyledSpanTitle>Auth Extra Groups</StyledSpanTitle> <Base64Input value={authExtraGroups} onChange={(emittedValue: string) => handleValueChange('auth-extra-groups', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Expiration</StyledSpanTitle> <Base64Input value={expiration} onChange={(emittedValue: string) => handleValueChange('expiration', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Token Id</StyledSpanTitle> <Base64Input value={tokenId} onChange={(emittedValue: string) => handleValueChange('token-id', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Token Secret</StyledSpanTitle> <Base64Input value={tokenSecret} onChange={(emittedValue: string) => handleValueChange('token-secret', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Usage Bootstrap Authentication</StyledSpanTitle> <Base64Input value={usageBootstrapAuthentication} onChange={(emittedValue: string) => handleValueChange('usage-bootstrap-authentication', emittedValue)} disabled={disabled} /> </div> <div> <StyledSpanTitle>Usage Bootstrap Signing</StyledSpanTitle> <Base64Input value={usageBootstrapSigning} onChange={(emittedValue: string) => handleValueChange('usage-bootstrap-signing', emittedValue)} disabled={disabled} /> </div> </FormContainer> ); }; const DynamicKeyValue = ({value, onChange, onDelete, disabled}: any) => { const [localValue, setLocalValue] = useState<{ id: string | undefined; key?: string | undefined; value?: string | undefined; }>({ id: undefined, key: undefined, value: undefined, }); useEffect(() => { if (value && value.id === 'NEW_ITEM') { setLocalValue({id: uuidv4(), key: undefined, value: undefined}); } else { setLocalValue({id: value.id, key: value.key, value: value.value}); } }, [value]); const handleValueChange = (property: string, propertyValue: string) => { if (property === 'KEY') { setLocalValue({...localValue, key: propertyValue || undefined}); } if (property === 'VALUE') { setLocalValue({...localValue, value: propertyValue || undefined}); } }; const handleDeleteValue = () => { if (onDelete) { onDelete(localValue); } }; useDebounce( () => { if (_.isEqual(localValue, value)) { return; } if (onChange && localValue.key && localValue.value) { onChange(localValue); } }, DEFAULT_EDITOR_DEBOUNCE, [localValue] ); return ( <DynamicKeyValueContainer> <DynamicKeyValueItem> <StyledSpanTitle>Key</StyledSpanTitle> <Input value={localValue.key} onChange={event => handleValueChange('KEY', event.target.value)} disabled={disabled} /> </DynamicKeyValueItem> <DynamicKeyValueItem> <StyledSpanTitle>Value</StyledSpanTitle> <Base64Input value={localValue.value} onChange={(emittedValue: string) => handleValueChange('VALUE', emittedValue)} disabled={disabled} /> </DynamicKeyValueItem> <DynamicKeyValueActionItem> <StyledSpanTitle>&nbsp;</StyledSpanTitle> <ButtonContainer> <Button onClick={handleDeleteValue} disabled={disabled}> <DeleteOutlined /> </Button> </ButtonContainer> </DynamicKeyValueActionItem> </DynamicKeyValueContainer> ); }; export const Base64Input = ({value, onChange, type = 'INPUT', disabled}: any) => { const [inputValue, setInputValue] = useState<string | undefined>( value && isBase64(value) ? Buffer.from(value, 'base64').toString('utf-8') : value ); const [debouncedValue, setDebouncedValue] = useState<string | undefined>( value && !isBase64(value) ? Buffer.from(value).toString('base64') : value ); const [isEncoded, setIsEncoded] = useState(isBase64(inputValue)); useEffect(() => { if (!value) { setInputValue(value); return; } if (isEncoded) { setInputValue(isBase64(value) ? value : Buffer.from(value).toString('base64')); } else { setInputValue(isBase64(value) ? Buffer.from(value, 'base64').toString('utf-8') : value); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [value]); useDebounce( () => { if (inputValue) { const encoded = isBase64(inputValue); setIsEncoded(encoded); if (encoded) { setDebouncedValue(inputValue); } else { setDebouncedValue(Buffer.from(inputValue).toString('base64')); } } else { setDebouncedValue(undefined); } }, DEFAULT_EDITOR_DEBOUNCE, [inputValue] ); const encode = () => { setInputValue(inputValue ? Buffer.from(inputValue).toString('base64') : undefined); setIsEncoded(true); }; const decode = () => { setInputValue(inputValue ? Buffer.from(inputValue, 'base64').toString('utf-8') : undefined); setIsEncoded(false); }; useEffect(() => { if (_.isEqual(debouncedValue, value)) { return; } if (onChange) { onChange(debouncedValue); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [debouncedValue]); return ( <> {type === 'INPUT' ? ( <Input value={inputValue} onChange={e => setInputValue(e.target.value || undefined)} onPaste={(e: any) => setInputValue(e.target.value || undefined)} disabled={disabled} /> ) : ( <TextArea rows={6} value={inputValue} onChange={e => setInputValue(e.target.value || undefined)} onPaste={(e: any) => setInputValue(e.target.value || undefined)} disabled={disabled} /> )} {!isEncoded ? ( <StyledSpanToggler onClick={() => encode()}>Encode</StyledSpanToggler> ) : ( <StyledSpanToggler onClick={() => decode()}>Decode</StyledSpanToggler> )} </> ); }; export const isBase64 = (str?: string | null) => { if (!str) { return false; } try { return Buffer.from(Buffer.from(str, 'base64').toString('utf-8')).toString('base64') === str; } catch (err) { return false; } };
the_stack
import { describe, it } from 'mocha'; import { expect } from 'chai'; import { withTempMethodParser, withTempValueParser } from './utils'; import { ParserError } from '../src/parser/ParserError'; import { BasicType, BasicTypeValue, DictionaryKeyType, DictionaryType, EnumSubType, EnumType, InterfaceType, OptionalType, PredefinedType, TupleType, ValueType, ValueTypeKind } from '../src/types'; const stringType: BasicType = { kind: ValueTypeKind.basicType, value: BasicTypeValue.string }; const numberType: BasicType = { kind: ValueTypeKind.basicType, value: BasicTypeValue.number }; const booleanType: BasicType = { kind: ValueTypeKind.basicType, value: BasicTypeValue.boolean }; describe('ValueParser', () => { describe('Return types', () => { it('Empty return', () => { const methodCode = 'mockedMethod();'; withTempMethodParser(methodCode, parseFunc => { expect(parseFunc).to.throw(ParserError).with.property('reason', 'return type error: no return type provided'); }) }); it('Return void', () => { const methodCode = 'mockedMethod(): void;'; withTempMethodParser(methodCode, parseFunc => { expect(parseFunc()).to.deep.equal({ name: 'mockedMethod', parameters: [], returnType: null, isAsync: false, documentation: '', }); }) }); it('Return promise void', () => { const methodCode = 'mockedMethod(): Promise<void>;'; withTempMethodParser(methodCode, parseFunc => { expect(parseFunc()).to.deep.equal({ name: 'mockedMethod', parameters: [], returnType: null, isAsync: true, documentation: '', }); }) }); }); describe('Parameters type', () => { it('Invalid parameters type', () => { const methodCode = 'mockedMethod(invalidArgs: string);'; withTempMethodParser(methodCode, parseFunc => { expect(parseFunc).to.throw(ParserError).with.property('reason', 'parameters error: parameters type string is not supported'); }); }); }); describe('Value types', () => { it('Not supported type', () => { withTempValueParser('void', parseFunc => { expect(parseFunc).to.throw('type void is not supported'); }); }); it('Non-existent type', () => { withTempValueParser('NonExistentType', parseFunc => { expect(parseFunc).to.throw('reference type NonExistentType not found'); }); }) testValueType('predefined type', 'PredefinedType', { kind: ValueTypeKind.predefinedType, name: 'PredefinedType' }, new Set(['PredefinedType'])); }); describe('Parse basic type', () => { testValueType('string', 'string', { kind: ValueTypeKind.basicType, value: BasicTypeValue.string }); testValueType('number', 'number', { kind: ValueTypeKind.basicType, value: BasicTypeValue.number }); testValueType('boolean', 'boolean', { kind: ValueTypeKind.basicType, value: BasicTypeValue.boolean }); }) describe('Parse InterfaceType', () => { const interfacesCode = ` interface EmptyInterface {} interface InterfaceWithMembers { stringMember: string; numberMember: number; } interface ExtendedInterface extends InterfaceWithMembers { booleanMember: boolean; } interface DictionaryInterface { [key: string]: string; } interface InterfaceWithNeverMember { stringMember: string; neverMember: never; } interface ExtendedInterfaceWithNeverMember extends InterfaceWithMembers { numberMember: never; } interface RecursiveInterface { self: RecursiveInterface; } `; const emptyInterfaceType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'EmptyInterface', members: [], documentation: '', customTags: {} }; testValueType('empty interface', 'EmptyInterface', emptyInterfaceType, new Set(), interfacesCode); const interfaceWithMembersType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'InterfaceWithMembers', members: [ { name: 'stringMember', type: stringType, documentation: '' }, { name: 'numberMember', type: numberType, documentation: '' }, ], documentation: '', customTags: {}, }; testValueType('interface with members', 'InterfaceWithMembers', interfaceWithMembersType, new Set(), interfacesCode); const extendedInterfaceType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'ExtendedInterface', members: [ { name: 'booleanMember', type: booleanType, documentation: '' }, { name: 'stringMember', type: stringType, documentation: '' }, { name: 'numberMember', type: numberType, documentation: '' }, ], documentation: '', customTags: {}, }; testValueType('extended interface', 'ExtendedInterface', extendedInterfaceType, new Set(), interfacesCode); const interfaceWithNeverMemberType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'InterfaceWithNeverMember', members: [ { name: 'stringMember', type: stringType, documentation: '' }, ], documentation: '', customTags: {}, }; testValueType('interface with never member', 'InterfaceWithNeverMember', interfaceWithNeverMemberType, new Set(), interfacesCode); const extendedInterfaceWithNeverMemberType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'ExtendedInterfaceWithNeverMember', members: [ { name: 'stringMember', type: stringType, documentation: '' }, ], documentation: '', customTags: {}, }; testValueType('extended interface with never member', 'ExtendedInterfaceWithNeverMember', extendedInterfaceWithNeverMemberType, new Set(), interfacesCode); // TODO: Recursive interface is not handled yet // const recursiveInterfaceType: InterfaceType = { // kind: ValueTypeKind.interfaceType, // name: 'RecursiveInterface', // members: [ // { name: 'self', type: { kind: ValueTypeKind.predefinedType, name: 'RecursiveInterface' }, documentation: '' }, // ], // documentation: '', // customTags: {}, // }; // testValueType('recursive interface', 'RecursiveInterface', recursiveInterfaceType, new Set(), interfacesCode); }) describe('Parse tuple type', () => { const emptyTupleType: TupleType = { kind: ValueTypeKind.tupleType, members: [] }; testValueType('empty tuple', '{}', emptyTupleType); const tupleWithMembersType: TupleType = { kind: ValueTypeKind.tupleType, members: [{ name: 'stringField', type: stringType, documentation: '' }, { name: 'numberField', type: numberType, documentation: '' }], }; testValueType('tuple with members', '{ stringField: string, numberField: number }', tupleWithMembersType); testValueType('merged tuple', '{ stringField: string } | { numberField: number }', tupleWithMembersType); const interfacesCode = ` interface InterfaceWithStringField { stringField: string; } interface InterfaceWithNumberField { numberField: number; } `; testValueType('merged interface and tuple', 'InterfaceWithStringField | { numberField: number }', tupleWithMembersType, new Set(), interfacesCode); testValueType('merged interfaces to tuple', 'InterfaceWithStringField | InterfaceWithNumberField', tupleWithMembersType, new Set(), interfacesCode); }) describe('Parse enum type', () => { const enumsCode = ` enum EmptyEnum {} enum DefaultEnum { a, b, } enum StringEnum { firstCase = 'firstCase', secondCase = 'secondCase', } enum NumberEnum { one = 1, two = 2, } enum InvalidEnum { firstCase = 'firstCase', two = 2, } `; const emptyEnumType: EnumType = { kind: ValueTypeKind.enumType, name: 'EmptyEnum', subType: EnumSubType.string, members: [], documentation: '', customTags: {} }; testValueType('empty enum', 'EmptyEnum', emptyEnumType, new Set(), enumsCode); const defaultEnumType: EnumType = { kind: ValueTypeKind.enumType, name: 'DefaultEnum', subType: EnumSubType.number, members: [ { key: 'a', value: 0, documentation: '' }, { key: 'b', value: 1, documentation: '' }, ], documentation: '', customTags: {}, } testValueType('default enum', 'DefaultEnum', defaultEnumType, new Set(), enumsCode); const stringEnumType: EnumType = { kind: ValueTypeKind.enumType, name: 'StringEnum', subType: EnumSubType.string, members: [ { key: 'firstCase', value: 'firstCase', documentation: '' }, { key: 'secondCase', value: 'secondCase', documentation: '' }, ], documentation: '', customTags: {}, } testValueType('string enum', 'StringEnum', stringEnumType, new Set(), enumsCode); const numberEnumType: EnumType = { kind: ValueTypeKind.enumType, name: 'NumberEnum', subType: EnumSubType.number, members: [ { key: 'one', value: 1, documentation: '' }, { key: 'two', value: 2, documentation: '' }, ], documentation: '', customTags: {}, } testValueType('number enum', 'NumberEnum', numberEnumType, new Set(), enumsCode); it('Invalid enum', () => { withTempValueParser('InvalidEnum', parseFunc => { expect(parseFunc).to.throw('enum InvalidEnum is invalid because enums with multiple subtypes are not supported.'); }, new Set(), enumsCode); }); }); describe('Parse array type', () => { testValueType('string array', 'string[]', { kind: ValueTypeKind.arrayType, elementType: stringType }); testValueType('number array', 'number[]', { kind: ValueTypeKind.arrayType, elementType: numberType }); testValueType('generic defined array', 'Array<string>', { kind: ValueTypeKind.arrayType, elementType: stringType }); }); describe('Parse dictionary type', () => { const stringDictionaryType: DictionaryType = { kind: ValueTypeKind.dictionaryType, keyType: DictionaryKeyType.string, valueType: stringType }; testValueType('string dictionary', '{ [key: string]: string }', stringDictionaryType); testValueType('record string dictionary', 'Record<string, string>', stringDictionaryType); testValueType('map string dictionary', 'Map<string, string>', stringDictionaryType); const numberDictionaryType: DictionaryType = { kind: ValueTypeKind.dictionaryType, keyType: DictionaryKeyType.number, valueType: booleanType }; testValueType('number dictionary', '{ [key: number]: boolean }', numberDictionaryType); testValueType('record number dictionary', 'Record<number, boolean>', numberDictionaryType); testValueType('map number dictionary', 'Map<number, boolean>', numberDictionaryType); const dictionaryCode = ` interface DictionaryInterface { [key: string]: number; } `; testValueType('string interface dictionary', 'DictionaryInterface', { kind: ValueTypeKind.dictionaryType, keyType: DictionaryKeyType.string, valueType: numberType }, new Set(), dictionaryCode); }); describe('Parse optional type', () => { it('Empty types union', () => { const valueTypeCode = 'null | undefined'; withTempValueParser(valueTypeCode, parseFunc => { expect(parseFunc).to.throw('union type null | undefined is invalid'); }); }); it('Multiple types union', () => { const valueTypeCode = 'string | number'; withTempValueParser(valueTypeCode, parseFunc => { expect(parseFunc).to.throw('union type string | number is invalid'); }); }); const optionalStringType: OptionalType = { kind: ValueTypeKind.optionalType, wrappedType: stringType }; testValueType('null union', 'string | null', optionalStringType); testValueType('undefined union', 'string | undefined', optionalStringType); testValueType('null and undefined union', 'string | null | undefined', optionalStringType); const tupleType: TupleType = { kind: ValueTypeKind.tupleType, members: [{ name: 'stringField', type: stringType, documentation: '' }, { name: 'numberField', type: numberType, documentation: '' }], }; const optionalTupleType: OptionalType = { kind: ValueTypeKind.optionalType, wrappedType: tupleType }; testValueType('merged optional tuple union', '{ stringField: string } | { numberField: number } | null', optionalTupleType); }); describe('Parse alias type', () => { const aliasTypesCode = ` interface ExampleInterface { foobar: string; } type str = string; type secondStr = str; type CodeGenStr = string & { _intBrand: never }; type AliasInterface = ExampleInterface; type AliasDefinedInterface = { foobar: string, }; `; const predefinedStringType: PredefinedType = { kind: ValueTypeKind.predefinedType, name: 'CodeGenStr' }; const aliasInterfaceType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'ExampleInterface', members: [ { name: 'foobar', type: stringType, documentation: '' }, ], documentation: '', customTags: {}, }; const aliasDefinedInterfaceType: InterfaceType = { kind: ValueTypeKind.interfaceType, name: 'AliasDefinedInterface', members: [ { name: 'foobar', type: stringType, documentation: '' }, ], documentation: '', customTags: {}, }; testValueType('string alias', 'str', stringType, new Set(), aliasTypesCode); testValueType('alias of string alias', 'secondStr', stringType, new Set(), aliasTypesCode); testValueType('predefined string alias', 'CodeGenStr', predefinedStringType, new Set(['CodeGenStr']), aliasTypesCode); testValueType('alias interface', 'AliasInterface', aliasInterfaceType, new Set(), aliasTypesCode); testValueType('alias defined interface', 'AliasDefinedInterface', aliasDefinedInterfaceType, new Set(), aliasTypesCode); }); }); function testValueType(name: string, valueTypeCode: string, type: ValueType, predefinedTypes: Set<string> = new Set(), customTypesCode: string = '') { it(`Return ${name}`, () => { withTempValueParser(valueTypeCode, parseFunc => { const valueType = parseFunc(); expect(valueType.return).to.deep.equal(type); }, predefinedTypes, customTypesCode); }) it(`Return promise ${name}`, () => { withTempValueParser(valueTypeCode, parseFunc => { const valueType = parseFunc(); expect(valueType.promiseReturn).to.deep.equal(type); }, predefinedTypes, customTypesCode); }) it(`Parameter type ${name}`, () => { withTempValueParser(valueTypeCode, parseFunc => { const valueType = parseFunc(); expect(valueType.parameter).to.deep.equal(type); }, predefinedTypes, customTypesCode); }) }
the_stack
export type InitInput = | RequestInfo | URL | Response | BufferSource | WebAssembly.Module; export abstract class WidgetryApp<InitOutput> { private appLoader: AppLoader<InitOutput>; private _assetsBaseURL: string; private _assetsAreGzipped: boolean; public constructor(domId: string) { this.appLoader = new AppLoader(this, domId); // Assume a default relative path to where we can find the "system" dir // Overide with `myApp.setAssetsBaseURL('path/to/dir')` this._assetsBaseURL = "./data"; // Assume files are gzipped unless on localhost. // Overide with `myApp.setAssetsAreGzipped(true)` this._assetsAreGzipped = !isLocalhost; } public async loadAndStart() { this.appLoader.loadAndStart(); } // Assets (the "system" dir) are assumed to be at "./data" relative // to the current URL. Otherwise override with `setAssetsBaseURL`. public assetsBaseURL(): string { return this._assetsBaseURL; } public setAssetsBaseURL(newValue: string) { this._assetsBaseURL = newValue; } // Assets are assumed to gzipped, unless on localhost public assetsAreGzipped(): boolean { return this._assetsAreGzipped; } public setAssetsAreGzipped(newValue: boolean) { this._assetsAreGzipped = newValue; } abstract initializeWasm( module_or_path?: InitInput | Promise<InitInput> ): Promise<InitOutput>; abstract run( rootDomId: string, assetsBaseURL: string, assetsAreGzipped: boolean ): void; abstract wasmURL(): string; } enum LoadState { unloaded, loading, loaded, starting, started, error, } /** * Helper class used by `WidgetryApp` implementations to load their wasm and * render their content. */ export class AppLoader<T> { app: WidgetryApp<T>; el: HTMLElement; loadingEl?: HTMLElement; errorEl?: HTMLElement; domId: string; state: LoadState = LoadState.unloaded; // (receivedLength, totalLength) downloadProgress?: [number, number]; errorMessage?: string; public constructor(app: WidgetryApp<T>, domId: string) { this.app = app; this.domId = domId; const el = document.getElementById(domId); if (el === null) { throw new Error(`element with domId: ${domId} not found`); } this.el = el; console.log("sim constructor", this); } public async loadAndStart() { this.render(); try { await this.load(); await this.start(); } catch (e) { this.reportErrorState(e.toString()); throw e; } } async load() { console.assert(this.state == LoadState.unloaded, "already loaded"); this.updateState(LoadState.loading); console.log("Started loading WASM"); const t0 = performance.now(); let response: Response = await fetch(this.app.wasmURL()); if (response.body == null) { this.reportErrorState("response.body was unexpectedly null"); return; } let reader = response.body.getReader(); let contentLength = response.headers.get("Content-Length"); if (contentLength == undefined) { this.reportErrorState( "unable to fetch wasm - contentLength was unexpectedly undefined" ); return; } if (response.status == 404) { this.reportErrorState( `server misconfiguration, wasm file not found: ${this.app.wasmURL()}` ); return; } this.downloadProgress = [0, parseInt(contentLength)]; let chunks: Uint8Array[] = []; while (true) { const { done, value } = await reader.read(); if (done) { break; } if (value == undefined) { console.error("reader value was unexpectedly undefined"); break; } chunks.push(value); this.downloadProgress[0] += value.length; this.render(); } let blob = new Blob(chunks); let buffer = await blob.arrayBuffer(); const t1 = performance.now(); console.log(`It took ${t1 - t0} ms to download WASM, now initializing it`); // TODO: Prefer streaming instantiation where available (not safari)? Seems like it'd be faster. // const { instance } = await WebAssembly.instantiateStreaming(response, imports); //let imports = {}; //let instance = await WebAssembly.instantiate(bytes, imports); await this.app.initializeWasm(buffer); this.updateState(LoadState.loaded); } async start() { console.assert(this.state == LoadState.loaded, "not yet loaded"); this.updateState(LoadState.starting); try { console.log( `running app with assetsBaseURL: ${this.app.assetsBaseURL()}, assetsAreGzipped: ${this.app.assetsAreGzipped()}` ); this.app.run( this.domId, this.app.assetsBaseURL(), this.app.assetsAreGzipped() ); } catch (e) { if ( e.toString() == "Error: Using exceptions for control flow, don't mind me. This isn't actually an error!" ) { // This is an expected, albeit unfortunate, control flow mechanism for winit on wasm. this.updateState(LoadState.started); } else { throw e; } } } isWebGL1Supported(): boolean { try { var canvas = document.createElement("canvas"); return !!canvas.getContext("webgl"); } catch (e) { return false; } } isWebGL2Supported(): boolean { try { var canvas = document.createElement("canvas"); return !!canvas.getContext("webgl2"); } catch (e) { return false; } } updateState(newValue: LoadState) { console.debug( `state change: ${LoadState[this.state]} -> ${LoadState[newValue]}` ); this.state = newValue; this.render(); } reportErrorState(errorMessage: string) { this.errorMessage = errorMessage; this.updateState(LoadState.error); } // UI render() { this.el.style.backgroundColor = "black"; switch (this.state) { case LoadState.loading: { if (this.loadingEl == undefined) { this.loadingEl = buildLoadingEl(); // insert after rendering initial progress to avoid jitter. this.el.append(this.loadingEl); } if (this.downloadProgress != undefined) { let received = this.downloadProgress[0]; let total = this.downloadProgress[1]; let progressText = `${prettyPrintBytes( received )} / ${prettyPrintBytes(total)}`; let percentText = `${(100.0 * received) / total}%`; this.loadingEl.querySelector<HTMLElement>( ".widgetry-app-loader-progress-text" )!.innerText = progressText; this.loadingEl.querySelector<HTMLElement>( ".widgetry-app-loader-progress-bar" )!.style.width = percentText; } break; } case LoadState.error: { if (this.loadingEl != undefined) { this.loadingEl.remove(); this.loadingEl = undefined; } if (this.errorEl == undefined) { if (!this.isWebGL1Supported() && !this.isWebGL2Supported()) { this.errorMessage = this.errorMessage + "😭 Looks like your browser doesn't support WebGL."; } if (this.errorMessage == undefined) { this.errorMessage = "An unknown error occurred. Try checking the developer console."; } let el = buildErrorEl(this.errorMessage); this.errorEl = el; this.el.append(el); } break; } } } } export function modRoot(importMetaURL: string): string { function dirname(path: string): string { return path.match(/.*\//)!.toString(); } let url = new URL(importMetaURL); url.pathname = dirname(url.pathname).toString(); return url.toString(); } function buildLoadingEl(): HTMLElement { let loadingEl = document.createElement("div"); loadingEl.innerHTML = ` <style type="text/css"> .widgetry-app-loader { color: white; padding: 16px; } .widgetry-app-loader-progress-bar-container { background-color: black; border: 1px solid white; border-radius: 4px; } .widgetry-app-loader-progress-bar { background-color: white; height: 12px; } .widgetry-app-loader-progress-text { margin-bottom: 16px; } </style> <p><strong>Loading...</strong></p> <div class="widgetry-app-loader-progress-bar-container" style="width: 100%;"> <div class="widgetry-app-loader-progress-bar" style="width: 1%;"></div> </div> <div class="widgetry-app-loader-progress-text">0 / 0</div> <p>If you think something has broken, check your browser's developer console (Ctrl+Shift+I or similar)</p> <p>(Your browser must support WebGL and WebAssembly)</p> `; loadingEl.setAttribute("class", "widgetry-app-loader"); return loadingEl; } function buildErrorEl(errorMessage: string): HTMLElement { let el = document.createElement("p"); el.innerHTML = ` <style type="text/css"> .widgetry-app-loader-error { color: white; text-align: center; padding: 16px; } </style> <h2>Error Loading App</h2> ${errorMessage} `; el.setAttribute("class", "widgetry-app-loader-error"); return el; } function prettyPrintBytes(bytes: number): string { if (bytes < 1024 ** 2) { return Math.round(bytes / 1024) + " KB"; } return Math.round(bytes / 1024 ** 2) + " MB"; } // courtesy: https://stackoverflow.com/a/57949518 const isLocalhost = Boolean( window.location.hostname === "localhost" || window.location.hostname === "0.0.0.0" || // [::1] is the IPv6 localhost address. window.location.hostname === "[::1]" || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) );
the_stack
import { DiagramElement, Corners } from '../core/elements/diagram-element'; import { compile as baseTemplateComplier } from '@syncfusion/ej2-base'; import { Rect } from '../primitives/rect'; import { Size } from '../primitives/size'; import { PointModel } from '../primitives/point-model'; import { Matrix, identityMatrix, transformPointByMatrix, rotateMatrix } from '../primitives/matrix'; import { TextAlign, TextWrap, WhiteSpace, TextDecoration } from '../enum/enum'; import { getValue } from '@syncfusion/ej2-base'; import { TextAttributes } from '../rendering/canvas-interface'; import { getChildNode, applyStyleAgainstCsp } from './dom-util'; import { Diagram } from '../diagram'; import { Node, BasicShape, Shape, Native, BpmnShape, BpmnActivity, BpmnTask, BpmnSubProcess } from '../objects/node'; import { IconShape } from '../objects/icon'; import { TextStyle, ShapeStyle, Margin } from '../core/appearance'; import { Port } from '../objects/port'; import { Annotation } from '../objects/annotation'; import { Connector, Decorator } from '../objects/connector'; /** * Implements the basic functionalities */ /** * Used to generate the random id \ * * @returns { boolean } Used to generate the random id .\ * * @private */ export function randomId(): string { const chars: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'; let id: string = ''; let num: number; for (let i: number = 0; i < 5; i++) { if ('crypto' in window && 'getRandomValues' in crypto) { const count: Uint16Array = new Uint16Array(1); // tslint:disable-next-line:no-any const intCrypto: any = (window as any).msCrypto || window.crypto; num = intCrypto.getRandomValues(count)[0] % (chars.length - 1); } else { num = Math.floor(Math.random() * chars.length); } if (i === 0 && num < 10) { i--; continue; } id += chars.substring(num, num + 1); } return id; } /** * Used to get the index value \ * * @returns { boolean } Used to get the index value .\ * @param {Diagram} comp - provide the Diagram value. * @param {string} id - provide the id value. * * @private */ export function getIndex(comp: Diagram, id: string): number { if (comp.nodes && comp.nodes.length > 0) { for (let i: number = 0; i < comp.nodes.length; i++) { if (comp.nodes[i].id === id) { return i; } } } if (comp.connectors && comp.connectors.length > 0) { for (let i: number = 0; i < comp.connectors.length; i++) { if (comp.connectors[i].id === id) { return i; } } } return null; } /** * templateCompiler method\ * * @returns { Function } templateCompiler method .\ * @param {string} template - provide the template value. * * @private */ export function templateCompiler(template: string): Function { if (template) { // eslint-disable-next-line @typescript-eslint/no-unused-vars let e: Object; try { if (document.querySelectorAll(template).length) { return baseTemplateComplier(document.querySelector(template).innerHTML.trim()); } } catch (e) { return baseTemplateComplier(template); } } return undefined; } /** * cornersPointsBeforeRotation method\ * * @returns { Rect } templateCompiler method .\ * @param {DiagramElement} ele - provide the template value. * * @private */ export function cornersPointsBeforeRotation(ele: DiagramElement): Rect { let bounds: Rect = new Rect(); const top: number = ele.offsetY - ele.actualSize.height * ele.pivot.y; const bottom: number = ele.offsetY + ele.actualSize.height * (1 - ele.pivot.y); const left: number = ele.offsetX - ele.actualSize.width * ele.pivot.x; const right: number = ele.offsetX + ele.actualSize.width * (1 - ele.pivot.x); const topLeft: PointModel = { x: left, y: top }; //const topCenter: PointModel = { x: (left + right) / 2, y: top }; const topRight: PointModel = { x: right, y: top }; //const middleLeft: PointModel = { x: left, y: (top + bottom) / 2 }; //const middleRight: PointModel = { x: right, y: (top + bottom) / 2 }; const bottomLeft: PointModel = { x: left, y: bottom }; //const bottomCenter: PointModel = { x: (left + right) / 2, y: bottom }; const bottomRight: PointModel = { x: right, y: bottom }; bounds = Rect.toBounds([topLeft, topRight, bottomLeft, bottomRight]); return bounds; } /** * getBounds method\ * * @returns { Rect } getBounds method .\ * @param {DiagramElement} element - provide the template value. * * @private */ export function getBounds(element: DiagramElement): Rect { let bounds: Rect = new Rect(); //let corners: Rect; const corners: Rect = cornersPointsBeforeRotation(element); let middleLeft: PointModel = corners.middleLeft; let topCenter: PointModel = corners.topCenter; let bottomCenter: PointModel = corners.bottomCenter; let middleRight: PointModel = corners.middleRight; let topLeft: PointModel = corners.topLeft; let topRight: PointModel = corners.topRight; let bottomLeft: PointModel = corners.bottomLeft; let bottomRight: PointModel = corners.bottomRight; element.corners = { topLeft: topLeft, topCenter: topCenter, topRight: topRight, middleLeft: middleLeft, middleRight: middleRight, bottomLeft: bottomLeft, bottomCenter: bottomCenter, bottomRight: bottomRight } as Corners; if (element.rotateAngle !== 0 || element.parentTransform !== 0) { const matrix: Matrix = identityMatrix(); rotateMatrix(matrix, element.rotateAngle + element.parentTransform, element.offsetX, element.offsetY); element.corners.topLeft = topLeft = transformPointByMatrix(matrix, topLeft); element.corners.topCenter = topCenter = transformPointByMatrix(matrix, topCenter); element.corners.topRight = topRight = transformPointByMatrix(matrix, topRight); element.corners.middleLeft = middleLeft = transformPointByMatrix(matrix, middleLeft); element.corners.middleRight = middleRight = transformPointByMatrix(matrix, middleRight); element.corners.bottomLeft = bottomLeft = transformPointByMatrix(matrix, bottomLeft); element.corners.bottomCenter = bottomCenter = transformPointByMatrix(matrix, bottomCenter); element.corners.bottomRight = bottomRight = transformPointByMatrix(matrix, bottomRight); //Set corners based on rotate angle } bounds = Rect.toBounds([topLeft, topRight, bottomLeft, bottomRight]); element.corners.left = bounds.left; element.corners.right = bounds.right; element.corners.top = bounds.top; element.corners.bottom = bounds.bottom; element.corners.center = bounds.center; element.corners.width = bounds.width; element.corners.height = bounds.height; return bounds; } /** * updateCloneProp method\ * * @returns { Rect } updateCloneProp method .\ * @param {DiagramElement} properties - provide the template value. * @param {DiagramElement} obj - provide the template value. * * @private */ function updateCloneProp(properties: string[], obj: Object): string[] { let prop: string[] = []; if (obj instanceof Node) { prop = ['width', 'height', 'offsetX', 'offsetY', 'container', 'visible', 'horizontalAlignment', 'verticalAlignment', 'backgroundColor', 'borderColor', 'borderWidth', 'rotateAngle', 'minHeight', 'minWidth', 'maxHeight', 'maxWidth', 'pivot', 'margin', 'flip', 'wrapper', 'constraints', 'style', 'annotations', 'ports', 'isExpanded', 'expandIcon']; } else if (obj instanceof Connector) { prop = ['constraints', 'sourcePadding', 'targetPadding', 'cornerRadius', 'flip', 'type', 'targetDecorator', 'sourceDecorator', 'sourceID', 'shape', 'bridgeSpace', 'annotations', 'segments', 'hitPadding', 'tooltip', 'previewSize', 'dragSize', 'style', 'sourcePortID', 'targetID', 'targetPortID', 'visible']; } else if (obj instanceof Decorator) { prop = ['height', 'width', 'shape', 'style', 'pivot', 'pathData']; } else if (obj instanceof Shape || obj instanceof IconShape) { prop.push('shape'); if (obj instanceof BasicShape) { prop.push('cornerRadius'); } else if (obj instanceof Text) { prop.push('margin'); } else if (obj instanceof Image) { prop.push('align'); prop.push('scale'); } else if (obj instanceof Native) { prop.push('scale'); } else if (obj instanceof BpmnShape) { prop.push('activity'); prop.push('annotations'); } else if (obj instanceof IconShape) { prop.push('borderColor'); prop.push('borderWidth'); prop.push('cornerRadius'); prop.push('fill'); } } else if (obj instanceof BpmnActivity) { prop.push('subProcess'); } else if (obj instanceof BpmnTask) { prop.push('call'); prop.push('compensation'); prop.push('loop'); } else if (obj instanceof BpmnSubProcess) { prop.push('adhoc'); prop.push('boundary'); prop.push('compensation'); prop.push('loop'); prop.push('processes'); } else if (obj instanceof Port) { prop.push('height'); prop.push('width'); prop.push('visibility'); prop.push('horizontalAlignment'); prop.push('verticalAlignment'); prop.push('shape'); } else if (obj instanceof Annotation) { prop.push('constraints'); prop.push('height'); prop.push('horizontalAlignment'); prop.push('rotateAngle'); prop.push('template'); prop.push('verticalAlignment'); prop.push('visibility'); prop.push('width'); prop.push('margin'); } else if (obj instanceof Margin) { prop.push('left'); prop.push('right'); prop.push('top'); prop.push('bottom'); } else if (obj instanceof TextStyle) { prop = ['strokeWidth', 'strokeDashArray', 'opacity', 'gradient', 'fontSize', 'fontFamily', 'textOverflow', 'textDecoration', 'whiteSpace', 'textWrapping', 'textAlign', 'italic', 'bold']; } if (obj instanceof ShapeStyle) { prop.push('strokeColor'); prop.push('color'); } properties = properties.concat(prop); return properties; } /** * cloneObject method\ * * @returns { Rect } cloneObject method .\ * @param {DiagramElement} obj - provide the obj value. * @param {DiagramElement} additionalProp - provide the additionalProp value. * @param {DiagramElement} key - provide the key value. * @param {DiagramElement} cloneBlazorProp - provide the cloneBlazorProp value. * * @private */ export function cloneObject(obj: Object, additionalProp?: Function | string, key?: string, cloneBlazorProp?: boolean): Object { const newObject: Object = {}; const keys: string = 'properties'; const prop: string = 'propName'; if (obj) { key = obj[prop]; const sourceObject: Object = obj[keys] || obj; let properties: string[] = []; properties = properties.concat(Object.keys(sourceObject)); let customProperties: string[] = []; properties.push('version'); if (key) { const propAdditional: Function = getFunction(additionalProp); if (propAdditional) { customProperties = propAdditional(key); } else { customProperties = []; } properties = properties.concat(customProperties); } const internalProp: string[] = getInternalProperties(key); properties = properties.concat(internalProp); if (cloneBlazorProp) { properties = updateCloneProp(properties, obj); } for (const property of properties) { if (property !== 'historyManager') { if (property !== 'wrapper') { //const constructorId: string = 'constructor'; //const name: string = 'name'; // eslint-disable-next-line no-prototype-builtins const isEventEmmitter: boolean = obj[property] && obj.hasOwnProperty('observers') ? true : false; if (!isEventEmmitter) { if (obj[property] instanceof Array) { newObject[property] = cloneArray( (internalProp.indexOf(property) === -1 && obj[keys]) ? obj[keys][property] : obj[property], additionalProp, property, cloneBlazorProp); } else if (obj[property] instanceof Array === false && obj[property] instanceof HTMLElement) { newObject[property] = obj[property].cloneNode(true).innerHtml; } else if (obj[property] instanceof Array === false && obj[property] instanceof Object) { newObject[property] = cloneObject( (internalProp.indexOf(property) === -1 && obj[keys]) ? obj[keys][property] : obj[property], undefined, undefined, cloneBlazorProp); } else { newObject[property] = obj[property]; } } } else { if (obj[property]) { newObject[property] = { actualSize: { width: obj[property].actualSize.width, height: obj[property].actualSize.height }, offsetX: obj[property].offsetX, offsetY: obj[property].offsetY }; } } } } } return newObject; } /** * getInternalProperties method\ * * @returns { string[] } getInternalProperties method .\ * @param {string} propName - provide the propName value. * * @private */ export function getInternalProperties(propName: string): string[] { switch (propName) { case 'nodes': case 'children': return ['inEdges', 'outEdges', 'parentId', 'processId', 'nodeId', 'umlIndex', 'isPhase', 'isLane']; case 'connectors': return ['parentId']; case 'annotation': return ['nodeId']; case 'annotations': return ['nodeId']; case 'shape': return ['hasHeader']; case 'layers': return ['objectZIndex']; } return []; } /** * cloneArray method\ * * @returns { Object[] } getInternalProperties method .\ * @param {string} sourceArray - provide the sourceArray value. * @param {string} additionalProp - provide the additionalProp value. * @param {string} key - provide the key value. * @param {string} cloneBlazorProp - provide the cloneBlazorProp value. * * @private */ export function cloneArray(sourceArray: Object[], additionalProp?: Function | string, key?: string, cloneBlazorProp?: boolean): Object[] { let clonedArray: Object[]; if (sourceArray) { clonedArray = []; for (let i: number = 0; i < sourceArray.length; i++) { if (sourceArray[i] instanceof Array) { clonedArray.push(sourceArray[i]); } else if (sourceArray[i] instanceof Object) { clonedArray.push(cloneObject(sourceArray[i], additionalProp, key, cloneBlazorProp)); } else { clonedArray.push(sourceArray[i]); } } } return clonedArray; } /** * extendObject method\ * * @returns { Object} getInternalProperties method .\ * @param {string} options - provide the options value. * @param {string} childObject - provide the childObject value. * * @private */ export function extendObject(options: Object, childObject: Object): Object { const properties: string = 'properties'; if (options) { if (!childObject) { childObject = { properties: {} }; } //const target: Object = childObject; for (const property of Object.keys(options)) { if (options[property] instanceof Array) { const extendeArray: Object[] = extendArray(options[property], childObject[properties][property]); if (!childObject[properties][property] || !childObject[properties][property].length) { childObject[property] = extendeArray; } } else if (options[property] instanceof Array === false && options[property] instanceof HTMLElement) { childObject[property] = options[property].cloneNode(true).innerHtml; } else if (options[property] instanceof Array === false && options[property] instanceof Object) { const extendedObject: Object = extendObject(options[property], childObject[properties][property]); if (extendedObject[properties] && !Object.keys(extendedObject[properties]).length) { delete extendedObject[properties]; } childObject[property] = extendedObject; } else { childObject[property] = childObject[properties][property] !== undefined ? childObject[property] : options[property]; } } } return childObject; } /** * extendObject method\ * * @returns { Object} getInternalProperties method .\ * @param {string} sourceArray - provide the sourceArray value. * @param {string} childArray - provide the childArray value. * * @private */ export function extendArray(sourceArray: Object[], childArray: Object[]): Object[] { const clonedArray: Object[] = []; let reset: boolean = false; if (!childArray) { childArray = []; } if (!childArray.length) { reset = true; } for (let i: number = 0; i < sourceArray.length; i++) { if (sourceArray[i] instanceof Array) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const extendedArray: Object[] = extendArray(sourceArray[i] as Object[], childArray[i] as Object[]); if (reset) { clonedArray.push(extendArray); } } else if (sourceArray[i] instanceof Object) { const extendedObject: Object = extendObject(sourceArray[i], childArray[i]); if (reset) { clonedArray.push(extendedObject); } } else { clonedArray.push(sourceArray[i]); } } return clonedArray; } /** * textAlignToString method\ * * @returns { Object} textAlignToString method .\ * @param {string} value - provide the sourceArray value. * * @private */ export function textAlignToString(value: TextAlign): string { let state: string = ''; switch (value) { case 'Center': state = 'center'; break; case 'Left': state = 'left'; break; case 'Right': state = 'right'; break; } return state; } /** * wordBreakToString method\ * * @returns { string } wordBreakToString method .\ * @param {TextWrap | TextDecoration} value - provide the value value. * * @private */ export function wordBreakToString(value: TextWrap | TextDecoration): string { let state: string = ''; switch (value) { case 'Wrap': state = 'breakall'; break; case 'NoWrap': state = 'keepall'; break; case 'WrapWithOverflow': state = 'normal'; break; case 'LineThrough': state = 'line-through'; break; } return state; } /** * bBoxText method\ * * @returns { number } bBoxText method .\ * @param {string} textContent - provide the textContent value. * @param {string} options - provide the options value. * * @private */ export function bBoxText(textContent: string, options: TextAttributes): number { const measureWindowElement: string = 'measureElement'; window[measureWindowElement].style.visibility = 'visible'; const svg: SVGElement = window[measureWindowElement].children[2]; const text: SVGTextElement = getChildNode(svg)[1] as SVGTextElement; text.textContent = textContent; applyStyleAgainstCsp(text, 'font-size:' + options.fontSize + 'px; font-family:' + options.fontFamily + ';font-weight:' + (options.bold ? 'bold' : 'normal')); const bBox: number = text.getBBox().width; window[measureWindowElement].style.visibility = 'hidden'; return bBox; } /** * middleElement method\ * * @returns { number} middleElement method .\ * @param {number} i - provide the textContent value. * @param {number} j - provide the options value. * * @private */ export function middleElement(i: number, j: number): number { let m: number = 0; m = (i + j) / 2; return m; } /** * overFlow method\ * * @returns { number} overFlow method .\ * @param {number} text - provide the text value. * @param {number} options - provide the options value. * * @private */ export function overFlow(text: string, options: TextAttributes): string { let i: number = 0; let j: number = 0; let middle: number = 0; let bounds: number = 0; let temp: string = ''; j = text.length; let t: number = 0; do { if (bounds > 0) { i = middle; } middle = Math.floor(middleElement(i, j)); temp += text.substr(i, middle); bounds = bBoxText(temp, options); } while (bounds <= options.width); temp = temp.substr(0, i); for (t = i; t < j; t++) { temp += text[t]; bounds = bBoxText(temp, options); if (bounds >= options.width) { text = text.substr(0, temp.length - 1); break; } } if (options.textOverflow === 'Ellipsis') { text = text.substr(0, text.length - 3); text += '...'; } else { text = text.substr(0, text.length); } return text; } /** * whiteSpaceToString method\ * * @returns { number} whiteSpaceToString method .\ * @param {number} value - provide the value value. * @param {number} wrap - provide the wrap value. * * @private */ export function whiteSpaceToString(value: WhiteSpace, wrap: TextWrap): string { if (wrap === 'NoWrap' && value === 'PreserveAll') { return 'pre'; } let state: string = ''; switch (value) { case 'CollapseAll': state = 'nowrap'; break; case 'CollapseSpace': state = 'pre-line'; break; case 'PreserveAll': state = 'pre-wrap'; break; } return state; } /** * rotateSize method\ * * @returns { number} rotateSize method .\ * @param {number} size - provide the size value. * @param {number} angle - provide the angle value. * * @private */ export function rotateSize(size: Size, angle: number): Size { const matrix: Matrix = identityMatrix(); rotateMatrix(matrix, angle, 0, 0); const topLeft: PointModel = transformPointByMatrix(matrix, { x: 0, y: 0 }); const topRight: PointModel = transformPointByMatrix(matrix, { x: size.width, y: 0 }); const bottomLeft: PointModel = transformPointByMatrix(matrix, { x: 0, y: size.height }); const bottomRight: PointModel = transformPointByMatrix(matrix, { x: size.width, y: size.height }); const minX: number = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); const minY: number = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); const maxX: number = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x); const maxY: number = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y); return new Size(maxX - minX, maxY - minY); } /** * rotatePoint method\ * * @returns { number} rotateSize method .\ * @param {number} angle - provide the angle value. * @param {number} pivotX - provide the pivotX value. * @param {number} pivotY - provide the pivotY value. * @param {PointModel} point - provide the point value. * @private */ export function rotatePoint(angle: number, pivotX: number, pivotY: number, point: PointModel): PointModel { if (angle !== 0) { const matrix: Matrix = identityMatrix(); rotateMatrix(matrix, angle, pivotX, pivotY); return transformPointByMatrix(matrix, point); } return point; } /** * getOffset method\ * * @returns { number} getOffset method .\ * @param {PointModel} topLeft - provide the angle value. * @param {DiagramElement} obj - provide the pivotX value. * @private */ export function getOffset(topLeft: PointModel, obj: DiagramElement): PointModel { const offX: number = topLeft.x + obj.desiredSize.width * obj.pivot.x; const offY: number = topLeft.y + obj.desiredSize.height * obj.pivot.y; return { x: offX, y: offY }; } /** * getFunction method\ * * @returns { Function } getFunction method .\ * @param {PointModel} value - provide the angle value. * @private */ export function getFunction(value: Function | string): Function { if (value !== undefined) { if (typeof value === 'string') { value = getValue(value, window); } } return value as Function; }
the_stack
import * as types from "../../../../common/types"; import {getDocumentedTypeLocation} from "../modules/astUtils"; import {getParsedComment} from "../modules/jsDoc"; /** Source File */ export function transformSourceFile(sourceFile: ts.SourceFile): types.DocumentedType { const name = sourceFile.fileName; const icon = ts.isExternalModule(sourceFile) ? types.IconType.Namespace : types.IconType.Global; const comment = getParsedComment(sourceFile, sourceFile); const subItems = getSignificantSubItems(sourceFile, sourceFile); return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, sourceFile.pos), }; } /** There are a few root level things we care about. This only recurses on those 🌹 */ function getSignificantSubItems(node: ts.SourceFile | ts.ModuleBlock, sourceFile: ts.SourceFile): types.DocumentedType[] { const subItems: types.DocumentedType[] = []; ts.forEachChild(node, (node) => { if (node.kind == ts.SyntaxKind.ClassDeclaration) { subItems.push(transformClass(node as ts.ClassDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.InterfaceDeclaration) { subItems.push(transformInterface(node as ts.InterfaceDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.EnumDeclaration) { subItems.push(transformEnum(node as ts.EnumDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.VariableStatement) { transformVariableStatement(node as ts.VariableStatement, sourceFile).forEach(variable => subItems.push(variable)); } if (node.kind == ts.SyntaxKind.FunctionDeclaration) { const functionDeclaration = node as ts.FunctionDeclaration; /** If it doesn't have a `block` then its an overload. We don't want to visit it */ if (!functionDeclaration.body) return; subItems.push(transformFunction(functionDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.ModuleDeclaration) { subItems.push(transformModule(node as ts.ModuleDeclaration, sourceFile)); } }); return subItems; } /** Class */ function transformClass(node: ts.ClassDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = node.name.text; const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.Class; if (node.typeParameters) { icon = types.IconType.ClassGeneric; } ts.forEachChild(node, (node) => { if (node.kind == ts.SyntaxKind.Constructor) { subItems.push(transformClassConstructor(node as ts.ConstructorDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.PropertyDeclaration) { subItems.push(transformClassProperty(node as ts.PropertyDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.MethodDeclaration) { subItems.push(transformClassMethod(node as ts.MethodDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.IndexSignature) { subItems.push(transformClassIndexSignature(node as ts.IndexSignatureDeclaration, sourceFile)); } }); return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Class Constructor */ function transformClassConstructor(node: ts.ConstructorDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = "constructor"; const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.ClassConstructor; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Class Property */ function transformClassProperty(node: ts.PropertyDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.ClassProperty; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Class Method */ function transformClassMethod(node: ts.MethodDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.ClassMethod; if (node.typeParameters) { icon = types.IconType.ClassMethodGeneric; } return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Class Index Signature */ function transformClassIndexSignature(node: ts.IndexSignatureDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = "Index Signature"; const comment = '`' + node.getText() + '`' + `\n` + (getParsedComment(node, sourceFile) || ''); const subItems: types.DocumentedType[] = []; let icon = types.IconType.ClassIndexSignature; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Interface */ function transformInterface(node: ts.InterfaceDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = node.name.text; const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.Interface; if (node.typeParameters) { icon = types.IconType.InterfaceGeneric; } ts.forEachChild(node, (node) => { if (node.kind == ts.SyntaxKind.ConstructSignature) { subItems.push(transformInterfaceConstructor(node as ts.ConstructSignatureDeclaration, sourceFile)); } if (node.kind == ts.SyntaxKind.PropertySignature) { subItems.push(transformInterfaceProperty(node as ts.PropertySignature, sourceFile)); } if (node.kind == ts.SyntaxKind.MethodSignature) { subItems.push(transformInterfaceMethod(node as ts.MethodSignature, sourceFile)); } if (node.kind == ts.SyntaxKind.IndexSignature) { subItems.push(transformInterfaceIndexSignature(node as ts.IndexSignatureDeclaration, sourceFile)); } }); return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Interface Property */ function transformInterfaceProperty(node: ts.PropertySignature, sourceFile: ts.SourceFile): types.DocumentedType { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.InterfaceProperty; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Interface Constructor */ function transformInterfaceConstructor(node: ts.ConstructSignatureDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = "constructor"; const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.InterfaceConstructor; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Interface Method */ function transformInterfaceMethod(node: ts.MethodSignature, sourceFile: ts.SourceFile): types.DocumentedType { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.InterfaceMethod; if (node.typeParameters) { icon = types.IconType.InterfaceMethodGeneric; } return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Interface Index Signature */ function transformInterfaceIndexSignature(node: ts.IndexSignatureDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = "Index Signature"; const comment = '`' + node.getText() + '`' + `\n` + (getParsedComment(node, sourceFile) || ''); const subItems: types.DocumentedType[] = []; let icon = types.IconType.InterfaceIndexSignature; return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.pos), }; } /** Enum */ function transformEnum(node: ts.EnumDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = node.name.text; const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.Enum; ts.forEachChild(node, (node) => { if (node.kind == ts.SyntaxKind.EnumMember) { const member = node as ts.EnumMember; subItems.push({ name: member.name.getText(), icon: types.IconType.EnumMember, comment: getParsedComment(node, sourceFile), subItems: [], location: getDocumentedTypeLocation(sourceFile, member.name.pos), }); } }); return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Variable */ function transformVariableStatement(node: ts.VariableStatement, sourceFile: ts.SourceFile): types.DocumentedType[] { const result: types.DocumentedType[] = []; const declarations = node.declarationList.declarations; declarations.forEach(d => { const comment = getParsedComment(d, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.Variable; if (d.name.kind === ts.SyntaxKind.ObjectBindingPattern) { /** destructured variable declaration */ const names = d.name as ts.ObjectBindingPattern; names.elements.forEach(bindingElement => { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(bindingElement.name)); result.push({ name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, bindingElement.pos), }); }); } else { let name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(d.name)); result.push({ name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, d.pos), }); } }); return result; } /** Function */ function transformFunction(node: ts.FunctionDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { const name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = []; let icon = types.IconType.Function; if (node.typeParameters) { icon = types.IconType.FunctionGeneric; } return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), }; } /** Module | Namespace */ function transformModule(node: ts.ModuleDeclaration, sourceFile: ts.SourceFile): types.DocumentedType { /** * Namespace chaining basics * a.b.c {} * a > declaration * b > declaration * c > declaration + body * * So if no body then we have to go down to get the name. * Also we the *body* is were we should recurse */ let icon = types.IconType.Namespace; let name = ts.unescapeLeadingUnderscores(ts.getPropertyNameForPropertyNameNode(node.name)); if (node.body.kind === ts.SyntaxKind.ModuleDeclaration) { name = name + '.'; const recurse = transformModule(node.body as ts.ModuleDeclaration, sourceFile); return { name: name + recurse.name, icon, comment: recurse.comment, subItems: recurse.subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos), } } else { const comment = getParsedComment(node, sourceFile); const subItems: types.DocumentedType[] = getSignificantSubItems(node.body as ts.ModuleBlock, sourceFile); return { name, icon, comment, subItems, location: getDocumentedTypeLocation(sourceFile, node.name.pos) }; } } // TODO: these /** Type */
the_stack
process.env.NODE_ENV = 'test'; import * as assert from 'assert'; import * as childProcess from 'child_process'; import { connectStream, signup, request, post } from './utils'; import { Following } from '../built/models/entities/following'; const initDb = require('../built/db/postgre.js').initDb; describe('Streaming', () => { let p: childProcess.ChildProcess; let Followings: any; beforeEach(done => { p = childProcess.spawn('node', [__dirname + '/../index.js'], { stdio: ['inherit', 'inherit', 'ipc'], env: { NODE_ENV: 'test' } }); p.on('message', message => { if (message === 'ok') { (p.channel as any).onread = () => {}; initDb(true).then(async (connection: any) => { Followings = connection.getRepository(Following); done(); }); } }); }); afterEach(() => { p.kill(); }); const follow = async (follower: any, followee: any) => { await Followings.save({ id: 'a', createdAt: new Date(), followerId: follower.id, followeeId: followee.id, followerHost: follower.host, followerInbox: null, followerSharedInbox: null, followeeHost: followee.host, followeeInbox: null, followeeSharedInbox: null }); }; it('mention event', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const ws = await connectStream(bob, 'main', ({ type, body }) => { if (type == 'mention') { assert.deepStrictEqual(body.userId, alice.id); ws.close(); done(); } }); post(alice, { text: 'foo @bob bar' }); })); it('renote event', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const bobNote = await post(bob, { text: 'foo' }); const ws = await connectStream(bob, 'main', ({ type, body }) => { if (type == 'renote') { assert.deepStrictEqual(body.renoteId, bobNote.id); ws.close(); done(); } }); post(alice, { renoteId: bobNote.id }); })); describe('Home Timeline', () => { it('自分の投稿が流れる', () => new Promise(async done => { const post = { text: 'foo' }; const me = await signup(); const ws = await connectStream(me, 'homeTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.text, post.text); ws.close(); done(); } }); request('/notes/create', post, me); })); it('フォローしているユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); const ws = await connectStream(alice, 'homeTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('フォローしていないユーザーの投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'homeTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); post(bob, { text: 'foo' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('フォローしているユーザーのダイレクト投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); const ws = await connectStream(alice, 'homeTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); assert.deepStrictEqual(body.text, 'foo'); ws.close(); done(); } }); // Bob が Alice 宛てのダイレクト投稿 post(bob, { text: 'foo', visibility: 'specified', visibleUserIds: [alice.id] }); })); it('フォローしているユーザーでも自分が指定されていないダイレクト投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const carol = await signup({ username: 'carol' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); let fired = false; const ws = await connectStream(alice, 'homeTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // Bob が Carol 宛てのダイレクト投稿 post(bob, { text: 'foo', visibility: 'specified', visibleUserIds: [carol.id] }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); }); describe('Local Timeline', () => { it('自分の投稿が流れる', () => new Promise(async done => { const me = await signup(); const ws = await connectStream(me, 'localTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, me.id); ws.close(); done(); } }); post(me, { text: 'foo' }); })); it('フォローしていないローカルユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('リモートユーザーの投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob', host: 'example.com' }); let fired = false; const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); post(bob, { text: 'foo' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('フォローしてたとしてもリモートユーザーの投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob', host: 'example.com' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); let fired = false; const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); post(bob, { text: 'foo' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('ホーム指定の投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // ホーム指定 post(bob, { text: 'foo', visibility: 'home' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('フォローしているローカルユーザーのダイレクト投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); assert.deepStrictEqual(body.text, 'foo'); ws.close(); done(); } }); // Bob が Alice 宛てのダイレクト投稿 post(bob, { text: 'foo', visibility: 'specified', visibleUserIds: [alice.id] }); })); it('フォローしていないローカルユーザーのフォロワー宛て投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'localTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // フォロワー宛て投稿 post(bob, { text: 'foo', visibility: 'followers' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); }); describe('Hybrid Timeline', () => { it('自分の投稿が流れる', () => new Promise(async done => { const me = await signup(); const ws = await connectStream(me, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, me.id); ws.close(); done(); } }); post(me, { text: 'foo' }); })); it('フォローしていないローカルユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('フォローしているリモートユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob', host: 'example.com' }); // Alice が Bob をフォロー await follow(alice, bob); const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('フォローしていないリモートユーザーの投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob', host: 'example.com' }); let fired = false; const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); post(bob, { text: 'foo' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('フォローしているユーザーのダイレクト投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); assert.deepStrictEqual(body.text, 'foo'); ws.close(); done(); } }); // Bob が Alice 宛てのダイレクト投稿 post(bob, { text: 'foo', visibility: 'specified', visibleUserIds: [alice.id] }); })); it('フォローしているユーザーのホーム投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // Alice が Bob をフォロー await request('/following/create', { userId: bob.id }, alice); const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); assert.deepStrictEqual(body.text, 'foo'); ws.close(); done(); } }); // ホーム投稿 post(bob, { text: 'foo', visibility: 'home' }); })); it('フォローしていないローカルユーザーのホーム投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // ホーム投稿 post(bob, { text: 'foo', visibility: 'home' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); it('フォローしていないローカルユーザーのフォロワー宛て投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'hybridTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // フォロワー宛て投稿 post(bob, { text: 'foo', visibility: 'followers' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); }); describe('Global Timeline', () => { it('フォローしていないローカルユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); const ws = await connectStream(alice, 'globalTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('フォローしていないリモートユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob', host: 'example.com' }); const ws = await connectStream(alice, 'globalTimeline', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }); post(bob, { text: 'foo' }); })); it('ホーム投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); let fired = false; const ws = await connectStream(alice, 'globalTimeline', ({ type, body }) => { if (type == 'note') { fired = true; } }); // ホーム投稿 post(bob, { text: 'foo', visibility: 'home' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); }); describe('UserList Timeline', () => { it('リストに入れているユーザーの投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // リスト作成 const list = await request('/users/lists/create', { name: 'my list' }, alice).then(x => x.body); // Alice が Bob をリスイン await request('/users/lists/push', { listId: list.id, userId: bob.id }, alice); const ws = await connectStream(alice, 'userList', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); ws.close(); done(); } }, { listId: list.id }); post(bob, { text: 'foo' }); })); it('リストに入れていないユーザーの投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // リスト作成 const list = await request('/users/lists/create', { name: 'my list' }, alice).then(x => x.body); let fired = false; const ws = await connectStream(alice, 'userList', ({ type, body }) => { if (type == 'note') { fired = true; } }, { listId: list.id }); post(bob, { text: 'foo' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); // #4471 it('リストに入れているユーザーのダイレクト投稿が流れる', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // リスト作成 const list = await request('/users/lists/create', { name: 'my list' }, alice).then(x => x.body); // Alice が Bob をリスイン await request('/users/lists/push', { listId: list.id, userId: bob.id }, alice); const ws = await connectStream(alice, 'userList', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.userId, bob.id); assert.deepStrictEqual(body.text, 'foo'); ws.close(); done(); } }, { listId: list.id }); // Bob が Alice 宛てのダイレクト投稿 post(bob, { text: 'foo', visibility: 'specified', visibleUserIds: [alice.id] }); })); // #4335 it('リストに入れているがフォローはしてないユーザーのフォロワー宛て投稿は流れない', () => new Promise(async done => { const alice = await signup({ username: 'alice' }); const bob = await signup({ username: 'bob' }); // リスト作成 const list = await request('/users/lists/create', { name: 'my list' }, alice).then(x => x.body); // Alice が Bob をリスイン await request('/users/lists/push', { listId: list.id, userId: bob.id }, alice); let fired = false; const ws = await connectStream(alice, 'userList', ({ type, body }) => { if (type == 'note') { fired = true; } }, { listId: list.id }); // フォロワー宛て投稿 post(bob, { text: 'foo', visibility: 'followers' }); setTimeout(() => { assert.strictEqual(fired, false); ws.close(); done(); }, 3000); })); }); describe('Hashtag Timeline', () => { it('指定したハッシュタグの投稿が流れる', () => new Promise(async done => { const me = await signup(); const ws = await connectStream(me, 'hashtag', ({ type, body }) => { if (type == 'note') { assert.deepStrictEqual(body.text, '#foo'); ws.close(); done(); } }, { q: [ ['foo'] ] }); post(me, { text: '#foo' }); })); it('指定したハッシュタグの投稿が流れる (AND)', () => new Promise(async done => { const me = await signup(); let fooCount = 0; let barCount = 0; let fooBarCount = 0; const ws = await connectStream(me, 'hashtag', ({ type, body }) => { if (type == 'note') { if (body.text === '#foo') fooCount++; if (body.text === '#bar') barCount++; if (body.text === '#foo #bar') fooBarCount++; } }, { q: [ ['foo', 'bar'] ] }); post(me, { text: '#foo' }); post(me, { text: '#bar' }); post(me, { text: '#foo #bar' }); setTimeout(() => { assert.strictEqual(fooCount, 0); assert.strictEqual(barCount, 0); assert.strictEqual(fooBarCount, 1); ws.close(); done(); }, 3000); })); it('指定したハッシュタグの投稿が流れる (OR)', () => new Promise(async done => { const me = await signup(); let fooCount = 0; let barCount = 0; let fooBarCount = 0; let piyoCount = 0; const ws = await connectStream(me, 'hashtag', ({ type, body }) => { if (type == 'note') { if (body.text === '#foo') fooCount++; if (body.text === '#bar') barCount++; if (body.text === '#foo #bar') fooBarCount++; if (body.text === '#piyo') piyoCount++; } }, { q: [ ['foo'], ['bar'] ] }); post(me, { text: '#foo' }); post(me, { text: '#bar' }); post(me, { text: '#foo #bar' }); post(me, { text: '#piyo' }); setTimeout(() => { assert.strictEqual(fooCount, 1); assert.strictEqual(barCount, 1); assert.strictEqual(fooBarCount, 1); assert.strictEqual(piyoCount, 0); ws.close(); done(); }, 3000); })); it('指定したハッシュタグの投稿が流れる (AND + OR)', () => new Promise(async done => { const me = await signup(); let fooCount = 0; let barCount = 0; let fooBarCount = 0; let piyoCount = 0; let waaaCount = 0; const ws = await connectStream(me, 'hashtag', ({ type, body }) => { if (type == 'note') { if (body.text === '#foo') fooCount++; if (body.text === '#bar') barCount++; if (body.text === '#foo #bar') fooBarCount++; if (body.text === '#piyo') piyoCount++; if (body.text === '#waaa') waaaCount++; } }, { q: [ ['foo', 'bar'], ['piyo'] ] }); post(me, { text: '#foo' }); post(me, { text: '#bar' }); post(me, { text: '#foo #bar' }); post(me, { text: '#piyo' }); post(me, { text: '#waaa' }); setTimeout(() => { assert.strictEqual(fooCount, 0); assert.strictEqual(barCount, 0); assert.strictEqual(fooBarCount, 1); assert.strictEqual(piyoCount, 1); assert.strictEqual(waaaCount, 0); ws.close(); done(); }, 3000); })); }); });
the_stack
import { ConditionalTransferTypes, EventNames, IConnextClient, PublicParams, EventPayloads, PrivateKey, Address, GRAPH_BATCHED_SWAP_CONVERSION, GraphReceipt, PublicResults, } from "@connext/types"; import { getTestVerifyingContract, getTestGraphReceiptToSign, getRandomPrivateKey, signGraphReceiptMessage, getChainId, signGraphConsumerMessage, getRandomBytes32, } from "@connext/utils"; import { providers, constants, utils, BigNumber } from "ethers"; import { AssetOptions, createClient, ETH_AMOUNT_SM, ethProviderUrl, expect, fundChannel, getTestLoggers, TOKEN_AMOUNT, } from "../util"; const { AddressZero, One } = constants; const { hexlify, randomBytes } = utils; const createBatchedTransfer = async ( senderClient: IConnextClient, receiverClient: IConnextClient, transfer: AssetOptions, paymentId: string = getRandomBytes32(), ): Promise<{ paymentId: string; chainId: number; verifyingContract: string; receipt: GraphReceipt; transferRes: PublicResults.GraphBatchedTransfer; }> => { const chainId = senderClient.chainId; const verifyingContract = getTestVerifyingContract(); const receipt = getTestGraphReceiptToSign(); const transferPromise = receiverClient.waitFor( EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, 10_000, ); const transferRes = await senderClient.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphBatchedTransfer, paymentId, consumerSigner: senderClient.signerAddress, chainId, verifyingContract, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: receiverClient.publicIdentifier, meta: { foo: "bar" }, } as PublicParams.GraphBatchedTransfer); const installed = await transferPromise; expect(installed).deep.contain({ amount: transfer.amount, appIdentityHash: installed.appIdentityHash, assetId: transfer.assetId, type: ConditionalTransferTypes.GraphBatchedTransfer, paymentId, sender: senderClient.publicIdentifier, transferMeta: { consumerSigner: senderClient.signerAddress, attestationSigner: receiverClient.signerAddress, chainId, verifyingContract, subgraphDeploymentID: receipt.subgraphDeploymentID, swapRate: One.mul(GRAPH_BATCHED_SWAP_CONVERSION), requestCID: undefined, }, meta: { foo: "bar", recipient: receiverClient.publicIdentifier, sender: senderClient.publicIdentifier, paymentId, senderAssetId: transfer.assetId, }, } as EventPayloads.GraphBatchedTransferCreated); const { [senderClient.signerAddress]: clientAPostTransferBal, } = await senderClient.getFreeBalance(transfer.assetId); expect(clientAPostTransferBal).to.eq(0); return { paymentId, chainId, verifyingContract, receipt, transferRes }; }; const resolveBatchedTransfer = async ( senderClient: IConnextClient, receiverClient: IConnextClient, transfer: AssetOptions, totalPaid: BigNumber, paymentId: string, privateKeyConsumer: string, privateKeyIndexer: string, ) => { const chainId = senderClient.chainId; const verifyingContract = getTestVerifyingContract(); const receipt = getTestGraphReceiptToSign(); const attestationSignature = await signGraphReceiptMessage( receipt, senderClient.chainId, verifyingContract, privateKeyIndexer, ); const consumerSignature = await signGraphConsumerMessage( receipt, chainId, verifyingContract, totalPaid, paymentId, privateKeyConsumer, ); const unlockedPromise = senderClient.waitFor( EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, 10_000, ); const uninstalledPromise = senderClient.waitFor(EventNames.UNINSTALL_EVENT, 10_000); await receiverClient.resolveCondition({ conditionType: ConditionalTransferTypes.GraphBatchedTransfer, totalPaid, paymentId, responseCID: receipt.responseCID, requestCID: receipt.requestCID, consumerSignature, attestationSignature, } as PublicParams.ResolveGraphBatchedTransfer); const eventData = await unlockedPromise; await uninstalledPromise; expect(eventData).to.deep.contain({ amount: transfer.amount, assetId: transfer.assetId, type: ConditionalTransferTypes.GraphBatchedTransfer, paymentId, sender: senderClient.publicIdentifier, transferMeta: { totalPaid, requestCID: receipt.requestCID, responseCID: receipt.responseCID, consumerSignature, attestationSignature, }, meta: { foo: "bar", recipient: receiverClient.publicIdentifier, sender: senderClient.publicIdentifier, paymentId, senderAssetId: transfer.assetId, }, } as EventPayloads.GraphBatchedTransferUnlocked); const { [senderClient.signerAddress]: senderClientPostReclaimBal, } = await senderClient.getFreeBalance(transfer.assetId); const { [receiverClient.signerAddress]: receiverClientPostTransferBal, } = await receiverClient.getFreeBalance(transfer.assetId); expect(senderClientPostReclaimBal).to.eq(transfer.amount.sub(totalPaid)); expect(receiverClientPostTransferBal).to.eq(totalPaid); }; const name = "Graph Batched Transfers"; const { timeElapsed } = getTestLoggers(name); describe(name, () => { let clientA: IConnextClient; let clientB: IConnextClient; let privateKeyA: PrivateKey; let privateKeyB: PrivateKey; let provider: providers.JsonRpcProvider; let start: number; let tokenAddress: Address; before(async () => { start = Date.now(); provider = new providers.JsonRpcProvider(ethProviderUrl, await getChainId(ethProviderUrl)); const currBlock = await provider.getBlockNumber(); // the node uses a `TIMEOUT_BUFFER` on recipient of 100 blocks // so make sure the current block const TIMEOUT_BUFFER = 100; if (currBlock > TIMEOUT_BUFFER) { // no adjustment needed, return return; } for (let index = currBlock; index <= TIMEOUT_BUFFER + 1; index++) { await provider.send("evm_mine", []); } timeElapsed("beforeEach complete", start); }); beforeEach(async () => { privateKeyA = getRandomPrivateKey(); clientA = await createClient({ signer: privateKeyA, id: "A" }); privateKeyB = getRandomPrivateKey(); clientB = await createClient({ signer: privateKeyB, id: "B" }); tokenAddress = clientA.config.contractAddresses[clientA.chainId].Token!; }); afterEach(async () => { await clientA.off(); await clientB.off(); }); it("clientA signed transfers eth to clientB through node, clientB is online", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { paymentId } = await createBatchedTransfer(clientA, clientB, transfer); const totalPaid = transfer.amount.div(3); await resolveBatchedTransfer( clientA, clientB, transfer, totalPaid, paymentId, privateKeyA, privateKeyB, ); }); it("clientA signed transfers tokens to clientB through node", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { paymentId } = await createBatchedTransfer(clientA, clientB, transfer); const totalPaid = transfer.amount.div(3); await resolveBatchedTransfer( clientA, clientB, transfer, totalPaid, paymentId, privateKeyA, privateKeyB, ); }); // TODO: figure out getters it("cannot resolve a signed transfer if attestation signature is wrong", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { paymentId, receipt, chainId, verifyingContract } = await createBatchedTransfer( clientA, clientB, transfer, ); const totalPaid = transfer.amount.div(3); const consumerSignature = await signGraphConsumerMessage( receipt, chainId, verifyingContract, totalPaid, paymentId, privateKeyA, ); const badSig = hexlify(randomBytes(65)); await expect( clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphBatchedTransfer, totalPaid, paymentId, requestCID: receipt.requestCID, responseCID: receipt.responseCID, consumerSignature, attestationSignature: badSig, } as PublicParams.ResolveGraphBatchedTransfer), ).to.eventually.be.rejectedWith(/invalid signature/); }); it("cannot resolve a signed transfer if attestation signature is wrong", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { paymentId, receipt, chainId, verifyingContract } = await createBatchedTransfer( clientA, clientB, transfer, ); const totalPaid = transfer.amount.div(3); const attestationSignature = await signGraphReceiptMessage( receipt, chainId, verifyingContract, privateKeyB, ); const badSig = hexlify(randomBytes(65)); await expect( clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphBatchedTransfer, totalPaid, paymentId, requestCID: receipt.requestCID, responseCID: receipt.responseCID, attestationSignature, consumerSignature: badSig, } as PublicParams.ResolveGraphBatchedTransfer), ).to.eventually.be.rejectedWith(/invalid signature/); }); it("if sender uninstalls, node should force uninstall receiver first", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const receiverPromise = clientB.waitFor(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, 10_000); const { transferRes } = await createBatchedTransfer(clientA, clientB, transfer); const receiverRes = (await receiverPromise) as EventPayloads.GraphBatchedTransferCreated; clientA.uninstallApp(transferRes.appIdentityHash); const winner = await Promise.race([ new Promise<EventPayloads.Uninstall>((res) => { clientA.once( EventNames.UNINSTALL_EVENT, res, (data) => data.appIdentityHash === (transferRes as any).appIdentityHash, ); }), new Promise<EventPayloads.Uninstall>((res) => { clientB.once(EventNames.UNINSTALL_EVENT, res); }), ]); expect(winner.appIdentityHash).to.be.eq(receiverRes.appIdentityHash); }); it("sender cannot uninstall before receiver", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { transferRes } = await createBatchedTransfer(clientA, clientB, transfer); // disconnect so receiver cannot uninstall await clientB.off(); await clientB.off(); await expect(clientA.uninstallApp(transferRes.appIdentityHash)).to.eventually.be.rejected; }); it("sender cannot uninstall unfinalized app when receiver is finalized", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const { paymentId, chainId, verifyingContract, receipt, transferRes, } = await createBatchedTransfer(clientA, clientB, transfer); const totalPaid = transfer.amount.div(3); // disconnect so sender cannot unlock await clientA.off(); const attestationSignature = await signGraphReceiptMessage( receipt, clientA.chainId, verifyingContract, privateKeyB, ); const consumerSignature = await signGraphConsumerMessage( receipt, chainId, verifyingContract, totalPaid, paymentId, privateKeyA, ); await Promise.all([ new Promise((res) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, res); }), clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphBatchedTransfer, totalPaid, paymentId, responseCID: receipt.responseCID, requestCID: receipt.requestCID, consumerSignature, attestationSignature, } as PublicParams.ResolveGraphBatchedTransfer), ]); clientA.messaging.connect(); await expect(clientA.uninstallApp(transferRes.appIdentityHash)).to.eventually.be.rejected; }); });
the_stack
import { SourceMapConsumer } from "source-map"; import * as tstl from "../../../src"; import { LuaTarget, transpileString } from "../../../src"; import { couldNotResolveRequire } from "../../../src/transpilation/diagnostics"; import * as util from "../../util"; import { lineAndColumnOf } from "./utils"; test.each([ { code: ` const abc = "foo"; const def = "bar"; const xyz = "baz"; `, assertPatterns: [ { luaPattern: "abc", typeScriptPattern: "abc" }, { luaPattern: "def", typeScriptPattern: "def" }, { luaPattern: "xyz", typeScriptPattern: "xyz" }, { luaPattern: '"foo"', typeScriptPattern: '"foo"' }, { luaPattern: '"bar"', typeScriptPattern: '"bar"' }, { luaPattern: '"baz"', typeScriptPattern: '"baz"' }, ], }, { code: ` function abc() { return def(); } function def() { return "foo"; } `, assertPatterns: [ { luaPattern: "function abc(", typeScriptPattern: "function abc() {" }, { luaPattern: "function def(", typeScriptPattern: "function def() {" }, { luaPattern: "return def(", typeScriptPattern: "return def(" }, { luaPattern: "end", typeScriptPattern: "function def() {" }, ], }, { code: ` const enum abc { foo = 2, bar = 4 }; const xyz = abc.foo; `, assertPatterns: [ { luaPattern: "xyz", typeScriptPattern: "xyz" }, { luaPattern: "2", typeScriptPattern: "abc.foo" }, ], }, { code: ` // @ts-ignore import { Foo } from "foo"; Foo; `, assertPatterns: [ { luaPattern: 'require("foo")', typeScriptPattern: '"foo"' }, { luaPattern: "Foo", typeScriptPattern: "Foo" }, ], }, { code: ` // @ts-ignore import * as Foo from "foo"; Foo; `, assertPatterns: [ { luaPattern: 'require("foo")', typeScriptPattern: '"foo"' }, { luaPattern: "Foo", typeScriptPattern: "Foo" }, ], }, { code: ` // @ts-ignore class Bar extends Foo { constructor() { super(); } } `, assertPatterns: [ { luaPattern: "Bar = __TS__Class()", typeScriptPattern: "class Bar" }, { luaPattern: "Bar.name =", typeScriptPattern: "class Bar" }, { luaPattern: "__TS__ClassExtends(", typeScriptPattern: "extends" }, // find use of function, not import { luaPattern: "Foo", typeScriptPattern: "Foo" }, { luaPattern: "function Bar.prototype.____constructor", typeScriptPattern: "constructor" }, ], }, { code: ` class Foo { } `, assertPatterns: [{ luaPattern: "function Foo.prototype.____constructor", typeScriptPattern: "class Foo" }], }, { code: ` class Foo { bar = "baz"; } `, assertPatterns: [{ luaPattern: "function Foo.prototype.____constructor", typeScriptPattern: "class Foo" }], }, { code: ` declare const arr: string[]; for (const element of arr) {} `, assertPatterns: [ { luaPattern: "arr", typeScriptPattern: "arr)" }, { luaPattern: "element", typeScriptPattern: "element" }, ], }, { code: ` declare function getArr(this: void): string[]; for (const element of getArr()) {} `, assertPatterns: [ { luaPattern: "for", typeScriptPattern: "for" }, { luaPattern: "getArr()", typeScriptPattern: "getArr()" }, { luaPattern: "element", typeScriptPattern: "element" }, ], }, { code: ` declare const arr: string[] for (let i = 0; i < arr.length; ++i) {} `, assertPatterns: [ { luaPattern: "i = 0", typeScriptPattern: "i = 0" }, { luaPattern: "i < #arr", typeScriptPattern: "i < arr.length" }, { luaPattern: "i + 1", typeScriptPattern: "++i" }, ], }, ])("Source map has correct mapping (%p)", async ({ code, assertPatterns }) => { const file = util .testModule(code) .ignoreDiagnostics([couldNotResolveRequire.code]) .expectToHaveNoDiagnostics() .getMainLuaFileResult(); const consumer = await new SourceMapConsumer(file.luaSourceMap); for (const { luaPattern, typeScriptPattern } of assertPatterns) { const luaPosition = lineAndColumnOf(file.lua, luaPattern); const mappedPosition = consumer.originalPositionFor(luaPosition); const typescriptPosition = lineAndColumnOf(code, typeScriptPattern); expect(mappedPosition).toMatchObject(typescriptPosition); } }); test.each([ { fileName: "/proj/foo.ts", config: {}, expectedSourcePath: "foo.ts", // ts and lua will be emitted to same directory }, { fileName: "/proj/src/foo.ts", config: { outDir: "/proj/dst", }, expectedSourcePath: "../src/foo.ts", // path from proj/dst outDir to proj/src/foo.ts }, { fileName: "/proj/src/foo.ts", config: { rootDir: "/proj/src", outDir: "/proj/dst" }, expectedSourcePath: "../src/foo.ts", // path from proj/dst outDir to proj/src/foo.ts }, { fileName: "/proj/src/sub/foo.ts", config: { rootDir: "/proj/src", outDir: "/proj/dst" }, expectedSourcePath: "../../src/sub/foo.ts", // path from proj/dst/sub outDir to proj/src/sub/foo.ts }, { fileName: "/proj/src/sub/main.ts", config: { rootDir: "/proj/src", outDir: "/proj/dst", sourceRoot: "bin/binsub/binsubsub" }, expectedSourcePath: "../../src/sub/main.ts", // path from proj/dst/sub outDir to proj/src/sub/foo.ts fullSource: "bin/src/sub/main.ts", }, ])("Source map has correct sources (%p)", async ({ fileName, config, fullSource, expectedSourcePath }) => { const file = util.testModule` const foo = "foo" ` .setOptions(config) .setMainFileName(fileName) .getMainLuaFileResult(); const sourceMap = JSON.parse(file.luaSourceMap); expect(sourceMap.sources).toHaveLength(1); expect(sourceMap.sources[0]).toBe(expectedSourcePath); const consumer = await new SourceMapConsumer(file.luaSourceMap); expect(consumer.sources).toHaveLength(1); expect(consumer.sources[0]).toBe(fullSource ?? expectedSourcePath); }); test.each([ { configSourceRoot: undefined, mapSourceRoot: "" }, { configSourceRoot: "src", mapSourceRoot: "src/" }, { configSourceRoot: "src/", mapSourceRoot: "src/" }, { configSourceRoot: "src\\", mapSourceRoot: "src/" }, ])("Source map has correct source root (%p)", ({ configSourceRoot, mapSourceRoot }) => { const file = util.testModule` const foo = "foo" ` .setOptions({ sourceMap: true, sourceRoot: configSourceRoot }) .expectToHaveNoDiagnostics() .getMainLuaFileResult(); const sourceMap = JSON.parse(file.luaSourceMap); expect(sourceMap.sourceRoot).toBe(mapSourceRoot); }); test.each([ { code: 'const type = "foobar";', name: "type" }, { code: 'const and = "foobar";', name: "and" }, { code: 'const $$$ = "foobar";', name: "$$$" }, { code: "const foo = { bar() { this; } };", name: "this" }, { code: "function foo($$$: unknown) {}", name: "$$$" }, { code: "class $$$ {}", name: "$$$" }, { code: 'namespace $$$ { const foo = "bar"; }', name: "$$$" }, ])("Source map has correct name mappings (%p)", async ({ code, name }) => { const file = util.testModule(code).expectToHaveNoDiagnostics().getMainLuaFileResult(); const consumer = await new SourceMapConsumer(file.luaSourceMap); const typescriptPosition = lineAndColumnOf(code, name); let mappedName: string | undefined; consumer.eachMapping(mapping => { if (mapping.originalLine === typescriptPosition.line && mapping.originalColumn === typescriptPosition.column) { mappedName = mapping.name; } }); expect(mappedName).toBe(name); }); test("sourceMapTraceback saves sourcemap in _G", () => { const code = ` function abc() { return "foo"; } return (globalThis as any).__TS__sourcemap; `; const builder = util .testFunction(code) .setOptions({ sourceMapTraceback: true, luaLibImport: tstl.LuaLibImportKind.Inline }); const sourceMap = builder.getLuaExecutionResult(); const transpiledLua = builder.getMainLuaCodeChunk(); expect(sourceMap).toEqual(expect.any(Object)); const sourceMapFiles = Object.keys(sourceMap); expect(sourceMapFiles).toHaveLength(1); const mainSourceMap = sourceMap[sourceMapFiles[0]]; const assertPatterns = [ { luaPattern: "function abc(", typeScriptPattern: "function abc() {" }, { luaPattern: 'return "foo"', typeScriptPattern: 'return "foo"' }, ]; for (const { luaPattern, typeScriptPattern } of assertPatterns) { const luaPosition = lineAndColumnOf(transpiledLua, luaPattern); const mappedLine = mainSourceMap[luaPosition.line.toString()]; const typescriptPosition = lineAndColumnOf(code, typeScriptPattern); expect(mappedLine).toEqual(typescriptPosition.line); } }); test("sourceMapTraceback gives traceback", () => { const builder = util.testFunction` return (debug.traceback as (this: void)=>string)(); `.setOptions({ sourceMapTraceback: true }); const traceback = builder.getLuaExecutionResult(); expect(traceback).toEqual(expect.any(String)); }); test("inline sourceMapTraceback gives traceback", () => { const builder = util.testFunction` return (debug.traceback as (this: void)=>string)(); `.setOptions({ sourceMapTraceback: true, luaLibImport: tstl.LuaLibImportKind.Inline }); const traceback = builder.getLuaExecutionResult(); expect(traceback).toEqual(expect.any(String)); }); test("Inline sourcemaps", () => { const code = ` function abc() { return def(); } function def() { return "foo"; } return abc(); `; const file = util .testFunction(code) .setOptions({ inlineSourceMap: true }) // We can't disable 'sourceMap' option because it's used for comparison .disableSemanticCheck() // TS5053: Option 'sourceMap' cannot be specified with option 'inlineSourceMap'. .expectToMatchJsResult() .getMainLuaFileResult(); const [, inlineSourceMapMatch] = file.lua.match(/--# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)/) ?? []; const inlineSourceMap = Buffer.from(inlineSourceMapMatch, "base64").toString(); expect(inlineSourceMap).toBe(file.luaSourceMap); }); test("loadstring sourceMapTraceback gives traceback", () => { const loadStrCode = transpileString( `function bar() { const trace = (debug.traceback as (this: void)=>string)(); return trace; } return bar();`, { sourceMapTraceback: true, luaTarget: LuaTarget.Lua51 } ).file?.lua; const builder = util.testModule` const luaCode = \`${loadStrCode}\`; return loadstring(luaCode, "foo.lua")(); ` .setTsHeader("declare function loadstring(this: void, string: string, chunkname: string): () => unknown") .setOptions({ sourceMapTraceback: true, luaTarget: LuaTarget.Lua51 }); const traceback = builder.getLuaExecutionResult(); expect(traceback).toContain("foo.ts"); });
the_stack
import { Locale } from '../i18n'; import { strings as _ } from '../strings'; const locale: Locale = { locale: "zh", // DO NOT TRANSLATE enName: "Chinese", // DO NOT TRANSLATE name: "中国", strings: { [_.addCtrlTitle]: "打开", [_.aggregatedTableName]: "源自多张表格", [_.AnalyzeModel]: "分析模型", [_.analyzeModelSummary]: `您的数据集大小是 <strong>{size:bytes}</strong> 并包含 <strong>{count}</strong> 列`, [_.analyzeModelSummary2]: `, 其中<span class="text-highlight"><strong>{count}</strong> 列在模型中未被引用</span>`, [_.appName]: "Bravo for Power BI", //DO NOT TRANSLATE [_.appUpdateAvailable]: "有可用的新版本: {version}", [_.appUpdateChangelog]: "更新日志", [_.appUpdateDownload]: "下载", [_.appUpdateViewDetails]: "查看详情", [_.appUpToDate]: "Bravo 已是最新版", [_.appVersion]: "版本 {version}", [_.backupReminder]: "在继续下一步之前,请务必保存您当前报告的备份 - <b>部分更改操作之后有可能无法撤销</b>.", [_.BestPractices]: "最佳实践", [_.canceled]: "已取消", [_.changeStatusAdded]: "A", [_.changeStatusAddedTitle]: "已添加", [_.changeStatusDeleted]: "D", [_.changeStatusDeletedTitle]: "已删除", [_.changeStatusModified]: "M", [_.changeStatusModifiedTitle]: "已修改", [_.checking]: "检查...", [_.clearCtrlTitle]: "清空", [_.closeCtrlTitle]: "关闭", [_.closeOtherTabs]: "关闭其他", [_.closeTab]: "关闭", [_.collapseAllCtrlTitle]: "折叠全部", [_.columnExportedCompleted]: "表格已成功导出。", [_.columnExportedFailed]: "由于未知错误,表格未能成功导出。", [_.columnExportedTruncated]: "由于行数超过了允许的最大值,表格被截断。", [_.columnMeasureFormatted]: "该度量值已经是标准格式", [_.columnMeasureNotFormattedTooltip]: "该度量值不是标准格式", [_.columnMeasureWithError]: "该度量值包含错误", [_.columnUnreferencedExplanation]: `<span class="text-highlight">未引用的列</span> 通常可以从模型中移除以优化性能。在移除之前, 请确保您没有在任何报告页面中使用这些列, 这一点Bravo无法为您做出判断。`, [_.columnUnreferencedTooltip]: "在当前模型中没有对该列的引用", [_.confirmTabCloseMessage]: "您尚未保存对本文件的修改.<br>您确定要关闭吗?", [_.connectBrowse]: "浏览", [_.connectDatasetsTableEndorsementCol]: "认可", [_.connectDatasetsTableNameCol]: "名称", [_.connectDatasetsTableOwnerCol]: "管理员", [_.connectDatasetsTableWorkspaceCol]: "工作区", [_.connectDialogAttachPBIMenu]: "powerbi.com 数据集", [_.connectDialogConnectPBIMenu]: "运行的Power BI Desktop报告", [_.connectDialogOpenVPXMenu]: "VPAX 文件", [_.connectDialogTitle]: "打开", [_.connectDragFile]: "拖拽一个VPAX文件到这里<br>或者浏览您的电脑", [_.connectNoReports]: "当前没有正在运行的Power BI Desktop报告.<br>请用Power BI Desktop打开一个报告并等待它出现在本窗口。", [_.copiedErrorDetails]: "已复制", [_.copy]: "复制", [_.copyErrorDetails]: "复制错误", [_.copyFormulaCtrlTitle]: "复制标准格式的度量值", [_.copyMessage]: "复制消息", [_.copyright]: "版权所有", [_.createIssue]: "报告问题", [_.cut]: "剪切", [_.dataUsageLink]: "如何使用您的数据?", [_.dataUsageMessage]: `为了对您的代码进行标准格式化, Bravo 会将数据集中的度量值通过一个安全的连接发送给由SQLBI管理的DAX Formatter服务接口.<p><strong>该服务不会在任何地方存储您的数据和代码。</strong></p><p>出于数据统计目的,有些信息可能会被收集,比如:最常用的DAX函数,代码复杂程度或者平均代码长度等。</p>`, [_.dataUsageTitle]: "如何使用您的数据?", [_.DaxFormatter]: "DAX标准格式化", [_.daxFormatterAgreement]: "Bravo需要将您的度量值发送到DAX Formatter服务接口以进行标准格式化", [_.daxFormatterAnalyzeConfirm]: "出于分析目的, Bravo需要将所有度量值发送给DAX Formatter服务接口。您确定继续吗?", [_.daxFormatterAutoPreviewOption]: "自动预览", [_.daxFormatterFormat]: "标准格式化选中的度量值", [_.daxFormatterFormatDisabled]: "标准格式化 (不支持)", [_.daxFormatterFormattedCode]: "标准格式 (预览)", [_.daxFormatterOriginalCode]: "当前格式", [_.daxFormatterPreviewAllButton]: "预览所有度量值", [_.daxFormatterPreviewButton]: "预览", [_.daxFormatterPreviewDesc]: "为生成标准格式预览, Bravo需要将该度量值发送给DAX Formatter服务接口。", [_.daxFormatterSuccessSceneMessage]: "恭喜, <strong>{count} 个度量值</strong> 已成功标准格式化。", [_.daxFormatterSummary]: `您的数据集包含 {count} 个度量值: <span class="text-error"><strong>{errors:number}</strong> 个存在错误</strong></span>, <span class="text-highlight"><strong>{formattable:number}</strong> 个需要格式优化</span>, <strong>{analyzable:number}</strong> 个待分析 (<span class="link manual-analyze">现在分析</span>).`, [_.daxFormatterSummaryNoAnalysis]: `您的数据集包含 <strong>{count}</strong> 个度量值: <span class="text-error"><strong>{errors:number}</strong> 个存在错误</strong></span> 以及 <span class="text-highlight"><strong>{formattable:number}</strong> 个需要格式优化</span>`, [_.defaultTabName]: "未命名", [_.dialogCancel]: "取消", [_.dialogOK]: "确定", [_.dialogOpen]: "打开", [_.docLimited]: "受限制的", [_.docLimitedTooltip]: "本文件部分功能不能完全使用。", [_.doneCtrlTitle]: "完成", [_.emailAddress]: "电子邮件", [_.emailAddressPlaceholder]: "输入您的电子邮件", [_.error]: "错误", [_.errorAborted]: "操作中止", [_.errorAnalysisServicesConnectionFailed]: "数据库与Bravo连接错误", [_.errorCheckForUpdates]: "不能查看更新 - 无法连接远程数据库", [_.errorConnectionUnsupported]: "不支持目标资源的连接", [_.errorDatasetConnectionUnknown]: "未指定连接", [_.errorDatasetsEmptyListing]: "未找到打开的报告", [_.errorDatasetsListing]: "无法获取Power BI Service的数据集列表", [_.errorExportDataFileError]: "导出数据时出现错误。请稍后再试。", [_.errorGetEnvironments]: "请输入有效的Power BI帐户。", [_.errorManageDateTemplateError]: "DAX模板引擎启动异常", [_.errorNetworkError]: "您没有连接到网络", [_.errorNone]: "未知错误", [_.errorNotAuthorized]: "您没有权限查看指定的资源", [_.errorNotConnected]: "您没有连接到Power BI, 请登录后再试", [_.errorNotFound]: "不能连接到指定资源", [_.errorReportConnectionUnknown]: "无效连接", [_.errorReportConnectionUnsupportedAnalysisServicesCompatibilityMode]: "Power BI Desktop Analysis Services 实例的兼容模式不是 PowerBI.", [_.errorReportConnectionUnsupportedAnalysisServicesConnectionNotFound]: "未找到Power BI Desktop Analysis Services的TCP连接", [_.errorReportConnectionUnsupportedAnalysisServicesProcessNotFound]: "未找到Power BI Desktop Analysis Services 实例的进程", [_.errorReportConnectionUnsupportedConnectionException]: "Power BI Desktop Analysis Services 实例连接异常", [_.errorReportConnectionUnsupportedDatabaseCollectionEmpty]: "Power BI Desktop Analysis Services 实例不包含任何数据库。 请尝试通过Power BI Desktop的 外部工具 选项卡下的Bravo图标连接到报告。", [_.errorReportConnectionUnsupportedDatabaseCollectionUnexpectedCount]: "Power BI Desktop Analysis Services 实例包含多个数据库, 而我们只需要0个或1个。", [_.errorReportConnectionUnsupportedProcessNotReady]: "Power BI Desktop进程正在打开, 或者Analysis Services实例尚未准备好。", [_.errorReportsEmptyListing]: "没找到未打开的报告", [_.errorRetry]: "再试一次", [_.errorSignInMsalExceptionOccurred]: "登录请求出现异常", [_.errorSignInMsalTimeoutExpired]: "操作超时, 登录请求被取消", [_.errorTimeout]: "请求超时", [_.errorTitle]: "Whoops...", [_.errorTOMDatabaseDatabaseNotFound]: "该数据库不存在, 或者用户没有管理员访问权限", [_.errorTOMDatabaseUpdateConflictMeasure]: "更新请求与目标资源的当前状态有冲突", [_.errorTOMDatabaseUpdateErrorMeasure]: "更新请求失败, 一个或多个度量值存在错误", [_.errorTOMDatabaseUpdateFailed]: "尝试将本地模型修改保存到数据库服务器时, 数据库更新失败", [_.errorTryingToUpdateMeasuresWithErrors]: `更新请求失败, 因为以下度量值包含错误: <br><strong>{measures}</strong>`, [_.errorUnhandled]: "未经处理的错误 - 请提交该错误并提供Trace ID(如果有Trace ID的话)", [_.errorUnspecified]: "未知错误", [_.errorUserSettingsSaveError]: "无法保存设置", [_.errorVpaxFileExportError]: "在导出VPAX文件时发生了一个错误。", [_.errorVpaxFileImportError]: "在导入VPAX文件时发生错误。", [_.expandAllCtrlTitle]: "扩展全部", [_.ExportData]: "导出数据", [_.exportDataCSVCustomDelimiter]: "自定义分隔符", [_.exportDataCSVDelimiter]: "分隔符", [_.exportDataCSVDelimiterComma]: "逗号", [_.exportDataCSVDelimiterDesc]: `选择字符作为每个字段的分隔符. <em>自动</em> 使用您系统设置的默认字符`, [_.exportDataCSVDelimiterOther]: "其他...", [_.exportDataCSVDelimiterPlaceholder]: "字符", [_.exportDataCSVDelimiterSemicolon]: "分号", [_.exportDataCSVDelimiterSystem]: "自动", [_.exportDataCSVDelimiterTab]: "制表符", [_.exportDataCSVEncoding]: "编码格式", [_.exportDataCSVEncodingDesc]: "", [_.exportDataCSVFolder]: "保存在子文件夹中", [_.exportDataCSVFolderDesc]: "将生成的CSV文件保存在子文件夹中。", [_.exportDataCSVQuote]: "用引号包含字符串", [_.exportDataCSVQuoteDesc]: "确保每一个字符串都包含在双引号中", [_.exportDataExcelCreateExportSummary]: "导出记录日志", [_.exportDataExcelCreateExportSummaryDesc]: "在导出文件中添加一页记录所有导出明细的日志", [_.exportDataExport]: "导出选中的表", [_.exportDataExportAs]: "导出为", [_.exportDataExportAsDesc]: "", [_.exportDataExporting]: "正在导出 {table}...", [_.exportDataExportingDone]: "完成!", [_.exportDataNoColumns]: "这个表不能被导出,因为它没有包含任何列。", [_.exportDataNotQueryable]: "这个表不能被导出,因为它包含一个或多个具有无效表达式的计算列或需要重新计算的列。", [_.exportDataOpenFile]: "打开导出文件", [_.exportDataOpenFolder]: "打开导出文件所在的文件夹", [_.exportDataOptions]: "导出选项", [_.exportDataStartExporting]: "初始化...", [_.exportDataSuccessSceneMessage]: "<strong>{count}/{total} </strong> 张表成功导出", [_.exportDataSummary]: "您的数据集包含 <strong>{count} </strong> 张可以导出的表", [_.exportDataTypeCSV]: "CSV (逗号分隔)", [_.exportDataTypeXLSX]: "Excel 工作簿", [_.failed]: "失败", [_.filterMeasuresWithErrorsCtrlTitle]: "只显示尚未格式化或者包含错误的度量值", [_.filterUnrefCtrlTitle]: "只显示未被引用的列", [_.formattingMeasures]: "正在标准格式化您的度量值...", [_.goBackCtrlTitle]: "取消并后退", [_.groupByTableCtrlTitle]: "以表格名分组", [_.helpConnectVideo]: "如何连接", [_.helpCtrlTitle]: "帮助", [_.hideUnsupportedCtrlTitle]: "仅支持", // To Do: double check [_.less]: "更少",// To Do: double check [_.license]: "Released under MIT license.", // To Do: double check [_.loading]: "加载...", [_.ManageDates]: "管理日期表", [_.manageDatesApplyCtrlTitle]: "应用更改", [_.manageDatesAuto]: "自动", [_.manageDatesAutoScan]: "自动扫描", [_.manageDatesAutoScanActiveRelationships]: "活动的关系", [_.manageDatesAutoScanDesc]: "设置 <em>全局</em> 扫描数据集中所有包含日期的列. 设置 <em>选择列...</em> 选取要扫描的日期列. 设置 <em>活动的关系</em> 和 <em>非活动的关系</em> 仅扫描通过关系关联的日期列", [_.manageDatesAutoScanDisabled]: "禁用", [_.manageDatesAutoScanFirstYear]: "起始年份", [_.manageDatesAutoScanFirstYearDesc]: "", [_.manageDatesAutoScanFull]: "全局", [_.manageDatesAutoScanInactiveRelationships]: "非活动的关系", [_.manageDatesAutoScanLastYear]: "最终年份", [_.manageDatesAutoScanLastYearDesc]: "", [_.manageDatesAutoScanSelectedTablesColumns]: "选择列...", [_.manageDatesBrowserPlaceholder]: "没有要更改的项目", [_.manageDatesCalendarDesc]: "选择一个日历模板来应用于这个模型。Bravo将创建或更新所需的日期表, 同时保持现有关系不变。", [_.manageDatesCalendarTemplateName]: "日历模板", [_.manageDatesCalendarTemplateNameDesc]: "选择 <em>月份模板</em>生成月份维度细分日历表. 选择 <em>周模板</em> 生成 445-454-544-ISO 标准日历表. 选择 <em>自定义</em> 生成可灵活自定义时间跨度的日历表.", [_.manageDatesCreatingTables]: "更新模型...", [_.manageDatesDatesDesc]: "设置您模型中日期的格式与区域", [_.manageDatesDatesTableDesc]: "您可以在报告中使用这张日期表", [_.manageDatesDatesTableName]: "日期表", [_.manageDatesDatesTableReferenceDesc]: "这是一张隐藏表, 包含生成日期表的所有DAX函数代码", [_.manageDatesDatesTableReferenceName]: "日期表定义", [_.manageDatesHolidaysDesc]: "在您的模型中添加假期表. Bravo会创建或更新所需表格, 并保持现有关系不变", [_.manageDatesHolidaysEnabledDesc]: "在您的模型中添加假期表", [_.manageDatesHolidaysEnabledName]: "假期", [_.manageDatesHolidaysTableDefinitionDesc]: "这是一张隐藏表, 包含生成假期表的所有DAX函数代码", [_.manageDatesHolidaysTableDefinitionName]: "假期定义表", [_.manageDatesHolidaysTableDesc]: "这是您可以在报告中使用的假期表", [_.manageDatesHolidaysTableName]: "假期表", [_.manageDatesIntervalDesc]: "为您的模型选择一个时间区间", [_.manageDatesISOCountryDesc]: "", [_.manageDatesISOCountryName]: "特定国家的假期", [_.manageDatesISOCustomFormatDesc]: "选择一个IETF BCP语言标记来定义区域格式, 例如: en-US", [_.manageDatesISOCustomFormatName]: "自定义格式", [_.manageDatesISOFormatDesc]: "选择一个日期的区域格式", [_.manageDatesISOFormatName]: "区域格式", [_.manageDatesISOFormatOther]: "其他...", [_.manageDatesISOFormatOtherPlaceholder]: "区域", [_.manageDatesMenuCalendar]: "日历", [_.manageDatesMenuDates]: "日期", [_.manageDatesMenuHolidays]: "假期", [_.manageDatesMenuInterval]: "时间区间", [_.manageDatesMenuPreviewCode]: "表达式", [_.manageDatesMenuPreviewModel]: "模型更改", [_.manageDatesMenuPreviewTable]: "示例数据", [_.manageDatesMenuPreviewTreeDate]: "日期", [_.manageDatesMenuPreviewTreeDateHolidays]: "日期与假期", [_.manageDatesMenuPreviewTreeTimeIntelligence]: "时间智能", [_.manageDatesMenuTimeIntelligence]: "时间智能", [_.manageDatesModelCheck]: "查看模型", [_.manageDatesPreview]: "预览", [_.manageDatesPreviewCtrlTitle]: "变更预览", [_.manageDatesSampleData]: "示例数据", [_.manageDatesSampleDataError]: "无法生成示例数据", [_.manageDatesStatusCompatible]: `<div class="hero">您的模型已经包含与Bravo<b>兼容的日期表</b>.</div>如果您在这里做了修改,您的日期表将随之更新,而已经建立的关系不会受到影响`, [_.manageDatesStatusError]: `<div class="hero">无法应用当前设置</div> 错误 {error}`, [_.manageDatesStatusIncompatible]: `<div class="hero">您的模型包含与Bravo <b>不兼容的日期表</b>.</div>如要修改, 请为Bravo将要自动生成的一张或多张表指定其他的名字.<br><br>查看 <b>日期</b> 和 <b>假期</b>.`, [_.manageDatesStatusNotAvailable]: `<div class="hero">您的模型不再有效.</div> 请尝试重新启动应用.`, [_.manageDatesStatusOk]: `<div class="hero">您的模型 <b>可以使用管理日期表功能</b>.</div>您可以创建新的日期表, 不会影响现有度量值和报告.`, [_.manageDatesSuccessSceneMessage]: "恭喜,您的模型已经更新成功", [_.manageDatesTemplateFirstDayOfWeek]: "每周的第一天", [_.manageDatesTemplateFirstDayOfWeekDesc]: "对于ISO周, 请选择 <em>周一</em>.", [_.manageDatesTemplateFirstFiscalMonth]: "每年的第一个月", [_.manageDatesTemplateFirstFiscalMonthDesc]: "对于ISO周, 请选择 <em>一月</em>.", [_.manageDatesTemplateMonthsInYear]: "一年中的月份", [_.manageDatesTemplateMonthsInYearDesc]: "", [_.manageDatesTemplateNameConfig01]: "标准模板", [_.manageDatesTemplateNameConfig02]: "月模板", [_.manageDatesTemplateNameConfig03]: "自定义", [_.manageDatesTemplateNameConfig04]: "周模板", [_.manageDatesTemplateQuarterWeekType]: "周历系统", [_.manageDatesTemplateQuarterWeekTypeDesc]: "", [_.manageDatesTemplateTypeStartFiscalYear]: "定义会计年度的日期", [_.manageDatesTemplateTypeStartFiscalYearDesc]: "对于ISO周, 请选择 <em>年度最后一天</em>.", [_.manageDatesTemplateTypeStartFiscalYearFirst]: "年度第一天", [_.manageDatesTemplateTypeStartFiscalYearLast]: "年度最后一天", [_.manageDatesTemplateWeeklyType]: "年度最后一个工作日", [_.manageDatesTemplateWeeklyTypeDesc]: "如果您的每一周从周日开始, 那么前一个工作日就是周六. 如果您选择 <em>年度最后一个工作日</em> 那么财政年度将在最后一个月的最后一个周六结束. 否则, 财政年度将在最接近年底最后一天的周六结束 - 这个周六有可能出现在下一年. 对于周模板, 选择 <em>最接近年底的工作日</em>.", [_.manageDatesTemplateWeeklyTypeLast]: "年度最后一个工作日", [_.manageDatesTemplateWeeklyTypeNearest]: "最接近年底的工作日", [_.manageDatesTimeIntelligenceDesc]: "为您的模型创建最常见的时间智能DAX函数", [_.manageDatesTimeIntelligenceEnabledDesc]: "", [_.manageDatesTimeIntelligenceEnabledName]: "时间智能函数", [_.manageDatesTimeIntelligenceTargetMeasuresAll]: "所有的度量值", [_.manageDatesTimeIntelligenceTargetMeasuresChoose]: "选择度量值...", [_.manageDatesTimeIntelligenceTargetMeasuresDesc]: "选择要创建时间智能函数的度量值.", [_.manageDatesTimeIntelligenceTargetMeasuresName]: "目标度量值", [_.manageDatesYearRange]: "日期区间", [_.manageDatesYearRangeDesc]: "为您的模型定义一个时间区间. 如果不填 <em>起始年份</em> 和/或 <em>结束年份</em> 就会应用自动扫描的结果", [_.menuCtrlTitle]: "收起/展开菜单", [_.minimizeCtrlTitle]: "最小化", [_.modelLanguage]: "模型语言 ({culture})", [_.more]: "更多", [_.notificationCtrlTitle]: "通知", [_.notificationsTitle]: "{count} 个通知", [_.openSourcePayoff]: "{appName} 是一个SQLBI与Github社区共同开发和维护的一款开源工具. 加入我们", [_.openWithDaxFormatterCtrlTitle]: "使用DAX Formatter在线标准格式化", [_.optionAccount]: "Power BI 账户", [_.optionAccountDescription]: "设置您的账户以访问Power BI 在线数据集", [_.optionCheckForUpdates]: "自动检查更新", [_.optionDiagnostic]: "诊断级别", [_.optionDiagnosticDescription]: "在诊断窗格中显示错误和日志. 选择 <em>基本</em> 记录部分信息 (这些信息将被匿名化). <em>详细</em> 记录所有信息(所有信息将完整保留)", [_.optionDiagnosticLevelBasic]: "基本", [_.optionDiagnosticLevelNone]: "无", [_.optionDiagnosticLevelVerbose]: "详细", [_.optionDiagnosticMore]: "要报告应用错误, 请使用", [_.optionFormattingBreaks]: "度量值名称-表达式 区分", [_.optionFormattingBreaksAuto]: "自动", [_.optionFormattingBreaksDescription]: "如何区分度量值的名称与其表达式. 选择 <em>自动</em> 以自动确定模型中使用的样式", [_.optionFormattingBreaksInitial]: "换行", [_.optionFormattingBreaksNone]: "同一行", [_.optionFormattingIncludeTimeIntelligence]: "包括时间智能", [_.optionFormattingIncludeTimeIntelligenceDescription]: "包括通过管理日期自动创建的措施以供时间智能创建。", [_.optionFormattingLines]: "代码行", [_.optionFormattingLinesDescription]: "选择使用长代码行或短代码行", [_.optionFormattingLinesValueLong]: "长代码行", [_.optionFormattingLinesValueShort]: "短代码行", [_.optionFormattingPreview]: "自动预览", [_.optionFormattingPreviewDescription]: "自动发送度量值到DAX Formatter并生成预览", [_.optionFormattingSeparators]: "分隔符", [_.optionFormattingSeparatorsDescription]: "选择小数点符号以及列表分隔符", [_.optionFormattingSeparatorsValueAuto]: "自动", [_.optionFormattingSeparatorsValueEU]: "A; B; C; 1234,00", [_.optionFormattingSeparatorsValueUS]: "A, B, C, 1234.00", [_.optionFormattingSpaces]: "空格", [_.optionFormattingSpacesDescription]: "函数名称后是否加空格", [_.optionFormattingSpacesValueBestPractice]: "最佳实践", [_.optionFormattingSpacesValueFalse]: "无空格 - IF( ", [_.optionFormattingSpacesValueTrue]: "有空格 - IF ( ", [_.optionInvalidValue]: "无效值", [_.optionLanguage]: "语言", [_.optionLanguageDescription]: "选择Bravo的语言, 需要重新加载", [_.optionLanguageResetConfirm]: "您需要重新加载Bravo以应用新的语言设置吗?", [_.optionProxyAddress]: "代理服务器地址", [_.optionProxyAddressDescription]: "提供代理服务器的地址。", [_.optionProxyBypassList]: "排除地址列表", [_.optionProxyBypassListDescription]: "使用代理服务器,除了以插入条目开头的地址。使用分号(;)分开条目。", [_.optionProxyBypassOnLocal]: "绕过本地地址", [_.optionProxyBypassOnLocalDescription]: "请勿将代理与本地(Intranet)地址一起使用。", [_.optionProxyConfirmDeleteCredentials]: "您确定从系统中删除自定义凭据吗?", [_.optionProxyCustomCredentials]: "自定义凭据", [_.optionProxyCustomCredentialsDescription]: "使用自定义凭据对代理服务器进行身份验证。离开以使用系统凭据。", [_.optionProxyCustomCredentialsEdit]: "编辑自定义凭据", [_.optionProxyType]: "代理服务器", [_.optionProxyTypeCustom]: "风俗", [_.optionProxyTypeDescription]: "选择代理服务器。", [_.optionProxyTypeNone]: "没有任何", [_.optionProxyTypeSystem]: "系统", [_.optionsDialogAboutMenu]: "关于", [_.optionsDialogFormattingMenu]: "格式化", [_.optionsDialogGeneralMenu]: "通用", [_.optionsDialogProxyMenu]: "代理", [_.optionsDialogTelemetryMenu]: "诊断", [_.optionsDialogTitle]: "选项", [_.optionTelemetry]: "远程诊断", [_.optionTelemetryDescription]: "匿名地将使用数据发送给SQLBI", [_.optionTelemetryMore]: "这将帮助我们理解您怎样使用Bravo以及如何继续优化。我们不会收集任何个人信息。请注意,如果您禁用该选项, 开发团队将无法收集任何未处理的错误或提供额外的信息或支持.", [_.optionTheme]: "主题", [_.optionThemeDescription]: "设置Bravo主题, 设置 <em>系统</em> 让操作系统选择", [_.optionThemeValueAuto]: "系统", [_.optionThemeValueDark]: "深色模式", [_.optionThemeValueLight]: "浅色模式", [_.otherColumnsRowName]: "较小的列...", [_.paste]: "粘贴", [_.powerBiObserving]: "等待Power BI Desktop打开文件...", [_.powerBiObservingCancel]: "取消", [_.powerBiSigninDescription]: "登录Power BI Service将您的在线数据集连接到Bravo", [_.powerBiSigninTitle]: "Power BI", [_.quickActionAttachPBITitle]: "连接到 Power BI Desktop", [_.quickActionConnectPBITitle]: "连接到 Power BI Service", [_.quickActionOpenVPXTitle]: "打开一个Vertipaq Analyzer文件", [_.refreshCtrlTitle]: "刷新", [_.refreshPreviewCtrlTitle]: "刷新预览", [_.saveVpaxCtrlTile]: "另存为 VPAX", [_.savingVpax]: "生成 VPAX...", [_.sceneUnsupportedReason]: "该数据源不能使用此功能.", [_.sceneUnsupportedReasonManageDatesAutoDateTimeEnabled]: `不支持启用自动日期/时间选项的模型.<br><span class="link" href="https://www.sqlbi.com/tv/disabling-auto-date-time-in-power-bi/">Power BI禁用自动日期/时间 (video)</span>`, [_.sceneUnsupportedReasonManageDatesEmptyTableCollection]: "该功能需要数据库中至少有一张表", [_.sceneUnsupportedReasonManageDatesPBIDesktopModelOnly]: "该功能仅由Power BI桌面模式下的模型支持.", [_.sceneUnsupportedReasonMetadataOnly]: "该数据库是由VPAX文件生成的, 其中只包括其元数据.", [_.sceneUnsupportedReasonReadOnly]: "与该数据库的连接是只读的.", [_.sceneUnsupportedReasonXmlaEndpointNotSupported]: "该数据集不支持XMLA端点.", [_.sceneUnsupportedTitle]: "不支持", [_.searchColumnPlaceholder]: "搜索列", [_.searchDatasetPlaceholder]: "搜索数据集", [_.searchEntityPlaceholder]: "搜索表/列", [_.searchMeasurePlaceholder]: "搜索度量值", [_.searchPlaceholder]: "搜索", [_.searchTablePlaceholder]: "搜索表", [_.settingsCtrlTitle]: "选项", [_.sheetOrphan]: "不可用", [_.sheetOrphanPBIXTooltip]: "该报告已经在Power BI Desktop关闭. 不允许任何写入操作", [_.sheetOrphanTooltip]: "这个模型已经不可用. 不允许任何写入操作.", [_.showDiagnosticPane]: "显示明细", [_.sideCtrlTitle]: "切换并列式视图", [_.signedInCtrlTitle]: "以 {name} 登录", [_.signIn]: "登录", [_.signInCtrlTitle]: "登录", [_.signOut]: "退出", [_.sqlbiPayoff]: "Bravo是SQLBI的项目.", [_.syncCtrlTitle]: "同步", [_.tableColCardinality]: "基数", [_.tableColCardinalityTooltip]: "非重复项的数量", [_.tableColColumn]: "列", [_.tableColColumns]: "列", [_.tableColMeasure]: "度量值", [_.tableColPath]: "表 \\ 列", [_.tableColRows]: "行", [_.tableColSize]: "大小", [_.tableColTable]: "表", [_.tableColWeight]: "占比", [_.tableSelectedCount]: "{count} 选中的", [_.tableValidationInvalid]: "不能使用这个名称", [_.tableValidationValid]: "这个名称有效", [_.themeCtrlTitle]: "主题变更", [_.toggleTree]: "切换树形图", [_.traceId]: "跟踪ID", [_.unknownMessage]: "收到的信息无效", [_.updateChannelBeta]: "测试版", [_.updateChannelCanary]: "Canary", [_.updateChannelDev]: "开发版", [_.updateChannelStable]: "稳定版", [_.updateMessage]: "Bravo有可用的新版本: {version}", [_.validating]: "正在验证...", [_.version]: "版本", [_.welcomeHelpText]: "观看以下视频学习如何使用Bravo:", [_.welcomeHelpTitle]: "如何使用Bravo?", [_.welcomeText]: "Bravo是一个方便实用的Power BI工具包, 你可以用它来分析您的模型, 标准格式化您的度量值, 创建日期表, 并导出数据。", [_.whitespacesTitle]: "空白区域", [_.wrappingTitle]: "文本自动换行", } } export default locale;
the_stack
import * as dom from 'vs/base/browser/dom'; import { ScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { IAction } from 'vs/base/common/actions'; import { isNonEmptyArray } from 'vs/base/common/arrays'; import { Color } from 'vs/base/common/color'; import { Emitter, Event } from 'vs/base/common/event'; import { getBaseLabel } from 'vs/base/common/labels'; import { DisposableStore, dispose } from 'vs/base/common/lifecycle'; import { basename } from 'vs/base/common/resources'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { splitLines } from 'vs/base/common/strings'; import 'vs/css!./media/gotoErrorWidget'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { EditorOption } from 'vs/editor/common/config/editorOptions'; import { Range } from 'vs/editor/common/core/range'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { peekViewTitleForeground, peekViewTitleInfoForeground, PeekViewWidget } from 'vs/editor/contrib/peekView/browser/peekView'; import * as nls from 'vs/nls'; import { createAndFillInActionBarActions } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { IMenuService, MenuId } from 'vs/platform/actions/common/actions'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILabelService } from 'vs/platform/label/common/label'; import { IMarker, IRelatedInformation, MarkerSeverity } from 'vs/platform/markers/common/markers'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { SeverityIcon } from 'vs/platform/severityIcon/common/severityIcon'; import { contrastBorder, editorBackground, editorErrorBorder, editorErrorForeground, editorInfoBorder, editorInfoForeground, editorWarningBorder, editorWarningForeground, oneOf, registerColor, transparent } from 'vs/platform/theme/common/colorRegistry'; import { IColorTheme, IThemeService } from 'vs/platform/theme/common/themeService'; class MessageWidget { private _lines: number = 0; private _longestLineLength: number = 0; private readonly _editor: ICodeEditor; private readonly _messageBlock: HTMLDivElement; private readonly _relatedBlock: HTMLDivElement; private readonly _scrollable: ScrollableElement; private readonly _relatedDiagnostics = new WeakMap<HTMLElement, IRelatedInformation>(); private readonly _disposables: DisposableStore = new DisposableStore(); private _codeLink?: HTMLElement; constructor( parent: HTMLElement, editor: ICodeEditor, onRelatedInformation: (related: IRelatedInformation) => void, private readonly _openerService: IOpenerService, private readonly _labelService: ILabelService ) { this._editor = editor; const domNode = document.createElement('div'); domNode.className = 'descriptioncontainer'; this._messageBlock = document.createElement('div'); this._messageBlock.classList.add('message'); this._messageBlock.setAttribute('aria-live', 'assertive'); this._messageBlock.setAttribute('role', 'alert'); domNode.appendChild(this._messageBlock); this._relatedBlock = document.createElement('div'); domNode.appendChild(this._relatedBlock); this._disposables.add(dom.addStandardDisposableListener(this._relatedBlock, 'click', event => { event.preventDefault(); const related = this._relatedDiagnostics.get(event.target); if (related) { onRelatedInformation(related); } })); this._scrollable = new ScrollableElement(domNode, { horizontal: ScrollbarVisibility.Auto, vertical: ScrollbarVisibility.Auto, useShadows: false, horizontalScrollbarSize: 6, verticalScrollbarSize: 6 }); parent.appendChild(this._scrollable.getDomNode()); this._disposables.add(this._scrollable.onScroll(e => { domNode.style.left = `-${e.scrollLeft}px`; domNode.style.top = `-${e.scrollTop}px`; })); this._disposables.add(this._scrollable); } dispose(): void { dispose(this._disposables); } update(marker: IMarker): void { const { source, message, relatedInformation, code } = marker; let sourceAndCodeLength = (source?.length || 0) + '()'.length; if (code) { if (typeof code === 'string') { sourceAndCodeLength += code.length; } else { sourceAndCodeLength += code.value.length; } } const lines = splitLines(message); this._lines = lines.length; this._longestLineLength = 0; for (const line of lines) { this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength); } dom.clearNode(this._messageBlock); this._messageBlock.setAttribute('aria-label', this.getAriaLabel(marker)); this._editor.applyFontInfo(this._messageBlock); let lastLineElement = this._messageBlock; for (const line of lines) { lastLineElement = document.createElement('div'); lastLineElement.innerText = line; if (line === '') { lastLineElement.style.height = this._messageBlock.style.lineHeight; } this._messageBlock.appendChild(lastLineElement); } if (source || code) { const detailsElement = document.createElement('span'); detailsElement.classList.add('details'); lastLineElement.appendChild(detailsElement); if (source) { const sourceElement = document.createElement('span'); sourceElement.innerText = source; sourceElement.classList.add('source'); detailsElement.appendChild(sourceElement); } if (code) { if (typeof code === 'string') { const codeElement = document.createElement('span'); codeElement.innerText = `(${code})`; codeElement.classList.add('code'); detailsElement.appendChild(codeElement); } else { this._codeLink = dom.$('a.code-link'); this._codeLink.setAttribute('href', `${code.target.toString()}`); this._codeLink.onclick = (e) => { this._openerService.open(code.target, { allowCommands: true }); e.preventDefault(); e.stopPropagation(); }; const codeElement = dom.append(this._codeLink, dom.$('span')); codeElement.innerText = code.value; detailsElement.appendChild(this._codeLink); } } } dom.clearNode(this._relatedBlock); this._editor.applyFontInfo(this._relatedBlock); if (isNonEmptyArray(relatedInformation)) { const relatedInformationNode = this._relatedBlock.appendChild(document.createElement('div')); relatedInformationNode.style.paddingTop = `${Math.floor(this._editor.getOption(EditorOption.lineHeight) * 0.66)}px`; this._lines += 1; for (const related of relatedInformation) { let container = document.createElement('div'); let relatedResource = document.createElement('a'); relatedResource.classList.add('filename'); relatedResource.innerText = `${getBaseLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `; relatedResource.title = this._labelService.getUriLabel(related.resource); this._relatedDiagnostics.set(relatedResource, related); let relatedMessage = document.createElement('span'); relatedMessage.innerText = related.message; container.appendChild(relatedResource); container.appendChild(relatedMessage); this._lines += 1; relatedInformationNode.appendChild(container); } } const fontInfo = this._editor.getOption(EditorOption.fontInfo); const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75); const scrollHeight = fontInfo.lineHeight * this._lines; this._scrollable.setScrollDimensions({ scrollWidth, scrollHeight }); } layout(height: number, width: number): void { this._scrollable.getDomNode().style.height = `${height}px`; this._scrollable.getDomNode().style.width = `${width}px`; this._scrollable.setScrollDimensions({ width, height }); } getHeightInLines(): number { return Math.min(17, this._lines); } private getAriaLabel(marker: IMarker): string { let severityLabel = ''; switch (marker.severity) { case MarkerSeverity.Error: severityLabel = nls.localize('Error', "Error"); break; case MarkerSeverity.Warning: severityLabel = nls.localize('Warning', "Warning"); break; case MarkerSeverity.Info: severityLabel = nls.localize('Info', "Info"); break; case MarkerSeverity.Hint: severityLabel = nls.localize('Hint', "Hint"); break; } let ariaLabel = nls.localize('marker aria', "{0} at {1}. ", severityLabel, marker.startLineNumber + ':' + marker.startColumn); const model = this._editor.getModel(); if (model && (marker.startLineNumber <= model.getLineCount()) && (marker.startLineNumber >= 1)) { const lineContent = model.getLineContent(marker.startLineNumber); ariaLabel = `${lineContent}, ${ariaLabel}`; } return ariaLabel; } } export class MarkerNavigationWidget extends PeekViewWidget { static readonly TitleMenu = new MenuId('gotoErrorTitleMenu'); private _parentContainer!: HTMLElement; private _container!: HTMLElement; private _icon!: HTMLElement; private _message!: MessageWidget; private readonly _callOnDispose = new DisposableStore(); private _severity: MarkerSeverity; private _backgroundColor?: Color; private readonly _onDidSelectRelatedInformation = new Emitter<IRelatedInformation>(); private _heightInPixel!: number; readonly onDidSelectRelatedInformation: Event<IRelatedInformation> = this._onDidSelectRelatedInformation.event; constructor( editor: ICodeEditor, @IThemeService private readonly _themeService: IThemeService, @IOpenerService private readonly _openerService: IOpenerService, @IMenuService private readonly _menuService: IMenuService, @IInstantiationService instantiationService: IInstantiationService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @ILabelService private readonly _labelService: ILabelService ) { super(editor, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService); this._severity = MarkerSeverity.Warning; this._backgroundColor = Color.white; this._applyTheme(_themeService.getColorTheme()); this._callOnDispose.add(_themeService.onDidColorThemeChange(this._applyTheme.bind(this))); this.create(); } private _applyTheme(theme: IColorTheme) { this._backgroundColor = theme.getColor(editorMarkerNavigationBackground); let colorId = editorMarkerNavigationError; let headerBackground = editorMarkerNavigationErrorHeader; if (this._severity === MarkerSeverity.Warning) { colorId = editorMarkerNavigationWarning; headerBackground = editorMarkerNavigationWarningHeader; } else if (this._severity === MarkerSeverity.Info) { colorId = editorMarkerNavigationInfo; headerBackground = editorMarkerNavigationInfoHeader; } const frameColor = theme.getColor(colorId); const headerBg = theme.getColor(headerBackground); this.style({ arrowColor: frameColor, frameColor: frameColor, headerBackgroundColor: headerBg, primaryHeadingColor: theme.getColor(peekViewTitleForeground), secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground) }); // style() will trigger _applyStyles } protected override _applyStyles(): void { if (this._parentContainer) { this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : ''; } super._applyStyles(); } override dispose(): void { this._callOnDispose.dispose(); super.dispose(); } focus(): void { this._parentContainer.focus(); } protected override _fillHead(container: HTMLElement): void { super._fillHead(container); this._disposables.add(this._actionbarWidget!.actionRunner.onBeforeRun(e => this.editor.focus())); const actions: IAction[] = []; const menu = this._menuService.createMenu(MarkerNavigationWidget.TitleMenu, this._contextKeyService); createAndFillInActionBarActions(menu, undefined, actions); this._actionbarWidget!.push(actions, { label: false, icon: true, index: 0 }); menu.dispose(); } protected override _fillTitleIcon(container: HTMLElement): void { this._icon = dom.append(container, dom.$('')); } protected _fillBody(container: HTMLElement): void { this._parentContainer = container; container.classList.add('marker-widget'); this._parentContainer.tabIndex = 0; this._parentContainer.setAttribute('role', 'tooltip'); this._container = document.createElement('div'); container.appendChild(this._container); this._message = new MessageWidget(this._container, this.editor, related => this._onDidSelectRelatedInformation.fire(related), this._openerService, this._labelService); this._disposables.add(this._message); } override show(): void { throw new Error('call showAtMarker'); } showAtMarker(marker: IMarker, markerIdx: number, markerCount: number): void { // update: // * title // * message this._container.classList.remove('stale'); this._message.update(marker); // update frame color (only applied on 'show') this._severity = marker.severity; this._applyTheme(this._themeService.getColorTheme()); // show let range = Range.lift(marker); const editorPosition = this.editor.getPosition(); let position = editorPosition && range.containsPosition(editorPosition) ? editorPosition : range.getStartPosition(); super.show(position, this.computeRequiredHeight()); const model = this.editor.getModel(); if (model) { const detail = markerCount > 1 ? nls.localize('problems', "{0} of {1} problems", markerIdx, markerCount) : nls.localize('change', "{0} of {1} problem", markerIdx, markerCount); this.setTitle(basename(model.uri), detail); } this._icon.className = `codicon ${SeverityIcon.className(MarkerSeverity.toSeverity(this._severity))}`; this.editor.revealPositionNearTop(position, ScrollType.Smooth); this.editor.focus(); } updateMarker(marker: IMarker): void { this._container.classList.remove('stale'); this._message.update(marker); } showStale() { this._container.classList.add('stale'); this._relayout(); } protected override _doLayoutBody(heightInPixel: number, widthInPixel: number): void { super._doLayoutBody(heightInPixel, widthInPixel); this._heightInPixel = heightInPixel; this._message.layout(heightInPixel, widthInPixel); this._container.style.height = `${heightInPixel}px`; } public override _onWidth(widthInPixel: number): void { this._message.layout(this._heightInPixel, widthInPixel); } protected override _relayout(): void { super._relayout(this.computeRequiredHeight()); } private computeRequiredHeight() { return 3 + this._message.getHeightInLines(); } } // theming let errorDefault = oneOf(editorErrorForeground, editorErrorBorder); let warningDefault = oneOf(editorWarningForeground, editorWarningBorder); let infoDefault = oneOf(editorInfoForeground, editorInfoBorder); export const editorMarkerNavigationError = registerColor('editorMarkerNavigationError.background', { dark: errorDefault, light: errorDefault, hcDark: contrastBorder, hcLight: contrastBorder }, nls.localize('editorMarkerNavigationError', 'Editor marker navigation widget error color.')); export const editorMarkerNavigationErrorHeader = registerColor('editorMarkerNavigationError.headerBackground', { dark: transparent(editorMarkerNavigationError, .1), light: transparent(editorMarkerNavigationError, .1), hcDark: null, hcLight: null }, nls.localize('editorMarkerNavigationErrorHeaderBackground', 'Editor marker navigation widget error heading background.')); export const editorMarkerNavigationWarning = registerColor('editorMarkerNavigationWarning.background', { dark: warningDefault, light: warningDefault, hcDark: contrastBorder, hcLight: contrastBorder }, nls.localize('editorMarkerNavigationWarning', 'Editor marker navigation widget warning color.')); export const editorMarkerNavigationWarningHeader = registerColor('editorMarkerNavigationWarning.headerBackground', { dark: transparent(editorMarkerNavigationWarning, .1), light: transparent(editorMarkerNavigationWarning, .1), hcDark: '#0C141F', hcLight: transparent(editorMarkerNavigationWarning, .2) }, nls.localize('editorMarkerNavigationWarningBackground', 'Editor marker navigation widget warning heading background.')); export const editorMarkerNavigationInfo = registerColor('editorMarkerNavigationInfo.background', { dark: infoDefault, light: infoDefault, hcDark: contrastBorder, hcLight: contrastBorder }, nls.localize('editorMarkerNavigationInfo', 'Editor marker navigation widget info color.')); export const editorMarkerNavigationInfoHeader = registerColor('editorMarkerNavigationInfo.headerBackground', { dark: transparent(editorMarkerNavigationInfo, .1), light: transparent(editorMarkerNavigationInfo, .1), hcDark: null, hcLight: null }, nls.localize('editorMarkerNavigationInfoHeaderBackground', 'Editor marker navigation widget info heading background.')); export const editorMarkerNavigationBackground = registerColor('editorMarkerNavigation.background', { dark: editorBackground, light: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, nls.localize('editorMarkerNavigationBackground', 'Editor marker navigation widget background.'));
the_stack
import * as zrUtil from 'zrender/src/core/util'; import { DisplayableState } from 'zrender/src/graphic/Displayable'; import { PathStyleProps } from 'zrender/src/graphic/Path'; import { parse, stringify } from 'zrender/src/tool/color'; import * as graphic from '../../util/graphic'; import { enableHoverEmphasis } from '../../util/states'; import {setLabelStyle, createTextStyle} from '../../label/labelStyle'; import {makeBackground} from '../helper/listComponent'; import * as layoutUtil from '../../util/layout'; import ComponentView from '../../view/Component'; import LegendModel, { LegendItemStyleOption, LegendLineStyleOption, LegendOption, LegendSelectorButtonOption, LegendIconParams, LegendTooltipFormatterParams } from './LegendModel'; import GlobalModel from '../../model/Global'; import ExtensionAPI from '../../core/ExtensionAPI'; import { ZRTextAlign, ZRRectLike, CommonTooltipOption, ColorString, SeriesOption, SymbolOptionMixin } from '../../util/types'; import Model from '../../model/Model'; import {LineStyleProps, LINE_STYLE_KEY_MAP} from '../../model/mixin/lineStyle'; import {ITEM_STYLE_KEY_MAP} from '../../model/mixin/itemStyle'; import {createSymbol, ECSymbol} from '../../util/symbol'; import SeriesModel from '../../model/Series'; const curry = zrUtil.curry; const each = zrUtil.each; const Group = graphic.Group; class LegendView extends ComponentView { static type = 'legend.plain'; type = LegendView.type; newlineDisabled = false; private _contentGroup: graphic.Group; private _backgroundEl: graphic.Rect; private _selectorGroup: graphic.Group; /** * If first rendering, `contentGroup.position` is [0, 0], which * does not make sense and may cause unexepcted animation if adopted. */ private _isFirstRender: boolean; init() { this.group.add(this._contentGroup = new Group()); this.group.add(this._selectorGroup = new Group()); this._isFirstRender = true; } /** * @protected */ getContentGroup() { return this._contentGroup; } /** * @protected */ getSelectorGroup() { return this._selectorGroup; } /** * @override */ render( legendModel: LegendModel, ecModel: GlobalModel, api: ExtensionAPI ) { const isFirstRender = this._isFirstRender; this._isFirstRender = false; this.resetInner(); if (!legendModel.get('show', true)) { return; } let itemAlign = legendModel.get('align'); const orient = legendModel.get('orient'); if (!itemAlign || itemAlign === 'auto') { itemAlign = ( legendModel.get('left') === 'right' && orient === 'vertical' ) ? 'right' : 'left'; } // selector has been normalized to an array in model const selector = legendModel.get('selector', true) as LegendSelectorButtonOption[]; let selectorPosition = legendModel.get('selectorPosition', true); if (selector && (!selectorPosition || selectorPosition === 'auto')) { selectorPosition = orient === 'horizontal' ? 'end' : 'start'; } this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout. const positionInfo = legendModel.getBoxLayoutParams(); const viewportSize = {width: api.getWidth(), height: api.getHeight()}; const padding = legendModel.get('padding'); const maxSize = layoutUtil.getLayoutRect(positionInfo, viewportSize, padding); const mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`. const layoutRect = layoutUtil.getLayoutRect( zrUtil.defaults({ width: mainRect.width, height: mainRect.height }, positionInfo), viewportSize, padding ); this.group.x = layoutRect.x - mainRect.x; this.group.y = layoutRect.y - mainRect.y; this.group.markRedraw(); // Render background after group is layout. this.group.add( this._backgroundEl = makeBackground(mainRect, legendModel) ); } protected resetInner() { this.getContentGroup().removeAll(); this._backgroundEl && this.group.remove(this._backgroundEl); this.getSelectorGroup().removeAll(); } protected renderInner( itemAlign: LegendOption['align'], legendModel: LegendModel, ecModel: GlobalModel, api: ExtensionAPI, selector: LegendSelectorButtonOption[], orient: LegendOption['orient'], selectorPosition: LegendOption['selectorPosition'] ) { const contentGroup = this.getContentGroup(); const legendDrawnMap = zrUtil.createHashMap(); const selectMode = legendModel.get('selectedMode'); const excludeSeriesId: string[] = []; ecModel.eachRawSeries(function (seriesModel) { !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id); }); each(legendModel.getData(), function (legendItemModel, dataIndex) { const name = legendItemModel.get('name'); // Use empty string or \n as a newline string if (!this.newlineDisabled && (name === '' || name === '\n')) { const g = new Group(); // @ts-ignore g.newline = true; contentGroup.add(g); return; } // Representitive series. const seriesModel = ecModel.getSeriesByName(name)[0] as SeriesModel<SeriesOption & SymbolOptionMixin>; if (legendDrawnMap.get(name)) { // Have been drawed return; } // Legend to control series. if (seriesModel) { const data = seriesModel.getData(); const lineVisualStyle = data.getVisual('legendLineStyle') || {}; const legendIcon = data.getVisual('legendIcon'); /** * `data.getVisual('style')` may be the color from the register * in series. For example, for line series, */ const style = data.getVisual('style'); const itemGroup = this._createItem( seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode ); itemGroup.on('click', curry(dispatchSelectAction, name, null, api, excludeSeriesId)) .on('mouseover', curry(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)) .on('mouseout', curry(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId)); legendDrawnMap.set(name, true); } else { // Legend to control data. In pie and funnel. ecModel.eachRawSeries(function (seriesModel) { // In case multiple series has same data name if (legendDrawnMap.get(name)) { return; } if (seriesModel.legendVisualProvider) { const provider = seriesModel.legendVisualProvider; if (!provider.containName(name)) { return; } const idx = provider.indexOfName(name); const style = provider.getItemVisual(idx, 'style') as PathStyleProps; const legendIcon = provider.getItemVisual(idx, 'legendIcon'); const colorArr = parse(style.fill as ColorString); // Color may be set to transparent in visualMap when data is out of range. // Do not show nothing. if (colorArr && colorArr[3] === 0) { colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA style.fill = stringify(colorArr, 'rgba'); } const itemGroup = this._createItem( seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode ); // FIXME: consider different series has items with the same name. itemGroup.on('click', curry(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls // more than one pie series. .on('mouseover', curry(dispatchHighlightAction, null, name, api, excludeSeriesId)) .on('mouseout', curry(dispatchDownplayAction, null, name, api, excludeSeriesId)); legendDrawnMap.set(name, true); } }, this); } if (__DEV__) { if (!legendDrawnMap.get(name)) { console.warn( name + ' series not exists. Legend data should be same with series name or data name.' ); } } }, this); if (selector) { this._createSelector(selector, legendModel, api, orient, selectorPosition); } } private _createSelector( selector: LegendSelectorButtonOption[], legendModel: LegendModel, api: ExtensionAPI, orient: LegendOption['orient'], selectorPosition: LegendOption['selectorPosition'] ) { const selectorGroup = this.getSelectorGroup(); each(selector, function createSelectorButton(selectorItem) { const type = selectorItem.type; const labelText = new graphic.Text({ style: { x: 0, y: 0, align: 'center', verticalAlign: 'middle' }, onclick() { api.dispatchAction({ type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect' }); } }); selectorGroup.add(labelText); const labelModel = legendModel.getModel('selectorLabel'); const emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']); setLabelStyle( labelText, { normal: labelModel, emphasis: emphasisLabelModel }, { defaultText: selectorItem.title } ); enableHoverEmphasis(labelText); }); } private _createItem( seriesModel: SeriesModel<SeriesOption & SymbolOptionMixin>, name: string, dataIndex: number, legendItemModel: LegendModel['_data'][number], legendModel: LegendModel, itemAlign: LegendOption['align'], lineVisualStyle: LineStyleProps, itemVisualStyle: PathStyleProps, legendIcon: string, selectMode: LegendOption['selectedMode'] ) { const drawType = seriesModel.visualDrawType; const itemWidth = legendModel.get('itemWidth'); const itemHeight = legendModel.get('itemHeight'); const isSelected = legendModel.isSelected(name); const iconRotate = legendItemModel.get('symbolRotate'); const symbolKeepAspect = legendItemModel.get('symbolKeepAspect'); const legendIconType = legendItemModel.get('icon'); legendIcon = legendIconType || legendIcon || 'roundRect'; const style = getLegendStyle( legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected ); const itemGroup = new Group(); const textStyleModel = legendItemModel.getModel('textStyle'); if (typeof seriesModel.getLegendIcon === 'function' && (!legendIconType || legendIconType === 'inherit') ) { // Series has specific way to define legend icon itemGroup.add(seriesModel.getLegendIcon({ itemWidth, itemHeight, icon: legendIcon, iconRotate: iconRotate, itemStyle: style.itemStyle, lineStyle: style.lineStyle, symbolKeepAspect })); } else { // Use default legend icon policy for most series const rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? (iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate ) : 0; // No rotation for no icon itemGroup.add(getDefaultLegendIcon({ itemWidth, itemHeight, icon: legendIcon, iconRotate: rotate, itemStyle: style.itemStyle, lineStyle: style.lineStyle, symbolKeepAspect })); } const textX = itemAlign === 'left' ? itemWidth + 5 : -5; const textAlign = itemAlign as ZRTextAlign; const formatter = legendModel.get('formatter'); let content = name; if (typeof formatter === 'string' && formatter) { content = formatter.replace('{name}', name != null ? name : ''); } else if (typeof formatter === 'function') { content = formatter(name); } const inactiveColor = legendItemModel.get('inactiveColor'); itemGroup.add(new graphic.Text({ style: createTextStyle(textStyleModel, { text: content, x: textX, y: itemHeight / 2, fill: isSelected ? textStyleModel.getTextColor() : inactiveColor, align: textAlign, verticalAlign: 'middle' }) })); // Add a invisible rect to increase the area of mouse hover const hitRect = new graphic.Rect({ shape: itemGroup.getBoundingRect(), invisible: true }); const tooltipModel = legendItemModel.getModel('tooltip') as Model<CommonTooltipOption<LegendTooltipFormatterParams>>; if (tooltipModel.get('show')) { graphic.setTooltipConfig({ el: hitRect, componentModel: legendModel, itemName: name, itemTooltipOption: tooltipModel.option }); } itemGroup.add(hitRect); itemGroup.eachChild(function (child) { child.silent = true; }); hitRect.silent = !selectMode; this.getContentGroup().add(itemGroup); enableHoverEmphasis(itemGroup); // @ts-ignore itemGroup.__legendDataIndex = dataIndex; return itemGroup; } protected layoutInner( legendModel: LegendModel, itemAlign: LegendOption['align'], maxSize: { width: number, height: number }, isFirstRender: boolean, selector: LegendOption['selector'], selectorPosition: LegendOption['selectorPosition'] ): ZRRectLike { const contentGroup = this.getContentGroup(); const selectorGroup = this.getSelectorGroup(); // Place items in contentGroup. layoutUtil.box( legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height ); const contentRect = contentGroup.getBoundingRect(); const contentPos = [-contentRect.x, -contentRect.y]; selectorGroup.markRedraw(); contentGroup.markRedraw(); if (selector) { // Place buttons in selectorGroup layoutUtil.box( // Buttons in selectorGroup always layout horizontally 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true) ); const selectorRect = selectorGroup.getBoundingRect(); const selectorPos = [-selectorRect.x, -selectorRect.y]; const selectorButtonGap = legendModel.get('selectorButtonGap', true); const orientIdx = legendModel.getOrient().index; const wh: 'width' | 'height' = orientIdx === 0 ? 'width' : 'height'; const hw: 'width' | 'height' = orientIdx === 0 ? 'height' : 'width'; const yx: 'x' | 'y' = orientIdx === 0 ? 'y' : 'x'; if (selectorPosition === 'end') { selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap; } else { contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap; } //Always align selector to content as 'middle' selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2; selectorGroup.x = selectorPos[0]; selectorGroup.y = selectorPos[1]; contentGroup.x = contentPos[0]; contentGroup.y = contentPos[1]; const mainRect = {x: 0, y: 0} as ZRRectLike; mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh]; mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]); mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]); return mainRect; } else { contentGroup.x = contentPos[0]; contentGroup.y = contentPos[1]; return this.group.getBoundingRect(); } } /** * @protected */ remove() { this.getContentGroup().removeAll(); this._isFirstRender = true; } } function getLegendStyle( iconType: string, legendModel: LegendModel['_data'][number], lineVisualStyle: PathStyleProps, itemVisualStyle: PathStyleProps, drawType: 'fill' | 'stroke', isSelected: boolean ) { /** * Use series style if is inherit; * elsewise, use legend style */ function handleCommonProps(style: PathStyleProps, visualStyle: PathStyleProps) { // If lineStyle.width is 'auto', it is set to be 2 if series has border if ((style.lineWidth as any) === 'auto') { style.lineWidth = (visualStyle.lineWidth > 0) ? 2 : 0; } each(style, (propVal, propName) => { style[propName] === 'inherit' && ((style as any)[propName] = visualStyle[propName]); }); } // itemStyle const legendItemModel = legendModel.getModel('itemStyle') as Model<LegendItemStyleOption>; const itemStyle = legendItemModel.getItemStyle(); const iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke'; itemStyle.decal = itemVisualStyle.decal; if (itemStyle.fill === 'inherit') { /** * Series with visualDrawType as 'stroke' should have * series stroke as legend fill */ itemStyle.fill = itemVisualStyle[drawType]; } if (itemStyle.stroke === 'inherit') { /** * icon type with "emptyXXX" should use fill color * in visual style */ itemStyle.stroke = itemVisualStyle[iconBrushType]; } if ((itemStyle.opacity as any) === 'inherit') { /** * Use lineStyle.opacity if drawType is stroke */ itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity; } handleCommonProps(itemStyle, itemVisualStyle); // lineStyle const legendLineModel = legendModel.getModel('lineStyle') as Model<LegendLineStyleOption>; const lineStyle: LineStyleProps = legendLineModel.getLineStyle(); handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color (itemStyle.fill === 'auto') && (itemStyle.fill = itemVisualStyle.fill); (itemStyle.stroke === 'auto') && (itemStyle.stroke = itemVisualStyle.fill); (lineStyle.stroke === 'auto') && (lineStyle.stroke = itemVisualStyle.fill); if (!isSelected) { const borderWidth = legendModel.get('inactiveBorderWidth'); /** * Since stroke is set to be inactiveBorderColor, it may occur that * there is no border in series but border in legend, so we need to * use border only when series has border if is set to be auto */ const visualHasBorder = itemStyle[iconBrushType]; itemStyle.lineWidth = borderWidth === 'auto' ? (itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0) : itemStyle.lineWidth; itemStyle.fill = legendModel.get('inactiveColor'); itemStyle.stroke = legendModel.get('inactiveBorderColor'); lineStyle.stroke = legendLineModel.get('inactiveColor'); lineStyle.lineWidth = legendLineModel.get('inactiveWidth'); } return { itemStyle, lineStyle }; } function getDefaultLegendIcon(opt: LegendIconParams): ECSymbol { const symboType = opt.icon || 'roundRect'; const icon = createSymbol( symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect ); icon.setStyle(opt.itemStyle); icon.rotation = (opt.iconRotate as number || 0) * Math.PI / 180; icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]); if (symboType.indexOf('empty') > -1) { icon.style.stroke = icon.style.fill; icon.style.fill = '#fff'; icon.style.lineWidth = 2; } return icon; } function dispatchSelectAction( seriesName: string, dataName: string, api: ExtensionAPI, excludeSeriesId: string[] ) { // downplay before unselect dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId); api.dispatchAction({ type: 'legendToggleSelect', name: seriesName != null ? seriesName : dataName }); // highlight after select // TODO higlight immediately may cause animation loss. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId); } function isUseHoverLayer(api: ExtensionAPI) { const list = api.getZr().storage.getDisplayList(); let emphasisState: DisplayableState; let i = 0; const len = list.length; while (i < len && !(emphasisState = list[i].states.emphasis)) { i++; } return emphasisState && emphasisState.hoverLayer; } function dispatchHighlightAction( seriesName: string, dataName: string, api: ExtensionAPI, excludeSeriesId: string[] ) { // If element hover will move to a hoverLayer. if (!isUseHoverLayer(api)) { api.dispatchAction({ type: 'highlight', seriesName: seriesName, name: dataName, excludeSeriesId: excludeSeriesId }); } } function dispatchDownplayAction( seriesName: string, dataName: string, api: ExtensionAPI, excludeSeriesId: string[] ) { // If element hover will move to a hoverLayer. if (!isUseHoverLayer(api)) { api.dispatchAction({ type: 'downplay', seriesName: seriesName, name: dataName, excludeSeriesId: excludeSeriesId }); } } export default LegendView;
the_stack
import { getMemoryStore } from "@connext/store"; import { ConditionalTransferTypes, IConnextClient, EventNames } from "@connext/types"; import { getRandomBytes32, getRandomPrivateKey, getPublicKeyFromPrivateKey, getPublicIdentifierFromPublicKey, delay, } from "@connext/utils"; import { ContractFactory, Wallet, constants } from "ethers"; import tokenArtifacts from "@openzeppelin/contracts/build/contracts/ERC20Mintable.json"; import { asyncTransferAsset, createClient, ETH_AMOUNT_LG, ETH_AMOUNT_MD, ETH_AMOUNT_SM, ethProvider, expect, fundChannel, FUNDED_MNEMONICS, getTestLoggers, requestCollateral, TOKEN_AMOUNT, withdrawFromChannel, ZERO_ZERO_ONE_ETH, } from "../util"; const { AddressZero } = constants; const name = "Async Transfers"; const { log, timeElapsed } = getTestLoggers(name); describe(name, () => { let clientA: IConnextClient; let clientB: IConnextClient; let start: number; let tokenAddress: string; beforeEach(async () => { start = Date.now(); clientA = await createClient({ id: "A" }); clientB = await createClient({ id: "B" }); tokenAddress = clientA.config.contractAddresses[clientA.chainId].Token!; timeElapsed("beforeEach complete", start); }); afterEach(async () => { await clientA.off(); await clientB.off(); }); it("client A transfers eth to client B through node", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); await requestCollateral(clientB, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); }); it("should transfer tokens to online peer (case-insensitive assetId)", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress.toUpperCase() }; await fundChannel(clientA, transfer.amount, transfer.assetId); await clientB.requestCollateral(transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); }); it("client A transfers eth to offline client through node", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); const receiverPk = getRandomPrivateKey(); const recevierStore = getMemoryStore(); let receiver = await createClient({ id: "C-initial", signer: receiverPk, store: recevierStore, }); await requestCollateral(receiver, transfer.assetId); await receiver.off(); const paymentId = getRandomBytes32(); await clientA.transfer({ amount: transfer.amount.toString(), assetId: transfer.assetId, recipient: receiver.publicIdentifier, paymentId, }); // transfer returns on the sender side when the sender app is installed only await delay(30_000); const senderUnlock = clientA.waitFor(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, 30000); receiver = await createClient( { id: "C-recreated", signer: receiverPk, store: recevierStore }, false, ); await senderUnlock; const { [receiver.signerAddress]: receiverFreeBalance } = await receiver.getFreeBalance( transfer.assetId, ); expect(receiverFreeBalance).to.eq(transfer.amount); }); it("client A successfully transfers to an address that doesn’t have a channel", async () => { const receiverPk = getRandomPrivateKey(); const receiverIdentifier = getPublicIdentifierFromPublicKey( getPublicKeyFromPrivateKey(receiverPk), ); await fundChannel(clientA, ETH_AMOUNT_SM, tokenAddress); await clientA.transfer({ amount: ETH_AMOUNT_SM.toString(), assetId: tokenAddress, recipient: receiverIdentifier, }); const receiverClient = await createClient({ signer: receiverPk, id: "R" }, false); await delay(5000); expect(receiverClient.publicIdentifier).to.eq(receiverIdentifier); const freeBalance = await receiverClient.getFreeBalance(tokenAddress); expect(freeBalance[receiverClient.signerAddress]).to.be.above(0); await receiverClient.off(); }); it.skip("latency test: deposit, collateralize, many transfers, withdraw", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, ETH_AMOUNT_MD, transfer.assetId); await requestCollateral(clientB, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); await withdrawFromChannel(clientA, ZERO_ZERO_ONE_ETH, AddressZero); /* // @ts-ignore this.timeout(1200000); const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); await requestCollateral(clientB, transfer.assetId); let startTime: number[] = []; let y = 0; clientB.on("RECEIVE_TRANSFER_FINISHED_EVENT", data => { // log.info(data) const duration = Date.now() - startTime[data.meta.index]; log.info("Caught #: " + y + ". Index: " + data.meta.index + ". Time: " + duration / 1000); y++; if (y === 5) { res(); } }); for (let i = 0; i < 5; i++) { startTime[i] = Date.now(); await clientA.transfer({ amount: transfer.amount.div(toBN(10)).toString(), assetId: AddressZero, meta: { index: i }, recipient: clientB.publicIdentifier, }); delay(30000); log.info("i: " + i); } }); */ }); it("client A transfers eth to client B without collateralizing", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); const receiverBal = await clientB.getFreeBalance(transfer.assetId); expect(receiverBal[clientB.nodeSignerAddress].lt(transfer.amount)).to.be.true; await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); }); it("client A transfers tokens to client B without collateralizing", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); }); it("Bot A tries to transfer a negative amount", async () => { await fundChannel(clientA, ETH_AMOUNT_MD, tokenAddress); // verify collateral await clientB.requestCollateral(tokenAddress); const amount = ETH_AMOUNT_SM.mul(-1).toString(); await expect( clientA.transfer({ amount, assetId: tokenAddress, recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith(`Will not accept transfer install where initiator deposit is <= 0`); }); it("Bot A tries to transfer with an invalid token address", async () => { await fundChannel(clientA, ETH_AMOUNT_SM, tokenAddress); const amount = ETH_AMOUNT_SM.toString(); const assetId = "0xabc"; await expect( clientA.transfer({ amount, assetId, recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith(`invalid address`); // NOTE: will also include a `Value (..) is not less than or equal to 0 // because it will not be able to fetch the free balance of the assetId }); // TODO: Fix race condition in this one it.skip("Bot A transfers w a valid, unsupported token address", async () => { // deploy a token const factory = ContractFactory.fromSolidity(tokenArtifacts); const token = await factory .connect(Wallet.fromMnemonic(FUNDED_MNEMONICS[0]).connect(ethProvider)) .deploy(); const deployHash = token.deployTransaction.hash; expect(deployHash).to.exist; await ethProvider.waitForTransaction(token.deployTransaction.hash!); // mint token to client await token.mint(clientA.signerAddress, TOKEN_AMOUNT); // assert sender balance const senderBal = await token.balanceOf(clientA.signerAddress); expect(senderBal).to.equal(TOKEN_AMOUNT); // fund channel await fundChannel(clientA, ETH_AMOUNT_LG, token.address); await expect( clientA.transfer({ amount: ETH_AMOUNT_LG.toString(), assetId: token.address, recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith("Install failed"); // NOTE: you will not get a more descriptive title // because the node maintains the valid tokens list }); it("Bot A tries to transfer with invalid recipient identifier", async () => { await fundChannel(clientA, ETH_AMOUNT_SM, tokenAddress); const recipient = "nope"; await expect( clientA.transfer({ amount: ETH_AMOUNT_SM.toString(), assetId: tokenAddress, recipient, }), ).to.be.rejectedWith(`Invalid checksum`); }); it("Bot A tries to transfer an amount greater than they have in their free balance", async () => { const amount = ETH_AMOUNT_SM.toString(); await expect( clientA.transfer({ amount, assetId: tokenAddress, recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith(`Insufficient funds.`); }); // this doesnt really matter anymore since its not encoded in the state it.skip("Bot A tries to transfer with a paymentId that is not 32 bytes", async () => { await fundChannel(clientA, ETH_AMOUNT_SM, tokenAddress); const paymentId = "nope"; await expect( clientA.conditionalTransfer({ amount: ETH_AMOUNT_SM.toString(), assetId: tokenAddress, conditionType: ConditionalTransferTypes.LinkedTransfer, paymentId, preImage: getRandomBytes32(), recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith(`Invalid hex string`); }); it("Bot A tries to transfer with a preImage that is not 32 bytes", async () => { await fundChannel(clientA, ETH_AMOUNT_SM, tokenAddress); const preImage = "nope"; await expect( clientA.conditionalTransfer({ amount: ETH_AMOUNT_SM.toString(), assetId: tokenAddress, conditionType: ConditionalTransferTypes.LinkedTransfer, paymentId: getRandomBytes32(), preImage, recipient: clientB.publicIdentifier, }), ).to.be.rejectedWith(`invalid arrayify value`); }); it("Experimental: Average latency of 10 async transfers with Eth", async () => { const runTime: number[] = []; let sum = 0; const numberOfRuns = 5; const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount.mul(25), transfer.assetId); await requestCollateral(clientB, transfer.assetId); for (let i = 0; i < numberOfRuns; i++) { const start = Date.now(); await asyncTransferAsset(clientA, clientB, transfer.amount, transfer.assetId); runTime[i] = Date.now() - start; log.info(`Run: ${i}, Runtime: ${runTime[i]}`); sum = sum + runTime[i]; } log.info(`Average = ${sum / numberOfRuns} ms`); }); });
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace translate_v2 { export interface Options extends GlobalOptions { version: 'v2'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * OAuth bearer token. */ bearer_token?: string; /** * JSONP */ callback?: 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; /** * Pretty-print response. */ pp?: boolean; /** * 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; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Google Cloud Translation API * * The Google Cloud Translation API lets websites and programs integrate with * Google Translate programmatically. * * @example * ```js * const {google} = require('googleapis'); * const translate = google.translate('v2'); * ``` */ export class Translate { context: APIRequestContext; detections: Resource$Detections; languages: Resource$Languages; translations: Resource$Translations; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.detections = new Resource$Detections(this.context); this.languages = new Resource$Languages(this.context); this.translations = new Resource$Translations(this.context); } } export interface Schema$DetectionsListResponse { /** * A detections contains detection results of several text */ detections?: Schema$DetectionsResource[]; } /** * An array of languages which we detect for the given text The most likely language list first. */ export interface Schema$DetectionsResource {} /** * The request message for language detection. */ export interface Schema$DetectLanguageRequest { /** * The input text upon which to perform language detection. Repeat this * parameter to perform language detection on multiple text inputs. */ q?: string[] | null; } /** * The request message for discovering supported languages. */ export interface Schema$GetSupportedLanguagesRequest { /** * The language to use to return localized, human readable names of supported * languages. */ target?: string | null; } export interface Schema$LanguagesListResponse { /** * List of source/target languages supported by the translation API. If target parameter is unspecified, the list is sorted by the ASCII code point order of the language code. If target parameter is specified, the list is sorted by the collation order of the language name in the target language. */ languages?: Schema$LanguagesResource[]; } export interface Schema$LanguagesResource { /** * Supported language code, generally consisting of its ISO 639-1 * identifier. (E.g. 'en', 'ja'). In certain cases, BCP-47 codes including * language + region identifiers are returned (e.g. 'zh-TW' and 'zh-CH') */ language?: string | null; /** * Human readable name of the language localized to the target language. */ name?: string | null; } /** * The main translation request message for the Cloud Translation API. */ export interface Schema$TranslateTextRequest { /** * The format of the source text, in either HTML (default) or plain-text. A * value of "html" indicates HTML and a value of "text" indicates plain-text. */ format?: string | null; /** * The `model` type requested for this translation. Valid values are * listed in public documentation. */ model?: string | null; /** * The input text to translate. Repeat this parameter to perform translation * operations on multiple text inputs. */ q?: string[] | null; /** * The language of the source text, set to one of the language codes listed in * Language Support. If the source language is not specified, the API will * attempt to identify the source language automatically and return it within * the response. */ source?: string | null; /** * The language to use for translation of the input text, set to one of the * language codes listed in Language Support. */ target?: string | null; } /** * The main language translation response message. */ export interface Schema$TranslationsListResponse { /** * Translations contains list of translation results of given text */ translations?: Schema$TranslationsResource[]; } export interface Schema$TranslationsResource { /** * The source language of the initial request, detected automatically, if * no source language was passed within the initial request. If the * source language was passed, auto-detection of the language will not * occur and this field will be empty. */ detectedSourceLanguage?: string | null; /** * The `model` type used for this translation. Valid values are * listed in public documentation. Can be different from requested `model`. * Present only if specific model type was explicitly requested. */ model?: string | null; /** * Text translated into the target language. */ translatedText?: string | null; } export class Resource$Detections { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Detects the language of text within a request. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/translate.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const translate = google.translate('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-translation', * 'https://www.googleapis.com/auth/cloud-platform', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await language.detections.detect({ * // Request body metadata * requestBody: { * // request body parameters * // { * // "q": [] * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "detections": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ detect( params: Params$Resource$Detections$Detect, options: StreamMethodOptions ): GaxiosPromise<Readable>; detect( params?: Params$Resource$Detections$Detect, options?: MethodOptions ): GaxiosPromise<Schema$DetectionsListResponse>; detect( params: Params$Resource$Detections$Detect, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; detect( params: Params$Resource$Detections$Detect, options: | MethodOptions | BodyResponseCallback<Schema$DetectionsListResponse>, callback: BodyResponseCallback<Schema$DetectionsListResponse> ): void; detect( params: Params$Resource$Detections$Detect, callback: BodyResponseCallback<Schema$DetectionsListResponse> ): void; detect(callback: BodyResponseCallback<Schema$DetectionsListResponse>): void; detect( paramsOrCallback?: | Params$Resource$Detections$Detect | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$DetectionsListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Detections$Detect; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Detections$Detect; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://translation.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/language/translate/v2/detect').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$DetectionsListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$DetectionsListResponse>(parameters); } } /** * Detects the language of text within a request. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/translate.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const translate = google.translate('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-translation', * 'https://www.googleapis.com/auth/cloud-platform', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await language.detections.list({ * // The input text upon which to perform language detection. Repeat this * // parameter to perform language detection on multiple text inputs. * q: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "detections": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Detections$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Detections$List, options?: MethodOptions ): GaxiosPromise<Schema$DetectionsListResponse>; list( params: Params$Resource$Detections$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Detections$List, options: | MethodOptions | BodyResponseCallback<Schema$DetectionsListResponse>, callback: BodyResponseCallback<Schema$DetectionsListResponse> ): void; list( params: Params$Resource$Detections$List, callback: BodyResponseCallback<Schema$DetectionsListResponse> ): void; list(callback: BodyResponseCallback<Schema$DetectionsListResponse>): void; list( paramsOrCallback?: | Params$Resource$Detections$List | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$DetectionsListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$DetectionsListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Detections$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Detections$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://translation.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/language/translate/v2/detect').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['q'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$DetectionsListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$DetectionsListResponse>(parameters); } } } export interface Params$Resource$Detections$Detect extends StandardParameters { /** * Request body metadata */ requestBody?: Schema$DetectLanguageRequest; } export interface Params$Resource$Detections$List extends StandardParameters { /** * The input text upon which to perform language detection. Repeat this * parameter to perform language detection on multiple text inputs. */ q?: string[]; } export class Resource$Languages { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns a list of supported languages for translation. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/translate.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const translate = google.translate('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-translation', * 'https://www.googleapis.com/auth/cloud-platform', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await language.languages.list({ * // The model type for which supported languages should be returned. * model: 'placeholder-value', * // The language to use to return localized, human readable names of supported * // languages. * target: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "languages": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Languages$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Languages$List, options?: MethodOptions ): GaxiosPromise<Schema$LanguagesListResponse>; list( params: Params$Resource$Languages$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Languages$List, options: | MethodOptions | BodyResponseCallback<Schema$LanguagesListResponse>, callback: BodyResponseCallback<Schema$LanguagesListResponse> ): void; list( params: Params$Resource$Languages$List, callback: BodyResponseCallback<Schema$LanguagesListResponse> ): void; list(callback: BodyResponseCallback<Schema$LanguagesListResponse>): void; list( paramsOrCallback?: | Params$Resource$Languages$List | BodyResponseCallback<Schema$LanguagesListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$LanguagesListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$LanguagesListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$LanguagesListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Languages$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Languages$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://translation.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/language/translate/v2/languages').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$LanguagesListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$LanguagesListResponse>(parameters); } } } export interface Params$Resource$Languages$List extends StandardParameters { /** * The model type for which supported languages should be returned. */ model?: string; /** * The language to use to return localized, human readable names of supported * languages. */ target?: string; } export class Resource$Translations { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Translates input text, returning translated text. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/translate.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const translate = google.translate('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-translation', * 'https://www.googleapis.com/auth/cloud-platform', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await language.translations.list({ * // The customization id for translate * cid: 'placeholder-value', * // The format of the source text, in either HTML (default) or plain-text. A * // value of "html" indicates HTML and a value of "text" indicates plain-text. * format: 'placeholder-value', * // The `model` type requested for this translation. Valid values are * // listed in public documentation. * model: 'placeholder-value', * // The input text to translate. Repeat this parameter to perform translation * // operations on multiple text inputs. * q: 'placeholder-value', * // The language of the source text, set to one of the language codes listed in * // Language Support. If the source language is not specified, the API will * // attempt to identify the source language automatically and return it within * // the response. * source: 'placeholder-value', * // The language to use for translation of the input text, set to one of the * // language codes listed in Language Support. * target: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "translations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Translations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Translations$List, options?: MethodOptions ): GaxiosPromise<Schema$TranslationsListResponse>; list( params: Params$Resource$Translations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Translations$List, options: | MethodOptions | BodyResponseCallback<Schema$TranslationsListResponse>, callback: BodyResponseCallback<Schema$TranslationsListResponse> ): void; list( params: Params$Resource$Translations$List, callback: BodyResponseCallback<Schema$TranslationsListResponse> ): void; list(callback: BodyResponseCallback<Schema$TranslationsListResponse>): void; list( paramsOrCallback?: | Params$Resource$Translations$List | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$TranslationsListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Translations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Translations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://translation.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/language/translate/v2').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['q', 'target'], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$TranslationsListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TranslationsListResponse>(parameters); } } /** * Translates input text, returning translated text. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/translate.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const translate = google.translate('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-translation', * 'https://www.googleapis.com/auth/cloud-platform', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await language.translations.translate({ * // Request body metadata * requestBody: { * // request body parameters * // { * // "format": "my_format", * // "model": "my_model", * // "q": [], * // "source": "my_source", * // "target": "my_target" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "translations": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ translate( params: Params$Resource$Translations$Translate, options: StreamMethodOptions ): GaxiosPromise<Readable>; translate( params?: Params$Resource$Translations$Translate, options?: MethodOptions ): GaxiosPromise<Schema$TranslationsListResponse>; translate( params: Params$Resource$Translations$Translate, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; translate( params: Params$Resource$Translations$Translate, options: | MethodOptions | BodyResponseCallback<Schema$TranslationsListResponse>, callback: BodyResponseCallback<Schema$TranslationsListResponse> ): void; translate( params: Params$Resource$Translations$Translate, callback: BodyResponseCallback<Schema$TranslationsListResponse> ): void; translate( callback: BodyResponseCallback<Schema$TranslationsListResponse> ): void; translate( paramsOrCallback?: | Params$Resource$Translations$Translate | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$TranslationsListResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$TranslationsListResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Translations$Translate; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Translations$Translate; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://translation.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/language/translate/v2').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: [], pathParams: [], context: this.context, }; if (callback) { createAPIRequest<Schema$TranslationsListResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$TranslationsListResponse>(parameters); } } } export interface Params$Resource$Translations$List extends StandardParameters { /** * The customization id for translate */ cid?: string[]; /** * The format of the source text, in either HTML (default) or plain-text. A * value of "html" indicates HTML and a value of "text" indicates plain-text. */ format?: string; /** * The `model` type requested for this translation. Valid values are * listed in public documentation. */ model?: string; /** * The input text to translate. Repeat this parameter to perform translation * operations on multiple text inputs. */ q?: string[]; /** * The language of the source text, set to one of the language codes listed in * Language Support. If the source language is not specified, the API will * attempt to identify the source language automatically and return it within * the response. */ source?: string; /** * The language to use for translation of the input text, set to one of the * language codes listed in Language Support. */ target?: string; } export interface Params$Resource$Translations$Translate extends StandardParameters { /** * Request body metadata */ requestBody?: Schema$TranslateTextRequest; } }
the_stack
import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, Inject, Input, OnDestroy, OnInit, Output, QueryList } from '@angular/core'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; import { COLOR_STRING_FORMAT, ColorStringFormat, EMPTY_COLOR, ENABLE_ALPHA_SELECTOR, MccColorPickerUsedColorPosition } from './color-picker.types'; import { MccColorPickerCollectionComponent } from './color-picker-collection.component'; import { MccColorPickerService } from './color-picker.service'; import { MccColorPickerCollectionService } from './color-picker-collection.service'; import { formatColor, parseColorString } from './color-picker.utils'; @Component({ selector: 'mcc-color-picker', templateUrl: './color-picker.component.html', styleUrls: ['./color-picker.component.scss'], preserveWhitespaces: false, changeDetection: ChangeDetectionStrategy.OnPush, providers: [MccColorPickerCollectionService] }) export class MccColorPickerComponent implements AfterContentInit, OnInit, OnDestroy { /** * Get all collections */ @ContentChildren(MccColorPickerCollectionComponent) _collections: QueryList<MccColorPickerCollectionComponent>; /** * Disable color-picker of showing up */ @Input() set disabled(disabled: boolean) { this._disabled = coerceBooleanProperty(disabled); } get disabled(): boolean { return this._disabled; } private _disabled: boolean = false; static ngAcceptInputType_disabled: boolean | string; /** * Change label of the collection UsedColors */ @Input() get usedColorLabel(): string { return this._usedColorLabel; } set usedColorLabel(value: string) { this._usedColorLabel = value; } private _usedColorLabel: string = 'Used Colors'; /** * Set initial value for used color */ @Input() set usedColorStart(colors: string[]) { if (colors && colors.length > 0) { for (const color of colors) { this.colorPickerService.addColor(color); } } } /** * Set usedColor to be used in reverse */ @Input() set reverseUsedColors(reverse: boolean) { this._reverseUsedColor = coerceBooleanProperty(reverse); } get reverseUsedColors(): boolean { return this._reverseUsedColor; } private _reverseUsedColor: boolean = false; static ngAcceptInputType_reverseUsedColors: boolean | string; /** * Set position of used colors collection */ @Input() set usedColorsPosition(position: MccColorPickerUsedColorPosition) { this._usedColorsPosition = position; } get usedColorsPosition(): MccColorPickerUsedColorPosition { return this._usedColorsPosition; } private _usedColorsPosition: MccColorPickerUsedColorPosition = 'top'; /** * Hide the hexadecimal color forms. */ @Input() set hideHexForms(value: boolean) { this._hideHexForms = coerceBooleanProperty(value); } get hideHexForms(): boolean { return this._hideHexForms; } private _hideHexForms: boolean = false; static ngAcceptInputType_hideHexForms: boolean | string; /** * Hide empty slots from the collection UsedColors */ @Input('hideEmptyUsedColors') set hideEmpty(value: boolean) { this._hideEmpty = coerceBooleanProperty(value); } get hideEmpty(): boolean { return this._hideEmpty; } private _hideEmpty: boolean = false; static ngAcceptInputType_hideEmpty: boolean | string; /** * Hide transparent option of UsedColors */ @Input('hideTransparentUsedColors') set hideTransparent(value: boolean) { this._hideTransparent = coerceBooleanProperty(value); } get hideTransparent(): boolean { return this._hideTransparent; } private _hideTransparent: boolean = false; static ngAcceptInputType_hideTransparent: boolean | string; /** * Hide UsedColors collection */ @Input('hideUsedColors') set hideUsedColors(value: boolean) { this._hideUsedColors = coerceBooleanProperty(value); } get hideUsedColors(): boolean { return this._hideUsedColors; } private _hideUsedColors: boolean = false; static ngAcceptInputType_hideUsedColors: boolean | string; /** * Start with a color selected */ @Input() get selectedColor(): string { return this._selectedColor; } set selectedColor(value: string) { if (this._selectedColor !== value) { this.changeDetectorRef.markForCheck(); } const color = parseColorString(value); if (color) { this._selectedColor = formatColor(color, this.format); } else { this._selectedColor = this.emptyColor; } } private _selectedColor: string; /** * Define if the panel will be initiated open */ @Input() set isOpen(value: boolean) { this._isOpen = coerceBooleanProperty(value); this.changeDetectorRef.detectChanges(); } get isOpen(): boolean { return this._isOpen; } private _isOpen: boolean = false; static ngAcceptInputType_isOpen: boolean | string; /** * Define if the panel will show in overlay or not */ @Input() set overlay(value: boolean) { this._overlay = coerceBooleanProperty(value); } get overlay(): boolean { return this._overlay; } private _overlay: boolean = true; static ngAcceptInputType_overlay: boolean | string; /** * Hide the action buttons (cancel/confirm) */ @Input() set hideButtons(value: boolean) { this._hideButtons = coerceBooleanProperty(value); } get hideButtons(): boolean { return this._hideButtons; } private _hideButtons: boolean = false; static ngAcceptInputType_hideButtons: boolean | string; /** * Define new height for the selector */ @Input() set colorPickerSelectorHeight(height: number) { this._colorPickerSelectorHeight = height; } get colorPickerSelectorHeight(): number { return this._colorPickerSelectorHeight; } private _colorPickerSelectorHeight: number = 170; static ngAcceptInputType_colorPickerSelectorHeight: number | string; /** * Hide the color picker selector */ @Input() set hideColorPickerSelector(value: boolean) { this._hideColorPickerSelector = coerceBooleanProperty(value); } get hideColorPickerSelector(): boolean { return this._hideColorPickerSelector; } private _hideColorPickerSelector: boolean = false; static ngAcceptInputType_hideColorPickerSelector: boolean | string; /** * Set the size of the used colors */ @Input() usedSizeColors: number = 30; static ngAcceptInputType_usedSizeColors: number | string; /** * Change btnCancel label */ @Input() btnCancelLabel: string = 'Cancel'; /** * Change btnConfirm label */ @Input() btnConfirmLabel: string = 'Confirm'; /** * Show alpha selector */ @Input() set alpha(value: boolean) { this._alpha = coerceBooleanProperty(value); } get alpha(): boolean { return this._alpha; } private _alpha: boolean = false; static ngAcceptInputType_alpha: boolean | string; /** * Choose color string format */ @Input() format: ColorStringFormat; /** * Event emitted when user change the selected color (without confirm) */ @Output() readonly change = new EventEmitter<string>(); /** * Event emitted when selected color is confirm */ @Output() readonly selected = new EventEmitter<string>(); /** * Event emitted when is clicked outside of the component */ @Output() readonly clickOut = new EventEmitter<void>(); /** * Event emitted when is clicked outside of the component */ @Output() readonly canceled = new EventEmitter<void>(); /** * Return a Observable with the color the user is picking */ get tmpSelectedColor$(): Observable<string> { return this._tmpSelectedColor.asObservable(); } private _tmpSelectedColor: BehaviorSubject<string>; /** * Observable with all the colors used by the user */ get usedColors$(): Observable<string[]> { return this.colorPickerService.getUsedColors().pipe( map(colors => colors.map(color => { const clr = parseColorString(color); if (this._alpha || clr.getAlpha() === 1) { return formatColor(clr, this.format); } }) ), map(colors => (!this._reverseUsedColor ? colors : [...colors].reverse())) ); } /** * Array of subscriptions from the collections */ private _collectionSubs: Subscription[] = []; constructor( private elementRef: ElementRef, private changeDetectorRef: ChangeDetectorRef, private colorPickerService: MccColorPickerService, private colorPickerCollectionService: MccColorPickerCollectionService, @Inject(EMPTY_COLOR) public emptyColor: string, @Inject(ENABLE_ALPHA_SELECTOR) showAlphaSelector: boolean, @Inject(COLOR_STRING_FORMAT) colorStringFormat: ColorStringFormat ) { this._alpha = showAlphaSelector; this.format = colorStringFormat; } ngOnInit() { this.colorPickerCollectionService.alpha = this._alpha; this.colorPickerCollectionService.format = this.format; if (!this._selectedColor) { this._selectedColor = this.emptyColor; } this._tmpSelectedColor = new BehaviorSubject<string>(this._selectedColor); } /** * Walk throw all collections and subcribe to changes */ ngAfterContentInit() { if (this._collections) { this._collections.forEach((collection: MccColorPickerCollectionComponent) => { const subscription = collection.changeColor.subscribe(color => { this.updateTmpSelectedColor(color); }); this._collectionSubs.push(subscription); }); } // change selected color on service this.selected.subscribe(color => this.colorPickerCollectionService.changeSelectedColor(color)); } /** * Destroy all subscriptions */ ngOnDestroy() { if (this._collectionSubs) { this._collectionSubs.forEach((subscription: Subscription) => { if (subscription && !subscription.closed) { subscription.unsubscribe(); } }); } } /** * Update selected color and emit the change */ private _updateSelectedColor() { if (this._isOpen || !this.overlay) { const color = this._tmpSelectedColor.getValue(); if (this._selectedColor !== color) { this._selectedColor = color; this.selected.emit(color); } else { this.selected.emit(color); } } } /** * Open/close color picker panel */ toggle() { if (!this._disabled) { this._isOpen = !this._isOpen; if (this._selectedColor !== this.emptyColor) { this.colorPickerService.addColor(this._selectedColor); } this.colorPickerCollectionService.changeSelectedColor(this._selectedColor); } } /** * Update selected color, close the panel and notify the user */ backdropClick(): void { if (this._hideButtons) { this.confirmSelectedColor(); } else { this.cancelSelection(); } this.clickOut.emit(); this.changeDetectorRef.detectChanges(); } /** * Update tmpSelectedColor * @param color string */ updateTmpSelectedColor(color: string) { const clr = parseColorString(color); const clrString = color === this.emptyColor ? color : formatColor(clr, this.format); this._tmpSelectedColor.next(clrString); if (this._selectedColor !== clrString) { this.change.emit(clrString); if (this._hideButtons) { this._updateSelectedColor(); } } } /** * Cancel the selection and close the panel */ cancelSelection() { this._tmpSelectedColor.next(this._selectedColor); this.colorPickerCollectionService.changeSelectedColor(this.selectedColor); this.canceled.emit(); this.toggle(); } /** * Update selectedColor and close the panel */ confirmSelectedColor() { this._updateSelectedColor(); this.toggle(); } }
the_stack
import { ILogger, onResolve } from '@aurelia/kernel'; import { IHydratedController, LifecycleFlags, ICustomElementController, Controller } from '@aurelia/runtime-html'; import { IViewport } from './resources/viewport.js'; import { ComponentAgent } from './component-agent.js'; import { processResidue, getDynamicChildren, RouteNode } from './route-tree.js'; import { IRouteContext } from './route-context.js'; import { Transition, ResolutionMode, NavigationOptions } from './router.js'; import { TransitionPlan } from './route.js'; import { Batch, mergeDistinct } from './util.js'; export class ViewportRequest { public constructor( public readonly viewportName: string, public readonly componentName: string, public readonly resolution: ResolutionMode, public readonly append: boolean, ) { } public static create(input: ViewportRequest): ViewportRequest { return new ViewportRequest( input.viewportName, input.componentName, input.resolution, input.append, ); } public toString(): string { return `VR(viewport:'${this.viewportName}',component:'${this.componentName}',resolution:'${this.resolution}',append:${this.append})`; } } const viewportAgentLookup: WeakMap<object, ViewportAgent> = new WeakMap(); export class ViewportAgent { private readonly logger: ILogger; private isActive: boolean = false; private curCA: ComponentAgent | null = null; private nextCA: ComponentAgent | null = null; private get $state(): string { return $state(this.state); } private state: State = State.bothAreEmpty; private get currState(): CurrState { return this.state & State.curr; } private set currState(state: CurrState) { this.state = (this.state & State.next) | state; } private get nextState(): NextState { return this.state & State.next; } private set nextState(state: NextState) { this.state = (this.state & State.curr) | state; } private $resolution: ResolutionMode = 'dynamic'; private $plan: TransitionPlan = 'replace'; private currNode: RouteNode | null = null; private nextNode: RouteNode | null = null; private currTransition: Transition | null = null; private prevTransition: Transition | null = null; public constructor( public readonly viewport: IViewport, public readonly hostController: ICustomElementController, public readonly ctx: IRouteContext, ) { this.logger = ctx.container.get(ILogger).scopeTo(`ViewportAgent<${ctx.friendlyPath}>`); this.logger.trace(`constructor()`); } public static for(viewport: IViewport, ctx: IRouteContext): ViewportAgent { let viewportAgent = viewportAgentLookup.get(viewport); if (viewportAgent === void 0) { const controller = Controller.getCachedOrThrow<IViewport>(viewport); viewportAgentLookup.set( viewport, viewportAgent = new ViewportAgent(viewport, controller, ctx) ); } return viewportAgent; } public activateFromViewport(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags): void | Promise<void> { const tr = this.currTransition; if (tr !== null) { ensureTransitionHasNotErrored(tr); } this.isActive = true; switch (this.nextState) { case State.nextIsEmpty: switch (this.currState) { case State.currIsEmpty: this.logger.trace(`activateFromViewport() - nothing to activate at %s`, this); return; case State.currIsActive: this.logger.trace(`activateFromViewport() - activating existing componentAgent at %s`, this); return this.curCA!.activate(initiator, parent, flags); default: this.unexpectedState('activateFromViewport 1'); } case State.nextLoadDone: { if (this.currTransition === null) { throw new Error(`Unexpected viewport activation outside of a transition context at ${this}`); } if (this.$resolution !== 'static') { throw new Error(`Unexpected viewport activation at ${this}`); } this.logger.trace(`activateFromViewport() - running ordinary activate at %s`, this); const b = Batch.start(b1 => { this.activate(initiator, this.currTransition!, b1); }); const p = new Promise<void>(resolve => { b.continueWith(() => { resolve(); }); }); return b.start().done ? void 0 : p; } default: this.unexpectedState('activateFromViewport 2'); } } public deactivateFromViewport(initiator: IHydratedController, parent: IHydratedController, flags: LifecycleFlags): void | Promise<void> { const tr = this.currTransition; if (tr !== null) { ensureTransitionHasNotErrored(tr); } this.isActive = false; switch (this.currState) { case State.currIsEmpty: this.logger.trace(`deactivateFromViewport() - nothing to deactivate at %s`, this); return; case State.currIsActive: this.logger.trace(`deactivateFromViewport() - deactivating existing componentAgent at %s`, this); return this.curCA!.deactivate(initiator, parent, flags); case State.currDeactivate: // This will happen with bottom-up deactivation because the child is already deactivated, the parent // again tries to deactivate the child (that would be this viewport) but the router hasn't finalized the transition yet. // Since this is viewport was already deactivated, and we know the precise circumstance under which that happens, we can safely ignore the call. this.logger.trace(`deactivateFromViewport() - already deactivating at %s`, this); return; default: { if (this.currTransition === null) { throw new Error(`Unexpected viewport deactivation outside of a transition context at ${this}`); } this.logger.trace(`deactivateFromViewport() - running ordinary deactivate at %s`, this); const b = Batch.start(b1 => { this.deactivate(initiator, this.currTransition!, b1); }); const p = new Promise<void>(resolve => { b.continueWith(() => { resolve(); }); }); return b.start().done ? void 0 : p; } } } public handles(req: ViewportRequest): boolean { if (!this.isAvailable(req.resolution)) { return false; } if (req.append && this.currState === State.currIsActive) { this.logger.trace(`handles(req:%s) -> false (append mode, viewport already has content %s)`, req, this.curCA); return false; } if (req.viewportName.length > 0 && this.viewport.name !== req.viewportName) { this.logger.trace(`handles(req:%s) -> false (names don't match)`, req); return false; } if (this.viewport.usedBy.length > 0 && !this.viewport.usedBy.split(',').includes(req.componentName)) { this.logger.trace(`handles(req:%s) -> false (componentName not included in usedBy)`, req); return false; } this.logger.trace(`handles(req:%s) -> true`, req); return true; } public isAvailable(resolution: ResolutionMode): boolean { if (resolution === 'dynamic' && !this.isActive) { this.logger.trace(`isAvailable(resolution:%s) -> false (viewport is not active and we're in dynamic resolution resolution)`, resolution); return false; } if (this.nextState !== State.nextIsEmpty) { this.logger.trace(`isAvailable(resolution:%s) -> false (update already scheduled for %s)`, resolution, this.nextNode); return false; } return true; } public canUnload(tr: Transition, b: Batch): void { if (this.currTransition === null) { this.currTransition = tr; } ensureTransitionHasNotErrored(tr); if (tr.guardsResult !== true) { return; } b.push(); // run canUnload bottom-up Batch.start(b1 => { this.logger.trace(`canUnload() - invoking on children at %s`, this); for (const node of this.currNode!.children) { node.context.vpa.canUnload(tr, b1); } }).continueWith(b1 => { switch (this.currState) { case State.currIsActive: this.logger.trace(`canUnload() - invoking on existing component at %s`, this); switch (this.$plan) { case 'none': this.currState = State.currCanUnloadDone; return; case 'invoke-lifecycles': case 'replace': this.currState = State.currCanUnload; b1.push(); Batch.start(b2 => { this.logger.trace(`canUnload() - finished invoking on children, now invoking on own component at %s`, this); this.curCA!.canUnload(tr, this.nextNode, b2); }).continueWith(() => { this.logger.trace(`canUnload() - finished at %s`, this); this.currState = State.currCanUnloadDone; b1.pop(); }).start(); return; } case State.currIsEmpty: this.logger.trace(`canUnload() - nothing to unload at %s`, this); return; default: tr.handleError(new Error(`Unexpected state at canUnload of ${this}`)); } }).continueWith(() => { b.pop(); }).start(); } public canLoad(tr: Transition, b: Batch): void { if (this.currTransition === null) { this.currTransition = tr; } ensureTransitionHasNotErrored(tr); if (tr.guardsResult !== true) { return; } b.push(); // run canLoad top-down Batch.start(b1 => { switch (this.nextState) { case State.nextIsScheduled: this.logger.trace(`canLoad() - invoking on new component at %s`, this); this.nextState = State.nextCanLoad; switch (this.$plan) { case 'none': return; case 'invoke-lifecycles': return this.curCA!.canLoad(tr, this.nextNode!, b1); case 'replace': this.nextCA = this.nextNode!.context.createComponentAgent(this.hostController, this.nextNode!); return this.nextCA.canLoad(tr, this.nextNode!, b1); } case State.nextIsEmpty: this.logger.trace(`canLoad() - nothing to load at %s`, this); return; default: this.unexpectedState('canLoad'); } }).continueWith(b1 => { const next = this.nextNode!; switch (this.$plan) { case 'none': case 'invoke-lifecycles': this.logger.trace(`canLoad(next:%s) - plan set to '%s', compiling residue`, next, this.$plan); // These plans can only occur if there is already a current component active in this viewport, // and it is the same component as `next`. // This means the RouteContext of `next` was created during a previous transition and might contain // already-active children. If that is the case, we want to eagerly call the router hooks on them during the // first pass of activation, instead of lazily in a later pass after `processResidue`. // By calling `compileResidue` here on the current context, we're ensuring that such nodes are created and // their target viewports have the appropriate updates scheduled. b1.push(); void onResolve(processResidue(next), () => { b1.pop(); }); return; case 'replace': // In the case of 'replace', always process this node and its subtree as if it's a new one switch (this.$resolution) { case 'dynamic': // Residue compilation will happen at `ViewportAgent#processResidue` this.logger.trace(`canLoad(next:%s) - (resolution: 'dynamic'), delaying residue compilation until activate`, next, this.$plan); return; case 'static': this.logger.trace(`canLoad(next:%s) - (resolution: '${this.$resolution}'), creating nextCA and compiling residue`, next, this.$plan); b1.push(); void onResolve(processResidue(next), () => { b1.pop(); }); return; } } }).continueWith(b1 => { switch (this.nextState) { case State.nextCanLoad: this.logger.trace(`canLoad() - finished own component, now invoking on children at %s`, this); this.nextState = State.nextCanLoadDone; for (const node of this.nextNode!.children) { node.context.vpa.canLoad(tr, b1); } return; case State.nextIsEmpty: return; default: this.unexpectedState('canLoad'); } }).continueWith(() => { this.logger.trace(`canLoad() - finished at %s`, this); b.pop(); }).start(); } public unload(tr: Transition, b: Batch): void { ensureTransitionHasNotErrored(tr); ensureGuardsResultIsTrue(this, tr); b.push(); // run unload bottom-up Batch.start(b1 => { this.logger.trace(`unload() - invoking on children at %s`, this); for (const node of this.currNode!.children) { node.context.vpa.unload(tr, b1); } }).continueWith(b1 => { switch (this.currState) { case State.currCanUnloadDone: this.logger.trace(`unload() - invoking on existing component at %s`, this); switch (this.$plan) { case 'none': this.currState = State.currUnloadDone; return; case 'invoke-lifecycles': case 'replace': this.currState = State.currUnload; b1.push(); Batch.start(b2 => { this.logger.trace(`unload() - finished invoking on children, now invoking on own component at %s`, this); this.curCA!.unload(tr, this.nextNode, b2); }).continueWith(() => { this.logger.trace(`unload() - finished at %s`, this); this.currState = State.currUnloadDone; b1.pop(); }).start(); return; } case State.currIsEmpty: this.logger.trace(`unload() - nothing to unload at %s`, this); for (const node of this.currNode!.children) { node.context.vpa.unload(tr, b); } return; default: this.unexpectedState('unload'); } }).continueWith(() => { b.pop(); }).start(); } public load(tr: Transition, b: Batch): void { ensureTransitionHasNotErrored(tr); ensureGuardsResultIsTrue(this, tr); b.push(); // run load top-down Batch.start(b1 => { switch (this.nextState) { case State.nextCanLoadDone: { this.logger.trace(`load() - invoking on new component at %s`, this); this.nextState = State.nextLoad; switch (this.$plan) { case 'none': return; case 'invoke-lifecycles': return this.curCA!.load(tr, this.nextNode!, b1); case 'replace': return this.nextCA!.load(tr, this.nextNode!, b1); } } case State.nextIsEmpty: this.logger.trace(`load() - nothing to load at %s`, this); return; default: this.unexpectedState('load'); } }).continueWith(b1 => { switch (this.nextState) { case State.nextLoad: this.logger.trace(`load() - finished own component, now invoking on children at %s`, this); this.nextState = State.nextLoadDone; for (const node of this.nextNode!.children) { node.context.vpa.load(tr, b1); } return; case State.nextIsEmpty: return; default: this.unexpectedState('load'); } }).continueWith(() => { this.logger.trace(`load() - finished at %s`, this); b.pop(); }).start(); } public deactivate(initiator: IHydratedController | null, tr: Transition, b: Batch): void { ensureTransitionHasNotErrored(tr); ensureGuardsResultIsTrue(this, tr); b.push(); switch (this.currState) { case State.currUnloadDone: this.logger.trace(`deactivate() - invoking on existing component at %s`, this); this.currState = State.currDeactivate; switch (this.$plan) { case 'none': case 'invoke-lifecycles': b.pop(); return; case 'replace': { const controller = this.hostController; const deactivateFlags = this.viewport.stateful ? LifecycleFlags.none : LifecycleFlags.dispose; tr.run(() => { return this.curCA!.deactivate(initiator, controller, deactivateFlags); }, () => { b.pop(); }); } } return; case State.currIsEmpty: this.logger.trace(`deactivate() - nothing to deactivate at %s`, this); b.pop(); return; case State.currDeactivate: this.logger.trace(`deactivate() - already deactivating at %s`, this); b.pop(); return; default: this.unexpectedState('deactivate'); } } public activate(initiator: IHydratedController | null, tr: Transition, b: Batch): void { ensureTransitionHasNotErrored(tr); ensureGuardsResultIsTrue(this, tr); b.push(); if ( this.nextState === State.nextIsScheduled && this.$resolution === 'dynamic' ) { this.logger.trace(`activate() - invoking canLoad(), load() and activate() on new component due to resolution 'dynamic' at %s`, this); // This is the default v2 mode "lazy loading" situation Batch.start(b1 => { this.canLoad(tr, b1); }).continueWith(b1 => { this.load(tr, b1); }).continueWith(b1 => { this.activate(initiator, tr, b1); }).continueWith(() => { b.pop(); }).start(); return; } switch (this.nextState) { case State.nextLoadDone: this.logger.trace(`activate() - invoking on existing component at %s`, this); this.nextState = State.nextActivate; // run activate top-down Batch.start(b1 => { switch (this.$plan) { case 'none': case 'invoke-lifecycles': return; case 'replace': { const controller = this.hostController; const activateFlags = LifecycleFlags.none; tr.run(() => { b1.push(); return this.nextCA!.activate(initiator, controller, activateFlags); }, () => { b1.pop(); }); } } }).continueWith(b1 => { this.processDynamicChildren(tr, b1); }).continueWith(() => { b.pop(); }).start(); return; case State.nextIsEmpty: this.logger.trace(`activate() - nothing to activate at %s`, this); b.pop(); return; default: this.unexpectedState('activate'); } } public swap(tr: Transition, b: Batch): void { if (this.currState === State.currIsEmpty) { this.logger.trace(`swap() - running activate on next instead, because there is nothing to deactivate at %s`, this); this.activate(null, tr, b); return; } if (this.nextState === State.nextIsEmpty) { this.logger.trace(`swap() - running deactivate on current instead, because there is nothing to activate at %s`, this); this.deactivate(null, tr, b); return; } ensureTransitionHasNotErrored(tr); ensureGuardsResultIsTrue(this, tr); if (!( this.currState === State.currUnloadDone && this.nextState === State.nextLoadDone )) { this.unexpectedState('swap'); } this.currState = State.currDeactivate; this.nextState = State.nextActivate; switch (this.$plan) { case 'none': case 'invoke-lifecycles': { this.logger.trace(`swap() - skipping this level and swapping children instead at %s`, this); const nodes = mergeDistinct(this.nextNode!.children, this.currNode!.children); for (const node of nodes) { node.context.vpa.swap(tr, b); } return; } case 'replace': { this.logger.trace(`swap() - running normally at %s`, this); const controller = this.hostController; const curCA = this.curCA!; const nextCA = this.nextCA!; const deactivateFlags = this.viewport.stateful ? LifecycleFlags.none : LifecycleFlags.dispose; const activateFlags = LifecycleFlags.none; b.push(); switch (tr.options.swapStrategy) { case 'sequential-add-first': Batch.start(b1 => { tr.run(() => { b1.push(); return nextCA.activate(null, controller, activateFlags); }, () => { b1.pop(); }); }).continueWith(b1 => { this.processDynamicChildren(tr, b1); }).continueWith(() => { tr.run(() => { return curCA.deactivate(null, controller, deactivateFlags); }, () => { b.pop(); }); }).start(); return; case 'sequential-remove-first': Batch.start(b1 => { tr.run(() => { b1.push(); return curCA.deactivate(null, controller, deactivateFlags); }, () => { b1.pop(); }); }).continueWith(b1 => { tr.run(() => { b1.push(); return nextCA.activate(null, controller, activateFlags); }, () => { b1.pop(); }); }).continueWith(b1 => { this.processDynamicChildren(tr, b1); }).continueWith(() => { b.pop(); }).start(); return; case 'parallel-remove-first': tr.run(() => { b.push(); return curCA.deactivate(null, controller, deactivateFlags); }, () => { b.pop(); }); Batch.start(b1 => { tr.run(() => { b1.push(); return nextCA.activate(null, controller, activateFlags); }, () => { b1.pop(); }); }).continueWith(b1 => { this.processDynamicChildren(tr, b1); }).continueWith(() => { b.pop(); }).start(); return; } } } } private processDynamicChildren(tr: Transition, b: Batch): void { this.logger.trace(`processDynamicChildren() - %s`, this); const next = this.nextNode!; tr.run(() => { b.push(); return getDynamicChildren(next); }, newChildren => { Batch.start(b1 => { for (const node of newChildren) { tr.run(() => { b1.push(); return node.context.vpa.canLoad(tr, b1); }, () => { b1.pop(); }); } }).continueWith(b1 => { for (const node of newChildren) { tr.run(() => { b1.push(); return node.context.vpa.load(tr, b1); }, () => { b1.pop(); }); } }).continueWith(b1 => { for (const node of newChildren) { tr.run(() => { b1.push(); return node.context.vpa.activate(null, tr, b1); }, () => { b1.pop(); }); } }).continueWith(() => { b.pop(); }).start(); }); } public scheduleUpdate(options: NavigationOptions, next: RouteNode): void | Promise<void> { switch (this.nextState) { case State.nextIsEmpty: this.nextNode = next; this.nextState = State.nextIsScheduled; this.$resolution = options.resolutionMode; break; default: this.unexpectedState('scheduleUpdate 1'); } switch (this.currState) { case State.currIsEmpty: case State.currIsActive: case State.currCanUnloadDone: break; default: this.unexpectedState('scheduleUpdate 2'); } const cur = this.curCA?.routeNode ?? null; if (cur === null || cur.component !== next.component) { // Component changed (or is cleared), so set to 'replace' this.$plan = 'replace'; } else { // Component is the same, so determine plan based on config and/or convention const plan = next.context.definition.config.transitionPlan; if (typeof plan === 'function') { this.$plan = plan(cur, next); } else { this.$plan = plan; } } this.logger.trace(`scheduleUpdate(next:%s) - plan set to '%s'`, next, this.$plan); } public cancelUpdate(): void { if (this.currNode !== null) { this.currNode.children.forEach(function (node) { node.context.vpa.cancelUpdate(); }); } if (this.nextNode !== null) { this.nextNode.children.forEach(function (node) { node.context.vpa.cancelUpdate(); }); } this.logger.trace(`cancelUpdate(nextNode:%s)`, this.nextNode); switch (this.currState) { case State.currIsEmpty: case State.currIsActive: break; case State.currCanUnload: case State.currCanUnloadDone: this.currState = State.currIsActive; break; case State.currUnload: case State.currDeactivate: // TODO: should schedule an 'undo' action break; } switch (this.nextState) { case State.nextIsEmpty: case State.nextIsScheduled: case State.nextCanLoad: case State.nextCanLoadDone: this.nextNode = null; this.nextState = State.nextIsEmpty; break; case State.nextLoad: case State.nextActivate: // TODO: should schedule an 'undo' action break; } } public endTransition(): void { if (this.currNode !== null) { this.currNode.children.forEach(function (node) { node.context.vpa.endTransition(); }); } if (this.nextNode !== null) { this.nextNode.children.forEach(function (node) { node.context.vpa.endTransition(); }); } if (this.currTransition !== null) { ensureTransitionHasNotErrored(this.currTransition); switch (this.nextState) { case State.nextIsEmpty: switch (this.currState) { case State.currDeactivate: this.logger.trace(`endTransition() - setting currState to State.nextIsEmpty at %s`, this); this.currState = State.currIsEmpty; this.curCA = null; break; default: this.unexpectedState('endTransition 1'); } break; case State.nextActivate: switch (this.currState) { case State.currIsEmpty: case State.currDeactivate: switch (this.$plan) { case 'none': case 'invoke-lifecycles': this.logger.trace(`endTransition() - setting currState to State.currIsActive at %s`, this); this.currState = State.currIsActive; break; case 'replace': this.logger.trace(`endTransition() - setting currState to State.currIsActive and reassigning curCA at %s`, this); this.currState = State.currIsActive; this.curCA = this.nextCA; break; } this.currNode = this.nextNode!; break; default: this.unexpectedState('endTransition 2'); } break; default: this.unexpectedState('endTransition 3'); } this.$plan = 'replace'; this.nextState = State.nextIsEmpty; this.nextNode = null; this.nextCA = null; this.prevTransition = this.currTransition; this.currTransition = null; } } public toString(): string { return `VPA(state:${this.$state},plan:'${this.$plan}',resolution:'${this.$resolution}',n:${this.nextNode},c:${this.currNode},viewport:${this.viewport})`; } public dispose(): void { if (this.viewport.stateful /* TODO: incorporate statefulHistoryLength / router opts as well */) { this.logger.trace(`dispose() - not disposing stateful viewport at %s`, this); } else { this.logger.trace(`dispose() - disposing %s`, this); this.curCA?.dispose(); } } private unexpectedState(label: string): never { throw new Error(`Unexpected state at ${label} of ${this}`); } } function ensureGuardsResultIsTrue(vpa: ViewportAgent, tr: Transition): void { if (tr.guardsResult !== true) { throw new Error(`Unexpected guardsResult ${tr.guardsResult} at ${vpa}`); } } function ensureTransitionHasNotErrored(tr: Transition): void { if (tr.error !== void 0) { throw tr.error; } } const enum State { curr = 0b1111111_0000000, currIsEmpty = 0b1000000_0000000, currIsActive = 0b0100000_0000000, currCanUnload = 0b0010000_0000000, currCanUnloadDone = 0b0001000_0000000, currUnload = 0b0000100_0000000, currUnloadDone = 0b0000010_0000000, currDeactivate = 0b0000001_0000000, next = 0b0000000_1111111, nextIsEmpty = 0b0000000_1000000, nextIsScheduled = 0b0000000_0100000, nextCanLoad = 0b0000000_0010000, nextCanLoadDone = 0b0000000_0001000, nextLoad = 0b0000000_0000100, nextLoadDone = 0b0000000_0000010, nextActivate = 0b0000000_0000001, bothAreEmpty = 0b1000000_1000000, } type CurrState = ( State.currIsEmpty | State.currIsActive | State.currCanUnload | State.currCanUnloadDone | State.currUnload | State.currUnloadDone | State.currDeactivate ); type NextState = ( State.nextIsEmpty | State.nextIsScheduled | State.nextCanLoad | State.nextCanLoadDone | State.nextLoad | State.nextLoadDone | State.nextActivate ); // Stringifying uses arrays and does not have a negligible cost, so cache the results to not let trace logging // in and of its own slow things down too much. const $stateCache = new Map<State, string>(); function $state(state: State): string { let str = $stateCache.get(state); if (str === void 0) { $stateCache.set(state, str = stringifyState(state)); } return str; } function stringifyState(state: State): string { const flags: string[] = []; if ((state & State.currIsEmpty) === State.currIsEmpty) { flags.push('currIsEmpty'); } if ((state & State.currIsActive) === State.currIsActive) { flags.push('currIsActive'); } if ((state & State.currCanUnload) === State.currCanUnload) { flags.push('currCanUnload'); } if ((state & State.currCanUnloadDone) === State.currCanUnloadDone) { flags.push('currCanUnloadDone'); } if ((state & State.currUnload) === State.currUnload) { flags.push('currUnload'); } if ((state & State.currUnloadDone) === State.currUnloadDone) { flags.push('currUnloadDone'); } if ((state & State.currDeactivate) === State.currDeactivate) { flags.push('currDeactivate'); } if ((state & State.nextIsEmpty) === State.nextIsEmpty) { flags.push('nextIsEmpty'); } if ((state & State.nextIsScheduled) === State.nextIsScheduled) { flags.push('nextIsScheduled'); } if ((state & State.nextCanLoad) === State.nextCanLoad) { flags.push('nextCanLoad'); } if ((state & State.nextCanLoadDone) === State.nextCanLoadDone) { flags.push('nextCanLoadDone'); } if ((state & State.nextLoad) === State.nextLoad) { flags.push('nextLoad'); } if ((state & State.nextLoadDone) === State.nextLoadDone) { flags.push('nextLoadDone'); } if ((state & State.nextActivate) === State.nextActivate) { flags.push('nextActivate'); } return flags.join('|'); }
the_stack
import { createElement } from "@syncfusion/ej2-base"; import { BarcodeGenerator } from "../../../src/barcode/barcode"; let barcode: BarcodeGenerator; let ele: HTMLElement; function output(){ // console.log(j + ': { width: ' + parseFloat((children.children[j + 3].getAttribute('width'))).toFixed(2) + ', height: ' // + parseFloat((children.children[j + 3].getAttribute('height'))).toFixed(2) + ', x: ' + // Math.round(Number(children.children[j + 3].getAttribute('x'))) // + ', y:' + Math.round(Number(children.children[j + 3].getAttribute('y')))+'}') } describe('Barcode Control -width', () => { describe('Checking the general rendering of bar code - width testing using pixels', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE' }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using pixels', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.getAttribute('width') === '200'&& barcode.children[0].getAttribute("id") ==="barcode1content").toBe(true); done(); }); }); describe('Checking the general rendering of bar code - width testing using numbers', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using pixels', (done: Function) => { let barcode = document.getElementById('barcode2') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.getAttribute('width') === '200').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - width testing using percentange', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode3' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '50%', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE' }); barcode.appendTo('#barcode3'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using percentange', (done: Function) => { let barcode = document.getElementById('barcode3') let children: HTMLElement = barcode.children[0] as HTMLElement console.log('testcase3') console.log(children.getAttribute('width')) console.log( children.getAttribute('width')) //error expect(children.getAttribute('width') === '632' || children.getAttribute('width') === '379'|| children.getAttribute('width') === '385' || children.getAttribute('width') === '384').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - width testing with no width given', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode4' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE' }); barcode.appendTo('#barcode4'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing with no width given', (done: Function) => { let barcode = document.getElementById('barcode4') let children: HTMLElement = barcode.children[0] as HTMLElement //error console.log('testcase4') console.log(children.getAttribute('width')) console.log(children.getAttribute('width')) expect(children.getAttribute('width') === '1264' || children.getAttribute('width') === '758'|| children.getAttribute('width') === '769' || children.getAttribute('width') === '767').toBe(true); done(); }); }); }); describe('Barcode Control -height', () => { describe('Checking the general rendering of bar code - height testing using pixels', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using pixels', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.getAttribute('height') === '150').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - height testing using numbers', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using pixels', (done: Function) => { let barcode = document.getElementById('barcode2') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.getAttribute('height') === '150').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - height testing without giving height', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode3' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode3'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - height testing without giving number', (done: Function) => { let barcode = document.getElementById('barcode3') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.getAttribute('height') === '100').toBe(true); done(); }); }); }); describe('Barcode Control -fore color', () => { describe('Checking the general rendering of bar code - fore color string value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', foreColor: 'blue', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - fore color string value', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('fill') === 'blue').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - fore color hex value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', foreColor: '#FF33E9', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - fore color hex value', (done: Function) => { let barcode = document.getElementById('barcode2') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('fill') === '#FF33E9').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - fore color invalid string value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', foreColor: 'blued', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - fore color string value', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); describe('Checking the general rendering of bar code - fore color invalid hex value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', foreColor: '#FF33Edcv9', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - fore color hex value', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); }); describe('Barcode Control -BG color', () => { describe('Checking the general rendering of bar code - BG color string value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', mode: 'SVG', height: '150px', backgroundColor: 'blue', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color string value', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[3].getAttribute('width') === '2.535211267605634' && children.children[2].getAttribute('width') === '1.267605633802817' && children.getAttribute('height') === '150' && children.getAttribute('width') === '200' && children.style.background === 'blue' && Math.round(Number(children.children[0].getAttribute('x'))) === 62 //error || Math.round(Number(children.children[0].getAttribute('x'))) === 58 && Math.round(Number(children.children[0].getAttribute('y'))) === 142 && children.children[1].getAttribute('x') === '10' && children.children[1].getAttribute('y') === '10' && Math.round(Number(children.children[children.children.length - 1].getAttribute('x'))) === 189).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - BG color Invalid string value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', backgroundColor: 'bdlue', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color Invalid string value', (done: Function) => { //let value = document.getElementById('barcode'); let barcode = document.getElementById('barcode2') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.style.background === "").toBe(true); done(); }); }); describe('Checking the general rendering of bar code - BG color hex value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode3' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', backgroundColor: '#FF33E9', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode3'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color hex value', (done: Function) => { let barcode = document.getElementById('barcode3') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.style.background === ('rgb(255, 51, 233)')).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - right align', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcoder' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', mode: 'SVG', //backgroundColor: 'red', displayText: { text: 'ABCDABCDABCD', margin: { left: 60, right: 30 } }, }); barcode.appendTo('#barcoder'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - right align', (done: Function) => { let barcode = document.getElementById('barcoder') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 86 && (children.children[0] as HTMLElement).style.fontSize === '8.4px' || (children.children[0] as HTMLElement).style.fontSize === '7.8px').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - BG color invalid hex value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode4' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', backgroundColor: '#FF33Es9', mode: 'SVG', type: 'Code39', value: 'BARCODE' }); barcode.appendTo('#barcode4'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color invalid hex value', (done: Function) => { let barcode = document.getElementById('barcode4') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.style.background === "").toBe(true); done(); }); }); }); describe('Barcode Control - Margin', () => { describe('Checking the general rendering of bar code -Margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 50, right: 50, top: 50, bottom: 50 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -Margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 62 || Math.round(Number(children.children[0].getAttribute('x'))) === 58 && children.children[0].getAttribute('y') === '102' && children.children[1].getAttribute('x') === '50' && children.children[1].getAttribute('y') === '50' && children.children[1].getAttribute('height') === '50' && Math.round(Number(children.children[1].getAttribute('width'))) === 1 && Math.round(Number(children.children[children.children.length - 1].getAttribute('x'))) === 149 && Math.round(Number(children.children[4].getAttribute('x'))) === 56 && Math.round(Number(children.children[4].getAttribute('width'))) === 1 ).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme Margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 90, right: 90, top: 60, bottom: 60 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme Margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '90' && parseFloat((children.children[1].getAttribute('width'))).toFixed(2) === '0.14' && Math.round(Number(children.children[3].getAttribute('x'))) === 91 && parseFloat((children.children[3].getAttribute('width'))).toFixed(2) === '0.28').toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme Margin 2', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 90, right: 90, top: 70, bottom: 70 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme Margin 2', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '90' && parseFloat((children.children[1].getAttribute('width'))).toFixed(2) === '0.14' && (children.children[1].getAttribute('height')) === '10' && Math.round(Number(children.children[11].getAttribute('x'))) === 94 && Math.round(Number(children.children[11].getAttribute('height'))) === 0).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme left - right margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 90, right: 90 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme left - right margin', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); describe('Checking the general rendering of bar code -extreme top - bottom margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 90, right: 90 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme left - right margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '90' && parseFloat((children.children[1].getAttribute('width'))).toFixed(2) === "0.14" && parseFloat((children.children[3].getAttribute('width'))).toFixed(2) === "0.28" && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 110).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme top bottom error margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { top: 90, bottom: 90 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme left - right margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children = barcode.children[0] expect(children.childElementCount === 0).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme left right error margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode111' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 100, right: 120 } }); barcode.appendTo('#barcode111'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme left - right margin', (done: Function) => { let barcode = document.getElementById('barcode111') let children = barcode.children[0] expect(children.childElementCount === 0).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme left negative margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: -40, } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme left negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement // expect(Math.round(Number(children.children[0].getAttribute('x'))) === 7//error 3 // || Math.round(Number(children.children[0].getAttribute('x'))) === 3 // && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 129 // && children.children[1].getAttribute('x') === '-40').toBe(true); expect(Math.round(Number(children.children[0].getAttribute('x'))) === 37 || Math.round(Number(children.children[0].getAttribute('x'))) === 33 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 188 && children.children[1].getAttribute('x') === '-40').toBe(true) done(); }); }); describe('Checking the general rendering of bar code -extreme right negative margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { right: -40, } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme right negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 87//error 83 || Math.round(Number(children.children[0].getAttribute('x'))) === 83 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 238).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme right negative left positive margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', margin: { right: -40, left: 40 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme right negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '40' && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 239).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme right positive left negative margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { right: 40, left: -40 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme right negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '-40' && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 159).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme right negative left negative margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', margin: { right: -40, left: -40 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme right negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '-40' && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 238).toBe(true); done(); }); }); describe('Checking the general rendering of bar code -extreme zero values on all the sides', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', margin: { right: 0, left: 0, top: 0, bottom: 0 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code -extreme right negative margin', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[1].getAttribute('x') === '0' && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 199).toBe(true); done(); }); }); }); describe('Barcode Control - text size', () => { describe('Checking the general rendering of bar code - larger text size', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', displayText: { size: 80 } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color string value', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); describe('Checking the general rendering of bar code - larger display text', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', displayText: { text: 'sdlkdjnv clsjdnf jvknfdknv kjfn kv' } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - BG color string value', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); }); describe('Barcode Control - text size', () => { describe('Checking the general rendering of bar code - text margin left', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { left: 60 } } }); barcode.appendTo('#barcode1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left', (done: Function) => { let barcode = document.getElementById('barcode1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 86).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin right', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { right: 60 } } }); barcode.appendTo('#barcode2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left', (done: Function) => { let barcode = document.getElementById('barcode2') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 37 || Math.round(Number(children.children[0].getAttribute('x'))) === 30 ).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin top', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode3' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { top: 20 } } }); barcode.appendTo('#barcode3'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left', (done: Function) => { let barcode = document.getElementById('barcode3') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 62 || Math.round(Number(children.children[0].getAttribute('x'))) === 58 && children.children[0].getAttribute('y') === '140' && Math.round(Number(children.children[12].getAttribute('height'))) === 96 || Math.round(Number(children.children[12].getAttribute('height'))) === 97).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin bottom', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode4' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { bottom: 20 } } }); barcode.appendTo('#barcode4'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin bottom', (done: Function) => { let barcode = document.getElementById('barcode4') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 62 || Math.round(Number(children.children[0].getAttribute('x'))) === 62 && Math.round(Number(children.children[0].getAttribute('y'))) === 120 && children.children[14].getAttribute('height') === '96' || children.children[14].getAttribute('height') === '96.5').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin left and right', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode5' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { left: 50, right: 50 } } }); barcode.appendTo('#barcode5'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left and right', (done: Function) => { let barcode = document.getElementById('barcode5') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 76 && (children.children[0] as HTMLElement).style.fontSize === '12.2px' || (children.children[0] as HTMLElement).style.fontSize === '11px' ).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin top and bottom', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', displayText: { margin: { top: 50, bottom: 50 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left and right', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(children.children[0].getAttribute('y') === '90' && children.children[14].getAttribute('height') === '16' || children.children[14].getAttribute('height') === '16.5').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin bottom and to', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', displayText: { text: 'ABCDABCD', margin: { bottom: 10, top: 5, } }, }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin left and right', (done: Function) => { let value = document.getElementById('barcode'); done(); }); }); describe('Checking the general rendering of bar code - text margin top bottom left right', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { left: 50, right: 50, top: 50, bottom: 50 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin top bottom left right', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 76 && (children.children[0] as HTMLElement).style.fontSize === '12.2px' || (children.children[0] as HTMLElement).style.fontSize === '11px' && Math.round(Number(children.children[13].getAttribute('height'))) === 16 || Math.round(Number(children.children[13].getAttribute('height'))) === 17).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin negative top value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { top: -10 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin negative top value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(children.children[0].getAttribute('y') === '120' || children.children[0].getAttribute('y') === '130' && Math.round(Number(children.children[18].getAttribute('height'))) === 116 || Math.round(Number(children.children[18].getAttribute('height'))) === 117).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - text margin negative bottom value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { bottom: -10 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin negative top value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('y') === '150' && children.children[17].getAttribute('height') === '116' || children.children[17].getAttribute('height') === '116.5').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - both barcode margin and text margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', mode: 'SVG', margin: { left: 40, right: 40 }, displayText: { margin: { left: 40, right: 40, top: 20, bottom: 20 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - text margin negative top value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(Math.round(Number(children.children[0].getAttribute('x'))) === 91 && (children.children[0] as HTMLElement).style.fontSize === '4.6px' || (children.children[0] as HTMLElement).style.fontSize === '4px' && children.children[1].getAttribute('x') === '40' && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 159 && children.children[18].getAttribute('height') === '76' || children.children[18].getAttribute('height') === '76.5').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - both barcode margin and text margin(invalid)', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 40, right: 40 }, displayText: { margin: { left: 50, right: 50 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - both barcode margin and text margin(invalid)', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 101).toBe(true); done(); }); }); describe('Checking the general rendering of bar code - negative bottom value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { bottom: -100, } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - negative bottom value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('y') === '242').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - negative top value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', displayText: { margin: { top: -100, } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - negative top value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement //error expect(children.children[0].getAttribute('y') === '140' || children.children[0].getAttribute('y') === '42').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - with greater bottom and top value', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', displayText: { margin: { bottom: 80, top: 50 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - negative bottom value', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('y') === '142').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - margin and text margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: 'BARCODE', mode: 'SVG', margin: { top: 40, bottom: 40 }, displayText: { margin: { bottom: 40, } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - margin and text margin', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(children.children[0].getAttribute('y') === '79' || children.children[0].getAttribute('y') === '70' && children.children[1].getAttribute('y') === '40' && children.children[1].getAttribute('height') === '70' && children.children[10].getAttribute('height') === '16' || children.children[10].getAttribute('height') === '16.5' && children.children[10].getAttribute('y') === '40' && children.children[54].getAttribute('height') === '70').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - all four text margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', mode: 'SVG', type: 'Code39', value: 'BARCODE', displayText: { margin: { top: 50, bottom: 50, left: 70, right: 70 } } }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - all four text margin', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 96 && (children.children[0] as HTMLElement).style.fontSize === '1.2px' || (children.children[0] as HTMLElement).style.fontSize === '1.4px' && children.children[11].getAttribute('height') === '16' || children.children[11].getAttribute('height') === '16.5').toBe(true); done(); }); }); describe('Checking the general rendering of bar code - propertychange', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcodeprop' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: '12341', }); barcode.appendTo('#barcodeprop'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - propertychange code39', (done: Function) => { let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 46 && Math.round(Number(children.children[0].getAttribute('x'))) === 70 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 188 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 3 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 184).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 30 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 43 && Math.round(Number(children.children[1].getAttribute('width'))) === 4 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 366 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 4 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 9 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 352).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); it('Checking the general rendering of bar code - propertychange codabar', (done: Function) => { barcode.type = 'Codabar'; barcode.mode= 'SVG' barcode.displayText.visibility = true barcode.displayText.margin.left = 10 barcode.displayText.margin.right=10 barcode.margin.left = 10; barcode.margin.right = 10; barcode.margin.bottom = 10; barcode.width = 200 barcode.height = 150 barcode.margin.top = 10; barcode.mode = 'SVG'; barcode.displayText.text = undefined barcode.value = '1111'; barcode.height = 200; barcode.width = 150; barcode.dataBind() let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 25 && Math.round(Number(children.children[0].getAttribute('x'))) === 51 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 138 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 131).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 20 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 43 && Math.round(Number(children.children[1].getAttribute('width'))) === 13 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 363 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 7 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 7 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 343).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); it('Checking the general rendering of bar code - propertychange code128', (done: Function) => { barcode.type = 'Code128'; barcode.mode= 'SVG' barcode.displayText.visibility = true barcode.displayText.margin.left = 10 barcode.displayText.margin.right=10 barcode.margin.left = 10; barcode.margin.right = 10; barcode.margin.bottom = 10; barcode.width = 200 barcode.height = 150 barcode.margin.top = 10; barcode.mode = 'SVG'; barcode.displayText.text = undefined barcode.value = '1111'; barcode.height = 200; barcode.width = 150; barcode.dataBind() let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 17 && Math.round(Number(children.children[0].getAttribute('x'))) === 51 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 135 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 131).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 19 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 45 && Math.round(Number(children.children[1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 360 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 10 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 350).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); it('Checking the general rendering of bar code - propertychange code128a', (done: Function) => { barcode.type = 'Code128A'; barcode.mode= 'SVG' barcode.displayText.visibility = true barcode.displayText.margin.left = 10 barcode.displayText.margin.right=10 barcode.margin.left = 10; barcode.margin.right = 10; barcode.margin.bottom = 10; barcode.width = 200 barcode.height = 150 barcode.margin.top = 10; barcode.mode = 'SVG'; barcode.displayText.text = undefined barcode.value = '1111'; barcode.height = 200; barcode.width = 150; barcode.dataBind() let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 23 && Math.round(Number(children.children[0].getAttribute('x'))) === 51 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 &&Math.round(Number(children.children[3].getAttribute('x')))===23 && Math.round(Number(children.children[1].getAttribute('width'))) === 3 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 137 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 3 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 133).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 19 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 45 && Math.round(Number(children.children[1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 360 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 10 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 350).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); it('Checking the general rendering of bar code - propertychange code128b', (done: Function) => { barcode.type = 'Code128B'; barcode.mode= 'SVG' barcode.displayText.visibility = true barcode.displayText.margin.left = 10 barcode.displayText.margin.right=10 barcode.margin.left = 10; barcode.margin.right = 10; barcode.margin.bottom = 10; barcode.width = 200 barcode.height = 150 barcode.margin.top = 10; barcode.mode = 'SVG'; barcode.displayText.text = undefined barcode.value = '1111'; barcode.height = 200; barcode.width = 150; barcode.dataBind() let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 23 && Math.round(Number(children.children[0].getAttribute('x'))) === 51 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 &&Math.round(Number(children.children[3].getAttribute('x')))===20 && Math.round(Number(children.children[1].getAttribute('width'))) === 3 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 137 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 3 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 133).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 19 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 45 && Math.round(Number(children.children[1].getAttribute('width'))) === 5 &&Math.round(Number(children.children[3].getAttribute('x')))===85 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 360 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 10 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 350).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); it('Checking the general rendering of bar code - propertychange code128c', (done: Function) => { barcode.type = 'Code128C'; barcode.mode= 'SVG' barcode.displayText.visibility = true barcode.displayText.margin.left = 10 barcode.displayText.margin.right=10 barcode.margin.left = 10; barcode.margin.right = 10; barcode.margin.bottom = 10; barcode.width = 200 barcode.height = 150 barcode.margin.top = 10; barcode.mode = 'SVG'; barcode.displayText.text = undefined barcode.value = '1111'; barcode.height = 200; barcode.width = 150; barcode.dataBind() let barcodeelement = document.getElementById('barcodeprop') let children = barcodeelement.children[0] expect(children.childElementCount === 17 && Math.round(Number(children.children[0].getAttribute('x'))) === 51 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 &&Math.round(Number(children.children[3].getAttribute('x')))===24 && Math.round(Number(children.children[1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 135 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 5 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 2 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 131).toBe(true); barcode.width = '400px'; barcode.height = '400px'; barcode.value = '11111111' barcode.margin.left = 30; barcode.margin.right = 30; barcode.margin.top = 30; barcode.margin.bottom = 30; barcode.displayText.margin.left = 60 barcode.displayText.margin.right = 60 barcode.displayText.text = '12223' barcode.displayText.visibility = false barcode.dataBind() expect(children.childElementCount === 22 && Math.round(Number(children.children[0].getAttribute('x'))) === 30 && Math.round(Number(children.children[1].getAttribute('x'))) === 43 && Math.round(Number(children.children[1].getAttribute('width'))) === 4 &&Math.round(Number(children.children[3].getAttribute('x')))===77 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 361 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 9 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('width'))) === 4 && Math.round(Number(children.children[children.childElementCount - 2].getAttribute('x'))) === 353).toBe(true); barcode.mode = 'Canvas'; barcode.dataBind(); var element = document.getElementById('barcodeprop'); expect(element.childElementCount===1).toBe(true) done(); }); }); var a = { 0: { width: "1.13", height: "110.00", x: 20, y: 20 }, 1: { width: "1.13", height: "110.00", x: 23, y: 20 }, 2: { width: "2.25", height: "110.00", x: 26, y: 20 }, 3: { width: "2.25", height: "110.00", x: 29, y: 20 }, 4: { width: "1.13", height: "110.00", x: 32, y: 20 }, 5: { width: "1.13", height: "56.50", x: 35, y: 20 }, 6: { width: "2.25", height: "56.50", x: 37, y: 20 }, 7: { width: "1.13", height: "56.50", x: 40, y: 20 }, 8: { width: "1.13", height: "56.50", x: 44, y: 20 }, 9: { width: "2.25", height: "56.50", x: 46, y: 20 }, 10: { width: "2.25", height: "56.50", x: 49, y: 20 }, 11: { width: "1.13", height: "56.50", x: 53, y: 20 }, 12: { width: "1.13", height: "56.50", x: 55, y: 20 }, 13: { width: "1.13", height: "56.50", x: 58, y: 20 }, 14: { width: "2.25", height: "56.50", x: 61, y: 20 }, 15: { width: "2.25", height: "56.50", x: 64, y: 20 }, 16: { width: "1.13", height: "56.50", x: 67, y: 20 }, 17: { width: "1.13", height: "56.50", x: 70, y: 20 }, 18: { width: "2.25", height: "56.50", x: 72, y: 20 }, 19: { width: "1.13", height: "56.50", x: 76, y: 20 }, 20: { width: "2.25", height: "56.50", x: 79, y: 20 }, 21: { width: "2.25", height: "56.50", x: 82, y: 20 }, 22: { width: "1.13", height: "56.50", x: 85, y: 20 }, 23: { width: "1.13", height: "56.50", x: 89, y: 20 }, 24: { width: "1.13", height: "56.50", x: 91, y: 20 }, 25: { width: "2.25", height: "56.50", x: 93, y: 20 }, 26: { width: "1.13", height: "56.50", x: 97, y: 20 }, 27: { width: "2.25", height: "56.50", x: 99, y: 20 }, 28: { width: "1.13", height: "56.50", x: 102, y: 20 }, 29: { width: "1.13", height: "56.50", x: 106, y: 20 }, 30: { width: "1.13", height: "56.50", x: 108, y: 20 }, 31: { width: "1.13", height: "56.50", x: 110, y: 20 }, 32: { width: "2.25", height: "56.50", x: 112, y: 20 }, 33: { width: "1.13", height: "56.50", x: 117, y: 20 }, 34: { width: "2.25", height: "56.50", x: 119, y: 20 }, 35: { width: "2.25", height: "56.50", x: 123, y: 20 }, 36: { width: "1.13", height: "56.50", x: 126, y: 20 }, 37: { width: "2.25", height: "56.50", x: 128, y: 20 }, 38: { width: "1.13", height: "56.50", x: 133, y: 20 }, 39: { width: "1.13", height: "56.50", x: 135, y: 20 }, 40: { width: "1.13", height: "56.50", x: 137, y: 20 }, 41: { width: "2.25", height: "56.50", x: 139, y: 20 }, 42: { width: "1.13", height: "56.50", x: 144, y: 20 }, 43: { width: "1.13", height: "56.50", x: 146, y: 20 }, 44: { width: "2.25", height: "56.50", x: 148, y: 20 }, 45: { width: "2.25", height: "56.50", x: 152, y: 20 }, 46: { width: "1.13", height: "56.50", x: 155, y: 20 }, 47: { width: "2.25", height: "56.50", x: 159, y: 20 }, 48: { width: "1.13", height: "56.50", x: 162, y: 20 }, 49: { width: "1.13", height: "56.50", x: 164, y: 20 }, 50: { width: "1.13", height: "110.00", x: 166, y: 20 }, 51: { width: "1.13", height: "110.00", x: 170, y: 20 }, 52: { width: "2.25", height: "110.00", x: 172, y: 20 }, 53: { width: "2.25", height: "110.00", x: 175, y: 20 }, 54: { width: "1.13", height: "110.00", x: 179, y: 20 }, }; describe('checking the bar code all lines width height offset x offsety testcase1', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 20, right: 20, top: 20, bottom: 20 }, displayText: { text: 'ABCDABCDABCD', margin: { left: 20, right: 20, top: 20, bottom: 20 } }, }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking the bar code all lines width height offset x offsety testcase1', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === a[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === a[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === parseFloat(a[j].width).toFixed(2) && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === parseFloat(a[j].height).toFixed(2)).toBe(true); } done(); }); }); let output1 = { 0: { width: "3.52", height: "260.00", x: 100, y: 120 }, 1: { width: "3.52", height: "260.00", x: 111, y: 120 }, 2: { width: "7.04", height: "260.00", x: 118, y: 120 }, 3: { width: "7.04", height: "260.00", x: 128, y: 120 }, 4: { width: "3.52", height: "260.00", x: 139, y: 120 }, 5: { width: "3.52", height: "26.50", x: 146, y: 120 }, 6: { width: "7.04", height: "26.50", x: 153, y: 120 }, 7: { width: "3.52", height: "26.50", x: 163, y: 120 }, 8: { width: "3.52", height: "26.50", x: 174, y: 120 }, 9: { width: "7.04", height: "26.50", x: 181, y: 120 }, 10: { width: "7.04", height: "26.50", x: 192, y: 120 }, 11: { width: "3.52", height: "26.50", x: 202, y: 120 }, 12: { width: "3.52", height: "26.50", x: 209, y: 120 }, 13: { width: "3.52", height: "26.50", x: 220, y: 120 }, 14: { width: "7.04", height: "26.50", x: 227, y: 120 }, 15: { width: "7.04", height: "26.50", x: 237, y: 120 }, 16: { width: "3.52", height: "26.50", x: 248, y: 120 }, 17: { width: "3.52", height: "26.50", x: 255, y: 120 }, 18: { width: "7.04", height: "26.50", x: 262, y: 120 }, 19: { width: "3.52", height: "26.50", x: 276, y: 120 }, 20: { width: "7.04", height: "26.50", x: 283, y: 120 }, 21: { width: "7.04", height: "26.50", x: 294, y: 120 }, 22: { width: "3.52", height: "26.50", x: 304, y: 120 }, 23: { width: "3.52", height: "26.50", x: 315, y: 120 }, 24: { width: "3.52", height: "26.50", x: 322, y: 120 }, 25: { width: "7.04", height: "26.50", x: 329, y: 120 }, 26: { width: "3.52", height: "26.50", x: 339, y: 120 }, 27: { width: "7.04", height: "26.50", x: 346, y: 120 }, 28: { width: "3.52", height: "26.50", x: 357, y: 120 }, 29: { width: "3.52", height: "26.50", x: 368, y: 120 }, 30: { width: "3.52", height: "26.50", x: 375, y: 120 }, 31: { width: "3.52", height: "26.50", x: 382, y: 120 }, 32: { width: "7.04", height: "26.50", x: 389, y: 120 }, 33: { width: "3.52", height: "26.50", x: 403, y: 120 }, 34: { width: "7.04", height: "26.50", x: 410, y: 120 }, 35: { width: "7.04", height: "26.50", x: 420, y: 120 }, 36: { width: "3.52", height: "26.50", x: 431, y: 120 }, 37: { width: "7.04", height: "26.50", x: 438, y: 120 }, 38: { width: "3.52", height: "26.50", x: 452, y: 120 }, 39: { width: "3.52", height: "26.50", x: 459, y: 120 }, 40: { width: "3.52", height: "26.50", x: 466, y: 120 }, 41: { width: "7.04", height: "26.50", x: 473, y: 120 }, 42: { width: "3.52", height: "26.50", x: 487, y: 120 }, 43: { width: "3.52", height: "26.50", x: 494, y: 120 }, 44: { width: "7.04", height: "26.50", x: 501, y: 120 }, 45: { width: "7.04", height: "26.50", x: 512, y: 120 }, 46: { width: "3.52", height: "26.50", x: 523, y: 120 }, 47: { width: "7.04", height: "26.50", x: 533, y: 120 }, 48: { width: "3.52", height: "26.50", x: 544, y: 120 }, 49: { width: "3.52", height: "26.50", x: 551, y: 120 }, 50: { width: "3.52", height: "260.00", x: 558, y: 120 }, 51: { width: "3.52", height: "260.00", x: 568, y: 120 }, 52: { width: "7.04", height: "260.00", x: 575, y: 120 }, 53: { width: "7.04", height: "260.00", x: 586, y: 120 }, 54: { width: "3.52", height: "260.00", x: 596, y: 120 }, } describe('checking the bar code all lines width height offset x offsety testcase2', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '700px', height: '500px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 100, right: 100, top: 120, bottom: 120 }, displayText: { text: 'ABCDABCDABCD', margin: { left: 180, right: 180, top: 100, bottom: 120 } }, }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking the bar code all lines width height offset x offsety testcase2', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 326 && (children.children[0] as HTMLElement).style.fontSize === '6.6px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true); } done(); }); }); var output2 = { 0: { width: "6.34", height: "740.00", x: -100, y: -120 }, 1: { width: "6.34", height: "740.00", x: -81, y: -120 }, 2: { width: "12.68", height: "740.00", x: -68, y: -120 }, 3: { width: "12.68", height: "740.00", x: -49, y: -120 }, 4: { width: "6.34", height: "740.00", x: -30, y: -120 }, 5: { width: "6.34", height: "726.50", x: -18, y: -120 }, 6: { width: "12.68", height: "726.50", x: -5, y: -120 }, 7: { width: "6.34", height: "726.50", x: 14, y: -120 }, 8: { width: "6.34", height: "726.50", x: 33, y: -120 }, 9: { width: "12.68", height: "726.50", x: 46, y: -120 }, 10: { width: "12.68", height: "726.50", x: 65, y: -120 }, 11: { width: "6.34", height: "726.50", x: 84, y: -120 }, 12: { width: "6.34", height: "726.50", x: 96, y: -120 }, 13: { width: "6.34", height: "726.50", x: 115, y: -120 }, 14: { width: "12.68", height: "726.50", x: 128, y: -120 }, 15: { width: "12.68", height: "726.50", x: 147, y: -120 }, 16: { width: "6.34", height: "726.50", x: 166, y: -120 }, 17: { width: "6.34", height: "726.50", x: 179, y: -120 }, 18: { width: "12.68", height: "726.50", x: 192, y: -120 }, 19: { width: "6.34", height: "726.50", x: 217, y: -120 }, 20: { width: "12.68", height: "726.50", x: 230, y: -120 }, 21: { width: "12.68", height: "726.50", x: 249, y: -120 }, 22: { width: "6.34", height: "726.50", x: 268, y: -120 }, 23: { width: "6.34", height: "726.50", x: 287, y: -120 }, 24: { width: "6.34", height: "726.50", x: 299, y: -120 }, 25: { width: "12.68", height: "726.50", x: 312, y: -120 }, 26: { width: "6.34", height: "726.50", x: 331, y: -120 }, 27: { width: "12.68", height: "726.50", x: 344, y: -120 }, 28: { width: "6.34", height: "726.50", x: 363, y: -120 }, 29: { width: "6.34", height: "726.50", x: 382, y: -120 }, 30: { width: "6.34", height: "726.50", x: 394, y: -120 }, 31: { width: "6.34", height: "726.50", x: 407, y: -120 }, 32: { width: "12.68", height: "726.50", x: 420, y: -120 }, 33: { width: "6.34", height: "726.50", x: 445, y: -120 }, 34: { width: "12.68", height: "726.50", x: 458, y: -120 }, 35: { width: "12.68", height: "726.50", x: 477, y: -120 }, 36: { width: "6.34", height: "726.50", x: 496, y: -120 }, 37: { width: "12.68", height: "726.50", x: 508, y: -120 }, 38: { width: "6.34", height: "726.50", x: 534, y: -120 }, 39: { width: "6.34", height: "726.50", x: 546, y: -120 }, 40: { width: "6.34", height: "726.50", x: 559, y: -120 }, 41: { width: "12.68", height: "726.50", x: 572, y: -120 }, 42: { width: "6.34", height: "726.50", x: 597, y: -120 }, 43: { width: "6.34", height: "726.50", x: 610, y: -120 }, 44: { width: "12.68", height: "726.50", x: 623, y: -120 }, 45: { width: "12.68", height: "726.50", x: 642, y: -120 }, 46: { width: "6.34", height: "726.50", x: 661, y: -120 }, 47: { width: "12.68", height: "726.50", x: 680, y: -120 }, 48: { width: "6.34", height: "726.50", x: 699, y: -120 }, 49: { width: "6.34", height: "726.50", x: 711, y: -120 }, 50: { width: "6.34", height: "740.00", x: 724, y: -120 }, 51: { width: "6.34", height: "740.00", x: 743, y: -120 }, 52: { width: "12.68", height: "740.00", x: 756, y: -120 }, 53: { width: "12.68", height: "740.00", x: 775, y: -120 }, 54: { width: "6.34", height: "740.00", x: 794, y: -120 }, }; describe('checking the bar code all lines width height offset x offsety testcase3', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '700px', height: '500px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: -100, right: -100, top: -120, bottom: -120 }, displayText: { text: 'ABCDABCDABCD', margin: { top: -200, right: 350, left: 350 } }, }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking the bar code all lines width height offset x offsety testcase3', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 332 && (children.children[0] as HTMLElement).style.fontSize === '4.8px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output2[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output2[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output2[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output2[j].height).toBe(true); } done(); }); }); var output3 = { 0: { width: "0.28", height: "40.00", x: 30, y: 30 }, 1: { width: "0.28", height: "40.00", x: 31, y: 30 }, 2: { width: "0.56", height: "40.00", x: 31, y: 30 }, 3: { width: "0.56", height: "40.00", x: 32, y: 30 }, 4: { width: "0.28", height: "40.00", x: 33, y: 30 }, 5: { width: "0.28", height: "26.50", x: 34, y: 30 }, 6: { width: "0.56", height: "26.50", x: 34, y: 30 }, 7: { width: "0.28", height: "26.50", x: 35, y: 30 }, 8: { width: "0.28", height: "26.50", x: 36, y: 30 }, 9: { width: "0.56", height: "26.50", x: 36, y: 30 }, 10: { width: "0.56", height: "26.50", x: 37, y: 30 }, 11: { width: "0.28", height: "26.50", x: 38, y: 30 }, 12: { width: "0.28", height: "26.50", x: 39, y: 30 }, 13: { width: "0.28", height: "26.50", x: 40, y: 30 }, 14: { width: "0.56", height: "26.50", x: 40, y: 30 }, 15: { width: "0.56", height: "26.50", x: 41, y: 30 }, 16: { width: "0.28", height: "26.50", x: 42, y: 30 }, 17: { width: "0.28", height: "26.50", x: 42, y: 30 }, 18: { width: "0.56", height: "26.50", x: 43, y: 30 }, 19: { width: "0.28", height: "26.50", x: 44, y: 30 }, 20: { width: "0.56", height: "26.50", x: 45, y: 30 }, 21: { width: "0.56", height: "26.50", x: 45, y: 30 }, 22: { width: "0.28", height: "26.50", x: 46, y: 30 }, 23: { width: "0.28", height: "26.50", x: 47, y: 30 }, 24: { width: "0.28", height: "26.50", x: 48, y: 30 }, 25: { width: "0.56", height: "26.50", x: 48, y: 30 }, 26: { width: "0.28", height: "26.50", x: 49, y: 30 }, 27: { width: "0.56", height: "26.50", x: 50, y: 30 }, 28: { width: "0.28", height: "26.50", x: 51, y: 30 }, 29: { width: "0.28", height: "26.50", x: 51, y: 30 }, 30: { width: "0.28", height: "26.50", x: 52, y: 30 }, 31: { width: "0.28", height: "26.50", x: 53, y: 30 }, 32: { width: "0.56", height: "26.50", x: 53, y: 30 }, 33: { width: "0.28", height: "26.50", x: 54, y: 30 }, 34: { width: "0.56", height: "26.50", x: 55, y: 30 }, 35: { width: "0.56", height: "26.50", x: 56, y: 30 }, 36: { width: "0.28", height: "26.50", x: 56, y: 30 }, 37: { width: "0.56", height: "26.50", x: 57, y: 30 }, 38: { width: "0.28", height: "26.50", x: 58, y: 30 }, 39: { width: "0.28", height: "26.50", x: 59, y: 30 }, 40: { width: "0.28", height: "26.50", x: 59, y: 30 }, 41: { width: "0.56", height: "26.50", x: 60, y: 30 }, 42: { width: "0.28", height: "26.50", x: 61, y: 30 }, 43: { width: "0.28", height: "26.50", x: 62, y: 30 }, 44: { width: "0.56", height: "26.50", x: 62, y: 30 }, 45: { width: "0.56", height: "26.50", x: 63, y: 30 }, 46: { width: "0.28", height: "26.50", x: 64, y: 30 }, 47: { width: "0.56", height: "26.50", x: 65, y: 30 }, 48: { width: "0.28", height: "26.50", x: 65, y: 30 }, 49: { width: "0.28", height: "26.50", x: 66, y: 30 }, 50: { width: "0.28", height: "40.00", x: 67, y: 30 }, 51: { width: "0.28", height: "40.00", x: 67, y: 30 }, 52: { width: "0.56", height: "40.00", x: 68, y: 30 }, 53: { width: "0.56", height: "40.00", x: 69, y: 30 }, 54: { width: "0.28", height: "40.00", x: 70, y: 30 }, }; describe('checking the bar code all lines width height offset x offsety testcase4', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'barcode6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '100px', height: '100px', type: 'Code39', mode: 'SVG', value: 'BARCODE', margin: { left: 30, right: 30, top: 30, bottom: 30 }, displayText: { text: 'ABCDABCDABCD', }, }); barcode.appendTo('#barcode6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking the bar code all lines width height offset x offsety testcase4', (done: Function) => { let barcode = document.getElementById('barcode6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 34 && (children.children[0] as HTMLElement).style.fontSize === '4.4px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output3[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output3[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output3[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output3[j].height).toBe(true); } done(); }); }); });
the_stack
import { ConnectionOptions, DebugEvents, DEFAULT_MAX_PING_OUT, DEFAULT_PING_INTERVAL, DEFAULT_RECONNECT_TIME_WAIT, Empty, Events, PublishOptions, Status, Subscription, } from "./types.ts"; import { newTransport, Transport } from "./transport.ts"; import { ErrorCode, NatsError } from "./error.ts"; import { CR_LF, CRLF, Deferred, deferred, delay, extend, timeout, } from "./util.ts"; import { nuid } from "./nuid.ts"; import { DataBuffer } from "./databuffer.ts"; import { ServerImpl, Servers } from "./servers.ts"; import { Dispatcher, QueuedIterator } from "./queued_iterator.ts"; import type { MsgHdrs, MsgHdrsImpl } from "./headers.ts"; import { SubscriptionImpl } from "./subscription.ts"; import { Subscriptions } from "./subscriptions.ts"; import { MuxSubscription } from "./muxsubscription.ts"; import type { Request } from "./request.ts"; import { Heartbeat, PH } from "./heartbeats.ts"; import { Kind, MsgArg, Parser, ParserEvent } from "./parser.ts"; import { MsgImpl } from "./msg.ts"; import { fastDecoder, fastEncoder } from "./encoders.ts"; const FLUSH_THRESHOLD = 1024 * 32; export const INFO = /^INFO\s+([^\r\n]+)\r\n/i; export function createInbox(): string { return `_INBOX.${nuid.next()}`; } const PONG_CMD = fastEncoder("PONG\r\n"); const PING_CMD = fastEncoder("PING\r\n"); export class Connect { echo?: boolean; no_responders?: boolean; protocol: number = 1; verbose?: boolean; pedantic?: boolean; jwt?: string; nkey?: string; sig?: string; user?: string; pass?: string; auth_token?: string; tls_required?: boolean; name?: string; lang: string; version: string; headers?: boolean; constructor( transport: { version: string; lang: string }, opts: ConnectionOptions, nonce?: string, ) { this.version = transport.version; this.lang = transport.lang; this.echo = opts.noEcho ? false : undefined; this.no_responders = opts.noResponders ? true : undefined; this.verbose = opts.verbose; this.pedantic = opts.pedantic; this.tls_required = opts.tls ? true : undefined; this.name = opts.name; this.headers = opts.headers; const creds = (opts && opts.authenticator ? opts.authenticator(nonce) : {}) || {}; extend(this, creds); } } export interface Publisher { publish( subject: string, data: any, options?: { reply?: string; headers?: MsgHdrs }, ): void; } export class ProtocolHandler implements Dispatcher<ParserEvent> { connected = false; connectedOnce = false; infoReceived = false; info?: any; muxSubscriptions: MuxSubscription; options: ConnectionOptions; outbound: DataBuffer; pongs: Array<Deferred<void>>; pout = 0; subscriptions: Subscriptions; transport!: Transport; noMorePublishing = false; connectError?: Function; publisher: Publisher; _closed = false; closed: Deferred<Error | void>; listeners: QueuedIterator<Status>[] = []; heartbeats: Heartbeat; parser: Parser; outMsgs = 0; inMsgs = 0; outBytes = 0; inBytes = 0; pendingLimit = FLUSH_THRESHOLD; private servers: Servers; private server!: ServerImpl; constructor(options: ConnectionOptions, publisher: Publisher) { this.options = options; this.publisher = publisher; this.subscriptions = new Subscriptions(); this.muxSubscriptions = new MuxSubscription(); this.outbound = new DataBuffer(); this.pongs = []; //@ts-ignore this.pendingLimit = options.pendingLimit || this.pendingLimit; this.servers = new Servers( !options.noRandomize, //@ts-ignore options.servers, ); this.closed = deferred<Error | void>(); this.parser = new Parser(this); this.heartbeats = new Heartbeat( this as PH, this.options.pingInterval || DEFAULT_PING_INTERVAL, this.options.maxPingOut || DEFAULT_MAX_PING_OUT, ); } resetOutbound(): void { this.outbound.reset(); const pongs = this.pongs; this.pongs = []; // reject the pongs pongs.forEach((p) => { p.reject(NatsError.errorForCode(ErrorCode.DISCONNECT)); }); this.parser = new Parser(this); this.infoReceived = false; } dispatchStatus(status: Status): void { this.listeners.forEach((q) => { q.push(status); }); } status(): AsyncIterable<Status> { const iter = new QueuedIterator<Status>(); this.listeners.push(iter); return iter; } private prepare(): Deferred<void> { this.info = undefined; this.resetOutbound(); const pong = deferred<void>(); this.pongs.unshift(pong); this.connectError = undefined; this.connectError = (err: NatsError) => { pong.reject(err); }; this.transport = newTransport(); this.transport.closed() .then(async (err?) => { this.connected = false; if (!this.isClosed()) { await this.disconnected(this.transport.closeError); return; } }); return pong; } public disconnect(): void { this.dispatchStatus({ type: DebugEvents.STALE_CONNECTION, data: "" }); this.transport.disconnect(); } async disconnected(err?: Error): Promise<void> { this.dispatchStatus( { type: Events.DISCONNECT, data: this.servers.getCurrentServer().toString(), }, ); if (this.options.reconnect) { await this.dialLoop() .then(() => { this.dispatchStatus( { type: Events.RECONNECT, data: this.servers.getCurrentServer().toString(), }, ); }) .catch((err) => { this._close(err); }); } else { await this._close(); } } async dial(srv: ServerImpl): Promise<void> { const pong = this.prepare(); const timer = timeout(this.options.timeout || 20000); try { await this.transport.connect(srv, this.options); (async () => { try { for await (const b of this.transport) { this.parser.parse(b); } } catch (err) { console.log("reader closed", err); } })().then(); } catch (err) { pong.reject(err); } try { await Promise.race([timer, pong]); timer.cancel(); this.connected = true; this.connectError = undefined; this.sendSubscriptions(); this.connectedOnce = true; this.server.didConnect = true; this.server.reconnects = 0; this.flushPending(); this.heartbeats.start(); } catch (err) { timer.cancel(); await this.transport.close(err); throw err; } } async dialLoop(): Promise<void> { let lastError: Error | undefined; while (true) { let wait = this.options.reconnectDelayHandler ? this.options.reconnectDelayHandler() : DEFAULT_RECONNECT_TIME_WAIT; let maxWait = wait; const srv = this.selectServer(); if (!srv) { throw lastError || NatsError.errorForCode(ErrorCode.CONNECTION_REFUSED); } const now = Date.now(); if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) { srv.lastConnect = Date.now(); try { this.dispatchStatus( { type: DebugEvents.RECONNECTING, data: srv.toString() }, ); await this.dial(srv); break; } catch (err) { lastError = err; if (!this.connectedOnce) { if (!this.options.waitOnFirstConnect) { this.servers.removeCurrentServer(); } continue; } srv.reconnects++; const mra = this.options.maxReconnectAttempts || 0; if (mra !== -1 && srv.reconnects >= mra) { this.servers.removeCurrentServer(); } } } else { maxWait = Math.min(maxWait, srv.lastConnect + wait - now); await delay(maxWait); } } } public static async connect( options: ConnectionOptions, publisher: Publisher, ): Promise<ProtocolHandler> { const h = new ProtocolHandler(options, publisher); await h.dialLoop(); return h; } static toError(s: string) { let t = s ? s.toLowerCase() : ""; if (t.indexOf("permissions violation") !== -1) { return new NatsError(s, ErrorCode.PERMISSIONS_VIOLATION); } else if (t.indexOf("authorization violation") !== -1) { return new NatsError(s, ErrorCode.AUTHORIZATION_VIOLATION); } else { return new NatsError(s, ErrorCode.NATS_PROTOCOL_ERR); } } processMsg(msg: MsgArg, data: Uint8Array) { this.inMsgs++; this.inBytes += data.length; if (!this.subscriptions.sidCounter) { return; } let sub = this.subscriptions.get(msg.sid) as SubscriptionImpl; if (!sub) { return; } sub.received += 1; if (sub.callback) { sub.callback(null, new MsgImpl(msg, data, this)); } if (sub.max !== undefined && sub.received >= sub.max) { sub.unsubscribe(); } } async processError(m: Uint8Array) { const s = fastDecoder(m); const err = ProtocolHandler.toError(s); this.subscriptions.handleError(err); await this._close(err); } processPing() { this.transport.send(PONG_CMD); } processPong() { this.pout = 0; const cb = this.pongs.shift(); if (cb) { cb.resolve(); } } processInfo(m: Uint8Array) { this.info = JSON.parse(fastDecoder(m)); const updates = this.options && this.options.ignoreClusterUpdates ? undefined : this.servers.update(this.info); if (!this.infoReceived) { this.infoReceived = true; if (this.transport.isEncrypted()) { this.servers.updateTLSName(); } // send connect const { version, lang } = this.transport; try { const c = new Connect( { version, lang }, this.options, this.info.nonce, ); const cs = JSON.stringify(c); this.transport.send( fastEncoder(`CONNECT ${cs}${CR_LF}`), ); this.transport.send(PING_CMD); } catch (err) { this._close( NatsError.errorForCode(ErrorCode.BAD_AUTHENTICATION, err), ); } } if (updates) { this.dispatchStatus({ type: Events.UPDATE, data: updates }); } const ldm = this.info.ldm !== undefined ? this.info.ldm : false; if (ldm) { this.dispatchStatus( { type: Events.LDM, data: this.servers.getCurrentServer().toString(), }, ); } } push(e: ParserEvent): void { switch (e.kind) { case Kind.MSG: const { msg, data } = e; this.processMsg(msg!, data!); break; case Kind.OK: break; case Kind.ERR: this.processError(e.data!); break; case Kind.PING: this.processPing(); break; case Kind.PONG: this.processPong(); break; case Kind.INFO: this.processInfo(e.data!); break; } } sendCommand(cmd: (string | Uint8Array), ...payloads: Uint8Array[]) { const len = this.outbound.length(); let buf: Uint8Array; if (typeof cmd === "string") { buf = fastEncoder(cmd); } else { buf = cmd as Uint8Array; } this.outbound.fill(buf, ...payloads); if (len === 0) { setTimeout(() => { this.flushPending(); }); } else if (this.outbound.size() >= this.pendingLimit) { this.flushPending(); } } publish( subject: string, data: Uint8Array, options?: PublishOptions, ) { if (this.isClosed()) { throw NatsError.errorForCode(ErrorCode.CONNECTION_CLOSED); } if (this.noMorePublishing) { throw NatsError.errorForCode(ErrorCode.CONNECTION_DRAINING); } let len = data.length; options = options || {}; options.reply = options.reply || ""; let headers = Empty; let hlen = 0; if (options.headers) { if (!this.options.headers) { throw new NatsError("headers", ErrorCode.SERVER_OPTION_NA); } const hdrs = options.headers as MsgHdrsImpl; headers = hdrs.encode(); hlen = headers.length; len = data.length + hlen; } if (len > this.info.max_payload) { throw NatsError.errorForCode((ErrorCode.MAX_PAYLOAD_EXCEEDED)); } this.outBytes += len; this.outMsgs++; let proto: string; if (options.headers) { if (options.reply) { proto = `HPUB ${subject} ${options.reply} ${hlen} ${len}${CR_LF}`; } else { proto = `HPUB ${subject} ${hlen} ${len}\r\n`; } this.sendCommand(proto, headers, data, CRLF); } else { if (options.reply) { proto = `PUB ${subject} ${options.reply} ${len}\r\n`; } else { proto = `PUB ${subject} ${len}\r\n`; } this.sendCommand(proto, data, CRLF); } } request(r: Request): Request { this.initMux(); this.muxSubscriptions.add(r); return r; } subscribe(s: SubscriptionImpl): Subscription { this.subscriptions.add(s); if (s.queue) { this.sendCommand(`SUB ${s.subject} ${s.queue} ${s.sid}\r\n`); } else { this.sendCommand(`SUB ${s.subject} ${s.sid}\r\n`); } if (s.max) { this.unsubscribe(s, s.max); } return s; } unsubscribe(s: SubscriptionImpl, max?: number) { this.unsub(s, max); if (s.max === undefined || s.received >= s.max) { this.subscriptions.cancel(s); } } unsub(s: SubscriptionImpl, max?: number) { if (!s || this.isClosed()) { return; } if (max) { this.sendCommand(`UNSUB ${s.sid} ${max}${CR_LF}`); } else { this.sendCommand(`UNSUB ${s.sid}${CR_LF}`); } s.max = max; } flush(p?: Deferred<void>): Promise<void> { if (!p) { p = deferred<void>(); } this.pongs.push(p); this.sendCommand(PING_CMD); return p; } sendSubscriptions() { let cmds: string[] = []; this.subscriptions.all().forEach((s) => { const sub = s as SubscriptionImpl; if (sub.queue) { cmds.push(`SUB ${sub.subject} ${sub.queue} ${sub.sid}${CR_LF}`); } else { cmds.push(`SUB ${sub.subject} ${sub.sid}${CR_LF}`); } }); if (cmds.length) { this.transport.send(fastEncoder(cmds.join(""))); } } private async _close(err?: Error): Promise<void> { if (this._closed) { return; } this.heartbeats.cancel(); if (this.connectError) { this.connectError(err); this.connectError = undefined; } this.muxSubscriptions.close(); this.subscriptions.close(); this.listeners.forEach((l) => { l.stop(); }); this._closed = true; await this.transport.close(err); await this.closed.resolve(err); } close(): Promise<void> { return this._close(); } isClosed(): boolean { return this._closed; } drain(): Promise<void> { let subs = this.subscriptions.all(); let promises: Promise<void>[] = []; subs.forEach((sub: Subscription) => { promises.push(sub.drain()); }); return Promise.all(promises) .then(async () => { this.noMorePublishing = true; return this.close(); }) .catch(() => { // cannot happen }); } private flushPending() { if (!this.infoReceived || !this.connected) { return; } if (this.outbound.size()) { let d = this.outbound.drain(); this.transport.send(d); } } private initMux(): void { let mux = this.subscriptions.getMux(); if (!mux) { let inbox = this.muxSubscriptions.init(); // dot is already part of mux const sub = new SubscriptionImpl(this, `${inbox}*`); sub.callback = this.muxSubscriptions.dispatcher(); this.subscriptions.setMux(sub); this.subscribe(sub); } } private selectServer(): ServerImpl | undefined { let server = this.servers.selectServer(); if (server === undefined) { return undefined; } // Place in client context. this.server = server; return this.server; } getServer(): ServerImpl | undefined { return this.server; } }
the_stack
import { defaultModelAssessmentContext, ICounterfactualData, MissingParametersPlaceholder, ModelAssessmentContext } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import _, { toNumber } from "lodash"; import { Callout, ComboBox, ConstrainMode, DetailsList, DetailsListLayoutMode, DetailsRow, IColumn, IComboBox, IComboBoxOption, IDetailsFooterProps, Link, SelectionMode, Stack, Text, TextField } from "office-ui-fabric-react"; import React from "react"; import { getCategoricalOption } from "../util/getCategoricalOption"; import { getFilterFeatures } from "../util/getFilterFeatures"; import { counterfactualListStyle } from "./CounterfactualListStyles"; import { counterfactualPanelStyles } from "./CounterfactualPanelStyles"; import { CustomPredictionLabels } from "./CustomPredictionLabels"; export interface ICounterfactualListProps { selectedIndex: number; originalData: { [key: string]: string | number }; data?: ICounterfactualData; filterText?: string; temporaryPoint: Record<string, string | number> | undefined; sortFeatures: boolean; setCustomRowProperty( key: string | number, isString: boolean, newValue?: string | number ): void; } interface ICounterfactualListState { data: Record<string, string | number>; showCallout: boolean; } const nameColumnKey = "row"; export class CounterfactualList extends React.Component< ICounterfactualListProps, ICounterfactualListState > { public static contextType = ModelAssessmentContext; public context: React.ContextType<typeof ModelAssessmentContext> = defaultModelAssessmentContext; public constructor(props: ICounterfactualListProps) { super(props); this.state = { data: {}, showCallout: false }; } public componentDidMount() { this.onSelect(0); } public render(): React.ReactNode { const items = this.getItems(); const columns = this.getColumns(); if (columns.length === 0) { return ( <MissingParametersPlaceholder> {localization.Counterfactuals.noFeatures} </MissingParametersPlaceholder> ); } return ( <DetailsList items={items} columns={columns} selectionMode={SelectionMode.none} setKey="set" constrainMode={ConstrainMode.unconstrained} layoutMode={DetailsListLayoutMode.fixedColumns} onRenderDetailsFooter={this.onRenderDetailsFooter} /> ); } private getItems(): Array<Record<string, string | number>> { const items: Array<Record<string, string | number>> = []; const selectedData = this.props.data?.cfs_list[ this.props.selectedIndex % this.props.data?.cfs_list.length ]; if (selectedData && this.props.originalData) { items.push(this.props.originalData); selectedData.forEach((point, i) => { const temp = { row: localization.formatString( localization.Counterfactuals.counterfactualEx, i + 1 ) }; this.props.data?.feature_names_including_target.forEach((f, j) => { temp[f] = this.props.originalData?.[f] !== point[j] ? point[j] : "-"; }); items.push(temp); }); } return items; } private onSelect(idx: number): void { const items = this.getItems(); const data = _.cloneDeep(items[idx]); Object.keys(data).forEach((k) => { data[k] = data[k] === "-" ? items[0][k] : data[k]; const keyIndex = this.props.data?.feature_names_including_target.indexOf(k); this.props.setCustomRowProperty(`Data${keyIndex}`, false, data[k]); }); data.row = localization.formatString( localization.Interpret.WhatIf.defaultCustomRootName, this.props.selectedIndex ); this.setState({ data }); } private renderName = ( item?: Record<string, string | number>, index?: number | undefined ) => { //footer if (index === -1) { const classNames = counterfactualPanelStyles(); return ( <Stack> <Stack.Item> <TextField value={this.state.data[nameColumnKey]?.toString()} label={localization.Counterfactuals.createOwn} id={nameColumnKey} disabled onChange={this.updateColValue} /> </Stack.Item> {this.context.requestPredictions && ( <Stack.Item className={classNames.predictedLink}> <div id={"predictionLink"} className={classNames.predictedLink} onMouseOver={this.toggleCallout} onFocus={this.toggleCallout} onMouseOut={this.toggleCallout} onBlur={this.toggleCallout} > {localization.Counterfactuals.seePrediction} </div> {this.state.showCallout && ( <Callout target={"#predictionLink"} onDismiss={this.toggleCallout} setInitialFocus > <CustomPredictionLabels jointDataset={this.context.jointDataset} metadata={this.context.modelMetadata} selectedWhatIfRootIndex={this.props.selectedIndex} temporaryPoint={this.props.temporaryPoint} /> </Callout> )} </Stack.Item> )} </Stack> ); } if (index === undefined || !item?.row) return React.Fragment; return ( <Stack> <Text>{item.row}</Text> {this.context.requestPredictions && ( <Link onClick={this.onSelect.bind(this, index)}> {localization.Counterfactuals.WhatIf.setValue} </Link> )} </Stack> ); }; private getColumns(): IColumn[] { const columns: IColumn[] = []; const targetFeature = this.props.data?.feature_names_including_target[ this.props.data?.feature_names_including_target.length - 1 ]; const featureNames = getFilterFeatures( this.props.data, this.props.selectedIndex, this.props.sortFeatures, this.props.filterText ); if (!featureNames || featureNames.length === 0) { return columns; } columns.push( { fieldName: nameColumnKey, isResizable: true, key: nameColumnKey, minWidth: 200, name: "", onRender: this.renderName }, { fieldName: targetFeature, isResizable: true, key: targetFeature || "", minWidth: 175, name: targetFeature || "" } ); featureNames .filter((f) => f !== targetFeature) .forEach((f) => columns.push({ fieldName: f, isResizable: true, key: f, minWidth: 175, name: f }) ); return columns; } private updateDropdownColValue = ( key: string | number, _event: React.FormEvent<IComboBox>, option?: IComboBoxOption ): void => { const id = key.toString(); const keyIndex = this.props.data?.feature_names_including_target.indexOf(id); if (option?.text) { this.props.setCustomRowProperty(`Data${keyIndex}`, false, option.text); this.setState((prevState) => { prevState.data[id] = option.text; return { data: prevState.data }; }); } }; private updateColValue = ( evt: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string ): void => { const target = evt.target as Element; const id = target.id; const keyIndex = this.props.data?.feature_names_including_target.indexOf(id); this.props.setCustomRowProperty(`Data${keyIndex}`, false, newValue); this.setState((prevState) => { prevState.data[id] = toNumber(newValue); return { data: prevState.data }; }); }; private toggleCallout = (): void => { this.setState((preState) => { return { showCallout: !preState.showCallout }; }); }; private renderDetailsFooterItemColumn = ( _item: Record<string, string | number>, _index?: number, column?: IColumn ): React.ReactNode | undefined => { const dropdownOption = getCategoricalOption( this.context.jointDataset, column?.key ); const styles = counterfactualListStyle(); if (column && dropdownOption?.data?.categoricalOptions) { return ( <Stack horizontal={false} tokens={{ childrenGap: "5px" }}> <Stack.Item className={styles.dropdownLabel}> <Text>{column.key}</Text> </Stack.Item> <Stack.Item> <ComboBox key={column.key} // label={metaInfo.abbridgedLabel} autoComplete={"on"} allowFreeform selectedKey={this.state.data[column.key]} options={dropdownOption.data.categoricalOptions} onChange={this.updateDropdownColValue.bind(this, column.key)} /> </Stack.Item> </Stack> ); } if (column) { return ( <Stack horizontal={false}> <Stack.Item> <TextField value={this.state.data[column.key]?.toString()} label={column.key} id={column.key} onChange={this.updateColValue} /> </Stack.Item> </Stack> ); } return undefined; }; private onRenderDetailsFooter = ( detailsFooterProps?: IDetailsFooterProps ): JSX.Element => { if (detailsFooterProps && this.context.requestPredictions) { return ( <DetailsRow {...detailsFooterProps} columns={detailsFooterProps.columns} item={this.state.data} itemIndex={-1} groupNestingDepth={detailsFooterProps.groupNestingDepth} selectionMode={SelectionMode.none} onRenderItemColumn={this.renderDetailsFooterItemColumn} /> ); } return <div />; }; }
the_stack
import * as k8s from "@kubernetes/client-node"; import * as _ from "lodash"; import { k8sErrMsg } from "../support/error"; import { K8sObjectApi } from "./api"; import { KubernetesClients, makeApiClients, } from "./clients"; import { loadKubeConfig } from "./config"; import { labelMatch } from "./labels"; import { nameMatch } from "./name"; /** Kubernetes resource type specifier. */ export interface KubernetesResourceKind { /** Kubernetes API version, e.g., "v1" or "apps/v1". */ apiVersion: string; /** Kubernetes resource, e.g., "Service" or "Deployment". */ kind: string; } /** * Various ways to select Kubernetes resources. All means provided * are logically ANDed together. */ export interface KubernetesResourceSelector { /** * Whether this selector is for inclusion or exclusion. * If not provided, the rule will be used for inclusion. */ action?: "include" | "exclude"; /** * If provided, only resources of a kind provided will be * considered a match. Only the "kind" is considered when * matching, since the same kind can appear under multiple * "apiVersion"s. See [[populateResourceSelectorDefaults]] for * rules on how it is populated if it is not set. */ kinds?: KubernetesResourceKind[]; /** * If provided, only resources with names matching either the * entire string or regular expression will be considered a match. * If not provided, the resource name is not considered when * matching. */ name?: string | RegExp; /** * If provided, only resources in namespaces matching either the * entire strings or regular expression will be considered a * match. If not provided, the resource namespace is not * considered when matching. */ namespace?: string | RegExp; /** * Kubernetes-style label selectors. If provided, only resources * matching the selectors are considered a match. If not * provided, the resource labels are not considered when matching. */ labelSelector?: k8s.V1LabelSelector; /** * If provided, resources will be considered a match if their * filter function returns `true`. If not provided, this property * has no effect on matching. */ filter?: (r: k8s.KubernetesObject) => boolean; } /** * Useful default set of kinds of Kubernetes resources. */ export const defaultKubernetesResourceSelectorKinds: KubernetesResourceKind[] = [ { apiVersion: "v1", kind: "ConfigMap" }, { apiVersion: "v1", kind: "Namespace" }, { apiVersion: "v1", kind: "Secret" }, { apiVersion: "v1", kind: "Service" }, { apiVersion: "v1", kind: "ServiceAccount" }, { apiVersion: "v1", kind: "PersistentVolume" }, { apiVersion: "v1", kind: "PersistentVolumeClaim" }, { apiVersion: "apps/v1", kind: "DaemonSet" }, { apiVersion: "apps/v1", kind: "Deployment" }, { apiVersion: "apps/v1", kind: "StatefulSet" }, { apiVersion: "autoscaling/v1", kind: "HorizontalPodAutoscaler" }, { apiVersion: "batch/v1beta1", kind: "CronJob" }, { apiVersion: "networking.k8s.io/v1beta1", kind: "Ingress" }, { apiVersion: "networking.k8s.io/v1", kind: "NetworkPolicy" }, { apiVersion: "policy/v1beta1", kind: "PodDisruptionBudget" }, { apiVersion: "policy/v1beta1", kind: "PodSecurityPolicy" }, { apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole" }, { apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRoleBinding" }, { apiVersion: "rbac.authorization.k8s.io/v1", kind: "Role" }, { apiVersion: "rbac.authorization.k8s.io/v1", kind: "RoleBinding" }, { apiVersion: "storage.k8s.io/v1", kind: "StorageClass" }, ]; /** * Kubernetes fetch options specifying which resources to fetch. */ export interface KubernetesFetchOptions { /** * Array of Kubernetes resource selectors. The selectors are * applied in order to each resource and the action of the first * matching selector is applied. */ selectors?: KubernetesResourceSelector[]; } /** * The default options used when fetching resource from a Kubernetes * cluster. By default it fetches resources whose kind is in the * [[defaultKubernetesResourceSelectorKinds]] array, excluding the * resources that look like Kubernetes managed resources like the * `kubernetes` service in the `default` namespace, resources in * namespaces that starts with "kube-", and system- and cloud-related * cluster roles and cluster role bindings. */ export const defaultKubernetesFetchOptions: KubernetesFetchOptions = { selectors: [ { action: "exclude", namespace: /^kube-/ }, { action: "exclude", name: /^(?:kubeadm|system):/ }, { action: "exclude", kinds: [{ apiVersion: "v1", kind: "Namespace" }], name: "default" }, { action: "exclude", kinds: [{ apiVersion: "v1", kind: "Namespace" }], name: /^kube-/ }, { action: "exclude", kinds: [{ apiVersion: "v1", kind: "Service" }], namespace: "default", name: "kubernetes" }, { action: "exclude", kinds: [{ apiVersion: "v1", kind: "ServiceAccount" }], name: "default" }, { action: "exclude", kinds: [{ apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRole" }], name: /^(?:(?:cluster-)?admin|edit|view|cloud-provider)$/, }, { action: "exclude", kinds: [{ apiVersion: "rbac.authorization.k8s.io/v1", kind: "ClusterRoleBinding" }], name: /^(?:cluster-admin(?:-binding)?|cloud-provider|kubernetes-dashboard)$/, }, { action: "exclude", kinds: [{ apiVersion: "storage.k8s.io/v1", kind: "StorageClass" }], name: "standard" }, { action: "exclude", filter: (r: any) => r.kind === "Secret" && r.type === "kubernetes.io/service-account-token", }, { action: "exclude", filter: r => /^ClusterRole/.test(r.kind) && /(?:kubelet|:)/.test(r.metadata.name) }, { action: "include", kinds: defaultKubernetesResourceSelectorKinds }, ], }; /** * Fetch resource specs from a Kubernetes cluster as directed by the * fetch options, removing read-only properties filled by the * Kubernetes system. * * The inclusion selectors are processed to determine which resources * in the Kubernetes cluster to query. * * @param options Kubernetes fetch options * @return Kubernetes resources matching the fetch options */ export async function kubernetesFetch( options: KubernetesFetchOptions = defaultKubernetesFetchOptions, ): Promise<k8s.KubernetesObject[]> { let client: K8sObjectApi; let clients: KubernetesClients; try { const kc = loadKubeConfig(); client = kc.makeApiClient(K8sObjectApi); clients = makeApiClients(kc); } catch (e) { e.message = `Failed to create Kubernetes client: ${k8sErrMsg(e)}`; throw e; } const selectors = populateResourceSelectorDefaults(options.selectors); const clusterResources = await clusterResourceKinds(selectors, client); const specs: k8s.KubernetesObject[] = []; for (const apiKind of clusterResources) { try { const obj = apiObject(apiKind); const listResponse = await client.list(obj); specs.push(...listResponse.body.items.map(s => cleanKubernetesSpec(s, apiKind))); } catch (e) { e.message = `Failed to list cluster resources ${apiKind.apiVersion}/${apiKind.kind}: ${e.message}`; throw e; } } let namespaces: k8s.V1Namespace[]; try { const nsResponse = await clients.core.listNamespace(); namespaces = nsResponse.body.items; } catch (e) { e.message = `Failed to list namespaces: ${e.message}`; throw e; } for (const nsObj of namespaces) { specs.push(cleanKubernetesSpec(nsObj, { apiVersion: "v1", kind: "Namespace" })); const ns = nsObj.metadata.name; const apiKinds = await namespaceResourceKinds(ns, selectors, client); for (const apiKind of apiKinds) { try { const obj = apiObject(apiKind, ns); const listResponse = await client.list(obj); specs.push(...listResponse.body.items.map(s => cleanKubernetesSpec(s, apiKind))); } catch (e) { e.message = `Failed to list resources ${apiKind.apiVersion}/${apiKind.kind} in namespace ${ns}: ${e.message}`; throw e; } } } return selectKubernetesResources(specs, selectors); } /** * Make sure Kubernetes resource selectors have appropriate properties * populated with default values. If the selector does not have an * `action` set, it is set to "include". If the selector does not have * `kinds` set and `action` is "include", `kinds` is set to * [[defaultKubernetesResourceSelectorKinds]]. Rules with `action` set * to "exclude" and have no selectors are discarded. * * @param selectors Kubernetes resource selectors to ensure have default values * @return Properly defaulted Kubernetes resource selectors */ export function populateResourceSelectorDefaults( selectors: KubernetesResourceSelector[], ): KubernetesResourceSelector[] { return selectors .map(s => { const k: KubernetesResourceSelector = { action: "include", ...s }; if (!k.kinds && k.action === "include") { k.kinds = defaultKubernetesResourceSelectorKinds; } return k; }) .filter(s => s.action === "include" || s.filter || s.kinds || s.labelSelector || s.name || s.namespace); } /** * Determine all Kuberenetes resources that we should query based on * all the selectors and return an array with each Kubernetes resource * type appearing no more than once. Note that uniqueness of a * Kubernetes resource type is determined solely by the `kind` * property, `apiVersion` is not considered since the same resource * can be found with the same kind and different API versions. * * @param selectors All the resource selectors * @return A deduplicated array of Kubernetes resource kinds among the inclusion rules */ export function includedResourceKinds(selectors: KubernetesResourceSelector[]): KubernetesResourceKind[] { const includeSelectors = selectors.filter(s => s.action === "include"); const includeKinds = _.flatten(includeSelectors.map(s => s.kinds)); const uniqueKinds = _.uniqBy(includeKinds, "kind"); return uniqueKinds; } /** * Determine all Kuberenetes cluster, i.e., not namespaced, resources * that we should query based on all the selectors and return an array * with each Kubernetes cluster resource type appearing no more than * once. Note that uniqueness of a Kubernetes resource type is * determined solely by the `kind` property, `apiVersion` is not * considered since the same resource can be found with the same kind * and different API versions. * * @param selectors All the resource selectors * @return A deduplicated array of Kubernetes cluster resource kinds among the inclusion rules */ export async function clusterResourceKinds( selectors: KubernetesResourceSelector[], client: K8sObjectApi, ): Promise<KubernetesResourceKind[]> { const included = includedResourceKinds(selectors); const apiKinds: KubernetesResourceKind[] = []; for (const apiKind of included) { try { const resource = await client.resource(apiKind.apiVersion, apiKind.kind); if (resource && !resource.namespaced) { apiKinds.push(apiKind); } } catch (e) { // ignore } } return apiKinds; } /** * For the provided set of selectors, return a deduplicated array of * resource kinds that match the provided namespace. * * @param ns Namespace to check * @param selectors Selectors to evaluate * @return A deduplicated array of Kubernetes resource kinds among the inclusion rules for namespace `ns` */ export async function namespaceResourceKinds( ns: string, selectors: KubernetesResourceSelector[], client: K8sObjectApi, ): Promise<KubernetesResourceKind[]> { const apiKinds: KubernetesResourceKind[] = []; for (const selector of selectors.filter(s => s.action === "include")) { if (nameMatch(ns, selector.namespace)) { for (const apiKind of selector.kinds) { try { const resource = await client.resource(apiKind.apiVersion, apiKind.kind); if (resource && resource.namespaced) { apiKinds.push(apiKind); } } catch (e) { // ignore } } } } return _.uniqBy(apiKinds, "kind"); } /** * Construct Kubernetes resource object for use with client API. */ function apiObject(apiKind: KubernetesResourceKind, ns?: string): k8s.KubernetesObject { const ko: k8s.KubernetesObject = { apiVersion: apiKind.apiVersion, kind: apiKind.kind, }; if (ns) { ko.metadata = { namespace: ns }; } return ko; } /** * Remove read-only type properties not useful to retain in a resource * specification used for upserting resources. This is probably not * perfect. Add the `apiVersion` and `kind` properties since the they * are not included in the items returned by the list endpoint, * https://github.com/kubernetes/kubernetes/issues/3030 . * * @param obj Kubernetes spec to clean * @return Kubernetes spec with status-like properties removed */ export function cleanKubernetesSpec(obj: k8s.KubernetesObject, apiKind: KubernetesResourceKind): k8s.KubernetesObject { if (!obj) { return obj; } const spec: any = { ...apiKind, ...obj }; if (spec.metadata) { delete spec.metadata.creationTimestamp; delete spec.metadata.generation; delete spec.metadata.resourceVersion; delete spec.metadata.selfLink; delete spec.metadata.uid; if (spec.metadata.annotations) { delete spec.metadata.annotations["deployment.kubernetes.io/revision"]; delete spec.metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"]; if (Object.keys(spec.metadata.annotations).length < 1) { delete spec.metadata.annotations; } } } if (spec.spec && spec.spec.template && spec.spec.template.metadata) { delete spec.spec.template.metadata.creationTimestamp; } delete spec.status; if (spec.kind === "ServiceAccount") { delete spec.secrets; } return spec; } /** * Filter provided Kubernetes resources according to the provides * selectors. Each selector is applied in turn to each spec. The * action of the first selector that matches a resource is applied to * that resource. If no selector matches a resource, it is not * returned, i.e., the default is to exclude. * * @param specs Kubernetes resources to filter * @param selectors Filtering rules * @return Filtered array of Kubernetes resources */ export function selectKubernetesResources( specs: k8s.KubernetesObject[], selectors: KubernetesResourceSelector[], ): k8s.KubernetesObject[] { const uniqueSpecs = _.uniqBy(specs, kubernetesResourceIdentity); if (!selectors || selectors.length < 1) { return uniqueSpecs; } const filteredSpecs: k8s.KubernetesObject[] = []; for (const spec of uniqueSpecs) { for (const selector of selectors) { const action = selectorMatch(spec, selector); if (action === "include") { filteredSpecs.push(spec); break; } else if (action === "exclude") { break; } } } return filteredSpecs; } /** * Reduce a Kubernetes resource to its uniquely identifying * properties. Note that `apiVersion` is not among them as identical * resources can be access via different API versions, e.g., * Deployment via app/v1 and extensions/v1beta1. * * @param obj Kubernetes resource * @return Stripped down resource for unique identification */ export function kubernetesResourceIdentity(obj: k8s.KubernetesObject): string { return `${obj.kind}|` + (obj.metadata.namespace ? `${obj.metadata.namespace}|` : "") + obj.metadata.name; } /** * Determine if Kubernetes resource is a match against the selector. * If there is a match, return the action of the selector. If there * is not a match, return `undefined`. * * @param spec Kubernetes resource to check * @param selector Selector to use for checking * @return Selector action if there is a match, `undefined` otherwise */ export function selectorMatch( spec: k8s.KubernetesObject, selector: KubernetesResourceSelector, ): "include" | "exclude" | undefined { if (!nameMatch(spec.metadata.name, selector.name)) { return undefined; } if (!nameMatch(spec.metadata.namespace, selector.namespace)) { return undefined; } if (!labelMatch(spec, selector.labelSelector)) { return undefined; } if (!kindMatch(spec, selector.kinds)) { return undefined; } if (!filterMatch(spec, selector.filter)) { return undefined; } return selector.action; } /** * Determine if Kubernetes resource `kind` property is among the kinds * provided. If no kinds are provided, it is considered matching. * Only the resource's `kind` property is considered when matching, * `apiVersion` is ignored. * * @param spec Kubernetes resource to check * @param kinds Kubernetes resource selector `kinds` property to use for checking * @return Return `true` if it is a match, `false` otherwise */ export function kindMatch(spec: k8s.KubernetesObject, kinds: KubernetesResourceKind[]): boolean { if (!kinds || kinds.length < 1) { return true; } return kinds.map(ak => ak.kind).includes(spec.kind); } /** * Determine if Kubernetes resource `kind` property is among the kinds * provided. If no kinds are provided, it is considered matching. * Only the resource's `kind` property is considered when matching, * `apiVersion` is ignored. * * @param spec Kubernetes resource to check * @param kinds Kubernetes resource selector `kinds` property to use for checking * @return Return `true` if it is a match, `false` otherwise */ export function filterMatch(spec: k8s.KubernetesObject, filter: (r: k8s.KubernetesObject) => boolean): boolean { if (!filter) { return true; } return filter(spec); }
the_stack
import * as ts_module from "../node_modules/typescript/lib/tsserverlibrary"; import * as tslint from 'tslint'; import * as path from 'path'; import * as mockRequire from 'mock-require'; // Settings for the plugin section in tsconfig.json interface Settings { alwaysShowRuleFailuresAsWarnings?: boolean; ignoreDefinitionFiles?: boolean; configFile?: string; disableNoUnusedVariableRule?: boolean // support to enable/disable the workaround for https://github.com/Microsoft/TypeScript/issues/15344 supressWhileTypeErrorsPresent: boolean; mockTypeScriptVersion: boolean; } const TSLINT_ERROR_CODE = 100000; function init(modules: { typescript: typeof ts_module }) { const ts = modules.typescript; let codeFixActions = new Map<string, Map<string, tslint.RuleFailure>>(); let registeredCodeFixes = false; let configCache = { filePath: <string>null, configuration: <any>null, isDefaultConfig: false, configFilePath: <string>null }; // Work around the lack of API to register a CodeFix function registerCodeFix(action: codefix.CodeFix) { return (ts as any).codefix.registerCodeFix(action); } if (!registeredCodeFixes && ts && (ts as any).codefix) { registerCodeFixes(registerCodeFix); registeredCodeFixes = true; } function registerCodeFixes(registerCodeFix: (action: codefix.CodeFix) => void) { // Code fix for that is used for all tslint fixes registerCodeFix({ errorCodes: [TSLINT_ERROR_CODE], getCodeActions: (_context: any) => { return null; } }); } function fixRelativeConfigFilePath(config: Settings, projectRoot: string): Settings { if (!config.configFile) { return config; } if (path.isAbsolute(config.configFile)) { return config; } config.configFile = path.join(projectRoot, config.configFile); return config; } function create(info: ts.server.PluginCreateInfo) { info.project.projectService.logger.info("tslint-language-service loaded"); let config: Settings = fixRelativeConfigFilePath(info.config, info.project.getCurrentDirectory()); let configuration: tslint.Configuration.IConfigurationFile = null; if(config.mockTypeScriptVersion) { mockRequire('typescript', ts); } const tslint = require('tslint') // Set up decorator const proxy = Object.create(null) as ts.LanguageService; const oldLS = info.languageService; for (const k in oldLS) { (<any>proxy)[k] = function () { return (<any>oldLS)[k].apply(oldLS, arguments); } } // key to identify a rule failure function computeKey(start: number, end: number): string { return `[${start},${end}]`; } function makeDiagnostic(problem: tslint.RuleFailure, file: ts.SourceFile): ts.Diagnostic { let message = (problem.getRuleName() !== null) ? `${problem.getFailure()} (${problem.getRuleName()})` : `${problem.getFailure()}`; let category; if (config.alwaysShowRuleFailuresAsWarnings === true) { category = ts.DiagnosticCategory.Warning; } else if ((<any>problem).getRuleSeverity && (<any>problem).getRuleSeverity() === 'error') { // tslint5 supports to assign severities to rules category = ts.DiagnosticCategory.Error; } else { category = ts.DiagnosticCategory.Warning; } let diagnostic: ts.Diagnostic = { file: file, start: problem.getStartPosition().getPosition(), length: problem.getEndPosition().getPosition() - problem.getStartPosition().getPosition(), messageText: message, category: category, source: 'tslint', code: TSLINT_ERROR_CODE }; return diagnostic; } /** * Filter failures for the given document */ function filterProblemsForDocument(documentPath: string, failures: tslint.RuleFailure[]): tslint.RuleFailure[] { let normalizedPath = path.normalize(documentPath); // we only show diagnostics targetting this open document, some tslint rule return diagnostics for other documents/files let normalizedFiles = new Map<string, string>(); return failures.filter(each => { let fileName = each.getFileName(); if (!normalizedFiles.has(fileName)) { normalizedFiles.set(fileName, path.normalize(fileName)); } return normalizedFiles.get(fileName) === normalizedPath; }); } function replacementsAreEmpty(fix: tslint.Fix): boolean { // in tslint 4 a Fix has a replacement property witht the Replacements if ((<any>fix).replacements) { return (<any>fix).replacements.length === 0; } // tslint 5 if (Array.isArray(fix)) { return fix.length === 0; } return false; } function recordCodeAction(problem: tslint.RuleFailure, file: ts.SourceFile) { let fix: tslint.Fix = null; // tslint can return a fix with an empty replacements array, these fixes are ignored if (problem.getFix && problem.getFix() && !replacementsAreEmpty(problem.getFix())) { // tslint fixes are not available in tslint < 3.17 fix = problem.getFix(); // createAutoFix(problem, document, problem.getFix()); } if (!fix) { return; } let documentAutoFixes: Map<string, tslint.RuleFailure> = codeFixActions.get(file.fileName); if (!documentAutoFixes) { documentAutoFixes = new Map<string, tslint.RuleFailure>(); codeFixActions.set(file.fileName, documentAutoFixes); } documentAutoFixes.set(computeKey(problem.getStartPosition().getPosition(), problem.getEndPosition().getPosition()), problem); } function getConfigurationFailureMessage(err: any): string { let errorMessage = `unknown error`; if (typeof err.message === 'string' || err.message instanceof String) { errorMessage = <string>err.message; } return `tslint: Cannot read tslint configuration - '${errorMessage}'`; } function getConfiguration(filePath: string, configFileName: string): any { if (configCache.configuration && configCache.filePath === filePath) { return configCache.configuration; } let isDefaultConfig = false; let configuration; let configFilePath = null; isDefaultConfig = tslint.Configuration.findConfigurationPath(configFileName, filePath) === undefined; let configurationResult = tslint.Configuration.findConfiguration(configFileName, filePath); // between tslint 4.0.1 and tslint 4.0.2 the attribute 'error' has been removed from IConfigurationLoadResult // in 4.0.2 findConfiguration throws an exception as in version ^3.0.0 if ((<any>configurationResult).error) { throw (<any>configurationResult).error; } configuration = configurationResult.results; // In tslint version 5 the 'no-unused-variable' rules breaks the TypeScript language service plugin. // See https://github.com/Microsoft/TypeScript/issues/15344 // Therefore we remove the rule from the configuration. // // In tslint 5 the rules are stored in a Map, in earlier versions they were stored in an Object if (config.disableNoUnusedVariableRule === true || config.disableNoUnusedVariableRule === undefined) { if (configuration.rules && configuration.rules instanceof Map) { configuration.rules.delete('no-unused-variable'); } if (configuration.jsRules && configuration.jsRules instanceof Map) { configuration.jsRules.delete('no-unused-variable'); } } configFilePath = configurationResult.path; configCache = { filePath: filePath, isDefaultConfig: isDefaultConfig, configuration: configuration, configFilePath: configFilePath }; return configCache.configuration; } function captureWarnings(message?: any): void { // TODO log to a user visible log and not only the TS-Server log info.project.projectService.logger.info(`[tslint] ${message}`); } function convertReplacementToTextChange(repl: tslint.Replacement): ts.TextChange { return { newText: repl.text, span: { start: repl.start, length: repl.length } }; } function getReplacements(fix: tslint.Fix): tslint.Replacement[]{ let replacements: tslint.Replacement[] = null; // in tslint4 a Fix has a replacement property with the Replacements if ((<any>fix).replacements) { // tslint4 replacements = (<any>fix).replacements; } else { // in tslint 5 a Fix is a Replacement | Replacement[] if (!Array.isArray(fix)) { replacements = [<any>fix]; } else { replacements = fix; } } return replacements; } function problemToFileTextChange(problem: tslint.RuleFailure, fileName: string): ts_module.FileTextChanges { let fix = problem.getFix(); let replacements: tslint.Replacement[] = getReplacements(fix); return { fileName: fileName, textChanges: replacements.map(each => convertReplacementToTextChange(each)), } } function addRuleFailureFix(fixes: ts_module.CodeAction[], problem: tslint.RuleFailure, fileName: string) { fixes.push({ description: `Fix '${problem.getRuleName()}'`, changes: [problemToFileTextChange(problem, fileName)] }); } /* Generate a code action that fixes all instances of ruleName. */ function addRuleFailureFixAll(fixes: ts_module.CodeAction[], ruleName: string, problems: Map<string, tslint.RuleFailure>, fileName: string) { const changes: ts_module.FileTextChanges[] = []; for (const problem of problems.values()) { if (problem.getRuleName() === ruleName) { changes.push(problemToFileTextChange(problem, fileName)); } } /* No need for this action if there's only one instance. */ if (changes.length < 2) { return; } fixes.push({ description: `Fix all '${ruleName}'`, changes: changes, }); } function addDisableRuleFix(fixes: ts_module.CodeAction[], problem: tslint.RuleFailure, fileName: string, file: ts_module.SourceFile) { fixes.push({ description: `Disable rule '${problem.getRuleName()}'`, changes: [{ fileName: fileName, textChanges: [{ newText: `// tslint:disable-next-line:${problem.getRuleName()}\n`, span: { start: file.getLineStarts()[problem.getStartPosition().getLineAndCharacter().line], length: 0 } }] }] }); } function addOpenConfigurationFix(fixes: ts_module.CodeAction[]) { // the Open Configuration code action is disabled since there is no specified API to open an editor let openConfigFixEnabled = false; if (openConfigFixEnabled && configCache && configCache.configFilePath) { fixes.push({ description: `Open tslint.json`, changes: [{ fileName: configCache.configFilePath, textChanges: [] }] }); } } function addAllAutoFixable(fixes: ts_module.CodeAction[], documentFixes: Map<string, tslint.RuleFailure>, fileName: string) { const allReplacements = getNonOverlappingReplacements(documentFixes); fixes.push({ description: `Fix all auto-fixable tslint failures`, changes: [{ fileName: fileName, textChanges: allReplacements.map(each => convertReplacementToTextChange(each)) }] }); } function getReplacement(failure: tslint.RuleFailure, at:number): tslint.Replacement { return getReplacements(failure.getFix())[at]; } function sortFailures(failures: tslint.RuleFailure[]):tslint.RuleFailure[] { // The failures.replacements are sorted by position, we sort on the position of the first replacement return failures.sort((a, b) => { return getReplacement(a, 0).start - getReplacement(b, 0).start; }); } function getNonOverlappingReplacements(documentFixes: Map<string, tslint.RuleFailure>): tslint.Replacement[] { function overlaps(a: tslint.Replacement, b: tslint.Replacement): boolean { return a.end >= b.start; } let sortedFailures = sortFailures([...documentFixes.values()]); let nonOverlapping: tslint.Replacement[] = []; for (let i = 0; i < sortedFailures.length; i++) { let replacements = getReplacements(sortedFailures[i].getFix()); if (i === 0 || !overlaps(nonOverlapping[nonOverlapping.length - 1], replacements[0])) { nonOverlapping.push(...replacements) } } return nonOverlapping; } proxy.getSemanticDiagnostics = (fileName: string) => { const prior = oldLS.getSemanticDiagnostics(fileName); if (config.supressWhileTypeErrorsPresent && prior.length > 0) { return prior; } try { info.project.projectService.logger.info(`Computing tslint semantic diagnostics...`); if (codeFixActions.has(fileName)) { codeFixActions.delete(fileName); } if (config.ignoreDefinitionFiles === true && fileName.endsWith('.d.ts')) { return prior; } try { configuration = getConfiguration(fileName, config.configFile); } catch (err) { // TODO: show the reason for the configuration failure to the user and not only in the log // https://github.com/Microsoft/TypeScript/issues/15913 info.project.projectService.logger.info(getConfigurationFailureMessage(err)) return prior; } let result: tslint.LintResult; // tslint writes warning messages using console.warn() // capture the warnings and write them to the tslint plugin log let warn = console.warn; console.warn = captureWarnings; try { // protect against tslint crashes // TODO the types of the Program provided by tsserver libary are not compatible with the one provided by typescript // casting away the type let options: tslint.ILinterOptions = { fix: false }; let linter = new tslint.Linter(options, <any>oldLS.getProgram()); linter.lint(fileName, "", configuration); result = linter.getResult(); } catch (err) { let errorMessage = `unknown error`; if (typeof err.message === 'string' || err.message instanceof String) { errorMessage = <string>err.message; } info.project.projectService.logger.info('tslint error ' + errorMessage); return prior; } finally { console.warn = warn; } if (result.failures.length > 0) { const tslintProblems = filterProblemsForDocument(fileName, result.failures); if (tslintProblems && tslintProblems.length) { const file = oldLS.getProgram().getSourceFile(fileName); const diagnostics = prior ? [...prior] : []; tslintProblems.forEach(problem => { diagnostics.push(makeDiagnostic(problem, file)); recordCodeAction(problem, file); }); return diagnostics; } } } catch (e) { info.project.projectService.logger.info(`tslint-language service error: ${e.toString()}`); info.project.projectService.logger.info(`Stack trace: ${e.stack}`); } return prior; }; proxy.getCodeFixesAtPosition = function (fileName: string, start: number, end: number, errorCodes: number[], formatOptions: ts.FormatCodeSettings, userPreferences: ts.UserPreferences): ReadonlyArray<ts.CodeFixAction> { let prior = oldLS.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, userPreferences); if (config.supressWhileTypeErrorsPresent && prior.length > 0) { return prior; } info.project.projectService.logger.info("tslint-language-service getCodeFixes " + errorCodes[0]); let documentFixes = codeFixActions.get(fileName); if (documentFixes) { const fixes = prior ? [...prior] : []; let problem = documentFixes.get(computeKey(start, end)); if (problem) { addRuleFailureFix(fixes, problem, fileName); addRuleFailureFixAll(fixes, problem.getRuleName(), documentFixes, fileName); } addAllAutoFixable(fixes, documentFixes, fileName); if (problem) { addOpenConfigurationFix(fixes); addDisableRuleFix(fixes, problem, fileName, oldLS.getProgram().getSourceFile(fileName)); } return fixes; } return prior; }; return proxy; } return { create }; } export = init; /* @internal */ // work around for missing API to register a code fix namespace codefix { export interface CodeFix { errorCodes: number[]; getCodeActions(context: any): ts.CodeAction[] | undefined; } }
the_stack
import * as assert from 'assert'; import { timeout } from 'vs/base/common/async'; import { bufferToReadable, VSBuffer } from 'vs/base/common/buffer'; import { consumeReadable, consumeStream, isReadable, isReadableBufferedStream, isReadableStream, listenStream, newWriteableStream, peekReadable, peekStream, prefixedReadable, prefixedStream, Readable, ReadableStream, toReadable, toStream, transform } from 'vs/base/common/stream'; suite('Stream', () => { test('isReadable', () => { assert.ok(!isReadable(undefined)); assert.ok(!isReadable(Object.create(null))); assert.ok(isReadable(bufferToReadable(VSBuffer.fromString('')))); }); test('isReadableStream', () => { assert.ok(!isReadableStream(undefined)); assert.ok(!isReadableStream(Object.create(null))); assert.ok(isReadableStream(newWriteableStream(d => d))); }); test('isReadableBufferedStream', async () => { assert.ok(!isReadableBufferedStream(Object.create(null))); const stream = newWriteableStream(d => d); stream.end(); const bufferedStream = await peekStream(stream, 1); assert.ok(isReadableBufferedStream(bufferedStream)); }); test('WriteableStream - basics', () => { const stream = newWriteableStream<string>(strings => strings.join()); let error = false; stream.on('error', e => { error = true; }); let end = false; stream.on('end', () => { end = true; }); stream.write('Hello'); const chunks: string[] = []; stream.on('data', data => { chunks.push(data); }); assert.strictEqual(chunks[0], 'Hello'); stream.write('World'); assert.strictEqual(chunks[1], 'World'); assert.strictEqual(error, false); assert.strictEqual(end, false); stream.pause(); stream.write('1'); stream.write('2'); stream.write('3'); assert.strictEqual(chunks.length, 2); stream.resume(); assert.strictEqual(chunks.length, 3); assert.strictEqual(chunks[2], '1,2,3'); stream.error(new Error()); assert.strictEqual(error, true); error = false; stream.error(new Error()); assert.strictEqual(error, true); stream.end('Final Bit'); assert.strictEqual(chunks.length, 4); assert.strictEqual(chunks[3], 'Final Bit'); assert.strictEqual(end, true); stream.destroy(); stream.write('Unexpected'); assert.strictEqual(chunks.length, 4); }); test('WriteableStream - end with empty string works', async () => { const reducer = (strings: string[]) => strings.length > 0 ? strings.join() : 'error'; const stream = newWriteableStream<string>(reducer); stream.end(''); const result = await consumeStream(stream, reducer); assert.strictEqual(result, ''); }); test('WriteableStream - end with error works', async () => { const reducer = (errors: Error[]) => errors[0]; const stream = newWriteableStream<Error>(reducer); stream.end(new Error('error')); const result = await consumeStream(stream, reducer); assert.ok(result instanceof Error); }); test('WriteableStream - removeListener', () => { const stream = newWriteableStream<string>(strings => strings.join()); let error = false; const errorListener = (e: Error) => { error = true; }; stream.on('error', errorListener); let data = false; const dataListener = () => { data = true; }; stream.on('data', dataListener); stream.write('Hello'); assert.strictEqual(data, true); data = false; stream.removeListener('data', dataListener); stream.write('World'); assert.strictEqual(data, false); stream.error(new Error()); assert.strictEqual(error, true); error = false; stream.removeListener('error', errorListener); // always leave at least one error listener to streams to avoid unexpected errors during test running stream.on('error', () => { }); stream.error(new Error()); assert.strictEqual(error, false); }); test('WriteableStream - highWaterMark', async () => { const stream = newWriteableStream<string>(strings => strings.join(), { highWaterMark: 3 }); let res = stream.write('1'); assert.ok(!res); res = stream.write('2'); assert.ok(!res); res = stream.write('3'); assert.ok(!res); let promise1 = stream.write('4'); assert.ok(promise1 instanceof Promise); let promise2 = stream.write('5'); assert.ok(promise2 instanceof Promise); let drained1 = false; (async () => { await promise1; drained1 = true; })(); let drained2 = false; (async () => { await promise2; drained2 = true; })(); let data: string | undefined = undefined; stream.on('data', chunk => { data = chunk; }); assert.ok(data); await timeout(0); assert.strictEqual(drained1, true); assert.strictEqual(drained2, true); }); test('consumeReadable', () => { const readable = arrayToReadable(['1', '2', '3', '4', '5']); const consumed = consumeReadable(readable, strings => strings.join()); assert.strictEqual(consumed, '1,2,3,4,5'); }); test('peekReadable', () => { for (let i = 0; i < 5; i++) { const readable = arrayToReadable(['1', '2', '3', '4', '5']); const consumedOrReadable = peekReadable(readable, strings => strings.join(), i); if (typeof consumedOrReadable === 'string') { assert.fail('Unexpected result'); } else { const consumed = consumeReadable(consumedOrReadable, strings => strings.join()); assert.strictEqual(consumed, '1,2,3,4,5'); } } let readable = arrayToReadable(['1', '2', '3', '4', '5']); let consumedOrReadable = peekReadable(readable, strings => strings.join(), 5); assert.strictEqual(consumedOrReadable, '1,2,3,4,5'); readable = arrayToReadable(['1', '2', '3', '4', '5']); consumedOrReadable = peekReadable(readable, strings => strings.join(), 6); assert.strictEqual(consumedOrReadable, '1,2,3,4,5'); }); test('peekReadable - error handling', async () => { // 0 Chunks let stream = newWriteableStream(data => data); let error: Error | undefined = undefined; let promise = (async () => { try { await peekStream(stream, 1); } catch (err) { error = err; } })(); stream.error(new Error()); await promise; assert.ok(error); // 1 Chunk stream = newWriteableStream(data => data); error = undefined; promise = (async () => { try { await peekStream(stream, 1); } catch (err) { error = err; } })(); stream.write('foo'); stream.error(new Error()); await promise; assert.ok(error); // 2 Chunks stream = newWriteableStream(data => data); error = undefined; promise = (async () => { try { await peekStream(stream, 1); } catch (err) { error = err; } })(); stream.write('foo'); stream.write('bar'); stream.error(new Error()); await promise; assert.ok(!error); stream.on('error', err => error = err); stream.on('data', chunk => { }); assert.ok(error); }); function arrayToReadable<T>(array: T[]): Readable<T> { return { read: () => array.shift() || null }; } function readableToStream(readable: Readable<string>): ReadableStream<string> { const stream = newWriteableStream<string>(strings => strings.join()); // Simulate async behavior setTimeout(() => { let chunk: string | null = null; while ((chunk = readable.read()) !== null) { stream.write(chunk); } stream.end(); }, 0); return stream; } test('consumeStream', async () => { const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5'])); const consumed = await consumeStream(stream, strings => strings.join()); assert.strictEqual(consumed, '1,2,3,4,5'); }); test('consumeStream - without reducer', async () => { const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5'])); const consumed = await consumeStream(stream); assert.strictEqual(consumed, undefined); }); test('consumeStream - without reducer and error', async () => { const stream = newWriteableStream<string>(strings => strings.join()); stream.error(new Error()); const consumed = await consumeStream(stream); assert.strictEqual(consumed, undefined); }); test('listenStream', () => { const stream = newWriteableStream<string>(strings => strings.join()); let error = false; let end = false; let data = ''; listenStream(stream, { onData: d => { data = d; }, onError: e => { error = true; }, onEnd: () => { end = true; } }); stream.write('Hello'); assert.strictEqual(data, 'Hello'); stream.write('World'); assert.strictEqual(data, 'World'); assert.strictEqual(error, false); assert.strictEqual(end, false); stream.error(new Error()); assert.strictEqual(error, true); stream.end('Final Bit'); assert.strictEqual(end, true); }); test('listenStream - dispose', () => { const stream = newWriteableStream<string>(strings => strings.join()); let error = false; let end = false; let data = ''; const disposable = listenStream(stream, { onData: d => { data = d; }, onError: e => { error = true; }, onEnd: () => { end = true; } }); disposable.dispose(); stream.write('Hello'); assert.strictEqual(data, ''); stream.write('World'); assert.strictEqual(data, ''); stream.error(new Error()); assert.strictEqual(error, false); stream.end('Final Bit'); assert.strictEqual(end, false); }); test('peekStream', async () => { for (let i = 0; i < 5; i++) { const stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5'])); const result = await peekStream(stream, i); assert.strictEqual(stream, result.stream); if (result.ended) { assert.fail('Unexpected result, stream should not have ended yet'); } else { assert.strictEqual(result.buffer.length, i + 1, `maxChunks: ${i}`); const additionalResult: string[] = []; await consumeStream(stream, strings => { additionalResult.push(...strings); return strings.join(); }); assert.strictEqual([...result.buffer, ...additionalResult].join(), '1,2,3,4,5'); } } let stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5'])); let result = await peekStream(stream, 5); assert.strictEqual(stream, result.stream); assert.strictEqual(result.buffer.join(), '1,2,3,4,5'); assert.strictEqual(result.ended, true); stream = readableToStream(arrayToReadable(['1', '2', '3', '4', '5'])); result = await peekStream(stream, 6); assert.strictEqual(stream, result.stream); assert.strictEqual(result.buffer.join(), '1,2,3,4,5'); assert.strictEqual(result.ended, true); }); test('toStream', async () => { const stream = toStream('1,2,3,4,5', strings => strings.join()); const consumed = await consumeStream(stream, strings => strings.join()); assert.strictEqual(consumed, '1,2,3,4,5'); }); test('toReadable', async () => { const readable = toReadable('1,2,3,4,5'); const consumed = consumeReadable(readable, strings => strings.join()); assert.strictEqual(consumed, '1,2,3,4,5'); }); test('transform', async () => { const source = newWriteableStream<string>(strings => strings.join()); const result = transform(source, { data: string => string + string }, strings => strings.join()); // Simulate async behavior setTimeout(() => { source.write('1'); source.write('2'); source.write('3'); source.write('4'); source.end('5'); }, 0); const consumed = await consumeStream(result, strings => strings.join()); assert.strictEqual(consumed, '11,22,33,44,55'); }); test('events are delivered even if a listener is removed during delivery', () => { const stream = newWriteableStream<string>(strings => strings.join()); let listener1Called = false; let listener2Called = false; const listener1 = () => { stream.removeListener('end', listener1); listener1Called = true; }; const listener2 = () => { listener2Called = true; }; stream.on('end', listener1); stream.on('end', listener2); stream.on('data', () => { }); stream.end(''); assert.strictEqual(listener1Called, true); assert.strictEqual(listener2Called, true); }); test('prefixedReadable', () => { // Basic let readable = prefixedReadable('1,2', arrayToReadable(['3', '4', '5']), val => val.join(',')); assert.strictEqual(consumeReadable(readable, val => val.join(',')), '1,2,3,4,5'); // Empty readable = prefixedReadable('empty', arrayToReadable<string>([]), val => val.join(',')); assert.strictEqual(consumeReadable(readable, val => val.join(',')), 'empty'); }); test('prefixedStream', async () => { // Basic let stream = newWriteableStream<string>(strings => strings.join()); stream.write('3'); stream.write('4'); stream.write('5'); stream.end(); let prefixStream = prefixedStream<string>('1,2', stream, val => val.join(',')); assert.strictEqual(await consumeStream(prefixStream, val => val.join(',')), '1,2,3,4,5'); // Empty stream = newWriteableStream<string>(strings => strings.join()); stream.end(); prefixStream = prefixedStream<string>('1,2', stream, val => val.join(',')); assert.strictEqual(await consumeStream(prefixStream, val => val.join(',')), '1,2'); // Error stream = newWriteableStream<string>(strings => strings.join()); stream.error(new Error('fail')); prefixStream = prefixedStream<string>('error', stream, val => val.join(',')); let error; try { await consumeStream(prefixStream, val => val.join(',')); } catch (e) { error = e; } assert.ok(error); }); });
the_stack
declare namespace GoogleAppsScript { namespace YoutubePartner { namespace Collection { interface AssetLabelsCollection { // Insert an asset label for an owner. insert(resource: Schema.AssetLabel): YoutubePartner.Schema.AssetLabel; // Insert an asset label for an owner. insert(resource: Schema.AssetLabel, optionalArgs: object): YoutubePartner.Schema.AssetLabel; // Retrieves a list of all asset labels for an owner. list(): YoutubePartner.Schema.AssetLabelListResponse; // Retrieves a list of all asset labels for an owner. list(optionalArgs: object): YoutubePartner.Schema.AssetLabelListResponse; } interface AssetMatchPolicyCollection { // Retrieves the match policy assigned to the specified asset by the content owner associated with the authenticated user. This information is only accessible to an owner of the asset. get(assetId: string): YoutubePartner.Schema.AssetMatchPolicy; // Retrieves the match policy assigned to the specified asset by the content owner associated with the authenticated user. This information is only accessible to an owner of the asset. get(assetId: string, optionalArgs: object): YoutubePartner.Schema.AssetMatchPolicy; // Updates the asset's match policy. If an asset has multiple owners, each owner may set its own match policy for the asset. YouTube then computes the match policy that is actually applied for the asset based on the territories where each owner owns the asset. This method supports patch semantics. patch(resource: Schema.AssetMatchPolicy, assetId: string): YoutubePartner.Schema.AssetMatchPolicy; // Updates the asset's match policy. If an asset has multiple owners, each owner may set its own match policy for the asset. YouTube then computes the match policy that is actually applied for the asset based on the territories where each owner owns the asset. This method supports patch semantics. patch(resource: Schema.AssetMatchPolicy, assetId: string, optionalArgs: object): YoutubePartner.Schema.AssetMatchPolicy; // Updates the asset's match policy. If an asset has multiple owners, each owner may set its own match policy for the asset. YouTube then computes the match policy that is actually applied for the asset based on the territories where each owner owns the asset. update(resource: Schema.AssetMatchPolicy, assetId: string): YoutubePartner.Schema.AssetMatchPolicy; // Updates the asset's match policy. If an asset has multiple owners, each owner may set its own match policy for the asset. YouTube then computes the match policy that is actually applied for the asset based on the territories where each owner owns the asset. update(resource: Schema.AssetMatchPolicy, assetId: string, optionalArgs: object): YoutubePartner.Schema.AssetMatchPolicy; } interface AssetRelationshipsCollection { // Creates a relationship that links two assets. insert(resource: Schema.AssetRelationship): YoutubePartner.Schema.AssetRelationship; // Creates a relationship that links two assets. insert(resource: Schema.AssetRelationship, optionalArgs: object): YoutubePartner.Schema.AssetRelationship; // Retrieves a list of relationships for a given asset. The list contains relationships where the specified asset is either the parent (embedding) or child (embedded) asset in the relationship. list(assetId: string): YoutubePartner.Schema.AssetRelationshipListResponse; // Retrieves a list of relationships for a given asset. The list contains relationships where the specified asset is either the parent (embedding) or child (embedded) asset in the relationship. list(assetId: string, optionalArgs: object): YoutubePartner.Schema.AssetRelationshipListResponse; // Deletes a relationship between two assets. remove(assetRelationshipId: string): void; // Deletes a relationship between two assets. remove(assetRelationshipId: string, optionalArgs: object): void; } interface AssetSearchCollection { // Searches for assets based on asset metadata. The method can retrieve all assets or only assets owned by the content owner. This method mimics the functionality of the advanced search feature on the Assets page in CMS. list(): YoutubePartner.Schema.AssetSearchResponse; // Searches for assets based on asset metadata. The method can retrieve all assets or only assets owned by the content owner. This method mimics the functionality of the advanced search feature on the Assets page in CMS. list(optionalArgs: object): YoutubePartner.Schema.AssetSearchResponse; } interface AssetSharesCollection { // This method either retrieves a list of asset shares the partner owns and that map to a specified asset view ID or it retrieves a list of asset views associated with a specified asset share ID owned by the partner. list(assetId: string): YoutubePartner.Schema.AssetShareListResponse; // This method either retrieves a list of asset shares the partner owns and that map to a specified asset view ID or it retrieves a list of asset views associated with a specified asset share ID owned by the partner. list(assetId: string, optionalArgs: object): YoutubePartner.Schema.AssetShareListResponse; } interface AssetsCollection { // Retrieves the metadata for the specified asset. Note that if the request identifies an asset that has been merged with another asset, meaning that YouTube identified the requested asset as a duplicate, then the request retrieves the merged, or synthesized, asset. get(assetId: string): YoutubePartner.Schema.Asset; // Retrieves the metadata for the specified asset. Note that if the request identifies an asset that has been merged with another asset, meaning that YouTube identified the requested asset as a duplicate, then the request retrieves the merged, or synthesized, asset. get(assetId: string, optionalArgs: object): YoutubePartner.Schema.Asset; // Inserts an asset with the specified metadata. After inserting an asset, you can set its ownership data and match policy. insert(resource: Schema.Asset): YoutubePartner.Schema.Asset; // Inserts an asset with the specified metadata. After inserting an asset, you can set its ownership data and match policy. insert(resource: Schema.Asset, optionalArgs: object): YoutubePartner.Schema.Asset; // Retrieves a list of assets based on asset metadata. The method can retrieve all assets or only assets owned by the content owner. // Note that in cases where duplicate assets have been merged, the API response only contains the synthesized asset. (It does not contain the constituent assets that were merged into the synthesized asset.) list(id: string): YoutubePartner.Schema.AssetListResponse; // Retrieves a list of assets based on asset metadata. The method can retrieve all assets or only assets owned by the content owner. // Note that in cases where duplicate assets have been merged, the API response only contains the synthesized asset. (It does not contain the constituent assets that were merged into the synthesized asset.) list(id: string, optionalArgs: object): YoutubePartner.Schema.AssetListResponse; // Updates the metadata for the specified asset. This method supports patch semantics. patch(resource: Schema.Asset, assetId: string): YoutubePartner.Schema.Asset; // Updates the metadata for the specified asset. This method supports patch semantics. patch(resource: Schema.Asset, assetId: string, optionalArgs: object): YoutubePartner.Schema.Asset; // Updates the metadata for the specified asset. update(resource: Schema.Asset, assetId: string): YoutubePartner.Schema.Asset; // Updates the metadata for the specified asset. update(resource: Schema.Asset, assetId: string, optionalArgs: object): YoutubePartner.Schema.Asset; } interface CampaignsCollection { // Retrieves a particular campaign for an owner. get(campaignId: string): YoutubePartner.Schema.Campaign; // Retrieves a particular campaign for an owner. get(campaignId: string, optionalArgs: object): YoutubePartner.Schema.Campaign; // Insert a new campaign for an owner using the specified campaign data. insert(resource: Schema.Campaign): YoutubePartner.Schema.Campaign; // Insert a new campaign for an owner using the specified campaign data. insert(resource: Schema.Campaign, optionalArgs: object): YoutubePartner.Schema.Campaign; // Retrieves a list of campaigns for an owner. list(): YoutubePartner.Schema.CampaignList; // Retrieves a list of campaigns for an owner. list(optionalArgs: object): YoutubePartner.Schema.CampaignList; // Update the data for a specific campaign. This method supports patch semantics. patch(resource: Schema.Campaign, campaignId: string): YoutubePartner.Schema.Campaign; // Update the data for a specific campaign. This method supports patch semantics. patch(resource: Schema.Campaign, campaignId: string, optionalArgs: object): YoutubePartner.Schema.Campaign; // Deletes a specified campaign for an owner. remove(campaignId: string): void; // Deletes a specified campaign for an owner. remove(campaignId: string, optionalArgs: object): void; // Update the data for a specific campaign. update(resource: Schema.Campaign, campaignId: string): YoutubePartner.Schema.Campaign; // Update the data for a specific campaign. update(resource: Schema.Campaign, campaignId: string, optionalArgs: object): YoutubePartner.Schema.Campaign; } interface ClaimHistoryCollection { // Retrieves the claim history for a specified claim. get(claimId: string): YoutubePartner.Schema.ClaimHistory; // Retrieves the claim history for a specified claim. get(claimId: string, optionalArgs: object): YoutubePartner.Schema.ClaimHistory; } interface ClaimSearchCollection { // Retrieves a list of claims that match the search criteria. You can search for claims that are associated with a specific asset or video or that match a specified query string. list(): YoutubePartner.Schema.ClaimSearchResponse; // Retrieves a list of claims that match the search criteria. You can search for claims that are associated with a specific asset or video or that match a specified query string. list(optionalArgs: object): YoutubePartner.Schema.ClaimSearchResponse; } interface ClaimsCollection { // Retrieves a specific claim by ID. get(claimId: string): YoutubePartner.Schema.Claim; // Retrieves a specific claim by ID. get(claimId: string, optionalArgs: object): YoutubePartner.Schema.Claim; // Creates a claim. The video being claimed must have been uploaded to a channel associated with the same content owner as the API user sending the request. You can set the claim's policy in any of the following ways: // - Use the claim resource's policy property to identify a saved policy by its unique ID. // - Use the claim resource's policy property to specify a custom set of rules. insert(resource: Schema.Claim): YoutubePartner.Schema.Claim; // Creates a claim. The video being claimed must have been uploaded to a channel associated with the same content owner as the API user sending the request. You can set the claim's policy in any of the following ways: // - Use the claim resource's policy property to identify a saved policy by its unique ID. // - Use the claim resource's policy property to specify a custom set of rules. insert(resource: Schema.Claim, optionalArgs: object): YoutubePartner.Schema.Claim; // Retrieves a list of claims administered by the content owner associated with the currently authenticated user. Results are sorted in descending order of creation time. list(): YoutubePartner.Schema.ClaimListResponse; // Retrieves a list of claims administered by the content owner associated with the currently authenticated user. Results are sorted in descending order of creation time. list(optionalArgs: object): YoutubePartner.Schema.ClaimListResponse; // Updates an existing claim by either changing its policy or its status. You can update a claim's status from active to inactive to effectively release the claim. This method supports patch semantics. patch(resource: Schema.Claim, claimId: string): YoutubePartner.Schema.Claim; // Updates an existing claim by either changing its policy or its status. You can update a claim's status from active to inactive to effectively release the claim. This method supports patch semantics. patch(resource: Schema.Claim, claimId: string, optionalArgs: object): YoutubePartner.Schema.Claim; // Updates an existing claim by either changing its policy or its status. You can update a claim's status from active to inactive to effectively release the claim. update(resource: Schema.Claim, claimId: string): YoutubePartner.Schema.Claim; // Updates an existing claim by either changing its policy or its status. You can update a claim's status from active to inactive to effectively release the claim. update(resource: Schema.Claim, claimId: string, optionalArgs: object): YoutubePartner.Schema.Claim; } interface ContentOwnerAdvertisingOptionsCollection { // Retrieves advertising options for the content owner associated with the authenticated user. get(): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Retrieves advertising options for the content owner associated with the authenticated user. get(optionalArgs: object): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Updates advertising options for the content owner associated with the authenticated API user. This method supports patch semantics. patch(resource: Schema.ContentOwnerAdvertisingOption): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Updates advertising options for the content owner associated with the authenticated API user. This method supports patch semantics. patch(resource: Schema.ContentOwnerAdvertisingOption, optionalArgs: object): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Updates advertising options for the content owner associated with the authenticated API user. update(resource: Schema.ContentOwnerAdvertisingOption): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Updates advertising options for the content owner associated with the authenticated API user. update(resource: Schema.ContentOwnerAdvertisingOption, optionalArgs: object): YoutubePartner.Schema.ContentOwnerAdvertisingOption; } interface ContentOwnersCollection { // Retrieves information about the specified content owner. get(contentOwnerId: string): YoutubePartner.Schema.ContentOwner; // Retrieves information about the specified content owner. get(contentOwnerId: string, optionalArgs: object): YoutubePartner.Schema.ContentOwner; // Retrieves a list of content owners that match the request criteria. list(): YoutubePartner.Schema.ContentOwnerListResponse; // Retrieves a list of content owners that match the request criteria. list(optionalArgs: object): YoutubePartner.Schema.ContentOwnerListResponse; } interface LiveCuepointsCollection { // Inserts a cuepoint into a live broadcast. insert(resource: Schema.LiveCuepoint, channelId: string): YoutubePartner.Schema.LiveCuepoint; // Inserts a cuepoint into a live broadcast. insert(resource: Schema.LiveCuepoint, channelId: string, optionalArgs: object): YoutubePartner.Schema.LiveCuepoint; } interface MetadataHistoryCollection { // Retrieves a list of all metadata provided for an asset, regardless of which content owner provided the data. list(assetId: string): YoutubePartner.Schema.MetadataHistoryListResponse; // Retrieves a list of all metadata provided for an asset, regardless of which content owner provided the data. list(assetId: string, optionalArgs: object): YoutubePartner.Schema.MetadataHistoryListResponse; } interface OrdersCollection { // Retrieve the details of an existing order. get(orderId: string): YoutubePartner.Schema.Order; // Retrieve the details of an existing order. get(orderId: string, optionalArgs: object): YoutubePartner.Schema.Order; // Creates a new basic order entry in the YouTube premium asset order management system. You must supply at least a country and channel in the new order. insert(resource: Schema.Order): YoutubePartner.Schema.Order; // Creates a new basic order entry in the YouTube premium asset order management system. You must supply at least a country and channel in the new order. insert(resource: Schema.Order, optionalArgs: object): YoutubePartner.Schema.Order; // Return a list of orders, filtered by the parameters below, may return more than a single page of results. list(): YoutubePartner.Schema.OrderListResponse; // Return a list of orders, filtered by the parameters below, may return more than a single page of results. list(optionalArgs: object): YoutubePartner.Schema.OrderListResponse; // Update the values in an existing order. This method supports patch semantics. patch(resource: Schema.Order, orderId: string): YoutubePartner.Schema.Order; // Update the values in an existing order. This method supports patch semantics. patch(resource: Schema.Order, orderId: string, optionalArgs: object): YoutubePartner.Schema.Order; // Delete an order, which moves orders to inactive state and removes any associated video. remove(orderId: string): void; // Delete an order, which moves orders to inactive state and removes any associated video. remove(orderId: string, optionalArgs: object): void; // Update the values in an existing order. update(resource: Schema.Order, orderId: string): YoutubePartner.Schema.Order; // Update the values in an existing order. update(resource: Schema.Order, orderId: string, optionalArgs: object): YoutubePartner.Schema.Order; } interface OwnershipCollection { // Retrieves the ownership data provided for the specified asset by the content owner associated with the authenticated user. get(assetId: string): YoutubePartner.Schema.RightsOwnership; // Retrieves the ownership data provided for the specified asset by the content owner associated with the authenticated user. get(assetId: string, optionalArgs: object): YoutubePartner.Schema.RightsOwnership; // Provides new ownership information for the specified asset. Note that YouTube may receive ownership information from multiple sources. For example, if an asset has multiple owners, each owner might send ownership data for the asset. YouTube algorithmically combines the ownership data received from all of those sources to generate the asset's canonical ownership data, which should provide the most comprehensive and accurate representation of the asset's ownership. This method supports patch semantics. patch(resource: Schema.RightsOwnership, assetId: string): YoutubePartner.Schema.RightsOwnership; // Provides new ownership information for the specified asset. Note that YouTube may receive ownership information from multiple sources. For example, if an asset has multiple owners, each owner might send ownership data for the asset. YouTube algorithmically combines the ownership data received from all of those sources to generate the asset's canonical ownership data, which should provide the most comprehensive and accurate representation of the asset's ownership. This method supports patch semantics. patch(resource: Schema.RightsOwnership, assetId: string, optionalArgs: object): YoutubePartner.Schema.RightsOwnership; // Provides new ownership information for the specified asset. Note that YouTube may receive ownership information from multiple sources. For example, if an asset has multiple owners, each owner might send ownership data for the asset. YouTube algorithmically combines the ownership data received from all of those sources to generate the asset's canonical ownership data, which should provide the most comprehensive and accurate representation of the asset's ownership. update(resource: Schema.RightsOwnership, assetId: string): YoutubePartner.Schema.RightsOwnership; // Provides new ownership information for the specified asset. Note that YouTube may receive ownership information from multiple sources. For example, if an asset has multiple owners, each owner might send ownership data for the asset. YouTube algorithmically combines the ownership data received from all of those sources to generate the asset's canonical ownership data, which should provide the most comprehensive and accurate representation of the asset's ownership. update(resource: Schema.RightsOwnership, assetId: string, optionalArgs: object): YoutubePartner.Schema.RightsOwnership; } interface OwnershipHistoryCollection { // Retrieves a list of the ownership data for an asset, regardless of which content owner provided the data. The list only includes the most recent ownership data for each content owner. However, if the content owner has submitted ownership data through multiple data sources (API, content feeds, etc.), the list will contain the most recent data for each content owner and data source. list(assetId: string): YoutubePartner.Schema.OwnershipHistoryListResponse; // Retrieves a list of the ownership data for an asset, regardless of which content owner provided the data. The list only includes the most recent ownership data for each content owner. However, if the content owner has submitted ownership data through multiple data sources (API, content feeds, etc.), the list will contain the most recent data for each content owner and data source. list(assetId: string, optionalArgs: object): YoutubePartner.Schema.OwnershipHistoryListResponse; } interface PackageCollection { // Retrieves information for the specified package. get(packageId: string): YoutubePartner.Schema.Package; // Retrieves information for the specified package. get(packageId: string, optionalArgs: object): YoutubePartner.Schema.Package; // Inserts a metadata-only package. insert(resource: Schema.Package): YoutubePartner.Schema.PackageInsertResponse; // Inserts a metadata-only package. insert(resource: Schema.Package, optionalArgs: object): YoutubePartner.Schema.PackageInsertResponse; } interface PoliciesCollection { // Retrieves the specified saved policy. get(policyId: string): YoutubePartner.Schema.Policy; // Retrieves the specified saved policy. get(policyId: string, optionalArgs: object): YoutubePartner.Schema.Policy; // Creates a saved policy. insert(resource: Schema.Policy): YoutubePartner.Schema.Policy; // Creates a saved policy. insert(resource: Schema.Policy, optionalArgs: object): YoutubePartner.Schema.Policy; // Retrieves a list of the content owner's saved policies. list(): YoutubePartner.Schema.PolicyList; // Retrieves a list of the content owner's saved policies. list(optionalArgs: object): YoutubePartner.Schema.PolicyList; // Updates the specified saved policy. This method supports patch semantics. patch(resource: Schema.Policy, policyId: string): YoutubePartner.Schema.Policy; // Updates the specified saved policy. This method supports patch semantics. patch(resource: Schema.Policy, policyId: string, optionalArgs: object): YoutubePartner.Schema.Policy; // Updates the specified saved policy. update(resource: Schema.Policy, policyId: string): YoutubePartner.Schema.Policy; // Updates the specified saved policy. update(resource: Schema.Policy, policyId: string, optionalArgs: object): YoutubePartner.Schema.Policy; } interface PublishersCollection { // Retrieves information about the specified publisher. get(publisherId: string): YoutubePartner.Schema.Publisher; // Retrieves information about the specified publisher. get(publisherId: string, optionalArgs: object): YoutubePartner.Schema.Publisher; // Retrieves a list of publishers that match the request criteria. This method is analogous to a publisher search function. list(): YoutubePartner.Schema.PublisherList; // Retrieves a list of publishers that match the request criteria. This method is analogous to a publisher search function. list(optionalArgs: object): YoutubePartner.Schema.PublisherList; } interface ReferenceConflictsCollection { // Retrieves information about the specified reference conflict. get(referenceConflictId: string): YoutubePartner.Schema.ReferenceConflict; // Retrieves information about the specified reference conflict. get(referenceConflictId: string, optionalArgs: object): YoutubePartner.Schema.ReferenceConflict; // Retrieves a list of unresolved reference conflicts. list(): YoutubePartner.Schema.ReferenceConflictListResponse; // Retrieves a list of unresolved reference conflicts. list(optionalArgs: object): YoutubePartner.Schema.ReferenceConflictListResponse; } interface ReferencesCollection { // Retrieves information about the specified reference. get(referenceId: string): YoutubePartner.Schema.Reference; // Retrieves information about the specified reference. get(referenceId: string, optionalArgs: object): YoutubePartner.Schema.Reference; // Creates a reference in one of the following ways: // - If your request is uploading a reference file, YouTube creates the reference from the provided content. You can provide either a video/audio file or a pre-generated fingerprint. If you are providing a pre-generated fingerprint, set the reference resource's fpDirect property to true in the request body. In this flow, you can use either the multipart or resumable upload flows to provide the reference content. // - If you want to create a reference using a claimed video as the reference content, use the claimId parameter to identify the claim. insert(resource: Schema.Reference): YoutubePartner.Schema.Reference; // Creates a reference in one of the following ways: // - If your request is uploading a reference file, YouTube creates the reference from the provided content. You can provide either a video/audio file or a pre-generated fingerprint. If you are providing a pre-generated fingerprint, set the reference resource's fpDirect property to true in the request body. In this flow, you can use either the multipart or resumable upload flows to provide the reference content. // - If you want to create a reference using a claimed video as the reference content, use the claimId parameter to identify the claim. insert(resource: Schema.Reference, mediaData: any): YoutubePartner.Schema.Reference; // Creates a reference in one of the following ways: // - If your request is uploading a reference file, YouTube creates the reference from the provided content. You can provide either a video/audio file or a pre-generated fingerprint. If you are providing a pre-generated fingerprint, set the reference resource's fpDirect property to true in the request body. In this flow, you can use either the multipart or resumable upload flows to provide the reference content. // - If you want to create a reference using a claimed video as the reference content, use the claimId parameter to identify the claim. insert(resource: Schema.Reference, mediaData: any, optionalArgs: object): YoutubePartner.Schema.Reference; // Retrieves a list of references by ID or the list of references for the specified asset. list(): YoutubePartner.Schema.ReferenceListResponse; // Retrieves a list of references by ID or the list of references for the specified asset. list(optionalArgs: object): YoutubePartner.Schema.ReferenceListResponse; // Updates a reference. This method supports patch semantics. patch(resource: Schema.Reference, referenceId: string): YoutubePartner.Schema.Reference; // Updates a reference. This method supports patch semantics. patch(resource: Schema.Reference, referenceId: string, optionalArgs: object): YoutubePartner.Schema.Reference; // Updates a reference. update(resource: Schema.Reference, referenceId: string): YoutubePartner.Schema.Reference; // Updates a reference. update(resource: Schema.Reference, referenceId: string, optionalArgs: object): YoutubePartner.Schema.Reference; } interface SpreadsheetTemplateCollection { // Retrieves a list of spreadsheet templates for a content owner. list(): YoutubePartner.Schema.SpreadsheetTemplateListResponse; // Retrieves a list of spreadsheet templates for a content owner. list(optionalArgs: object): YoutubePartner.Schema.SpreadsheetTemplateListResponse; } interface UploaderCollection { // Retrieves a list of uploaders for a content owner. list(): YoutubePartner.Schema.UploaderListResponse; // Retrieves a list of uploaders for a content owner. list(optionalArgs: object): YoutubePartner.Schema.UploaderListResponse; } interface ValidatorCollection { // Validate a metadata file. validate(resource: Schema.ValidateRequest): YoutubePartner.Schema.ValidateResponse; // Validate a metadata file. validate(resource: Schema.ValidateRequest, optionalArgs: object): YoutubePartner.Schema.ValidateResponse; // Validate a metadata file asynchronously. validateAsync(resource: Schema.ValidateAsyncRequest): YoutubePartner.Schema.ValidateAsyncResponse; // Validate a metadata file asynchronously. validateAsync(resource: Schema.ValidateAsyncRequest, optionalArgs: object): YoutubePartner.Schema.ValidateAsyncResponse; // Get the asynchronous validation status. validateAsyncStatus(resource: Schema.ValidateStatusRequest): YoutubePartner.Schema.ValidateStatusResponse; // Get the asynchronous validation status. validateAsyncStatus(resource: Schema.ValidateStatusRequest, optionalArgs: object): YoutubePartner.Schema.ValidateStatusResponse; } interface VideoAdvertisingOptionsCollection { // Retrieves advertising settings for the specified video. get(videoId: string): YoutubePartner.Schema.VideoAdvertisingOption; // Retrieves advertising settings for the specified video. get(videoId: string, optionalArgs: object): YoutubePartner.Schema.VideoAdvertisingOption; // Retrieves details about the types of allowed ads for a specified partner- or user-uploaded video. getEnabledAds(videoId: string): YoutubePartner.Schema.VideoAdvertisingOptionGetEnabledAdsResponse; // Retrieves details about the types of allowed ads for a specified partner- or user-uploaded video. getEnabledAds(videoId: string, optionalArgs: object): YoutubePartner.Schema.VideoAdvertisingOptionGetEnabledAdsResponse; // Updates the advertising settings for the specified video. This method supports patch semantics. patch(resource: Schema.VideoAdvertisingOption, videoId: string): YoutubePartner.Schema.VideoAdvertisingOption; // Updates the advertising settings for the specified video. This method supports patch semantics. patch(resource: Schema.VideoAdvertisingOption, videoId: string, optionalArgs: object): YoutubePartner.Schema.VideoAdvertisingOption; // Updates the advertising settings for the specified video. update(resource: Schema.VideoAdvertisingOption, videoId: string): YoutubePartner.Schema.VideoAdvertisingOption; // Updates the advertising settings for the specified video. update(resource: Schema.VideoAdvertisingOption, videoId: string, optionalArgs: object): YoutubePartner.Schema.VideoAdvertisingOption; } interface WhitelistsCollection { // Retrieves a specific whitelisted channel by ID. get(id: string): YoutubePartner.Schema.Whitelist; // Retrieves a specific whitelisted channel by ID. get(id: string, optionalArgs: object): YoutubePartner.Schema.Whitelist; // Whitelist a YouTube channel for your content owner. Whitelisted channels are channels that are not owned or managed by you, but you would like to whitelist so that no claims from your assets are placed on videos uploaded to these channels. insert(resource: Schema.Whitelist): YoutubePartner.Schema.Whitelist; // Whitelist a YouTube channel for your content owner. Whitelisted channels are channels that are not owned or managed by you, but you would like to whitelist so that no claims from your assets are placed on videos uploaded to these channels. insert(resource: Schema.Whitelist, optionalArgs: object): YoutubePartner.Schema.Whitelist; // Retrieves a list of whitelisted channels for a content owner. list(): YoutubePartner.Schema.WhitelistListResponse; // Retrieves a list of whitelisted channels for a content owner. list(optionalArgs: object): YoutubePartner.Schema.WhitelistListResponse; // Removes a whitelisted channel for a content owner. remove(id: string): void; // Removes a whitelisted channel for a content owner. remove(id: string, optionalArgs: object): void; } } namespace Schema { interface AdBreak { midrollSeconds?: number | undefined; position?: string | undefined; slot?: YoutubePartner.Schema.AdSlot[] | undefined; } interface AdSlot { id?: string | undefined; type?: string | undefined; } interface AllowedAdvertisingOptions { adsOnEmbeds?: boolean | undefined; kind?: string | undefined; licAdFormats?: string[] | undefined; ugcAdFormats?: string[] | undefined; } interface Asset { aliasId?: string[] | undefined; id?: string | undefined; kind?: string | undefined; label?: string[] | undefined; matchPolicy?: YoutubePartner.Schema.AssetMatchPolicy | undefined; matchPolicyEffective?: YoutubePartner.Schema.AssetMatchPolicy | undefined; matchPolicyMine?: YoutubePartner.Schema.AssetMatchPolicy | undefined; metadata?: YoutubePartner.Schema.Metadata | undefined; metadataEffective?: YoutubePartner.Schema.Metadata | undefined; metadataMine?: YoutubePartner.Schema.Metadata | undefined; ownership?: YoutubePartner.Schema.RightsOwnership | undefined; ownershipConflicts?: YoutubePartner.Schema.OwnershipConflicts | undefined; ownershipEffective?: YoutubePartner.Schema.RightsOwnership | undefined; ownershipMine?: YoutubePartner.Schema.RightsOwnership | undefined; status?: string | undefined; timeCreated?: string | undefined; type?: string | undefined; } interface AssetLabel { kind?: string | undefined; labelName?: string | undefined; } interface AssetLabelListResponse { items?: YoutubePartner.Schema.AssetLabel[] | undefined; kind?: string | undefined; } interface AssetListResponse { items?: YoutubePartner.Schema.Asset[] | undefined; kind?: string | undefined; } interface AssetMatchPolicy { kind?: string | undefined; policyId?: string | undefined; rules?: YoutubePartner.Schema.PolicyRule[] | undefined; } interface AssetRelationship { childAssetId?: string | undefined; id?: string | undefined; kind?: string | undefined; parentAssetId?: string | undefined; } interface AssetRelationshipListResponse { items?: YoutubePartner.Schema.AssetRelationship[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface AssetSearchResponse { items?: YoutubePartner.Schema.AssetSnippet[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface AssetShare { kind?: string | undefined; shareId?: string | undefined; viewId?: string | undefined; } interface AssetShareListResponse { items?: YoutubePartner.Schema.AssetShare[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface AssetSnippet { customId?: string | undefined; id?: string | undefined; isrc?: string | undefined; iswc?: string | undefined; kind?: string | undefined; timeCreated?: string | undefined; title?: string | undefined; type?: string | undefined; } interface Campaign { campaignData?: YoutubePartner.Schema.CampaignData | undefined; id?: string | undefined; kind?: string | undefined; status?: string | undefined; timeCreated?: string | undefined; timeLastModified?: string | undefined; } interface CampaignData { campaignSource?: YoutubePartner.Schema.CampaignSource | undefined; expireTime?: string | undefined; name?: string | undefined; promotedContent?: YoutubePartner.Schema.PromotedContent[] | undefined; startTime?: string | undefined; } interface CampaignList { items?: YoutubePartner.Schema.Campaign[] | undefined; kind?: string | undefined; } interface CampaignSource { sourceType?: string | undefined; sourceValue?: string[] | undefined; } interface CampaignTargetLink { targetId?: string | undefined; targetType?: string | undefined; } interface Claim { appliedPolicy?: YoutubePartner.Schema.Policy | undefined; assetId?: string | undefined; blockOutsideOwnership?: boolean | undefined; contentType?: string | undefined; id?: string | undefined; isPartnerUploaded?: boolean | undefined; kind?: string | undefined; matchInfo?: YoutubePartner.Schema.ClaimMatchInfo | undefined; origin?: YoutubePartner.Schema.ClaimOrigin | undefined; policy?: YoutubePartner.Schema.Policy | undefined; status?: string | undefined; timeCreated?: string | undefined; videoId?: string | undefined; } interface ClaimEvent { kind?: string | undefined; reason?: string | undefined; source?: YoutubePartner.Schema.ClaimEventSource | undefined; time?: string | undefined; type?: string | undefined; typeDetails?: YoutubePartner.Schema.ClaimEventTypeDetails | undefined; } interface ClaimEventSource { contentOwnerId?: string | undefined; type?: string | undefined; userEmail?: string | undefined; } interface ClaimEventTypeDetails { appealExplanation?: string | undefined; disputeNotes?: string | undefined; disputeReason?: string | undefined; updateStatus?: string | undefined; } interface ClaimHistory { event?: YoutubePartner.Schema.ClaimEvent[] | undefined; id?: string | undefined; kind?: string | undefined; uploaderChannelId?: string | undefined; } interface ClaimListResponse { items?: YoutubePartner.Schema.Claim[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; previousPageToken?: string | undefined; } interface ClaimMatchInfo { longestMatch?: YoutubePartner.Schema.ClaimMatchInfoLongestMatch | undefined; matchSegments?: YoutubePartner.Schema.MatchSegment[] | undefined; referenceId?: string | undefined; totalMatch?: YoutubePartner.Schema.ClaimMatchInfoTotalMatch | undefined; } interface ClaimMatchInfoLongestMatch { durationSecs?: string | undefined; referenceOffset?: string | undefined; userVideoOffset?: string | undefined; } interface ClaimMatchInfoTotalMatch { referenceDurationSecs?: string | undefined; userVideoDurationSecs?: string | undefined; } interface ClaimOrigin { source?: string | undefined; } interface ClaimSearchResponse { items?: YoutubePartner.Schema.ClaimSnippet[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; previousPageToken?: string | undefined; } interface ClaimSnippet { assetId?: string | undefined; contentType?: string | undefined; id?: string | undefined; isPartnerUploaded?: boolean | undefined; kind?: string | undefined; origin?: YoutubePartner.Schema.ClaimSnippetOrigin | undefined; status?: string | undefined; thirdPartyClaim?: boolean | undefined; timeCreated?: string | undefined; timeStatusLastModified?: string | undefined; videoId?: string | undefined; videoTitle?: string | undefined; videoViews?: string | undefined; } interface ClaimSnippetOrigin { source?: string | undefined; } interface ClaimedVideoDefaults { autoGeneratedBreaks?: boolean | undefined; channelOverride?: boolean | undefined; kind?: string | undefined; newVideoDefaults?: string[] | undefined; } interface Conditions { contentMatchType?: string[] | undefined; matchDuration?: YoutubePartner.Schema.IntervalCondition[] | undefined; matchPercent?: YoutubePartner.Schema.IntervalCondition[] | undefined; referenceDuration?: YoutubePartner.Schema.IntervalCondition[] | undefined; referencePercent?: YoutubePartner.Schema.IntervalCondition[] | undefined; requiredTerritories?: YoutubePartner.Schema.TerritoryCondition | undefined; } interface ConflictingOwnership { owner?: string | undefined; ratio?: number | undefined; } interface ContentOwner { conflictNotificationEmail?: string | undefined; displayName?: string | undefined; disputeNotificationEmails?: string[] | undefined; fingerprintReportNotificationEmails?: string[] | undefined; id?: string | undefined; kind?: string | undefined; primaryNotificationEmails?: string[] | undefined; } interface ContentOwnerAdvertisingOption { allowedOptions?: YoutubePartner.Schema.AllowedAdvertisingOptions | undefined; claimedVideoOptions?: YoutubePartner.Schema.ClaimedVideoDefaults | undefined; id?: string | undefined; kind?: string | undefined; } interface ContentOwnerListResponse { items?: YoutubePartner.Schema.ContentOwner[] | undefined; kind?: string | undefined; } interface CountriesRestriction { adFormats?: string[] | undefined; territories?: string[] | undefined; } interface CuepointSettings { cueType?: string | undefined; durationSecs?: number | undefined; offsetTimeMs?: string | undefined; walltime?: string | undefined; } interface Date { day?: number | undefined; month?: number | undefined; year?: number | undefined; } interface DateRange { end?: YoutubePartner.Schema.Date | undefined; kind?: string | undefined; start?: YoutubePartner.Schema.Date | undefined; } interface ExcludedInterval { high?: number | undefined; low?: number | undefined; origin?: string | undefined; timeCreated?: string | undefined; } interface IntervalCondition { high?: number | undefined; low?: number | undefined; } interface LiveCuepoint { broadcastId?: string | undefined; id?: string | undefined; kind?: string | undefined; settings?: YoutubePartner.Schema.CuepointSettings | undefined; } interface MatchSegment { channel?: string | undefined; reference_segment?: YoutubePartner.Schema.Segment | undefined; video_segment?: YoutubePartner.Schema.Segment | undefined; } interface Metadata { actor?: string[] | undefined; album?: string | undefined; artist?: string[] | undefined; broadcaster?: string[] | undefined; category?: string | undefined; contentType?: string | undefined; copyrightDate?: YoutubePartner.Schema.Date | undefined; customId?: string | undefined; description?: string | undefined; director?: string[] | undefined; eidr?: string | undefined; endYear?: number | undefined; episodeNumber?: string | undefined; episodesAreUntitled?: boolean | undefined; genre?: string[] | undefined; grid?: string | undefined; hfa?: string | undefined; infoUrl?: string | undefined; isan?: string | undefined; isrc?: string | undefined; iswc?: string | undefined; keyword?: string[] | undefined; label?: string | undefined; notes?: string | undefined; originalReleaseMedium?: string | undefined; producer?: string[] | undefined; ratings?: YoutubePartner.Schema.Rating[] | undefined; releaseDate?: YoutubePartner.Schema.Date | undefined; seasonNumber?: string | undefined; showCustomId?: string | undefined; showTitle?: string | undefined; spokenLanguage?: string | undefined; startYear?: number | undefined; subtitledLanguage?: string[] | undefined; title?: string | undefined; tmsId?: string | undefined; totalEpisodesExpected?: number | undefined; upc?: string | undefined; writer?: string[] | undefined; } interface MetadataHistory { kind?: string | undefined; metadata?: YoutubePartner.Schema.Metadata | undefined; origination?: YoutubePartner.Schema.Origination | undefined; timeProvided?: string | undefined; } interface MetadataHistoryListResponse { items?: YoutubePartner.Schema.MetadataHistory[] | undefined; kind?: string | undefined; } interface Order { availGroupId?: string | undefined; channelId?: string | undefined; contentType?: string | undefined; country?: string | undefined; customId?: string | undefined; dvdReleaseDate?: YoutubePartner.Schema.Date | undefined; estDates?: YoutubePartner.Schema.DateRange | undefined; events?: YoutubePartner.Schema.StateCompleted[] | undefined; id?: string | undefined; kind?: string | undefined; movie?: string | undefined; originalReleaseDate?: YoutubePartner.Schema.Date | undefined; priority?: string | undefined; productionHouse?: string | undefined; purchaseOrder?: string | undefined; requirements?: YoutubePartner.Schema.Requirements | undefined; show?: YoutubePartner.Schema.ShowDetails | undefined; status?: string | undefined; videoId?: string | undefined; vodDates?: YoutubePartner.Schema.DateRange | undefined; } interface OrderListResponse { items?: YoutubePartner.Schema.Order[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; previousPageToken?: string | undefined; } interface Origination { owner?: string | undefined; source?: string | undefined; } interface OwnershipConflicts { general?: YoutubePartner.Schema.TerritoryConflicts[] | undefined; kind?: string | undefined; mechanical?: YoutubePartner.Schema.TerritoryConflicts[] | undefined; performance?: YoutubePartner.Schema.TerritoryConflicts[] | undefined; synchronization?: YoutubePartner.Schema.TerritoryConflicts[] | undefined; } interface OwnershipHistoryListResponse { items?: YoutubePartner.Schema.RightsOwnershipHistory[] | undefined; kind?: string | undefined; } interface Package { content?: string | undefined; customIds?: string[] | undefined; id?: string | undefined; kind?: string | undefined; locale?: string | undefined; name?: string | undefined; status?: string | undefined; statusReports?: YoutubePartner.Schema.StatusReport[] | undefined; timeCreated?: string | undefined; type?: string | undefined; uploaderName?: string | undefined; } interface PackageInsertResponse { errors?: YoutubePartner.Schema.ValidateError[] | undefined; kind?: string | undefined; resource?: YoutubePartner.Schema.Package | undefined; status?: string | undefined; } interface PageInfo { resultsPerPage?: number | undefined; startIndex?: number | undefined; totalResults?: number | undefined; } interface Policy { description?: string | undefined; id?: string | undefined; kind?: string | undefined; name?: string | undefined; rules?: YoutubePartner.Schema.PolicyRule[] | undefined; timeUpdated?: string | undefined; } interface PolicyList { items?: YoutubePartner.Schema.Policy[] | undefined; kind?: string | undefined; } interface PolicyRule { action?: string | undefined; conditions?: YoutubePartner.Schema.Conditions | undefined; subaction?: string[] | undefined; } interface PromotedContent { link?: YoutubePartner.Schema.CampaignTargetLink[] | undefined; } interface Publisher { caeNumber?: string | undefined; id?: string | undefined; ipiNumber?: string | undefined; kind?: string | undefined; name?: string | undefined; } interface PublisherList { items?: YoutubePartner.Schema.Publisher[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface Rating { rating?: string | undefined; ratingSystem?: string | undefined; } interface Reference { assetId?: string | undefined; audioswapEnabled?: boolean | undefined; claimId?: string | undefined; contentType?: string | undefined; duplicateLeader?: string | undefined; excludedIntervals?: YoutubePartner.Schema.ExcludedInterval[] | undefined; fpDirect?: boolean | undefined; hashCode?: string | undefined; id?: string | undefined; ignoreFpMatch?: boolean | undefined; kind?: string | undefined; length?: number | undefined; origination?: YoutubePartner.Schema.Origination | undefined; status?: string | undefined; statusReason?: string | undefined; urgent?: boolean | undefined; videoId?: string | undefined; } interface ReferenceConflict { conflictingReferenceId?: string | undefined; expiryTime?: string | undefined; id?: string | undefined; kind?: string | undefined; matches?: YoutubePartner.Schema.ReferenceConflictMatch[] | undefined; originalReferenceId?: string | undefined; status?: string | undefined; } interface ReferenceConflictListResponse { items?: YoutubePartner.Schema.ReferenceConflict[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface ReferenceConflictMatch { conflicting_reference_offset_ms?: string | undefined; length_ms?: string | undefined; original_reference_offset_ms?: string | undefined; type?: string | undefined; } interface ReferenceListResponse { items?: YoutubePartner.Schema.Reference[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } interface Requirements { caption?: boolean | undefined; hdTranscode?: boolean | undefined; posterArt?: boolean | undefined; spotlightArt?: boolean | undefined; spotlightReview?: boolean | undefined; trailer?: boolean | undefined; } interface RightsOwnership { general?: YoutubePartner.Schema.TerritoryOwners[] | undefined; kind?: string | undefined; mechanical?: YoutubePartner.Schema.TerritoryOwners[] | undefined; performance?: YoutubePartner.Schema.TerritoryOwners[] | undefined; synchronization?: YoutubePartner.Schema.TerritoryOwners[] | undefined; } interface RightsOwnershipHistory { kind?: string | undefined; origination?: YoutubePartner.Schema.Origination | undefined; ownership?: YoutubePartner.Schema.RightsOwnership | undefined; timeProvided?: string | undefined; } interface Segment { duration?: string | undefined; kind?: string | undefined; start?: string | undefined; } interface ShowDetails { episodeNumber?: string | undefined; episodeTitle?: string | undefined; seasonNumber?: string | undefined; title?: string | undefined; } interface SpreadsheetTemplate { kind?: string | undefined; status?: string | undefined; templateContent?: string | undefined; templateName?: string | undefined; templateType?: string | undefined; } interface SpreadsheetTemplateListResponse { items?: YoutubePartner.Schema.SpreadsheetTemplate[] | undefined; kind?: string | undefined; status?: string | undefined; } interface StateCompleted { state?: string | undefined; timeCompleted?: string | undefined; } interface StatusReport { statusContent?: string | undefined; statusFileName?: string | undefined; } interface TerritoryCondition { territories?: string[] | undefined; type?: string | undefined; } interface TerritoryConflicts { conflictingOwnership?: YoutubePartner.Schema.ConflictingOwnership[] | undefined; territory?: string | undefined; } interface TerritoryOwners { owner?: string | undefined; publisher?: string | undefined; ratio?: number | undefined; territories?: string[] | undefined; type?: string | undefined; } interface Uploader { kind?: string | undefined; uploaderName?: string | undefined; } interface UploaderListResponse { items?: YoutubePartner.Schema.Uploader[] | undefined; kind?: string | undefined; } interface ValidateAsyncRequest { content?: string | undefined; kind?: string | undefined; uploaderName?: string | undefined; } interface ValidateAsyncResponse { kind?: string | undefined; status?: string | undefined; validationId?: string | undefined; } interface ValidateError { columnName?: string | undefined; columnNumber?: number | undefined; lineNumber?: number | undefined; message?: string | undefined; messageCode?: number | undefined; severity?: string | undefined; } interface ValidateRequest { content?: string | undefined; kind?: string | undefined; locale?: string | undefined; uploaderName?: string | undefined; } interface ValidateResponse { errors?: YoutubePartner.Schema.ValidateError[] | undefined; kind?: string | undefined; status?: string | undefined; } interface ValidateStatusRequest { kind?: string | undefined; locale?: string | undefined; validationId?: string | undefined; } interface ValidateStatusResponse { errors?: YoutubePartner.Schema.ValidateError[] | undefined; isMetadataOnly?: boolean | undefined; kind?: string | undefined; status?: string | undefined; } interface VideoAdvertisingOption { adBreaks?: YoutubePartner.Schema.AdBreak[] | undefined; adFormats?: string[] | undefined; autoGeneratedBreaks?: boolean | undefined; breakPosition?: string[] | undefined; id?: string | undefined; kind?: string | undefined; tpAdServerVideoId?: string | undefined; tpTargetingUrl?: string | undefined; tpUrlParameters?: string | undefined; } interface VideoAdvertisingOptionGetEnabledAdsResponse { adBreaks?: YoutubePartner.Schema.AdBreak[] | undefined; adsOnEmbeds?: boolean | undefined; countriesRestriction?: YoutubePartner.Schema.CountriesRestriction[] | undefined; id?: string | undefined; kind?: string | undefined; } interface Whitelist { id?: string | undefined; kind?: string | undefined; title?: string | undefined; } interface WhitelistListResponse { items?: YoutubePartner.Schema.Whitelist[] | undefined; kind?: string | undefined; nextPageToken?: string | undefined; pageInfo?: YoutubePartner.Schema.PageInfo | undefined; } } } interface YoutubePartner { AssetLabels?: YoutubePartner.Collection.AssetLabelsCollection | undefined; AssetMatchPolicy?: YoutubePartner.Collection.AssetMatchPolicyCollection | undefined; AssetRelationships?: YoutubePartner.Collection.AssetRelationshipsCollection | undefined; AssetSearch?: YoutubePartner.Collection.AssetSearchCollection | undefined; AssetShares?: YoutubePartner.Collection.AssetSharesCollection | undefined; Assets?: YoutubePartner.Collection.AssetsCollection | undefined; Campaigns?: YoutubePartner.Collection.CampaignsCollection | undefined; ClaimHistory?: YoutubePartner.Collection.ClaimHistoryCollection | undefined; ClaimSearch?: YoutubePartner.Collection.ClaimSearchCollection | undefined; Claims?: YoutubePartner.Collection.ClaimsCollection | undefined; ContentOwnerAdvertisingOptions?: YoutubePartner.Collection.ContentOwnerAdvertisingOptionsCollection | undefined; ContentOwners?: YoutubePartner.Collection.ContentOwnersCollection | undefined; LiveCuepoints?: YoutubePartner.Collection.LiveCuepointsCollection | undefined; MetadataHistory?: YoutubePartner.Collection.MetadataHistoryCollection | undefined; Orders?: YoutubePartner.Collection.OrdersCollection | undefined; Ownership?: YoutubePartner.Collection.OwnershipCollection | undefined; OwnershipHistory?: YoutubePartner.Collection.OwnershipHistoryCollection | undefined; Package?: YoutubePartner.Collection.PackageCollection | undefined; Policies?: YoutubePartner.Collection.PoliciesCollection | undefined; Publishers?: YoutubePartner.Collection.PublishersCollection | undefined; ReferenceConflicts?: YoutubePartner.Collection.ReferenceConflictsCollection | undefined; References?: YoutubePartner.Collection.ReferencesCollection | undefined; SpreadsheetTemplate?: YoutubePartner.Collection.SpreadsheetTemplateCollection | undefined; Uploader?: YoutubePartner.Collection.UploaderCollection | undefined; Validator?: YoutubePartner.Collection.ValidatorCollection | undefined; VideoAdvertisingOptions?: YoutubePartner.Collection.VideoAdvertisingOptionsCollection | undefined; Whitelists?: YoutubePartner.Collection.WhitelistsCollection | undefined; // Create a new instance of AdBreak newAdBreak(): YoutubePartner.Schema.AdBreak; // Create a new instance of AdSlot newAdSlot(): YoutubePartner.Schema.AdSlot; // Create a new instance of AllowedAdvertisingOptions newAllowedAdvertisingOptions(): YoutubePartner.Schema.AllowedAdvertisingOptions; // Create a new instance of Asset newAsset(): YoutubePartner.Schema.Asset; // Create a new instance of AssetLabel newAssetLabel(): YoutubePartner.Schema.AssetLabel; // Create a new instance of AssetMatchPolicy newAssetMatchPolicy(): YoutubePartner.Schema.AssetMatchPolicy; // Create a new instance of AssetRelationship newAssetRelationship(): YoutubePartner.Schema.AssetRelationship; // Create a new instance of Campaign newCampaign(): YoutubePartner.Schema.Campaign; // Create a new instance of CampaignData newCampaignData(): YoutubePartner.Schema.CampaignData; // Create a new instance of CampaignSource newCampaignSource(): YoutubePartner.Schema.CampaignSource; // Create a new instance of CampaignTargetLink newCampaignTargetLink(): YoutubePartner.Schema.CampaignTargetLink; // Create a new instance of Claim newClaim(): YoutubePartner.Schema.Claim; // Create a new instance of ClaimMatchInfo newClaimMatchInfo(): YoutubePartner.Schema.ClaimMatchInfo; // Create a new instance of ClaimMatchInfoLongestMatch newClaimMatchInfoLongestMatch(): YoutubePartner.Schema.ClaimMatchInfoLongestMatch; // Create a new instance of ClaimMatchInfoTotalMatch newClaimMatchInfoTotalMatch(): YoutubePartner.Schema.ClaimMatchInfoTotalMatch; // Create a new instance of ClaimOrigin newClaimOrigin(): YoutubePartner.Schema.ClaimOrigin; // Create a new instance of ClaimedVideoDefaults newClaimedVideoDefaults(): YoutubePartner.Schema.ClaimedVideoDefaults; // Create a new instance of Conditions newConditions(): YoutubePartner.Schema.Conditions; // Create a new instance of ConflictingOwnership newConflictingOwnership(): YoutubePartner.Schema.ConflictingOwnership; // Create a new instance of ContentOwnerAdvertisingOption newContentOwnerAdvertisingOption(): YoutubePartner.Schema.ContentOwnerAdvertisingOption; // Create a new instance of CuepointSettings newCuepointSettings(): YoutubePartner.Schema.CuepointSettings; // Create a new instance of Date newDate(): YoutubePartner.Schema.Date; // Create a new instance of DateRange newDateRange(): YoutubePartner.Schema.DateRange; // Create a new instance of ExcludedInterval newExcludedInterval(): YoutubePartner.Schema.ExcludedInterval; // Create a new instance of IntervalCondition newIntervalCondition(): YoutubePartner.Schema.IntervalCondition; // Create a new instance of LiveCuepoint newLiveCuepoint(): YoutubePartner.Schema.LiveCuepoint; // Create a new instance of MatchSegment newMatchSegment(): YoutubePartner.Schema.MatchSegment; // Create a new instance of Metadata newMetadata(): YoutubePartner.Schema.Metadata; // Create a new instance of Order newOrder(): YoutubePartner.Schema.Order; // Create a new instance of Origination newOrigination(): YoutubePartner.Schema.Origination; // Create a new instance of OwnershipConflicts newOwnershipConflicts(): YoutubePartner.Schema.OwnershipConflicts; // Create a new instance of Package newPackage(): YoutubePartner.Schema.Package; // Create a new instance of Policy newPolicy(): YoutubePartner.Schema.Policy; // Create a new instance of PolicyRule newPolicyRule(): YoutubePartner.Schema.PolicyRule; // Create a new instance of PromotedContent newPromotedContent(): YoutubePartner.Schema.PromotedContent; // Create a new instance of Rating newRating(): YoutubePartner.Schema.Rating; // Create a new instance of Reference newReference(): YoutubePartner.Schema.Reference; // Create a new instance of Requirements newRequirements(): YoutubePartner.Schema.Requirements; // Create a new instance of RightsOwnership newRightsOwnership(): YoutubePartner.Schema.RightsOwnership; // Create a new instance of Segment newSegment(): YoutubePartner.Schema.Segment; // Create a new instance of ShowDetails newShowDetails(): YoutubePartner.Schema.ShowDetails; // Create a new instance of StateCompleted newStateCompleted(): YoutubePartner.Schema.StateCompleted; // Create a new instance of StatusReport newStatusReport(): YoutubePartner.Schema.StatusReport; // Create a new instance of TerritoryCondition newTerritoryCondition(): YoutubePartner.Schema.TerritoryCondition; // Create a new instance of TerritoryConflicts newTerritoryConflicts(): YoutubePartner.Schema.TerritoryConflicts; // Create a new instance of TerritoryOwners newTerritoryOwners(): YoutubePartner.Schema.TerritoryOwners; // Create a new instance of ValidateAsyncRequest newValidateAsyncRequest(): YoutubePartner.Schema.ValidateAsyncRequest; // Create a new instance of ValidateRequest newValidateRequest(): YoutubePartner.Schema.ValidateRequest; // Create a new instance of ValidateStatusRequest newValidateStatusRequest(): YoutubePartner.Schema.ValidateStatusRequest; // Create a new instance of VideoAdvertisingOption newVideoAdvertisingOption(): YoutubePartner.Schema.VideoAdvertisingOption; // Create a new instance of Whitelist newWhitelist(): YoutubePartner.Schema.Whitelist; } } declare var YoutubePartner: GoogleAppsScript.YoutubePartner;
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Bot Channels Registration. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const current = azure.core.getClientConfig({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleChannelsRegistration = new azure.bot.ChannelsRegistration("exampleChannelsRegistration", { * location: "global", * resourceGroupName: exampleResourceGroup.name, * sku: "F0", * microsoftAppId: current.then(current => current.clientId), * }); * ``` * * ## Import * * Bot Channels Registration can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:bot/channelsRegistration:ChannelsRegistration example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.BotService/botServices/example * ``` */ export class ChannelsRegistration extends pulumi.CustomResource { /** * Get an existing ChannelsRegistration resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ChannelsRegistrationState, opts?: pulumi.CustomResourceOptions): ChannelsRegistration { return new ChannelsRegistration(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:bot/channelsRegistration:ChannelsRegistration'; /** * Returns true if the given object is an instance of ChannelsRegistration. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ChannelsRegistration { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ChannelsRegistration.__pulumiType; } /** * The CMK Key Vault Key URL to encrypt the Bot Channels Registration with the Customer Managed Encryption Key. */ public readonly cmkKeyVaultUrl!: pulumi.Output<string | undefined>; /** * The description of the Bot Channels Registration. */ public readonly description!: pulumi.Output<string | undefined>; /** * The Application Insights API Key to associate with the Bot Channels Registration. */ public readonly developerAppInsightsApiKey!: pulumi.Output<string>; /** * The Application Insights Application ID to associate with the Bot Channels Registration. */ public readonly developerAppInsightsApplicationId!: pulumi.Output<string>; /** * The Application Insights Key to associate with the Bot Channels Registration. */ public readonly developerAppInsightsKey!: pulumi.Output<string>; /** * The name of the Bot Channels Registration will be displayed as. This defaults to `name` if not specified. */ public readonly displayName!: pulumi.Output<string>; /** * The Bot Channels Registration endpoint. */ public readonly endpoint!: pulumi.Output<string | undefined>; /** * The icon URL to visually identify the Bot Channels Registration. */ public readonly iconUrl!: pulumi.Output<string>; /** * Is the Bot Channels Registration in an isolated network? */ public readonly isolatedNetworkEnabled!: pulumi.Output<boolean | undefined>; /** * The supported Azure location where the resource exists. Changing this forces a new resource to be created. */ public readonly location!: pulumi.Output<string>; /** * The Microsoft Application ID for the Bot Channels Registration. Changing this forces a new resource to be created. */ public readonly microsoftAppId!: pulumi.Output<string>; /** * Specifies the name of the Bot Channels Registration. Changing this forces a new resource to be created. Must be globally unique. */ public readonly name!: pulumi.Output<string>; /** * The name of the resource group in which to create the Bot Channels Registration. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The SKU of the Bot Channels Registration. Valid values include `F0` or `S1`. Changing this forces a new resource to be created. */ public readonly sku!: pulumi.Output<string>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Create a ChannelsRegistration resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ChannelsRegistrationArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ChannelsRegistrationArgs | ChannelsRegistrationState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ChannelsRegistrationState | undefined; inputs["cmkKeyVaultUrl"] = state ? state.cmkKeyVaultUrl : undefined; inputs["description"] = state ? state.description : undefined; inputs["developerAppInsightsApiKey"] = state ? state.developerAppInsightsApiKey : undefined; inputs["developerAppInsightsApplicationId"] = state ? state.developerAppInsightsApplicationId : undefined; inputs["developerAppInsightsKey"] = state ? state.developerAppInsightsKey : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["endpoint"] = state ? state.endpoint : undefined; inputs["iconUrl"] = state ? state.iconUrl : undefined; inputs["isolatedNetworkEnabled"] = state ? state.isolatedNetworkEnabled : undefined; inputs["location"] = state ? state.location : undefined; inputs["microsoftAppId"] = state ? state.microsoftAppId : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["sku"] = state ? state.sku : undefined; inputs["tags"] = state ? state.tags : undefined; } else { const args = argsOrState as ChannelsRegistrationArgs | undefined; if ((!args || args.microsoftAppId === undefined) && !opts.urn) { throw new Error("Missing required property 'microsoftAppId'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.sku === undefined) && !opts.urn) { throw new Error("Missing required property 'sku'"); } inputs["cmkKeyVaultUrl"] = args ? args.cmkKeyVaultUrl : undefined; inputs["description"] = args ? args.description : undefined; inputs["developerAppInsightsApiKey"] = args ? args.developerAppInsightsApiKey : undefined; inputs["developerAppInsightsApplicationId"] = args ? args.developerAppInsightsApplicationId : undefined; inputs["developerAppInsightsKey"] = args ? args.developerAppInsightsKey : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["endpoint"] = args ? args.endpoint : undefined; inputs["iconUrl"] = args ? args.iconUrl : undefined; inputs["isolatedNetworkEnabled"] = args ? args.isolatedNetworkEnabled : undefined; inputs["location"] = args ? args.location : undefined; inputs["microsoftAppId"] = args ? args.microsoftAppId : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["sku"] = args ? args.sku : undefined; inputs["tags"] = args ? args.tags : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ChannelsRegistration.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ChannelsRegistration resources. */ export interface ChannelsRegistrationState { /** * The CMK Key Vault Key URL to encrypt the Bot Channels Registration with the Customer Managed Encryption Key. */ cmkKeyVaultUrl?: pulumi.Input<string>; /** * The description of the Bot Channels Registration. */ description?: pulumi.Input<string>; /** * The Application Insights API Key to associate with the Bot Channels Registration. */ developerAppInsightsApiKey?: pulumi.Input<string>; /** * The Application Insights Application ID to associate with the Bot Channels Registration. */ developerAppInsightsApplicationId?: pulumi.Input<string>; /** * The Application Insights Key to associate with the Bot Channels Registration. */ developerAppInsightsKey?: pulumi.Input<string>; /** * The name of the Bot Channels Registration will be displayed as. This defaults to `name` if not specified. */ displayName?: pulumi.Input<string>; /** * The Bot Channels Registration endpoint. */ endpoint?: pulumi.Input<string>; /** * The icon URL to visually identify the Bot Channels Registration. */ iconUrl?: pulumi.Input<string>; /** * Is the Bot Channels Registration in an isolated network? */ isolatedNetworkEnabled?: pulumi.Input<boolean>; /** * The supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * The Microsoft Application ID for the Bot Channels Registration. Changing this forces a new resource to be created. */ microsoftAppId?: pulumi.Input<string>; /** * Specifies the name of the Bot Channels Registration. Changing this forces a new resource to be created. Must be globally unique. */ name?: pulumi.Input<string>; /** * The name of the resource group in which to create the Bot Channels Registration. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The SKU of the Bot Channels Registration. Valid values include `F0` or `S1`. Changing this forces a new resource to be created. */ sku?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a ChannelsRegistration resource. */ export interface ChannelsRegistrationArgs { /** * The CMK Key Vault Key URL to encrypt the Bot Channels Registration with the Customer Managed Encryption Key. */ cmkKeyVaultUrl?: pulumi.Input<string>; /** * The description of the Bot Channels Registration. */ description?: pulumi.Input<string>; /** * The Application Insights API Key to associate with the Bot Channels Registration. */ developerAppInsightsApiKey?: pulumi.Input<string>; /** * The Application Insights Application ID to associate with the Bot Channels Registration. */ developerAppInsightsApplicationId?: pulumi.Input<string>; /** * The Application Insights Key to associate with the Bot Channels Registration. */ developerAppInsightsKey?: pulumi.Input<string>; /** * The name of the Bot Channels Registration will be displayed as. This defaults to `name` if not specified. */ displayName?: pulumi.Input<string>; /** * The Bot Channels Registration endpoint. */ endpoint?: pulumi.Input<string>; /** * The icon URL to visually identify the Bot Channels Registration. */ iconUrl?: pulumi.Input<string>; /** * Is the Bot Channels Registration in an isolated network? */ isolatedNetworkEnabled?: pulumi.Input<boolean>; /** * The supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * The Microsoft Application ID for the Bot Channels Registration. Changing this forces a new resource to be created. */ microsoftAppId: pulumi.Input<string>; /** * Specifies the name of the Bot Channels Registration. Changing this forces a new resource to be created. Must be globally unique. */ name?: pulumi.Input<string>; /** * The name of the resource group in which to create the Bot Channels Registration. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * The SKU of the Bot Channels Registration. Valid values include `F0` or `S1`. Changing this forces a new resource to be created. */ sku: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import webpack from 'webpack'; import path from 'path'; import { unstable_SIMPLIFY_COMPONENTS as SIMPLIFY_COMPONENTS } from '@goji/core'; import deepmerge from 'deepmerge'; import { urlToRequest } from 'loader-utils'; import { getWhitelistedComponents, getRenderedComponents } from '../utils/components'; import { transformTemplate } from '../utils/render'; import { getRelativePathToBridge } from '../utils/path'; import { BRIDGE_OUTPUT_DIR } from '../constants/paths'; import { pathEntriesMap, appConfigMap, usedComponentsMap } from '../shared'; import { GojiBasedWebpackPlugin } from './based'; import { minimize } from '../utils/minimize'; import { getSubpackagesInfo, findBelongingSubPackage, MAIN_PACKAGE } from '../utils/config'; import { renderTemplate } from '../templates'; import { componentWxml } from '../templates/components/components.wxml'; import { childrenWxml } from '../templates/components/children.wxml'; import { leafComponentWxml } from '../templates/components/leaf-components.wxml'; import { itemWxml } from '../templates/components/item.wxml'; import { itemJson } from '../templates/components/item.json'; import { subtreeJs } from '../templates/components/subtree.js'; import { subtreeJson } from '../templates/components/subtree.json'; import { subtreeWxml } from '../templates/components/subtree.wxml'; import { wrappedJson } from '../templates/components/wrapped.json'; import { getFeatures } from '../constants/features'; import { wrappedWxml } from '../templates/components/wrapped.wxml'; import { wrappedJs } from '../templates/components/wrapped.js'; /** * render bridge files and page/components entry files */ export class GojiBridgeWebpackPlugin extends GojiBasedWebpackPlugin { private getWhitelistedComponents(compilation: webpack.Compilation) { if (!usedComponentsMap.has(compilation)) { throw new Error('`usedComponents` not found, This might be an internal error in GojiJS.'); } const usedComponents = usedComponentsMap.get(compilation); return getWhitelistedComponents(this.options.target, usedComponents); } private getRenderedComponents(compilation: webpack.Compilation) { if (!usedComponentsMap.has(compilation)) { throw new Error('`usedComponents` not found, This might be an internal error in GojiJS.'); } const usedComponents = usedComponentsMap.get(compilation); return getRenderedComponents(this.options.target, SIMPLIFY_COMPONENTS, usedComponents); } private async renderTemplateComponentToAsset( compilation: webpack.Compilation, assetPath: string, component: () => string, merge?: (newSource: string, oldSource: string) => string, ) { const formattedAssetPath = this.transformExtForPath(assetPath); let content = renderTemplate({ target: this.options.target }, component); const type = path.posix.extname(assetPath).replace(/^\./, ''); content = await transformTemplate(content, this.options.target, type); if (!merge && compilation.assets[formattedAssetPath] !== undefined) { console.warn('skip existing asset', formattedAssetPath); } if (merge && compilation.assets[formattedAssetPath]) { content = merge(content, compilation.assets[formattedAssetPath].source().toString()); } if (this.options.minimize) { content = await minimize(content, path.posix.extname(assetPath)); } compilation.assets[formattedAssetPath] = new webpack.sources.RawSource(content); } private async renderSubtreeBridge(compilation: webpack.Compilation, basedir: string) { const components = this.getRenderedComponents(compilation); const { maxDepth } = this.options; for (let depth = 0; depth < maxDepth; depth += 1) { await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `children${depth}.wxml`), () => childrenWxml({ maxDepth, componentsDepth: depth + 1, }), ); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `components${depth}.wxml`), () => componentWxml({ depth, componentsDepth: depth + 1, components: components.filter(c => !c.isLeaf), useFlattenSwiper: getFeatures(this.options.target).useFlattenSwiper, }), ); } } private async renderLeafTemplate(compilation: webpack.Compilation, basedir: string) { const components = this.getRenderedComponents(compilation); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `leaf-components.wxml`), () => leafComponentWxml({ components: components.filter(c => c.isLeaf), }), ); } private async renderChildrenRenderComponent(compilation: webpack.Compilation, basedir: string) { await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `subtree.js`), () => subtreeJs(), ); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `subtree.json`), () => subtreeJson({ relativePathToBridge: '.', components: this.getWhitelistedComponents(compilation), }), ); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `subtree.wxml`), () => subtreeWxml(), ); } private async renderComponentTemplate(compilation: webpack.Compilation, basedir: string) { const components = this.getRenderedComponents(compilation); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `components0.wxml`), () => componentWxml({ depth: 0, componentsDepth: 0, components: components.filter(c => !c.isLeaf), useFlattenSwiper: getFeatures(this.options.target).useFlattenSwiper, }), ); } private async renderChildrenTemplate(compilation: webpack.Compilation, basedir: string) { await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, `children0.wxml`), () => childrenWxml({ maxDepth: Infinity, componentsDepth: 0, }), ); } private async renderWrappedComponents(compilation: webpack.Compilation, basedir: string) { const components = this.getWhitelistedComponents(compilation); for (const component of components) { if (component.isWrapped) { await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, 'components', `${component.name}.wxml`), () => wrappedWxml({ component }), ); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, 'components', `${component.name}.json`), () => wrappedJson({ relativePathToBridge: '..', component, components: this.getWhitelistedComponents(compilation), }), ); await this.renderTemplateComponentToAsset( compilation, path.posix.join(basedir, BRIDGE_OUTPUT_DIR, 'components', `${component.name}.js`), () => wrappedJs({ component, }), ); } } } public apply(compiler: webpack.Compiler) { compiler.hooks.thisCompilation.tap('GojiBridgeWebpackPlugin', compilation => { compilation.hooks.processAssets.tapPromise('GojiBridgeWebpackPlugin', async () => { const appConfig = appConfigMap.get(compiler); if (!appConfig) { throw new Error('`appConfig` not found. This might be an internal error in GojiJS.'); } const [, independents] = getSubpackagesInfo(appConfig); const independentRoots = independents.map(independent => independent.root!); const independentPaths = independentRoots.map(root => urlToRequest(root)); const { useSubtree } = getFeatures(this.options.target); for (const bridgeBasedirs of ['.', ...independentPaths]) { if (useSubtree) { // render componentX and childrenX await this.renderSubtreeBridge(compilation, bridgeBasedirs); // render subtree component await this.renderChildrenRenderComponent(compilation, bridgeBasedirs); } else if (getFeatures(this.options.target).useInlineChildren) { // render component0 with inlined children0 await this.renderComponentTemplate(compilation, bridgeBasedirs); } else { // render component0 await this.renderComponentTemplate(compilation, bridgeBasedirs); // render children0 await this.renderChildrenTemplate(compilation, bridgeBasedirs); } // render leaf-components await this.renderLeafTemplate(compilation, bridgeBasedirs); // render wrapped components await this.renderWrappedComponents(compilation, bridgeBasedirs); } const pathEntries = pathEntriesMap.get(compiler); if (!pathEntries) { throw new Error('pathEntries not found'); } for (const entrypoint of pathEntries) { const belongingIndependentPackage = findBelongingSubPackage(entrypoint, independentRoots); const bridgeBasedir = belongingIndependentPackage === MAIN_PACKAGE ? '.' : urlToRequest(belongingIndependentPackage); // generate entry wxml await this.renderTemplateComponentToAsset(compilation, `${entrypoint}.wxml`, () => itemWxml({ relativePathToBridge: getRelativePathToBridge(entrypoint, bridgeBasedir), fixBaiduTemplateBug: this.options.target === 'baidu', }), ); // generate entry json await this.renderTemplateComponentToAsset( compilation, `${entrypoint}.json`, () => itemJson({ relativePathToBridge: getRelativePathToBridge(entrypoint, bridgeBasedir), components: this.getWhitelistedComponents(compilation), }), (newSource, oldSource) => JSON.stringify(deepmerge(JSON.parse(oldSource), JSON.parse(newSource)), null, 2), ); } }); }); } }
the_stack
import React from 'react' import { BackHandler, Dimensions, StatusBar, View, Animated, Linking, AsyncStorage, NetInfo, DeviceEventEmitter, Platform } from 'react-native' import { Provider } from 'react-redux' import Snackbar from 'react-native-snackbar' import SplashScreen from 'react-native-splash-screen' import StackNavigator, { getCurrentRoute, tracker } from './router' import ColorConfig, { getAccentColorFromName } from './constant/colorConfig' import configureStore from './redux/store' import checkVersion from './bootstrap/checkVersion' import { ColorInfo, ModeInfo } from './interface' let backPressClickTimeStamp = 0 declare var global global.toast = () => {} const netInfoHandler = (reach) => { global.netInfo = reach } const shouldChangeBackground = Platform.OS !== 'android' || (Platform.OS === 'android' && Platform.Version <= 20) export default class Root extends React.Component<any, any> { store = configureStore() constructor(props) { super(props) const { height, width } = Dimensions.get('window') this.state = { text: '', width, height, minWidth: Math.min(height, width), isNightMode: false, tipBarMarginBottom: new Animated.Value(0), progress: new Animated.Value(0), isLoadingAsyncStorage: true, settingInfo: { tabMode: 'tab', psnid: '', userInfo: { avatar: require('./../art/avatar.jpg'), platinum: '白', gold: '金', silver: '银', bronze: '铜', isSigned: true, exp: '' }, isNightMode: false, colorTheme: 'lightBlue' }, colorTheme: 'lightBlue', secondaryColor: 'pink', loadingText: 'P9 · 酷玩趣友' } } switchModeOnRoot = (theme) => { if (!theme) { let targetState = !this.state.isNightMode this.setState({ isNightMode: targetState }) return AsyncStorage.setItem('@Theme:isNightMode', targetState.toString()) } else { const { colorTheme, secondaryColor } = theme if (colorTheme) { this.setState({ colorTheme: colorTheme.toString() }) return AsyncStorage.setItem('@Theme:colorTheme', colorTheme.toString()) } else if (secondaryColor) { this.setState({ secondaryColor: secondaryColor.toString() }) return AsyncStorage.setItem('@Theme:secondaryColor', secondaryColor.toString()) } } } componentWillMount() { global.toast = this.toast BackHandler.addEventListener('hardwareBackPress', () => { let timestamp: any = new Date() if (timestamp - backPressClickTimeStamp > 2000) { backPressClickTimeStamp = timestamp global.toast && global.toast('再按一次退出程序') return true } else { return false } }) } reloadSetting = () => { const settingInfo: any = {} return Promise.all([ AsyncStorage.getItem('@Theme:tabMode'), AsyncStorage.getItem('@psnid'), AsyncStorage.getItem('@userInfo'), AsyncStorage.getItem('@Theme:isNightMode'), AsyncStorage.getItem('@Theme:loadImageWithoutWifi'), AsyncStorage.getItem('@Theme:colorTheme'), AsyncStorage.getItem('@Theme:shouldSendGA'), AsyncStorage.getItem('@Theme:secondaryColor') ]).then(result => { // console.log('getting psnid: ' + result[1]) Object.assign(settingInfo, { tabMode: result[0] || 'tab', psnid: result[1] || '', userInfo: JSON.parse(result[2]) || { avatar: require('./../art/avatar.jpg'), platinum: '白', gold: '金', silver: '银', bronze: '铜', isSigned: true, exp: '' }, isNightMode: JSON.parse(result[3]) || false, colorTheme: result[5] || 'lightBlue', secondaryColor: result[7] || 'pink' }) this.setState({ settingInfo, colorTheme: settingInfo.colorTheme, isNightMode: settingInfo.isNightMode, secondaryColor: settingInfo.secondaryColor }) global.shouldSendGA = JSON.parse(result[6] || 'true') global.loadImageWithoutWifi = JSON.parse(result[4]) || false }).catch(err => { // console.log(err) global.toast && global.toast(err.toString()) }) } loadSetting = () => { this.setState({ isLoadingAsyncStorage: true }) const settingInfo: any = {} Promise.all([ AsyncStorage.getItem('@Theme:tabMode'), AsyncStorage.getItem('@psnid'), AsyncStorage.getItem('@userInfo'), AsyncStorage.getItem('@Theme:isNightMode'), AsyncStorage.getItem('@Theme:loadImageWithoutWifi'), AsyncStorage.getItem('@Theme:colorTheme'), AsyncStorage.getItem('@Theme:shouldSendGA'), AsyncStorage.getItem('@Theme:secondaryColor') ]).then(result => { Object.assign(settingInfo, { tabMode: result[0] || this.state.settingInfo.tabMode, psnid: result[1] || this.state.settingInfo.psnid, userInfo: JSON.parse(result[2]) || this.state.settingInfo.userInfo, isNightMode: JSON.parse(result[3]) || this.state.settingInfo.isNightMode, colorTheme: result[5] || 'lightBlue', secondaryColor: result[7] || 'pink' }) // alert(result[7]) global.loadImageWithoutWifi = JSON.parse(result[4]) || false // console.log('==> GA', JSON.parse(result[6]), JSON.parse(result[6] || 'true'), result[6], typeof result[6]) global.shouldSendGA = JSON.parse(result[6] || 'true') this.setState({ isLoadingAsyncStorage: false, settingInfo, colorTheme: settingInfo.colorTheme, isNightMode: settingInfo.isNightMode, secondaryColor: settingInfo.secondaryColor }, () => { SplashScreen.hide() if (global.isIOS === false) checkVersion().catch(() => {}) }) }) } componentDidMount() { this.loadSetting() Linking.getInitialURL().then((url) => { if (url) { // console.log('Initial url is: ' + url); } }).catch(err => console.error('An error occurred linking', err)) Linking.addEventListener('url', this._handleOpenURL) NetInfo.fetch().then((reach) => { global.netInfo = reach }) NetInfo.addEventListener( 'change', netInfoHandler ) this._orientationSubscription = DeviceEventEmitter.addListener('namedOrientationDidChange', this._handleOrientation) } componentWillUnmount() { Linking.removeEventListener('url', this._handleOpenURL) NetInfo.removeEventListener('change', netInfoHandler) this._orientationSubscription && this._orientationSubscription.remove() } _handleOpenURL() { // console.log(event.url); } _orientationSubscription: any = false _handleOrientation = orientation => { let screen: any = {} const { height, width } = Dimensions.get('window') const min = Math.min(height, width) const max = Math.max(height, width) const { isLandscape } = orientation screen = { height: isLandscape ? min : max, width: isLandscape ? max : min } // console.log(orientation, screen) this.setState({ width: screen.width, height: screen.height, minWidth: min }) } toast = (text: any, options?: any) => { const action: any = {} if (typeof options === 'object') { Object.assign(action, options) } Snackbar.show({ title: text.toString(), duration: Snackbar.LENGTH_SHORT, action: Object.keys(action).length ? action : undefined }) } render() { const dayModeInfo: ColorInfo = ColorConfig[this.state.colorTheme] const nightModeInfo: ColorInfo = ColorConfig[this.state.colorTheme + 'Night'] const targetModeInfo: ColorInfo = this.state.isNightMode ? nightModeInfo : dayModeInfo const { isLoadingAsyncStorage } = this.state const { colorTheme, secondaryColor, isNightMode, width, height, minWidth } = this.state /* get value to avoid remote debugger bug */ secondaryColor isNightMode const modeInfo: ModeInfo = Object.assign({}, targetModeInfo, { loadSetting: this.loadSetting, reloadSetting: this.reloadSetting, settingInfo: this.state.settingInfo, isNightMode, reverseModeInfo: isNightMode ? dayModeInfo : nightModeInfo, dayModeInfo: dayModeInfo, nightModeInfo: nightModeInfo, switchModeOnRoot: this.switchModeOnRoot, themeName: isNightMode ? `${colorTheme}Night:${secondaryColor}:${width}` : `${colorTheme}:${secondaryColor}:${width}`, colorTheme, secondaryColor, width, height, minWidth, numColumns: Math.max(1, Math.floor(width / 360)), accentColor: getAccentColorFromName(secondaryColor, isNightMode), background: (shouldChangeBackground || isNightMode) ? targetModeInfo.brighterLevelOne : targetModeInfo.backgroundColor }) global.modeInfo = modeInfo const screens = ['Home', 'NewGame', 'Stats', 'Main'] const onNavigationStateChange = global.shouldSendGA ? (prevState, currentState) => { const currentScreen = getCurrentRoute(currentState) const prevScreen = getCurrentRoute(prevState) if (prevScreen && currentScreen && prevScreen.routeName !== currentScreen.routeName) { if (global.shouldSendGA) { const { routeName = 'Unknow' } = currentScreen tracker.trackScreenView(routeName) } // if (screens.includes(currentScreen.routeName)) { // StatusBar.setTranslucent(true) // StatusBar.setBackgroundColor('rgba(0,0,0,0.251)') // modeInfo.isNightMode && StatusBar.setBarStyle('dark-content') // } else if (screens.includes(prevScreen.routeName)) { // StatusBar.setTranslucent(false) // StatusBar.setBackgroundColor(modeInfo.deepColor) // modeInfo.isNightMode && StatusBar.setBarStyle('light-content') // } } } : undefined const child = isLoadingAsyncStorage ? ( <View style={{ flex: 1 }}/> ) : ( <View style={{ flex: 1 }}> <StatusBar translucent={true} hidden={false} backgroundColor={modeInfo.deepColor} barStyle={'light-content'} /> <StackNavigator uriPrefix={'p9://psnine.com/'} onNavigationStateChange={onNavigationStateChange} screenProps={{ modeInfo, switchModeOnRoot: this.switchModeOnRoot, bottomText: this.state.text }} /> </View> ) return ( <Provider store={this.store}> {child} </Provider> ) } }
the_stack
import { ɵivyEnabled as ivyEnabled, Component, Directive, Injectable, Pipe, PipeTransform, } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Subject } from 'rxjs'; import { finalize } from 'rxjs/operators'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; describe('until-destroy runtime behavior', () => { it('ivy has to be enabled', () => { // This assertion has to be performed as we have to // be sure that we're running these tests with the Ivy engine expect(ivyEnabled).toBeTruthy(); }); it('should unsubscribe from the component property', () => { // Arrange @UntilDestroy({ checkProperties: true }) @Component({ template: '' }) class MockComponent { disposed = false; subscription = new Subject() .pipe( finalize(() => { this.disposed = true; }) ) .subscribe(); } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); // Assert expect(fixture.componentInstance.disposed).toBeFalsy(); fixture.destroy(); expect(fixture.componentInstance.disposed).toBeTruthy(); }); it('should unsubscribe from the directive property', () => { // Arrange @Component({ template: '<div test></div>', }) class MockComponent {} @UntilDestroy({ checkProperties: true }) @Directive({ selector: '[test]' }) class MockDirective { disposed = false; subscription = new Subject() .pipe( finalize(() => { this.disposed = true; }) ) .subscribe(); } // Act TestBed.configureTestingModule({ declarations: [MockComponent, MockDirective], }); const fixture = TestBed.createComponent(MockComponent); fixture.detectChanges(); const elementWithDirective = fixture.debugElement.query(By.directive(MockDirective)); const directive = elementWithDirective.injector.get(MockDirective); fixture.destroy(); // Assert expect(directive.disposed).toBeTruthy(); }); it('should unsubscribe from pipe property', () => { // Arrange let disposed = false; @UntilDestroy({ checkProperties: true }) @Pipe({ name: 'mock', pure: false }) class MockPipe implements PipeTransform { disposed = false; subscription = new Subject().pipe(finalize(() => (disposed = true))).subscribe(); transform(): string { return 'I have been piped'; } } @Component({ template: ` <div>{{ '' | mock }}</div> `, }) class MockComponent {} // Act TestBed.configureTestingModule({ declarations: [MockComponent, MockPipe], }); const fixture = TestBed.createComponent(MockComponent); fixture.detectChanges(); fixture.destroy(); // Assert expect(disposed).toBeTruthy(); }); it('should loop an array of subscriptions and unsubscribe', () => { // Arrange @UntilDestroy({ arrayName: 'subscriptions' }) @Component({ template: '' }) class MockComponent { disposed = false; subscriptions = [ new Subject() .pipe( finalize(() => { this.disposed = true; }) ) .subscribe(), ]; } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); // Assert expect(fixture.componentInstance.disposed).toBeFalsy(); fixture.destroy(); expect(fixture.componentInstance.disposed).toBeTruthy(); }); it('should complete the stream using the "untilDestroyed" operator', () => { // Arrange @UntilDestroy() @Component({ template: '' }) class MockComponent { disposed = false; constructor() { new Subject() .pipe( untilDestroyed(this), finalize(() => { this.disposed = true; }) ) .subscribe(); } } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); // Assert expect(fixture.componentInstance.disposed).toBeFalsy(); fixture.destroy(); expect(fixture.componentInstance.disposed).toBeTruthy(); }); it('should unsubscribe from the provider property', () => { // Arrange @UntilDestroy({ checkProperties: true }) @Injectable() class MockService { disposed = false; subscription = new Subject() .pipe( finalize(() => { this.disposed = true; }) ) .subscribe(); } @Component({ template: '', providers: [MockService], }) class MockComponent { constructor(mockService: MockService) {} } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); const service = fixture.componentRef.injector.get(MockService); // Assert expect(service.disposed).toBeFalsy(); fixture.destroy(); expect(service.disposed).toBeTruthy(); }); it('should complete the stream on provider', () => { // Arrange @UntilDestroy() @Injectable() class MockService { disposed = false; constructor() { new Subject() .pipe( untilDestroyed(this), finalize(() => { this.disposed = true; }) ) .subscribe(); } } @Component({ template: '', providers: [MockService], }) class MockComponent { constructor(mockService: MockService) {} } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); const service = fixture.componentRef.injector.get(MockService); // Assert expect(service.disposed).toBeFalsy(); fixture.destroy(); expect(service.disposed).toBeTruthy(); }); describe('https://github.com/ngneat/until-destroy/issues/61', () => { it('should unsubscribe from streams if component inherits another directive or component', () => { // Arrange let baseDirectiveSubjectUnsubscribed = false, mockComponentSubjectUnsubscribed = false; @Directive() abstract class BaseDirective { constructor() { new Subject() .pipe( untilDestroyed(this), finalize(() => (baseDirectiveSubjectUnsubscribed = true)) ) .subscribe(); } } @UntilDestroy() @Component({ template: '' }) class MockComponent extends BaseDirective { constructor() { super(); new Subject() .pipe( untilDestroyed(this), finalize(() => (mockComponentSubjectUnsubscribed = true)) ) .subscribe(); } } // Act TestBed.configureTestingModule({ declarations: [MockComponent], }); const fixture = TestBed.createComponent(MockComponent); // Assert expect(baseDirectiveSubjectUnsubscribed).toBeFalsy(); expect(mockComponentSubjectUnsubscribed).toBeFalsy(); fixture.destroy(); expect(baseDirectiveSubjectUnsubscribed).toBeTruthy(); expect(mockComponentSubjectUnsubscribed).toBeTruthy(); }); }); describe('https://github.com/ngneat/until-destroy/issues/66', () => { it('should be able to re-use methods of the singleton service multiple times', () => { // Arrange let disposedTimes = 0; let startCalledTimes = 0; let originalStopCalledTimes = 0; @Injectable() class IssueSixtySixService { start(): void { startCalledTimes++; new Subject() .pipe( untilDestroyed(this, 'stop'), finalize(() => disposedTimes++) ) .subscribe(); } stop(): void { originalStopCalledTimes++; } } @Component({ template: '' }) class IssueSixtySixComponent { constructor(private issueSixtySixService: IssueSixtySixService) {} start(): void { this.issueSixtySixService.start(); } stop(): void { this.issueSixtySixService.stop(); } } // Act TestBed.configureTestingModule({ declarations: [IssueSixtySixComponent], providers: [IssueSixtySixService], }); const fixture = TestBed.createComponent(IssueSixtySixComponent); fixture.componentInstance.start(); fixture.componentInstance.stop(); fixture.componentInstance.start(); fixture.componentInstance.stop(); // Assert expect(disposedTimes).toBe(2); expect(startCalledTimes).toBe(2); expect(originalStopCalledTimes).toBe(2); }); it('should not use the single subject for different streams when `destroyMethodName` is provided', () => { // Arrange @Injectable() class IssueSixtySixService { firstSubjectUnsubscribed = false; secondSubjectUnsubscribed = false; startFirst(): void { new Subject() .pipe( untilDestroyed(this, 'stopFirst'), finalize(() => (this.firstSubjectUnsubscribed = true)) ) .subscribe(); } stopFirst(): void {} startSecond(): void { new Subject() .pipe( untilDestroyed(this, 'stopSecond'), finalize(() => (this.secondSubjectUnsubscribed = true)) ) .subscribe(); } stopSecond(): void {} } @Component({ template: '' }) class IssueSixtySixComponent { constructor(private issueSixtySixService: IssueSixtySixService) {} startFirst(): void { this.issueSixtySixService.startFirst(); } stopFirst(): void { this.issueSixtySixService.stopFirst(); } startSecond(): void { this.issueSixtySixService.startSecond(); } stopSecond(): void { this.issueSixtySixService.stopSecond(); } } // Act TestBed.configureTestingModule({ declarations: [IssueSixtySixComponent], providers: [IssueSixtySixService], }); const fixture = TestBed.createComponent(IssueSixtySixComponent); const issueSixtySixService = TestBed.inject(IssueSixtySixService); fixture.componentInstance.startFirst(); fixture.componentInstance.startSecond(); fixture.componentInstance.stopFirst(); // Arrange expect(issueSixtySixService.firstSubjectUnsubscribed).toBeTruthy(); // Ensure that they listen to different subjects and all streams // are not completed together. expect(issueSixtySixService.secondSubjectUnsubscribed).toBeFalsy(); fixture.componentInstance.stopSecond(); expect(issueSixtySixService.secondSubjectUnsubscribed).toBeTruthy(); }); }); });
the_stack
import {Config as SystemJSConfig} from "systemjs"; import createLogger from "debug"; const debug = createLogger("WebIO:Scope"); import WebIONode, {WebIONodeSchema, WebIONodeContext} from "./Node"; import WebIOObservable, {ObservableData} from "./Observable"; import {getObservableName, ObservableSpecifier, OptionalKeys} from "./utils"; import {WebIOCommandType, WebIOMessage} from "./message"; import {createWebIOEventListener} from "./events"; import createNode from "./createNode"; import {BlockImport, importBlock} from "./imports"; /** * A map of observable names to arrays-of-listeners that should be * evoked when the observable changes. * * `preDependencies` is a special array-of-listeners which are evoked * when all the scope dependencies are loaded. */ export interface ScopeListeners { preDependencies?: Array<(scope: WebIOScope) => void>; [handlerName: string]: Array<((value: any, scope?: WebIOScope) => void)> | undefined; } /** * Promises associated with a scope. */ interface ScopePromises { importsLoaded: Promise<any[] | null>; connected: Promise<WebIOScope>; [promiseName: string]: Promise<any> | undefined; } export const SCOPE_NODE_TYPE = "Scope"; /** * Data associated with a scope node. */ export interface ScopeSchema extends WebIONodeSchema { nodeType: typeof SCOPE_NODE_TYPE; instanceArgs: { /** * The id of the scope. */ id: string; /** * Map from "observableName" => { data about observable }. * * @example * observables = { * "obs-output": { * id: "ob_02", * value: 0.0, * sync: true, * } * } */ observables?: { [observableName: string]: ObservableData; }; /** * Map from "observableName" => ["array", "of", "handlers"] where each handler * is specified as a function definition string. * * @example * handlers = { * "obs-output": [ * "function (newValue) { console.log('obs-output got ', newValue); }", * "function (newValue) { alert('obs-output got ' + newValue); }" * ] * } * */ handlers?: { [observableName: string]: string[]; }; imports?: BlockImport; mount_callbacks?: string[]; /** * Configuration to apply to SystemJS before importing the dependencies. * * See {@link https://github.com/systemjs/systemjs/blob/0.21/docs/config-api.md}. */ systemjs_options: SystemJSConfig; } } /** * Handlers that are associated with the scope promises. * * @todo This needs to be refactored. */ export interface PromiseHandlers { importsLoaded?: string[]; // (imports: any[] | null) => void; // TODO: other promise handlers? } class WebIOScope extends WebIONode { readonly id: string; readonly element: HTMLElement; children: Array<WebIONode | string> | null = null; handlers: ScopeListeners; observables: {[observableName: string]: WebIOObservable}; promises: ScopePromises; get dom() { return this.element; } constructor( schema: ScopeSchema, context: WebIONodeContext, ) { super(schema, context); debug("Creating new WebIOScope.", schema); // NOTE: we use a span here because we don't Scopes to always be block-level // elements (e..g inline scopes should be a thing). // This technically violates HTML standards, (because we might have a block // element within this span) but, it works in all of the browsers so it's // whatever. this.element = document.createElement("span"); this.element.className = "webio-scope"; this.element.setAttribute("data-webio-scope-id", schema.instanceArgs.id); const {id, observables = {}, handlers = {}} = schema.instanceArgs; this.id = id; // Create WebIOObservables. this.observables = {}; Object.keys(observables).forEach((name) => { const observable = new WebIOObservable(name, observables[name], this); this.observables[name] = observable; observable.subscribe((value) => this.evokeObservableHandlers(name, value)); }); this.handlers = {}; // TODO: refactor registerScope as described elsewhere this.webIO.registerScope(this); // TODO: this following is super messy and needs to be refactored. /** * The issue here is that we need to have this.promises hooked up before * we create children... and we have to do the imports **after** we create * the children. There's definitely a cleaner way to do this but my brain * is a little bit fried right now. * * Currently, we just have a "dummy promise" that we create and then * "manually" resolve **after** the imports are done, so that * `this.promises` is set when we call `initialize` -- which we need since * `initialize` creates children which might in turn (e.g. in the case of * {@link WebIOObservableNode}) rely on `this.promises`. */ let resolveImportsLoaded: (...args: any[]) => void; let rejectImportsLoaded: (...args: any[]) => void; const importsLoadedPromise = new Promise<any[] | null>((resolve, reject) => { resolveImportsLoaded = resolve; rejectImportsLoaded = reject; }); this.promises = { connected: this.webIO.connected.then(() => this), importsLoaded: importsLoadedPromise, }; // This is super messy and should be refactored. // We must do `setupScope` after imports are loaded (see pull #217). this.initialize(schema) .then((...args) => resolveImportsLoaded(args)) .then(() => this.setupScope()) .catch((...args) => rejectImportsLoaded(args)); } /** * Perform asynchronous initialization tasks. */ private async initialize(schema: ScopeSchema) { const {handlers = {}, imports, systemjs_options: systemJSConfig} = schema.instanceArgs; // (Asynchronously) perform dependency initialization const {preDependencies = [], _promises = {}, ...restHandlers} = handlers; preDependencies .map((functionString) => createWebIOEventListener( this, functionString, {scope: this, webIO: this.webIO}, ) as (() => void)) .forEach((handler) => handler.call(this)) ; // Map the function strings into handlers which have `this` bound to the scope's // element and which have access to the _webIOScope resources variable (via closure). Object.keys(restHandlers).forEach((observableName) => { this.handlers[observableName] = handlers[observableName].map((handlerString) => { return createWebIOEventListener(this, handlerString, {scope: this, webIO: this.webIO}); }); }); const resources = imports ? await importBlock(imports, systemJSConfig) : null; // Create children WebIONodes. debug(`Creating children for scope (id: ${this.id}).`); this.children = schema.children.map((nodeData) => { if (typeof nodeData === "string") { return nodeData; } return createNode(nodeData, {webIO: this.webIO, scope: this}) }); // Append children elements to our element. for (const child of this.children) { if (typeof child === "string") { this.element.appendChild(document.createTextNode(child)); } else { this.element.appendChild(child.element); } } // TypeScript hackery to deal with how promiseHandlers is a very special case const {importsLoaded: importsLoadedHandlers} = _promises as any as PromiseHandlers; if (resources && importsLoadedHandlers) { debug(`Invoking importsLoaded handlers for scope (${this.id}).`, {scope: this, importsLoadedHandlers, resources}); const handlers = importsLoadedHandlers.map((handler) => { return createWebIOEventListener(this, handler, {scope: this, webIO: this.webIO}) }); // `as any` is necessary because createWebIOEventListener normally returns // a function which is expected to be an event listener... but this is // kind of a special case of that. handlers.forEach((handler) => (handler as any)(...resources)); } if (schema.instanceArgs.mount_callbacks) { const callbacks = schema.instanceArgs.mount_callbacks.map( (src) => createWebIOEventListener(this, src, {scope: this, webIO: this.webIO}) as any ); callbacks.forEach((callback) => callback()); } // This isn't super clean, but this function is used to create the // importsLoaded promise, so we need to return the promises. // TODO: refactor this return resources; } getLocalObservable(observableName: string) { // Only return a "local" observable const obs = this.observables[observableName]; if (!obs) { throw new Error(`Scope(id=${this.id}) has no observable named "${observableName}".`) } return obs; } getObservable(observable: ObservableSpecifier) { if (typeof observable === "string" || observable.scope === this.id) { return this.getLocalObservable(getObservableName(observable)); } // Otherwise, let the root WebIO instance find the correct scope and // observable. return this.webIO.getObservable(observable); } getObservableValue(observable: ObservableSpecifier) { return this.getObservable(observable).value; } /** * Update an observable within the scope. * @param observable - The name (or specifier) of the observable to modify. * @param value - The value to set the observable to. * @param sync - Whether or not to sync the value to Julia. This should always be * false if the update originated from Julia and is just being propogated into * the browser. */ setObservableValue(observable: ObservableSpecifier, value: any, sync: boolean = true) { debug("WebIOScope¬setObservableValue", {scope: this, observable, value, sync}); const observableName = getObservableName(observable); if (!(observableName in this.observables)) { throw new Error(`Scope(id=${this.id}) has no observable named "${observableName}".`) } debug(`Setting Observable (name: ${observableName}) to "${value}" in WebIOScope (id: ${this.id}).`); this.observables[observableName].setValue(value, sync); } /** * Send a message to the WebIO Julia machinery. * * Sets the scope id if not specified. */ send(message: WebIOMessage) { return this.webIO.send(message); } /** * Evoke the listeners for an observable with the current value of * that observable. * * @param name - The name of the observable whose listeners should be evoked. * @param value - The current value of the observable. */ protected evokeObservableHandlers(name: string, value: any) { const listeners = this.handlers[name] || []; debug(`Evoking ${listeners.length} observable handlers for observable "${name}".`); listeners.forEach((listener) => { listener.call(this, value, this); }) } /** * Send the setup-scope message. * * This informs Julia/WebIO that we want to listen to changes associated * with this scope. */ protected setupScope() { return this.send({ type: "command", command: WebIOCommandType.SETUP_SCOPE, scope: this.id, }) } } export default WebIOScope;
the_stack
import {UniformsUtils} from 'three/src/renderers/shaders/UniformsUtils'; import {ShaderLib} from 'three/src/renderers/shaders/ShaderLib'; import {GlobalsGlNode} from '../../../../src/engine/nodes/gl/Globals'; import {OutputGlNode} from '../../../../src/engine/nodes/gl/Output'; import {GlConnectionPointType} from '../../../../src/engine/nodes/utils/io/connections/Gl'; import {ConstantGlNode} from '../../../../src/engine/nodes/gl/Constant'; // import {CoreSleep} from '../../../../src/core/Sleep'; import {SceneJsonImporter} from '../../../../src/engine/io/json/import/Scene'; import {SceneJsonExporter} from '../../../../src/engine/io/json/export/Scene'; import BasicDefaultVertex from './templates/meshBasicBuilder/Basic.default.vert.glsl'; import BasicDefaultFragment from './templates/meshBasicBuilder/Basic.default.frag.glsl'; import BasicMinimalVertex from './templates/meshBasicBuilder/Basic.minimal.vert.glsl'; import BasicMinimalFragment from './templates/meshBasicBuilder/Basic.minimal.frag.glsl'; import BasicPositionVertex from './templates/meshBasicBuilder/Basic.position.vert.glsl'; import BasicPositionFragment from './templates/meshBasicBuilder/Basic.position.frag.glsl'; import BasicPositionXZVertex from './templates/meshBasicBuilder/Basic.positionXZ.vert.glsl'; import BasicPositionXZFragment from './templates/meshBasicBuilder/Basic.positionXZ.frag.glsl'; import BasicAttribInVertexVertex from './templates/meshBasicBuilder/Basic.attribInVertex.vert.glsl'; import BasicAttribInVertexFragment from './templates/meshBasicBuilder/Basic.attribInVertex.frag.glsl'; import BasicAttribInFragmentVertex from './templates/meshBasicBuilder/Basic.attribInFragment.vert.glsl'; import BasicAttribInFragmentFragment from './templates/meshBasicBuilder/Basic.attribInFragment.frag.glsl'; import BasicAttribInFragmentOnlyVertex from './templates/meshBasicBuilder/Basic.attribInFragmentOnly.vert.glsl'; import BasicAttribInFragmentOnlyFragment from './templates/meshBasicBuilder/Basic.attribInFragmentOnly.frag.glsl'; import BasicIfThenVertex from './templates/meshBasicBuilder/Basic.IfThen.vert.glsl'; import BasicIfThenFragment from './templates/meshBasicBuilder/Basic.IfThen.frag.glsl'; import BasicIfThenRotateFragment from './templates/meshBasicBuilder/Basic.IfThenRotate.frag.glsl'; import BasicForLoopFragment from './templates/meshBasicBuilder/Basic.ForLoop.frag.glsl'; import BasicSubnetFragment from './templates/meshBasicBuilder/Basic.Subnet.frag.glsl'; import {BaseBuilderMatNodeType} from '../../../../src/engine/nodes/mat/_BaseBuilder'; import {Vec4ToVec3GlNode} from '../../../../src/engine/nodes/gl/_ConversionVecTo'; import {TextureGlNode} from '../../../../src/engine/nodes/gl/Texture'; import {GlCompareTestName} from '../../../../src/engine/nodes/gl/Compare'; import {FloatParam} from '../../../../src/engine/params/Float'; import {Vector3Param} from '../../../../src/engine/params/Vector3'; import {AssemblersUtils} from '../../../helpers/AssemblersUtils'; import {create_required_nodes_for_subnet_gl_node} from '../gl/Subnet'; import {create_required_nodes_for_ifThen_gl_node} from '../gl/IfThen'; import {create_required_nodes_for_forLoop_gl_node} from '../gl/ForLoop'; const TEST_SHADER_LIB = { default: {vert: BasicDefaultVertex, frag: BasicDefaultFragment}, minimal: {vert: BasicMinimalVertex, frag: BasicMinimalFragment}, position: {vert: BasicPositionVertex, frag: BasicPositionFragment}, positionXZ: {vert: BasicPositionXZVertex, frag: BasicPositionXZFragment}, attribInVertex: {vert: BasicAttribInVertexVertex, frag: BasicAttribInVertexFragment}, attribInFragment: {vert: BasicAttribInFragmentVertex, frag: BasicAttribInFragmentFragment}, attribInFragmentOnly: {vert: BasicAttribInFragmentOnlyVertex, frag: BasicAttribInFragmentOnlyFragment}, IfThen: {vert: BasicIfThenVertex, frag: BasicIfThenFragment}, IfThenRotate: {vert: BasicIfThenVertex, frag: BasicIfThenRotateFragment}, ForLoop: {vert: BasicIfThenVertex, frag: BasicForLoopFragment}, Subnet: {vert: BasicIfThenVertex, frag: BasicSubnetFragment}, }; const BASIC_UNIFORMS = UniformsUtils.clone(ShaderLib.basic.uniforms); QUnit.test('mesh basic builder simple', async (assert) => { const MAT = window.MAT; // const debug = MAT.createNode('test') const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const material = mesh_basic1.material; const globals1: GlobalsGlNode = mesh_basic1.node('globals1')! as GlobalsGlNode; const output1: OutputGlNode = mesh_basic1.node('output1')! as OutputGlNode; await mesh_basic1.compute(); assert.equal(material.vertexShader, TEST_SHADER_LIB.default.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.default.frag); assert.deepEqual(Object.keys(material.uniforms).sort(), Object.keys(BASIC_UNIFORMS).sort()); const constant1 = mesh_basic1.createNode('constant'); constant1.set_gl_type(GlConnectionPointType.VEC3); constant1.p.vec3.set([1, 0, 0.5]); output1.setInput('color', constant1, ConstantGlNode.OUTPUT_NAME); // output1.p.color.set([1, 0, 0.5]); await mesh_basic1.compute(); assert.equal(material.vertexShader, TEST_SHADER_LIB.minimal.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.minimal.frag); output1.setInput('color', globals1, 'position'); await mesh_basic1.compute(); assert.equal(material.vertexShader, TEST_SHADER_LIB.position.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.position.frag); const vec3ToFloat1 = mesh_basic1.createNode('vec3ToFloat'); const float_to_vec3_1 = mesh_basic1.createNode('floatToVec3'); float_to_vec3_1.setInput('x', vec3ToFloat1, 'x'); float_to_vec3_1.setInput('z', vec3ToFloat1, 'y'); vec3ToFloat1.setInput('vec', globals1, 'position'); output1.setInput('color', float_to_vec3_1); await mesh_basic1.compute(); assert.equal(material.lights, false); assert.equal(material.vertexShader, TEST_SHADER_LIB.positionXZ.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.positionXZ.frag); // add frame dependency const float_to_vec3_2 = mesh_basic1.createNode('floatToVec3'); float_to_vec3_2.setInput('z', globals1, 'time'); output1.setInput('position', float_to_vec3_2, 'vec3'); await mesh_basic1.compute(); assert.deepEqual(Object.keys(material.uniforms).sort(), Object.keys(BASIC_UNIFORMS).concat(['time']).sort()); }); QUnit.test('mesh basic builder can save and load param configs', async (assert) => { const scene = window.scene; const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); await scene.waitForCooksCompleted(); await mesh_basic1.compute(); assert.deepEqual(mesh_basic1.params.spare_names.sort(), []); assert.notOk(mesh_basic1.assemblerController?.compileRequired()); const output1 = mesh_basic1.node('output1')! as OutputGlNode; const attribute1 = mesh_basic1.createNode('attribute'); const texture1 = mesh_basic1.createNode('texture'); const vec4_to_vector1 = mesh_basic1.createNode('vec4ToVec3'); output1.setInput('color', vec4_to_vector1, Vec4ToVec3GlNode.OUTPUT_NAME_VEC3); vec4_to_vector1.setInput('vec4', texture1, TextureGlNode.OUTPUT_NAME); texture1.setInput('uv', attribute1); attribute1.p.name.set('uv'); attribute1.set_gl_type(GlConnectionPointType.VEC2); // await CoreSleep.sleep(50); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); // mesh_basic1.param_names(); assert.deepEqual(mesh_basic1.params.spare_names.sort(), ['textureMap'], 'spare params has textureMap'); assert.equal(mesh_basic1.p.textureMap.value, '/COP/imageUv', 'textureMap value is "/COP/imageUv"'); mesh_basic1.params.get('textureMap')!.set('/COP/file2'); const data = new SceneJsonExporter(scene).data(); console.log('************ LOAD **************'); const scene2 = await SceneJsonImporter.loadData(data); await scene2.waitForCooksCompleted(); const new_mesh_basic1 = scene2.node('/MAT/meshBasicBuilder1') as BaseBuilderMatNodeType; await new_mesh_basic1.compute(); assert.notOk(new_mesh_basic1.assemblerController?.compileRequired(), 'compile is not required'); assert.deepEqual(new_mesh_basic1.params.spare_names.sort(), ['textureMap'], 'spare params has textureMap'); assert.equal(new_mesh_basic1.params.get('textureMap')?.value, '/COP/file2', 'textureMap value is "/COP/file_uv"'); }); QUnit.test( 'mesh basic builder: attrib is declared accordingly and uses varying if used in fragment', async (assert) => { const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const material = mesh_basic1.material; const output1 = mesh_basic1.node('output1')! as OutputGlNode; const attribute1 = mesh_basic1.createNode('attribute'); attribute1.p.name.set('uv'); attribute1.set_gl_type(GlConnectionPointType.VEC2); const vec2ToFloat1 = mesh_basic1.createNode('vec2ToFloat'); const float_to_vec31 = mesh_basic1.createNode('floatToVec3'); vec2ToFloat1.setInput(0, attribute1); float_to_vec31.setInput('x', vec2ToFloat1, 'x'); float_to_vec31.setInput('z', vec2ToFloat1, 'y'); output1.setInput('position', float_to_vec31); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); assert.equal(material.vertexShader, TEST_SHADER_LIB.attribInVertex.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.attribInVertex.frag); // set uv to color, to have it declared to the fragment shader output1.setInput('color', float_to_vec31); await mesh_basic1.compute(); assert.equal(material.vertexShader, TEST_SHADER_LIB.attribInFragment.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.attribInFragment.frag); // remove uv from position, to have it declared ONLY to the fragment shader output1.setInput('position', null); await mesh_basic1.compute(); assert.equal(material.vertexShader, TEST_SHADER_LIB.attribInFragmentOnly.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.attribInFragmentOnly.frag); } ); QUnit.test('mesh basic builder with ifThen', async (assert) => { const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const material = mesh_basic1.material; const output1 = mesh_basic1.nodesByType('output')[0]; const globals1 = mesh_basic1.nodesByType('globals')[0]; const vec3ToFloat1 = mesh_basic1.createNode('vec3ToFloat'); const compare1 = mesh_basic1.createNode('compare'); const ifThen1 = mesh_basic1.createNode('ifThen'); const {subnetInput1, subnetOutput1} = create_required_nodes_for_ifThen_gl_node(ifThen1); const ifThen_subnetInput1 = subnetInput1; const ifThen_subnetOutput1 = subnetOutput1; const multAdd1 = ifThen1.createNode('multAdd'); vec3ToFloat1.setInput(0, globals1, 'position'); compare1.setInput(0, vec3ToFloat1, 1); compare1.set_test_name(GlCompareTestName.LESS_THAN); ifThen1.setInput(0, compare1); ifThen1.setInput(1, globals1, 'position'); output1.setInput('color', ifThen1, 'position'); multAdd1.setInput(0, ifThen_subnetInput1); multAdd1.params.get('mult')!.set([2, 2, 2]); ifThen_subnetOutput1.setInput(0, multAdd1); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); assert.equal(material.vertexShader, TEST_SHADER_LIB.IfThen.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.IfThen.frag); // now add a node that would create a function const rotate1 = ifThen1.createNode('rotate'); rotate1.setInput(0, ifThen_subnetInput1); ifThen_subnetOutput1.setInput(0, rotate1); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); assert.equal(material.vertexShader, TEST_SHADER_LIB.IfThenRotate.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.IfThenRotate.frag); }); QUnit.test('mesh basic builder with forLoop', async (assert) => { const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const material = mesh_basic1.material; const output1 = mesh_basic1.nodesByType('output')[0]; const globals1 = mesh_basic1.nodesByType('globals')[0]; const forLoop1 = mesh_basic1.createNode('forLoop'); const {subnetInput1, subnetOutput1} = create_required_nodes_for_forLoop_gl_node(forLoop1); const forLoop_subnetInput1 = subnetInput1; const forLoop_subnetOutput1 = subnetOutput1; const add1 = forLoop1.createNode('add'); forLoop1.setInput(0, globals1, 'position'); output1.setInput('color', forLoop1); forLoop_subnetOutput1.setInput(0, add1); add1.setInput(0, forLoop_subnetInput1); add1.params.get('add1')!.set([0.1, 0.1, 0.1]); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); assert.equal(material.vertexShader, TEST_SHADER_LIB.ForLoop.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.ForLoop.frag); }); QUnit.test('mesh basic builder with subnet', async (assert) => { const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const material = mesh_basic1.material; const output1 = mesh_basic1.nodesByType('output')[0]; const globals1 = mesh_basic1.nodesByType('globals')[0]; const subnet1 = mesh_basic1.createNode('subnet'); const {subnetInput1, subnetOutput1} = create_required_nodes_for_subnet_gl_node(subnet1); const subnet_subnetInput1 = subnetInput1; const subnet_subnetOutput1 = subnetOutput1; const add1 = subnet1.createNode('add'); subnet1.setInput(0, globals1, 'position'); output1.setInput('color', subnet1); subnet_subnetOutput1.setInput(0, add1); add1.setInput(0, subnet_subnetInput1); add1.params.get('add1')!.set([1.0, 0.5, 0.25]); assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); await mesh_basic1.compute(); assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required'); assert.equal(material.vertexShader, TEST_SHADER_LIB.Subnet.vert); assert.equal(material.fragmentShader, TEST_SHADER_LIB.Subnet.frag); }); QUnit.test('mesh basic builder persisted_config', async (assert) => { const MAT = window.MAT; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const output1 = mesh_basic1.nodesByType('output')[0]; const globals1 = mesh_basic1.nodesByType('globals')[0]; const param1 = mesh_basic1.createNode('param'); param1.p.name.set('float_param'); const param2 = mesh_basic1.createNode('param'); param2.set_gl_type(GlConnectionPointType.VEC3); param2.p.name.set('vec3_param'); const float_to_vec31 = mesh_basic1.createNode('floatToVec3'); float_to_vec31.setInput(0, param1); float_to_vec31.setInput(1, globals1, 'time'); output1.setInput('color', float_to_vec31); output1.setInput('position', param2); await mesh_basic1.compute(); const scene = window.scene; const data = new SceneJsonExporter(scene).data(); await AssemblersUtils.withUnregisteredAssembler(mesh_basic1.usedAssembler(), async () => { console.log('************ LOAD **************'); const scene2 = await SceneJsonImporter.loadData(data); await scene2.waitForCooksCompleted(); const new_mesh_basic1 = scene2.node('/MAT/meshBasicBuilder1') as BaseBuilderMatNodeType; assert.notOk(new_mesh_basic1.assemblerController); assert.ok(new_mesh_basic1.persisted_config); const float_param = new_mesh_basic1.params.get('float_param') as FloatParam; const vec3_param = new_mesh_basic1.params.get('vec3_param') as Vector3Param; assert.ok(float_param); assert.ok(vec3_param); const material = new_mesh_basic1.material; assert.equal(material.fragmentShader, mesh_basic1.material.fragmentShader); assert.equal(material.vertexShader, mesh_basic1.material.vertexShader); // float param callback assert.equal(material.uniforms.v_POLY_param1_val.value, 0); float_param.set(2); assert.equal(material.uniforms.v_POLY_param1_val.value, 2); float_param.set(4); assert.equal(material.uniforms.v_POLY_param1_val.value, 4); // vector3 param callback assert.deepEqual(material.uniforms.v_POLY_param2_val.value.toArray(), [0, 0, 0]); vec3_param.set([1, 2, 3]); assert.deepEqual(material.uniforms.v_POLY_param2_val.value.toArray(), [1, 2, 3]); vec3_param.set([5, 6, 7]); assert.deepEqual(material.uniforms.v_POLY_param2_val.value.toArray(), [5, 6, 7]); }); }); QUnit.test('mesh basic builder frame dependent with custom mat', async (assert) => { const MAT = window.MAT; const scene = window.scene; const mesh_basic1 = MAT.createNode('meshBasicBuilder'); mesh_basic1.createNode('output'); mesh_basic1.createNode('globals'); const output1 = mesh_basic1.nodesByType('output')[0]; const globals1 = mesh_basic1.nodesByType('globals')[0]; assert.notOk((mesh_basic1.material as any).uniforms.time); output1.setInput('alpha', globals1, 'time'); await mesh_basic1.compute(); const customMat = mesh_basic1.material.customMaterials.customDepthDOFMaterial!; assert.equal((mesh_basic1.material as any).uniforms.time.value, 0); assert.equal(customMat.uniforms.time.value, 0); scene.setFrame(60); assert.equal((mesh_basic1.material as any).uniforms.time.value, 1); assert.equal(customMat.uniforms.time.value, 1); const data = new SceneJsonExporter(scene).data(); await AssemblersUtils.withUnregisteredAssembler(mesh_basic1.usedAssembler(), async () => { console.log('************ LOAD **************'); const scene2 = await SceneJsonImporter.loadData(data); await scene2.waitForCooksCompleted(); const new_mesh_basic1 = scene2.node('/MAT/meshBasicBuilder1') as BaseBuilderMatNodeType; const mesh_basic2 = new_mesh_basic1; const customMat2 = mesh_basic2.material.customMaterials.customDepthDOFMaterial!; assert.equal((mesh_basic2.material as any).uniforms.time.value, 1); assert.equal(customMat2.uniforms.time.value, 1); scene.setFrame(120); assert.equal((mesh_basic2.material as any).uniforms.time.value, 1); assert.equal(customMat2.uniforms.time.value, 1); }); }); QUnit.skip('mesh basic builder bbox dependent', (assert) => {}); QUnit.skip('mesh basic builder basic instanced works without an input node', (assert) => {});
the_stack
import { HardhatRuntimeEnvironment } from "hardhat/types"; import { DeployFunction } from "hardhat-deploy/types"; import { ethers, network } from "hardhat"; import { Timelock__factory } from "../../../../typechain"; import MainnetConfig from "../../../../.mainnet.json"; import TestnetConfig from "../../../../.testnet.json"; import { FileService, TimelockService } from "../../../services"; import { TimelockEntity } from "../../../entities"; interface IWorker { WORKER_NAME: string; ADDRESS: string; } type IWorkers = Array<IWorker>; interface IWorkerReinvestConfig { WORKER_NAME: string; ADDRESS: string; REINVEST_BOUNTY_BPS: string; REINVEST_THRESHOLD: string; REINVEST_PATH: Array<string>; } type IWorkerReinvestConfigs = Array<IWorkerReinvestConfig>; interface IWorkerReinvestConfigInput { WORKER_NAME: string; REINVEST_BOUNTY_BPS: string; REINVEST_THRESHOLD: string; REINVEST_PATH?: Array<string>; } type IWorkerReinvestConfigInputs = Array<IWorkerReinvestConfigInput>; /** * @description Deployment script for upgrades workers to 02 version * @param {HardhatRuntimeEnvironment} hre */ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { /* ░██╗░░░░░░░██╗░█████╗░██████╗░███╗░░██╗██╗███╗░░██╗░██████╗░ ░██║░░██╗░░██║██╔══██╗██╔══██╗████╗░██║██║████╗░██║██╔════╝░ ░╚██╗████╗██╔╝███████║██████╔╝██╔██╗██║██║██╔██╗██║██║░░██╗░ ░░████╔═████║░██╔══██║██╔══██╗██║╚████║██║██║╚████║██║░░╚██╗ ░░╚██╔╝░╚██╔╝░██║░░██║██║░░██║██║░╚███║██║██║░╚███║╚██████╔╝ ░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝░░╚═╝╚═╝░░╚══╝╚═╝╚═╝░░╚══╝░╚═════╝░ Check all variables below before execute the deployment script */ const title = "mainnet-xALPACA-set-reinvest-config"; const workerInputs: IWorkerReinvestConfigInputs = [ { WORKER_NAME: "USDT-BTCB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB", "BTCB"], }, { WORKER_NAME: "ETH-BTCB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB", "BTCB"], }, { WORKER_NAME: "WBNB-BTCB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB", "BTCB"], }, { WORKER_NAME: "BTCB-USDT MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "USDT"], }, { WORKER_NAME: "ETH-USDT MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "USDT"], }, { WORKER_NAME: "WBNB-USDT MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "USDT"], }, { WORKER_NAME: "USDC-USDT MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "USDT"], }, { WORKER_NAME: "DAI-USDT MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "USDT"], }, { WORKER_NAME: "USDT-ETH MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "ETH"], }, { WORKER_NAME: "WBNB-ETH MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "ETH"], }, { WORKER_NAME: "BTCB-ETH MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "ETH"], }, { WORKER_NAME: "MDX-BUSD MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "BUSD"], }, { WORKER_NAME: "WBNB-BUSD MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "BUSD"], }, { WORKER_NAME: "MDX-WBNB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB"], }, { WORKER_NAME: "BUSD-WBNB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB"], }, { WORKER_NAME: "ETH-WBNB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB"], }, { WORKER_NAME: "USDT-WBNB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB"], }, { WORKER_NAME: "BTCB-WBNB MdexWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "33", REINVEST_PATH: ["MDX", "WBNB"], }, { WORKER_NAME: "BUSD-TUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD", "TUSD"], }, { WORKER_NAME: "ETH-BTCB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "BTCB"], }, { WORKER_NAME: "BUSD-BTCB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "BTCB"], }, { WORKER_NAME: "WBNB-BTCB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "BTCB"], }, { WORKER_NAME: "USDC-USDT PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "USDT"], }, { WORKER_NAME: "CAKE-USDT PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "USDT"], }, { WORKER_NAME: "WBNB-USDT PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "USDT"], }, { WORKER_NAME: "BUSD-USDT PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "USDT"], }, { WORKER_NAME: "BUSD-ALPACA PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD", "ALPACA"], }, { WORKER_NAME: "BTCB-ETH PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "ETH"], }, { WORKER_NAME: "WBNB-ETH PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "ETH"], }, { WORKER_NAME: "SUSHI-ETH PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "ETH"], }, { WORKER_NAME: "COMP-ETH PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB", "ETH"], }, { WORKER_NAME: "BMON-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "POTS-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "PHA-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "PMON-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "BTT-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "TRX-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "ORBS-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "TUSD-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "FORM-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "CAKE-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "ALPACA-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "BTCB-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "UST-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "DAI-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "USDC-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "VAI-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "WBNB-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "USDT-BUSD PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "BUSD"], }, { WORKER_NAME: "SPS-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "BMON-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "QBT-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "DVI-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "MBOX-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "NAOS-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "AXS-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "ADA-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "ODDZ-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "USDT-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "DODO-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "SWINGBY-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "pCWS-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "BELT-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "bMXX-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "BUSD-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "YFI-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "XVS-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "LINK-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "UNI-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "DOT-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "ETH-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "BTCB-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, { WORKER_NAME: "CAKE-WBNB PancakeswapWorker", REINVEST_BOUNTY_BPS: "900", REINVEST_THRESHOLD: "1", REINVEST_PATH: ["CAKE", "WBNB"], }, ]; const EXACT_ETA = "1640242800"; const config = network.name === "mainnet" ? MainnetConfig : TestnetConfig; const allWorkers: IWorkers = config.Vaults.reduce((accum, vault) => { return accum.concat( vault.workers.map((worker) => { return { WORKER_NAME: worker.name, ADDRESS: worker.address, }; }) ); }, [] as IWorkers); const reinvestConfigs: IWorkerReinvestConfigs = workerInputs.map((reinvestConfig) => { // 1. find each worker having an identical name as workerInput // 2. if hit return // 3. other wise throw error const hit = allWorkers.find((worker) => { return worker.WORKER_NAME === reinvestConfig.WORKER_NAME; }); if (hit === undefined) throw new Error(`could not find ${reinvestConfig.WORKER_NAME}`); if (!reinvestConfig.WORKER_NAME.includes("CakeMaxiWorker") && !reinvestConfig.REINVEST_PATH) throw new Error(`${reinvestConfig.WORKER_NAME} must have a REINVEST_PATH`); const tokenList: any = config.Tokens; let reinvestPath: Array<string> = []; if (reinvestConfig.REINVEST_PATH) { reinvestPath = reinvestConfig.REINVEST_PATH.map((p) => { const addr = tokenList[p]; if (addr === undefined) { throw `error: path: unable to find address of ${p}`; } return addr; }); } return { WORKER_NAME: hit.WORKER_NAME, ADDRESS: hit.ADDRESS, REINVEST_BOUNTY_BPS: reinvestConfig.REINVEST_BOUNTY_BPS, REINVEST_THRESHOLD: ethers.utils.parseEther(reinvestConfig.REINVEST_THRESHOLD).toString(), REINVEST_PATH: reinvestPath, }; }); const deployer = (await ethers.getSigners())[0]; const timelockTransactions: Array<TimelockEntity.Transaction> = []; let nonce = await deployer.getTransactionCount(); for (const reinvestConfig of reinvestConfigs) { if (reinvestConfig.WORKER_NAME.includes("CakeMaxiWorker")) { timelockTransactions.push( await TimelockService.queueTransaction( `setting reinvest params for ${reinvestConfig.WORKER_NAME}`, reinvestConfig.ADDRESS, "0", "setReinvestConfig(uint256,uint256)", ["uint256", "uint256"], [reinvestConfig.REINVEST_BOUNTY_BPS, reinvestConfig.REINVEST_THRESHOLD], EXACT_ETA, { nonce: nonce++ } ) ); } else { timelockTransactions.push( await TimelockService.queueTransaction( `setting reinvest params for ${reinvestConfig.WORKER_NAME}`, reinvestConfig.ADDRESS, "0", "setReinvestConfig(uint256,uint256,address[])", ["uint256", "uint256", "address[]"], [reinvestConfig.REINVEST_BOUNTY_BPS, reinvestConfig.REINVEST_THRESHOLD, reinvestConfig.REINVEST_PATH], EXACT_ETA, { nonce: nonce++ } ) ); } } FileService.write(`${title}`, timelockTransactions); }; export default func; func.tags = ["TimelockSetReinvestConfigWorkers02"];
the_stack
* @packageDocumentation * @module std */ //================================================================ import { IArrayContainer } from "../base/container/IArrayContainer"; import { ArrayContainer } from "../internal/container/linear/ArrayContainer"; import { ArrayIterator } from "../internal/iterator/ArrayIterator"; import { ArrayReverseIterator } from "../internal/iterator/ArrayReverseIterator"; import { TreeMap } from "./TreeMap"; import { IForwardIterator } from "../iterator/IForwardIterator"; import { NativeArrayIterator } from "../internal/iterator/disposable/NativeArrayIterator"; import { Pair } from "../utility/Pair"; import { not_equal_to } from "../functional/comparators"; /** * Vector only for `boolean`. * * @author Jeongho Nam - https://github.com/samchon */ export class VectorBoolean extends ArrayContainer<boolean, VectorBoolean, VectorBoolean, VectorBoolean.Iterator, VectorBoolean.ReverseIterator, boolean> implements IArrayContainer<boolean, VectorBoolean, VectorBoolean.Iterator, VectorBoolean.ReverseIterator> { /** * Store not full elements, but their sequence. * * - first: index * - second: value */ private data_!: TreeMap<number, boolean>; /** * Number of elements */ private size_!: number; /* ========================================================= CONSTRUCTORS & SEMI-CONSTRUCTORS - CONSTRUCTORS - ASSIGN & CLEAR ============================================================ CONSTURCTORS --------------------------------------------------------- */ /** * Default Constructor. */ public constructor(); /** * Initializer Constructor. * * @param items Items to assign. */ public constructor(array: boolean[]); /** * Copy Constructor * * @param obj Object to copy. */ public constructor(obj: VectorBoolean); /** * Fill Constructor. * * @param size Initial size. * @param val Value to fill. */ public constructor(n: number, val: boolean); /** * Range Constructor. * * @param first Input iterator of the first position. * @param last Input iteartor of the last position. */ public constructor(first: Readonly<IForwardIterator<boolean>>, last: Readonly<IForwardIterator<boolean>>); public constructor(...args: any[]) { super(); if (args.length === 1 && args[0] instanceof VectorBoolean) { // COPY CONSTRUCTOR const obj: VectorBoolean = args[0]; this.data_ = new TreeMap(obj.data_.begin(), obj.data_.end()); this.size_ = obj.size_; } else if (args.length === 1 && args[0] instanceof Array) { // INITIALIZER this.clear(); this.push(...args[0]); } else if (args.length === 2) { // ASSIGNER this.assign(args[0], args[1]); } else // DEFAULT CONSTRUCTOR this.clear(); } /* --------------------------------------------------------- ASSIGN & CLEAR --------------------------------------------------------- */ /** * @inheritDoc */ public assign(n: number, val: boolean): void; /** * @inheritDoc */ public assign<InputIterator extends Readonly<IForwardIterator<boolean, InputIterator>>> (first: InputIterator, last: InputIterator): void; public assign(first: any, last: any): void { this.clear(); this.insert(this.end(), first, last); } /** * @inheritDoc */ public clear(): void { this.data_ = new TreeMap(); this.size_ = 0; } /** * @inheritDoc */ public resize(n: number): void { const expansion: number = n - this.size(); if (expansion > 0) this.insert(this.end(), expansion, false); else if (expansion < 0) this.erase(this.end().advance(-expansion), this.end()); } /** * Flip all values. */ public flip(): void { for (const entry of this.data_) entry.second = !entry.second; } /** * @inheritDoc */ public swap(obj: VectorBoolean): void { [this.data_, obj.data_] = [obj.data_, this.data_]; [this.size_, obj.size_] = [obj.size_, this.size_]; } /* ========================================================= ACCESSORS ========================================================= */ protected source(): VectorBoolean { return this; } /** * @inheritDoc */ public size(): number { return this.size_; } protected _At(index: number): boolean { // FIND THE NEAREST NODE OF LEFT const it = this._Find_node(index); return it.second; // RETURNS } protected _Set(index: number, val: boolean): void { val = !!val; // SIFT // FIND THE NEAREAST NODE OF LEFT let it = this._Find_node(index); if (it.second === val) return; // NO NEED TO CHANGE //---- // CHANGE VALUE //---- if (it.first === index) { // CHANGE VALUE DIRECTLY it.second = val; } else { // EMPLACE NEW NODE it = this.data_.emplace(index, val).first; } //---- // POST-PROCESS //---- // THE LAST ELEMENT, NO POST-PROCESS REQUIRED if (index === this.size() - 1) return; // LIST UP NEIGHBORS const prev = it.prev(); const next = it.next(); // ARRANGE LEFT SIDE if (not_equal_to(prev, this.data_.end()) && prev.second === it.second) this.data_.erase(it); // ARRANGE RIGHT SIDE if (next.equals(this.data_.end()) === true || (next.first !== index + 1 || next.second !== val)) { // 1) IT'S THE LAST NODE // 2) NEXT NODE DOES NOT POINT THE INDEX + 1 (NEAREST NEIGHBOR) // 3) NEXT NODE'S VALUE IS DIFFERENT WITH THE CHANGED VALUE //---- // EMPLACE NEW NODE WITH OLD this.data_.emplace(index + 1, !val); } else { // NEXT NODE'S VALUE IS SAME WITH THE CHANGED VALUE //---- // ERASE THE NEXT NODE this.data_.erase(next); } } /** * @inheritDoc */ public nth(index: number): VectorBoolean.Iterator { return new VectorBoolean.Iterator(this as VectorBoolean, index); } private _Find_node(index: number): TreeMap.Iterator<number, boolean> { return this.data_.upper_bound(index).prev(); } /* ========================================================= ELEMENTS I/O - PUSH & POP - INSERT - ERASE ============================================================ PUSH & POP --------------------------------------------------------- */ /** * @inheritDoc */ public push(...items: boolean[]): number { if (items.length === 0) return this.size(); const first = new NativeArrayIterator(items, 0); const last = new NativeArrayIterator(items, items.length); this._Insert_by_range(this.end(), first, last); return this.size(); } /** * @inheritDoc */ public push_back(val: boolean): void { const it = this.data_.rbegin(); const index: number = this.size_++; val = !!val; // SIFT // EMPLACE OR NOT if (this.data_.empty() || it.second !== val) this.data_.emplace(index, val); } protected _Pop_back(): void { const it: TreeMap.ReverseIterator<number, boolean> = this.data_.rbegin(); const index: number = --this.size_; // ERASE OR NOT if (it.first === index) this.data_.erase(it.base()); } /* --------------------------------------------------------- INSERT --------------------------------------------------------- */ protected _Insert_by_repeating_val(pos: VectorBoolean.Iterator, n: number, val: boolean): VectorBoolean.Iterator { // RESERVE ELEMENTS -> THE REPEATED COUNT AND VALUE const elements: Pair<number, boolean>[] = []; elements.push(new Pair(n, val)); // DO INSERT if (pos.equals(this.end()) === true) return this._Insert_to_end(elements); else return this._Insert_to_middle(pos, elements); } protected _Insert_by_range<InputIterator extends Readonly<IForwardIterator<boolean, InputIterator>>> (pos: VectorBoolean.Iterator, first: InputIterator, last: InputIterator): VectorBoolean.Iterator { // RESERVE ELEMENTS -> REPEATED SIZE & VALUE const elements: Pair<number, boolean>[] = []; for (let it = first; !it.equals(last); it = it.next()) { if (elements.length === 0 || elements[elements.length - 1].second !== it.value) elements.push(new Pair(1, it.value)); else ++elements[elements.length - 1].first; } if (pos.equals(this.end()) === true) return this._Insert_to_end(elements); else return this._Insert_to_middle(pos, elements); } private _Insert_to_middle(pos: VectorBoolean.Iterator, elements: Pair<number, boolean>[]): VectorBoolean.Iterator { const first = this._Find_node(pos.index()); for (let it = first; !it.equals(this.data_.end()); it = it.next()) { // COMPUTE SIZE TO ENROLL const next: TreeMap.Iterator<number, boolean> = it.next(); const sx: number = (it.first < pos.index()) ? pos.index() // POSITION TO INSERT : it.first; // CURRENT POINT const sy: number = next.equals(this.data_.end()) ? this.size() // IT'S THE LAST ELEMENT : next.first; // TO NEXT ELEMENT // DO ENROLL const size: number = sy - sx; const value: boolean = !!it.second; elements.push(new Pair(size, value)); } // ERASE BACK-SIDE ELEMENTS FOR THE POST-INSERTION this.size_ = pos.index(); this.data_.erase ( first.first === pos.index() ? first : first.next(), this.data_.end() ); // DO POST-INSERTION return this._Insert_to_end(elements); } private _Insert_to_end(elements: Pair<number, boolean>[]): VectorBoolean.Iterator { const old_size: number = this.size(); const last_value: boolean | null = this.data_.empty() ? null : this.data_.rbegin().second; for (let i: number = 0; i < elements.length; ++i) { const p: Pair<number, boolean> = elements[i]; // INDEXING const index: number = this.size(); const value: boolean = !!p.second; this.size_ += p.first; // NEED NOT TO EMPLACE, JUST SKIP if (i === 0 && value === last_value) continue; // DO EMPLACE this.data_.emplace(index, value); } return this.begin().advance(old_size); } /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ protected _Erase_by_range(first: VectorBoolean.Iterator, last: VectorBoolean.Iterator): VectorBoolean.Iterator { const elements: Pair<number, boolean>[] = []; if (last.equals(this.end()) === false) { const last_index: number = Math.min(this.size(), last.index()); for (let it = this._Find_node(last_index); !it.equals(this.data_.end()); it = it.next()) { const next: TreeMap.Iterator<number, boolean> = it.next(); const sx: number = Math.max(it.first, last_index); const sy: number = next.equals(this.data_.end()) ? this.size() // IT'S THE LAST ELEMENT : next.first; // TO NEXT ELEMENT const size: number = sy - sx; const value: boolean = it.second; elements.push(new Pair(size, value)); } } this.size_ = first.index(); this.data_.erase ( this.data_.lower_bound(this.size_), this.data_.end() ); return this._Insert_to_end(elements); } } /** * */ export namespace VectorBoolean { // HEAD /** * Iterator of {@link VectorBoolean} */ export type Iterator = ArrayIterator<boolean, VectorBoolean>; /** * Reverse iterator of {@link VectorBoolean} */ export type ReverseIterator = ArrayReverseIterator<boolean, VectorBoolean>; // BODY export const Iterator = ArrayIterator; export const ReverseIterator = ArrayReverseIterator; }
the_stack
namespace fgui { export class GRootMouseStatus { public touchDown: boolean = false; public mouseX: number = 0; public mouseY: number = 0; } export class GRoot extends GComponent { private static uniqueID:number = 0; private $uiStage: UIStage; private $modalLayer: GGraph; private $popupStack: GObject[]; private $justClosedPopups: GObject[]; private $modalWaitPane: GObject; private $focusedObject: GObject; private $tooltipWin: GObject; private $defaultTooltipWin: GObject; private $checkingPopups:boolean; private $uid:number; private static $inst: GRoot; private static $gmStatus = new GRootMouseStatus(); /** * the singleton instance of the GRoot object */ public static get inst(): GRoot { if (GRoot.$inst == null) new GRoot(); return GRoot.$inst; } /** * the current mouse/pointer data */ public static get globalMouseStatus(): GRootMouseStatus { return GRoot.$gmStatus; } /** * the main entry to lauch the UI root, e.g.: GRoot.inst.attachTo(app, options) * @param app your PIXI.Application instance to be used in this GRoot instance * @param stageOptions stage rotation / resize options */ public attachTo(app: PIXI.Application, stageOptions?: UIStageOptions): void { createjs.Ticker = null; //no need this one GTimer.inst.setTicker(app.ticker); if (this.$uiStage) { this.$uiStage.off(DisplayObjectEvent.SIZE_CHANGED, this.$winResize, this); this.$uiStage.nativeStage.off(InteractiveEvents.Down, this.$stageDown, this); this.$uiStage.nativeStage.off(InteractiveEvents.Up, this.$stageUp, this); this.$uiStage.nativeStage.off(InteractiveEvents.Move, this.$stageMove, this); this.$uiStage.nativeStage.removeChild(this.$displayObject); this.$uiStage.dispose(); } this.$uiStage = new UIStage(app, stageOptions); this.$uiStage.on(DisplayObjectEvent.SIZE_CHANGED, this.$winResize, this); this.$uiStage.nativeStage.on(InteractiveEvents.Down, this.$stageDown, this); this.$uiStage.nativeStage.on(InteractiveEvents.Up, this.$stageUp, this); this.$uiStage.nativeStage.on(InteractiveEvents.Move, this.$stageMove, this); this.$uiStage.nativeStage.addChild(this.$displayObject); this.$winResize(this.$uiStage); if (!this.$modalLayer) { this.$modalLayer = new GGraph(); this.$modalLayer.setSize(this.width, this.height); this.$modalLayer.drawRect(0, 0, 0, UIConfig.modalLayerColor, UIConfig.modalLayerAlpha); this.$modalLayer.addRelation(this, RelationType.Size); } } public constructor() { super(); if (GRoot.$inst == null) GRoot.$inst = this; this.opaque = false; this.$popupStack = [] this.$justClosedPopups = []; this.$uid = GRoot.uniqueID++; utils.DOMEventManager.inst.on(DisplayObjectEvent.MOUSE_WHEEL, this.dispatchMouseWheel, this); } public get uniqueID():number { return this.$uid; } public get stageWidth(): number { return this.$uiStage.stageWidth; } public get stageHeight(): number { return this.$uiStage.stageHeight; } public get contentScaleFactor(): number { return this.$uiStage.resolution; } public get applicationContext(): PIXI.Application { return this.$uiStage.applicationContext; } public get nativeStage(): PIXI.Container { return this.$uiStage.nativeStage; } public get orientation():StageOrientation { return this.$uiStage.orientation; } public get stageWrapper(): UIStage { return this.$uiStage; } protected dispatchMouseWheel(evt:any):void { let childUnderMouse = this.getObjectUnderPoint(GRoot.globalMouseStatus.mouseX, GRoot.globalMouseStatus.mouseY); if(childUnderMouse != null) { //bubble while(childUnderMouse.parent && childUnderMouse.parent != this) { childUnderMouse.emit(DisplayObjectEvent.MOUSE_WHEEL, evt); childUnderMouse = childUnderMouse.parent; } } } /** * get the objects which are placed underneath the given stage coordinate * @param globalX the stage X * @param globalY the stage Y */ public getObjectUnderPoint(globalX:number, globalY:number):GObject { GRoot.sHelperPoint.set(globalX, globalY); let ret: PIXI.DisplayObject = this.$uiStage.applicationContext.renderer.plugins.interaction.hitTest(GRoot.sHelperPoint, this.nativeStage); return GObject.castFromNativeObject(ret); } public showWindow(win: Window): void { this.addChild(win); win.requestFocus(); if (win.x > this.width) win.x = this.width - win.width; else if (win.x + win.width < 0) win.x = 0; if (win.y > this.height) win.y = this.height - win.height; else if (win.y + win.height < 0) win.y = 0; this.adjustModalLayer(); } public hideWindow(win: Window): void { win.hide(); } public hideWindowImmediately(win: Window): void { if (win.parent == this) this.removeChild(win); this.adjustModalLayer(); } public bringToFront(win: Window): void { let i: number; if (this.$modalLayer.parent != null && !win.modal) i = this.getChildIndex(this.$modalLayer) - 1; else i = this.numChildren - 1; for (; i >= 0; i--) { let g: GObject = this.getChildAt(i); if (g == win) return; if (g instanceof Window) break; } if (i >= 0) this.setChildIndex(win, i); } public showModalWait(msg: string = null): void { if (UIConfig.globalModalWaiting != null) { if (this.$modalWaitPane == null) { this.$modalWaitPane = UIPackage.createObjectFromURL(UIConfig.globalModalWaiting); this.$modalWaitPane.addRelation(this, RelationType.Size); } this.$modalWaitPane.setSize(this.width, this.height); this.addChild(this.$modalWaitPane); this.$modalWaitPane.text = msg; } } public closeModalWait(): void { if (this.$modalWaitPane != null && this.$modalWaitPane.parent != null) this.removeChild(this.$modalWaitPane); } public closeAllExceptModals(): void { let arr: GObject[] = this.$children.slice(); arr.forEach(g => { if ((g instanceof Window) && !(g as Window).modal) g.hide(); }, this); } public closeAllWindows(): void { let arr: GObject[] = this.$children.slice(); arr.forEach(g => { if (g instanceof Window) g.hide(); }, this); } public getTopWindow(): Window { let cnt: number = this.numChildren; for (let i: number = cnt - 1; i >= 0; i--) { let g: GObject = this.getChildAt(i); if (g instanceof Window) { return g as Window; } } return null; } public get hasModalWindow(): boolean { return this.$modalLayer.parent != null; } public get modalWaiting(): boolean { return this.$modalWaitPane && this.$modalWaitPane.inContainer; } public showPopup(popup: GObject, target: GObject = null, dir: PopupDirection = PopupDirection.Auto): void { if (this.$popupStack.length > 0) { let k: number = this.$popupStack.indexOf(popup); if (k != -1) { for (let i: number = this.$popupStack.length - 1; i >= k; i--) this.removeChild(this.$popupStack.pop()); } } this.$popupStack.push(popup); this.addChild(popup); this.adjustModalLayer(); let pos: PIXI.Point; let sizeW: number = 0, sizeH: number = 0; if (target) { pos = target.localToRoot(); sizeW = target.width; sizeH = target.height; } else pos = this.globalToLocal(GRoot.$gmStatus.mouseX, GRoot.$gmStatus.mouseY); let xx: number, yy: number; xx = pos.x; if (xx + popup.width > this.width) xx = xx + sizeW - popup.width; yy = pos.y + sizeH; if ((dir == PopupDirection.Auto && yy + popup.height > this.height) || dir == PopupDirection.Up) { yy = pos.y - popup.height - 1; if (yy < 0) { yy = 0; xx += sizeW * .5; } } popup.x = xx; popup.y = yy; } public togglePopup(popup: GObject, target: GObject = null, dir?: PopupDirection): void { if (this.$justClosedPopups.indexOf(popup) != -1) return; this.showPopup(popup, target, dir); } public hidePopup(popup: GObject = null): void { let i:number; if (popup != null) { let k: number = this.$popupStack.indexOf(popup); if (k != -1) { for (i = this.$popupStack.length - 1; i >= k; i--) this.closePopup(this.$popupStack.pop()); } } else { let cnt: number = this.$popupStack.length; for (i = cnt - 1; i >= 0; i--) this.closePopup(this.$popupStack[i]); this.$popupStack.length = 0; } } public get hasAnyPopup(): boolean { return this.$popupStack.length != 0; } private closePopup(target: GObject): void { if (target.parent != null) { if (target instanceof Window) (target as Window).hide(); else this.removeChild(target); } } public showTooltips(msg: string): void { if (this.$defaultTooltipWin == null) { let resourceURL: string = UIConfig.tooltipsWin; if (!resourceURL) { console.error("UIConfig.tooltipsWin not defined"); return; } this.$defaultTooltipWin = UIPackage.createObjectFromURL(resourceURL); } this.$defaultTooltipWin.text = msg; this.showTooltipsWin(this.$defaultTooltipWin); } public showTooltipsWin(tooltipWin: GObject, position: PIXI.Point = null): void { this.hideTooltips(); this.$tooltipWin = tooltipWin; let xx: number = 0; let yy: number = 0; if (position == null) { xx = GRoot.$gmStatus.mouseX + 10; yy = GRoot.$gmStatus.mouseY + 20; } else { xx = position.x; yy = position.y; } let pt: PIXI.Point = this.globalToLocal(xx, yy); xx = pt.x; yy = pt.y; if (xx + this.$tooltipWin.width > this.width) { xx = xx - this.$tooltipWin.width - 1; if (xx < 0) xx = 10; } if (yy + this.$tooltipWin.height > this.height) { yy = yy - this.$tooltipWin.height - 1; if (xx - this.$tooltipWin.width - 1 > 0) xx = xx - this.$tooltipWin.width - 1; if (yy < 0) yy = 10; } this.$tooltipWin.x = xx; this.$tooltipWin.y = yy; this.addChild(this.$tooltipWin); } public hideTooltips(): void { if (this.$tooltipWin != null) { if (this.$tooltipWin.parent) this.removeChild(this.$tooltipWin); this.$tooltipWin = null; } } public get focus(): GObject { if (this.$focusedObject && !this.$focusedObject.onStage) this.$focusedObject = null; return this.$focusedObject; } public set focus(value: GObject) { if (value && (!value.focusable || !value.onStage)) throw new Error("Invalid target to focus"); this.setFocus(value); } private setFocus(value: GObject) { if (this.$focusedObject != value) { this.$focusedObject = value; this.emit(FocusEvent.CHANGED, this); } } private adjustModalLayer(): void { let cnt: number = this.numChildren; if (this.$modalWaitPane != null && this.$modalWaitPane.parent != null) this.setChildIndex(this.$modalWaitPane, cnt - 1); for (let i: number = cnt - 1; i >= 0; i--) { let g: GObject = this.getChildAt(i); if ((g instanceof Window) && g.modal) { if (this.$modalLayer.parent == null) this.addChildAt(this.$modalLayer, i); else this.setChildIndexBefore(this.$modalLayer, i); return; } } if (this.$modalLayer.parent != null) this.removeChild(this.$modalLayer); } private $stageDown(evt: PIXI.interaction.InteractionEvent): void { GRoot.$gmStatus.mouseX = evt.data.global.x; GRoot.$gmStatus.mouseY = evt.data.global.y; GRoot.$gmStatus.touchDown = true; //check focus let mc: PIXI.DisplayObject = evt.target; while (mc && mc != this.nativeStage) { if (fgui.isUIObject(mc)) { let g = mc.UIOwner; if (g.touchable && g.focusable) { this.setFocus(g); break; } } mc = mc.parent; } if (this.$tooltipWin != null) this.hideTooltips(); this.checkPopups(evt.target); } public checkPopups(target:PIXI.DisplayObject):void { if(this.$checkingPopups) return; this.$checkingPopups = true; this.$justClosedPopups.length = 0; if (this.$popupStack.length > 0) { let mc = target; while (mc && mc != this.nativeStage) { if (fgui.isUIObject(mc)) { let pindex = this.$popupStack.indexOf(mc.UIOwner); if (pindex != -1) { let popup:GObject; for(let i = this.$popupStack.length - 1; i > pindex; i--) { popup = this.$popupStack.pop(); this.closePopup(popup); this.$justClosedPopups.push(popup); } return; } } mc = mc.parent; } let cnt = this.$popupStack.length; let popup:GObject; for(let i = cnt - 1; i >= 0; i--) { popup = this.$popupStack[i]; this.closePopup(popup); this.$justClosedPopups.push(popup); } this.$popupStack.length = 0; } } private $stageMove(evt: PIXI.interaction.InteractionEvent): void { GRoot.$gmStatus.mouseX = evt.data.global.x; GRoot.$gmStatus.mouseY = evt.data.global.y; } private $stageUp(evt: PIXI.interaction.InteractionEvent): void { GRoot.$gmStatus.touchDown = false; this.$checkingPopups = false; } private $winResize(stage: UIStage): void { this.setSize(stage.stageWidth, stage.stageHeight); } } }
the_stack
var DEBUG_STATE: boolean; // avoid TS compilation errors but still get working JS code namespace ContentScript { export class SelectionData { isInInputField: boolean; // doesn't include "content editable" fields (use isInContentEditableField() for that) unprocessedText: string; text: string; element: HTMLElement; selection: Selection; } // TODO: move this enum to the background script and add all possible messages const enum MessageType { EngineClick = "engineClick", Log = "log", GetActivationSettings = "getActivationSettings", GetPopupSettings = "getPopupSettings", } abstract class Message { constructor(public type: MessageType) { this.type = type; } } class EngineClickMessage extends Message { selection: string; engine: SSS.SearchEngine; href: string; openingBehaviour: SSS.OpenResultBehaviour; constructor() { super(MessageType.EngineClick); } } class LogMessage extends Message { constructor(public log: any) { super(MessageType.Log); } } class GetPopupSettingsMessage extends Message { constructor() { super(MessageType.GetPopupSettings); } } const DEBUG = typeof DEBUG_STATE !== "undefined" && DEBUG_STATE === true; if (DEBUG) { // To have all log messages in the same console, we always request the background script to log. // Otherwise content script messages will be in the Web Console instead of the Dev Tools Console. var log = msg => browser.runtime.sendMessage(new LogMessage(msg)); } // Globals let popup: PopupCreator.SSSPopup = null; const selection: SelectionData = new SelectionData(); let mousePositionX: number = 0; let mousePositionY: number = 0; let canMiddleClickEngine: boolean = true; let activationSettings: SSS.ActivationSettings = null; let settings: SSS.Settings = null; let sssIcons: { [id: string] : SSS.SSSIconDefinition; } = null; let popupShowTimeout: number = null; setTimeout(() => PopupCreator.onSearchEngineClick = onSearchEngineClick, 0); // be prepared for messages from background script browser.runtime.onMessage.addListener(onMessageReceived); if (DEBUG) { log("content script has started!"); } // act when the background script requests something from this script function onMessageReceived(msg, sender, callbackFunc) { switch (msg.type) { case "isAlive": callbackFunc(true); // simply return true to say "I'm alive!" break; case "activate": // if this is not the first activation, reset everything first if (activationSettings !== null) { deactivate(); } activate(msg.activationSettings, msg.isPageBlocked); // background script passes a few settings needed for setup break; case "showPopup": if (saveCurrentSelection()) { showPopupForSelection(null, true); } break; case "copyToClipboardAsHtml": copyToClipboardAsHtml(); break; case "copyToClipboardAsPlainText": copyToClipboardAsPlainText(); break; default: break; } } function copyToClipboardAsHtml() { document.execCommand("copy"); } function copyToClipboardAsPlainText() { document.addEventListener("copy", copyToClipboardAsPlainText_Listener); document.execCommand("copy"); document.removeEventListener("copy", copyToClipboardAsPlainText_Listener); } function copyToClipboardAsPlainText_Listener(e: ClipboardEvent) { if (saveCurrentSelection()) { e.clipboardData.setData("text/plain", selection.unprocessedText); e.preventDefault(); } } // default error handler for promises function getErrorHandler(text: string): (reason: any) => void { if (DEBUG) { return error => { log(`${text} (${error})`); }; } else { return undefined; } } function activate(_activationSettings: SSS.ActivationSettings, isPageBlocked: boolean) { activationSettings = _activationSettings; // now register with events based on user settings if (activationSettings.popupLocation === SSS.PopupLocation.Cursor) { document.addEventListener("mousemove", onMouseUpdate); document.addEventListener("mouseenter", onMouseUpdate); } if (activationSettings.useEngineShortcutWithoutPopup) { document.documentElement.addEventListener("keydown", onKeyDown); } if (!isPageBlocked) { if (activationSettings.popupOpenBehaviour === SSS.PopupOpenBehaviour.Auto || activationSettings.popupOpenBehaviour === SSS.PopupOpenBehaviour.HoldAlt) { selectionchange.start(); document.addEventListener("customselectionchange", onSelectionChange); } else if (activationSettings.popupOpenBehaviour === SSS.PopupOpenBehaviour.MiddleMouse) { document.addEventListener("mousedown", onMouseDown); document.addEventListener("mouseup", onMouseUp); } } if (DEBUG) { log("content script activated, url: " + window.location.href.substr(0, 40)); } } function deactivate() { // unregister with all events document.removeEventListener("mousemove", onMouseUpdate); document.removeEventListener("mouseenter", onMouseUpdate); document.removeEventListener("mousedown", onMouseDown); document.removeEventListener("mouseup", onMouseUp); document.removeEventListener("customselectionchange", onSelectionChange); selectionchange.stop(); document.documentElement.removeEventListener("keydown", onKeyDown); document.documentElement.removeEventListener("mousedown", maybeHidePopup); window.removeEventListener("scroll", maybeHidePopup); // remove the popup from the page (other listeners in the popup are destroyed along with their objects) if (popup !== null) { document.documentElement.removeChild(popup); popup = null; } // also clear any previously saved settings activationSettings = null; settings = null; if (DEBUG) { log("content script deactivated"); } } function onSelectionChange(ev: selectionchange.CustomSelectionChangeEvent) { if (popup && popup.isReceiverOfEvent(ev.event)) return; if (activationSettings.popupOpenBehaviour === SSS.PopupOpenBehaviour.Auto && activationSettings.popupDelay > 0) { clearPopupShowTimeout(); if (saveCurrentSelection()) { popupShowTimeout = window.setTimeout(() => showPopupForSelection(ev, false), activationSettings.popupDelay); // use "window.setTimeout" to avoid problems with TS type definitions } } else { if (saveCurrentSelection()) { showPopupForSelection(ev, false); } } } // called whenever selection changes or when we want to force the popup to appear for the current selection function showPopupForSelection(ev: Event, isForced: boolean) { clearPopupShowTimeout(); if (settings !== null) { // if we have settings already, use them... tryShowPopup(ev, isForced); } else { // ...otherwise ask the background script for all needed settings, store them, and THEN try to show the popup acquireSettings(() => tryShowPopup(ev, isForced)); } } function acquireSettings(onSettingsAcquired: () => void) { browser.runtime.sendMessage(new GetPopupSettingsMessage()).then( popupSettings => { settings = popupSettings.settings; sssIcons = popupSettings.sssIcons; onSettingsAcquired(); }, getErrorHandler("Error sending getPopupSettings message from content script.") ); } function clearPopupShowTimeout() { if (popupShowTimeout !== null) { clearTimeout(popupShowTimeout); popupShowTimeout = null; } } function saveCurrentSelection() { const elem: Element = document.activeElement; if (elem instanceof HTMLTextAreaElement || (elem instanceof HTMLInputElement && elem.type !== "password")) { selection.isInInputField = true; // for editable fields, getting the selected text is different selection.unprocessedText = (elem as HTMLTextAreaElement).value.substring(elem.selectionStart, elem.selectionEnd); selection.element = elem; } else { selection.isInInputField = false; // get selection, but exit if there's no text selected after all const selectionObject = window.getSelection(); if (selectionObject === null) return false; let selectedText = selectionObject.toString(); // if selection.toString() is empty, try to get string from the ranges instead (this can happen!) if (selectedText.length === 0) { selectedText = ""; for (let i = 0; i < selectionObject.rangeCount; i++) { selectedText += selectionObject.getRangeAt(i).toString(); } } selection.unprocessedText = selectedText; selection.selection = selectionObject; } selection.unprocessedText = selection.unprocessedText.trim(); let text = selection.unprocessedText; text = text.replace(/[\r\n]+/g, " "); // replace newlines with spaces text = text.replace(/\s\s+/g, " "); // replace consecutive whitespaces selection.text = text; return selection.text.length > 0; } // shows the popup if the conditions are proper, according to settings function tryShowPopup(ev: Event, isForced: boolean) { // [TypeScript]: Usually we would check for the altKey only if "ev instanceof selectionchange.CustomSelectionChangeEvent", // but ev has an undefined class type in pages outside the options page, so it doesn't match. We use ev["altKey"]. if (settings.popupOpenBehaviour === SSS.PopupOpenBehaviour.HoldAlt && !ev["altKey"]) return; if (settings.popupOpenBehaviour === SSS.PopupOpenBehaviour.Auto) { if ((settings.minSelectedCharacters > 0 && selection.text.length < settings.minSelectedCharacters) || (settings.maxSelectedCharacters > 0 && selection.text.length > settings.maxSelectedCharacters)) { return; } } if (!isForced) { // If showing popup for editable fields is not allowed, check if selection is in an editable field. if (!settings.allowPopupOnEditableFields) { if (selection.isInInputField) return; // even if this is not an input field, don't show popup in contentEditable elements, such as Gmail's compose window if (isInContentEditableField(selection.selection.anchorNode)) return; } // If editable fields are allowed, they are still not allowed for keyboard selections else { if (!ev["isMouse"] && isInContentEditableField(selection.selection.anchorNode)) return; } } if (settings.autoCopyToClipboard === SSS.AutoCopyToClipboard.Always || (settings.autoCopyToClipboard === SSS.AutoCopyToClipboard.NonEditableOnly && !selection.isInInputField && !isInContentEditableField(selection.selection.anchorNode))) { if (DEBUG) { log("auto copied to clipboard: " + selection.text); } document.execCommand("copy"); } if (DEBUG) { log("showing popup, previous value was: " + popup); } if (popup === null) { popup = createPopup(settings); } if (settings.showSelectionTextField === true) { popup.setInputFieldText(selection.text); if (isForced) { // if forced by keyboard, focus the text field setTimeout(() => popup.setFocusOnInputFieldText(), 0); } } popup.show(); // call "show" first so that popup size calculations are correct in setPopupPosition popup.setPopupPosition(settings, selection, mousePositionX, mousePositionY); if (settings.popupAnimationDuration > 0) { popup.playAnimation(settings); } } function createPopup(settings: SSS.Settings): PopupCreator.SSSPopup { // only define new element if not already defined (can get here multiple times if settings are reloaded) if (!customElements.get("sss-popup")) { // temp class that locks in settings as arguments to SSSPopup class SSSPopupWithSettings extends PopupCreator.SSSPopup { constructor() { super(getSettings(), getIcons()); } } customElements.define("sss-popup", SSSPopupWithSettings); } const popup = document.createElement("sss-popup") as PopupCreator.SSSPopup; document.documentElement.appendChild(popup); // register popup events if (!settings.useEngineShortcutWithoutPopup) { // if we didn't register the keydown listener before, do it now document.documentElement.addEventListener("keydown", onKeyDown); } document.documentElement.addEventListener("mousedown", maybeHidePopup); // hide popup from a press down anywhere... popup.addEventListener("mousedown", ev => ev.stopPropagation()); // ...except on the popup itself if (settings.hidePopupOnPageScroll) { window.addEventListener("scroll", maybeHidePopup); } return popup; } function getSettings(): SSS.Settings { return settings; } function getIcons(): { [id: string] : SSS.SSSIconDefinition; } { return sssIcons; } function isInContentEditableField(node): boolean { // to find if this element is editable, we go up the hierarchy until an element that specifies "isContentEditable" (or the root) for (let elem = node; elem !== document; elem = elem.parentNode) { const concreteElem = elem as HTMLElement; if (concreteElem.isContentEditable === undefined) { continue; // check parent for value } return concreteElem.isContentEditable; } return false; } function isAnyEditableFieldFocused() { const elem: Element = document.activeElement; return elem instanceof HTMLTextAreaElement || (elem instanceof HTMLInputElement && elem.type !== "password") || isInContentEditableField(elem); } function getEngineWithShortcut(key) { // Look through the search engines to find if one them has a shortcut that matches the pressed key key = key.toUpperCase(); return settings.searchEngines.find(e => e.shortcut === key); } function onKeyDown(ev) { // Check if the user pressed a shortcut. // The popup must be visible, unless 'Always enable shortcuts' is checked. const isPopupVisible = popup !== null && popup.isShown(); if (!ev.altKey && !ev.ctrlKey && !ev.metaKey && !ev.shiftKey // modifiers are not supported right now && !isAnyEditableFieldFocused()) // shortcuts are disabled in editable fields { if ((isPopupVisible && ev.originalTarget.className !== "sss-input-field") // if using popup, make sure we're not inside the popup's text field || (activationSettings.useEngineShortcutWithoutPopup && saveCurrentSelection())) // if outside popup, ensure a selection exists, otherwise we crash later { if (settings !== null) { searchWithEngineUsingShortcut(ev.key); } else { acquireSettings(() => searchWithEngineUsingShortcut(ev.key)); } } } // The code below should only work if the popup is showing. if (!isPopupVisible) return; // Loop the icons using "Tab" if (ev.key === "Tab") { const firstIcon = popup.enginesContainer.firstChild as HTMLImageElement; const lastIcon = popup.enginesContainer.lastChild as HTMLImageElement; // Focus the first icon for the first time, as well as after the last one so as to keep looping them. if (document.activeElement.nodeName !== "SSS-POPUP" || ev.originalTarget === lastIcon) { firstIcon.focus(); ev.preventDefault(); return; } } // if pressing the enter key if (ev.keyCode == 13 && popup.isReceiverOfEvent(ev)) { let engine; let openingBehaviour; // if we're inside the popup's text field, grab the first user-defined engine and search using that if (ev.originalTarget.nodeName === "INPUT") { engine = settings.searchEngines.find(e => e.type !== SSS.SearchEngineType.SSS); openingBehaviour = SSS.OpenResultBehaviour.NewBgTab; // for now, using enter is the same as ctrl-clicking } else { // if cycling the icons using "tab", grab the focused icon const engineIndex = [...popup.enginesContainer.children].indexOf(ev.originalTarget); engine = settings.searchEngines[engineIndex]; openingBehaviour = settings.shortcutBehaviour; } const message = createSearchMessage(engine, settings); message.openingBehaviour = openingBehaviour; browser.runtime.sendMessage(message); } else { maybeHidePopup(ev); } } function searchWithEngineUsingShortcut(key: string) { const engine = getEngineWithShortcut(key); if (engine) { const message = createSearchMessage(engine, settings); message.openingBehaviour = settings.shortcutBehaviour; browser.runtime.sendMessage(message); } } function maybeHidePopup(ev?) { if (popup === null) return; if (ev) { if (ev.type === "keydown") { // these keys shouldn't hide the popup if (ev.keyCode == 16) return; // shift if (ev.keyCode == 17) return; // ctrl if (ev.keyCode == 18) return; // alt if (ev.keyCode == 224) return; // mac cmd (224 only on Firefox) if (ev.keyCode == 27) { // escape forces hide popup.hide(); return; } // if event is a keydown on the text field, don't hide if (popup.isReceiverOfEvent(ev)) return; // Pressing a shortcut key should be treated as a click to an icon. // So we should only hide the popup when the user presses a shortcut key if // hidePopupOnSearch is true. if (!settings.hidePopupOnSearch && getEngineWithShortcut(ev.key)) return; } // if we pressed with right mouse button and that isn't supposed to hide the popup, don't hide if (ev.button === 2 && settings && settings.hidePopupOnRightClick === false) return; } popup.hide(); } function onMouseUpdate(ev: MouseEvent) { mousePositionX = ev.pageX; mousePositionY = ev.pageY; } function onSearchEngineClick(ev: MouseEvent, engine: SSS.SearchEngine, settings: SSS.Settings) { // if using middle mouse and can't, early out so we don't hide popup if (ev.button === 1 && !canMiddleClickEngine) return; if (settings.hidePopupOnSearch) { // If we hide the popup *immediately* and this is a right click, // it will consequently be detected on whatever's behind the popup // and call the context menu, which we don't want. setTimeout(() => maybeHidePopup(), 0); } if (ev.button === 0 || ev.button === 1 || ev.button === 2) { const message: EngineClickMessage = createSearchMessage(engine, settings); if (ev[selectionchange.modifierKey]) { message.openingBehaviour = SSS.OpenResultBehaviour.NewBgTab; } else if (ev.button === 0) { message.openingBehaviour = settings.mouseLeftButtonBehaviour; } else if (ev.button === 1) { message.openingBehaviour = settings.mouseMiddleButtonBehaviour; } else { message.openingBehaviour = settings.mouseRightButtonBehaviour; } browser.runtime.sendMessage(message); } } function createSearchMessage(engine: SSS.SearchEngine, settings: SSS.Settings): EngineClickMessage { const message = new EngineClickMessage(); // Due to shortcuts, we can search without a popup, so we only get the input field contents if popup is not null. message.selection = popup !== null && settings.showSelectionTextField === true ? popup.getInputFieldText() : selection.text; message.engine = engine; if (window.location) { message.href = window.location.href; } return message; } function onMouseDown(ev: MouseEvent) { if (ev.button !== 1) return; const selection: Selection = window.getSelection(); // for selections inside editable elements const elem: Element = document.activeElement; if (elem instanceof HTMLTextAreaElement || (elem instanceof HTMLInputElement && elem.type !== "password")) { if (forceSelectionIfWithinRect(ev, elem.getBoundingClientRect())) { return false; } } // for normal text selections for (let i = 0; i < selection.rangeCount; ++i) { const range: Range = selection.getRangeAt(i); // get the text range const bounds: ClientRect | DOMRect = range.getBoundingClientRect(); if (bounds.width > 0 && bounds.height > 0 && forceSelectionIfWithinRect(ev, bounds)) { return false; } } } function onMouseUp(ev: MouseEvent) { if (ev.button === 1) { // return value to normal to allow clicking engines again with middle mouse canMiddleClickEngine = true; } } // if ev position is within the given rect plus margin, try to show popup for the selection function forceSelectionIfWithinRect(ev: MouseEvent, rect: ClientRect | DOMRect) { const margin = activationSettings.middleMouseSelectionClickMargin; if (ev.clientX > rect.left - margin && ev.clientX < rect.right + margin && ev.clientY > rect.top - margin && ev.clientY < rect.bottom + margin) { // We got it! Event shouldn't do anything else. ev.preventDefault(); ev.stopPropagation(); if (saveCurrentSelection()) { ev["isMouse"] = true; showPopupForSelection(ev, false); } // blocks same middle click from triggering popup on down and then a search on up (on an engine icon) canMiddleClickEngine = false; return true; } return false; } } namespace PopupCreator { export let onSearchEngineClick = null; export class SSSPopup extends HTMLElement { content: HTMLDivElement; inputField: HTMLInputElement; enginesContainer: HTMLDivElement; constructor(settings: SSS.Settings, sssIcons: { [id: string] : SSS.SSSIconDefinition; }) { super(); Object.setPrototypeOf(this, SSSPopup.prototype); // needed so that instanceof and casts work const shadowRoot = this.attachShadow({mode: "closed"}); const css = this.generateStylesheet(settings); var style = document.createElement("style"); style.appendChild(document.createTextNode(css)); shadowRoot.appendChild(style); // create popup parent (will contain all icons) this.content = document.createElement("div"); this.content.classList.add("sss-content"); shadowRoot.appendChild(this.content); if (settings.showSelectionTextField) { this.inputField = document.createElement("input"); this.inputField.type = "text"; this.inputField.classList.add("sss-input-field"); this.content.appendChild(this.inputField); } if (this.inputField && settings.selectionTextFieldLocation === SSS.SelectionTextFieldLocation.Top) { this.content.appendChild(this.inputField); } this.enginesContainer = document.createElement("div"); this.enginesContainer.classList.add("sss-engines"); this.content.appendChild(this.enginesContainer); if (this.inputField && settings.selectionTextFieldLocation === SSS.SelectionTextFieldLocation.Bottom) { this.content.appendChild(this.inputField); } this.createPopupContent(settings, sssIcons); } generateStylesheet(settings: SSS.Settings) { // Due to "all: initial !important", all inherited properties that are // defined afterwards will also need to use !important. // Inherited properties: https://stackoverflow.com/a/5612360/2162837 return ` :host { all: initial !important; } .sss-content { font-size: 0px !important; direction: ltr !important; position: absolute; z-index: 2147483647; user-select: none; -moz-user-select: none; box-shadow: rgba(0, 0, 0, 0.5) 0px 0px 3px; background-color: ${settings.popupBackgroundColor}; border-radius: ${settings.popupBorderRadius}px; padding: ${settings.popupPaddingY}px ${settings.popupPaddingX}px; text-align: center; ${this.generateStylesheet_Width(settings)} } .sss-content img { width: ${settings.popupItemSize}px; height: ${settings.popupItemSize}px; padding: ${3 + settings.popupItemVerticalPadding}px ${settings.popupItemPadding}px; border-radius: ${settings.popupItemBorderRadius}px; cursor: pointer; } .sss-content img:hover { ${this.generateStylesheet_IconHover(settings)} } .separator { ${this.generateStylesheet_Separator(settings)} } .sss-engines { ${this.generateStylesheet_TextAlign(settings)} } .sss-input-field { box-sizing: border-box; width: calc(100% - 8px); border: 1px solid #ccc; border-radius: ${settings.popupBorderRadius}px; padding: 4px 7px; margin: 4px 0px 2px 0px; } .sss-input-field:hover { border: 1px solid ${settings.popupHighlightColor}; } ${settings.useCustomPopupCSS === true ? settings.customPopupCSS : ""} `; } generateStylesheet_TextAlign(settings: SSS.Settings): string { let textAlign: string = "center"; if (!settings.useSingleRow) { switch (settings.iconAlignmentInGrid) { case SSS.IconAlignment.Left: textAlign = "left"; break; case SSS.IconAlignment.Right: textAlign = "right"; break; } } return `text-align: ${textAlign} !important;`; } generateStylesheet_Width(settings: SSS.Settings): string { let width: number; if (settings.useSingleRow) { // Calculate the final width of the popup based on the known widths and paddings of everything. // We need this so that if the popup is created too close to the borders of the page it still gets the right size. const nSeparators = settings.searchEngines.filter(e => e.type === SSS.SearchEngineType.SSS && (e as SSS.SearchEngine_SSS).id === "separator").length; const nPopupIcons: number = settings.searchEngines.length - nSeparators; width = nPopupIcons * (settings.popupItemSize + 2 * settings.popupItemPadding); width += nSeparators * (settings.popupItemSize * settings.popupSeparatorWidth / 100 + 2 * settings.popupItemPadding); } else { const nPopupIconsPerRow: number = Math.max(1, Math.min(settings.nPopupIconsPerRow, settings.searchEngines.length)); width = nPopupIconsPerRow * (settings.popupItemSize + 2 * settings.popupItemPadding); } return `width: ${width}px;`; } generateStylesheet_IconHover(settings: SSS.Settings): string { if (settings.popupItemHoverBehaviour === SSS.ItemHoverBehaviour.Highlight || settings.popupItemHoverBehaviour === SSS.ItemHoverBehaviour.HighlightAndMove) { let borderCompensation; if (settings.popupItemHoverBehaviour === SSS.ItemHoverBehaviour.HighlightAndMove) { const marginTopValue = Math.min(-3 - settings.popupItemVerticalPadding + 2, -2); // equal or less than -2 to counter the border's 2px borderCompensation = `margin-top: ${marginTopValue}px;`; } else { const paddingBottomValue = Math.max(3 + settings.popupItemVerticalPadding - 2, 0); // must be positive to counter the border's 2px borderCompensation = `padding-bottom: ${paddingBottomValue}px;`; } return ` border-bottom: 2px ${settings.popupHighlightColor} solid; border-radius: ${settings.popupItemBorderRadius == 0 ? 2 : settings.popupItemBorderRadius}px; ${borderCompensation} `; } else if (settings.popupItemHoverBehaviour === SSS.ItemHoverBehaviour.Scale) { // "backface-visibility: hidden" prevents blurriness return ` transform: scale(1.15); backface-visibility: hidden; `; } return ""; } generateStylesheet_Separator(settings: SSS.Settings): string { const separatorWidth = settings.popupItemSize * settings.popupSeparatorWidth / 100; const separatorMargin = (separatorWidth - settings.popupItemSize) / 2; return ` pointer-events: none !important; margin-left: ${separatorMargin}px; margin-right: ${separatorMargin}px; `; } createPopupContent(settings: SSS.Settings, sssIcons: { [id: string] : SSS.SSSIconDefinition; }) { // add each engine to the popup for (let i = 0; i < settings.searchEngines.length; i++) { const engine = settings.searchEngines[i]; let icon: HTMLImageElement; // special SSS icons with special functions if (engine.type === SSS.SearchEngineType.SSS) { const sssEngine = engine as SSS.SearchEngine_SSS; const sssIcon = sssIcons[sssEngine.id]; const iconImgSource = browser.extension.getURL(sssIcon.iconPath); const isInteractive = sssIcon.isInteractive !== false; // undefined or true means it's interactive icon = this.setupEngineIcon(sssEngine, iconImgSource, sssIcon.name, isInteractive, settings); if (sssEngine.id === "separator") { icon.classList.add("separator"); } } // "normal" custom search engines else { const userEngine = engine as SSS.SearchEngine_NonSSS; let iconImgSource: string; if (userEngine.iconUrl.startsWith("data:")) { iconImgSource = userEngine.iconUrl; // use "URL" directly, as it's pure image data } else { const cachedIcon = settings.searchEnginesCache[userEngine.iconUrl]; iconImgSource = cachedIcon ? cachedIcon : userEngine.iconUrl; // should have cached icon, but if not (for some reason) fall back to URL } icon = this.setupEngineIcon(userEngine, iconImgSource, userEngine.name, true, settings); } this.enginesContainer.appendChild(icon); } } setupEngineIcon(engine: SSS.SearchEngine, iconImgSource: string, iconTitle: string, isInteractive: boolean, settings: SSS.Settings): HTMLImageElement { const icon: HTMLImageElement = document.createElement("img"); icon.src = iconImgSource; icon.tabIndex = 0; // to allow cycling through the icons using "tab" // if icon responds to mouse interaction if (isInteractive) { icon.title = engine.shortcut ? `${iconTitle} (${engine.shortcut})` : iconTitle; // tooltip icon.addEventListener("mouseup", ev => onSearchEngineClick(ev, engine, settings)); // "mouse up" instead of "click" to support middle click // prevent context menu since icons have a right click behaviour icon.addEventListener("contextmenu", ev => { ev.preventDefault(); return false; }); } // prevents focus from changing to icon and breaking copy from input fields icon.addEventListener("mousedown", ev => ev.preventDefault()); // disable dragging popup images icon.ondragstart = _ => false; return icon; } setPopupPosition(settings: SSS.Settings, selection: ContentScript.SelectionData, mousePositionX: number, mousePositionY: number) { const bounds = this.content.getBoundingClientRect(); const width = bounds.width; const height = bounds.height; // position popup let positionLeft: number; let positionTop: number; // decide popup position based on settings if (settings.popupLocation === SSS.PopupLocation.Selection) { let rect; if (selection.isInInputField) { rect = selection.element.getBoundingClientRect(); } else { const range = selection.selection.getRangeAt(0); // get the text range rect = range.getBoundingClientRect(); } // lower right corner of selected text's "bounds" positionLeft = rect.right + window.pageXOffset; positionTop = rect.bottom + window.pageYOffset; } else if (settings.popupLocation === SSS.PopupLocation.Cursor) { // right above the mouse position positionLeft = mousePositionX; positionTop = mousePositionY - height - 10; // 10 is forced padding to avoid popup being too close to cursor } // center horizontally positionLeft -= width / 2; // apply user offsets from settings positionLeft += settings.popupOffsetX; positionTop -= settings.popupOffsetY; // invert sign because y is 0 at the top // don't const popup be outside of the viewport const margin: number = 5; // left/right checks if (positionLeft < margin + window.scrollX) { positionLeft = margin + window.scrollX; } else { const clientWidth = Math.max(document.body.clientWidth, document.documentElement.clientWidth); if (positionLeft + width + margin > clientWidth + window.scrollX) { positionLeft = clientWidth + window.scrollX - width - margin; } } // top/bottom checks if (positionTop < margin + window.scrollY) { positionTop = margin + window.scrollY; } else { const clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight); if (positionTop + height + margin > clientHeight + window.scrollY) { positionTop = clientHeight + window.scrollY - height - margin; } } // finally set the size and position values this.content.style.setProperty("left", positionLeft + "px"); this.content.style.setProperty("top", positionTop + "px"); } playAnimation(settings: SSS.Settings) { this.content.animate({ transform: ["scale(0.8)", "scale(1)"] } as PropertyIndexedKeyframes, settings.popupAnimationDuration); this.content.animate({ opacity: ["0", "1"] } as PropertyIndexedKeyframes, settings.popupAnimationDuration * 0.5); } isReceiverOfEvent(ev: Event) { return ev.target === this; } setFocusOnInputFieldText() { this.inputField.focus(); } setInputFieldText(text: string) { this.inputField.value = text; } getInputFieldText(): string { return this.inputField.value; } isShown(): boolean { return this.content.style.display === "inline-block"; } show() { this.content.style.setProperty("display", "inline-block"); } hide() { this.content.style.setProperty("display", "none"); } } }
the_stack
class GitGraphView { private gitRepos: GG.GitRepoSet; private gitBranches: ReadonlyArray<string> = []; private gitBranchHead: string | null = null; private gitConfig: GG.GitRepoConfig | null = null; private gitRemotes: ReadonlyArray<string> = []; private gitStashes: ReadonlyArray<GG.GitStash> = []; private gitTags: ReadonlyArray<string> = []; private commits: GG.GitCommit[] = []; private commitHead: string | null = null; private commitLookup: { [hash: string]: number } = {}; private onlyFollowFirstParent: boolean = false; private avatars: AvatarImageCollection = {}; private currentBranches: string[] | null = null; private currentRepo!: string; private currentRepoLoading: boolean = true; private currentRepoRefreshState: { inProgress: boolean; hard: boolean; loadRepoInfoRefreshId: number; loadCommitsRefreshId: number; repoInfoChanges: boolean; configChanges: boolean; requestingRepoInfo: boolean; requestingConfig: boolean; }; private loadViewTo: GG.LoadGitGraphViewTo = null; private readonly graph: Graph; private readonly config: Config; private moreCommitsAvailable: boolean = false; private expandedCommit: ExpandedCommit | null = null; private maxCommits: number; private scrollTop = 0; private renderedGitBranchHead: string | null = null; private lastScrollToStash: { time: number, hash: string | null } = { time: 0, hash: null }; private readonly findWidget: FindWidget; private readonly settingsWidget: SettingsWidget; private readonly repoDropdown: Dropdown; private readonly branchDropdown: Dropdown; private readonly viewElem: HTMLElement; private readonly controlsElem: HTMLElement; private readonly tableElem: HTMLElement; private readonly footerElem: HTMLElement; private readonly showRemoteBranchesElem: HTMLInputElement; private readonly refreshBtnElem: HTMLElement; private readonly scrollShadowElem: HTMLElement; constructor(viewElem: HTMLElement, prevState: WebViewState | null) { this.gitRepos = initialState.repos; this.config = initialState.config; this.maxCommits = this.config.initialLoadCommits; this.viewElem = viewElem; this.currentRepoRefreshState = { inProgress: false, hard: true, loadRepoInfoRefreshId: initialState.loadRepoInfoRefreshId, loadCommitsRefreshId: initialState.loadCommitsRefreshId, repoInfoChanges: false, configChanges: false, requestingRepoInfo: false, requestingConfig: false }; this.controlsElem = document.getElementById('controls')!; this.tableElem = document.getElementById('commitTable')!; this.footerElem = document.getElementById('footer')!; this.scrollShadowElem = <HTMLInputElement>document.getElementById('scrollShadow')!; viewElem.focus(); this.graph = new Graph('commitGraph', viewElem, this.config.graph, this.config.mute); this.repoDropdown = new Dropdown('repoDropdown', true, false, 'Repos', (values) => { this.loadRepo(values[0]); }); this.branchDropdown = new Dropdown('branchDropdown', false, true, 'Branches', (values) => { this.currentBranches = values; this.maxCommits = this.config.initialLoadCommits; this.saveState(); this.clearCommits(); this.requestLoadRepoInfoAndCommits(true, true); }); this.showRemoteBranchesElem = <HTMLInputElement>document.getElementById('showRemoteBranchesCheckbox')!; this.showRemoteBranchesElem.addEventListener('change', () => { this.saveRepoStateValue(this.currentRepo, 'showRemoteBranchesV2', this.showRemoteBranchesElem.checked ? GG.BooleanOverride.Enabled : GG.BooleanOverride.Disabled); this.refresh(true); }); this.refreshBtnElem = document.getElementById('refreshBtn')!; this.refreshBtnElem.addEventListener('click', () => { if (!this.refreshBtnElem.classList.contains(CLASS_REFRESHING)) { this.refresh(true, true); } }); this.renderRefreshButton(); this.findWidget = new FindWidget(this); this.settingsWidget = new SettingsWidget(this); alterClass(document.body, CLASS_BRANCH_LABELS_ALIGNED_TO_GRAPH, this.config.referenceLabels.branchLabelsAlignedToGraph); alterClass(document.body, CLASS_TAG_LABELS_RIGHT_ALIGNED, this.config.referenceLabels.tagLabelsOnRight); this.observeWindowSizeChanges(); this.observeWebviewStyleChanges(); this.observeViewScroll(); this.observeKeyboardEvents(); this.observeUrls(); this.observeTableEvents(); if (prevState && !prevState.currentRepoLoading && typeof this.gitRepos[prevState.currentRepo] !== 'undefined') { this.currentRepo = prevState.currentRepo; this.currentBranches = prevState.currentBranches; this.maxCommits = prevState.maxCommits; this.expandedCommit = prevState.expandedCommit; this.avatars = prevState.avatars; this.gitConfig = prevState.gitConfig; this.loadRepoInfo(prevState.gitBranches, prevState.gitBranchHead, prevState.gitRemotes, prevState.gitStashes, true); this.loadCommits(prevState.commits, prevState.commitHead, prevState.gitTags, prevState.moreCommitsAvailable, prevState.onlyFollowFirstParent); this.findWidget.restoreState(prevState.findWidget); this.settingsWidget.restoreState(prevState.settingsWidget); this.showRemoteBranchesElem.checked = getShowRemoteBranches(this.gitRepos[prevState.currentRepo].showRemoteBranchesV2); } let loadViewTo = initialState.loadViewTo; if (loadViewTo === null && prevState && prevState.currentRepoLoading && typeof prevState.currentRepo !== 'undefined') { loadViewTo = { repo: prevState.currentRepo }; } if (!this.loadRepos(this.gitRepos, initialState.lastActiveRepo, loadViewTo)) { if (prevState) { this.scrollTop = prevState.scrollTop; this.viewElem.scroll(0, this.scrollTop); } this.requestLoadRepoInfoAndCommits(false, false); } const fetchBtn = document.getElementById('fetchBtn')!, findBtn = document.getElementById('findBtn')!, settingsBtn = document.getElementById('settingsBtn')!, terminalBtn = document.getElementById('terminalBtn')!; fetchBtn.title = 'Fetch' + (this.config.fetchAndPrune ? ' & Prune' : '') + ' from Remote(s)'; fetchBtn.innerHTML = SVG_ICONS.download; fetchBtn.addEventListener('click', () => this.fetchFromRemotesAction()); findBtn.innerHTML = SVG_ICONS.search; findBtn.addEventListener('click', () => this.findWidget.show(true)); settingsBtn.innerHTML = SVG_ICONS.gear; settingsBtn.addEventListener('click', () => this.settingsWidget.show(this.currentRepo)); terminalBtn.innerHTML = SVG_ICONS.terminal; terminalBtn.addEventListener('click', () => { runAction({ command: 'openTerminal', repo: this.currentRepo, name: this.gitRepos[this.currentRepo].name || getRepoName(this.currentRepo) }, 'Opening Terminal'); }); } /* Loading Data */ public loadRepos(repos: GG.GitRepoSet, lastActiveRepo: string | null, loadViewTo: GG.LoadGitGraphViewTo) { this.gitRepos = repos; this.saveState(); let newRepo: string; if (loadViewTo !== null && this.currentRepo !== loadViewTo.repo && typeof repos[loadViewTo.repo] !== 'undefined') { newRepo = loadViewTo.repo; } else if (typeof repos[this.currentRepo] === 'undefined') { newRepo = lastActiveRepo !== null && typeof repos[lastActiveRepo] !== 'undefined' ? lastActiveRepo : getSortedRepositoryPaths(repos, this.config.repoDropdownOrder)[0]; } else { newRepo = this.currentRepo; } alterClass(this.controlsElem, 'singleRepo', Object.keys(repos).length === 1); this.renderRepoDropdownOptions(newRepo); if (loadViewTo !== null) { if (loadViewTo.repo === newRepo) { this.loadViewTo = loadViewTo; } else { this.loadViewTo = null; showErrorMessage('Unable to load the Git Graph View for the repository "' + loadViewTo.repo + '". It is not currently included in Git Graph.'); } } else { this.loadViewTo = null; } if (this.currentRepo !== newRepo) { this.loadRepo(newRepo); return true; } else { this.finaliseRepoLoad(false); return false; } } private loadRepo(repo: string) { this.currentRepo = repo; this.currentRepoLoading = true; this.showRemoteBranchesElem.checked = getShowRemoteBranches(this.gitRepos[this.currentRepo].showRemoteBranchesV2); this.maxCommits = this.config.initialLoadCommits; this.gitConfig = null; this.gitRemotes = []; this.gitStashes = []; this.gitTags = []; this.currentBranches = null; this.renderFetchButton(); this.closeCommitDetails(false); this.settingsWidget.close(); this.saveState(); this.refresh(true); } private loadRepoInfo(branchOptions: ReadonlyArray<string>, branchHead: string | null, remotes: ReadonlyArray<string>, stashes: ReadonlyArray<GG.GitStash>, isRepo: boolean) { // Changes to this.gitStashes are reflected as changes to the commits when loadCommits is run this.gitStashes = stashes; if (!isRepo || (!this.currentRepoRefreshState.hard && arraysStrictlyEqual(this.gitBranches, branchOptions) && this.gitBranchHead === branchHead && arraysStrictlyEqual(this.gitRemotes, remotes))) { this.saveState(); this.finaliseLoadRepoInfo(false, isRepo); return; } // Changes to these properties must be indicated as a repository info change this.gitBranches = branchOptions; this.gitBranchHead = branchHead; this.gitRemotes = remotes; // Update the state of the fetch button this.renderFetchButton(); // Configure current branches if (this.currentBranches !== null && !(this.currentBranches.length === 1 && this.currentBranches[0] === SHOW_ALL_BRANCHES)) { // Filter any branches that are currently selected, but no longer exist const globPatterns = this.config.customBranchGlobPatterns.map((pattern) => pattern.glob); this.currentBranches = this.currentBranches.filter((branch) => this.gitBranches.includes(branch) || globPatterns.includes(branch) ); } if (this.currentBranches === null || this.currentBranches.length === 0) { // No branches are currently selected const onRepoLoadShowCheckedOutBranch = getOnRepoLoadShowCheckedOutBranch(this.gitRepos[this.currentRepo].onRepoLoadShowCheckedOutBranch); const onRepoLoadShowSpecificBranches = getOnRepoLoadShowSpecificBranches(this.gitRepos[this.currentRepo].onRepoLoadShowSpecificBranches); this.currentBranches = []; if (onRepoLoadShowSpecificBranches.length > 0) { // Show specific branches if they exist in the repository const globPatterns = this.config.customBranchGlobPatterns.map((pattern) => pattern.glob); this.currentBranches.push(...onRepoLoadShowSpecificBranches.filter((branch) => this.gitBranches.includes(branch) || globPatterns.includes(branch) )); } if (onRepoLoadShowCheckedOutBranch && this.gitBranchHead !== null && !this.currentBranches.includes(this.gitBranchHead)) { // Show the checked-out branch, and it hasn't already been added as a specific branch this.currentBranches.push(this.gitBranchHead); } if (this.currentBranches.length === 0) { this.currentBranches.push(SHOW_ALL_BRANCHES); } } this.saveState(); // Set up branch dropdown options this.branchDropdown.setOptions(this.getBranchOptions(true), this.currentBranches); // Remove hidden remotes that no longer exist let hiddenRemotes = this.gitRepos[this.currentRepo].hideRemotes; let hideRemotes = hiddenRemotes.filter((hiddenRemote) => remotes.includes(hiddenRemote)); if (hiddenRemotes.length !== hideRemotes.length) { this.saveRepoStateValue(this.currentRepo, 'hideRemotes', hideRemotes); } this.finaliseLoadRepoInfo(true, isRepo); } private finaliseLoadRepoInfo(repoInfoChanges: boolean, isRepo: boolean) { const refreshState = this.currentRepoRefreshState; if (refreshState.inProgress) { if (isRepo) { refreshState.repoInfoChanges = refreshState.repoInfoChanges || repoInfoChanges; refreshState.requestingRepoInfo = false; this.requestLoadCommits(); } else { dialog.closeActionRunning(); refreshState.inProgress = false; this.loadViewTo = null; this.renderRefreshButton(); sendMessage({ command: 'loadRepos', check: true }); } } } private loadCommits(commits: GG.GitCommit[], commitHead: string | null, tags: ReadonlyArray<string>, moreAvailable: boolean, onlyFollowFirstParent: boolean) { // This list of tags is just used to provide additional information in the dialogs. Tag information included in commits is used for all other purposes (e.g. rendering, context menus) const tagsChanged = !arraysStrictlyEqual(this.gitTags, tags); this.gitTags = tags; if (!this.currentRepoLoading && !this.currentRepoRefreshState.hard && this.moreCommitsAvailable === moreAvailable && this.onlyFollowFirstParent === onlyFollowFirstParent && this.commitHead === commitHead && commits.length > 0 && arraysEqual(this.commits, commits, (a, b) => a.hash === b.hash && arraysStrictlyEqual(a.heads, b.heads) && arraysEqual(a.tags, b.tags, (a, b) => a.name === b.name && a.annotated === b.annotated) && arraysEqual(a.remotes, b.remotes, (a, b) => a.name === b.name && a.remote === b.remote) && arraysStrictlyEqual(a.parents, b.parents) && ((a.stash === null && b.stash === null) || (a.stash !== null && b.stash !== null && a.stash.selector === b.stash.selector)) ) && this.renderedGitBranchHead === this.gitBranchHead) { if (this.commits[0].hash === UNCOMMITTED) { this.commits[0] = commits[0]; this.saveState(); this.renderUncommittedChanges(); if (this.expandedCommit !== null && this.expandedCommit.commitElem !== null) { if (this.expandedCommit.compareWithHash === null) { // Commit Details View is open if (this.expandedCommit.commitHash === UNCOMMITTED) { this.requestCommitDetails(this.expandedCommit.commitHash, true); } } else { // Commit Comparison is open if (this.expandedCommit.compareWithElem !== null && (this.expandedCommit.commitHash === UNCOMMITTED || this.expandedCommit.compareWithHash === UNCOMMITTED)) { this.requestCommitComparison(this.expandedCommit.commitHash, this.expandedCommit.compareWithHash, true); } } } } else if (tagsChanged) { this.saveState(); } this.finaliseLoadCommits(); return; } const currentRepoLoading = this.currentRepoLoading; this.currentRepoLoading = false; this.moreCommitsAvailable = moreAvailable; this.onlyFollowFirstParent = onlyFollowFirstParent; this.commits = commits; this.commitHead = commitHead; this.commitLookup = {}; let i: number, expandedCommitVisible = false, expandedCompareWithCommitVisible = false, avatarsNeeded: { [email: string]: string[] } = {}, commit; for (i = 0; i < this.commits.length; i++) { commit = this.commits[i]; this.commitLookup[commit.hash] = i; if (this.expandedCommit !== null) { if (this.expandedCommit.commitHash === commit.hash) { expandedCommitVisible = true; } else if (this.expandedCommit.compareWithHash === commit.hash) { expandedCompareWithCommitVisible = true; } } if (this.config.fetchAvatars && typeof this.avatars[commit.email] !== 'string' && commit.email !== '') { if (typeof avatarsNeeded[commit.email] === 'undefined') { avatarsNeeded[commit.email] = [commit.hash]; } else { avatarsNeeded[commit.email].push(commit.hash); } } } if (this.expandedCommit !== null && (!expandedCommitVisible || (this.expandedCommit.compareWithHash !== null && !expandedCompareWithCommitVisible))) { this.closeCommitDetails(false); } this.saveState(); this.graph.loadCommits(this.commits, this.commitHead, this.commitLookup, this.onlyFollowFirstParent); this.render(); if (currentRepoLoading && this.config.onRepoLoad.scrollToHead && this.commitHead !== null) { this.scrollToCommit(this.commitHead, true); } this.finaliseLoadCommits(); this.requestAvatars(avatarsNeeded); } private finaliseLoadCommits() { const refreshState = this.currentRepoRefreshState; if (refreshState.inProgress) { dialog.closeActionRunning(); if (dialog.isTargetDynamicSource()) { if (refreshState.repoInfoChanges) { dialog.close(); } else { dialog.refresh(this.getCommits()); } } if (contextMenu.isTargetDynamicSource()) { if (refreshState.repoInfoChanges) { contextMenu.close(); } else { contextMenu.refresh(this.getCommits()); } } refreshState.inProgress = false; this.renderRefreshButton(); } this.finaliseRepoLoad(true); } private finaliseRepoLoad(didLoadRepoData: boolean) { if (this.loadViewTo !== null && this.currentRepo === this.loadViewTo.repo) { if (this.loadViewTo.commitDetails && (this.expandedCommit === null || this.expandedCommit.commitHash !== this.loadViewTo.commitDetails.commitHash || this.expandedCommit.compareWithHash !== this.loadViewTo.commitDetails.compareWithHash)) { const commitIndex = this.getCommitId(this.loadViewTo.commitDetails.commitHash); const compareWithIndex = this.loadViewTo.commitDetails.compareWithHash !== null ? this.getCommitId(this.loadViewTo.commitDetails.compareWithHash) : null; const commitElems = getCommitElems(); const commitElem = findCommitElemWithId(commitElems, commitIndex); const compareWithElem = findCommitElemWithId(commitElems, compareWithIndex); if (commitElem !== null && (this.loadViewTo.commitDetails.compareWithHash === null || compareWithElem !== null)) { if (compareWithElem !== null) { this.loadCommitComparison(commitElem, compareWithElem); } else { this.loadCommitDetails(commitElem); } } else { showErrorMessage('Unable to resume Code Review, it could not be found in the latest ' + this.maxCommits + ' commits that were loaded in this repository.'); } } else if (this.loadViewTo.runCommandOnLoad) { switch (this.loadViewTo.runCommandOnLoad) { case 'fetch': this.fetchFromRemotesAction(); break; } } } this.loadViewTo = null; if (this.gitConfig === null || (didLoadRepoData && this.currentRepoRefreshState.configChanges)) { this.requestLoadConfig(); } } private clearCommits() { closeDialogAndContextMenu(); this.moreCommitsAvailable = false; this.commits = []; this.commitHead = null; this.commitLookup = {}; this.renderedGitBranchHead = null; this.closeCommitDetails(false); this.saveState(); this.graph.loadCommits(this.commits, this.commitHead, this.commitLookup, this.onlyFollowFirstParent); this.tableElem.innerHTML = ''; this.footerElem.innerHTML = ''; this.renderGraph(); this.findWidget.refresh(); } public processLoadRepoInfoResponse(msg: GG.ResponseLoadRepoInfo) { if (msg.error === null) { const refreshState = this.currentRepoRefreshState; if (refreshState.inProgress && refreshState.loadRepoInfoRefreshId === msg.refreshId) { this.loadRepoInfo(msg.branches, msg.head, msg.remotes, msg.stashes, msg.isRepo); } } else { this.displayLoadDataError('Unable to load Repository Info', msg.error); } } public processLoadCommitsResponse(msg: GG.ResponseLoadCommits) { if (msg.error === null) { const refreshState = this.currentRepoRefreshState; if (refreshState.inProgress && refreshState.loadCommitsRefreshId === msg.refreshId) { this.loadCommits(msg.commits, msg.head, msg.tags, msg.moreCommitsAvailable, msg.onlyFollowFirstParent); } } else { const error = this.gitBranches.length === 0 && msg.error.indexOf('bad revision \'HEAD\'') > -1 ? 'There are no commits in this repository.' : msg.error; this.displayLoadDataError('Unable to load Commits', error); } } public processLoadConfig(msg: GG.ResponseLoadConfig) { this.currentRepoRefreshState.requestingConfig = false; if (msg.config !== null && this.currentRepo === msg.repo) { this.gitConfig = msg.config; this.saveState(); this.renderCdvExternalDiffBtn(); } this.settingsWidget.refresh(); } private displayLoadDataError(message: string, reason: string) { this.clearCommits(); this.currentRepoRefreshState.inProgress = false; this.loadViewTo = null; this.renderRefreshButton(); dialog.showError(message, reason, 'Retry', () => { this.refresh(true); }); } public loadAvatar(email: string, image: string) { this.avatars[email] = image; this.saveState(); let avatarsElems = <HTMLCollectionOf<HTMLElement>>document.getElementsByClassName('avatar'), escapedEmail = escapeHtml(email); for (let i = 0; i < avatarsElems.length; i++) { if (avatarsElems[i].dataset.email === escapedEmail) { avatarsElems[i].innerHTML = '<img class="avatarImg" src="' + image + '">'; } } } /* Getters */ public getBranches(): ReadonlyArray<string> { return this.gitBranches; } public getBranchOptions(includeShowAll?: boolean): ReadonlyArray<DialogSelectInputOption> { const options: DialogSelectInputOption[] = []; if (includeShowAll) { options.push({ name: 'Show All', value: SHOW_ALL_BRANCHES }); } for (let i = 0; i < this.config.customBranchGlobPatterns.length; i++) { options.push({ name: 'Glob: ' + this.config.customBranchGlobPatterns[i].name, value: this.config.customBranchGlobPatterns[i].glob }); } for (let i = 0; i < this.gitBranches.length; i++) { options.push({ name: this.gitBranches[i].indexOf('remotes/') === 0 ? this.gitBranches[i].substring(8) : this.gitBranches[i], value: this.gitBranches[i] }); } return options; } public getCommitId(hash: string) { return typeof this.commitLookup[hash] === 'number' ? this.commitLookup[hash] : null; } private getCommitOfElem(elem: HTMLElement) { let id = parseInt(elem.dataset.id!); return id < this.commits.length ? this.commits[id] : null; } public getCommits(): ReadonlyArray<GG.GitCommit> { return this.commits; } private getPushRemote(branch: string | null = null) { const possibleRemotes = []; if (this.gitConfig !== null) { if (branch !== null && typeof this.gitConfig.branches[branch] !== 'undefined') { possibleRemotes.push(this.gitConfig.branches[branch].pushRemote, this.gitConfig.branches[branch].remote); } possibleRemotes.push(this.gitConfig.pushDefault); } possibleRemotes.push('origin'); return possibleRemotes.find((remote) => remote !== null && this.gitRemotes.includes(remote)) || this.gitRemotes[0]; } public getRepoConfig(): Readonly<GG.GitRepoConfig> | null { return this.gitConfig; } public getRepoState(repo: string): Readonly<GG.GitRepoState> | null { return typeof this.gitRepos[repo] !== 'undefined' ? this.gitRepos[repo] : null; } public isConfigLoading(): boolean { return this.currentRepoRefreshState.requestingConfig; } /* Refresh */ public refresh(hard: boolean, configChanges: boolean = false) { if (hard) { this.clearCommits(); } this.requestLoadRepoInfoAndCommits(hard, false, configChanges); } /* Requests */ private requestLoadRepoInfo() { const repoState = this.gitRepos[this.currentRepo]; sendMessage({ command: 'loadRepoInfo', repo: this.currentRepo, refreshId: ++this.currentRepoRefreshState.loadRepoInfoRefreshId, showRemoteBranches: getShowRemoteBranches(repoState.showRemoteBranchesV2), showStashes: getShowStashes(repoState.showStashes), hideRemotes: repoState.hideRemotes }); } private requestLoadCommits() { const repoState = this.gitRepos[this.currentRepo]; sendMessage({ command: 'loadCommits', repo: this.currentRepo, refreshId: ++this.currentRepoRefreshState.loadCommitsRefreshId, branches: this.currentBranches === null || (this.currentBranches.length === 1 && this.currentBranches[0] === SHOW_ALL_BRANCHES) ? null : this.currentBranches, maxCommits: this.maxCommits, showTags: getShowTags(repoState.showTags), showRemoteBranches: getShowRemoteBranches(repoState.showRemoteBranchesV2), includeCommitsMentionedByReflogs: getIncludeCommitsMentionedByReflogs(repoState.includeCommitsMentionedByReflogs), onlyFollowFirstParent: getOnlyFollowFirstParent(repoState.onlyFollowFirstParent), commitOrdering: getCommitOrdering(repoState.commitOrdering), remotes: this.gitRemotes, hideRemotes: repoState.hideRemotes, stashes: this.gitStashes }); } private requestLoadRepoInfoAndCommits(hard: boolean, skipRepoInfo: boolean, configChanges: boolean = false) { const refreshState = this.currentRepoRefreshState; if (refreshState.inProgress) { refreshState.hard = refreshState.hard || hard; refreshState.configChanges = refreshState.configChanges || configChanges; if (!skipRepoInfo) { // This request will trigger a loadCommit request after the loadRepoInfo request has completed. // Invalidate any previous commit requests in progress. refreshState.loadCommitsRefreshId++; } } else { refreshState.hard = hard; refreshState.inProgress = true; refreshState.repoInfoChanges = false; refreshState.configChanges = configChanges; refreshState.requestingRepoInfo = false; } this.renderRefreshButton(); if (this.commits.length === 0) { this.tableElem.innerHTML = '<h2 id="loadingHeader">' + SVG_ICONS.loading + 'Loading ...</h2>'; } if (skipRepoInfo) { if (!refreshState.requestingRepoInfo) { this.requestLoadCommits(); } } else { refreshState.requestingRepoInfo = true; this.requestLoadRepoInfo(); } } public requestLoadConfig() { this.currentRepoRefreshState.requestingConfig = true; sendMessage({ command: 'loadConfig', repo: this.currentRepo, remotes: this.gitRemotes }); this.settingsWidget.refresh(); } public requestCommitDetails(hash: string, refresh: boolean) { let commit = this.commits[this.commitLookup[hash]]; sendMessage({ command: 'commitDetails', repo: this.currentRepo, commitHash: hash, hasParents: commit.parents.length > 0, stash: commit.stash, avatarEmail: this.config.fetchAvatars && hash !== UNCOMMITTED ? commit.email : null, refresh: refresh }); } public requestCommitComparison(hash: string, compareWithHash: string, refresh: boolean) { let commitOrder = this.getCommitOrder(hash, compareWithHash); sendMessage({ command: 'compareCommits', repo: this.currentRepo, commitHash: hash, compareWithHash: compareWithHash, fromHash: commitOrder.from, toHash: commitOrder.to, refresh: refresh }); } private requestAvatars(avatars: { [email: string]: string[] }) { let emails = Object.keys(avatars), remote = this.gitRemotes.length > 0 ? this.gitRemotes.includes('origin') ? 'origin' : this.gitRemotes[0] : null; for (let i = 0; i < emails.length; i++) { sendMessage({ command: 'fetchAvatar', repo: this.currentRepo, remote: remote, email: emails[i], commits: avatars[emails[i]] }); } } /* State */ public saveState() { let expandedCommit; if (this.expandedCommit !== null) { expandedCommit = Object.assign({}, this.expandedCommit); expandedCommit.commitElem = null; expandedCommit.compareWithElem = null; expandedCommit.contextMenuOpen = { summary: false, fileView: -1 }; } else { expandedCommit = null; } VSCODE_API.setState({ currentRepo: this.currentRepo, currentRepoLoading: this.currentRepoLoading, gitRepos: this.gitRepos, gitBranches: this.gitBranches, gitBranchHead: this.gitBranchHead, gitConfig: this.gitConfig, gitRemotes: this.gitRemotes, gitStashes: this.gitStashes, gitTags: this.gitTags, commits: this.commits, commitHead: this.commitHead, avatars: this.avatars, currentBranches: this.currentBranches, moreCommitsAvailable: this.moreCommitsAvailable, maxCommits: this.maxCommits, onlyFollowFirstParent: this.onlyFollowFirstParent, expandedCommit: expandedCommit, scrollTop: this.scrollTop, findWidget: this.findWidget.getState(), settingsWidget: this.settingsWidget.getState() }); } public saveRepoState() { sendMessage({ command: 'setRepoState', repo: this.currentRepo, state: this.gitRepos[this.currentRepo] }); } private saveColumnWidths(columnWidths: GG.ColumnWidth[]) { this.gitRepos[this.currentRepo].columnWidths = [columnWidths[0], columnWidths[2], columnWidths[3], columnWidths[4]]; this.saveRepoState(); } private saveExpandedCommitLoading(index: number, commitHash: string, commitElem: HTMLElement, compareWithHash: string | null, compareWithElem: HTMLElement | null) { this.expandedCommit = { index: index, commitHash: commitHash, commitElem: commitElem, compareWithHash: compareWithHash, compareWithElem: compareWithElem, commitDetails: null, fileChanges: null, fileTree: null, avatar: null, codeReview: null, lastViewedFile: null, loading: true, scrollTop: { summary: 0, fileView: 0 }, contextMenuOpen: { summary: false, fileView: -1 } }; this.saveState(); } public saveRepoStateValue<K extends keyof GG.GitRepoState>(repo: string, key: K, value: GG.GitRepoState[K]) { if (repo === this.currentRepo) { this.gitRepos[this.currentRepo][key] = value; this.saveRepoState(); } } /* Renderers */ private render() { this.renderTable(); this.renderGraph(); } private renderGraph() { if (typeof this.currentRepo === 'undefined') { // Only render the graph if a repo is loaded (or a repo is currently being loaded) return; } const colHeadersElem = document.getElementById('tableColHeaders'); const cdvHeight = this.gitRepos[this.currentRepo].cdvHeight; const headerHeight = colHeadersElem !== null ? colHeadersElem.clientHeight + 1 : 0; const expandedCommit = this.isCdvDocked() ? null : this.expandedCommit; const expandedCommitElem = expandedCommit !== null ? document.getElementById('cdv') : null; // Update the graphs grid dimensions this.config.graph.grid.expandY = expandedCommitElem !== null ? expandedCommitElem.getBoundingClientRect().height : cdvHeight; this.config.graph.grid.y = this.commits.length > 0 && this.tableElem.children.length > 0 ? (this.tableElem.children[0].clientHeight - headerHeight - (expandedCommit !== null ? cdvHeight : 0)) / this.commits.length : this.config.graph.grid.y; this.config.graph.grid.offsetY = headerHeight + this.config.graph.grid.y / 2; this.graph.render(expandedCommit); } private renderTable() { const colVisibility = this.getColumnVisibility(); const currentHash = this.commits.length > 0 && this.commits[0].hash === UNCOMMITTED ? UNCOMMITTED : this.commitHead; const vertexColours = this.graph.getVertexColours(); const widthsAtVertices = this.config.referenceLabels.branchLabelsAlignedToGraph ? this.graph.getWidthsAtVertices() : []; const mutedCommits = this.graph.getMutedCommits(currentHash); const textFormatter = new TextFormatter(this.commits, this.gitRepos[this.currentRepo].issueLinkingConfig, { emoji: true, issueLinking: true, markdown: this.config.markdown }); let html = '<tr id="tableColHeaders"><th id="tableHeaderGraphCol" class="tableColHeader" data-col="0">Graph</th><th class="tableColHeader" data-col="1">Description</th>' + (colVisibility.date ? '<th class="tableColHeader dateCol" data-col="2">Date</th>' : '') + (colVisibility.author ? '<th class="tableColHeader authorCol" data-col="3">Author</th>' : '') + (colVisibility.commit ? '<th class="tableColHeader" data-col="4">Commit</th>' : '') + '</tr>'; for (let i = 0; i < this.commits.length; i++) { let commit = this.commits[i]; let message = '<span class="text">' + textFormatter.format(commit.message) + '</span>'; let date = formatShortDate(commit.date); let branchLabels = getBranchLabels(commit.heads, commit.remotes); let refBranches = '', refTags = '', j, k, refName, remoteName, refActive, refHtml, branchCheckedOutAtCommit: string | null = null; for (j = 0; j < branchLabels.heads.length; j++) { refName = escapeHtml(branchLabels.heads[j].name); refActive = branchLabels.heads[j].name === this.gitBranchHead; refHtml = '<span class="gitRef head' + (refActive ? ' active' : '') + '" data-name="' + refName + '">' + SVG_ICONS.branch + '<span class="gitRefName" data-fullref="' + refName + '">' + refName + '</span>'; for (k = 0; k < branchLabels.heads[j].remotes.length; k++) { remoteName = escapeHtml(branchLabels.heads[j].remotes[k]); refHtml += '<span class="gitRefHeadRemote" data-remote="' + remoteName + '" data-fullref="' + escapeHtml(branchLabels.heads[j].remotes[k] + '/' + branchLabels.heads[j].name) + '">' + remoteName + '</span>'; } refHtml += '</span>'; refBranches = refActive ? refHtml + refBranches : refBranches + refHtml; if (refActive) branchCheckedOutAtCommit = this.gitBranchHead; } for (j = 0; j < branchLabels.remotes.length; j++) { refName = escapeHtml(branchLabels.remotes[j].name); refBranches += '<span class="gitRef remote" data-name="' + refName + '" data-remote="' + (branchLabels.remotes[j].remote !== null ? escapeHtml(branchLabels.remotes[j].remote!) : '') + '">' + SVG_ICONS.branch + '<span class="gitRefName" data-fullref="' + refName + '">' + refName + '</span></span>'; } for (j = 0; j < commit.tags.length; j++) { refName = escapeHtml(commit.tags[j].name); refTags += '<span class="gitRef tag" data-name="' + refName + '" data-tagtype="' + (commit.tags[j].annotated ? 'annotated' : 'lightweight') + '">' + SVG_ICONS.tag + '<span class="gitRefName" data-fullref="' + refName + '">' + refName + '</span></span>'; } if (commit.stash !== null) { refName = escapeHtml(commit.stash.selector); refBranches = '<span class="gitRef stash" data-name="' + refName + '">' + SVG_ICONS.stash + '<span class="gitRefName" data-fullref="' + refName + '">' + escapeHtml(commit.stash.selector.substring(5)) + '</span></span>' + refBranches; } const commitDot = commit.hash === this.commitHead ? '<span class="commitHeadDot" title="' + (branchCheckedOutAtCommit !== null ? 'The branch ' + escapeHtml('"' + branchCheckedOutAtCommit + '"') + ' is currently checked out at this commit' : 'This commit is currently checked out' ) + '."></span>' : ''; html += '<tr class="commit' + (commit.hash === currentHash ? ' current' : '') + (mutedCommits[i] ? ' mute' : '') + '"' + (commit.hash !== UNCOMMITTED ? '' : ' id="uncommittedChanges"') + ' data-id="' + i + '" data-color="' + vertexColours[i] + '">' + (this.config.referenceLabels.branchLabelsAlignedToGraph ? '<td>' + (refBranches !== '' ? '<span style="margin-left:' + (widthsAtVertices[i] - 4) + 'px"' + refBranches.substring(5) : '') + '</td><td><span class="description">' + commitDot : '<td></td><td><span class="description">' + commitDot + refBranches) + (this.config.referenceLabels.tagLabelsOnRight ? message + refTags : refTags + message) + '</span></td>' + (colVisibility.date ? '<td class="dateCol text" title="' + date.title + '">' + date.formatted + '</td>' : '') + (colVisibility.author ? '<td class="authorCol text" title="' + escapeHtml(commit.author + ' <' + commit.email + '>') + '">' + (this.config.fetchAvatars ? '<span class="avatar" data-email="' + escapeHtml(commit.email) + '">' + (typeof this.avatars[commit.email] === 'string' ? '<img class="avatarImg" src="' + this.avatars[commit.email] + '">' : '') + '</span>' : '') + escapeHtml(commit.author) + '</td>' : '') + (colVisibility.commit ? '<td class="text" title="' + escapeHtml(commit.hash) + '">' + abbrevCommit(commit.hash) + '</td>' : '') + '</tr>'; } this.tableElem.innerHTML = '<table>' + html + '</table>'; this.footerElem.innerHTML = this.moreCommitsAvailable ? '<div id="loadMoreCommitsBtn" class="roundedBtn">Load More Commits</div>' : ''; this.makeTableResizable(); this.findWidget.refresh(); this.renderedGitBranchHead = this.gitBranchHead; if (this.moreCommitsAvailable) { document.getElementById('loadMoreCommitsBtn')!.addEventListener('click', () => { this.loadMoreCommits(); }); } if (this.expandedCommit !== null) { const expandedCommit = this.expandedCommit, elems = getCommitElems(); const commitElem = findCommitElemWithId(elems, this.getCommitId(expandedCommit.commitHash)); const compareWithElem = expandedCommit.compareWithHash !== null ? findCommitElemWithId(elems, this.getCommitId(expandedCommit.compareWithHash)) : null; if (commitElem === null || (expandedCommit.compareWithHash !== null && compareWithElem === null)) { this.closeCommitDetails(false); this.saveState(); } else { expandedCommit.index = parseInt(commitElem.dataset.id!); expandedCommit.commitElem = commitElem; expandedCommit.compareWithElem = compareWithElem; this.saveState(); if (expandedCommit.compareWithHash === null) { // Commit Details View is open if (!expandedCommit.loading && expandedCommit.commitDetails !== null && expandedCommit.fileTree !== null) { this.showCommitDetails(expandedCommit.commitDetails, expandedCommit.fileTree, expandedCommit.avatar, expandedCommit.codeReview, expandedCommit.lastViewedFile, true); if (expandedCommit.commitHash === UNCOMMITTED) { this.requestCommitDetails(expandedCommit.commitHash, true); } } else { this.loadCommitDetails(commitElem); } } else { // Commit Comparison is open if (!expandedCommit.loading && expandedCommit.fileChanges !== null && expandedCommit.fileTree !== null) { this.showCommitComparison(expandedCommit.commitHash, expandedCommit.compareWithHash, expandedCommit.fileChanges, expandedCommit.fileTree, expandedCommit.codeReview, expandedCommit.lastViewedFile, true); if (expandedCommit.commitHash === UNCOMMITTED || expandedCommit.compareWithHash === UNCOMMITTED) { this.requestCommitComparison(expandedCommit.commitHash, expandedCommit.compareWithHash, true); } } else { this.loadCommitComparison(commitElem, compareWithElem!); } } } } } private renderUncommittedChanges() { const colVisibility = this.getColumnVisibility(), date = formatShortDate(this.commits[0].date); document.getElementById('uncommittedChanges')!.innerHTML = '<td></td><td><b>' + escapeHtml(this.commits[0].message) + '</b></td>' + (colVisibility.date ? '<td class="dateCol text" title="' + date.title + '">' + date.formatted + '</td>' : '') + (colVisibility.author ? '<td class="authorCol text" title="* <>">*</td>' : '') + (colVisibility.commit ? '<td class="text" title="*">*</td>' : ''); } private renderFetchButton() { alterClass(this.controlsElem, CLASS_FETCH_SUPPORTED, this.gitRemotes.length > 0); } public renderRefreshButton() { const enabled = !this.currentRepoRefreshState.inProgress; this.refreshBtnElem.title = enabled ? 'Refresh' : 'Refreshing'; this.refreshBtnElem.innerHTML = enabled ? SVG_ICONS.refresh : SVG_ICONS.loading; alterClass(this.refreshBtnElem, CLASS_REFRESHING, !enabled); } public renderTagDetails(tagName: string, commitHash: string, details: GG.GitTagDetails) { const textFormatter = new TextFormatter(this.commits, this.gitRepos[this.currentRepo].issueLinkingConfig, { commits: true, emoji: true, issueLinking: true, markdown: this.config.markdown, multiline: true, urls: true }); dialog.showMessage( 'Tag <b><i>' + escapeHtml(tagName) + '</i></b><br><span class="messageContent">' + '<b>Object: </b>' + escapeHtml(details.hash) + '<br>' + '<b>Commit: </b>' + escapeHtml(commitHash) + '<br>' + '<b>Tagger: </b>' + escapeHtml(details.taggerName) + ' &lt;<a class="' + CLASS_EXTERNAL_URL + '" href="mailto:' + escapeHtml(details.taggerEmail) + '" tabindex="-1">' + escapeHtml(details.taggerEmail) + '</a>&gt;' + (details.signature !== null ? generateSignatureHtml(details.signature) : '') + '<br>' + '<b>Date: </b>' + formatLongDate(details.taggerDate) + '<br><br>' + textFormatter.format(details.message) + '</span>' ); } public renderRepoDropdownOptions(repo?: string) { this.repoDropdown.setOptions(getRepoDropdownOptions(this.gitRepos), [repo || this.currentRepo]); } /* Context Menu Generation */ private getBranchContextMenuActions(target: DialogTarget & RefTarget): ContextMenuActions { const refName = target.ref, visibility = this.config.contextMenuActionsVisibility.branch; const isSelectedInBranchesDropdown = this.branchDropdown.isSelected(refName); return [[ { title: 'Checkout Branch', visible: visibility.checkout && this.gitBranchHead !== refName, onClick: () => this.checkoutBranchAction(refName, null, null, target) }, { title: 'Rename Branch' + ELLIPSIS, visible: visibility.rename, onClick: () => { dialog.showRefInput('Enter the new name for branch <b><i>' + escapeHtml(refName) + '</i></b>:', refName, 'Rename Branch', (newName) => { runAction({ command: 'renameBranch', repo: this.currentRepo, oldName: refName, newName: newName }, 'Renaming Branch'); }, target); } }, { title: 'Delete Branch' + ELLIPSIS, visible: visibility.delete && this.gitBranchHead !== refName, onClick: () => { let remotesWithBranch = this.gitRemotes.filter(remote => this.gitBranches.includes('remotes/' + remote + '/' + refName)); let inputs: DialogInput[] = [{ type: DialogInputType.Checkbox, name: 'Force Delete', value: this.config.dialogDefaults.deleteBranch.forceDelete }]; if (remotesWithBranch.length > 0) { inputs.push({ type: DialogInputType.Checkbox, name: 'Delete this branch on the remote' + (this.gitRemotes.length > 1 ? 's' : ''), value: false, info: 'This branch is on the remote' + (remotesWithBranch.length > 1 ? 's: ' : ' ') + formatCommaSeparatedList(remotesWithBranch.map((remote) => '"' + remote + '"')) }); } dialog.showForm('Are you sure you want to delete the branch <b><i>' + escapeHtml(refName) + '</i></b>?', inputs, 'Yes, delete', (values) => { runAction({ command: 'deleteBranch', repo: this.currentRepo, branchName: refName, forceDelete: <boolean>values[0], deleteOnRemotes: remotesWithBranch.length > 0 && <boolean>values[1] ? remotesWithBranch : [] }, 'Deleting Branch'); }, target); } }, { title: 'Merge into current branch' + ELLIPSIS, visible: visibility.merge && this.gitBranchHead !== refName, onClick: () => this.mergeAction(refName, refName, GG.MergeActionOn.Branch, target) }, { title: 'Rebase current branch on Branch' + ELLIPSIS, visible: visibility.rebase && this.gitBranchHead !== refName, onClick: () => this.rebaseAction(refName, refName, GG.RebaseActionOn.Branch, target) }, { title: 'Push Branch' + ELLIPSIS, visible: visibility.push && this.gitRemotes.length > 0, onClick: () => { const multipleRemotes = this.gitRemotes.length > 1; const inputs: DialogInput[] = [ { type: DialogInputType.Checkbox, name: 'Set Upstream', value: true }, { type: DialogInputType.Radio, name: 'Push Mode', options: [ { name: 'Normal', value: GG.GitPushBranchMode.Normal }, { name: 'Force With Lease', value: GG.GitPushBranchMode.ForceWithLease }, { name: 'Force', value: GG.GitPushBranchMode.Force } ], default: GG.GitPushBranchMode.Normal } ]; if (multipleRemotes) { inputs.unshift({ type: DialogInputType.Select, name: 'Push to Remote(s)', defaults: [this.getPushRemote(refName)], options: this.gitRemotes.map((remote) => ({ name: remote, value: remote })), multiple: true }); } dialog.showForm('Are you sure you want to push the branch <b><i>' + escapeHtml(refName) + '</i></b>' + (multipleRemotes ? '' : ' to the remote <b><i>' + escapeHtml(this.gitRemotes[0]) + '</i></b>') + '?', inputs, 'Yes, push', (values) => { const remotes = multipleRemotes ? <string[]>values.shift() : [this.gitRemotes[0]]; const setUpstream = <boolean>values[0]; runAction({ command: 'pushBranch', repo: this.currentRepo, branchName: refName, remotes: remotes, setUpstream: setUpstream, mode: <GG.GitPushBranchMode>values[1], willUpdateBranchConfig: setUpstream && remotes.length > 0 && (this.gitConfig === null || typeof this.gitConfig.branches[refName] === 'undefined' || this.gitConfig.branches[refName].remote !== remotes[remotes.length - 1]) }, 'Pushing Branch'); }, target); } } ], [ this.getViewIssueAction(refName, visibility.viewIssue, target), { title: 'Create Pull Request' + ELLIPSIS, visible: visibility.createPullRequest && this.gitRepos[this.currentRepo].pullRequestConfig !== null, onClick: () => { const config = this.gitRepos[this.currentRepo].pullRequestConfig; if (config === null) return; dialog.showCheckbox('Are you sure you want to create a Pull Request for branch <b><i>' + escapeHtml(refName) + '</i></b>?', 'Push branch before creating the Pull Request', true, 'Yes, create Pull Request', (push) => { runAction({ command: 'createPullRequest', repo: this.currentRepo, config: config, sourceRemote: config.sourceRemote, sourceOwner: config.sourceOwner, sourceRepo: config.sourceRepo, sourceBranch: refName, push: push }, 'Creating Pull Request'); }, target); } } ], [ { title: 'Create Archive', visible: visibility.createArchive, onClick: () => { runAction({ command: 'createArchive', repo: this.currentRepo, ref: refName }, 'Creating Archive'); } }, { title: 'Select in Branches Dropdown', visible: visibility.selectInBranchesDropdown && !isSelectedInBranchesDropdown, onClick: () => this.branchDropdown.selectOption(refName) }, { title: 'Unselect in Branches Dropdown', visible: visibility.unselectInBranchesDropdown && isSelectedInBranchesDropdown, onClick: () => this.branchDropdown.unselectOption(refName) } ], [ { title: 'Copy Branch Name to Clipboard', visible: visibility.copyName, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Branch Name', data: refName }); } } ]]; } private getCommitContextMenuActions(target: DialogTarget & CommitTarget): ContextMenuActions { const hash = target.hash, visibility = this.config.contextMenuActionsVisibility.commit; const commit = this.commits[this.commitLookup[hash]]; return [[ { title: 'Add Tag' + ELLIPSIS, visible: visibility.addTag, onClick: () => this.addTagAction(hash, '', this.config.dialogDefaults.addTag.type, '', null, target) }, { title: 'Create Branch' + ELLIPSIS, visible: visibility.createBranch, onClick: () => this.createBranchAction(hash, '', this.config.dialogDefaults.createBranch.checkout, target) } ], [ { title: 'Checkout' + (globalState.alwaysAcceptCheckoutCommit ? '' : ELLIPSIS), visible: visibility.checkout, onClick: () => { const checkoutCommit = () => runAction({ command: 'checkoutCommit', repo: this.currentRepo, commitHash: hash }, 'Checking out Commit'); if (globalState.alwaysAcceptCheckoutCommit) { checkoutCommit(); } else { dialog.showCheckbox('Are you sure you want to checkout commit <b><i>' + abbrevCommit(hash) + '</i></b>? This will result in a \'detached HEAD\' state.', 'Always Accept', false, 'Yes, checkout', (alwaysAccept) => { if (alwaysAccept) { updateGlobalViewState('alwaysAcceptCheckoutCommit', true); } checkoutCommit(); }, target); } } }, { title: 'Cherry Pick' + ELLIPSIS, visible: visibility.cherrypick, onClick: () => { const isMerge = commit.parents.length > 1; let inputs: DialogInput[] = []; if (isMerge) { let options = commit.parents.map((hash, index) => ({ name: abbrevCommit(hash) + (typeof this.commitLookup[hash] === 'number' ? ': ' + this.commits[this.commitLookup[hash]].message : ''), value: (index + 1).toString() })); inputs.push({ type: DialogInputType.Select, name: 'Parent Hash', options: options, default: '1', info: 'Choose the parent hash on the main branch, to cherry pick the commit relative to.' }); } inputs.push({ type: DialogInputType.Checkbox, name: 'Record Origin', value: this.config.dialogDefaults.cherryPick.recordOrigin, info: 'Record that this commit was the origin of the cherry pick by appending a line to the original commit message that states "(cherry picked from commit ...​)".' }, { type: DialogInputType.Checkbox, name: 'No Commit', value: this.config.dialogDefaults.cherryPick.noCommit, info: 'Cherry picked changes will be staged but not committed, so that you can select and commit specific parts of this commit.' }); dialog.showForm('Are you sure you want to cherry pick commit <b><i>' + abbrevCommit(hash) + '</i></b>?', inputs, 'Yes, cherry pick', (values) => { let parentIndex = isMerge ? parseInt(<string>values.shift()) : 0; runAction({ command: 'cherrypickCommit', repo: this.currentRepo, commitHash: hash, parentIndex: parentIndex, recordOrigin: <boolean>values[0], noCommit: <boolean>values[1] }, 'Cherry picking Commit'); }, target); } }, { title: 'Revert' + ELLIPSIS, visible: visibility.revert, onClick: () => { if (commit.parents.length > 1) { let options = commit.parents.map((hash, index) => ({ name: abbrevCommit(hash) + (typeof this.commitLookup[hash] === 'number' ? ': ' + this.commits[this.commitLookup[hash]].message : ''), value: (index + 1).toString() })); dialog.showSelect('Are you sure you want to revert merge commit <b><i>' + abbrevCommit(hash) + '</i></b>? Choose the parent hash on the main branch, to revert the commit relative to:', '1', options, 'Yes, revert', (parentIndex) => { runAction({ command: 'revertCommit', repo: this.currentRepo, commitHash: hash, parentIndex: parseInt(parentIndex) }, 'Reverting Commit'); }, target); } else { dialog.showConfirmation('Are you sure you want to revert commit <b><i>' + abbrevCommit(hash) + '</i></b>?', 'Yes, revert', () => { runAction({ command: 'revertCommit', repo: this.currentRepo, commitHash: hash, parentIndex: 0 }, 'Reverting Commit'); }, target); } } }, { title: 'Drop' + ELLIPSIS, visible: visibility.drop && this.graph.dropCommitPossible(this.commitLookup[hash]), onClick: () => { dialog.showConfirmation('Are you sure you want to permanently drop commit <b><i>' + abbrevCommit(hash) + '</i></b>?' + (this.onlyFollowFirstParent ? '<br/><i>Note: By enabling "Only follow the first parent of commits", some commits may have been hidden from the Git Graph View that could affect the outcome of performing this action.</i>' : ''), 'Yes, drop', () => { runAction({ command: 'dropCommit', repo: this.currentRepo, commitHash: hash }, 'Dropping Commit'); }, target); } } ], [ { title: 'Merge into current branch' + ELLIPSIS, visible: visibility.merge, onClick: () => this.mergeAction(hash, abbrevCommit(hash), GG.MergeActionOn.Commit, target) }, { title: 'Rebase current branch on this Commit' + ELLIPSIS, visible: visibility.rebase, onClick: () => this.rebaseAction(hash, abbrevCommit(hash), GG.RebaseActionOn.Commit, target) }, { title: 'Reset current branch to this Commit' + ELLIPSIS, visible: visibility.reset, onClick: () => { dialog.showSelect('Are you sure you want to reset ' + (this.gitBranchHead !== null ? '<b><i>' + escapeHtml(this.gitBranchHead) + '</i></b> (the current branch)' : 'the current branch') + ' to commit <b><i>' + abbrevCommit(hash) + '</i></b>?', this.config.dialogDefaults.resetCommit.mode, [ { name: 'Soft - Keep all changes, but reset head', value: GG.GitResetMode.Soft }, { name: 'Mixed - Keep working tree, but reset index', value: GG.GitResetMode.Mixed }, { name: 'Hard - Discard all changes', value: GG.GitResetMode.Hard } ], 'Yes, reset', (mode) => { runAction({ command: 'resetToCommit', repo: this.currentRepo, commit: hash, resetMode: <GG.GitResetMode>mode }, 'Resetting to Commit'); }, target); } } ], [ { title: 'Copy Commit Hash to Clipboard', visible: visibility.copyHash, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Commit Hash', data: hash }); } }, { title: 'Copy Commit Subject to Clipboard', visible: visibility.copySubject, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Commit Subject', data: commit.message }); } } ]]; } private getRemoteBranchContextMenuActions(remote: string, target: DialogTarget & RefTarget): ContextMenuActions { const refName = target.ref, visibility = this.config.contextMenuActionsVisibility.remoteBranch; const branchName = remote !== '' ? refName.substring(remote.length + 1) : ''; const prefixedRefName = 'remotes/' + refName; const isSelectedInBranchesDropdown = this.branchDropdown.isSelected(prefixedRefName); return [[ { title: 'Checkout Branch' + ELLIPSIS, visible: visibility.checkout, onClick: () => this.checkoutBranchAction(refName, remote, null, target) }, { title: 'Delete Remote Branch' + ELLIPSIS, visible: visibility.delete && remote !== '', onClick: () => { dialog.showConfirmation('Are you sure you want to delete the remote branch <b><i>' + escapeHtml(refName) + '</i></b>?', 'Yes, delete', () => { runAction({ command: 'deleteRemoteBranch', repo: this.currentRepo, branchName: branchName, remote: remote }, 'Deleting Remote Branch'); }, target); } }, { title: 'Fetch into local branch' + ELLIPSIS, visible: visibility.fetch && remote !== '' && this.gitBranches.includes(branchName) && this.gitBranchHead !== branchName, onClick: () => { dialog.showForm('Are you sure you want to fetch the remote branch <b><i>' + escapeHtml(refName) + '</i></b> into the local branch <b><i>' + escapeHtml(branchName) + '</i></b>?', [{ type: DialogInputType.Checkbox, name: 'Force Fetch', value: this.config.dialogDefaults.fetchIntoLocalBranch.forceFetch, info: 'Force the local branch to be reset to this remote branch.' }], 'Yes, fetch', (values) => { runAction({ command: 'fetchIntoLocalBranch', repo: this.currentRepo, remote: remote, remoteBranch: branchName, localBranch: branchName, force: <boolean>values[0] }, 'Fetching Branch'); }, target); } }, { title: 'Merge into current branch' + ELLIPSIS, visible: visibility.merge, onClick: () => this.mergeAction(refName, refName, GG.MergeActionOn.RemoteTrackingBranch, target) }, { title: 'Pull into current branch' + ELLIPSIS, visible: visibility.pull && remote !== '', onClick: () => { dialog.showForm('Are you sure you want to pull the remote branch <b><i>' + escapeHtml(refName) + '</i></b> into ' + (this.gitBranchHead !== null ? '<b><i>' + escapeHtml(this.gitBranchHead) + '</i></b> (the current branch)' : 'the current branch') + '? If a merge is required:', [ { type: DialogInputType.Checkbox, name: 'Create a new commit even if fast-forward is possible', value: this.config.dialogDefaults.pullBranch.noFastForward }, { type: DialogInputType.Checkbox, name: 'Squash Commits', value: this.config.dialogDefaults.pullBranch.squash, info: 'Create a single commit on the current branch whose effect is the same as merging this remote branch.' } ], 'Yes, pull', (values) => { runAction({ command: 'pullBranch', repo: this.currentRepo, branchName: branchName, remote: remote, createNewCommit: <boolean>values[0], squash: <boolean>values[1] }, 'Pulling Branch'); }, target); } } ], [ this.getViewIssueAction(refName, visibility.viewIssue, target), { title: 'Create Pull Request', visible: visibility.createPullRequest && this.gitRepos[this.currentRepo].pullRequestConfig !== null && branchName !== 'HEAD' && (this.gitRepos[this.currentRepo].pullRequestConfig!.sourceRemote === remote || this.gitRepos[this.currentRepo].pullRequestConfig!.destRemote === remote), onClick: () => { const config = this.gitRepos[this.currentRepo].pullRequestConfig; if (config === null) return; const isDestRemote = config.destRemote === remote; runAction({ command: 'createPullRequest', repo: this.currentRepo, config: config, sourceRemote: isDestRemote ? config.destRemote! : config.sourceRemote, sourceOwner: isDestRemote ? config.destOwner : config.sourceOwner, sourceRepo: isDestRemote ? config.destRepo : config.sourceRepo, sourceBranch: branchName, push: false }, 'Creating Pull Request'); } } ], [ { title: 'Create Archive', visible: visibility.createArchive, onClick: () => { runAction({ command: 'createArchive', repo: this.currentRepo, ref: refName }, 'Creating Archive'); } }, { title: 'Select in Branches Dropdown', visible: visibility.selectInBranchesDropdown && !isSelectedInBranchesDropdown, onClick: () => this.branchDropdown.selectOption(prefixedRefName) }, { title: 'Unselect in Branches Dropdown', visible: visibility.unselectInBranchesDropdown && isSelectedInBranchesDropdown, onClick: () => this.branchDropdown.unselectOption(prefixedRefName) } ], [ { title: 'Copy Branch Name to Clipboard', visible: visibility.copyName, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Branch Name', data: refName }); } } ]]; } private getStashContextMenuActions(target: DialogTarget & RefTarget): ContextMenuActions { const hash = target.hash, selector = target.ref, visibility = this.config.contextMenuActionsVisibility.stash; return [[ { title: 'Apply Stash' + ELLIPSIS, visible: visibility.apply, onClick: () => { dialog.showForm('Are you sure you want to apply the stash <b><i>' + escapeHtml(selector.substring(5)) + '</i></b>?', [{ type: DialogInputType.Checkbox, name: 'Reinstate Index', value: this.config.dialogDefaults.applyStash.reinstateIndex, info: 'Attempt to reinstate the indexed changes, in addition to the working tree\'s changes.' }], 'Yes, apply stash', (values) => { runAction({ command: 'applyStash', repo: this.currentRepo, selector: selector, reinstateIndex: <boolean>values[0] }, 'Applying Stash'); }, target); } }, { title: 'Create Branch from Stash' + ELLIPSIS, visible: visibility.createBranch, onClick: () => { dialog.showRefInput('Create a branch from stash <b><i>' + escapeHtml(selector.substring(5)) + '</i></b> with the name:', '', 'Create Branch', (branchName) => { runAction({ command: 'branchFromStash', repo: this.currentRepo, selector: selector, branchName: branchName }, 'Creating Branch'); }, target); } }, { title: 'Pop Stash' + ELLIPSIS, visible: visibility.pop, onClick: () => { dialog.showForm('Are you sure you want to pop the stash <b><i>' + escapeHtml(selector.substring(5)) + '</i></b>?', [{ type: DialogInputType.Checkbox, name: 'Reinstate Index', value: this.config.dialogDefaults.popStash.reinstateIndex, info: 'Attempt to reinstate the indexed changes, in addition to the working tree\'s changes.' }], 'Yes, pop stash', (values) => { runAction({ command: 'popStash', repo: this.currentRepo, selector: selector, reinstateIndex: <boolean>values[0] }, 'Popping Stash'); }, target); } }, { title: 'Drop Stash' + ELLIPSIS, visible: visibility.drop, onClick: () => { dialog.showConfirmation('Are you sure you want to drop the stash <b><i>' + escapeHtml(selector.substring(5)) + '</i></b>?', 'Yes, drop', () => { runAction({ command: 'dropStash', repo: this.currentRepo, selector: selector }, 'Dropping Stash'); }, target); } } ], [ { title: 'Copy Stash Name to Clipboard', visible: visibility.copyName, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Stash Name', data: selector }); } }, { title: 'Copy Stash Hash to Clipboard', visible: visibility.copyHash, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Stash Hash', data: hash }); } } ]]; } private getTagContextMenuActions(isAnnotated: boolean, target: DialogTarget & RefTarget): ContextMenuActions { const hash = target.hash, tagName = target.ref, visibility = this.config.contextMenuActionsVisibility.tag; return [[ { title: 'View Details', visible: visibility.viewDetails && isAnnotated, onClick: () => { runAction({ command: 'tagDetails', repo: this.currentRepo, tagName: tagName, commitHash: hash }, 'Retrieving Tag Details'); } }, { title: 'Delete Tag' + ELLIPSIS, visible: visibility.delete, onClick: () => { let message = 'Are you sure you want to delete the tag <b><i>' + escapeHtml(tagName) + '</i></b>?'; if (this.gitRemotes.length > 1) { let options = [{ name: 'Don\'t delete on any remote', value: '-1' }]; this.gitRemotes.forEach((remote, i) => options.push({ name: remote, value: i.toString() })); dialog.showSelect(message + '<br>Do you also want to delete the tag on a remote:', '-1', options, 'Yes, delete', remoteIndex => { this.deleteTagAction(tagName, remoteIndex !== '-1' ? this.gitRemotes[parseInt(remoteIndex)] : null); }, target); } else if (this.gitRemotes.length === 1) { dialog.showCheckbox(message, 'Also delete on remote', false, 'Yes, delete', deleteOnRemote => { this.deleteTagAction(tagName, deleteOnRemote ? this.gitRemotes[0] : null); }, target); } else { dialog.showConfirmation(message, 'Yes, delete', () => { this.deleteTagAction(tagName, null); }, target); } } }, { title: 'Push Tag' + ELLIPSIS, visible: visibility.push && this.gitRemotes.length > 0, onClick: () => { const runPushTagAction = (remotes: string[]) => { runAction({ command: 'pushTag', repo: this.currentRepo, tagName: tagName, remotes: remotes, commitHash: hash, skipRemoteCheck: globalState.pushTagSkipRemoteCheck }, 'Pushing Tag'); }; if (this.gitRemotes.length === 1) { dialog.showConfirmation('Are you sure you want to push the tag <b><i>' + escapeHtml(tagName) + '</i></b> to the remote <b><i>' + escapeHtml(this.gitRemotes[0]) + '</i></b>?', 'Yes, push', () => { runPushTagAction([this.gitRemotes[0]]); }, target); } else if (this.gitRemotes.length > 1) { const defaults = [this.getPushRemote()]; const options = this.gitRemotes.map((remote) => ({ name: remote, value: remote })); dialog.showMultiSelect('Are you sure you want to push the tag <b><i>' + escapeHtml(tagName) + '</i></b>? Select the remote(s) to push the tag to:', defaults, options, 'Yes, push', (remotes) => { runPushTagAction(remotes); }, target); } } } ], [ { title: 'Create Archive', visible: visibility.createArchive, onClick: () => { runAction({ command: 'createArchive', repo: this.currentRepo, ref: tagName }, 'Creating Archive'); } }, { title: 'Copy Tag Name to Clipboard', visible: visibility.copyName, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'Tag Name', data: tagName }); } } ]]; } private getUncommittedChangesContextMenuActions(target: DialogTarget & CommitTarget): ContextMenuActions { let visibility = this.config.contextMenuActionsVisibility.uncommittedChanges; return [[ { title: 'Stash uncommitted changes' + ELLIPSIS, visible: visibility.stash, onClick: () => { dialog.showForm('Are you sure you want to stash the <b>uncommitted changes</b>?', [ { type: DialogInputType.Text, name: 'Message', default: '', placeholder: 'Optional' }, { type: DialogInputType.Checkbox, name: 'Include Untracked', value: this.config.dialogDefaults.stashUncommittedChanges.includeUntracked, info: 'Include all untracked files in the stash, and then clean them from the working directory.' } ], 'Yes, stash', (values) => { runAction({ command: 'pushStash', repo: this.currentRepo, message: <string>values[0], includeUntracked: <boolean>values[1] }, 'Stashing uncommitted changes'); }, target); } } ], [ { title: 'Reset uncommitted changes' + ELLIPSIS, visible: visibility.reset, onClick: () => { dialog.showSelect('Are you sure you want to reset the <b>uncommitted changes</b> to <b>HEAD</b>?', this.config.dialogDefaults.resetUncommitted.mode, [ { name: 'Mixed - Keep working tree, but reset index', value: GG.GitResetMode.Mixed }, { name: 'Hard - Discard all changes', value: GG.GitResetMode.Hard } ], 'Yes, reset', (mode) => { runAction({ command: 'resetToCommit', repo: this.currentRepo, commit: 'HEAD', resetMode: <GG.GitResetMode>mode }, 'Resetting uncommitted changes'); }, target); } }, { title: 'Clean untracked files' + ELLIPSIS, visible: visibility.clean, onClick: () => { dialog.showCheckbox('Are you sure you want to clean all untracked files?', 'Clean untracked directories', true, 'Yes, clean', directories => { runAction({ command: 'cleanUntrackedFiles', repo: this.currentRepo, directories: directories }, 'Cleaning untracked files'); }, target); } } ], [ { title: 'Open Source Control View', visible: visibility.openSourceControlView, onClick: () => { sendMessage({ command: 'viewScm' }); } } ]]; } private getViewIssueAction(refName: string, visible: boolean, target: DialogTarget & RefTarget): ContextMenuAction { const issueLinks: { url: string, displayText: string }[] = []; let issueLinking: IssueLinking | null, match: RegExpExecArray | null; if (visible && (issueLinking = parseIssueLinkingConfig(this.gitRepos[this.currentRepo].issueLinkingConfig)) !== null) { issueLinking.regexp.lastIndex = 0; while (match = issueLinking.regexp.exec(refName)) { if (match[0].length === 0) break; issueLinks.push({ url: generateIssueLinkFromMatch(match, issueLinking), displayText: match[0] }); } } return { title: 'View Issue' + (issueLinks.length > 1 ? ELLIPSIS : ''), visible: issueLinks.length > 0, onClick: () => { if (issueLinks.length > 1) { dialog.showSelect('Select which issue you want to view for this branch:', '0', issueLinks.map((issueLink, i) => ({ name: issueLink.displayText, value: i.toString() })), 'View Issue', (value) => { sendMessage({ command: 'openExternalUrl', url: issueLinks[parseInt(value)].url }); }, target); } else if (issueLinks.length === 1) { sendMessage({ command: 'openExternalUrl', url: issueLinks[0].url }); } } }; } /* Actions */ private addTagAction(hash: string, initialName: string, initialType: GG.TagType, initialMessage: string, initialPushToRemote: string | null, target: DialogTarget & CommitTarget, isInitialLoad: boolean = true) { let mostRecentTagsIndex = -1; for (let i = 0; i < this.commits.length; i++) { if (this.commits[i].tags.length > 0 && (mostRecentTagsIndex === -1 || this.commits[i].date > this.commits[mostRecentTagsIndex].date)) { mostRecentTagsIndex = i; } } const mostRecentTags = mostRecentTagsIndex > -1 ? this.commits[mostRecentTagsIndex].tags.map((tag) => '"' + tag.name + '"') : []; const inputs: DialogInput[] = [ { type: DialogInputType.TextRef, name: 'Name', default: initialName, info: mostRecentTags.length > 0 ? 'The most recent tag' + (mostRecentTags.length > 1 ? 's' : '') + ' in the loaded commits ' + (mostRecentTags.length > 1 ? 'are' : 'is') + ' ' + formatCommaSeparatedList(mostRecentTags) + '.' : undefined }, { type: DialogInputType.Select, name: 'Type', default: initialType === GG.TagType.Annotated ? 'annotated' : 'lightweight', options: [{ name: 'Annotated', value: 'annotated' }, { name: 'Lightweight', value: 'lightweight' }] }, { type: DialogInputType.Text, name: 'Message', default: initialMessage, placeholder: 'Optional', info: 'A message can only be added to an annotated tag.' } ]; if (this.gitRemotes.length > 1) { const options = [{ name: 'Don\'t push', value: '-1' }]; this.gitRemotes.forEach((remote, i) => options.push({ name: remote, value: i.toString() })); const defaultOption = initialPushToRemote !== null ? this.gitRemotes.indexOf(initialPushToRemote) : isInitialLoad && this.config.dialogDefaults.addTag.pushToRemote ? this.gitRemotes.indexOf(this.getPushRemote()) : -1; inputs.push({ type: DialogInputType.Select, name: 'Push to remote', options: options, default: defaultOption.toString(), info: 'Once this tag has been added, push it to this remote.' }); } else if (this.gitRemotes.length === 1) { const defaultValue = initialPushToRemote !== null || (isInitialLoad && this.config.dialogDefaults.addTag.pushToRemote); inputs.push({ type: DialogInputType.Checkbox, name: 'Push to remote', value: defaultValue, info: 'Once this tag has been added, push it to the repositories remote.' }); } dialog.showForm('Add tag to commit <b><i>' + abbrevCommit(hash) + '</i></b>:', inputs, 'Add Tag', (values) => { const tagName = <string>values[0]; const type = <string>values[1] === 'annotated' ? GG.TagType.Annotated : GG.TagType.Lightweight; const message = <string>values[2]; const pushToRemote = this.gitRemotes.length > 1 && <string>values[3] !== '-1' ? this.gitRemotes[parseInt(<string>values[3])] : this.gitRemotes.length === 1 && <boolean>values[3] ? this.gitRemotes[0] : null; const runAddTagAction = (force: boolean) => { runAction({ command: 'addTag', repo: this.currentRepo, tagName: tagName, commitHash: hash, type: type, message: message, pushToRemote: pushToRemote, pushSkipRemoteCheck: globalState.pushTagSkipRemoteCheck, force: force }, 'Adding Tag'); }; if (this.gitTags.includes(tagName)) { dialog.showTwoButtons('A tag named <b><i>' + escapeHtml(tagName) + '</i></b> already exists, do you want to replace it with this new tag?', 'Yes, replace the existing tag', () => { runAddTagAction(true); }, 'No, choose another tag name', () => { this.addTagAction(hash, tagName, type, message, pushToRemote, target, false); }, target); } else { runAddTagAction(false); } }, target); } private checkoutBranchAction(refName: string, remote: string | null, prefillName: string | null, target: DialogTarget & (CommitTarget | RefTarget)) { if (remote !== null) { dialog.showRefInput('Enter the name of the new branch you would like to create when checking out <b><i>' + escapeHtml(refName) + '</i></b>:', (prefillName !== null ? prefillName : (remote !== '' ? refName.substring(remote.length + 1) : refName)), 'Checkout Branch', newBranch => { if (this.gitBranches.includes(newBranch)) { const canPullFromRemote = remote !== ''; dialog.showTwoButtons('The name <b><i>' + escapeHtml(newBranch) + '</i></b> is already used by another branch:', 'Choose another branch name', () => { this.checkoutBranchAction(refName, remote, newBranch, target); }, 'Checkout the existing branch' + (canPullFromRemote ? ' & pull changes' : ''), () => { runAction({ command: 'checkoutBranch', repo: this.currentRepo, branchName: newBranch, remoteBranch: null, pullAfterwards: canPullFromRemote ? { branchName: refName.substring(remote.length + 1), remote: remote, createNewCommit: this.config.dialogDefaults.pullBranch.noFastForward, squash: this.config.dialogDefaults.pullBranch.squash } : null }, 'Checking out Branch' + (canPullFromRemote ? ' & Pulling Changes' : '')); }, target); } else { runAction({ command: 'checkoutBranch', repo: this.currentRepo, branchName: newBranch, remoteBranch: refName, pullAfterwards: null }, 'Checking out Branch'); } }, target); } else { runAction({ command: 'checkoutBranch', repo: this.currentRepo, branchName: refName, remoteBranch: null, pullAfterwards: null }, 'Checking out Branch'); } } private createBranchAction(hash: string, initialName: string, initialCheckOut: boolean, target: DialogTarget & CommitTarget) { dialog.showForm('Create branch at commit <b><i>' + abbrevCommit(hash) + '</i></b>:', [ { type: DialogInputType.TextRef, name: 'Name', default: initialName }, { type: DialogInputType.Checkbox, name: 'Check out', value: initialCheckOut } ], 'Create Branch', (values) => { const branchName = <string>values[0], checkOut = <boolean>values[1]; if (this.gitBranches.includes(branchName)) { dialog.showTwoButtons('A branch named <b><i>' + escapeHtml(branchName) + '</i></b> already exists, do you want to replace it with this new branch?', 'Yes, replace the existing branch', () => { runAction({ command: 'createBranch', repo: this.currentRepo, branchName: branchName, commitHash: hash, checkout: checkOut, force: true }, 'Creating Branch'); }, 'No, choose another branch name', () => { this.createBranchAction(hash, branchName, checkOut, target); }, target); } else { runAction({ command: 'createBranch', repo: this.currentRepo, branchName: branchName, commitHash: hash, checkout: checkOut, force: false }, 'Creating Branch'); } }, target); } private deleteTagAction(refName: string, deleteOnRemote: string | null) { runAction({ command: 'deleteTag', repo: this.currentRepo, tagName: refName, deleteOnRemote: deleteOnRemote }, 'Deleting Tag'); } private fetchFromRemotesAction() { runAction({ command: 'fetch', repo: this.currentRepo, name: null, prune: this.config.fetchAndPrune, pruneTags: this.config.fetchAndPruneTags }, 'Fetching from Remote(s)'); } private mergeAction(obj: string, name: string, actionOn: GG.MergeActionOn, target: DialogTarget & (CommitTarget | RefTarget)) { dialog.showForm('Are you sure you want to merge ' + actionOn.toLowerCase() + ' <b><i>' + escapeHtml(name) + '</i></b> into ' + (this.gitBranchHead !== null ? '<b><i>' + escapeHtml(this.gitBranchHead) + '</i></b> (the current branch)' : 'the current branch') + '?', [ { type: DialogInputType.Checkbox, name: 'Create a new commit even if fast-forward is possible', value: this.config.dialogDefaults.merge.noFastForward }, { type: DialogInputType.Checkbox, name: 'Squash Commits', value: this.config.dialogDefaults.merge.squash, info: 'Create a single commit on the current branch whose effect is the same as merging this ' + actionOn.toLowerCase() + '.' }, { type: DialogInputType.Checkbox, name: 'No Commit', value: this.config.dialogDefaults.merge.noCommit, info: 'The changes of the merge will be staged but not committed, so that you can review and/or modify the merge result before committing.' } ], 'Yes, merge', (values) => { runAction({ command: 'merge', repo: this.currentRepo, obj: obj, actionOn: actionOn, createNewCommit: <boolean>values[0], squash: <boolean>values[1], noCommit: <boolean>values[2] }, 'Merging ' + actionOn); }, target); } private rebaseAction(obj: string, name: string, actionOn: GG.RebaseActionOn, target: DialogTarget & (CommitTarget | RefTarget)) { dialog.showForm('Are you sure you want to rebase ' + (this.gitBranchHead !== null ? '<b><i>' + escapeHtml(this.gitBranchHead) + '</i></b> (the current branch)' : 'the current branch') + ' on ' + actionOn.toLowerCase() + ' <b><i>' + escapeHtml(name) + '</i></b>?', [ { type: DialogInputType.Checkbox, name: 'Launch Interactive Rebase in new Terminal', value: this.config.dialogDefaults.rebase.interactive }, { type: DialogInputType.Checkbox, name: 'Ignore Date', value: this.config.dialogDefaults.rebase.ignoreDate, info: 'Only applicable to a non-interactive rebase.' } ], 'Yes, rebase', (values) => { let interactive = <boolean>values[0]; runAction({ command: 'rebase', repo: this.currentRepo, obj: obj, actionOn: actionOn, ignoreDate: <boolean>values[1], interactive: interactive }, interactive ? 'Launching Interactive Rebase' : 'Rebasing on ' + actionOn); }, target); } /* Table Utils */ private makeTableResizable() { let colHeadersElem = document.getElementById('tableColHeaders')!, cols = <HTMLCollectionOf<HTMLElement>>document.getElementsByClassName('tableColHeader'); let columnWidths: GG.ColumnWidth[], mouseX = -1, col = -1, colIndex = -1; const makeTableFixedLayout = () => { cols[0].style.width = columnWidths[0] + 'px'; cols[0].style.padding = ''; for (let i = 2; i < cols.length; i++) { cols[i].style.width = columnWidths[parseInt(cols[i].dataset.col!)] + 'px'; } this.tableElem.className = 'fixedLayout'; this.tableElem.style.removeProperty(CSS_PROP_LIMIT_GRAPH_WIDTH); this.graph.limitMaxWidth(columnWidths[0] + COLUMN_LEFT_RIGHT_PADDING); }; for (let i = 0; i < cols.length; i++) { let col = parseInt(cols[i].dataset.col!); cols[i].innerHTML += (i > 0 ? '<span class="resizeCol left" data-col="' + (col - 1) + '"></span>' : '') + (i < cols.length - 1 ? '<span class="resizeCol right" data-col="' + col + '"></span>' : ''); } let cWidths = this.gitRepos[this.currentRepo].columnWidths; if (cWidths === null) { // Initialise auto column layout if it is the first time viewing the repo. let defaults = this.config.defaultColumnVisibility; columnWidths = [COLUMN_AUTO, COLUMN_AUTO, defaults.date ? COLUMN_AUTO : COLUMN_HIDDEN, defaults.author ? COLUMN_AUTO : COLUMN_HIDDEN, defaults.commit ? COLUMN_AUTO : COLUMN_HIDDEN]; this.saveColumnWidths(columnWidths); } else { columnWidths = [cWidths[0], COLUMN_AUTO, cWidths[1], cWidths[2], cWidths[3]]; } if (columnWidths[0] !== COLUMN_AUTO) { // Table should have fixed layout makeTableFixedLayout(); } else { // Table should have automatic layout this.tableElem.className = 'autoLayout'; let colWidth = cols[0].offsetWidth, graphWidth = this.graph.getContentWidth(); let maxWidth = Math.round(this.viewElem.clientWidth * 0.333); if (Math.max(graphWidth, colWidth) > maxWidth) { this.graph.limitMaxWidth(maxWidth); graphWidth = maxWidth; this.tableElem.className += ' limitGraphWidth'; this.tableElem.style.setProperty(CSS_PROP_LIMIT_GRAPH_WIDTH, maxWidth + 'px'); } else { this.graph.limitMaxWidth(-1); this.tableElem.style.removeProperty(CSS_PROP_LIMIT_GRAPH_WIDTH); } if (colWidth < Math.max(graphWidth, 64)) { cols[0].style.padding = '6px ' + Math.floor((Math.max(graphWidth, 64) - (colWidth - COLUMN_LEFT_RIGHT_PADDING)) / 2) + 'px'; } } const processResizingColumn: EventListener = (e) => { if (col > -1) { let mouseEvent = <MouseEvent>e; let mouseDeltaX = mouseEvent.clientX - mouseX; if (col === 0) { if (columnWidths[0] + mouseDeltaX < COLUMN_MIN_WIDTH) mouseDeltaX = -columnWidths[0] + COLUMN_MIN_WIDTH; if (cols[1].clientWidth - COLUMN_LEFT_RIGHT_PADDING - mouseDeltaX < COLUMN_MIN_WIDTH) mouseDeltaX = cols[1].clientWidth - COLUMN_LEFT_RIGHT_PADDING - COLUMN_MIN_WIDTH; columnWidths[0] += mouseDeltaX; cols[0].style.width = columnWidths[0] + 'px'; this.graph.limitMaxWidth(columnWidths[0] + COLUMN_LEFT_RIGHT_PADDING); } else { let colWidth = col !== 1 ? columnWidths[col] : cols[1].clientWidth - COLUMN_LEFT_RIGHT_PADDING; let nextCol = col + 1; while (columnWidths[nextCol] === COLUMN_HIDDEN) nextCol++; if (colWidth + mouseDeltaX < COLUMN_MIN_WIDTH) mouseDeltaX = -colWidth + COLUMN_MIN_WIDTH; if (columnWidths[nextCol] - mouseDeltaX < COLUMN_MIN_WIDTH) mouseDeltaX = columnWidths[nextCol] - COLUMN_MIN_WIDTH; if (col !== 1) { columnWidths[col] += mouseDeltaX; cols[colIndex].style.width = columnWidths[col] + 'px'; } columnWidths[nextCol] -= mouseDeltaX; cols[colIndex + 1].style.width = columnWidths[nextCol] + 'px'; } mouseX = mouseEvent.clientX; } }; const stopResizingColumn: EventListener = () => { if (col > -1) { col = -1; colIndex = -1; mouseX = -1; eventOverlay.remove(); this.saveColumnWidths(columnWidths); } }; addListenerToClass('resizeCol', 'mousedown', (e) => { if (e.target === null) return; col = parseInt((<HTMLElement>e.target).dataset.col!); while (columnWidths[col] === COLUMN_HIDDEN) col--; mouseX = (<MouseEvent>e).clientX; let isAuto = columnWidths[0] === COLUMN_AUTO; for (let i = 0; i < cols.length; i++) { let curCol = parseInt(cols[i].dataset.col!); if (isAuto && curCol !== 1) columnWidths[curCol] = cols[i].clientWidth - COLUMN_LEFT_RIGHT_PADDING; if (curCol === col) colIndex = i; } if (isAuto) makeTableFixedLayout(); eventOverlay.create('colResize', processResizingColumn, stopResizingColumn); }); colHeadersElem.addEventListener('contextmenu', (e: MouseEvent) => { handledEvent(e); const toggleColumnState = (col: number, defaultWidth: number) => { columnWidths[col] = columnWidths[col] !== COLUMN_HIDDEN ? COLUMN_HIDDEN : columnWidths[0] === COLUMN_AUTO ? COLUMN_AUTO : defaultWidth - COLUMN_LEFT_RIGHT_PADDING; this.saveColumnWidths(columnWidths); this.render(); }; const commitOrdering = getCommitOrdering(this.gitRepos[this.currentRepo].commitOrdering); const changeCommitOrdering = (repoCommitOrdering: GG.RepoCommitOrdering) => { this.saveRepoStateValue(this.currentRepo, 'commitOrdering', repoCommitOrdering); this.refresh(true); }; contextMenu.show([ [ { title: 'Date', visible: true, checked: columnWidths[2] !== COLUMN_HIDDEN, onClick: () => toggleColumnState(2, 128) }, { title: 'Author', visible: true, checked: columnWidths[3] !== COLUMN_HIDDEN, onClick: () => toggleColumnState(3, 128) }, { title: 'Commit', visible: true, checked: columnWidths[4] !== COLUMN_HIDDEN, onClick: () => toggleColumnState(4, 80) } ], [ { title: 'Commit Timestamp Order', visible: true, checked: commitOrdering === GG.CommitOrdering.Date, onClick: () => changeCommitOrdering(GG.RepoCommitOrdering.Date) }, { title: 'Author Timestamp Order', visible: true, checked: commitOrdering === GG.CommitOrdering.AuthorDate, onClick: () => changeCommitOrdering(GG.RepoCommitOrdering.AuthorDate) }, { title: 'Topological Order', visible: true, checked: commitOrdering === GG.CommitOrdering.Topological, onClick: () => changeCommitOrdering(GG.RepoCommitOrdering.Topological) } ] ], true, null, e, this.viewElem); }); } public getColumnVisibility() { let colWidths = this.gitRepos[this.currentRepo].columnWidths; if (colWidths !== null) { return { date: colWidths[1] !== COLUMN_HIDDEN, author: colWidths[2] !== COLUMN_HIDDEN, commit: colWidths[3] !== COLUMN_HIDDEN }; } else { let defaults = this.config.defaultColumnVisibility; return { date: defaults.date, author: defaults.author, commit: defaults.commit }; } } private getNumColumns() { let colVisibility = this.getColumnVisibility(); return 2 + (colVisibility.date ? 1 : 0) + (colVisibility.author ? 1 : 0) + (colVisibility.commit ? 1 : 0); } /** * Scroll the view to the previous or next stash. * @param next TRUE => Jump to the next stash, FALSE => Jump to the previous stash. */ private scrollToStash(next: boolean) { const stashCommits = this.commits.filter((commit) => commit.stash !== null); if (stashCommits.length > 0) { const curTime = (new Date()).getTime(); if (this.lastScrollToStash.time < curTime - 5000) { // Reset the lastScrollToStash hash if it was more than 5 seconds ago this.lastScrollToStash.hash = null; } const lastScrollToStashCommitIndex = this.lastScrollToStash.hash !== null ? stashCommits.findIndex((commit) => commit.hash === this.lastScrollToStash.hash) : -1; let scrollToStashCommitIndex = lastScrollToStashCommitIndex + (next ? 1 : -1); if (scrollToStashCommitIndex >= stashCommits.length) { scrollToStashCommitIndex = 0; } else if (scrollToStashCommitIndex < 0) { scrollToStashCommitIndex = stashCommits.length - 1; } this.scrollToCommit(stashCommits[scrollToStashCommitIndex].hash, true, true); this.lastScrollToStash.time = curTime; this.lastScrollToStash.hash = stashCommits[scrollToStashCommitIndex].hash; } } /** * Scroll the view to a commit (if it exists). * @param hash The hash of the commit to scroll to. * @param alwaysCenterCommit TRUE => Always scroll the view to be centered on the commit. FALSE => Don't scroll the view if the commit is already within the visible portion of commits. * @param flash Should the commit flash after it has been scrolled to. */ public scrollToCommit(hash: string, alwaysCenterCommit: boolean, flash: boolean = false) { const elem = findCommitElemWithId(getCommitElems(), this.getCommitId(hash)); if (elem === null) return; let elemTop = this.controlsElem.clientHeight + elem.offsetTop; if (alwaysCenterCommit || elemTop - 8 < this.viewElem.scrollTop || elemTop + 32 - this.viewElem.clientHeight > this.viewElem.scrollTop) { this.viewElem.scroll(0, this.controlsElem.clientHeight + elem.offsetTop + 12 - this.viewElem.clientHeight / 2); } if (flash && !elem.classList.contains('flash')) { elem.classList.add('flash'); setTimeout(() => { elem.classList.remove('flash'); }, 850); } } private loadMoreCommits() { this.footerElem.innerHTML = '<h2 id="loadingHeader">' + SVG_ICONS.loading + 'Loading ...</h2>'; this.maxCommits += this.config.loadMoreCommits; this.saveState(); this.requestLoadRepoInfoAndCommits(false, true); } /* Observers */ private observeWindowSizeChanges() { let windowWidth = window.outerWidth, windowHeight = window.outerHeight; window.addEventListener('resize', () => { if (windowWidth === window.outerWidth && windowHeight === window.outerHeight) { this.renderGraph(); } else { windowWidth = window.outerWidth; windowHeight = window.outerHeight; } }); } private observeWebviewStyleChanges() { let fontFamily = getVSCodeStyle(CSS_PROP_FONT_FAMILY), editorFontFamily = getVSCodeStyle(CSS_PROP_EDITOR_FONT_FAMILY), findMatchColour = getVSCodeStyle(CSS_PROP_FIND_MATCH_HIGHLIGHT_BACKGROUND), selectionBackgroundColor = !!getVSCodeStyle(CSS_PROP_SELECTION_BACKGROUND); const setFlashColour = (colour: string) => { document.body.style.setProperty('--git-graph-flashPrimary', modifyColourOpacity(colour, 0.7)); document.body.style.setProperty('--git-graph-flashSecondary', modifyColourOpacity(colour, 0.5)); }; const setSelectionBackgroundColorExists = () => { alterClass(document.body, 'selection-background-color-exists', selectionBackgroundColor); }; this.findWidget.setColour(findMatchColour); setFlashColour(findMatchColour); setSelectionBackgroundColorExists(); (new MutationObserver(() => { let ff = getVSCodeStyle(CSS_PROP_FONT_FAMILY), eff = getVSCodeStyle(CSS_PROP_EDITOR_FONT_FAMILY), fmc = getVSCodeStyle(CSS_PROP_FIND_MATCH_HIGHLIGHT_BACKGROUND), sbc = !!getVSCodeStyle(CSS_PROP_SELECTION_BACKGROUND); if (ff !== fontFamily || eff !== editorFontFamily) { fontFamily = ff; editorFontFamily = eff; this.repoDropdown.refresh(); this.branchDropdown.refresh(); } if (fmc !== findMatchColour) { findMatchColour = fmc; this.findWidget.setColour(findMatchColour); setFlashColour(findMatchColour); } if (selectionBackgroundColor !== sbc) { selectionBackgroundColor = sbc; setSelectionBackgroundColorExists(); } })).observe(document.documentElement, { attributes: true, attributeFilter: ['style'] }); } private observeViewScroll() { let active = this.viewElem.scrollTop > 0, timeout: NodeJS.Timer | null = null; this.scrollShadowElem.className = active ? CLASS_ACTIVE : ''; this.viewElem.addEventListener('scroll', () => { const scrollTop = this.viewElem.scrollTop; if (active !== scrollTop > 0) { active = scrollTop > 0; this.scrollShadowElem.className = active ? CLASS_ACTIVE : ''; } if (this.config.loadMoreCommitsAutomatically && this.moreCommitsAvailable && !this.currentRepoRefreshState.inProgress) { const viewHeight = this.viewElem.clientHeight, contentHeight = this.viewElem.scrollHeight; if (scrollTop > 0 && viewHeight > 0 && contentHeight > 0 && (scrollTop + viewHeight) >= contentHeight - 25) { // If the user has scrolled such that the bottom of the visible view is within 25px of the end of the content, load more commits. this.loadMoreCommits(); } } if (timeout !== null) clearTimeout(timeout); timeout = setTimeout(() => { this.scrollTop = scrollTop; this.saveState(); timeout = null; }, 250); }); } private observeKeyboardEvents() { document.addEventListener('keydown', (e) => { if (contextMenu.isOpen()) { if (e.key === 'Escape') { contextMenu.close(); handledEvent(e); } } else if (dialog.isOpen()) { if (e.key === 'Escape') { dialog.close(); handledEvent(e); } else if (e.keyCode ? e.keyCode === 13 : e.key === 'Enter') { // Use keyCode === 13 to detect 'Enter' events if available (for compatibility with IME Keyboards used by Chinese / Japanese / Korean users) dialog.submit(); handledEvent(e); } } else if (this.expandedCommit !== null && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) { const curHashIndex = this.commitLookup[this.expandedCommit.commitHash]; let newHashIndex = -1; if (e.ctrlKey || e.metaKey) { // Up / Down navigates according to the order of commits on the branch if (e.shiftKey) { // Follow commits on alternative branches when possible if (e.key === 'ArrowUp') { newHashIndex = this.graph.getAlternativeChildIndex(curHashIndex); } else if (e.key === 'ArrowDown') { newHashIndex = this.graph.getAlternativeParentIndex(curHashIndex); } } else { // Follow commits on the same branch if (e.key === 'ArrowUp') { newHashIndex = this.graph.getFirstChildIndex(curHashIndex); } else if (e.key === 'ArrowDown') { newHashIndex = this.graph.getFirstParentIndex(curHashIndex); } } } else { // Up / Down navigates according to the order of commits in the table if (e.key === 'ArrowUp' && curHashIndex > 0) { newHashIndex = curHashIndex - 1; } else if (e.key === 'ArrowDown' && curHashIndex < this.commits.length - 1) { newHashIndex = curHashIndex + 1; } } if (newHashIndex > -1) { handledEvent(e); const elem = findCommitElemWithId(getCommitElems(), newHashIndex); if (elem !== null) this.loadCommitDetails(elem); } } else if (e.key && (e.ctrlKey || e.metaKey)) { const key = e.key.toLowerCase(), keybindings = this.config.keybindings; if (key === keybindings.scrollToStash) { this.scrollToStash(!e.shiftKey); handledEvent(e); } else if (!e.shiftKey) { if (key === keybindings.refresh) { this.refresh(true, true); handledEvent(e); } else if (key === keybindings.find) { this.findWidget.show(true); handledEvent(e); } else if (key === keybindings.scrollToHead && this.commitHead !== null) { this.scrollToCommit(this.commitHead, true, true); handledEvent(e); } } } else if (e.key === 'Escape') { if (this.repoDropdown.isOpen()) { this.repoDropdown.close(); handledEvent(e); } else if (this.branchDropdown.isOpen()) { this.branchDropdown.close(); handledEvent(e); } else if (this.settingsWidget.isVisible()) { this.settingsWidget.close(); handledEvent(e); } else if (this.findWidget.isVisible()) { this.findWidget.close(); handledEvent(e); } else if (this.expandedCommit !== null) { this.closeCommitDetails(true); handledEvent(e); } } }); } private observeUrls() { const followInternalLink = (e: MouseEvent) => { if (e.target !== null && isInternalUrlElem(<Element>e.target)) { const value = unescapeHtml((<HTMLElement>e.target).dataset.value!); switch ((<HTMLElement>e.target).dataset.type!) { case 'commit': if (typeof this.commitLookup[value] === 'number' && (this.expandedCommit === null || this.expandedCommit.commitHash !== value || this.expandedCommit.compareWithHash !== null)) { const elem = findCommitElemWithId(getCommitElems(), this.commitLookup[value]); if (elem !== null) this.loadCommitDetails(elem); } break; } } }; document.body.addEventListener('click', followInternalLink); document.body.addEventListener('contextmenu', (e: MouseEvent) => { if (e.target === null) return; const eventTarget = <Element>e.target; const isExternalUrl = isExternalUrlElem(eventTarget), isInternalUrl = isInternalUrlElem(eventTarget); if (isExternalUrl || isInternalUrl) { const viewElem: HTMLElement | null = eventTarget.closest('#view'); let eventElem: HTMLElement | null; let target: (ContextMenuTarget & CommitTarget) | RepoTarget, isInDialog = false; if (this.expandedCommit !== null && eventTarget.closest('#cdv') !== null) { // URL is in the Commit Details View target = { type: TargetType.CommitDetailsView, hash: this.expandedCommit.commitHash, index: this.commitLookup[this.expandedCommit.commitHash], elem: <HTMLElement>eventTarget }; GitGraphView.closeCdvContextMenuIfOpen(this.expandedCommit); this.expandedCommit.contextMenuOpen.summary = true; } else if ((eventElem = eventTarget.closest('.commit')) !== null) { // URL is in the Commits const commit = this.getCommitOfElem(eventElem); if (commit === null) return; target = { type: TargetType.Commit, hash: commit.hash, index: parseInt(eventElem.dataset.id!), elem: <HTMLElement>eventTarget }; } else { // URL is in a dialog target = { type: TargetType.Repo }; isInDialog = true; } handledEvent(e); contextMenu.show([ [ { title: 'Open URL', visible: isExternalUrl, onClick: () => { sendMessage({ command: 'openExternalUrl', url: (<HTMLAnchorElement>eventTarget).href }); } }, { title: 'Follow Internal Link', visible: isInternalUrl, onClick: () => followInternalLink(e) }, { title: 'Copy URL to Clipboard', visible: isExternalUrl, onClick: () => { sendMessage({ command: 'copyToClipboard', type: 'External URL', data: (<HTMLAnchorElement>eventTarget).href }); } } ] ], false, target, e, viewElem || document.body, () => { if (target.type === TargetType.CommitDetailsView && this.expandedCommit !== null) { this.expandedCommit.contextMenuOpen.summary = false; } }, isInDialog ? 'dialogContextMenu' : null); } }); } private observeTableEvents() { // Register Click Event Handler this.tableElem.addEventListener('click', (e: MouseEvent) => { if (e.target === null) return; const eventTarget = <Element>e.target; if (isUrlElem(eventTarget)) return; let eventElem: HTMLElement | null; if ((eventElem = eventTarget.closest('.gitRef')) !== null) { // .gitRef was clicked e.stopPropagation(); if (contextMenu.isOpen()) { contextMenu.close(); } } else if ((eventElem = eventTarget.closest('.commit')) !== null) { // .commit was clicked if (this.expandedCommit !== null) { const commit = this.getCommitOfElem(eventElem); if (commit === null) return; if (this.expandedCommit.commitHash === commit.hash) { this.closeCommitDetails(true); } else if ((<MouseEvent>e).ctrlKey || (<MouseEvent>e).metaKey) { if (this.expandedCommit.compareWithHash === commit.hash) { this.closeCommitComparison(true); } else if (this.expandedCommit.commitElem !== null) { this.loadCommitComparison(this.expandedCommit.commitElem, eventElem); } } else { this.loadCommitDetails(eventElem); } } else { this.loadCommitDetails(eventElem); } } }); // Register Double Click Event Handler this.tableElem.addEventListener('dblclick', (e: MouseEvent) => { if (e.target === null) return; const eventTarget = <Element>e.target; if (isUrlElem(eventTarget)) return; let eventElem: HTMLElement | null; if ((eventElem = eventTarget.closest('.gitRef')) !== null) { // .gitRef was double clicked e.stopPropagation(); closeDialogAndContextMenu(); const commitElem = <HTMLElement>eventElem.closest('.commit')!; const commit = this.getCommitOfElem(commitElem); if (commit === null) return; if (eventElem.classList.contains(CLASS_REF_HEAD) || eventElem.classList.contains(CLASS_REF_REMOTE)) { let sourceElem = <HTMLElement>eventElem.children[1]; let refName = unescapeHtml(eventElem.dataset.name!), isHead = eventElem.classList.contains(CLASS_REF_HEAD), isRemoteCombinedWithHead = eventTarget.classList.contains('gitRefHeadRemote'); if (isHead && isRemoteCombinedWithHead) { refName = unescapeHtml((<HTMLElement>eventTarget).dataset.fullref!); sourceElem = <HTMLElement>eventTarget; isHead = false; } const target: ContextMenuTarget & DialogTarget & RefTarget = { type: TargetType.Ref, hash: commit.hash, index: parseInt(commitElem.dataset.id!), ref: refName, elem: sourceElem }; this.checkoutBranchAction(refName, isHead ? null : unescapeHtml((isRemoteCombinedWithHead ? <HTMLElement>eventTarget : eventElem).dataset.remote!), null, target); } } }); // Register ContextMenu Event Handler this.tableElem.addEventListener('contextmenu', (e: Event) => { if (e.target === null) return; const eventTarget = <Element>e.target; if (isUrlElem(eventTarget)) return; let eventElem: HTMLElement | null; if ((eventElem = eventTarget.closest('.gitRef')) !== null) { // .gitRef was right clicked handledEvent(e); const commitElem = <HTMLElement>eventElem.closest('.commit')!; const commit = this.getCommitOfElem(commitElem); if (commit === null) return; const target: ContextMenuTarget & DialogTarget & RefTarget = { type: TargetType.Ref, hash: commit.hash, index: parseInt(commitElem.dataset.id!), ref: unescapeHtml(eventElem.dataset.name!), elem: <HTMLElement>eventElem.children[1] }; let actions: ContextMenuActions; if (eventElem.classList.contains(CLASS_REF_STASH)) { actions = this.getStashContextMenuActions(target); } else if (eventElem.classList.contains(CLASS_REF_TAG)) { actions = this.getTagContextMenuActions(eventElem.dataset.tagtype === 'annotated', target); } else { let isHead = eventElem.classList.contains(CLASS_REF_HEAD), isRemoteCombinedWithHead = eventTarget.classList.contains('gitRefHeadRemote'); if (isHead && isRemoteCombinedWithHead) { target.ref = unescapeHtml((<HTMLElement>eventTarget).dataset.fullref!); target.elem = <HTMLElement>eventTarget; isHead = false; } if (isHead) { actions = this.getBranchContextMenuActions(target); } else { const remote = unescapeHtml((isRemoteCombinedWithHead ? <HTMLElement>eventTarget : eventElem).dataset.remote!); actions = this.getRemoteBranchContextMenuActions(remote, target); } } contextMenu.show(actions, false, target, <MouseEvent>e, this.viewElem); } else if ((eventElem = eventTarget.closest('.commit')) !== null) { // .commit was right clicked handledEvent(e); const commit = this.getCommitOfElem(eventElem); if (commit === null) return; const target: ContextMenuTarget & DialogTarget & CommitTarget = { type: TargetType.Commit, hash: commit.hash, index: parseInt(eventElem.dataset.id!), elem: eventElem }; let actions: ContextMenuActions; if (commit.hash === UNCOMMITTED) { actions = this.getUncommittedChangesContextMenuActions(target); } else if (commit.stash !== null) { target.ref = commit.stash.selector; actions = this.getStashContextMenuActions(<RefTarget>target); } else { actions = this.getCommitContextMenuActions(target); } contextMenu.show(actions, false, target, <MouseEvent>e, this.viewElem); } }); } /* Commit Details View */ public loadCommitDetails(commitElem: HTMLElement) { const commit = this.getCommitOfElem(commitElem); if (commit === null) return; this.closeCommitDetails(false); this.saveExpandedCommitLoading(parseInt(commitElem.dataset.id!), commit.hash, commitElem, null, null); commitElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); this.renderCommitDetailsView(false); this.requestCommitDetails(commit.hash, false); } public closeCommitDetails(saveAndRender: boolean) { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; const elem = document.getElementById('cdv'), isDocked = this.isCdvDocked(); if (elem !== null) { elem.remove(); } if (isDocked) { this.viewElem.style.bottom = '0px'; } if (expandedCommit.commitElem !== null) { expandedCommit.commitElem.classList.remove(CLASS_COMMIT_DETAILS_OPEN); } if (expandedCommit.compareWithElem !== null) { expandedCommit.compareWithElem.classList.remove(CLASS_COMMIT_DETAILS_OPEN); } GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); this.expandedCommit = null; if (saveAndRender) { this.saveState(); if (!isDocked) { this.renderGraph(); } } } public showCommitDetails(commitDetails: GG.GitCommitDetails, fileTree: FileTreeFolder, avatar: string | null, codeReview: GG.CodeReview | null, lastViewedFile: string | null, refresh: boolean) { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.commitElem === null || expandedCommit.commitHash !== commitDetails.hash || expandedCommit.compareWithHash !== null) return; if (!this.isCdvDocked()) { const elem = document.getElementById('cdv'); if (elem !== null) elem.remove(); } expandedCommit.commitDetails = commitDetails; if (haveFilesChanged(expandedCommit.fileChanges, commitDetails.fileChanges)) { expandedCommit.fileChanges = commitDetails.fileChanges; expandedCommit.fileTree = fileTree; GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); } expandedCommit.avatar = avatar; expandedCommit.codeReview = codeReview; if (!refresh) { expandedCommit.lastViewedFile = lastViewedFile; } expandedCommit.commitElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); expandedCommit.loading = false; this.saveState(); this.renderCommitDetailsView(refresh); } public createFileTree(gitFiles: ReadonlyArray<GG.GitFileChange>, codeReview: GG.CodeReview | null) { let contents: FileTreeFolderContents = {}, i, j, path, absPath, cur: FileTreeFolder; let files: FileTreeFolder = { type: 'folder', name: '', folderPath: '', contents: contents, open: true, reviewed: true }; for (i = 0; i < gitFiles.length; i++) { cur = files; path = gitFiles[i].newFilePath.split('/'); absPath = this.currentRepo; for (j = 0; j < path.length; j++) { absPath += '/' + path[j]; if (typeof this.gitRepos[absPath] !== 'undefined') { if (typeof cur.contents[path[j]] === 'undefined') { cur.contents[path[j]] = { type: 'repo', name: path[j], path: absPath }; } break; } else if (j < path.length - 1) { if (typeof cur.contents[path[j]] === 'undefined') { contents = {}; cur.contents[path[j]] = { type: 'folder', name: path[j], folderPath: absPath.substring(this.currentRepo.length + 1), contents: contents, open: true, reviewed: true }; } cur = <FileTreeFolder>cur.contents[path[j]]; } else if (path[j] !== '') { cur.contents[path[j]] = { type: 'file', name: path[j], index: i, reviewed: codeReview === null || !codeReview.remainingFiles.includes(gitFiles[i].newFilePath) }; } } } if (codeReview !== null) calcFileTreeFoldersReviewed(files); return files; } /* Commit Comparison View */ private loadCommitComparison(commitElem: HTMLElement, compareWithElem: HTMLElement) { const commit = this.getCommitOfElem(commitElem); const compareWithCommit = this.getCommitOfElem(compareWithElem); if (commit !== null && compareWithCommit !== null) { if (this.expandedCommit !== null) { if (this.expandedCommit.commitHash !== commit.hash) { this.closeCommitDetails(false); } else if (this.expandedCommit.compareWithHash !== compareWithCommit.hash) { this.closeCommitComparison(false); } } this.saveExpandedCommitLoading(parseInt(commitElem.dataset.id!), commit.hash, commitElem, compareWithCommit.hash, compareWithElem); commitElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); compareWithElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); this.renderCommitDetailsView(false); this.requestCommitComparison(commit.hash, compareWithCommit.hash, false); } } public closeCommitComparison(saveAndRequestCommitDetails: boolean) { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.compareWithHash === null) return; if (expandedCommit.compareWithElem !== null) { expandedCommit.compareWithElem.classList.remove(CLASS_COMMIT_DETAILS_OPEN); } GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); if (saveAndRequestCommitDetails) { if (expandedCommit.commitElem !== null) { this.saveExpandedCommitLoading(expandedCommit.index, expandedCommit.commitHash, expandedCommit.commitElem, null, null); this.renderCommitDetailsView(false); this.requestCommitDetails(expandedCommit.commitHash, false); } else { this.closeCommitDetails(true); } } } public showCommitComparison(commitHash: string, compareWithHash: string, fileChanges: ReadonlyArray<GG.GitFileChange>, fileTree: FileTreeFolder, codeReview: GG.CodeReview | null, lastViewedFile: string | null, refresh: boolean) { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.commitElem === null || expandedCommit.compareWithElem === null || expandedCommit.commitHash !== commitHash || expandedCommit.compareWithHash !== compareWithHash) return; if (haveFilesChanged(expandedCommit.fileChanges, fileChanges)) { expandedCommit.fileChanges = fileChanges; expandedCommit.fileTree = fileTree; GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); } expandedCommit.codeReview = codeReview; if (!refresh) { expandedCommit.lastViewedFile = lastViewedFile; } expandedCommit.commitElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); expandedCommit.compareWithElem.classList.add(CLASS_COMMIT_DETAILS_OPEN); expandedCommit.loading = false; this.saveState(); this.renderCommitDetailsView(refresh); } /* Render Commit Details / Comparison View */ private renderCommitDetailsView(refresh: boolean) { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.commitElem === null) return; let elem = document.getElementById('cdv'), html = '<div id="cdvContent">', isDocked = this.isCdvDocked(); const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash === null ? expandedCommit.commitHash : expandedCommit.compareWithHash); const codeReviewPossible = !expandedCommit.loading && commitOrder.to !== UNCOMMITTED; const externalDiffPossible = !expandedCommit.loading && (expandedCommit.compareWithHash !== null || this.commits[this.commitLookup[expandedCommit.commitHash]].parents.length > 0); if (elem === null) { elem = document.createElement(isDocked ? 'div' : 'tr'); elem.id = 'cdv'; elem.className = isDocked ? 'docked' : 'inline'; this.setCdvHeight(elem, isDocked); if (isDocked) { document.body.appendChild(elem); } else { insertAfter(elem, expandedCommit.commitElem); } } if (expandedCommit.loading) { html += '<div id="cdvLoading">' + SVG_ICONS.loading + ' Loading ' + (expandedCommit.compareWithHash === null ? expandedCommit.commitHash !== UNCOMMITTED ? 'Commit Details' : 'Uncommitted Changes' : 'Commit Comparison') + ' ...</div>'; } else { html += '<div id="cdvSummary">'; if (expandedCommit.compareWithHash === null) { // Commit details should be shown if (expandedCommit.commitHash !== UNCOMMITTED) { const textFormatter = new TextFormatter(this.commits, this.gitRepos[this.currentRepo].issueLinkingConfig, { commits: true, emoji: true, issueLinking: true, markdown: this.config.markdown, multiline: true, urls: true }); const commitDetails = expandedCommit.commitDetails!; const parents = commitDetails.parents.length > 0 ? commitDetails.parents.map((parent) => { const escapedParent = escapeHtml(parent); return typeof this.commitLookup[parent] === 'number' ? '<span class="' + CLASS_INTERNAL_URL + '" data-type="commit" data-value="' + escapedParent + '" tabindex="-1">' + escapedParent + '</span>' : escapedParent; }).join(', ') : 'None'; html += '<span class="cdvSummaryTop' + (expandedCommit.avatar !== null ? ' withAvatar' : '') + '"><span class="cdvSummaryTopRow"><span class="cdvSummaryKeyValues">' + '<b>Commit: </b>' + escapeHtml(commitDetails.hash) + '<br>' + '<b>Parents: </b>' + parents + '<br>' + '<b>Author: </b>' + escapeHtml(commitDetails.author) + (commitDetails.authorEmail !== '' ? ' &lt;<a class="' + CLASS_EXTERNAL_URL + '" href="mailto:' + escapeHtml(commitDetails.authorEmail) + '" tabindex="-1">' + escapeHtml(commitDetails.authorEmail) + '</a>&gt;' : '') + '<br>' + (commitDetails.authorDate !== commitDetails.committerDate ? '<b>Author Date: </b>' + formatLongDate(commitDetails.authorDate) + '<br>' : '') + '<b>Committer: </b>' + escapeHtml(commitDetails.committer) + (commitDetails.committerEmail !== '' ? ' &lt;<a class="' + CLASS_EXTERNAL_URL + '" href="mailto:' + escapeHtml(commitDetails.committerEmail) + '" tabindex="-1">' + escapeHtml(commitDetails.committerEmail) + '</a>&gt;' : '') + (commitDetails.signature !== null ? generateSignatureHtml(commitDetails.signature) : '') + '<br>' + '<b>' + (commitDetails.authorDate !== commitDetails.committerDate ? 'Committer ' : '') + 'Date: </b>' + formatLongDate(commitDetails.committerDate) + '</span>' + (expandedCommit.avatar !== null ? '<span class="cdvSummaryAvatar"><img src="' + expandedCommit.avatar + '"></span>' : '') + '</span></span><br><br>' + textFormatter.format(commitDetails.body); } else { html += 'Displaying all uncommitted changes.'; } } else { // Commit comparison should be shown html += 'Displaying all changes from <b>' + commitOrder.from + '</b> to <b>' + (commitOrder.to !== UNCOMMITTED ? commitOrder.to : 'Uncommitted Changes') + '</b>.'; } html += '</div><div id="cdvFiles">' + generateFileViewHtml(expandedCommit.fileTree!, expandedCommit.fileChanges!, expandedCommit.lastViewedFile, expandedCommit.contextMenuOpen.fileView, this.getFileViewType(), commitOrder.to === UNCOMMITTED) + '</div><div id="cdvDivider"></div>'; } html += '</div><div id="cdvControls"><div id="cdvClose" class="cdvControlBtn" title="Close">' + SVG_ICONS.close + '</div>' + (codeReviewPossible ? '<div id="cdvCodeReview" class="cdvControlBtn">' + SVG_ICONS.review + '</div>' : '') + (!expandedCommit.loading ? '<div id="cdvFileViewTypeTree" class="cdvControlBtn cdvFileViewTypeBtn" title="File Tree View">' + SVG_ICONS.fileTree + '</div><div id="cdvFileViewTypeList" class="cdvControlBtn cdvFileViewTypeBtn" title="File List View">' + SVG_ICONS.fileList + '</div>' : '') + (externalDiffPossible ? '<div id="cdvExternalDiff" class="cdvControlBtn">' + SVG_ICONS.linkExternal + '</div>' : '') + '</div><div class="cdvHeightResize"></div>'; elem.innerHTML = isDocked ? html : '<td><div class="cdvHeightResize"></div></td><td colspan="' + (this.getNumColumns() - 1) + '">' + html + '</td>'; if (!expandedCommit.loading) this.setCdvDivider(); if (!isDocked) this.renderGraph(); if (!refresh) { if (isDocked) { let elemTop = this.controlsElem.clientHeight + expandedCommit.commitElem.offsetTop; if (elemTop - 8 < this.viewElem.scrollTop) { // Commit is above what is visible on screen this.viewElem.scroll(0, elemTop - 8); } else if (elemTop - this.viewElem.clientHeight + 32 > this.viewElem.scrollTop) { // Commit is below what is visible on screen this.viewElem.scroll(0, elemTop - this.viewElem.clientHeight + 32); } } else { let elemTop = this.controlsElem.clientHeight + elem.offsetTop, cdvHeight = this.gitRepos[this.currentRepo].cdvHeight; if (this.config.commitDetailsView.autoCenter) { // Center Commit Detail View setting is enabled // elemTop - commit height [24px] + (commit details view height + commit height [24px]) / 2 - (view height) / 2 this.viewElem.scroll(0, elemTop - 12 + (cdvHeight - this.viewElem.clientHeight) / 2); } else if (elemTop - 32 < this.viewElem.scrollTop) { // Commit Detail View is opening above what is visible on screen // elemTop - commit height [24px] - desired gap from top [8px] < view scroll offset this.viewElem.scroll(0, elemTop - 32); } else if (elemTop + cdvHeight - this.viewElem.clientHeight + 8 > this.viewElem.scrollTop) { // Commit Detail View is opening below what is visible on screen // elemTop + commit details view height + desired gap from bottom [8px] - view height > view scroll offset this.viewElem.scroll(0, elemTop + cdvHeight - this.viewElem.clientHeight + 8); } } } this.makeCdvResizable(); document.getElementById('cdvClose')!.addEventListener('click', () => { this.closeCommitDetails(true); }); if (!expandedCommit.loading) { this.makeCdvFileViewInteractive(); this.renderCdvFileViewTypeBtns(); this.renderCdvExternalDiffBtn(); this.makeCdvDividerDraggable(); observeElemScroll('cdvSummary', expandedCommit.scrollTop.summary, (scrollTop) => { if (this.expandedCommit === null) return; this.expandedCommit.scrollTop.summary = scrollTop; if (this.expandedCommit.contextMenuOpen.summary) { this.expandedCommit.contextMenuOpen.summary = false; contextMenu.close(); } }, () => this.saveState()); observeElemScroll('cdvFiles', expandedCommit.scrollTop.fileView, (scrollTop) => { if (this.expandedCommit === null) return; this.expandedCommit.scrollTop.fileView = scrollTop; if (this.expandedCommit.contextMenuOpen.fileView > -1) { this.expandedCommit.contextMenuOpen.fileView = -1; contextMenu.close(); } }, () => this.saveState()); document.getElementById('cdvFileViewTypeTree')!.addEventListener('click', () => { this.changeFileViewType(GG.FileViewType.Tree); }); document.getElementById('cdvFileViewTypeList')!.addEventListener('click', () => { this.changeFileViewType(GG.FileViewType.List); }); if (codeReviewPossible) { this.renderCodeReviewBtn(); document.getElementById('cdvCodeReview')!.addEventListener('click', (e) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || e.target === null) return; let sourceElem = <HTMLElement>(<Element>e.target).closest('#cdvCodeReview')!; if (sourceElem.classList.contains(CLASS_ACTIVE)) { sendMessage({ command: 'endCodeReview', repo: this.currentRepo, id: expandedCommit.codeReview!.id }); this.endCodeReview(); } else { const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash === null ? expandedCommit.commitHash : expandedCommit.compareWithHash); const id = expandedCommit.compareWithHash !== null ? commitOrder.from + '-' + commitOrder.to : expandedCommit.commitHash; sendMessage({ command: 'startCodeReview', repo: this.currentRepo, id: id, commitHash: expandedCommit.commitHash, compareWithHash: expandedCommit.compareWithHash, files: getFilesInTree(expandedCommit.fileTree!, expandedCommit.fileChanges!), lastViewedFile: expandedCommit.lastViewedFile }); } }); } if (externalDiffPossible) { document.getElementById('cdvExternalDiff')!.addEventListener('click', () => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || this.gitConfig === null || (this.gitConfig.diffTool === null && this.gitConfig.guiDiffTool === null)) return; const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash === null ? expandedCommit.commitHash : expandedCommit.compareWithHash); runAction({ command: 'openExternalDirDiff', repo: this.currentRepo, fromHash: commitOrder.from, toHash: commitOrder.to, isGui: this.gitConfig.guiDiffTool !== null }, 'Opening External Directory Diff'); }); } } } private setCdvHeight(elem: HTMLElement, isDocked: boolean) { let height = this.gitRepos[this.currentRepo].cdvHeight, windowHeight = window.innerHeight; if (height > windowHeight - 40) { height = Math.max(windowHeight - 40, 100); if (height !== this.gitRepos[this.currentRepo].cdvHeight) { this.gitRepos[this.currentRepo].cdvHeight = height; this.saveRepoState(); } } let heightPx = height + 'px'; elem.style.height = heightPx; if (isDocked) this.viewElem.style.bottom = heightPx; } private setCdvDivider() { let percent = (this.gitRepos[this.currentRepo].cdvDivider * 100).toFixed(2) + '%'; let summaryElem = document.getElementById('cdvSummary'), dividerElem = document.getElementById('cdvDivider'), filesElem = document.getElementById('cdvFiles'); if (summaryElem !== null) summaryElem.style.width = percent; if (dividerElem !== null) dividerElem.style.left = percent; if (filesElem !== null) filesElem.style.left = percent; } private makeCdvResizable() { let prevY = -1; const processResizingCdvHeight: EventListener = (e) => { if (prevY < 0) return; let delta = (<MouseEvent>e).pageY - prevY, isDocked = this.isCdvDocked(), windowHeight = window.innerHeight; prevY = (<MouseEvent>e).pageY; let height = this.gitRepos[this.currentRepo].cdvHeight + (isDocked ? -delta : delta); if (height < 100) height = 100; else if (height > 600) height = 600; if (height > windowHeight - 40) height = Math.max(windowHeight - 40, 100); if (this.gitRepos[this.currentRepo].cdvHeight !== height) { this.gitRepos[this.currentRepo].cdvHeight = height; let elem = document.getElementById('cdv'); if (elem !== null) this.setCdvHeight(elem, isDocked); if (!isDocked) this.renderGraph(); } }; const stopResizingCdvHeight: EventListener = (e) => { if (prevY < 0) return; processResizingCdvHeight(e); this.saveRepoState(); prevY = -1; eventOverlay.remove(); }; addListenerToClass('cdvHeightResize', 'mousedown', (e) => { prevY = (<MouseEvent>e).pageY; eventOverlay.create('rowResize', processResizingCdvHeight, stopResizingCdvHeight); }); } private makeCdvDividerDraggable() { let minX = -1, width = -1; const processDraggingCdvDivider: EventListener = (e) => { if (minX < 0) return; let percent = ((<MouseEvent>e).clientX - minX) / width; if (percent < 0.2) percent = 0.2; else if (percent > 0.8) percent = 0.8; if (this.gitRepos[this.currentRepo].cdvDivider !== percent) { this.gitRepos[this.currentRepo].cdvDivider = percent; this.setCdvDivider(); } }; const stopDraggingCdvDivider: EventListener = (e) => { if (minX < 0) return; processDraggingCdvDivider(e); this.saveRepoState(); minX = -1; eventOverlay.remove(); }; document.getElementById('cdvDivider')!.addEventListener('mousedown', () => { const contentElem = document.getElementById('cdvContent'); if (contentElem === null) return; const bounds = contentElem.getBoundingClientRect(); minX = bounds.left; width = bounds.width; eventOverlay.create('colResize', processDraggingCdvDivider, stopDraggingCdvDivider); }); } /** * Updates the state of a file in the Commit Details View. * @param file The file that was affected. * @param fileElem The HTML Element of the file. * @param isReviewed TRUE/FALSE => Set the files reviewed state accordingly, NULL => Don't update the files reviewed state. * @param fileWasViewed Was the file viewed - if so, set it to be the last viewed file. */ private cdvUpdateFileState(file: GG.GitFileChange, fileElem: HTMLElement, isReviewed: boolean | null, fileWasViewed: boolean) { const expandedCommit = this.expandedCommit, filesElem = document.getElementById('cdvFiles'), filePath = file.newFilePath; if (expandedCommit === null || expandedCommit.fileTree === null || filesElem === null) return; if (fileWasViewed) { expandedCommit.lastViewedFile = filePath; let lastViewedElem = document.getElementById('cdvLastFileViewed'); if (lastViewedElem !== null) lastViewedElem.remove(); lastViewedElem = document.createElement('span'); lastViewedElem.id = 'cdvLastFileViewed'; lastViewedElem.title = 'Last File Viewed'; lastViewedElem.innerHTML = SVG_ICONS.eyeOpen; insertBeforeFirstChildWithClass(lastViewedElem, fileElem, 'fileTreeFileAction'); } if (expandedCommit.codeReview !== null) { if (isReviewed !== null) { if (isReviewed) { expandedCommit.codeReview.remainingFiles = expandedCommit.codeReview.remainingFiles.filter((path: string) => path !== filePath); } else { expandedCommit.codeReview.remainingFiles.push(filePath); } alterFileTreeFileReviewed(expandedCommit.fileTree, filePath, isReviewed); updateFileTreeHtmlFileReviewed(filesElem, expandedCommit.fileTree, filePath); } sendMessage({ command: 'updateCodeReview', repo: this.currentRepo, id: expandedCommit.codeReview.id, remainingFiles: expandedCommit.codeReview.remainingFiles, lastViewedFile: expandedCommit.lastViewedFile }); if (expandedCommit.codeReview.remainingFiles.length === 0) { expandedCommit.codeReview = null; this.renderCodeReviewBtn(); } } this.saveState(); } private isCdvDocked() { return this.config.commitDetailsView.location === GG.CommitDetailsViewLocation.DockedToBottom; } public isCdvOpen(commitHash: string, compareWithHash: string | null) { return this.expandedCommit !== null && this.expandedCommit.commitHash === commitHash && this.expandedCommit.compareWithHash === compareWithHash; } private getCommitOrder(hash1: string, hash2: string) { if (this.commitLookup[hash1] > this.commitLookup[hash2]) { return { from: hash1, to: hash2 }; } else { return { from: hash2, to: hash1 }; } } private getFileViewType() { return this.gitRepos[this.currentRepo].fileViewType === GG.FileViewType.Default ? this.config.commitDetailsView.fileViewType : this.gitRepos[this.currentRepo].fileViewType; } private setFileViewType(type: GG.FileViewType) { this.gitRepos[this.currentRepo].fileViewType = type; this.saveRepoState(); } private changeFileViewType(type: GG.FileViewType) { const expandedCommit = this.expandedCommit, filesElem = document.getElementById('cdvFiles'); if (expandedCommit === null || expandedCommit.fileTree === null || expandedCommit.fileChanges === null || filesElem === null) return; GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); this.setFileViewType(type); const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash === null ? expandedCommit.commitHash : expandedCommit.compareWithHash); filesElem.innerHTML = generateFileViewHtml(expandedCommit.fileTree, expandedCommit.fileChanges, expandedCommit.lastViewedFile, expandedCommit.contextMenuOpen.fileView, type, commitOrder.to === UNCOMMITTED); this.makeCdvFileViewInteractive(); this.renderCdvFileViewTypeBtns(); } private makeCdvFileViewInteractive() { const getFileElemOfEventTarget = (target: EventTarget) => <HTMLElement>(<Element>target).closest('.fileTreeFileRecord'); const getFileOfFileElem = (fileChanges: ReadonlyArray<GG.GitFileChange>, fileElem: HTMLElement) => fileChanges[parseInt(fileElem.dataset.index!)]; const getCommitHashForFile = (file: GG.GitFileChange, expandedCommit: ExpandedCommit) => { const commit = this.commits[this.commitLookup[expandedCommit.commitHash]]; if (expandedCommit.compareWithHash !== null) { return this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash).to; } else if (commit.stash !== null && file.type === GG.GitFileStatus.Untracked) { return commit.stash.untrackedFilesHash!; } else { return expandedCommit.commitHash; } }; const triggerViewFileDiff = (file: GG.GitFileChange, fileElem: HTMLElement) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; let commit = this.commits[this.commitLookup[expandedCommit.commitHash]], fromHash: string, toHash: string, fileStatus = file.type; if (expandedCommit.compareWithHash !== null) { // Commit Comparison const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash); fromHash = commitOrder.from; toHash = commitOrder.to; } else if (commit.stash !== null) { // Stash Commit if (fileStatus === GG.GitFileStatus.Untracked) { fromHash = commit.stash.untrackedFilesHash!; toHash = commit.stash.untrackedFilesHash!; fileStatus = GG.GitFileStatus.Added; } else { fromHash = commit.stash.baseHash; toHash = expandedCommit.commitHash; } } else { // Single Commit fromHash = expandedCommit.commitHash; toHash = expandedCommit.commitHash; } this.cdvUpdateFileState(file, fileElem, true, true); sendMessage({ command: 'viewDiff', repo: this.currentRepo, fromHash: fromHash, toHash: toHash, oldFilePath: file.oldFilePath, newFilePath: file.newFilePath, type: fileStatus }); }; const triggerCopyFilePath = (file: GG.GitFileChange, absolute: boolean) => { sendMessage({ command: 'copyFilePath', repo: this.currentRepo, filePath: file.newFilePath, absolute: absolute }); }; const triggerResetFileToRevision = (file: GG.GitFileChange, fileElem: HTMLElement) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; const commitHash = getCommitHashForFile(file, expandedCommit); dialog.showConfirmation('Are you sure you want to reset <b><i>' + escapeHtml(file.newFilePath) + '</i></b> to it\'s state at commit <b><i>' + abbrevCommit(commitHash) + '</i></b>? Any uncommitted changes made to this file will be overwritten.', 'Yes, reset file', () => { runAction({ command: 'resetFileToRevision', repo: this.currentRepo, commitHash: commitHash, filePath: file.newFilePath }, 'Resetting file'); }, { type: TargetType.CommitDetailsView, hash: commitHash, elem: fileElem }); }; const triggerViewFileAtRevision = (file: GG.GitFileChange, fileElem: HTMLElement) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; this.cdvUpdateFileState(file, fileElem, true, true); sendMessage({ command: 'viewFileAtRevision', repo: this.currentRepo, hash: getCommitHashForFile(file, expandedCommit), filePath: file.newFilePath }); }; const triggerViewFileDiffWithWorkingFile = (file: GG.GitFileChange, fileElem: HTMLElement) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; this.cdvUpdateFileState(file, fileElem, null, true); sendMessage({ command: 'viewDiffWithWorkingFile', repo: this.currentRepo, hash: getCommitHashForFile(file, expandedCommit), filePath: file.newFilePath }); }; const triggerOpenFile = (file: GG.GitFileChange, fileElem: HTMLElement) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null) return; this.cdvUpdateFileState(file, fileElem, true, true); sendMessage({ command: 'openFile', repo: this.currentRepo, hash: getCommitHashForFile(file, expandedCommit), filePath: file.newFilePath }); }; addListenerToClass('fileTreeFolder', 'click', (e) => { let expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileTree === null || e.target === null) return; let sourceElem = <HTMLElement>(<Element>e.target).closest('.fileTreeFolder'); let parent = sourceElem.parentElement!; parent.classList.toggle('closed'); let isOpen = !parent.classList.contains('closed'); parent.children[0].children[0].innerHTML = isOpen ? SVG_ICONS.openFolder : SVG_ICONS.closedFolder; parent.children[1].classList.toggle('hidden'); alterFileTreeFolderOpen(expandedCommit.fileTree, decodeURIComponent(sourceElem.dataset.folderpath!), isOpen); this.saveState(); }); addListenerToClass('fileTreeRepo', 'click', (e) => { if (e.target === null) return; this.loadRepos(this.gitRepos, null, { repo: decodeURIComponent((<HTMLElement>(<Element>e.target).closest('.fileTreeRepo')).dataset.path!) }); }); addListenerToClass('fileTreeFile', 'click', (e) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileChanges === null || e.target === null) return; const sourceElem = <HTMLElement>(<Element>e.target).closest('.fileTreeFile'), fileElem = getFileElemOfEventTarget(e.target); if (!sourceElem.classList.contains('gitDiffPossible')) return; triggerViewFileDiff(getFileOfFileElem(expandedCommit.fileChanges, fileElem), fileElem); }); addListenerToClass('copyGitFile', 'click', (e) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileChanges === null || e.target === null) return; const fileElem = getFileElemOfEventTarget(e.target); triggerCopyFilePath(getFileOfFileElem(expandedCommit.fileChanges, fileElem), true); }); addListenerToClass('viewGitFileAtRevision', 'click', (e) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileChanges === null || e.target === null) return; const fileElem = getFileElemOfEventTarget(e.target); triggerViewFileAtRevision(getFileOfFileElem(expandedCommit.fileChanges, fileElem), fileElem); }); addListenerToClass('openGitFile', 'click', (e) => { const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileChanges === null || e.target === null) return; const fileElem = getFileElemOfEventTarget(e.target); triggerOpenFile(getFileOfFileElem(expandedCommit.fileChanges, fileElem), fileElem); }); addListenerToClass('fileTreeFileRecord', 'contextmenu', (e: Event) => { handledEvent(e); const expandedCommit = this.expandedCommit; if (expandedCommit === null || expandedCommit.fileChanges === null || e.target === null) return; const fileElem = getFileElemOfEventTarget(e.target); const file = getFileOfFileElem(expandedCommit.fileChanges, fileElem); const commitOrder = this.getCommitOrder(expandedCommit.commitHash, expandedCommit.compareWithHash === null ? expandedCommit.commitHash : expandedCommit.compareWithHash); const isUncommitted = commitOrder.to === UNCOMMITTED; GitGraphView.closeCdvContextMenuIfOpen(expandedCommit); expandedCommit.contextMenuOpen.fileView = parseInt(fileElem.dataset.index!); const target: ContextMenuTarget & CommitTarget = { type: TargetType.CommitDetailsView, hash: expandedCommit.commitHash, index: this.commitLookup[expandedCommit.commitHash], elem: fileElem }; const diffPossible = file.type === GG.GitFileStatus.Untracked || (file.additions !== null && file.deletions !== null); const fileExistsAtThisRevision = file.type !== GG.GitFileStatus.Deleted && !isUncommitted; const fileExistsAtThisRevisionAndDiffPossible = fileExistsAtThisRevision && diffPossible; const codeReviewInProgressAndNotReviewed = expandedCommit.codeReview !== null && expandedCommit.codeReview.remainingFiles.includes(file.newFilePath); const visibility = this.config.contextMenuActionsVisibility.commitDetailsViewFile; contextMenu.show([ [ { title: 'View Diff', visible: visibility.viewDiff && diffPossible, onClick: () => triggerViewFileDiff(file, fileElem) }, { title: 'View File at this Revision', visible: visibility.viewFileAtThisRevision && fileExistsAtThisRevisionAndDiffPossible, onClick: () => triggerViewFileAtRevision(file, fileElem) }, { title: 'View Diff with Working File', visible: visibility.viewDiffWithWorkingFile && fileExistsAtThisRevisionAndDiffPossible, onClick: () => triggerViewFileDiffWithWorkingFile(file, fileElem) }, { title: 'Open File', visible: visibility.openFile && file.type !== GG.GitFileStatus.Deleted, onClick: () => triggerOpenFile(file, fileElem) } ], [ { title: 'Mark as Reviewed', visible: visibility.markAsReviewed && codeReviewInProgressAndNotReviewed, onClick: () => this.cdvUpdateFileState(file, fileElem, true, false) }, { title: 'Mark as Not Reviewed', visible: visibility.markAsNotReviewed && expandedCommit.codeReview !== null && !codeReviewInProgressAndNotReviewed, onClick: () => this.cdvUpdateFileState(file, fileElem, false, false) } ], [ { title: 'Reset File to this Revision' + ELLIPSIS, visible: visibility.resetFileToThisRevision && fileExistsAtThisRevision && expandedCommit.compareWithHash === null, onClick: () => triggerResetFileToRevision(file, fileElem) } ], [ { title: 'Copy Absolute File Path to Clipboard', visible: visibility.copyAbsoluteFilePath, onClick: () => triggerCopyFilePath(file, true) }, { title: 'Copy Relative File Path to Clipboard', visible: visibility.copyRelativeFilePath, onClick: () => triggerCopyFilePath(file, false) } ] ], false, target, <MouseEvent>e, this.isCdvDocked() ? document.body : this.viewElem, () => { expandedCommit.contextMenuOpen.fileView = -1; }); }); } private renderCdvFileViewTypeBtns() { if (this.expandedCommit === null) return; let treeBtnElem = document.getElementById('cdvFileViewTypeTree'), listBtnElem = document.getElementById('cdvFileViewTypeList'); if (treeBtnElem === null || listBtnElem === null) return; let listView = this.getFileViewType() === GG.FileViewType.List; alterClass(treeBtnElem, CLASS_ACTIVE, !listView); alterClass(listBtnElem, CLASS_ACTIVE, listView); } private renderCdvExternalDiffBtn() { if (this.expandedCommit === null) return; const externalDiffBtnElem = document.getElementById('cdvExternalDiff'); if (externalDiffBtnElem === null) return; alterClass(externalDiffBtnElem, CLASS_ENABLED, this.gitConfig !== null && (this.gitConfig.diffTool !== null || this.gitConfig.guiDiffTool !== null)); const toolName = this.gitConfig !== null ? this.gitConfig.guiDiffTool !== null ? this.gitConfig.guiDiffTool : this.gitConfig.diffTool : null; externalDiffBtnElem.title = 'Open External Directory Diff' + (toolName !== null ? ' with "' + toolName + '"' : ''); } private static closeCdvContextMenuIfOpen(expandedCommit: ExpandedCommit) { if (expandedCommit.contextMenuOpen.summary || expandedCommit.contextMenuOpen.fileView > -1) { expandedCommit.contextMenuOpen.summary = false; expandedCommit.contextMenuOpen.fileView = -1; contextMenu.close(); } } /* Code Review */ public startCodeReview(commitHash: string, compareWithHash: string | null, codeReview: GG.CodeReview) { if (this.expandedCommit === null || this.expandedCommit.commitHash !== commitHash || this.expandedCommit.compareWithHash !== compareWithHash) return; this.saveAndRenderCodeReview(codeReview); } public endCodeReview() { if (this.expandedCommit === null || this.expandedCommit.codeReview === null) return; this.saveAndRenderCodeReview(null); } private saveAndRenderCodeReview(codeReview: GG.CodeReview | null) { let filesElem = document.getElementById('cdvFiles'); if (this.expandedCommit === null || this.expandedCommit.fileTree === null || filesElem === null) return; this.expandedCommit.codeReview = codeReview; setFileTreeReviewed(this.expandedCommit.fileTree, codeReview === null); this.saveState(); this.renderCodeReviewBtn(); updateFileTreeHtml(filesElem, this.expandedCommit.fileTree); } private renderCodeReviewBtn() { if (this.expandedCommit === null) return; let btnElem = document.getElementById('cdvCodeReview'); if (btnElem === null) return; let active = this.expandedCommit.codeReview !== null; alterClass(btnElem, CLASS_ACTIVE, active); btnElem.title = (active ? 'End' : 'Start') + ' Code Review'; } } /* Main */ const contextMenu = new ContextMenu(), dialog = new Dialog(), eventOverlay = new EventOverlay(); let loaded = false; window.addEventListener('load', () => { if (loaded) return; loaded = true; TextFormatter.registerCustomEmojiMappings(initialState.config.customEmojiShortcodeMappings); const viewElem = document.getElementById('view'); if (viewElem === null) return; const gitGraph = new GitGraphView(viewElem, VSCODE_API.getState()); const imageResizer = new ImageResizer(); /* Command Processing */ window.addEventListener('message', event => { const msg: GG.ResponseMessage = event.data; switch (msg.command) { case 'addRemote': refreshOrDisplayError(msg.error, 'Unable to Add Remote', true); break; case 'addTag': if (msg.pushToRemote !== null && msg.errors.length === 2 && msg.errors[0] === null && isExtensionErrorInfo(msg.errors[1], GG.ErrorInfoExtensionPrefix.PushTagCommitNotOnRemote)) { gitGraph.refresh(false); handleResponsePushTagCommitNotOnRemote(msg.repo, msg.tagName, [msg.pushToRemote], msg.commitHash, msg.errors[1]!); } else { refreshAndDisplayErrors(msg.errors, 'Unable to Add Tag'); } break; case 'applyStash': refreshOrDisplayError(msg.error, 'Unable to Apply Stash'); break; case 'branchFromStash': refreshOrDisplayError(msg.error, 'Unable to Create Branch from Stash'); break; case 'checkoutBranch': refreshAndDisplayErrors(msg.errors, 'Unable to Checkout Branch' + (msg.pullAfterwards !== null ? ' & Pull Changes' : '')); break; case 'checkoutCommit': refreshOrDisplayError(msg.error, 'Unable to Checkout Commit'); break; case 'cherrypickCommit': refreshAndDisplayErrors(msg.errors, 'Unable to Cherry Pick Commit'); break; case 'cleanUntrackedFiles': refreshOrDisplayError(msg.error, 'Unable to Clean Untracked Files'); break; case 'commitDetails': if (msg.commitDetails !== null) { gitGraph.showCommitDetails(msg.commitDetails, gitGraph.createFileTree(msg.commitDetails.fileChanges, msg.codeReview), msg.avatar, msg.codeReview, msg.codeReview !== null ? msg.codeReview.lastViewedFile : null, msg.refresh); } else { gitGraph.closeCommitDetails(true); dialog.showError('Unable to load Commit Details', msg.error, null, null); } break; case 'compareCommits': if (msg.error === null) { gitGraph.showCommitComparison(msg.commitHash, msg.compareWithHash, msg.fileChanges, gitGraph.createFileTree(msg.fileChanges, msg.codeReview), msg.codeReview, msg.codeReview !== null ? msg.codeReview.lastViewedFile : null, msg.refresh); } else { gitGraph.closeCommitComparison(true); dialog.showError('Unable to load Commit Comparison', msg.error, null, null); } break; case 'copyFilePath': finishOrDisplayError(msg.error, 'Unable to Copy File Path to Clipboard'); break; case 'copyToClipboard': finishOrDisplayError(msg.error, 'Unable to Copy ' + msg.type + ' to Clipboard'); break; case 'createArchive': finishOrDisplayError(msg.error, 'Unable to Create Archive', true); break; case 'createBranch': refreshAndDisplayErrors(msg.errors, 'Unable to Create Branch'); break; case 'createPullRequest': finishOrDisplayErrors(msg.errors, 'Unable to Create Pull Request', () => { if (msg.push) { gitGraph.refresh(false); } }, true); break; case 'deleteBranch': handleResponseDeleteBranch(msg); break; case 'deleteRemote': refreshOrDisplayError(msg.error, 'Unable to Delete Remote', true); break; case 'deleteRemoteBranch': refreshOrDisplayError(msg.error, 'Unable to Delete Remote Branch'); break; case 'deleteTag': refreshOrDisplayError(msg.error, 'Unable to Delete Tag'); break; case 'deleteUserDetails': finishOrDisplayErrors(msg.errors, 'Unable to Remove Git User Details', () => gitGraph.requestLoadConfig(), true); break; case 'dropCommit': refreshOrDisplayError(msg.error, 'Unable to Drop Commit'); break; case 'dropStash': refreshOrDisplayError(msg.error, 'Unable to Drop Stash'); break; case 'editRemote': refreshOrDisplayError(msg.error, 'Unable to Save Changes to Remote', true); break; case 'editUserDetails': finishOrDisplayErrors(msg.errors, 'Unable to Save Git User Details', () => gitGraph.requestLoadConfig(), true); break; case 'exportRepoConfig': refreshOrDisplayError(msg.error, 'Unable to Export Repository Configuration'); break; case 'fetch': refreshOrDisplayError(msg.error, 'Unable to Fetch from Remote(s)'); break; case 'fetchAvatar': imageResizer.resize(msg.image, (resizedImage) => { gitGraph.loadAvatar(msg.email, resizedImage); }); break; case 'fetchIntoLocalBranch': refreshOrDisplayError(msg.error, 'Unable to Fetch into Local Branch'); break; case 'loadCommits': gitGraph.processLoadCommitsResponse(msg); break; case 'loadConfig': gitGraph.processLoadConfig(msg); break; case 'loadRepoInfo': gitGraph.processLoadRepoInfoResponse(msg); break; case 'loadRepos': gitGraph.loadRepos(msg.repos, msg.lastActiveRepo, msg.loadViewTo); break; case 'merge': refreshOrDisplayError(msg.error, 'Unable to Merge ' + msg.actionOn); break; case 'openExtensionSettings': finishOrDisplayError(msg.error, 'Unable to Open Extension Settings'); break; case 'openExternalDirDiff': finishOrDisplayError(msg.error, 'Unable to Open External Directory Diff', true); break; case 'openExternalUrl': finishOrDisplayError(msg.error, 'Unable to Open External URL'); break; case 'openFile': finishOrDisplayError(msg.error, 'Unable to Open File'); break; case 'openTerminal': finishOrDisplayError(msg.error, 'Unable to Open Terminal', true); break; case 'popStash': refreshOrDisplayError(msg.error, 'Unable to Pop Stash'); break; case 'pruneRemote': refreshOrDisplayError(msg.error, 'Unable to Prune Remote'); break; case 'pullBranch': refreshOrDisplayError(msg.error, 'Unable to Pull Branch'); break; case 'pushBranch': refreshAndDisplayErrors(msg.errors, 'Unable to Push Branch', msg.willUpdateBranchConfig); break; case 'pushStash': refreshOrDisplayError(msg.error, 'Unable to Stash Uncommitted Changes'); break; case 'pushTag': if (msg.errors.length === 1 && isExtensionErrorInfo(msg.errors[0], GG.ErrorInfoExtensionPrefix.PushTagCommitNotOnRemote)) { handleResponsePushTagCommitNotOnRemote(msg.repo, msg.tagName, msg.remotes, msg.commitHash, msg.errors[0]!); } else { refreshAndDisplayErrors(msg.errors, 'Unable to Push Tag'); } break; case 'rebase': if (msg.error === null) { if (msg.interactive) { dialog.closeActionRunning(); } else { gitGraph.refresh(false); } } else { dialog.showError('Unable to Rebase current branch on ' + msg.actionOn, msg.error, null, null); } break; case 'refresh': gitGraph.refresh(false); break; case 'renameBranch': refreshOrDisplayError(msg.error, 'Unable to Rename Branch'); break; case 'resetFileToRevision': refreshOrDisplayError(msg.error, 'Unable to Reset File to Revision'); break; case 'resetToCommit': refreshOrDisplayError(msg.error, 'Unable to Reset to Commit'); break; case 'revertCommit': refreshOrDisplayError(msg.error, 'Unable to Revert Commit'); break; case 'setGlobalViewState': finishOrDisplayError(msg.error, 'Unable to save the Global View State'); break; case 'setWorkspaceViewState': finishOrDisplayError(msg.error, 'Unable to save the Workspace View State'); break; case 'startCodeReview': if (msg.error === null) { gitGraph.startCodeReview(msg.commitHash, msg.compareWithHash, msg.codeReview); } else { dialog.showError('Unable to Start Code Review', msg.error, null, null); } break; case 'tagDetails': if (msg.details !== null) { gitGraph.renderTagDetails(msg.tagName, msg.commitHash, msg.details); } else { dialog.showError('Unable to retrieve Tag Details', msg.error, null, null); } break; case 'updateCodeReview': if (msg.error !== null) { dialog.showError('Unable to update Code Review', msg.error, null, null); } break; case 'viewDiff': finishOrDisplayError(msg.error, 'Unable to View Diff'); break; case 'viewDiffWithWorkingFile': finishOrDisplayError(msg.error, 'Unable to View Diff with Working File'); break; case 'viewFileAtRevision': finishOrDisplayError(msg.error, 'Unable to View File at Revision'); break; case 'viewScm': finishOrDisplayError(msg.error, 'Unable to open the Source Control View'); break; } }); function handleResponseDeleteBranch(msg: GG.ResponseDeleteBranch) { if (msg.errors.length > 0 && msg.errors[0] !== null && msg.errors[0].includes('git branch -D')) { dialog.showConfirmation('The branch <b><i>' + escapeHtml(msg.branchName) + '</i></b> is not fully merged. Would you like to force delete it?', 'Yes, force delete branch', () => { runAction({ command: 'deleteBranch', repo: msg.repo, branchName: msg.branchName, forceDelete: true, deleteOnRemotes: msg.deleteOnRemotes }, 'Deleting Branch'); }, { type: TargetType.Repo }); } else { refreshAndDisplayErrors(msg.errors, 'Unable to Delete Branch'); } } function handleResponsePushTagCommitNotOnRemote(repo: string, tagName: string, remotes: string[], commitHash: string, error: string) { const remotesNotContainingCommit: string[] = parseExtensionErrorInfo(error, GG.ErrorInfoExtensionPrefix.PushTagCommitNotOnRemote); const html = '<span class="dialogAlert">' + SVG_ICONS.alert + 'Warning: Commit is not on Remote' + (remotesNotContainingCommit.length > 1 ? 's ' : ' ') + '</span><br>' + '<span class="messageContent">' + '<p style="margin:0 0 6px 0;">The tag <b><i>' + escapeHtml(tagName) + '</i></b> is on a commit that isn\'t on any known branch on the remote' + (remotesNotContainingCommit.length > 1 ? 's' : '') + ' ' + formatCommaSeparatedList(remotesNotContainingCommit.map((remote) => '<b><i>' + escapeHtml(remote) + '</i></b>')) + '.</p>' + '<p style="margin:0;">Would you like to proceed to push the tag to the remote' + (remotes.length > 1 ? 's' : '') + ' ' + formatCommaSeparatedList(remotes.map((remote) => '<b><i>' + escapeHtml(remote) + '</i></b>')) + ' anyway?</p>' + '</span>'; dialog.showForm(html, [{ type: DialogInputType.Checkbox, name: 'Always Proceed', value: false }], 'Proceed to Push', (values) => { if (<boolean>values[0]) { updateGlobalViewState('pushTagSkipRemoteCheck', true); } runAction({ command: 'pushTag', repo: repo, tagName: tagName, remotes: remotes, commitHash: commitHash, skipRemoteCheck: true }, 'Pushing Tag'); }, { type: TargetType.Repo }, 'Cancel', null, true); } function refreshOrDisplayError(error: GG.ErrorInfo, errorMessage: string, configChanges: boolean = false) { if (error === null) { gitGraph.refresh(false, configChanges); } else { dialog.showError(errorMessage, error, null, null); } } function refreshAndDisplayErrors(errors: GG.ErrorInfo[], errorMessage: string, configChanges: boolean = false) { const reducedErrors = reduceErrorInfos(errors); if (reducedErrors.error !== null) { dialog.showError(errorMessage, reducedErrors.error, null, null); } if (reducedErrors.partialOrCompleteSuccess) { gitGraph.refresh(false, configChanges); } else if (configChanges) { gitGraph.requestLoadConfig(); } } function finishOrDisplayError(error: GG.ErrorInfo, errorMessage: string, dismissActionRunning: boolean = false) { if (error !== null) { dialog.showError(errorMessage, error, null, null); } else if (dismissActionRunning) { dialog.closeActionRunning(); } } function finishOrDisplayErrors(errors: GG.ErrorInfo[], errorMessage: string, partialOrCompleteSuccessCallback: () => void, dismissActionRunning: boolean = false) { const reducedErrors = reduceErrorInfos(errors); finishOrDisplayError(reducedErrors.error, errorMessage, dismissActionRunning); if (reducedErrors.partialOrCompleteSuccess) { partialOrCompleteSuccessCallback(); } } function reduceErrorInfos(errors: GG.ErrorInfo[]) { let error: GG.ErrorInfo = null, partialOrCompleteSuccess = false; for (let i = 0; i < errors.length; i++) { if (errors[i] !== null) { error = error !== null ? error + '\n\n' + errors[i] : errors[i]; } else { partialOrCompleteSuccess = true; } } return { error: error, partialOrCompleteSuccess: partialOrCompleteSuccess }; } /** * Checks whether the given ErrorInfo has an ErrorInfoExtensionPrefix. * @param error The ErrorInfo to check. * @param prefix The ErrorInfoExtensionPrefix to test. * @returns TRUE => ErrorInfo has the ErrorInfoExtensionPrefix, FALSE => ErrorInfo doesn\'t have the ErrorInfoExtensionPrefix */ function isExtensionErrorInfo(error: GG.ErrorInfo, prefix: GG.ErrorInfoExtensionPrefix) { return error !== null && error.startsWith(prefix); } /** * Parses the JSON data from an ErrorInfo prefixed by the provided ErrorInfoExtensionPrefix. * @param error The ErrorInfo to parse. * @param prefix The ErrorInfoExtensionPrefix used by `error`. * @returns The parsed JSON data. */ function parseExtensionErrorInfo(error: string, prefix: GG.ErrorInfoExtensionPrefix) { return JSON.parse(error.substring(prefix.length)); } }); /* File Tree Methods (for the Commit Details & Comparison Views) */ function generateFileViewHtml(folder: FileTreeFolder, gitFiles: ReadonlyArray<GG.GitFileChange>, lastViewedFile: string | null, fileContextMenuOpen: number, type: GG.FileViewType, isUncommitted: boolean) { return type === GG.FileViewType.List ? generateFileListHtml(folder, gitFiles, lastViewedFile, fileContextMenuOpen, isUncommitted) : generateFileTreeHtml(folder, gitFiles, lastViewedFile, fileContextMenuOpen, isUncommitted, true); } function generateFileTreeHtml(folder: FileTreeFolder, gitFiles: ReadonlyArray<GG.GitFileChange>, lastViewedFile: string | null, fileContextMenuOpen: number, isUncommitted: boolean, topLevelFolder: boolean): string { const curFolderInfo = topLevelFolder || !initialState.config.commitDetailsView.fileTreeCompactFolders ? { folder: folder, name: folder.name, pathSeg: folder.name } : getCurrentFolderInfo(folder, folder.name, folder.name); const children = sortFolderKeys(curFolderInfo.folder).map((key) => { const cur = curFolderInfo.folder.contents[key]; return cur.type === 'folder' ? generateFileTreeHtml(cur, gitFiles, lastViewedFile, fileContextMenuOpen, isUncommitted, false) : generateFileTreeLeafHtml(cur.name, cur, gitFiles, lastViewedFile, fileContextMenuOpen, isUncommitted); }); return (topLevelFolder ? '' : '<li' + (curFolderInfo.folder.open ? '' : ' class="closed"') + ' data-pathseg="' + encodeURIComponent(curFolderInfo.pathSeg) + '"><span class="fileTreeFolder' + (curFolderInfo.folder.reviewed ? '' : ' pendingReview') + '" title="./' + escapeHtml(curFolderInfo.folder.folderPath) + '" data-folderpath="' + encodeURIComponent(curFolderInfo.folder.folderPath) + '"><span class="fileTreeFolderIcon">' + (curFolderInfo.folder.open ? SVG_ICONS.openFolder : SVG_ICONS.closedFolder) + '</span><span class="gitFolderName">' + escapeHtml(curFolderInfo.name) + '</span></span>') + '<ul class="fileTreeFolderContents' + (curFolderInfo.folder.open ? '' : ' hidden') + '">' + children.join('') + '</ul>' + (topLevelFolder ? '' : '</li>'); } function getCurrentFolderInfo(folder: FileTreeFolder, name: string, pathSeg: string): { folder: FileTreeFolder, name: string, pathSeg: string } { const keys = Object.keys(folder.contents); let child: FileTreeNode; return keys.length === 1 && (child = folder.contents[keys[0]]).type === 'folder' ? getCurrentFolderInfo(<FileTreeFolder>child, name + ' / ' + child.name, pathSeg + '/' + child.name) : { folder: folder, name: name, pathSeg: pathSeg }; } function generateFileListHtml(folder: FileTreeFolder, gitFiles: ReadonlyArray<GG.GitFileChange>, lastViewedFile: string | null, fileContextMenuOpen: number, isUncommitted: boolean) { const sortLeaves = (folder: FileTreeFolder, folderPath: string) => { let keys = sortFolderKeys(folder); let items: { relPath: string, leaf: FileTreeLeaf }[] = []; for (let i = 0; i < keys.length; i++) { let cur = folder.contents[keys[i]]; let relPath = (folderPath !== '' ? folderPath + '/' : '') + cur.name; if (cur.type === 'folder') { items = items.concat(sortLeaves(cur, relPath)); } else { items.push({ relPath: relPath, leaf: cur }); } } return items; }; let sortedLeaves = sortLeaves(folder, ''); let html = ''; for (let i = 0; i < sortedLeaves.length; i++) { html += generateFileTreeLeafHtml(sortedLeaves[i].relPath, sortedLeaves[i].leaf, gitFiles, lastViewedFile, fileContextMenuOpen, isUncommitted); } return '<ul class="fileTreeFolderContents">' + html + '</ul>'; } function generateFileTreeLeafHtml(name: string, leaf: FileTreeLeaf, gitFiles: ReadonlyArray<GG.GitFileChange>, lastViewedFile: string | null, fileContextMenuOpen: number, isUncommitted: boolean) { let encodedName = encodeURIComponent(name), escapedName = escapeHtml(name); if (leaf.type === 'file') { const fileTreeFile = gitFiles[leaf.index]; const textFile = fileTreeFile.additions !== null && fileTreeFile.deletions !== null; const diffPossible = fileTreeFile.type === GG.GitFileStatus.Untracked || textFile; const changeTypeMessage = GIT_FILE_CHANGE_TYPES[fileTreeFile.type] + (fileTreeFile.type === GG.GitFileStatus.Renamed ? ' (' + escapeHtml(fileTreeFile.oldFilePath) + ' → ' + escapeHtml(fileTreeFile.newFilePath) + ')' : ''); return '<li data-pathseg="' + encodedName + '"><span class="fileTreeFileRecord' + (leaf.index === fileContextMenuOpen ? ' ' + CLASS_CONTEXT_MENU_ACTIVE : '') + '" data-index="' + leaf.index + '"><span class="fileTreeFile' + (diffPossible ? ' gitDiffPossible' : '') + (leaf.reviewed ? '' : ' ' + CLASS_PENDING_REVIEW) + '" title="' + (diffPossible ? 'Click to View Diff' : 'Unable to View Diff' + (fileTreeFile.type !== GG.GitFileStatus.Deleted ? ' (this is a binary file)' : '')) + ' • ' + changeTypeMessage + '"><span class="fileTreeFileIcon">' + SVG_ICONS.file + '</span><span class="gitFileName ' + fileTreeFile.type + '">' + escapedName + '</span></span>' + (initialState.config.enhancedAccessibility ? '<span class="fileTreeFileType" title="' + changeTypeMessage + '">' + fileTreeFile.type + '</span>' : '') + (fileTreeFile.type !== GG.GitFileStatus.Added && fileTreeFile.type !== GG.GitFileStatus.Untracked && fileTreeFile.type !== GG.GitFileStatus.Deleted && textFile ? '<span class="fileTreeFileAddDel">(<span class="fileTreeFileAdd" title="' + fileTreeFile.additions + ' addition' + (fileTreeFile.additions !== 1 ? 's' : '') + '">+' + fileTreeFile.additions + '</span>|<span class="fileTreeFileDel" title="' + fileTreeFile.deletions + ' deletion' + (fileTreeFile.deletions !== 1 ? 's' : '') + '">-' + fileTreeFile.deletions + '</span>)</span>' : '') + (fileTreeFile.newFilePath === lastViewedFile ? '<span id="cdvLastFileViewed" title="Last File Viewed">' + SVG_ICONS.eyeOpen + '</span>' : '') + '<span class="copyGitFile fileTreeFileAction" title="Copy Absolute File Path to Clipboard">' + SVG_ICONS.copy + '</span>' + (fileTreeFile.type !== GG.GitFileStatus.Deleted ? (diffPossible && !isUncommitted ? '<span class="viewGitFileAtRevision fileTreeFileAction" title="View File at this Revision">' + SVG_ICONS.commit + '</span>' : '') + '<span class="openGitFile fileTreeFileAction" title="Open File">' + SVG_ICONS.openFile + '</span>' : '' ) + '</span></li>'; } else { return '<li data-pathseg="' + encodedName + '"><span class="fileTreeRepo" data-path="' + encodeURIComponent(leaf.path) + '" title="Click to View Repository"><span class="fileTreeRepoIcon">' + SVG_ICONS.closedFolder + '</span>' + escapedName + '</span></li>'; } } function alterFileTreeFolderOpen(folder: FileTreeFolder, folderPath: string, open: boolean) { let path = folderPath.split('/'), i, cur = folder; for (i = 0; i < path.length; i++) { if (typeof cur.contents[path[i]] !== 'undefined') { cur = <FileTreeFolder>cur.contents[path[i]]; if (i === path.length - 1) cur.open = open; } else { return; } } } function alterFileTreeFileReviewed(folder: FileTreeFolder, filePath: string, reviewed: boolean) { let path = filePath.split('/'), i, cur = folder, folders = [folder]; for (i = 0; i < path.length; i++) { if (typeof cur.contents[path[i]] !== 'undefined') { if (i < path.length - 1) { cur = <FileTreeFolder>cur.contents[path[i]]; folders.push(cur); } else { (<FileTreeFile>cur.contents[path[i]]).reviewed = reviewed; } } else { break; } } // Recalculate whether each of the folders leading to the file are now reviewed (deepest first). for (i = folders.length - 1; i >= 0; i--) { let keys = Object.keys(folders[i].contents), entireFolderReviewed = true; for (let j = 0; j < keys.length; j++) { let cur = folders[i].contents[keys[j]]; if ((cur.type === 'folder' || cur.type === 'file') && !cur.reviewed) { entireFolderReviewed = false; break; } } folders[i].reviewed = entireFolderReviewed; } } function setFileTreeReviewed(folder: FileTreeFolder, reviewed: boolean) { folder.reviewed = reviewed; let keys = Object.keys(folder.contents); for (let i = 0; i < keys.length; i++) { let cur = folder.contents[keys[i]]; if (cur.type === 'folder') { setFileTreeReviewed(cur, reviewed); } else if (cur.type === 'file') { cur.reviewed = reviewed; } } } function calcFileTreeFoldersReviewed(folder: FileTreeFolder) { const calc = (folder: FileTreeFolder) => { let reviewed = true; let keys = Object.keys(folder.contents); for (let i = 0; i < keys.length; i++) { let cur = folder.contents[keys[i]]; if ((cur.type === 'folder' && !calc(cur)) || (cur.type === 'file' && !cur.reviewed)) reviewed = false; } folder.reviewed = reviewed; return reviewed; }; calc(folder); } function updateFileTreeHtml(elem: HTMLElement, folder: FileTreeFolder) { let ul = getChildUl(elem); if (ul === null) return; for (let i = 0; i < ul.children.length; i++) { let li = <HTMLLIElement>ul.children[i]; let pathSeg = decodeURIComponent(li.dataset.pathseg!); let child = getChildByPathSegment(folder, pathSeg); if (child.type === 'folder') { alterClass(<HTMLSpanElement>li.children[0], CLASS_PENDING_REVIEW, !child.reviewed); updateFileTreeHtml(li, child); } else if (child.type === 'file') { alterClass(<HTMLSpanElement>li.children[0].children[0], CLASS_PENDING_REVIEW, !child.reviewed); } } } function updateFileTreeHtmlFileReviewed(elem: HTMLElement, folder: FileTreeFolder, filePath: string) { let path = filePath; const update = (elem: HTMLElement, folder: FileTreeFolder) => { let ul = getChildUl(elem); if (ul === null) return; for (let i = 0; i < ul.children.length; i++) { let li = <HTMLLIElement>ul.children[i]; let pathSeg = decodeURIComponent(li.dataset.pathseg!); if (path === pathSeg || path.startsWith(pathSeg + '/')) { let child = getChildByPathSegment(folder, pathSeg); if (child.type === 'folder') { alterClass(<HTMLSpanElement>li.children[0], CLASS_PENDING_REVIEW, !child.reviewed); path = path.substring(pathSeg.length + 1); update(li, child); } else if (child.type === 'file') { alterClass(<HTMLSpanElement>li.children[0].children[0], CLASS_PENDING_REVIEW, !child.reviewed); } break; } } }; update(elem, folder); } function getFilesInTree(folder: FileTreeFolder, gitFiles: ReadonlyArray<GG.GitFileChange>) { let files: string[] = []; const scanFolder = (folder: FileTreeFolder) => { let keys = Object.keys(folder.contents); for (let i = 0; i < keys.length; i++) { let cur = folder.contents[keys[i]]; if (cur.type === 'folder') { scanFolder(cur); } else if (cur.type === 'file') { files.push(gitFiles[cur.index].newFilePath); } } }; scanFolder(folder); return files; } function sortFolderKeys(folder: FileTreeFolder) { let keys = Object.keys(folder.contents); keys.sort((a, b) => folder.contents[a].type !== 'file' && folder.contents[b].type === 'file' ? -1 : folder.contents[a].type === 'file' && folder.contents[b].type !== 'file' ? 1 : folder.contents[a].name.localeCompare(folder.contents[b].name)); return keys; } function getChildByPathSegment(folder: FileTreeFolder, pathSeg: string) { let cur: FileTreeNode = folder, comps = pathSeg.split('/'); for (let i = 0; i < comps.length; i++) { cur = (<FileTreeFolder>cur).contents[comps[i]]; } return cur; } /* Repository State Helpers */ function getCommitOrdering(repoValue: GG.RepoCommitOrdering): GG.CommitOrdering { switch (repoValue) { case GG.RepoCommitOrdering.Default: return initialState.config.commitOrdering; case GG.RepoCommitOrdering.Date: return GG.CommitOrdering.Date; case GG.RepoCommitOrdering.AuthorDate: return GG.CommitOrdering.AuthorDate; case GG.RepoCommitOrdering.Topological: return GG.CommitOrdering.Topological; } } function getShowRemoteBranches(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.showRemoteBranches : repoValue === GG.BooleanOverride.Enabled; } function getShowStashes(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.showStashes : repoValue === GG.BooleanOverride.Enabled; } function getShowTags(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.showTags : repoValue === GG.BooleanOverride.Enabled; } function getIncludeCommitsMentionedByReflogs(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.includeCommitsMentionedByReflogs : repoValue === GG.BooleanOverride.Enabled; } function getOnlyFollowFirstParent(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.onlyFollowFirstParent : repoValue === GG.BooleanOverride.Enabled; } function getOnRepoLoadShowCheckedOutBranch(repoValue: GG.BooleanOverride) { return repoValue === GG.BooleanOverride.Default ? initialState.config.onRepoLoad.showCheckedOutBranch : repoValue === GG.BooleanOverride.Enabled; } function getOnRepoLoadShowSpecificBranches(repoValue: string[] | null) { return repoValue === null ? initialState.config.onRepoLoad.showSpecificBranches : repoValue; } /* Miscellaneous Helper Methods */ function haveFilesChanged(oldFiles: ReadonlyArray<GG.GitFileChange> | null, newFiles: ReadonlyArray<GG.GitFileChange> | null) { if ((oldFiles === null) !== (newFiles === null)) { return true; } else if (oldFiles === null && newFiles === null) { return false; } else { return !arraysEqual(oldFiles!, newFiles!, (a, b) => a.additions === b.additions && a.deletions === b.deletions && a.newFilePath === b.newFilePath && a.oldFilePath === b.oldFilePath && a.type === b.type); } } function abbrevCommit(commitHash: string) { return commitHash.substring(0, 8); } function getRepoDropdownOptions(repos: Readonly<GG.GitRepoSet>) { const repoPaths = getSortedRepositoryPaths(repos, initialState.config.repoDropdownOrder); const paths: string[] = [], names: string[] = [], distinctNames: string[] = [], firstSep: number[] = []; const resolveAmbiguous = (indexes: number[]) => { // Find ambiguous names within indexes let firstOccurrence: { [name: string]: number } = {}, ambiguous: { [name: string]: number[] } = {}; for (let i = 0; i < indexes.length; i++) { let name = distinctNames[indexes[i]]; if (typeof firstOccurrence[name] === 'number') { // name is ambiguous if (typeof ambiguous[name] === 'undefined') { // initialise ambiguous array with the first occurrence ambiguous[name] = [firstOccurrence[name]]; } ambiguous[name].push(indexes[i]); // append current ambiguous index } else { firstOccurrence[name] = indexes[i]; // set the first occurrence of the name } } let ambiguousNames = Object.keys(ambiguous); for (let i = 0; i < ambiguousNames.length; i++) { // For each ambiguous name, resolve the ambiguous indexes let ambiguousIndexes = ambiguous[ambiguousNames[i]], retestIndexes = []; for (let j = 0; j < ambiguousIndexes.length; j++) { let ambiguousIndex = ambiguousIndexes[j]; let nextSep = paths[ambiguousIndex].lastIndexOf('/', paths[ambiguousIndex].length - distinctNames[ambiguousIndex].length - 2); if (firstSep[ambiguousIndex] < nextSep) { // prepend the addition path and retest distinctNames[ambiguousIndex] = paths[ambiguousIndex].substring(nextSep + 1); retestIndexes.push(ambiguousIndex); } else { distinctNames[ambiguousIndex] = paths[ambiguousIndex]; } } if (retestIndexes.length > 1) { // If there are 2 or more indexes that may be ambiguous resolveAmbiguous(retestIndexes); } } }; // Initialise recursion const indexes = []; for (let i = 0; i < repoPaths.length; i++) { firstSep.push(repoPaths[i].indexOf('/')); const repo = repos[repoPaths[i]]; if (repo.name) { // A name has been set for the repository paths.push(repoPaths[i]); names.push(repo.name); distinctNames.push(repo.name); } else if (firstSep[i] === repoPaths[i].length - 1 || firstSep[i] === -1) { // Path has no slashes, or a single trailing slash ==> use the path as the name paths.push(repoPaths[i]); names.push(repoPaths[i]); distinctNames.push(repoPaths[i]); } else { paths.push(repoPaths[i].endsWith('/') ? repoPaths[i].substring(0, repoPaths[i].length - 1) : repoPaths[i]); // Remove trailing slash if it exists let name = paths[i].substring(paths[i].lastIndexOf('/') + 1); names.push(name); distinctNames.push(name); indexes.push(i); } } resolveAmbiguous(indexes); const options: DropdownOption[] = []; for (let i = 0; i < repoPaths.length; i++) { let hint; if (names[i] === distinctNames[i]) { // Name is distinct, no hint needed hint = ''; } else { // Hint path is the prefix of the distinctName before the common suffix with name let hintPath = distinctNames[i].substring(0, distinctNames[i].length - names[i].length - 1); // Keep two informative directories let hintComps = hintPath.split('/'); let keepDirs = hintComps[0] !== '' ? 2 : 3; if (hintComps.length > keepDirs) hintComps.splice(keepDirs, hintComps.length - keepDirs, '...'); // Construct the hint hint = (distinctNames[i] !== paths[i] ? '.../' : '') + hintComps.join('/'); } options.push({ name: names[i], value: repoPaths[i], hint: hint }); } return options; } function runAction(msg: GG.RequestMessage, action: string) { dialog.showActionRunning(action); sendMessage(msg); } function getBranchLabels(heads: ReadonlyArray<string>, remotes: ReadonlyArray<GG.GitCommitRemote>) { let headLabels: { name: string; remotes: string[] }[] = [], headLookup: { [name: string]: number } = {}, remoteLabels: ReadonlyArray<GG.GitCommitRemote>; for (let i = 0; i < heads.length; i++) { headLabels.push({ name: heads[i], remotes: [] }); headLookup[heads[i]] = i; } if (initialState.config.referenceLabels.combineLocalAndRemoteBranchLabels) { let remainingRemoteLabels = []; for (let i = 0; i < remotes.length; i++) { if (remotes[i].remote !== null) { // If the remote of the remote branch ref is known let branchName = remotes[i].name.substring(remotes[i].remote!.length + 1); if (typeof headLookup[branchName] === 'number') { headLabels[headLookup[branchName]].remotes.push(remotes[i].remote!); continue; } } remainingRemoteLabels.push(remotes[i]); } remoteLabels = remainingRemoteLabels; } else { remoteLabels = remotes; } return { heads: headLabels, remotes: remoteLabels }; } function findCommitElemWithId(elems: HTMLCollectionOf<HTMLElement>, id: number | null) { if (id === null) return null; let findIdStr = id.toString(); for (let i = 0; i < elems.length; i++) { if (findIdStr === elems[i].dataset.id) return elems[i]; } return null; } function generateSignatureHtml(signature: GG.GitSignature) { return '<span class="signatureInfo ' + signature.status + '" title="' + GIT_SIGNATURE_STATUS_DESCRIPTIONS[signature.status] + ':' + ' Signed by ' + escapeHtml(signature.signer !== '' ? signature.signer : '<Unknown>') + ' (GPG Key Id: ' + escapeHtml(signature.key !== '' ? signature.key : '<Unknown>') + ')">' + (signature.status === GG.GitSignatureStatus.GoodAndValid ? SVG_ICONS.passed : signature.status === GG.GitSignatureStatus.Bad ? SVG_ICONS.failed : SVG_ICONS.inconclusive) + '</span>'; } function closeDialogAndContextMenu() { if (dialog.isOpen()) dialog.close(); if (contextMenu.isOpen()) contextMenu.close(); }
the_stack
type PromiseFactory<T> = () => Promise<T>; type PromiseCallback = (value: any) => void; interface QueueItem { factory: PromiseFactory<unknown>; resolve: PromiseCallback; reject: PromiseCallback; } interface IPromiseQueue { add<T>(promiseFactory: PromiseFactory<T>): Promise<T>; addAll<T>(...promiseFactory: PromiseFactory<T>[]): Promise<T>[]; } interface ModelConfig< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorConstructionOptions, TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext> > { language: string | undefined; scheme: string | undefined; directory: string | undefined; basename: string | undefined; extension: string | undefined; createDefaultDir: ( context: TContext, extender: TExtender, ) => string; createExtenderModel: ( context: TContext, extender: TExtender, options: PrimeFaces.widget.ExtMonacoEditor.CreateModelOptions<TEditorOpts> ) => import("monaco-editor").editor.ITextModel | undefined; } interface DiffEditorCustomInitData { originalModel: import("monaco-editor").editor.ITextModel; modifiedModel: import("monaco-editor").editor.ITextModel; } interface EditorInitData<TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TCustomArgs> { custom: TCustomArgs; options: TEditorOpts; } interface IframeRenderData { scrollTop: number; value: string; } interface IframeDiffRenderData extends IframeRenderData { originalScrollTop: number; originalValue: string; } interface RenderArgs< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorConstructionOptions, TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext>, TCustomArgs > { custom: TCustomArgs, extender: TExtender; options: TEditorOpts; wasLibLoaded: boolean; } interface RenderedArgs< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorConstructionOptions, TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext>, TCustomArgs > extends RenderArgs<TEditor, TEditorOpts, TContext, TExtender, TCustomArgs> { editor: TEditor; } interface Helper { assign: typeof Object.assign; createDiffEditorInitData: < TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoDiffEditorContext, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderDiffEditor<TContext> >( context: TContext, extender: TExtender, originalValue: string, modifiedValue: string, wasLibLoaded: boolean ) => Promise<EditorInitData< import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions, DiffEditorCustomInitData >>; createEditorConstructionOptions: < TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoCodeEditorContext, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderCodeEditor<TContext> >( context: TContext, extender: TExtender, editorValue: string, wasLibLoaded: boolean ) => Promise<import("monaco-editor").editor.IStandaloneEditorConstructionOptions>; createModel: < TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorConstructionOptions, TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext> >( context: TContext, editorOptions: TEditorOpts, extender: TExtender, value: string, modelConfig: ModelConfig<TEditor, TEditorOpts, TContext, TExtender>, ) => import("monaco-editor").editor.ITextModel; defineCustomThemes(customThemes: Record<string, import("monaco-editor").editor.IStandaloneThemeData> | undefined): void; endsWith: (string: any, suffix: any) => boolean; getFacesResourceUri: () => string; getMonacoResource: (resource: string, queryParams?: Record<string, number | string | string[]>) => string; getScript: (url: string) => Promise<void>; getScriptName: (moduleId: string, label: string) => string; globalEval: (script: string, nonce?: string) => void; invokeMonaco: < TEditor extends import("monaco-editor").editor.IEditor, K extends PrimeFaces.MatchingKeys<TEditor, (...args: never[]) => unknown> >( editor: TEditor, method: K, args: PrimeFaces.widget.ExtMonacoEditor.ParametersIfFn<TEditor[K]> ) => Promise<Awaited<PrimeFaces.widget.ExtMonacoEditor.ReturnTypeIfFn<TEditor[K]>>>; invokeMonacoScript: <TEditor extends import("monaco-editor").editor.IEditor, TRet, TArgs extends any[]>( editor: TEditor, script: ((editor: TEditor, ...args: TArgs) => TRet) | string, args: TArgs, evalFn: (script: string) => void ) => Promise<Awaited<TRet>>; isMonacoMessage: (value: unknown) => value is MonacoMessage; isNotNullOrUndefined: <T>(x: T | null | undefined) => x is T; isNullOrUndefined: (x: unknown) => x is null | undefined; loadEditorLib: ( options: Partial<PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<import("monaco-editor").editor.IEditorOptions>>, forceLibReload: boolean ) => Promise<boolean>; loadExtender: < TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TContext extends PrimeFaces.widget.ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends PrimeFaces.widget.ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext> >( editor: TEditor | undefined, options: Partial<PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<TEditorOpts>>, context: TContext | undefined ) => Partial<TExtender>; loadLanguage: ( options: Partial<PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<import("monaco-editor").editor.IEditorOptions>> ) => Promise<{ forceLibReload: boolean; localeUrl: string; }>; parseSimpleQuery: (query: string) => Record<string, string | undefined>; resolveLocaleUrl: ( options: Partial<PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<import("monaco-editor").editor.IEditorOptions>> ) => string; BaseEditorDefaults: PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<import("monaco-editor").editor.IEditorOptions>; DefaultThemeData: import("monaco-editor").editor.IStandaloneThemeData; FramedDiffEditorDefaults: PrimeFaces.widget.ExtMonacoDiffEditorFramedCfgBase; FramedEditorDefaults: PrimeFaces.widget.ExtMonacoCodeEditorFramedCfgBase; InlineDiffEditorDefaults: PrimeFaces.widget.ExtMonacoDiffEditorInlineCfgBase; InlineEditorDefaults: PrimeFaces.widget.ExtMonacoCodeEditorInlineCfgBase; } interface PromiseHook<T> { resolve: (widget: T) => void; reject: (reason: any) => void; } declare class ExtMonacoEditorBase< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TCfg extends PrimeFaces.widget.ExtMonacoBaseEditorCfg<TEditorOpts> > extends PrimeFaces.widget.ExtMonacoBaseEditor<TEditor, TEditorOpts, TCfg> { _editorValue: string | undefined; _onDone: PromiseHook<this>[] | undefined; _input: JQuery | undefined; _editorContainer: JQuery | undefined; _init(cfg: PrimeFaces.PartialWidgetCfg<TCfg>, defaults: Partial<TCfg>): void; _bindEvents(): void; _fireEvent(eventName: string, ...params: any[]): void; _listSupportedEvents(): string[]; _rejectOnDone(): void; _supportsEvent(eventName: string): boolean; _onInitSuccess(): Promise<void>; _onInitError(error: unknown): void; } interface Window { monacoModule: { helper: Helper, PromiseQueue: new () => IPromiseQueue; ExtMonacoEditorBase: typeof ExtMonacoEditorBase; }, } // == Post message events interface MonacoMessage { payload: MonacoMessagePayload; instanceId: number; } interface MonacoMessagePayloadType<K extends string, T> { kind: K; data: T; } interface InitBaseMessageData { facesResourceUri: string, id: string; nonce: string | undefined; resolvedLocaleUrl: string; resourceUrlExtension: string; scrollTop: number; supportedEvents: string[]; value: string; version: string; } interface InitMessageData extends InitBaseMessageData { options: Partial<PrimeFaces.widget.ExtMonacoCodeEditorFramedCfgBase>, } interface InitDiffMessageData extends InitMessageData { options: Partial<PrimeFaces.widget.ExtMonacoDiffEditorFramedCfgBase>, originalScrollTop: number; originalValue: string; } type ResponseMessageData = | { success: true; value: any; messageId: number; } | { success: false; error: string; messageId: number; }; type InvokeMonacoMessageData< TEditor extends import("monaco-editor").editor.IEditor, K extends PrimeFaces.MatchingKeys< TEditor, (...args: never[]) => unknown > = PrimeFaces.MatchingKeys<TEditor, (...args: never[]) => unknown> > = { args: PrimeFaces.widget.ExtMonacoEditor.ParametersIfFn<TEditor[K]>; messageId: number; method: K; } type InvokeMonacoScriptData = { script: string; args: any[]; messageId: number; }; type BindEventsMessageData = { }; type ValueChangeMessageData = { value: string; changes: import("monaco-editor").editor.IModelContentChangedEvent; }; type ScrollChangeMessageData = { scrollLeft: number; scrollTop: number; }; type DomEventMessageData = { name: string; data: string; } type AfterInitMessageData = { success: true } | { success: false, error: string; }; type MonacoMessagePayload = // When the iframe load event was triggered and the iframe is now ready | MonacoMessagePayloadType<"load", undefined> // When the widget was created and the editor needs to be rendered | MonacoMessagePayloadType<"init", InitMessageData> // When the widget was created and the diff editor needs to be rendered | MonacoMessagePayloadType<"initDiff", InitDiffMessageData> // When the widget was destroyed | MonacoMessagePayloadType<"destroy", undefined> // When the event listeners should be added to the Monaco editor | MonacoMessagePayloadType<"bindEvents", BindEventsMessageData> // When the iframe controller responds to a message sent by the widget | MonacoMessagePayloadType<"response", ResponseMessageData> // When the invokeMonaco method was called on the widget | MonacoMessagePayloadType<"invokeMonaco", InvokeMonacoMessageData<import("monaco-editor").editor.IStandaloneCodeEditor>> // When the invokeMonaco method was called on the widget | MonacoMessagePayloadType<"invokeMonacoDiff", InvokeMonacoMessageData<import("monaco-editor").editor.IStandaloneDiffEditor>> // When the invokeMonacoScript method was called on the widget | MonacoMessagePayloadType<"invokeMonacoScript", InvokeMonacoScriptData> // When the value of the Monaco editor changed | MonacoMessagePayloadType<"valueChange", ValueChangeMessageData> // When the value of the original Monaco editor changed (for the diff editor) | MonacoMessagePayloadType<"originalValueChange", ValueChangeMessageData> // When the scroll position of the Monaco editor changed | MonacoMessagePayloadType<"scrollChange", ScrollChangeMessageData> // When the scroll position of the original Monaco editor changed (for the diff editor) | MonacoMessagePayloadType<"originalScrollChange", ScrollChangeMessageData> // When a DOM event (blur / focus / mousemove etc.) occurred on the Monaco editor | MonacoMessagePayloadType<"domEvent", DomEventMessageData> // After the editor was rendered | MonacoMessagePayloadType<"afterInit", AfterInitMessageData> ;
the_stack
import React from "react"; import styles from "./DetailThread.module.css"; import * as ConnectionManager from "../../../connection/connectionManager"; import {Button, CircularProgress, Typography} from "@mui/material"; import { Conversation, ConversationItem, LinkedConversation, MessageItem, MessageModifier, QueuedFile } from "../../../data/blocks"; import MessageList from "./MessageList"; import MessageInput from "./MessageInput"; import { generateAttachmentLocalID, generateMessageLocalID, getFallbackTitle, getMemberTitle, isConversationItemMessage, isModifierStatusUpdate, isModifierSticker, isModifierTapback } from "../../../util/conversationUtils"; import {ConversationItemType, MessageError, MessageStatusCode} from "../../../data/stateCodes"; import {DetailFrame} from "../master/DetailFrame"; import EventEmitter from "../../../util/eventEmitter"; import {playSoundMessageOut} from "../../../util/soundUtils"; import {appleServiceAppleMessage} from "../../../data/appleConstants"; import {getNotificationUtils} from "shared/util/notificationUtils"; import localMessageCache from "shared/util/localMessageCacheUtils"; import ConversationTarget from "shared/data/conversationTarget"; type HistoryLoadState = "idle" | "loading" | "complete"; interface Props { conversation: Conversation; } interface State { display: Display; unconfirmedMessages: MessageItem[]; title?: string; message: string; attachments: QueuedFile[]; historyLoadState: HistoryLoadState; isFaceTimeSupported: boolean; } enum DisplayType { Loading, Error, Messages } type DisplayMessages = { type: DisplayType.Messages; data: ConversationItem[]; }; type Display = { type: DisplayType.Loading | DisplayType.Error; } | DisplayMessages; export default class DetailThread extends React.Component<Props, State> { readonly dragDropRef = React.createRef<HTMLDivElement>(); readonly messageSubmitEmitter = new EventEmitter(); state: Readonly<State> = { display: {type: DisplayType.Loading}, unconfirmedMessages: [], title: getFallbackTitle(this.props.conversation), message: "", attachments: [], historyLoadState: "idle", isFaceTimeSupported: false }; private handleMessageChange(messageText: string) { //Updating the message input this.setState({message: messageText}); } private applyMessageError(error: MessageError, localID: number) { this.setState((prevState) => { //Ignoring if there are no messages if(prevState.display.type !== DisplayType.Messages) return null; //Updating the message's error state const pendingItems = [...prevState.display.data]; const itemIndex = pendingItems.findIndex((item) => item.localID === localID); if(itemIndex !== -1) { pendingItems[itemIndex] = { ...pendingItems[itemIndex], error: error } as MessageItem; } return {display: {type: DisplayType.Messages, data: pendingItems}}; }); } private handleMessageSubmit(messageText: string, queuedFiles: QueuedFile[]) { //Ignoring if there are no messages if(this.state.display.type !== DisplayType.Messages) return; const conversationTarget: ConversationTarget = !this.props.conversation.localOnly ? { type: "linked", guid: this.props.conversation.guid } : { type: "unlinked", members: this.props.conversation.members, service: this.props.conversation.service }; const addedItems: MessageItem[] = []; //Handling the text message messageText = messageText.trim(); if(messageText !== "") { //Clearing the message input this.setState({message: ""}); //Creating the message and adding it to the chat const message: MessageItem = { itemType: ConversationItemType.Message, localID: generateMessageLocalID(), serverID: undefined, guid: undefined, chatGuid: !this.props.conversation.localOnly ? this.props.conversation.guid : undefined, chatLocalID: this.props.conversation.localID, date: new Date(), text: messageText, subject: undefined, sender: undefined, attachments: [], stickers: [], tapbacks: [], sendStyle: undefined, status: MessageStatusCode.Unconfirmed, error: undefined, statusDate: undefined }; //Sending the message ConnectionManager.sendMessage(conversationTarget, messageText) .catch((error: MessageError) => this.applyMessageError(error, message.localID!)); //Adding the item to the added items list addedItems.push(message); } //Handling attachments if(queuedFiles.length > 0) { //Clearing the attachments input this.setState({attachments: []}); const messages = queuedFiles.map((file) => { return { itemType: ConversationItemType.Message, localID: generateMessageLocalID(), serverID: undefined, guid: undefined, chatGuid: !this.props.conversation.localOnly ? this.props.conversation.guid : undefined, chatLocalID: this.props.conversation.localID, date: new Date(), text: undefined, subject: undefined, sender: undefined, attachments: [{ localID: file.id, name: file.file.name, type: file.file.type, size: file.file.size, data: file.file }], stickers: [], tapbacks: [], sendStyle: undefined, status: MessageStatusCode.Unconfirmed, statusDate: undefined, error: undefined, progress: -1 //Show indeterminate progress by default for attachments } as MessageItem; }); //Sending the messages for(const message of messages) { ConnectionManager.sendFile(conversationTarget, message.attachments[0].data!) .progress((progressData) => { this.setState((prevState) => { //Ignoring if there are no messages if(prevState.display.type !== DisplayType.Messages) return null; //Cloning the item array const pendingItems: ConversationItem[] = [...prevState.display.data]; //Finding the item const itemIndex = pendingItems.findIndex((item) => item.localID === message.localID); if(itemIndex !== -1) { if(typeof progressData === "number") { //Updating the upload progress pendingItems[itemIndex] = { ...pendingItems[itemIndex], progress: progressData / message.attachments[0].size * 100 } as MessageItem; } else { //Updating the checksum pendingItems[itemIndex] = { ...pendingItems[itemIndex], attachments: [{ ...(pendingItems[itemIndex] as MessageItem).attachments[0], checksum: progressData }] } as MessageItem; } } return {display: {type: DisplayType.Messages, data: pendingItems}}; }); }) .then(() => { this.setState((prevState) => { //Ignoring if there are no messages if(prevState.display.type !== DisplayType.Messages) return null; //Cloning the item array const pendingItems: ConversationItem[] = [...prevState.display.data]; //Finding the item const itemIndex = pendingItems.findIndex((item) => item.localID === message.localID); if(itemIndex !== -1) { //Clearing the item's upload progress pendingItems[itemIndex] = { ...pendingItems[itemIndex], progress: undefined } as MessageItem; } return {display: {type: DisplayType.Messages, data: pendingItems}}; }); }) .catch((error: MessageError) => this.applyMessageError(error, message.localID!)); } //Adding the items to the added items list addedItems.push(...messages); } if(addedItems.length > 0) { //Notifying message listeners ConnectionManager.messageUpdateEmitter.notify(addedItems); this.messageSubmitEmitter.notify(undefined); //Playing a sound playSoundMessageOut(); } } private handleAttachmentRemove(file: QueuedFile) { this.setState(state => { const attachments = [...state.attachments]; const itemIndex = attachments.findIndex((queuedFile) => file.id === queuedFile.id); if(itemIndex !== -1) { attachments.splice(itemIndex, 1); } return {attachments: attachments}; }); } private handleAttachmentAdd(files: File[]) { const queuedFiles: QueuedFile[] = files.map((file) => { return {id: generateAttachmentLocalID(), file: file}; }); this.setState(state => { return {attachments: state.attachments.concat(...queuedFiles)}; }); } private readonly handleDragIn = (event: DragEvent) => { event.preventDefault(); event.stopPropagation(); //this.dragCounter++; //this.setState({dragHighlight: true}); }; private readonly handleDragOut = (event: DragEvent) => { event.preventDefault(); event.stopPropagation(); /* this.dragCounter--; if(this.dragCounter === 0) { this.setState({dragHighlight: false}); } */ }; private readonly handleDragOver = (event: DragEvent) => { event.preventDefault(); event.stopPropagation(); if(event.dataTransfer) event.dataTransfer.dropEffect = "copy"; }; private readonly handleDrop = (event: DragEvent) => { event.preventDefault(); event.stopPropagation(); //this.setState({dragHighlight: false}); //this.dragCounter = 0; //Adding the files if(event.dataTransfer) { const files: QueuedFile[] = [...event.dataTransfer.files].map((file) => { return {id: generateAttachmentLocalID(), file: file}; }); this.setState(state => { return {attachments: state.attachments.concat(...files)}; }); } }; private readonly handleRequestHistory = () => { //Returning if this is a local conversation, or if the state is already loading or is complete if(this.props.conversation.localOnly || this.state.historyLoadState !== "idle") return; //Fetching history const items = (this.state.display as DisplayMessages).data; ConnectionManager.fetchThread(this.props.conversation.guid, items[items.length - 1].serverID).then(data => { if(data.length > 0) { //Add the new items to the end of the array, and reset the load state this.setState((prevState) => { if(prevState.display.type !== DisplayType.Messages) return null; return { display: {type: DisplayType.Messages, data: prevState.display.data.concat(data)}, historyLoadState: "idle" }; }); } else { //No more history, we're done this.setState({historyLoadState: "complete"}); } }).catch(() => { //Ignore, and wait for the user to retry this.setState({historyLoadState: "idle"}); }); //Setting the state this.setState({historyLoadState: "loading"}); }; private readonly requestMessages = () => { if(!this.props.conversation.localOnly) { //Fetching messages from the server ConnectionManager.fetchThread(this.props.conversation.guid).then(data => { this.setState({display: {type: DisplayType.Messages, data: data}}); }).catch(() => { this.setState({display: {type: DisplayType.Error}}); }); } else { //Fetching messages from the cache this.setState({display: {type: DisplayType.Messages, data: localMessageCache.get(this.props.conversation.localID) ?? []}}); } }; private readonly updateFaceTimeSupported = (isFaceTimeSupported: boolean) => { this.setState({isFaceTimeSupported}); }; private readonly startCall = () => { ConnectionManager.initiateFaceTimeCall(this.props.conversation.members); }; render() { //Creating the body view (use a loading spinner while conversation details aren't available) let body: React.ReactNode; if(this.state.display.type === DisplayType.Messages) { body = <MessageList conversation={this.props.conversation} items={this.state.display.data} messageSubmitEmitter={this.messageSubmitEmitter} showHistoryLoader={this.state.historyLoadState === "loading"} onRequestHistory={this.handleRequestHistory} />; } else if(this.state.display.type === DisplayType.Loading) { body = ( <div className={styles.centerContainer}> <CircularProgress /> </div> ); } else if(this.state.display.type === DisplayType.Error) { body = ( <div className={styles.centerContainer}> <Typography color="textSecondary" gutterBottom>Couldn&apos;t load this conversation</Typography> <Button onClick={this.requestMessages}>Retry</Button> </div> ); } let inputPlaceholder: string; if(this.props.conversation.service === appleServiceAppleMessage) { inputPlaceholder = "iMessage"; } else { inputPlaceholder = "Text message"; } //Returning the element return ( <DetailFrame title={this.state.title ?? ""} ref={this.dragDropRef} showCall={this.state.isFaceTimeSupported} onClickCall={this.startCall}> <div className={styles.body}>{body}</div> <div className={styles.input}> <MessageInput placeholder={inputPlaceholder} message={this.state.message} attachments={this.state.attachments} onMessageChange={this.handleMessageChange.bind(this)} onMessageSubmit={this.handleMessageSubmit.bind(this)} onAttachmentAdd={this.handleAttachmentAdd.bind(this)} onAttachmentRemove={this.handleAttachmentRemove.bind(this)} /> </div> </DetailFrame> ); } componentDidMount() { //Clearing notifications if(!this.props.conversation.localOnly) { getNotificationUtils().dismissNotifications(this.props.conversation.guid); } //Fetching messages this.requestMessages(); //Building a conversation title from the participants' names if the conversation isn't explicitly named if(!this.props.conversation.name) { getMemberTitle(this.props.conversation.members).then((title) => { this.setState({title: title}); }); } //Subscribing to message updates ConnectionManager.messageUpdateEmitter.registerListener(this.onMessageUpdate); ConnectionManager.modifierUpdateEmitter.registerListener(this.onModifierUpdate); //Subscribing to FaceTime updates ConnectionManager.faceTimeSupportedEmitter.registerListener(this.updateFaceTimeSupported); //Subscribing to drag-and-drop updates { const element = this.dragDropRef.current!; element.addEventListener("dragenter", this.handleDragIn); element.addEventListener("dragleave", this.handleDragOut); element.addEventListener("dragover", this.handleDragOver); element.addEventListener("drop", this.handleDrop); } } componentDidUpdate(prevProps: Readonly<Props>) { //Checking if the conversation's title or members have changed if(this.props.conversation.name !== prevProps.conversation.name || this.props.conversation.members !== prevProps.conversation.members) { //Updating the conversation title if(this.props.conversation.name) { this.setState({title: this.props.conversation.name}); } else { this.setState({title: getFallbackTitle(this.props.conversation)}); getMemberTitle(this.props.conversation.members).then((title) => { this.setState({title: title}); }); } } } componentWillUnmount() { //Unsubscribing from message updates ConnectionManager.messageUpdateEmitter.unregisterListener(this.onMessageUpdate); ConnectionManager.modifierUpdateEmitter.unregisterListener(this.onModifierUpdate); //Unsubscribing from FaceTime updates ConnectionManager.faceTimeSupportedEmitter.unregisterListener(this.updateFaceTimeSupported); //Unsubscribing from drag-and-drop updates { const element = this.dragDropRef.current!; element.removeEventListener("dragenter", this.handleDragIn); element.removeEventListener("dragleave", this.handleDragOut); element.removeEventListener("dragover", this.handleDragOver); element.removeEventListener("drop", this.handleDrop); } //Storing messages in the cache if(this.props.conversation.localOnly && this.state.display.type === DisplayType.Messages) { localMessageCache.set(this.props.conversation.localID, this.state.display.data); } } private readonly onMessageUpdate = (itemArray: ConversationItem[]): void => { //Ignoring if the chat isn't loaded if(this.state.display.type !== DisplayType.Messages) return; //Merging the item into the conversation this.setState((prevState, props) => { if(prevState.display.type !== DisplayType.Messages) return null; //Filtering out items that aren't part of this conversation const newItemArray = itemArray.filter((item) => { if(item.chatGuid !== undefined) { if(!props.conversation.localOnly) { return item.chatGuid === props.conversation.guid; } } else if(item.chatLocalID !== undefined) { return item.chatLocalID === props.conversation.localID; } return false; }); //Cloning the item array const pendingItemArray: ConversationItem[] = [...prevState.display.data]; //Iterating over new items for(let i = 0; i < newItemArray.length; i++) { const newItem = newItemArray[i]; //If this is not a message, or the message is incoming, we can't match the item if(!isConversationItemMessage(newItem) || newItem.sender) continue; //Trying to find a matching unconfirmed message let matchedIndex: number = -1; if(newItem.text && newItem.attachments.length === 0) { matchedIndex = pendingItemArray.findIndex((existingItem) => isConversationItemMessage(existingItem) && existingItem.status === MessageStatusCode.Unconfirmed && !existingItem.sender && existingItem.attachments.length === 0 && existingItem.text === newItem.text); } else if(!newItem.text && newItem.attachments.length === 1 && newItem.attachments[0].checksum) { matchedIndex = pendingItemArray.findIndex((existingItem) => isConversationItemMessage(existingItem) && existingItem.status === MessageStatusCode.Unconfirmed && !existingItem.sender && existingItem.attachments.length === 1 && existingItem.attachments[0].checksum === newItem.attachments[0].checksum); } if(matchedIndex === -1) continue; //Merging the information into the item pendingItemArray[matchedIndex] = { ...pendingItemArray[matchedIndex], serverID: newItem.serverID, guid: newItem.guid, date: newItem.date, status: newItem.status, error: newItem.error, statusDate: newItem.statusDate } as MessageItem; //Removing the new message from the new item array (since we've already added it to the conversation) newItemArray.splice(i, 1); } //Adding new unmatched conversation items to the start of the array pendingItemArray.unshift(...newItemArray); return {display: {type: DisplayType.Messages, data: pendingItemArray}}; }); }; private readonly onModifierUpdate = (itemArray: MessageModifier[]): void => { //Ignoring if the chat isn't loaded if(this.state.display.type !== DisplayType.Messages) return; //Updating affected messages this.setState((prevState) => { if(prevState.display.type !== DisplayType.Messages) return null; //Cloning the item array const pendingItemArray: ConversationItem[] = [...prevState.display.data]; for(const modifier of itemArray) { //Trying to match the modifier with an item const matchingIndex = pendingItemArray.findIndex((item) => isConversationItemMessage(item) && item.guid === modifier.messageGuid); if(matchingIndex === -1) continue; //Applying the modifier if(isModifierStatusUpdate(modifier)) { pendingItemArray[matchingIndex] = { ...pendingItemArray[matchingIndex], status: modifier.status, statusDate: modifier.date } as MessageItem; } else if(isModifierSticker(modifier)) { pendingItemArray[matchingIndex] = { ...pendingItemArray[matchingIndex], stickers: (pendingItemArray[matchingIndex] as MessageItem).stickers.concat(modifier), } as MessageItem; } else if(isModifierTapback(modifier)) { const pendingTapbacks = [...(pendingItemArray[matchingIndex] as MessageItem).tapbacks]; const matchingTapbackIndex = pendingTapbacks.findIndex((tapback) => tapback.sender === modifier.sender); if(matchingTapbackIndex !== -1) pendingTapbacks[matchingTapbackIndex] = modifier; else pendingTapbacks.push(modifier); pendingItemArray[matchingIndex] = { ...pendingItemArray[matchingIndex], tapbacks: pendingTapbacks } as MessageItem; } } return {display: {type: DisplayType.Messages, data: pendingItemArray}}; }); }; }
the_stack
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {AbstractComponent} from '@common/component/abstract.component'; import {AuditService} from '../service/audit.service'; import {Alert} from '@common/util/alert.util'; import {Audit} from '@domain/audit/audit'; import {MomentDatePipe} from '@common/pipe/moment.date.pipe'; import {CookieConstant} from '@common/constant/cookie.constant'; import {CommonConstant} from '@common/constant/common.constant'; import {CommonUtil} from '@common/util/common.util'; import {PeriodData} from '@common/value/period.data.value'; import {PeriodComponent} from '@common/component/period/period.component'; import * as _ from 'lodash'; declare let moment: any; @Component({ selector: 'app-job-log', templateUrl: './job-log.component.html', providers: [MomentDatePipe] }) export class JobLogComponent extends AbstractComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private _searchParams: { [key: string]: string }; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild(PeriodComponent) public periodComponent: PeriodComponent; // 선택된 캘린더 public selectedDate: PeriodData; // audit 리스트 public auditList: Audit[] = []; // status types public statusTypes: any[]; public selectedStatus: any; // types public types: any[]; public selectedType: any; // 검색어 public searchText: string = ''; // 정렬 public selectedContentSort: Order = new Order(); // 팝업 모드 public mode: string; public selectedElapsedTime: any; public CommonUtil = CommonUtil; @ViewChild('elapsedTime') public elapsedTime: ElementRef; public logTypeDefaultIndex: number = 0; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(private auditService: AuditService, private activatedRoute: ActivatedRoute, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Methods |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ ngOnInit() { super.ngOnInit(); // ui init this.initView(); this.subscriptions.push( // Get query param from url this.activatedRoute.queryParams.subscribe((params) => { if (!_.isEmpty(params)) { if (!this.isNullOrUndefined(params['size'])) { this.page.size = params['size']; } if (!this.isNullOrUndefined(params['page'])) { this.page.page = params['page']; } if (!this.isNullOrUndefined(params['searchKeyword'])) { this.searchText = params['searchKeyword']; } // status let index = 0; if (!this.isNullOrUndefined(params['status'])) { index = this.statusTypes.findIndex((item) => { return item.value.toLowerCase() === params['status'].toLowerCase() }); } this.selectedStatus = this.statusTypes[index]; // log type let idx = 0; if (!this.isNullOrUndefined(params['type'])) { idx = this.types.findIndex((item) => { return item.value.toLowerCase() === params['type'].toLowerCase() }); } this.selectedType = this.types[idx]; this.logTypeDefaultIndex = idx; // sort const sort = params['sort']; if (!this.isNullOrUndefined(sort)) { const sortInfo = decodeURIComponent(sort).split(','); this.selectedContentSort.key = sortInfo[0]; this.selectedContentSort.sort = sortInfo[1]; } // elapsed time if (!this.isNullOrUndefined(params['elapsedTime'])) { const sec = ['10', '30', '60']; this.selectedElapsedTime = Number(params['elapsedTime']); if (sec.indexOf(params['elapsedTime']) === -1) { this.elapsedTime.nativeElement.value = this.selectedElapsedTime; } } else { this.selectedElapsedTime = 'ALL'; } // Date const from = params['from']; const to = params['to']; this.selectedDate = new PeriodData(); this.selectedDate.type = 'ALL'; if (!this.isNullOrUndefined(from) && !this.isNullOrUndefined(to)) { this.selectedDate.startDate = from; this.selectedDate.endDate = to; this.selectedDate.dateType = 'CREATED'; this.selectedDate.startDateStr = decodeURIComponent(from); this.selectedDate.endDateStr = decodeURIComponent(to); this.selectedDate.type = params['dateType']; this.safelyDetectChanges(); } } this.getAuditList(); }) ) } ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 페이지 변경 * @param data */ public changePage(data: { page: number, size: number }) { if (data) { this.page.page = data.page; this.page.size = data.size; // 워크스페이스 조회 this.reloadPage(false); } } /** * 페이지를 새로 불러온다. * @param {boolean} isFirstPage */ public reloadPage(isFirstPage: boolean = true) { (isFirstPage) && (this.page.page = 0); this._searchParams = this.getAuditRequestParams(); this.router.navigate( [this.router.url.replace(/\?.*/gi, '')], {queryParams: this._searchParams, replaceUrl: true} ).then(); } /** * audit 상세보기 오픈 * @param {string} id */ public auditDetailOpen(id: string) { // 페이지 이동 this.router.navigateByUrl('/management/monitoring/audit/' + id).then(); } /** * 타입 필터링 변경 이벤트 */ public onChangeType(event) { // type 변경 this.selectedType = event; this.reloadPage(); } /** * 캘린더 선택 이벤트 * @param event */ public onChangeDate(event) { this.selectedDate = event; this.reloadPage(); } /** * 검색 이벤트 */ public search() { this.reloadPage(); } /** * status 정렬 필터링 * @param status */ public onChangeStatus(status) { this.selectedStatus = status; this.reloadPage(); } /** * 정렬 필터링 * @param {string} key */ public sort(key: string) { // 초기화 this.selectedContentSort.sort = this.selectedContentSort.key !== key ? 'default' : this.selectedContentSort.sort; // 정렬 정보 저장 this.selectedContentSort.key = key; if (this.selectedContentSort.key === key) { // asc, desc switch (this.selectedContentSort.sort) { case 'asc': this.selectedContentSort.sort = 'desc'; break; case 'desc': this.selectedContentSort.sort = 'asc'; break; case 'default': this.selectedContentSort.sort = 'desc'; break; } } this.reloadPage(); } /** * Refresh filters */ public refreshFilters() { // 정렬 this.selectedContentSort = new Order(); // create date 초기화 this.selectedDate = null; // 검색조건 초기화 this.searchText = ''; this.periodComponent.setAll(); this.selectedType = this.types[0]; this.logTypeDefaultIndex = 0; this.onChangeStatus(this.statusTypes[0]); this.onClickElapsedTime('ALL'); this.reloadPage(); } /** * On click of elapsed time * @param time */ public onClickElapsedTime(time?: string | number) { if (time) { this.elapsedTime.nativeElement.value = ''; this.selectedElapsedTime = time; } else { this.selectedElapsedTime = this.elapsedTime.nativeElement.value; } this.reloadPage(); } /** * Csv download */ public downloadCsv() { if (this.auditList.length === 0) { return; } let url = CommonConstant.API_CONSTANT.API_URL + `audits/download`; let params = {}; if (this.searchText) { params = { searchKeyword: this.searchText } } // status if (this.selectedStatus.value !== 'all') { params['status'] = this.selectedStatus.value; } // type if (this.selectedType.value !== 'all') { params['type'] = this.selectedType.value; } if (this.selectedElapsedTime !== 'ALL') { params['elapsedTime'] = Number(this.selectedElapsedTime); } // date if (this.selectedDate && this.selectedDate.type !== 'ALL') { if (this.selectedDate.startDateStr) { params['from'] = moment(this.selectedDate.startDateStr).format('YYYY-MM-DDTHH:mm:ss.SSSZ'); } params['to'] = moment(this.selectedDate.endDateStr).format('YYYY-MM-DDTHH:mm:ss.SSSZ'); } if (params) { url += '?' + CommonUtil.objectToUrlString(params); } try { const form = document.getElementsByTagName('form'); const inputs = form[0].getElementsByTagName('input'); inputs[0].value = this.cookieService.get(CookieConstant.KEY.LOGIN_TOKEN); inputs[1].value = 'job_log_list'; const downloadCsvForm = $('#downloadCsvForm'); downloadCsvForm.attr('action', url); downloadCsvForm.submit(); } catch (e) { // 재현이 되지 않음. console.log('Download error : ' + e); } } /** * Elapsed time keyup event */ public elapsedTimeKeyup() { // Remove selected btn this.selectedElapsedTime = ''; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ private initView() { this.types = [ {label: 'All', value: 'all'}, {label: 'Workbench Query', value: 'QUERY'}, {label: 'Workbench Others', value: 'JOB'} ]; this.selectedType = this.types[0]; this.statusTypes = [ {label: 'All', value: 'all'}, {label: 'Success', value: 'SUCCESS'}, {label: 'Running', value: 'RUNNING'}, {label: 'Cancelled', value: 'CANCELLED'}, {label: 'Fail', value: 'FAIL'} ]; this.selectedStatus = this.statusTypes[0]; this.selectedElapsedTime = 'ALL'; } /** * audit list request params * @returns {page: number; size: number} */ private getAuditRequestParams(): any { const params = { page: this.page.page, size: this.page.size, pseudoParam: (new Date()).getTime() }; // 이름 if (this.searchText !== '') { params['searchKeyword'] = this.searchText; } // status if (this.selectedStatus.value !== 'all') { params['status'] = this.selectedStatus.value; } // type if (this.selectedType.value !== 'all') { params['type'] = this.selectedType.value; } // date if (this.selectedDate && this.selectedDate.type !== 'ALL') { params['dateType'] = this.selectedDate.type; if (this.selectedDate.startDateStr) { params['from'] = moment(this.selectedDate.startDateStr).format('YYYY-MM-DDTHH:mm:ss.SSSZ'); } params['to'] = moment(this.selectedDate.endDateStr).format('YYYY-MM-DDTHH:mm:ss.SSSZ'); } // sort if (this.selectedContentSort.sort !== 'default') { params['sort'] = this.selectedContentSort.key + ',' + this.selectedContentSort.sort; } if (this.selectedElapsedTime !== 'ALL') { params['elapsedTime'] = this.selectedElapsedTime; } return params; } /** * audit 리스트 조회 */ private getAuditList() { // 로딩 시작 this.loadingShow(); const params = this.getAuditRequestParams(); this.auditList = []; this.auditService.getAuditList(params) .then((result) => { this._searchParams = params; // page this.pageResult = result.page; // 리스트 존재 시 this.auditList = result['_embedded'] ? this.auditList.concat(result['_embedded'].audits) : []; // 로딩 종료 this.loadingHide(); }) .catch((error) => { Alert.error(error); // 로딩 종료 this.loadingHide(); }); } } class Order { key: string = 'startTime'; sort: string = 'desc'; }
the_stack
import 'fast-text-encoding'; import * as esCookie from 'es-cookie'; import unfetch from 'unfetch'; import { verify } from '../../src/jwt'; import { MessageChannel } from 'worker_threads'; import * as utils from '../../src/utils'; import * as scope from '../../src/scope'; import { expectToHaveBeenCalledWithAuth0ClientParam, expectToHaveBeenCalledWithHash } from '../helpers'; // @ts-ignore import { assertPostFn, assertUrlEquals, loginWithRedirectFn, setupFn } from './helpers'; import { TEST_ACCESS_TOKEN, TEST_CLIENT_ID, TEST_CODE, TEST_CODE_CHALLENGE, TEST_CODE_VERIFIER, TEST_DOMAIN, TEST_ID_TOKEN, TEST_NONCE, TEST_ORG_ID, TEST_REDIRECT_URI, TEST_SCOPES, TEST_STATE } from '../constants'; import version from '../../src/version'; jest.mock('unfetch'); jest.mock('es-cookie'); jest.mock('../../src/jwt'); jest.mock('../../src/worker/token.worker'); const mockWindow = <any>global; const mockFetch = (mockWindow.fetch = <jest.Mock>unfetch); const mockVerify = <jest.Mock>verify; const mockCookies = require('es-cookie'); const tokenVerifier = require('../../src/jwt').verify; jest .spyOn(utils, 'bufferToBase64UrlEncoded') .mockReturnValue(TEST_CODE_CHALLENGE); jest.spyOn(utils, 'runPopup'); const assertPost = assertPostFn(mockFetch); const setup = setupFn(mockVerify); const loginWithRedirect = loginWithRedirectFn(mockWindow, mockFetch); describe('Auth0Client', () => { const oldWindowLocation = window.location; beforeEach(() => { // https://www.benmvp.com/blog/mocking-window-location-methods-jest-jsdom/ delete window.location; window.location = Object.defineProperties( {}, { ...Object.getOwnPropertyDescriptors(oldWindowLocation), assign: { configurable: true, value: jest.fn() }, replace: { configurable: true, value: jest.fn() } } ) as Location; // -- mockWindow.open = jest.fn(); mockWindow.addEventListener = jest.fn(); mockWindow.crypto = { subtle: { digest: () => 'foo' }, getRandomValues() { return '123'; } }; mockWindow.MessageChannel = MessageChannel; mockWindow.Worker = {}; jest.spyOn(scope, 'getUniqueScopes'); sessionStorage.clear(); }); afterEach(() => { mockFetch.mockReset(); jest.clearAllMocks(); window.location = oldWindowLocation; }); describe('loginWithRedirect', () => { it('should log the user in and get the token', async () => { const auth0 = setup(); await loginWithRedirect(auth0); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { client_id: TEST_CLIENT_ID, redirect_uri: TEST_REDIRECT_URI, scope: TEST_SCOPES, response_type: 'code', response_mode: 'query', state: TEST_STATE, nonce: TEST_NONCE, code_challenge: TEST_CODE_CHALLENGE, code_challenge_method: 'S256' }); assertPost( 'https://auth0_domain/oauth/token', { redirect_uri: TEST_REDIRECT_URI, client_id: TEST_CLIENT_ID, code_verifier: TEST_CODE_VERIFIER, grant_type: 'authorization_code', code: TEST_CODE }, { 'Auth0-Client': btoa( JSON.stringify({ name: 'auth0-spa-js', version: version }) ) } ); }); it('should log the user in using different default scope', async () => { const auth0 = setup({ advancedOptions: { defaultScope: 'email' } }); await loginWithRedirect(auth0); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { scope: 'openid email' }); }); it('should log the user in using different default redirect_uri', async () => { const redirect_uri = 'https://custom-redirect-uri/callback'; const auth0 = setup({ redirect_uri }); await loginWithRedirect(auth0); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { redirect_uri }); }); it('should log the user in when overriding default redirect_uri', async () => { const redirect_uri = 'https://custom-redirect-uri/callback'; const auth0 = setup({ redirect_uri }); await loginWithRedirect(auth0, { redirect_uri: 'https://my-redirect-uri/callback' }); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { redirect_uri: 'https://my-redirect-uri/callback' }); }); it('should log the user in by calling window.location.replace when redirectMethod=replace param is passed', async () => { const auth0 = setup(); await loginWithRedirect(auth0, { audience: 'test_audience', redirectMethod: 'replace' }); const url = new URL(mockWindow.location.replace.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { audience: 'test_audience' }); }); it('should log the user in with custom params', async () => { const auth0 = setup(); await loginWithRedirect(auth0, { audience: 'test_audience' }); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { audience: 'test_audience' }); }); it('should log the user in using offline_access when using refresh tokens', async () => { const auth0 = setup({ useRefreshTokens: true }); await loginWithRedirect(auth0); const url = new URL(mockWindow.location.assign.mock.calls[0][0]); assertUrlEquals(url, TEST_DOMAIN, '/authorize', { scope: `${TEST_SCOPES} offline_access` }); }); it('should log the user in and get the user', async () => { const auth0 = setup({ scope: 'foo' }); await loginWithRedirect(auth0); const expectedUser = { sub: 'me' }; expect(await auth0.getUser()).toEqual(expectedUser); expect(await auth0.getUser({})).toEqual(expectedUser); expect(await auth0.getUser({ audience: 'default' })).toEqual( expectedUser ); expect(await auth0.getUser({ scope: 'foo' })).toEqual(expectedUser); expect(await auth0.getUser({ audience: 'invalid' })).toBeUndefined(); }); it('should log the user in and get the user with custom scope', async () => { const auth0 = setup({ scope: 'scope1', advancedOptions: { defaultScope: 'scope2' } }); await loginWithRedirect(auth0, { scope: 'scope3' }); const expectedUser = { sub: 'me' }; expect(await auth0.getUser({ scope: 'scope1 scope2 scope3' })).toEqual( expectedUser ); }); it('should log the user in with custom auth0Client', async () => { const auth0Client = { name: '__test_client__', version: '0.0.0' }; const auth0 = setup({ auth0Client }); await loginWithRedirect(auth0); expectToHaveBeenCalledWithAuth0ClientParam( mockWindow.location.assign, auth0Client ); }); it('should log the user in with custom fragment', async () => { const auth0Client = { name: '__test_client__', version: '0.0.0' }; const auth0 = setup({ auth0Client }); await loginWithRedirect(auth0, { fragment: '/reset' }); expectToHaveBeenCalledWithHash(mockWindow.location.assign, '#/reset'); }); it('uses session storage for transactions by default', async () => { const auth0 = setup(); await auth0.loginWithRedirect(); expect((sessionStorage.setItem as jest.Mock).mock.calls[0][0]).toBe( `a0.spajs.txs.${TEST_CLIENT_ID}` ); }); it('uses cookie storage for transactions', async () => { const auth0 = setup({ useCookiesForTransactions: true }); await loginWithRedirect(auth0); // Don't necessarily need to check the contents of the cookie (the storage tests are doing that), // just that cookies were used when I set the correct option. expect((mockCookies.set as jest.Mock).mock.calls[1][0]).toEqual( `a0.spajs.txs.${TEST_CLIENT_ID}` ); }); it('should throw an error on token failure', async () => { const auth0 = setup(); await expect( loginWithRedirect(auth0, undefined, { token: { success: false } }) ).rejects.toThrowError( 'HTTP error. Unable to fetch https://auth0_domain/oauth/token' ); }); it('calls `tokenVerifier.verify` with the `id_token` from in the oauth/token response', async () => { const auth0 = setup({ issuer: 'test-123.auth0.com' }); await loginWithRedirect(auth0); expect(tokenVerifier).toHaveBeenCalledWith( expect.objectContaining({ iss: 'https://test-123.auth0.com/', id_token: TEST_ID_TOKEN }) ); }); it('calls `tokenVerifier.verify` with the global organization id', async () => { const auth0 = setup({ organization: 'test_org_123' }); await loginWithRedirect(auth0); expect(tokenVerifier).toHaveBeenCalledWith( expect.objectContaining({ organizationId: 'test_org_123' }) ); }); it('stores the organization ID in a hint cookie', async () => { const auth0 = setup({}, { org_id: TEST_ORG_ID }); await loginWithRedirect(auth0); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `auth0.${TEST_CLIENT_ID}.organization_hint`, JSON.stringify(TEST_ORG_ID), {} ); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `_legacy_auth0.${TEST_CLIENT_ID}.organization_hint`, JSON.stringify(TEST_ORG_ID), {} ); }); it('removes the org hint cookie if no org_id claim in the ID token', async () => { const auth0 = setup({}); await loginWithRedirect(auth0); expect(<jest.Mock>esCookie.remove).toHaveBeenCalledWith( `auth0.${TEST_CLIENT_ID}.organization_hint` ); expect(<jest.Mock>esCookie.remove).toHaveBeenCalledWith( `_legacy_auth0.${TEST_CLIENT_ID}.organization_hint` ); }); it('calls `tokenVerifier.verify` with the specific organization id', async () => { const auth0 = setup({ organization: 'test_org_123' }); await loginWithRedirect(auth0, { organization: 'test_org_456' }); expect(tokenVerifier).toHaveBeenCalledWith( expect.objectContaining({ organizationId: 'test_org_456' }) ); }); it('saves into cache', async () => { const auth0 = setup(); jest.spyOn(auth0['cacheManager'], 'set'); await loginWithRedirect(auth0); expect(auth0['cacheManager']['set']).toHaveBeenCalledWith( expect.objectContaining({ client_id: TEST_CLIENT_ID, access_token: TEST_ACCESS_TOKEN, expires_in: 86400, audience: 'default', id_token: TEST_ID_TOKEN, scope: TEST_SCOPES }) ); }); it('saves `auth0.is.authenticated` key in storage', async () => { const auth0 = setup(); await loginWithRedirect(auth0); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `_legacy_auth0.${TEST_CLIENT_ID}.is.authenticated`, 'true', { expires: 1 } ); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `auth0.${TEST_CLIENT_ID}.is.authenticated`, 'true', { expires: 1 } ); }); it('saves authenticated cookie key in storage for an extended period', async () => { const auth0 = setup({ sessionCheckExpiryDays: 2 }); await loginWithRedirect(auth0); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `_legacy_auth0.${TEST_CLIENT_ID}.is.authenticated`, 'true', { expires: 2 } ); expect(<jest.Mock>esCookie.set).toHaveBeenCalledWith( `auth0.${TEST_CLIENT_ID}.is.authenticated`, 'true', { expires: 2 } ); }); }); });
the_stack
import http = require('http') import https = require('https') import ifm = require('./interfaces') import pm = require('./proxy') let tunnel: any export enum HttpCodes { OK = 200, MultipleChoices = 300, MovedPermanently = 301, ResourceMoved = 302, SeeOther = 303, NotModified = 304, UseProxy = 305, SwitchProxy = 306, TemporaryRedirect = 307, PermanentRedirect = 308, BadRequest = 400, Unauthorized = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticationRequired = 407, RequestTimeout = 408, Conflict = 409, Gone = 410, TooManyRequests = 429, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504 } export enum Headers { Accept = 'accept', ContentType = 'content-type' } export enum MediaTypes { ApplicationJson = 'application/json' } /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ export function getProxyUrl(serverUrl: string): string { let proxyUrl = pm.getProxyUrl(new URL(serverUrl)) return proxyUrl ? proxyUrl.href : '' } const HttpRedirectCodes: number[] = [ HttpCodes.MovedPermanently, HttpCodes.ResourceMoved, HttpCodes.SeeOther, HttpCodes.TemporaryRedirect, HttpCodes.PermanentRedirect ] const HttpResponseRetryCodes: number[] = [ HttpCodes.BadGateway, HttpCodes.ServiceUnavailable, HttpCodes.GatewayTimeout ] const RetryableHttpVerbs: string[] = ['OPTIONS', 'GET', 'DELETE', 'HEAD'] const ExponentialBackoffCeiling = 10 const ExponentialBackoffTimeSlice = 5 export class HttpClientError extends Error { constructor(message: string, statusCode: number) { super(message) this.name = 'HttpClientError' this.statusCode = statusCode Object.setPrototypeOf(this, HttpClientError.prototype) } public statusCode: number public result?: any } export class HttpClientResponse implements ifm.IHttpClientResponse { constructor(message: http.IncomingMessage) { this.message = message } public message: http.IncomingMessage readBody(): Promise<string> { return new Promise<string>(async (resolve, reject) => { let output = Buffer.alloc(0) this.message.on('data', (chunk: Buffer) => { output = Buffer.concat([output, chunk]) }) this.message.on('end', () => { resolve(output.toString()) }) }) } } export function isHttps(requestUrl: string) { let parsedUrl: URL = new URL(requestUrl) return parsedUrl.protocol === 'https:' } export class HttpClient { userAgent: string | undefined handlers: ifm.IRequestHandler[] requestOptions: ifm.IRequestOptions private _ignoreSslError: boolean = false private _socketTimeout: number private _allowRedirects: boolean = true private _allowRedirectDowngrade: boolean = false private _maxRedirects: number = 50 private _allowRetries: boolean = false private _maxRetries: number = 1 private _agent private _proxyAgent private _keepAlive: boolean = false private _disposed: boolean = false constructor( userAgent?: string, handlers?: ifm.IRequestHandler[], requestOptions?: ifm.IRequestOptions ) { this.userAgent = userAgent this.handlers = handlers || [] this.requestOptions = requestOptions if (requestOptions) { if (requestOptions.ignoreSslError != null) { this._ignoreSslError = requestOptions.ignoreSslError } this._socketTimeout = requestOptions.socketTimeout if (requestOptions.allowRedirects != null) { this._allowRedirects = requestOptions.allowRedirects } if (requestOptions.allowRedirectDowngrade != null) { this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade } if (requestOptions.maxRedirects != null) { this._maxRedirects = Math.max(requestOptions.maxRedirects, 0) } if (requestOptions.keepAlive != null) { this._keepAlive = requestOptions.keepAlive } if (requestOptions.allowRetries != null) { this._allowRetries = requestOptions.allowRetries } if (requestOptions.maxRetries != null) { this._maxRetries = requestOptions.maxRetries } } } public options( requestUrl: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}) } public get( requestUrl: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('GET', requestUrl, null, additionalHeaders || {}) } public del( requestUrl: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('DELETE', requestUrl, null, additionalHeaders || {}) } public post( requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('POST', requestUrl, data, additionalHeaders || {}) } public patch( requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('PATCH', requestUrl, data, additionalHeaders || {}) } public put( requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('PUT', requestUrl, data, additionalHeaders || {}) } public head( requestUrl: string, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request('HEAD', requestUrl, null, additionalHeaders || {}) } public sendStream( verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { return this.request(verb, requestUrl, stream, additionalHeaders) } /** * Gets a typed object from an endpoint * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise */ public async getJson<T>( requestUrl: string, additionalHeaders: ifm.IHeaders = {} ): Promise<ifm.ITypedResponse<T>> { additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson ) let res: ifm.IHttpClientResponse = await this.get( requestUrl, additionalHeaders ) return this._processResponse<T>(res, this.requestOptions) } public async postJson<T>( requestUrl: string, obj: any, additionalHeaders: ifm.IHeaders = {} ): Promise<ifm.ITypedResponse<T>> { let data: string = JSON.stringify(obj, null, 2) additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson ) additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson ) let res: ifm.IHttpClientResponse = await this.post( requestUrl, data, additionalHeaders ) return this._processResponse<T>(res, this.requestOptions) } public async putJson<T>( requestUrl: string, obj: any, additionalHeaders: ifm.IHeaders = {} ): Promise<ifm.ITypedResponse<T>> { let data: string = JSON.stringify(obj, null, 2) additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson ) additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson ) let res: ifm.IHttpClientResponse = await this.put( requestUrl, data, additionalHeaders ) return this._processResponse<T>(res, this.requestOptions) } public async patchJson<T>( requestUrl: string, obj: any, additionalHeaders: ifm.IHeaders = {} ): Promise<ifm.ITypedResponse<T>> { let data: string = JSON.stringify(obj, null, 2) additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson ) additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader( additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson ) let res: ifm.IHttpClientResponse = await this.patch( requestUrl, data, additionalHeaders ) return this._processResponse<T>(res, this.requestOptions) } /** * Makes a raw http request. * All other methods such as get, post, patch, and request ultimately call this. * Prefer get, del, post and patch */ public async request( verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: ifm.IHeaders ): Promise<ifm.IHttpClientResponse> { if (this._disposed) { throw new Error('Client has already been disposed.') } let parsedUrl = new URL(requestUrl) let info: ifm.IRequestInfo = this._prepareRequest(verb, parsedUrl, headers) // Only perform retries on reads since writes may not be idempotent. let maxTries: number = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 ? this._maxRetries + 1 : 1 let numTries: number = 0 let response: HttpClientResponse while (numTries < maxTries) { response = await this.requestRaw(info, data) // Check if it's an authentication challenge if ( response && response.message && response.message.statusCode === HttpCodes.Unauthorized ) { let authenticationHandler: ifm.IRequestHandler for (let i = 0; i < this.handlers.length; i++) { if (this.handlers[i].canHandleAuthentication(response)) { authenticationHandler = this.handlers[i] break } } if (authenticationHandler) { return authenticationHandler.handleAuthentication(this, info, data) } else { // We have received an unauthorized response but have no handlers to handle it. // Let the response return to the caller. return response } } let redirectsRemaining: number = this._maxRedirects while ( HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && this._allowRedirects && redirectsRemaining > 0 ) { const redirectUrl: string | null = response.message.headers['location'] if (!redirectUrl) { // if there's no location to redirect to, we won't break } let parsedRedirectUrl = new URL(redirectUrl) if ( parsedUrl.protocol == 'https:' && parsedUrl.protocol != parsedRedirectUrl.protocol && !this._allowRedirectDowngrade ) { throw new Error( 'Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.' ) } // we need to finish reading the response before reassigning response // which will leak the open socket. await response.readBody() // strip authorization header if redirected to a different hostname if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { for (let header in headers) { // header names are case insensitive if (header.toLowerCase() === 'authorization') { delete headers[header] } } } // let's make the request with the new redirectUrl info = this._prepareRequest(verb, parsedRedirectUrl, headers) response = await this.requestRaw(info, data) redirectsRemaining-- } if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { // If not a retry code, return immediately instead of retrying return response } numTries += 1 if (numTries < maxTries) { await response.readBody() await this._performExponentialBackoff(numTries) } } return response } /** * Needs to be called if keepAlive is set to true in request options. */ public dispose() { if (this._agent) { this._agent.destroy() } this._disposed = true } /** * Raw request. * @param info * @param data */ public requestRaw( info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream ): Promise<ifm.IHttpClientResponse> { return new Promise<ifm.IHttpClientResponse>((resolve, reject) => { let callbackForResult = function ( err: any, res: ifm.IHttpClientResponse ) { if (err) { reject(err) } resolve(res) } this.requestRawWithCallback(info, data, callbackForResult) }) } /** * Raw request with callback. * @param info * @param data * @param onResult */ public requestRawWithCallback( info: ifm.IRequestInfo, data: string | NodeJS.ReadableStream, onResult: (err: any, res: ifm.IHttpClientResponse) => void ): void { let socket if (typeof data === 'string') { info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8') } let callbackCalled: boolean = false let handleResult = (err: any, res: HttpClientResponse) => { if (!callbackCalled) { callbackCalled = true onResult(err, res) } } let req: http.ClientRequest = info.httpModule.request( info.options, (msg: http.IncomingMessage) => { let res: HttpClientResponse = new HttpClientResponse(msg) handleResult(null, res) } ) req.on('socket', sock => { socket = sock }) // If we ever get disconnected, we want the socket to timeout eventually req.setTimeout(this._socketTimeout || 3 * 60000, () => { if (socket) { socket.end() } handleResult(new Error('Request timeout: ' + info.options.path), null) }) req.on('error', function (err) { // err has statusCode property // res should have headers handleResult(err, null) }) if (data && typeof data === 'string') { req.write(data, 'utf8') } if (data && typeof data !== 'string') { data.on('close', function () { req.end() }) data.pipe(req) } else { req.end() } } /** * Gets an http agent. This function is useful when you need an http agent that handles * routing through a proxy server - depending upon the url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ public getAgent(serverUrl: string): http.Agent { let parsedUrl = new URL(serverUrl) return this._getAgent(parsedUrl) } private _prepareRequest( method: string, requestUrl: URL, headers: ifm.IHeaders ): ifm.IRequestInfo { const info: ifm.IRequestInfo = <ifm.IRequestInfo>{} info.parsedUrl = requestUrl const usingSsl: boolean = info.parsedUrl.protocol === 'https:' info.httpModule = usingSsl ? https : http const defaultPort: number = usingSsl ? 443 : 80 info.options = <http.RequestOptions>{} info.options.host = info.parsedUrl.hostname info.options.port = info.parsedUrl.port ? parseInt(info.parsedUrl.port) : defaultPort info.options.path = (info.parsedUrl.pathname || '') + (info.parsedUrl.search || '') info.options.method = method info.options.headers = this._mergeHeaders(headers) if (this.userAgent != null) { info.options.headers['user-agent'] = this.userAgent } info.options.agent = this._getAgent(info.parsedUrl) // gives handlers an opportunity to participate if (this.handlers) { this.handlers.forEach(handler => { handler.prepareRequest(info.options) }) } return info } private _mergeHeaders(headers: ifm.IHeaders): ifm.IHeaders { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}) if (this.requestOptions && this.requestOptions.headers) { return Object.assign( {}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers) ) } return lowercaseKeys(headers || {}) } private _getExistingOrDefaultHeader( additionalHeaders: ifm.IHeaders, header: string, _default: string ) { const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}) let clientHeader: string if (this.requestOptions && this.requestOptions.headers) { clientHeader = lowercaseKeys(this.requestOptions.headers)[header] } return additionalHeaders[header] || clientHeader || _default } private _getAgent(parsedUrl: URL): http.Agent { let agent let proxyUrl: URL = pm.getProxyUrl(parsedUrl) let useProxy = proxyUrl && proxyUrl.hostname if (this._keepAlive && useProxy) { agent = this._proxyAgent } if (this._keepAlive && !useProxy) { agent = this._agent } // if agent is already assigned use that agent. if (!!agent) { return agent } const usingSsl = parsedUrl.protocol === 'https:' let maxSockets = 100 if (!!this.requestOptions) { maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets } if (useProxy) { // If using proxy, need tunnel if (!tunnel) { tunnel = require('tunnel') } const agentOptions = { maxSockets: maxSockets, keepAlive: this._keepAlive, proxy: { ...((proxyUrl.username || proxyUrl.password) && { proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` }), host: proxyUrl.hostname, port: proxyUrl.port } } let tunnelAgent: Function const overHttps = proxyUrl.protocol === 'https:' if (usingSsl) { tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp } else { tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp } agent = tunnelAgent(agentOptions) this._proxyAgent = agent } // if reusing agent across request and tunneling agent isn't assigned create a new agent if (this._keepAlive && !agent) { const options = {keepAlive: this._keepAlive, maxSockets: maxSockets} agent = usingSsl ? new https.Agent(options) : new http.Agent(options) this._agent = agent } // if not using private agent and tunnel agent isn't setup then use global agent if (!agent) { agent = usingSsl ? https.globalAgent : http.globalAgent } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options // we have to cast it to any and change it directly agent.options = Object.assign(agent.options || {}, { rejectUnauthorized: false }) } return agent } private _performExponentialBackoff(retryNumber: number): Promise<void> { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber) const ms: number = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber) return new Promise(resolve => setTimeout(() => resolve(), ms)) } private static dateTimeDeserializer(key: any, value: any): any { if (typeof value === 'string') { let a = new Date(value) if (!isNaN(a.valueOf())) { return a } } return value } private async _processResponse<T>( res: ifm.IHttpClientResponse, options: ifm.IRequestOptions ): Promise<ifm.ITypedResponse<T>> { return new Promise<ifm.ITypedResponse<T>>(async (resolve, reject) => { const statusCode: number = res.message.statusCode const response: ifm.ITypedResponse<T> = { statusCode: statusCode, result: null, headers: {} } // not found leads to null obj returned if (statusCode == HttpCodes.NotFound) { resolve(response) } let obj: any let contents: string // get the result from the body try { contents = await res.readBody() if (contents && contents.length > 0) { if (options && options.deserializeDates) { obj = JSON.parse(contents, HttpClient.dateTimeDeserializer) } else { obj = JSON.parse(contents) } response.result = obj } response.headers = res.message.headers } catch (err) { // Invalid resource (contents not json); leaving result obj null } // note that 3xx redirects are handled by the http layer. if (statusCode > 299) { let msg: string // if exception/error in body, attempt to get better error if (obj && obj.message) { msg = obj.message } else if (contents && contents.length > 0) { // it may be the case that the exception is in the body message as string msg = contents } else { msg = 'Failed request: (' + statusCode + ')' } let err = new HttpClientError(msg, statusCode) err.result = response.result reject(err) } else { resolve(response) } }) } }
the_stack
export namespace AnomalyDetectionModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface Anomaly */ export interface Anomaly { /** * Extent of anomaly at this point * @type {number} * @memberof Anomaly */ anomalyExtent?: number; /** * time * @type {string} * @memberof Anomaly */ time?: string; } /** * * @export * @interface JobProcessingException */ export interface JobProcessingException { /** * * @type {string} * @memberof JobProcessingException */ logref?: string; /** * * @type {string} * @memberof JobProcessingException */ message?: string; } /** * * @export * @interface Model */ export interface Model { /** * ID of the created Model. * @type {string} * @memberof Model */ id?: string; /** * Timestamp model was created at. * @type {string} * @memberof Model */ creationTimestamp?: string; /** * Variables used to train the model (variables from input json). * @type {string} * @memberof Model */ variables?: string; /** * Human-friendly name of the model, not an empty string. Maximum length is 255 characters. Only ASCII characters. * @type {string} * @memberof Model */ name?: string; } /** * * @export * @interface ModelError */ export interface ModelError { /** * * @type {string} * @memberof ModelError */ logref?: string; /** * * @type {string} * @memberof ModelError */ message?: string; } /** * * @export * @interface NotFoundException */ export interface NotFoundException { /** * * @type {string} * @memberof NotFoundException */ logref?: string; /** * * @type {string} * @memberof NotFoundException */ message?: string; } /** * * @export * @interface ReasoningJobInfo */ export interface ReasoningJobInfo { /** * unique identifier of the job * @type {string} * @memberof ReasoningJobInfo */ id?: string; /** * job status * @type {string} * @memberof ReasoningJobInfo */ status?: ReasoningJobInfo.StatusEnum; /** * job creation time * @type {Date} * @memberof ReasoningJobInfo */ timestamp?: Date; /** * * @type {any} * @memberof ReasoningJobInfo */ parameters?: any; } /** * @export * @namespace ReasoningJobInfo */ export namespace ReasoningJobInfo { /** * @export * @enum {string} */ export enum StatusEnum { SUBMITTED = <any> 'SUBMITTED', RUNNING = <any> 'RUNNING', SUCCEEDED = <any> 'SUCCEEDED', FAILED = <any> 'FAILED' } } /** * * @export * @interface SubmitReasoningRequest */ export interface SubmitReasoningRequest { /** * Name of the entity in IoT Timeseries service to read data for. * @type {string} * @memberof SubmitReasoningRequest */ asset?: string; /** * Name of the property set in IoT Timeseries service to read data for. * @type {string} * @memberof SubmitReasoningRequest */ aspect?: string; /** * List of variables to take from property set in IoT Timeseries service. Only those variables which are both in this list and in the propertySet will be taken. Also this list must be the same as the one used to train the model, in other words training and reasoning must be performed over the same variables. * @type {string} * @memberof SubmitReasoningRequest */ variables?: string; /** * Beginning of the time range to read (exclusive) from IoT Timeseries service. Date must follow the specified format 'YYYY-MM-DDThh:mm:ss'. * @type {Date} * @memberof SubmitReasoningRequest */ from?: Date; /** * End of the time range to read (inclusive) from IoT Timeseries service. Date must follow the specified format 'YYYY-MM-DDThh:mm:ss'. * @type {Date} * @memberof SubmitReasoningRequest */ to?: Date; /** * ID of the folder in Data Exchange Service to get model from. Must not be empty. * @type {string} * @memberof SubmitReasoningRequest */ modelFolderId?: string; /** * ID of the folder in Data Exchange Service to save results to. Must not be empty. * @type {string} * @memberof SubmitReasoningRequest */ resultFolderId?: string; } /** * * @export * @interface SubmitTrainingRequest */ export interface SubmitTrainingRequest { /** * Name of the entity in IoT Timeseries service to read data for. * @type {string} * @memberof SubmitTrainingRequest */ asset?: string; /** * Name of the property set in IoT Timeseries service to read data for. * @type {string} * @memberof SubmitTrainingRequest */ aspect?: string; /** * List of variables to take from property set in IoT Timeseries service. Only those variables which are both in this list and in the propertySet will be taken. List must contain up to 10 variables. * @type {string} * @memberof SubmitTrainingRequest */ variables?: string; /** * Beginning of the time range to read (exclusive) from IoT Timeseries service. Date must follow the specified format 'YYYY-MM-DDThh:mm:ss'. * @type {Date} * @memberof SubmitTrainingRequest */ from?: Date; /** * End of the time range to read (inclusive) from IoT Timeseries service. Date must follow the specified format 'YYYY-MM-DDThh:mm:ss'. * @type {Date} * @memberof SubmitTrainingRequest */ to?: Date; /** * Anomaly Detection threshold for the distance to check if point belongs to cluster. * @type {number} * @memberof SubmitTrainingRequest */ epsilon?: number; /** * Anomaly detection minimum cluster size. Positive. Minimum is 2. * @type {number} * @memberof SubmitTrainingRequest */ minPointsPerCluster?: number; /** * Name of the Anomaly Detection distance measure algorithm. * @type {string} * @memberof SubmitTrainingRequest */ distanceMeasureAlgorithm?: SubmitTrainingRequest.DistanceMeasureAlgorithmEnum; /** * ID of the folder in Data Exchange Service to save results to. Must not be empty. * @type {string} * @memberof SubmitTrainingRequest */ resultFolderId?: string; } /** * @export * @namespace SubmitTrainingRequest */ export namespace SubmitTrainingRequest { /** * @export * @enum {string} */ export enum DistanceMeasureAlgorithmEnum { EUCLIDEAN = <any> 'EUCLIDEAN', MANHATTAN = <any> 'MANHATTAN', CHEBYSHEV = <any> 'CHEBYSHEV' } } /** * * @export * @interface Timeseries */ export interface Timeseries { [key: string]: any | any; /** * time * @type {string} * @memberof Timeseries */ time: string; } /** * * @export * @interface TrainingJobInfo */ export interface TrainingJobInfo { /** * unique identifier of the job * @type {string} * @memberof TrainingJobInfo */ id?: string; /** * job status * @type {string} * @memberof TrainingJobInfo */ status?: TrainingJobInfo.StatusEnum; /** * job creation time * @type {Date} * @memberof TrainingJobInfo */ timestamp?: Date; /** * * @type {any} * @memberof TrainingJobInfo */ parameters?: any; } /** * @export * @namespace TrainingJobInfo */ export namespace TrainingJobInfo { /** * @export * @enum {string} */ export enum StatusEnum { SUBMITTED = <any> 'SUBMITTED', RUNNING = <any> 'RUNNING', SUCCEEDED = <any> 'SUCCEEDED', FAILED = <any> 'FAILED' } } /** * * @export * @interface WrongArgumentException */ export interface WrongArgumentException { /** * * @type {string} * @memberof WrongArgumentException */ logref?: string; /** * * @type {string} * @memberof WrongArgumentException */ message?: string; } /** * * @export */ export const COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; }
the_stack
import { BigNumber } from '@0x/asset-swapper'; import { expect } from '@0x/contracts-test-utils'; import { RfqOrder } from '@0x/protocol-utils'; import { Fee } from '@0x/quote-server/lib/src/types'; import 'mocha'; import { Connection } from 'typeorm'; import { getDBConnectionAsync } from '../src/db_connection'; import { RfqmJobEntity, RfqmQuoteEntity, RfqmTransactionSubmissionEntity } from '../src/entities'; import { RfqmJobStatus } from '../src/entities/RfqmJobEntity'; import { RfqmTransactionSubmissionStatus } from '../src/entities/RfqmTransactionSubmissionEntity'; import { feeToStoredFee, RfqmDbUtils, v4RfqOrderToStoredOrder } from '../src/utils/rfqm_db_utils'; import { MATCHA_AFFILIATE_ADDRESS } from './constants'; import { setupDependenciesAsync, teardownDependenciesAsync } from './utils/deployment'; // Force reload of the app avoid variables being polluted between test suites delete require.cache[require.resolve('../src/app')]; const SUITE_NAME = 'rfqm db test'; describe(SUITE_NAME, () => { let connection: Connection; let dbUtils: RfqmDbUtils; const createdAt = new Date(); // it's expired if it's over 9000 const expiry = new BigNumber(9000); const chainId = 1; const makerUri = 'https://marketmaking.over9000.io'; const integratorId = 'an integrator'; const metaTransactionHash = '0x5678'; const calldata = '0xfillinganorder'; const fee: Fee = { token: '0xatoken', amount: new BigNumber(5), type: 'fixed', }; const order = new RfqOrder({ txOrigin: '0x0000000000000000000000000000000000000000', taker: '0x1111111111111111111111111111111111111111', maker: '0x2222222222222222222222222222222222222222', makerToken: '0x3333333333333333333333333333333333333333', takerToken: '0x4444444444444444444444444444444444444444', expiry, salt: new BigNumber(1), chainId, verifyingContract: '0x0000000000000000000000000000000000000000', pool: '0x1', }); const orderHash = order.getHash(); // tx properties const transactionHash = '0x5678'; const from = '0xanRfqmWorker'; const to = '0xexchangeProxyAddress'; const gasPrice = new BigNumber('100'); const gasUsed = null; const blockMined = null; const nonce = 0; before(async () => { await setupDependenciesAsync(SUITE_NAME); connection = await getDBConnectionAsync(); await connection.synchronize(true); dbUtils = new RfqmDbUtils(connection); }); after(async () => { // reset DB connection = await getDBConnectionAsync(); await connection.synchronize(true); await teardownDependenciesAsync(SUITE_NAME); }); beforeEach(async () => { // reset DB connection = await getDBConnectionAsync(); await connection.synchronize(true); dbUtils = new RfqmDbUtils(connection); }); describe('rfqm db tests', () => { it("should use the database's timestamp", async () => { const testRfqmQuoteEntity = new RfqmQuoteEntity({ orderHash, metaTransactionHash, integratorId, chainId, makerUri, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), }); const quoteRepository = connection.getRepository(RfqmQuoteEntity); await quoteRepository.save(testRfqmQuoteEntity); const dbEntity = await quoteRepository.findOne(); const { createdAt: recordCreatedAt } = dbEntity!; expect(recordCreatedAt.getTime()).to.be.a('number'); const timeDiff = Math.abs(Date.now() - recordCreatedAt.getTime()); const tenMinutesMs = 10 * 60 * 1000; // tslint:disable-line custom-no-magic-numbers expect(timeDiff).to.be.lessThan(tenMinutesMs); }); it('should be able to save and read an rfqm quote entity w/ no change in information', async () => { const testRfqmQuoteEntity = new RfqmQuoteEntity({ orderHash, metaTransactionHash, createdAt, integratorId, chainId, makerUri, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), affiliateAddress: MATCHA_AFFILIATE_ADDRESS, }); const quoteRepository = connection.getRepository(RfqmQuoteEntity); await quoteRepository.save(testRfqmQuoteEntity); const dbEntity = await quoteRepository.findOne(); // the saved + read entity should match the original entity in information expect(dbEntity).to.deep.eq(testRfqmQuoteEntity); }); it('should be able to save and read an rfqm job entity w/ no change in information', async () => { const rfqmJobOpts = { orderHash, metaTransactionHash, createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingEnqueued, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), affiliateAddress: MATCHA_AFFILIATE_ADDRESS, }; const testRfqmJobEntity = new RfqmJobEntity(rfqmJobOpts); await dbUtils.writeRfqmJobToDbAsync(rfqmJobOpts); const dbEntity = await dbUtils.findJobByOrderHashAsync(orderHash); // the saved + read entity should match the original entity in information expect(dbEntity).to.deep.eq(testRfqmJobEntity); }); it('should be able to update an rfqm job entity', async () => { const rfqmJobOpts = { orderHash, metaTransactionHash, createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingEnqueued, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), affiliateAddress: MATCHA_AFFILIATE_ADDRESS, }; await dbUtils.writeRfqmJobToDbAsync(rfqmJobOpts); const dbEntityFirstSnapshot = await dbUtils.findJobByOrderHashAsync(orderHash); await dbUtils.updateRfqmJobAsync(orderHash, false, { status: RfqmJobStatus.PendingProcessing }); const dbEntitySecondSnapshot = await dbUtils.findJobByOrderHashAsync(orderHash); // expect status to be updated expect(dbEntityFirstSnapshot?.status).to.eq(RfqmJobStatus.PendingEnqueued); expect(dbEntitySecondSnapshot?.status).to.eq(RfqmJobStatus.PendingProcessing); // spot check that other values have not changed expect(dbEntityFirstSnapshot?.calldata).to.eq(dbEntitySecondSnapshot?.calldata); expect(dbEntityFirstSnapshot?.expiry).to.deep.eq(dbEntitySecondSnapshot?.expiry); }); it('should be able to save and read an rfqm tx submission entity w/ no change in information', async () => { // need a pre-existing job entity bc of foreign key const rfqmJobOpts = { orderHash, metaTransactionHash, createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingEnqueued, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), }; await dbUtils.writeRfqmJobToDbAsync(rfqmJobOpts); const rfqmTransactionSubmissionEntityOpts: Partial<RfqmTransactionSubmissionEntity> = { transactionHash, orderHash, createdAt, from, to, gasPrice, gasUsed, blockMined, nonce, status: RfqmTransactionSubmissionStatus.Submitted, statusReason: null, }; const testEntity = new RfqmTransactionSubmissionEntity(rfqmTransactionSubmissionEntityOpts); await dbUtils.writeRfqmTransactionSubmissionToDbAsync(rfqmTransactionSubmissionEntityOpts); const dbEntity = await dbUtils.findRfqmTransactionSubmissionByTransactionHashAsync(transactionHash); // the saved + read entity should match the original entity in information expect(dbEntity).to.deep.eq(testEntity); }); it('should be able to update a transaction submission entity', async () => { // need a pre-existing job entity bc of foreign key const rfqmJobOpts = { orderHash, metaTransactionHash, createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingEnqueued, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), }; await dbUtils.writeRfqmJobToDbAsync(rfqmJobOpts); const rfqmTransactionSubmissionEntityOpts: Partial<RfqmTransactionSubmissionEntity> = { transactionHash, orderHash, createdAt, from, to, gasPrice, gasUsed, blockMined, nonce, status: RfqmTransactionSubmissionStatus.Submitted, statusReason: null, }; await dbUtils.writeRfqmTransactionSubmissionToDbAsync(rfqmTransactionSubmissionEntityOpts); const initialEntity = await dbUtils.findRfqmTransactionSubmissionByTransactionHashAsync(transactionHash); const updatedAt = new Date(); const newBlockMined = new BigNumber(5); const newGasUsed = new BigNumber('165000'); const newStatus = RfqmTransactionSubmissionStatus.SucceededUnconfirmed; initialEntity!.updatedAt = updatedAt; initialEntity!.blockMined = newBlockMined; initialEntity!.gasUsed = newGasUsed; initialEntity!.status = newStatus; await dbUtils.updateRfqmTransactionSubmissionsAsync([initialEntity!]); const updatedEntity = await dbUtils.findRfqmTransactionSubmissionByTransactionHashAsync(transactionHash); // the saved + read entity should match the original entity in information expect(updatedEntity?.updatedAt).to.deep.eq(updatedAt); expect(updatedEntity?.blockMined).to.deep.eq(newBlockMined); expect(updatedEntity?.gasUsed).to.deep.eq(newGasUsed); expect(updatedEntity?.status).to.deep.eq(newStatus); expect(updatedEntity?.createdAt).to.deep.eq(createdAt); }); it('should find unresolved jobs', async () => { const workerAddress = '0x123'; const unresolvedJob1 = { orderHash, metaTransactionHash, createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingEnqueued, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), workerAddress, isCompleted: false, }; const unresolvedJob2 = { orderHash: '0x1234', metaTransactionHash: '0x1234', createdAt, expiry, chainId, integratorId, makerUri, status: RfqmJobStatus.PendingSubmitted, statusReason: null, calldata, fee: feeToStoredFee(fee), order: v4RfqOrderToStoredOrder(order), workerAddress, isCompleted: false, }; await dbUtils.writeRfqmJobToDbAsync(unresolvedJob1); await dbUtils.writeRfqmJobToDbAsync(unresolvedJob2); const unresolvedJobs = await dbUtils.findUnresolvedJobsAsync(workerAddress); expect(unresolvedJobs.length).to.deep.eq(2); expect(unresolvedJobs[0].orderHash).to.deep.eq(orderHash); expect(unresolvedJobs[1].orderHash).to.deep.eq('0x1234'); }); }); }); // tslint:disable-line:max-file-line-count
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { NotificationHubs } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NotificationHubsManagementClient } from "../notificationHubsManagementClient"; import { NotificationHubResource, NotificationHubsListNextOptionalParams, NotificationHubsListOptionalParams, SharedAccessAuthorizationRuleResource, NotificationHubsListAuthorizationRulesNextOptionalParams, NotificationHubsListAuthorizationRulesOptionalParams, CheckAvailabilityParameters, NotificationHubsCheckNotificationHubAvailabilityOptionalParams, NotificationHubsCheckNotificationHubAvailabilityResponse, NotificationHubCreateOrUpdateParameters, NotificationHubsCreateOrUpdateOptionalParams, NotificationHubsCreateOrUpdateResponse, NotificationHubsPatchOptionalParams, NotificationHubsPatchResponse, NotificationHubsDeleteOptionalParams, NotificationHubsGetOptionalParams, NotificationHubsGetResponse, NotificationHubsDebugSendOptionalParams, NotificationHubsDebugSendResponse, SharedAccessAuthorizationRuleCreateOrUpdateParameters, NotificationHubsCreateOrUpdateAuthorizationRuleOptionalParams, NotificationHubsCreateOrUpdateAuthorizationRuleResponse, NotificationHubsDeleteAuthorizationRuleOptionalParams, NotificationHubsGetAuthorizationRuleOptionalParams, NotificationHubsGetAuthorizationRuleResponse, NotificationHubsListResponse, NotificationHubsListAuthorizationRulesResponse, NotificationHubsListKeysOptionalParams, NotificationHubsListKeysResponse, PolicykeyResource, NotificationHubsRegenerateKeysOptionalParams, NotificationHubsRegenerateKeysResponse, NotificationHubsGetPnsCredentialsOptionalParams, NotificationHubsGetPnsCredentialsResponse, NotificationHubsListNextResponse, NotificationHubsListAuthorizationRulesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing NotificationHubs operations. */ export class NotificationHubsImpl implements NotificationHubs { private readonly client: NotificationHubsManagementClient; /** * Initialize a new instance of the class NotificationHubs class. * @param client Reference to the service client */ constructor(client: NotificationHubsManagementClient) { this.client = client; } /** * Lists the notification hubs associated with a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param options The options parameters. */ public list( resourceGroupName: string, namespaceName: string, options?: NotificationHubsListOptionalParams ): PagedAsyncIterableIterator<NotificationHubResource> { const iter = this.listPagingAll(resourceGroupName, namespaceName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, namespaceName, options); } }; } private async *listPagingPage( resourceGroupName: string, namespaceName: string, options?: NotificationHubsListOptionalParams ): AsyncIterableIterator<NotificationHubResource[]> { let result = await this._list(resourceGroupName, namespaceName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, namespaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, namespaceName: string, options?: NotificationHubsListOptionalParams ): AsyncIterableIterator<NotificationHubResource> { for await (const page of this.listPagingPage( resourceGroupName, namespaceName, options )) { yield* page; } } /** * Gets the authorization rules for a NotificationHub. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param notificationHubName The notification hub name. * @param options The options parameters. */ public listAuthorizationRules( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsListAuthorizationRulesOptionalParams ): PagedAsyncIterableIterator<SharedAccessAuthorizationRuleResource> { const iter = this.listAuthorizationRulesPagingAll( resourceGroupName, namespaceName, notificationHubName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, notificationHubName, options ); } }; } private async *listAuthorizationRulesPagingPage( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SharedAccessAuthorizationRuleResource[]> { let result = await this._listAuthorizationRules( resourceGroupName, namespaceName, notificationHubName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAuthorizationRulesNext( resourceGroupName, namespaceName, notificationHubName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAuthorizationRulesPagingAll( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SharedAccessAuthorizationRuleResource> { for await (const page of this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, notificationHubName, options )) { yield* page; } } /** * Checks the availability of the given notificationHub in a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param parameters The notificationHub name. * @param options The options parameters. */ checkNotificationHubAvailability( resourceGroupName: string, namespaceName: string, parameters: CheckAvailabilityParameters, options?: NotificationHubsCheckNotificationHubAvailabilityOptionalParams ): Promise<NotificationHubsCheckNotificationHubAvailabilityResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, parameters, options }, checkNotificationHubAvailabilityOperationSpec ); } /** * Creates/Update a NotificationHub in a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param parameters Parameters supplied to the create/update a NotificationHub Resource. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, notificationHubName: string, parameters: NotificationHubCreateOrUpdateParameters, options?: NotificationHubsCreateOrUpdateOptionalParams ): Promise<NotificationHubsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, parameters, options }, createOrUpdateOperationSpec ); } /** * Patch a NotificationHub in a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param options The options parameters. */ patch( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsPatchOptionalParams ): Promise<NotificationHubsPatchResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, patchOperationSpec ); } /** * Deletes a notification hub associated with a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param options The options parameters. */ delete( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, deleteOperationSpec ); } /** * Lists the notification hubs associated with a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsGetOptionalParams ): Promise<NotificationHubsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, getOperationSpec ); } /** * test send a push notification * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param options The options parameters. */ debugSend( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsDebugSendOptionalParams ): Promise<NotificationHubsDebugSendResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, debugSendOperationSpec ); } /** * Creates/Updates an authorization rule for a NotificationHub * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param authorizationRuleName Authorization Rule Name. * @param parameters The shared access authorization rule. * @param options The options parameters. */ createOrUpdateAuthorizationRule( resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: SharedAccessAuthorizationRuleCreateOrUpdateParameters, options?: NotificationHubsCreateOrUpdateAuthorizationRuleOptionalParams ): Promise<NotificationHubsCreateOrUpdateAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters, options }, createOrUpdateAuthorizationRuleOperationSpec ); } /** * Deletes a notificationHub authorization rule * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param authorizationRuleName Authorization Rule Name. * @param options The options parameters. */ deleteAuthorizationRule( resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: NotificationHubsDeleteAuthorizationRuleOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options }, deleteAuthorizationRuleOperationSpec ); } /** * Gets an authorization rule for a NotificationHub by name. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param notificationHubName The notification hub name. * @param authorizationRuleName authorization rule name. * @param options The options parameters. */ getAuthorizationRule( resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: NotificationHubsGetAuthorizationRuleOptionalParams ): Promise<NotificationHubsGetAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options }, getAuthorizationRuleOperationSpec ); } /** * Lists the notification hubs associated with a namespace. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param options The options parameters. */ private _list( resourceGroupName: string, namespaceName: string, options?: NotificationHubsListOptionalParams ): Promise<NotificationHubsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, listOperationSpec ); } /** * Gets the authorization rules for a NotificationHub. * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param notificationHubName The notification hub name. * @param options The options parameters. */ private _listAuthorizationRules( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsListAuthorizationRulesOptionalParams ): Promise<NotificationHubsListAuthorizationRulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, listAuthorizationRulesOperationSpec ); } /** * Gets the Primary and Secondary ConnectionStrings to the NotificationHub * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param authorizationRuleName The connection string of the NotificationHub for the specified * authorizationRule. * @param options The options parameters. */ listKeys( resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, options?: NotificationHubsListKeysOptionalParams ): Promise<NotificationHubsListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options }, listKeysOperationSpec ); } /** * Regenerates the Primary/Secondary Keys to the NotificationHub Authorization Rule * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param authorizationRuleName The connection string of the NotificationHub for the specified * authorizationRule. * @param parameters Parameters supplied to regenerate the NotificationHub Authorization Rule Key. * @param options The options parameters. */ regenerateKeys( resourceGroupName: string, namespaceName: string, notificationHubName: string, authorizationRuleName: string, parameters: PolicykeyResource, options?: NotificationHubsRegenerateKeysOptionalParams ): Promise<NotificationHubsRegenerateKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters, options }, regenerateKeysOperationSpec ); } /** * Lists the PNS Credentials associated with a notification hub . * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param notificationHubName The notification hub name. * @param options The options parameters. */ getPnsCredentials( resourceGroupName: string, namespaceName: string, notificationHubName: string, options?: NotificationHubsGetPnsCredentialsOptionalParams ): Promise<NotificationHubsGetPnsCredentialsResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, options }, getPnsCredentialsOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, namespaceName: string, nextLink: string, options?: NotificationHubsListNextOptionalParams ): Promise<NotificationHubsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, nextLink, options }, listNextOperationSpec ); } /** * ListAuthorizationRulesNext * @param resourceGroupName The name of the resource group. * @param namespaceName The namespace name * @param notificationHubName The notification hub name. * @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method. * @param options The options parameters. */ private _listAuthorizationRulesNext( resourceGroupName: string, namespaceName: string, notificationHubName: string, nextLink: string, options?: NotificationHubsListAuthorizationRulesNextOptionalParams ): Promise<NotificationHubsListAuthorizationRulesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, notificationHubName, nextLink, options }, listAuthorizationRulesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const checkNotificationHubAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/checkNotificationHubAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CheckAvailabilityResult } }, requestBody: Parameters.parameters, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.NotificationHubResource }, 201: { bodyMapper: Mappers.NotificationHubResource } }, requestBody: Parameters.parameters5, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patchOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.NotificationHubResource } }, requestBody: Parameters.parameters6, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}", httpMethod: "DELETE", responses: { 200: {} }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NotificationHubResource } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer }; const debugSendOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/debugsend", httpMethod: "POST", responses: { 201: { bodyMapper: Mappers.DebugSendResponse } }, requestBody: Parameters.parameters7, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createOrUpdateAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleResource } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.notificationHubName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {} }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.notificationHubName ], serializer }; const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleResource } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NotificationHubListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer }; const listKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}/listKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ResourceListKeys } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer }; const regenerateKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ResourceListKeys } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.notificationHubName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getPnsCredentialsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/pnsCredentials", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.PnsCredentialsResource } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NotificationHubListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SharedAccessAuthorizationRuleListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.notificationHubName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { BackstageTheme } from '@backstage/theme'; import { makeStyles, useTheme, withStyles } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; // Material-table is not using the standard icons available in in material-ui. https://github.com/mbrn/material-table/issues/51 import AddBox from '@material-ui/icons/AddBox'; import ArrowUpward from '@material-ui/icons/ArrowUpward'; import Check from '@material-ui/icons/Check'; import ChevronLeft from '@material-ui/icons/ChevronLeft'; import ChevronRight from '@material-ui/icons/ChevronRight'; import Clear from '@material-ui/icons/Clear'; import DeleteOutline from '@material-ui/icons/DeleteOutline'; import Edit from '@material-ui/icons/Edit'; import FilterList from '@material-ui/icons/FilterList'; import FirstPage from '@material-ui/icons/FirstPage'; import LastPage from '@material-ui/icons/LastPage'; import Remove from '@material-ui/icons/Remove'; import SaveAlt from '@material-ui/icons/SaveAlt'; import ViewColumn from '@material-ui/icons/ViewColumn'; import { isEqual, transform } from 'lodash'; import MTable, { Column, Icons, MaterialTableProps, MTableBody, MTableHeader, MTableToolbar, Options, } from '@material-table/core'; import React, { forwardRef, MutableRefObject, ReactNode, useCallback, useEffect, useState, } from 'react'; import { SelectProps } from '../Select/Select'; import { Filter, Filters, SelectedFilters, Without } from './Filters'; const tableIcons: Icons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />), Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />), DetailPanel: forwardRef((props, ref) => ( <ChevronRight {...props} ref={ref} /> )), Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />), Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />), Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />), LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />), NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />), PreviousPage: forwardRef((props, ref) => ( <ChevronLeft {...props} ref={ref} /> )), ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />), Search: forwardRef((props, ref) => <FilterList {...props} ref={ref} />), SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />), ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />), ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />), }; // TODO: Material table might already have such a function internally that we can use? function extractValueByField(data: any, field: string): any | undefined { const path = field.split('.'); let value = data[path[0]]; for (let i = 1; i < path.length; ++i) { if (value === undefined) { return value; } const f = path[i]; value = value[f]; } return value; } export type TableHeaderClassKey = 'header'; const StyledMTableHeader = withStyles( theme => ({ header: { padding: theme.spacing(1, 2, 1, 2.5), borderTop: `1px solid ${theme.palette.grey.A100}`, borderBottom: `1px solid ${theme.palette.grey.A100}`, // withStyles hasn't a generic overload for theme color: (theme as BackstageTheme).palette.textSubtle, fontWeight: theme.typography.fontWeightBold, position: 'static', wordBreak: 'normal', }, }), { name: 'BackstageTableHeader' }, )(MTableHeader); export type TableToolbarClassKey = 'root' | 'title' | 'searchField'; const StyledMTableToolbar = withStyles( theme => ({ root: { padding: theme.spacing(3, 0, 2.5, 2.5), }, title: { '& > h6': { fontWeight: 'bold', }, }, searchField: { paddingRight: theme.spacing(2), }, }), { name: 'BackstageTableToolbar' }, )(MTableToolbar); export type FiltersContainerClassKey = 'root' | 'title'; const useFilterStyles = makeStyles<BackstageTheme>( () => ({ root: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', }, title: { fontWeight: 'bold', fontSize: 18, whiteSpace: 'nowrap', }, }), { name: 'BackstageTableFiltersContainer' }, ); export type TableClassKey = 'root'; const useTableStyles = makeStyles<BackstageTheme>( () => ({ root: { display: 'flex', alignItems: 'start', }, }), { name: 'BackstageTable' }, ); function convertColumns<T extends object>( columns: TableColumn<T>[], theme: BackstageTheme, ): TableColumn<T>[] { return columns.map(column => { const headerStyle: React.CSSProperties = {}; const cellStyle: React.CSSProperties = typeof column.cellStyle === 'object' ? column.cellStyle : {}; if (column.highlight) { headerStyle.color = theme.palette.textContrast; cellStyle.fontWeight = theme.typography.fontWeightBold; } return { ...column, headerStyle, cellStyle, }; }); } function removeDefaultValues(state: any, defaultState: any): any { return transform(state, (result, value, key) => { if (!isEqual(value, defaultState[key])) { result[key] = value; } }); } const defaultInitialState = { search: '', filtersOpen: false, filters: {}, }; export interface TableColumn<T extends object = {}> extends Column<T> { highlight?: boolean; width?: string; } export type TableFilter = { column: string; type: 'select' | 'multiple-select'; }; export type TableState = { search?: string; filtersOpen?: boolean; filters?: SelectedFilters; }; export interface TableProps<T extends object = {}> extends MaterialTableProps<T> { columns: TableColumn<T>[]; subtitle?: string; filters?: TableFilter[]; initialState?: TableState; emptyContent?: ReactNode; onStateChange?: (state: TableState) => any; } export function TableToolbar(toolbarProps: { toolbarRef: MutableRefObject<any>; setSearch: (value: string) => void; onSearchChanged: (value: string) => void; toggleFilters: () => void; hasFilters: boolean; selectedFiltersLength: number; }) { const { toolbarRef, setSearch, hasFilters, selectedFiltersLength, toggleFilters, } = toolbarProps; const filtersClasses = useFilterStyles(); const onSearchChanged = useCallback( (searchText: string) => { toolbarProps.onSearchChanged(searchText); setSearch(searchText); }, [toolbarProps, setSearch], ); if (hasFilters) { return ( <div className={filtersClasses.root}> <div className={filtersClasses.root}> <IconButton onClick={toggleFilters} aria-label="filter list"> <FilterList /> </IconButton> <Typography className={filtersClasses.title}> Filters ({selectedFiltersLength}) </Typography> </div> <StyledMTableToolbar {...toolbarProps} ref={toolbarRef} onSearchChanged={onSearchChanged} /> </div> ); } return ( <StyledMTableToolbar {...toolbarProps} ref={toolbarRef} onSearchChanged={onSearchChanged} /> ); } export function Table<T extends object = {}>(props: TableProps<T>) { const { data, columns, options, title, subtitle, filters, initialState, emptyContent, onStateChange, ...restProps } = props; const tableClasses = useTableStyles(); const theme = useTheme<BackstageTheme>(); const calculatedInitialState = { ...defaultInitialState, ...initialState }; const [filtersOpen, setFiltersOpen] = useState( calculatedInitialState.filtersOpen, ); const toggleFilters = useCallback( () => setFiltersOpen(v => !v), [setFiltersOpen], ); const [selectedFiltersLength, setSelectedFiltersLength] = useState(0); const [tableData, setTableData] = useState(data as any[]); const [selectedFilters, setSelectedFilters] = useState( calculatedInitialState.filters, ); const MTColumns = convertColumns(columns, theme); const [search, setSearch] = useState(calculatedInitialState.search); useEffect(() => { if (onStateChange) { const state = removeDefaultValues( { search, filtersOpen, filters: selectedFilters, }, defaultInitialState, ); onStateChange(state); } }, [search, filtersOpen, selectedFilters, onStateChange]); const defaultOptions: Options<T> = { headerStyle: { textTransform: 'uppercase', }, }; const getFieldByTitle = useCallback( (titleValue: string | keyof T) => columns.find(el => el.title === titleValue)?.field, [columns], ); useEffect(() => { if (typeof data === 'function') { return; } if (!selectedFilters) { setTableData(data as any[]); return; } const selectedFiltersArray = Object.values(selectedFilters); if (data && selectedFiltersArray.flat().length) { const newData = (data as any[]).filter( el => !!Object.entries(selectedFilters) .filter(([, value]) => !!value.length) .every(([key, filterValue]) => { const fieldValue = extractValueByField( el, getFieldByTitle(key) as string, ); if (Array.isArray(fieldValue) && Array.isArray(filterValue)) { return fieldValue.some(v => filterValue.includes(v)); } else if (Array.isArray(fieldValue)) { return fieldValue.includes(filterValue); } else if (Array.isArray(filterValue)) { return filterValue.includes(fieldValue); } return fieldValue === filterValue; }), ); setTableData(newData); } else { setTableData(data as any[]); } setSelectedFiltersLength(selectedFiltersArray.flat().length); }, [data, selectedFilters, getFieldByTitle]); const constructFilters = ( filterConfig: TableFilter[], dataValue: any[] | undefined, ): Filter[] => { const extractDistinctValues = (field: string | keyof T): Set<any> => { const distinctValues = new Set<any>(); const addValue = (value: any) => { if (value !== undefined && value !== null) { distinctValues.add(value); } }; if (dataValue) { dataValue.forEach(el => { const value = extractValueByField( el, getFieldByTitle(field) as string, ); if (Array.isArray(value)) { (value as []).forEach(addValue); } else { addValue(value); } }); } return distinctValues; }; const constructSelect = ( filter: TableFilter, ): Without<SelectProps, 'onChange'> => { return { placeholder: 'All results', label: filter.column, multiple: filter.type === 'multiple-select', items: [...extractDistinctValues(filter.column)].sort().map(value => ({ label: value, value, })), }; }; return filterConfig.map(filter => ({ type: filter.type, element: constructSelect(filter), })); }; const hasFilters = !!filters?.length; const Toolbar = useCallback( toolbarProps => { return ( <TableToolbar setSearch={setSearch} hasFilters={hasFilters} selectedFiltersLength={selectedFiltersLength} toggleFilters={toggleFilters} {...toolbarProps} /> ); }, [toggleFilters, hasFilters, selectedFiltersLength, setSearch], ); const hasNoRows = typeof data !== 'function' && data.length === 0; const columnCount = columns.length; const Body = useCallback( bodyProps => { if (emptyContent && hasNoRows) { return ( <tbody> <tr> <td colSpan={columnCount}>{emptyContent}</td> </tr> </tbody> ); } return <MTableBody {...bodyProps} />; }, [hasNoRows, emptyContent, columnCount], ); return ( <div className={tableClasses.root}> {filtersOpen && data && typeof data !== 'function' && filters?.length && ( <Filters filters={constructFilters(filters, data as any[])} selectedFilters={selectedFilters} onChangeFilters={setSelectedFilters} /> )} <MTable<T> components={{ Header: StyledMTableHeader, Toolbar, Body, }} options={{ ...defaultOptions, ...options }} columns={MTColumns} icons={tableIcons} title={ <> <Typography variant="h5" component="h3"> {title} </Typography> {subtitle && ( <Typography color="textSecondary" variant="body1"> {subtitle} </Typography> )} </> } data={typeof data === 'function' ? data : tableData} style={{ width: '100%' }} localization={{ toolbar: { searchPlaceholder: 'Filter' } }} {...restProps} /> </div> ); }
the_stack
import { mockedPoller, runMockedLro } from "./utils/router"; import { RawResponse } from "../src/lroEngine/models"; import { assert } from "chai"; describe("Lro Engine", function () { it("put201Succeeded", async function () { const result = await runMockedLro("PUT", "/put/201/succeeded"); assert.equal(result.id, "100"); assert.equal(result.name, "foo"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); describe("BodyPolling Strategy", () => { it("put200Succeeded", async function () { const result = await runMockedLro("PUT", "/put/200/succeeded"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle initial response with terminal state without provisioning State", async () => { const result = await runMockedLro("PUT", "/put/200/succeeded/nostate"); assert.deepEqual(result.id, "100"); assert.deepEqual(result.name, "foo"); }); it("should handle initial response creating followed by success through an Azure Resource", async () => { const result = await runMockedLro("PUT", "/put/201/creating/succeeded/200"); assert.deepEqual(result.properties?.provisioningState, "Succeeded"); assert.deepEqual(result.id, "100"); assert.deepEqual(result.name, "foo"); }); it("should handle put200Acceptedcanceled200", async () => { try { await runMockedLro("PUT", "/put/200/accepted/canceled/200"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: canceled." ); } }); it("should handle put200UpdatingSucceeded204", async () => { const result = await runMockedLro("PUT", "/put/200/updating/succeeded/200"); assert.deepEqual(result.properties?.provisioningState, "Succeeded"); assert.deepEqual(result.id, "100"); assert.deepEqual(result.name, "foo"); }); it("should handle put201CreatingFailed200", async () => { try { await runMockedLro("PUT", "/put/201/created/failed/200"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: failed." ); } }); }); describe("Location Strategy", () => { it("should handle post202Retry200", async () => { const response = await runMockedLro("POST", "/post/202/retry/200"); assert.equal(response.statusCode, 200); }); it("should handle post202NoRetry204", async () => { try { await runMockedLro("POST", "/post/202/noretry/204"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "Received unexpected HTTP status code 204 while polling. This may indicate a server issue." ); } }); it("should handle deleteNoHeaderInRetry", async () => { try { await runMockedLro("DELETE", "/delete/noheader"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "Received unexpected HTTP status code 204 while polling. This may indicate a server issue." ); } }); it("should handle put202Retry200", async () => { const response = await runMockedLro("PUT", "/put/202/retry/200"); assert.equal(response.statusCode, 200); }); it("should handle putNoHeaderInRetry", async () => { const result = await runMockedLro("PUT", "/put/noheader/202/200"); assert.equal(result.id, "100"); assert.equal(result.name, "foo"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle putSubResource", async () => { const result = await runMockedLro("PUT", "/putsubresource/202/200"); assert.equal(result.id, "100"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle putNonResource", async () => { const result = await runMockedLro("PUT", "/putnonresource/202/200"); assert.equal(result.id, "100"); assert.equal(result.name, "sku"); }); it("should handle delete202Retry200", async () => { const response = await runMockedLro("DELETE", "/delete/202/retry/200"); assert.equal(response.statusCode, 200); }); it("should handle delete202NoRetry204", async () => { try { await runMockedLro("DELETE", "/delete/202/noretry/204"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "Received unexpected HTTP status code 204 while polling. This may indicate a server issue." ); } }); it("should handle deleteProvisioning202Accepted200Succeeded", async () => { const response = await runMockedLro( "DELETE", "/delete/provisioning/202/accepted/200/succeeded" ); assert.equal(response.statusCode, 200); }); it("should handle deleteProvisioning202DeletingFailed200", async () => { const result = await runMockedLro("DELETE", "/delete/provisioning/202/deleting/200/failed"); assert.equal(result.properties?.provisioningState, "Failed"); }); it("should handle deleteProvisioning202Deletingcanceled200", async () => { const result = await runMockedLro("DELETE", "/delete/provisioning/202/deleting/200/canceled"); assert.equal(result.properties?.provisioningState, "Canceled"); }); }); describe("Passthrough strategy", () => { it("should handle delete204Succeeded", async () => { const response = await runMockedLro("DELETE", "/delete/204/succeeded"); assert.equal(response.statusCode, 204); }); }); describe("Azure Async Operation Strategy", () => { it("should handle postDoubleHeadersFinalLocationGet", async () => { const result = await runMockedLro("POST", "/LROPostDoubleHeadersFinalLocationGet"); assert.equal(result.id, "100"); assert.equal(result.name, "foo"); }); it("should handle postDoubleHeadersFinalAzureHeaderGet", async () => { const result = await runMockedLro( "POST", "/LROPostDoubleHeadersFinalAzureHeaderGet", undefined, "azure-async-operation" ); assert.equal(result.id, "100"); }); it("should handle post200WithPayload", async () => { const result = await runMockedLro("POST", "/post/payload/200"); assert.equal(result.id, "1"); assert.equal(result.name, "product"); }); it("should handle postDoubleHeadersFinalAzureHeaderGetDefault", async () => { const result = await runMockedLro("POST", "/LROPostDoubleHeadersFinalAzureHeaderGetDefault"); assert.equal(result.id, "100"); assert.equal(result.statusCode, 200); }); it("should handle deleteAsyncRetrySucceeded", async () => { const response = await runMockedLro("DELETE", "/deleteasync/retry/succeeded"); assert.equal(response.statusCode, 200); }); it("should handle deleteAsyncNoRetrySucceeded", async () => { const response = await runMockedLro("DELETE", "/deleteasync/noretry/succeeded"); assert.equal(response.statusCode, 200); }); it("should handle deleteAsyncRetrycanceled", async () => { try { await runMockedLro("DELETE", "/deleteasync/retry/canceled"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: canceled." ); } }); it("should handle DeleteAsyncRetryFailed", async () => { try { await runMockedLro("DELETE", "/deleteasync/retry/failed"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: failed." ); } }); it("should handle putAsyncRetrySucceeded", async () => { const result = await runMockedLro("PUT", "/putasync/noretry/succeeded"); assert.equal(result.id, "100"); assert.equal(result.name, "foo"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle put201Succeeded", async () => { const result = await runMockedLro("PUT", "/put/201/succeeded"); assert.equal(result.id, "100"); assert.equal(result.name, "foo"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle post202List", async () => { const result = await runMockedLro("POST", "/list"); assert.equal((result as any)[0].id, "100"); assert.equal((result as any)[0].name, "foo"); }); it("should handle putAsyncRetryFailed", async () => { try { await runMockedLro("PUT", "/putasync/retry/failed"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: failed." ); } }); it("should handle putAsyncNonResource", async () => { const result = await runMockedLro("PUT", "/putnonresourceasync/202/200"); assert.equal(result.name, "sku"); assert.equal(result.id, "100"); }); it("should handle patchAsync", async () => { const result = await runMockedLro("PATCH", "/patchasync/202/200"); assert.equal(result.name, "sku"); assert.equal(result.id, "100"); }); it("should handle putAsyncNoHeaderInRetry", async () => { const result = await runMockedLro("PUT", "/putasync/noheader/201/200"); assert.equal(result.name, "foo"); assert.equal(result.id, "100"); assert.deepEqual(result.properties?.provisioningState, "Succeeded"); }); it("should handle putAsyncNoRetrySucceeded", async () => { const result = await runMockedLro("PUT", "/putasync/noretry/succeeded"); assert.equal(result.name, "foo"); assert.equal(result.id, "100"); }); it("should handle putAsyncNoRetrycanceled", async () => { try { await runMockedLro("PUT", "/putasync/noretry/canceled"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: canceled." ); } }); it("should handle putAsyncSubResource", async () => { const result = await runMockedLro("PUT", "/putsubresourceasync/202/200"); assert.equal(result.id, "100"); assert.equal(result.properties?.provisioningState, "Succeeded"); }); it("should handle deleteAsyncNoHeaderInRetry", async () => { const response = await runMockedLro("DELETE", "/deleteasync/noheader/202/204"); assert.equal(response.statusCode, 200); }); it("should handle postAsyncNoRetrySucceeded", async () => { const result = await runMockedLro("POST", "/postasync/noretry/succeeded"); assert.deepInclude(result, { id: "100", name: "foo" }); }); it("should handle postAsyncRetryFailed", async () => { try { await runMockedLro("POST", "/postasync/retry/failed"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: failed." ); } }); it("should handle postAsyncRetrySucceeded", async () => { const result = await runMockedLro("POST", "/postasync/retry/succeeded"); assert.deepInclude(result, { id: "100", name: "foo" }); }); it("should handle postAsyncRetrycanceled", async () => { try { await runMockedLro("POST", "/postasync/retry/canceled"); throw new Error("should have thrown instead"); } catch (e) { assert.equal( e.message, "The long running operation has failed. The provisioning state: canceled." ); } }); }); describe("LRO Sad scenarios", () => { it("should handle PutNonRetry400 ", async () => { try { await runMockedLro("PUT", "/nonretryerror/put/400"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle putNonRetry201Creating400 ", async () => { try { await runMockedLro("PUT", "/nonretryerror/put/201/creating/400"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should throw with putNonRetry201Creating400InvalidJson ", async () => { try { await runMockedLro("PUT", "/nonretryerror/put/201/creating/400/invalidjson"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle putAsyncRelativeRetry400 ", async () => { try { await runMockedLro("PUT", "/nonretryerror/putasync/retry/400"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle delete202NonRetry400 ", async () => { try { await runMockedLro("DELETE", "/nonretryerror/delete/202/retry/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle deleteNonRetry400 ", async () => { try { await runMockedLro("DELETE", "/nonretryerror/delete/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle deleteAsyncRelativeRetry400 ", async () => { try { await runMockedLro("DELETE", "/nonretryerror/deleteasync/retry/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle postNonRetry400 ", async () => { try { await runMockedLro("POST", "/nonretryerror/post/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle post202NonRetry400 ", async () => { try { await runMockedLro("POST", "/nonretryerror/post/202/retry/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle postAsyncRelativeRetry400 ", async () => { try { await runMockedLro("POST", "/nonretryerror/postasync/retry/400"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 400); } }); it("should handle PutError201NoProvisioningStatePayload ", async () => { const response = await runMockedLro("PUT", "/error/put/201/noprovisioningstatepayload"); assert.equal(response.statusCode, 201); // weird! }); it("should handle putAsyncRelativeRetryNoStatusPayload ", async () => { const response = await runMockedLro("PUT", "/error/putasync/retry/nostatuspayload"); assert.equal(response.statusCode, 200); }); it("should handle putAsyncRelativeRetryNoStatus ", async () => { const response = await runMockedLro("PUT", "/error/putasync/retry/nostatus"); assert.equal(response.statusCode, 200); }); it("should handle delete204Succeeded ", async () => { const response = await runMockedLro("DELETE", "/error/delete/204/nolocation"); assert.equal(response.statusCode, 204); }); it("should handle deleteAsyncRelativeRetryNoStatus ", async () => { const response = await runMockedLro("DELETE", "/error/deleteasync/retry/nostatus"); assert.equal(response.statusCode, 200); }); it("should handle post202NoLocation ", async () => { const response = await runMockedLro("POST", "/error/post/202/nolocation"); assert.equal(response.statusCode, 202); }); it("should handle postAsyncRelativeRetryNoPayload ", async () => { const response = await runMockedLro("POST", "/error/postasync/retry/nopayload"); assert.equal(response.statusCode, 200); }); it("should handle put200InvalidJson ", async () => { try { await runMockedLro("PUT", "/error/put/200/invalidjson"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.message, "Unexpected end of JSON input"); } }); it("should handle putAsyncRelativeRetryInvalidHeader ", async () => { try { await runMockedLro("PUT", "/error/putasync/retry/invalidheader"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 404); // assert.equal(error.statusCode, 404); // core-client would have validated the retry-after header } }); it("should handle putAsyncRelativeRetryInvalidJsonPolling ", async () => { try { await runMockedLro("PUT", "/error/putasync/retry/invalidjsonpolling"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.message, "Unexpected end of JSON input"); } }); it("should handle delete202RetryInvalidHeader ", async () => { try { await runMockedLro("DELETE", "/error/delete/202/retry/invalidheader"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 404); } }); it("should handle deleteAsyncRelativeRetryInvalidHeader ", async () => { try { await runMockedLro("DELETE", "/error/deleteasync/retry/invalidheader"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 404); } }); it("should handle DeleteAsyncRelativeRetryInvalidJsonPolling ", async () => { try { await runMockedLro("DELETE", "/error/deleteasync/retry/invalidjsonpolling"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.message, "Unexpected end of JSON input"); } }); it("should handle post202RetryInvalidHeader ", async () => { try { await runMockedLro("POST", "/error/post/202/retry/invalidheader"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 404); } }); it("should handle postAsyncRelativeRetryInvalidHeader ", async () => { try { await runMockedLro("POST", "/error/postasync/retry/invalidheader"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.statusCode, 404); } }); it("should handle postAsyncRelativeRetryInvalidJsonPolling ", async () => { try { await runMockedLro("POST", "/error/postasync/retry/invalidjsonpolling"); assert.fail("Scenario should throw"); } catch (error) { assert.equal(error.message, "Unexpected end of JSON input"); } }); }); describe("serialized state", () => { let state: any, serializedState: string; it("should handle serializing the state", async () => { const poller = mockedPoller("PUT", "/put/200/succeeded"); poller.onProgress((currentState) => { if (state === undefined && serializedState === undefined) { state = currentState; serializedState = JSON.stringify({ state: currentState }); assert.equal(serializedState, poller.toString()); } }); await poller.pollUntilDone(); assert.ok(state.initialRawResponse); }); }); describe("mutate state", () => { it("The state can be mutated in onProgress", async () => { const poller = mockedPoller("POST", "/error/postasync/retry/nopayload"); poller.onProgress((currentState) => { // Abruptly stop the LRO after the first poll request without getting a result currentState.isCompleted = true; }); const result = await poller.pollUntilDone(); // there is no result because the poller did not run to completion. assert.isUndefined(result); }); it("The state can be mutated in processState", async () => { const poller = mockedPoller( "POST", "/error/postasync/retry/nopayload", undefined, undefined, (state: any, lastResponse: RawResponse) => { assert.ok(lastResponse); assert.ok(lastResponse?.statusCode); // Abruptly stop the LRO after the first poll request without getting a result state.isCompleted = true; } ); const result = await poller.pollUntilDone(); // there is no result because the poller did not run to completion. assert.isUndefined(result); }); }); describe("process result", () => { it("The final result can be processed using processResult", async () => { const poller = await mockedPoller( "POST", "/postasync/noretry/succeeded", undefined, (result: unknown, state: any) => { const serializedState = JSON.stringify({ state: state }); assert.equal(serializedState, poller.toString()); assert.ok(state.initialRawResponse); assert.ok(state.pollingURL); assert.equal((result as any).id, "100"); return { ...(result as any), id: "200" }; } ); const result = await poller.pollUntilDone(); assert.deepInclude(result, { id: "200", name: "foo" }); }); }); });
the_stack
import { extend } from './util'; import { Property, Complex, NotifyPropertyChanges, INotifyPropertyChanged, Event } from './notify-property-change'; import { Browser } from './browser'; import { Base, EmitType } from './base'; import { ChildProperty } from './child-property'; import { EventHandler, BaseEventArgs } from './event-handler'; import { TouchModel, SwipeSettingsModel } from './touch-model'; /** * SwipeSettings is a framework module that provides support to handle swipe event like swipe up, swipe right, etc.., */ export class SwipeSettings extends ChildProperty<SwipeSettings> { /** * Property specifies minimum distance of swipe moved. */ @Property(50) public swipeThresholdDistance: number; } const swipeRegex: RegExp = /(Up|Down)/; /** * Touch class provides support to handle the touch event like tap, double tap, tap hold, etc.., * ```typescript * let node: HTMLElement; * let touchObj: Touch = new Touch({ * element: node, * tap: function (e) { * // tap handler function code * } * tapHold: function (e) { * // tap hold handler function code * } * scroll: function (e) { * // scroll handler function code * } * swipe: function (e) { * // swipe handler function code * } * }); * ``` */ @NotifyPropertyChanges export class Touch extends Base<HTMLElement> implements INotifyPropertyChanged { //Internal Variables private isTouchMoved: boolean; private startPoint: Points; private movedPoint: Points; private endPoint: Points; private startEventData: MouseEventArgs | TouchEventArgs; private lastTapTime: number; private lastMovedPoint: Points; private scrollDirection: string; private hScrollLocked: boolean; private vScrollLocked: boolean; private defaultArgs: TapEventArgs; private distanceX: number; private distanceY: number; private movedDirection: string; private tStampStart: number; private touchAction: boolean = true; // eslint-disable-next-line private timeOutTap: any; // eslint-disable-next-line private modeClear: any; // eslint-disable-next-line private timeOutTapHold: any; /* Properties */ /** * Specifies the callback function for tap event. * * @event tap */ @Event() public tap: EmitType<TapEventArgs>; /** * Specifies the callback function for tapHold event. * * @event tapHold */ @Event() public tapHold: EmitType<TapEventArgs>; /** * Specifies the callback function for swipe event. * * @event swipe */ @Event() public swipe: EmitType<SwipeEventArgs>; /** * Specifies the callback function for scroll event. * * @event scroll */ @Event() public scroll: EmitType<ScrollEventArgs>; /** * Specifies the time delay for tap. * * @default 350 */ @Property(350) public tapThreshold: number; /** * Specifies the time delay for tap hold. * * @default 750 */ @Property(750) public tapHoldThreshold: number; /** * Customize the swipe event configuration. * * @default { swipeThresholdDistance: 50 } */ @Complex<SwipeSettingsModel>({}, SwipeSettings) public swipeSettings: SwipeSettingsModel; private tapCount: number = 0; /* End-Properties */ constructor(element: HTMLElement, options?: TouchModel) { super(options, element); this.bind(); } // triggers when property changed /** * * @private * @param {TouchModel} newProp ? * @param {TouchModel} oldProp ? * @returns {void} ? */ // eslint-disable-next-line public onPropertyChanged(newProp: TouchModel, oldProp: TouchModel): void { //No Code to handle } protected bind(): void { this.wireEvents(); if (Browser.isIE) { this.element.classList.add('e-block-touch'); } } /** * To destroy the touch instance. * * @returns {void} */ public destroy(): void { this.unwireEvents(); super.destroy(); } // Need to changes the event binding once we updated the event handler. private wireEvents(): void { EventHandler.add(this.element, Browser.touchStartEvent, this.startEvent, this); } private unwireEvents(): void { EventHandler.remove(this.element, Browser.touchStartEvent, this.startEvent); } /** * Returns module name as touch * * @returns {string} ? * @private */ public getModuleName(): string { return 'touch'; } /** * Returns if the HTML element is Scrollable. * * @param {HTMLElement} element - HTML Element to check if Scrollable. * @returns {boolean} ? */ private isScrollable(element: HTMLElement): boolean { const eleStyle: CSSStyleDeclaration = getComputedStyle(element); const style: string = eleStyle.overflow + eleStyle.overflowX + eleStyle.overflowY; if ((/(auto|scroll)/).test(style)) { return true; } return false; } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private startEvent: Function = (evt: MouseEventArgs | TouchEventArgs): void => { if (this.touchAction === true) { const point: MouseEventArgs | TouchEventArgs = this.updateChangeTouches(evt); if (evt.changedTouches !== undefined) { this.touchAction = false; } this.isTouchMoved = false; this.movedDirection = ''; this.startPoint = this.lastMovedPoint = { clientX: point.clientX, clientY: point.clientY }; this.startEventData = point; this.hScrollLocked = this.vScrollLocked = false; this.tStampStart = Date.now(); this.timeOutTapHold = setTimeout(() => { this.tapHoldEvent(evt); }, this.tapHoldThreshold); EventHandler.add(this.element, Browser.touchMoveEvent, this.moveEvent, this); EventHandler.add(this.element, Browser.touchEndEvent, this.endEvent, this); EventHandler.add(this.element, Browser.touchCancelEvent, this.cancelEvent, this); } } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private moveEvent: Function = (evt: MouseEventArgs | TouchEventArgs): void => { const point: MouseEventArgs | TouchEventArgs = this.updateChangeTouches(evt); this.movedPoint = point; this.isTouchMoved = !(point.clientX === this.startPoint.clientX && point.clientY === this.startPoint.clientY); let eScrollArgs: Object = {}; if (this.isTouchMoved) { clearTimeout(this.timeOutTapHold); this.calcScrollPoints(evt); const scrollArg: ScrollEventArgs = { startEvents: this.startEventData, originalEvent: evt, startX: this.startPoint.clientX, startY: this.startPoint.clientY, distanceX: this.distanceX, distanceY: this.distanceY, scrollDirection: this.scrollDirection, velocity: this.getVelocity(point) }; eScrollArgs = extend(eScrollArgs, {}, scrollArg); this.trigger('scroll', eScrollArgs); this.lastMovedPoint = { clientX: point.clientX, clientY: point.clientY }; } } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private cancelEvent: Function = (evt: MouseEventArgs | TouchEventArgs): void => { clearTimeout(this.timeOutTapHold); clearTimeout(this.timeOutTap); this.tapCount = 0; this.swipeFn(evt); EventHandler.remove(this.element, Browser.touchCancelEvent, this.cancelEvent); } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private tapHoldEvent(evt: MouseEvent | TouchEventArgs): void { this.tapCount = 0; this.touchAction = true; let eTapArgs: TapEventArgs; EventHandler.remove(this.element, Browser.touchMoveEvent, this.moveEvent); EventHandler.remove(this.element, Browser.touchEndEvent, this.endEvent); // eslint-disable-next-line eTapArgs = { originalEvent: <TouchEventArgs>evt }; this.trigger('tapHold', eTapArgs); EventHandler.remove(this.element, Browser.touchCancelEvent, this.cancelEvent); } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private endEvent: Function = (evt: MouseEventArgs | TouchEventArgs): void => { this.swipeFn(evt); if (!this.isTouchMoved) { if (typeof this.tap === 'function') { this.trigger('tap', { originalEvent: evt, tapCount: ++this.tapCount }); this.timeOutTap = setTimeout( () => { this.tapCount = 0; }, this.tapThreshold); } } this.modeclear(); } /** * * @param {MouseEventArgs | TouchEventArgs} evt ? * @returns {void} ? */ private swipeFn: Function = (evt: MouseEventArgs | TouchEventArgs): void => { clearTimeout(this.timeOutTapHold); clearTimeout(this.timeOutTap); const point: MouseEventArgs | TouchEventArgs = this.updateChangeTouches(evt); let diffX: number = point.clientX - this.startPoint.clientX; let diffY: number = point.clientY - this.startPoint.clientY; diffX = Math.floor(diffX < 0 ? -1 * diffX : diffX); diffY = Math.floor(diffY < 0 ? -1 * diffY : diffX); this.isTouchMoved = diffX > 1 || diffY > 1; this.endPoint = point; this.calcPoints(evt); const swipeArgs: SwipeEventArgs = { originalEvent: evt, startEvents: this.startEventData, startX: this.startPoint.clientX, startY: this.startPoint.clientY, distanceX: this.distanceX, distanceY: this.distanceY, swipeDirection: this.movedDirection, velocity: this.getVelocity(point) }; if (this.isTouchMoved) { let eSwipeArgs: Object; const tDistance: number = this.swipeSettings.swipeThresholdDistance; // eslint-disable-next-line eSwipeArgs = extend(eSwipeArgs, this.defaultArgs, swipeArgs); let canTrigger: boolean = false; const ele: HTMLElement = this.element; const scrollBool: boolean = this.isScrollable(ele); const moved: boolean = swipeRegex.test(this.movedDirection); if ((tDistance < this.distanceX && !moved) || (tDistance < this.distanceY && moved)) { if (!scrollBool) { canTrigger = true; } else { canTrigger = this.checkSwipe(ele, moved); } } if (canTrigger) { this.trigger('swipe', eSwipeArgs); } } this.modeclear(); } private modeclear: Function = (): void => { this.modeClear = setTimeout( () => { this.touchAction = true; }, (typeof this.tap !== 'function' ? 0 : 20)); this.lastTapTime = new Date().getTime(); EventHandler.remove(this.element, Browser.touchMoveEvent, this.moveEvent); EventHandler.remove(this.element, Browser.touchEndEvent, this.endEvent); EventHandler.remove(this.element, Browser.touchCancelEvent, this.cancelEvent); } private calcPoints(evt: MouseEventArgs | TouchEventArgs): void { const point: MouseEventArgs | TouchEventArgs = this.updateChangeTouches(evt); this.defaultArgs = { originalEvent: evt }; this.distanceX = Math.abs((Math.abs(point.clientX) - Math.abs(this.startPoint.clientX))); this.distanceY = Math.abs((Math.abs(point.clientY) - Math.abs(this.startPoint.clientY))); if (this.distanceX > this.distanceY) { this.movedDirection = (point.clientX > this.startPoint.clientX) ? 'Right' : 'Left'; } else { this.movedDirection = (point.clientY < this.startPoint.clientY) ? 'Up' : 'Down'; } } private calcScrollPoints(evt: MouseEventArgs | TouchEventArgs): void { const point: MouseEventArgs | TouchEventArgs = this.updateChangeTouches(evt); this.defaultArgs = { originalEvent: evt }; this.distanceX = Math.abs((Math.abs(point.clientX) - Math.abs(this.lastMovedPoint.clientX))); this.distanceY = Math.abs((Math.abs(point.clientY) - Math.abs(this.lastMovedPoint.clientY))); if ((this.distanceX > this.distanceY || this.hScrollLocked === true) && this.vScrollLocked === false) { this.scrollDirection = (point.clientX > this.lastMovedPoint.clientX) ? 'Right' : 'Left'; this.hScrollLocked = true; } else { this.scrollDirection = (point.clientY < this.lastMovedPoint.clientY) ? 'Up' : 'Down'; this.vScrollLocked = true; } } private getVelocity(pnt: MouseEventArgs | TouchEventArgs): number { const newX: number = pnt.clientX; const newY: number = pnt.clientY; const newT: number = Date.now(); const xDist: number = newX - this.startPoint.clientX; const yDist: number = newY - this.startPoint.clientX; const interval: number = newT - this.tStampStart; return Math.sqrt(xDist * xDist + yDist * yDist) / interval; } // eslint-disable-next-line private checkSwipe(ele: any, flag: boolean): boolean { const keys: string[] = ['scroll', 'offset']; const temp: string[] = flag ? ['Height', 'Top'] : ['Width', 'Left']; if ((ele[keys[0] + temp[0]] <= ele[keys[1] + temp[0]])) { return true; } return (ele[keys[0] + temp[1]] === 0) || (ele[keys[1] + temp[0]] + ele[keys[0] + temp[1]] >= ele[keys[0] + temp[0]]); } private updateChangeTouches(evt: MouseEventArgs | TouchEventArgs): MouseEventArgs | TouchEventArgs { const point: MouseEventArgs | TouchEventArgs = evt.changedTouches && evt.changedTouches.length !== 0 ? evt.changedTouches[0] : evt; return point; } } interface Points { clientX: number; clientY: number; } /** * The argument type of `Tap` Event */ export interface TapEventArgs extends BaseEventArgs { /** * Original native event Object. */ originalEvent: TouchEventArgs | MouseEventArgs; /** * Tap Count. */ tapCount?: number; } /** * The argument type of `Scroll` Event */ export interface ScrollEventArgs extends BaseEventArgs { /** * Event argument for start event. */ startEvents: TouchEventArgs | MouseEventArgs; /** * Original native event object for scroll. */ originalEvent: TouchEventArgs | MouseEventArgs; /** * X position when scroll started. */ startX: number; /** * Y position when scroll started. */ startY: number; /** * The direction scroll. */ scrollDirection: string; /** * The total traveled distance from X position */ distanceX: number; /** * The total traveled distance from Y position */ distanceY: number; /** * The velocity of scroll. */ velocity: number; } /** * The argument type of `Swipe` Event */ export interface SwipeEventArgs extends BaseEventArgs { /** * Event argument for start event. */ startEvents: TouchEventArgs | MouseEventArgs; /** * Original native event object for swipe. */ originalEvent: TouchEventArgs | MouseEventArgs; /** * X position when swipe started. */ startX: number; /** * Y position when swipe started. */ startY: number; /** * The direction swipe. */ swipeDirection: string; /** * The total traveled distance from X position */ distanceX: number; /** * The total traveled distance from Y position */ distanceY: number; /** * The velocity of swipe. */ velocity: number; } export interface TouchEventArgs extends MouseEvent { /** * A TouchList with touched points. */ changedTouches: MouseEventArgs[] | TouchEventArgs[]; /** * Cancel the default action. */ preventDefault(): void; /** * The horizontal coordinate point of client area. */ clientX: number; /** * The vertical coordinate point of client area. */ clientY: number; } export interface MouseEventArgs extends MouseEvent { /** * A TouchList with touched points. */ changedTouches: MouseEventArgs[] | TouchEventArgs[]; /** * Cancel the default action. */ preventDefault(): void; /** * The horizontal coordinate point of client area. */ clientX: number; /** * The vertical coordinate point of client area. */ clientY: number; }
the_stack
import BigNumber from 'bignumber.js'; import { Order } from '@dydxprotocol/exchange-wrappers'; import { TransactionReceipt, Log, EventLog } from 'web3/types'; export type address = string; export type Integer = BigNumber; export type Decimal = BigNumber; export type BigNumberable = BigNumber | string | number; export enum ConfirmationType { Hash = 0, Confirmed = 1, Both = 2, Simulate = 3, } export const MarketId = { WETH: new BigNumber(0), SAI: new BigNumber(1), USDC: new BigNumber(2), DAI: new BigNumber(3), // This market number does not exist on the protocol, // but can be used for standard actions ETH: new BigNumber(-1), }; export const Networks = { MAINNET: 1, KOVAN: 42, }; export enum ProxyType { None = 'None', Payable = 'Payable', Sender = 'Sender', // Deprecated Signed = 'Sender', } export enum SigningMethod { Compatibility = 'Compatibility', // picks intelligently between UnsafeHash and Hash UnsafeHash = 'UnsafeHash', // raw hash signed Hash = 'Hash', // hash prepended according to EIP-191 TypedData = 'TypedData', // order hashed according to EIP-712 MetaMask = 'MetaMask', // order hashed according to EIP-712 (MetaMask-only) MetaMaskLatest = 'MetaMaskLatest', // ... according to latest version of EIP-712 (MetaMask-only) CoinbaseWallet = 'CoinbaseWallet', // ... according to latest version of EIP-712 (CoinbaseWallet) } export interface SoloOptions { defaultAccount?: address; confirmationType?: ConfirmationType; defaultConfirmations?: number; autoGasMultiplier?: number; defaultGas?: number | string; defaultGasPrice?: number | string; blockGasLimit?: number; accounts?: EthereumAccount[]; apiEndpoint?: string; apiTimeout?: number; ethereumNodeTimeout?: number; wsOrigin?: string; wsEndpoint?: string; wsTimeout?: number; } export interface EthereumAccount { address?: string; privateKey: string; } export interface TxOptions { from?: address; value?: number | string; } export interface NativeSendOptions extends TxOptions { gasPrice?: number | string; gas?: number | string; nonce?: string | number; } export interface SendOptions extends NativeSendOptions { confirmations?: number; confirmationType?: ConfirmationType; autoGasMultiplier?: number; } export interface CallOptions extends TxOptions { blockNumber?: number; } export interface AccountOperationOptions { usePayableProxy?: boolean; // deprecated proxy?: ProxyType; sendEthTo?: address; } export interface LogParsingOptions { skipOperationLogs?: boolean; skipAdminLogs?: boolean; skipPermissionLogs?: boolean; skipExpiryLogs?: boolean; skipFinalSettlementLogs?: boolean; skipRefunderLogs?: boolean; skipLimitOrdersLogs?: boolean; skipSignedOperationProxyLogs?: boolean; } export interface TxResult { transactionHash?: string; transactionIndex?: number; blockHash?: string; blockNumber?: number; from?: string; to?: string; contractAddress?: string; cumulativeGasUsed?: number; gasUsed?: number; logs?: Log[]; events?: { [eventName: string]: EventLog; }; nonce?: number; // non-standard field, returned only through dYdX Sender service status?: boolean; confirmation?: Promise<TransactionReceipt>; gasEstimate?: number; gas?: number; } export enum AmountDenomination { Actual = 0, Principal = 1, Wei = 0, Par = 1, } export enum AmountReference { Delta = 0, Target = 1, } export enum ActionType { Deposit = 0, Withdraw = 1, Transfer = 2, Buy = 3, Sell = 4, Trade = 5, Liquidate = 6, Vaporize = 7, Call = 8, } export enum AccountStatus { Normal = 0, Liquidating = 1, Vaporizing = 2, } export interface Amount { value: Integer; denomination: AmountDenomination; reference: AmountReference; } export interface AccountAction { primaryAccountOwner: address; primaryAccountId: Integer; } interface ExternalTransfer extends AccountAction { marketId: Integer; amount: Amount; } export interface Deposit extends ExternalTransfer { from: address; } export interface Withdraw extends ExternalTransfer { to: address; } export interface Transfer extends AccountAction { marketId: Integer; toAccountOwner: address; toAccountId: Integer; amount: Amount; } export interface Exchange extends AccountAction { takerMarketId: Integer; makerMarketId: Integer; order: Order; amount: Amount; } export interface Buy extends Exchange {} export interface Sell extends Exchange {} export interface Trade extends AccountAction { autoTrader: address; inputMarketId: Integer; outputMarketId: Integer; otherAccountOwner: address; otherAccountId: Integer; amount: Amount; data: (string | number[])[]; } export interface Liquidate extends AccountAction { liquidMarketId: Integer; payoutMarketId: Integer; liquidAccountOwner: address; liquidAccountId: Integer; amount: Amount; } export interface Vaporize extends AccountAction { vaporMarketId: Integer; payoutMarketId: Integer; vaporAccountOwner: address; vaporAccountId: Integer; amount: Amount; } export interface SetExpiry extends AccountAction { marketId: Integer; expiryTime: Integer; } export interface ExpiryV2Arg { accountOwner: address; accountId: Integer; marketId: Integer; timeDelta: Integer; forceUpdate: boolean; } export interface SetExpiryV2 extends AccountAction { expiryV2Args: ExpiryV2Arg[]; } export interface Refund extends AccountAction { receiverAccountOwner: address; receiverAccountId: Integer; refundMarketId: Integer; otherMarketId: Integer; wei: Integer; } export interface DaiMigrate extends AccountAction { userAccountOwner: address; userAccountId: Integer; amount: Amount; } export interface AccountActionWithOrder extends AccountAction { order: LimitOrder | StopLimitOrder | CanonicalOrder; } export interface Call extends AccountAction { callee: address; data: (string | number[])[]; } export interface AccountInfo { owner: string; number: number | string; } export interface ActionArgs { actionType: number | string; accountId: number | string; amount: { sign: boolean; denomination: number | string; ref: number | string; value: number | string; }; primaryMarketId: number | string; secondaryMarketId: number | string; otherAddress: string; otherAccountId: number | string; data: (string | number[])[]; } export interface Index { borrow: Decimal; supply: Decimal; lastUpdate: Integer; } export interface TotalPar { borrow: Integer; supply: Integer; } export interface Market { token: address; totalPar: TotalPar; index: Index; priceOracle: address; interestSetter: address; marginPremium: Decimal; spreadPremium: Decimal; isClosing: boolean; } export interface MarketWithInfo { market: Market; currentIndex: Index; currentPrice: Integer; currentInterestRate: Decimal; } export interface RiskLimits { marginRatioMax: Decimal; liquidationSpreadMax: Decimal; earningsRateMax: Decimal; marginPremiumMax: Decimal; spreadPremiumMax: Decimal; minBorrowedValueMax: Integer; } export interface RiskParams { marginRatio: Decimal; liquidationSpread: Decimal; earningsRate: Decimal; minBorrowedValue: Integer; } export interface Balance { tokenAddress: address; par: Integer; wei: Integer; } export interface Values { supply: Integer; borrow: Integer; } export interface BalanceUpdate { deltaWei: Integer; newPar: Integer; } // ============ Expiry ============ export interface SetExpiry extends AccountAction { marketId: Integer; expiryTime: Integer; } export interface ExpiryV2Arg { accountOwner: address; accountId: Integer; marketId: Integer; timeDelta: Integer; } export interface SetExpiryV2 extends AccountAction { expiryV2Args: ExpiryV2Arg[]; } export interface SetApprovalForExpiryV2 extends AccountAction { sender: address; minTimeDelta: Integer; } export enum ExpiryV2CallFunctionType { SetExpiry = 0, SetApproval = 1, } // ============ Limit Orders ============ export interface SignableOrder { makerAccountOwner: address; makerAccountNumber: Integer; } export interface SignedOrder extends SignableOrder { typedSignature: string; } export interface LimitOrder extends SignableOrder { makerMarket: Integer; takerMarket: Integer; makerAmount: Integer; takerAmount: Integer; takerAccountOwner: address; takerAccountNumber: Integer; expiration: Integer; salt: Integer; } export interface SignedLimitOrder extends LimitOrder, SignedOrder { } export interface StopLimitOrder extends LimitOrder { triggerPrice: Integer; decreaseOnly: boolean; } export interface SignedStopLimitOrder extends StopLimitOrder, SignedOrder { } export interface CanonicalOrder extends SignableOrder { isBuy: boolean; isDecreaseOnly: boolean; baseMarket: Integer; quoteMarket: Integer; amount: Integer; limitPrice: Decimal; triggerPrice: Decimal; limitFee: Decimal; expiration: Integer; salt: Integer; } export interface SignedCanonicalOrder extends CanonicalOrder, SignedOrder { } export enum LimitOrderStatus { Null = 0, Approved = 1, Canceled = 2, } export interface LimitOrderState { status: LimitOrderStatus; totalMakerFilledAmount: Integer; } export interface CanonicalOrderState { status: LimitOrderStatus; totalFilledAmount: Integer; } export enum LimitOrderCallFunctionType { Approve = 0, Cancel = 1, SetFillArgs = 2, } // ============ Sender Proxy ============ export interface OperationAuthorization { startIndex: Integer; numActions: Integer; expiration: Integer; salt: Integer; sender: address; signer: address; typedSignature: string; } export interface AssetAmount { sign: boolean; denomination: AmountDenomination; ref: AmountReference; value: Integer; } export interface Action { actionType: ActionType; primaryAccountOwner: address; primaryAccountNumber: Integer; secondaryAccountOwner: address; secondaryAccountNumber: Integer; primaryMarketId: Integer; secondaryMarketId: Integer; amount: AssetAmount; otherAddress: address; data: string; } export interface Operation { actions: Action[]; expiration: Integer; salt: Integer; sender: address; signer: address; } export interface SignedOperation extends Operation { typedSignature: string; } // ============ Api ============ export enum ApiOrderTypeV2 { LIMIT = 'LIMIT', ISOLATED_MARKET = 'ISOLATED_MARKET', STOP_LIMIT = 'STOP_LIMIT', CANONICAL_CROSS = 'CANONICAL_CROSS', CANONICAL_SPOT = 'CANONICAL_SPOT', CANONICAL_SPOT_STOP_LIMIT = 'CANONICAL_SPOT_STOP_LIMIT', CANONICAL_STOP_LIMIT = 'CANONICAL_STOP_LIMIT', CANONICAL_ISOLATED_STOP_LIMIT = 'CANONICAL_ISOLATED_STOP_LIMIT', CANONICAL_ISOLATED_OPEN = 'CANONICAL_ISOLATED_OPEN', CANONICAL_ISOLATED_PARTIAL_CLOSE = 'CANONICAL_ISOLATED_PARTIAL_CLOSE', CANONICAL_ISOLATED_FULL_CLOSE = 'CANONICAL_ISOLATED_FULL_CLOSE', CANONICAL_ISOLATED_TAKE_PROFIT = 'CANONICAL_ISOLATED_TAKE_PROFIT', PERPETUAL_CROSS = 'PERPETUAL_CROSS', PERPETUAL_STOP_LIMIT = 'PERPETUAL_STOP_LIMIT', } export enum ApiOrderType { LIMIT_V1 = 'dydexLimitV1', } export enum ApiOrderStatus { PENDING = 'PENDING', OPEN = 'OPEN', FILLED = 'FILLED', PARTIALLY_FILLED = 'PARTIALLY_FILLED', CANCELED = 'CANCELED', UNTRIGGERED = 'UNTRIGGERED', } export enum ApiFillStatus { PENDING = 'PENDING', REVERTED = 'REVERTED', CONFIRMED = 'CONFIRMED', } export enum ApiMarketName { WETH_DAI = 'WETH-DAI', WETH_USDC = 'WETH-USDC', DAI_USDC = 'DAI-USDC', } export enum ApiOrderCancelReason { EXPIRED = 'EXPIRED', UNDERCOLLATERALIZED = 'UNDERCOLLATERALIZED', CANCELED_ON_CHAIN = 'CANCELED_ON_CHAIN', USER_CANCELED = 'USER_CANCELED', SELF_TRADE = 'SELF_TRADE', FAILED = 'FAILED', COULD_NOT_FILL = 'COULD_NOT_FILL', POST_ONLY_WOULD_CROSS = 'POST_ONLY_WOULD_CROSS', } export interface ApiOrderQueryV2 { accountOwner?: string; accountNumber?: Integer | string; status?: ApiOrderStatus[]; market?: ApiMarketName[]; side?: ApiSide; orderType?: ApiOrderTypeV2[]; limit?: number; startingBefore?: Date; } export interface ApiOrderV2 extends ApiModel { uuid: string; id: string; status: ApiOrderStatus; accountOwner: string; accountNumber: string; orderType: ApiOrderTypeV2; fillOrKill: boolean; market: ApiMarketName; side: ApiSide; baseAmount: string; quoteAmount: string; filledAmount: string; price: string; cancelReason: ApiOrderCancelReason; } export interface ApiOrder extends ApiModel { id: string; uuid: string; rawData: string; orderType: ApiOrderType; pairUuid: string; makerAccountOwner: string; makerAccountNumber: string; makerAmount: string; takerAmount: string; makerAmountRemaining: string; takerAmountRemaining: string; price: string; fillOrKill: boolean; postOnly: boolean; status: ApiOrderStatus; expiresAt?: string; unfillableReason?: string; unfillableAt?: string; pair: ApiPair; } export interface ApiPair extends ApiModel { name: string; makerCurrencyUuid: string; takerCurrencyUuid: string; makerCurrency: ApiCurrency; takerCurrency: ApiCurrency; } export interface ApiCurrency extends ApiModel { symbol: string; contractAddress: string; decimals: number; soloMarket: number; } export interface ApiAccount extends ApiModel { owner: string; number: string; balances: { [marketNumber: string]: { par: string; wei: string; expiresAt?: string; expiryAddress?: string; }; }; } export interface ApiOrderOnOrderbook { id: string; uuid: string; amount: string; price: string; } export interface ApiFillQueryV2 { orderId?: string; side?: ApiSide; market?: Market[]; transactionHash?: string; accountOwner?: string; accountNumber?: Integer | string; startingBefore?: Date; limit?: number; } export enum ApiLiquidity { TAKER = 'TAKER', MAKER = 'MAKER', } export interface ApiFillV2 extends ApiModel { transactionHash: string; status: ApiFillStatus; market: ApiMarketName; side: ApiSide; price: string; amount: string; orderId: string; accountOwner: string; accountNumber: string; liquidity: ApiLiquidity; } export interface ApiTradeQueryV2 { orderId?: string; side?: ApiSide; market?: ApiMarketName[]; transactionHash?: string; accountOwner?: string; accountNumber?: Integer | string; startingBefore?: Date; limit?: number; } export interface ApiTradeV2 extends ApiModel { transactionHash: string; status: ApiFillStatus; market: ApiMarketName; side: ApiSide; price: string; amount: string; makerOrderId: string; makerAccountOwner: string; makerAccountNumber: string; takerOrderId: string; takerAccountOwner: string; takerAccountNumber: string; } export interface ApiMarket { id: number; createdAt: string; updatedAt: string; deletedAt?: string; name: string; symbol: string; supplyIndex: string; borrowIndex: string; totalSupplyPar: string; totalBorrowPar: string; lastIndexUpdateSeconds: string; oraclePrice: string; collateralRatio: string; marginPremium: string; spreadPremium: string; currencyUuid: string; currency: ApiCurrency; totalSupplyAPR: string; totalBorrowAPR: string; totalSupplyAPY: string; totalBorrowAPY: string; totalSupplyWei: string; totalBorrowWei: string; } interface ApiModel { uuid: string; createdAt: string; updatedAt: string; deletedAt?: string; } export enum OrderType { DYDX = 'dydexLimitV1', ETH_2_DAI = 'OasisV3', ZERO_EX = '0x-V2', } export enum ApiOrderUpdateType { NEW = 'NEW', REMOVED = 'REMOVED', UPDATED = 'UPDATED', } export enum ApiSide { BUY = 'BUY', SELL = 'SELL', } export interface ApiOrderbookUpdate { type: ApiOrderUpdateType; id: string; side: ApiSide; amount?: string; price?: string; } export interface ApiMarketMessageV2 { name: Market; baseCurrency: { currency: ApiCurrency; decimals: number; soloMarketId: number; }; quoteCurrency: { currency: ApiCurrency; decimals: number; soloMarketId: number; }; minimumTickSize: BigNumber; minimumOrderSize: BigNumber; smallOrderThreshold: BigNumber; makerFee: BigNumber; largeTakerFee: BigNumber; smallTakerFee: BigNumber; } export enum RequestMethod { GET = 'get', POST = 'post', DELETE = 'delete', } export const AccountNumbers: { [accountNumber: string]: BigNumber } = { SPOT: new BigNumber('78249916358380492593314239409032173911741268194868200833150293576330928686520'), MARGIN: new BigNumber('0'), }; export enum OffChainAction { LOGIN = 'Login', CANCEL_ALL = 'CancelAll', }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type FairsPastFairsQueryVariables = { first: number; after?: string | null; }; export type FairsPastFairsQueryResponse = { readonly viewer: { readonly " $fragmentRefs": FragmentRefs<"FairsPastFairs_viewer">; } | null; }; export type FairsPastFairsQuery = { readonly response: FairsPastFairsQueryResponse; readonly variables: FairsPastFairsQueryVariables; }; /* query FairsPastFairsQuery( $first: Int! $after: String ) { viewer { ...FairsPastFairs_viewer_2HEEH6 } } fragment FairsFairRow_fair on Fair { href name isoStartAt: startAt exhibitionPeriod profile { icon { resized(width: 80, height: 80, version: "square140") { width height src srcSet } } id } organizer { profile { href id } id } } fragment FairsPastFairs_viewer_2HEEH6 on Viewer { pastFairs: fairsConnection(hasListing: true, hasFullFeature: true, sort: START_AT_DESC, status: CLOSED, first: $first, after: $after) { edges { node { internalID isPublished profile { isPublished id } ...FairsFairRow_fair id __typename } cursor } pageInfo { endCursor hasNextPage } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "first", "type": "Int!" }, { "defaultValue": null, "kind": "LocalArgument", "name": "after", "type": "String" } ], v1 = { "kind": "Variable", "name": "after", "variableName": "after" }, v2 = { "kind": "Variable", "name": "first", "variableName": "first" }, v3 = [ (v1/*: any*/), (v2/*: any*/), { "kind": "Literal", "name": "hasFullFeature", "value": true }, { "kind": "Literal", "name": "hasListing", "value": true }, { "kind": "Literal", "name": "sort", "value": "START_AT_DESC" }, { "kind": "Literal", "name": "status", "value": "CLOSED" } ], v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "isPublished", "storageKey": null }, v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "FairsPastFairsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Viewer", "kind": "LinkedField", "name": "viewer", "plural": false, "selections": [ { "args": [ (v1/*: any*/), (v2/*: any*/) ], "kind": "FragmentSpread", "name": "FairsPastFairs_viewer" } ], "storageKey": null } ], "type": "Query" }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "FairsPastFairsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Viewer", "kind": "LinkedField", "name": "viewer", "plural": false, "selections": [ { "alias": "pastFairs", "args": (v3/*: any*/), "concreteType": "FairConnection", "kind": "LinkedField", "name": "fairsConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "FairEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Fair", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, (v4/*: any*/), { "alias": null, "args": null, "concreteType": "Profile", "kind": "LinkedField", "name": "profile", "plural": false, "selections": [ (v4/*: any*/), (v5/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "icon", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "height", "value": 80 }, { "kind": "Literal", "name": "version", "value": "square140" }, { "kind": "Literal", "name": "width", "value": 80 } ], "concreteType": "ResizedImageUrl", "kind": "LinkedField", "name": "resized", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "src", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "srcSet", "storageKey": null } ], "storageKey": "resized(height:80,version:\"square140\",width:80)" } ], "storageKey": null } ], "storageKey": null }, (v6/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, { "alias": "isoStartAt", "args": null, "kind": "ScalarField", "name": "startAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "exhibitionPeriod", "storageKey": null }, { "alias": null, "args": null, "concreteType": "FairOrganizer", "kind": "LinkedField", "name": "organizer", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Profile", "kind": "LinkedField", "name": "profile", "plural": false, "selections": [ (v6/*: any*/), (v5/*: any*/) ], "storageKey": null }, (v5/*: any*/) ], "storageKey": null }, (v5/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null } ], "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 } ], "storageKey": null }, { "alias": "pastFairs", "args": (v3/*: any*/), "filters": [ "hasListing", "hasFullFeature", "sort", "status" ], "handle": "connection", "key": "FairsPastFairsQuery_pastFairs", "kind": "LinkedHandle", "name": "fairsConnection" } ], "storageKey": null } ] }, "params": { "id": null, "metadata": {}, "name": "FairsPastFairsQuery", "operationKind": "query", "text": "query FairsPastFairsQuery(\n $first: Int!\n $after: String\n) {\n viewer {\n ...FairsPastFairs_viewer_2HEEH6\n }\n}\n\nfragment FairsFairRow_fair on Fair {\n href\n name\n isoStartAt: startAt\n exhibitionPeriod\n profile {\n icon {\n resized(width: 80, height: 80, version: \"square140\") {\n width\n height\n src\n srcSet\n }\n }\n id\n }\n organizer {\n profile {\n href\n id\n }\n id\n }\n}\n\nfragment FairsPastFairs_viewer_2HEEH6 on Viewer {\n pastFairs: fairsConnection(hasListing: true, hasFullFeature: true, sort: START_AT_DESC, status: CLOSED, first: $first, after: $after) {\n edges {\n node {\n internalID\n isPublished\n profile {\n isPublished\n id\n }\n ...FairsFairRow_fair\n id\n __typename\n }\n cursor\n }\n pageInfo {\n endCursor\n hasNextPage\n }\n }\n}\n" } }; })(); (node as any).hash = '7f80f8f97ce6a0ea32f24a95205a4395'; export default node;
the_stack
import * as PTM from "./PTI"; // PTM = "Published Types and Methods", but this file can also include app-state and app-event handlers import Ambrosia = require("ambrosia-node"); import Utils = Ambrosia.Utils; import IC = Ambrosia.IC; import Messages = Ambrosia.Messages; import Meta = Ambrosia.Meta; import Streams = Ambrosia.Streams; // Code-gen: 'AppState' section skipped (using provided state variable 'PTM.State._appState' and class 'State.AppState' instead) /** Returns an OutgoingCheckpoint object used to serialize app state to a checkpoint. */ export function checkpointProducer(): Streams.OutgoingCheckpoint { function onCheckpointSent(error?: Error): void { Utils.log(`checkpointProducer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint saved"}`) } return (Streams.simpleCheckpointProducer(PTM.State._appState, onCheckpointSent)); } /** Returns an IncomingCheckpoint object used to receive a checkpoint of app state. */ export function checkpointConsumer(): Streams.IncomingCheckpoint { function onCheckpointReceived(appState?: Ambrosia.AmbrosiaAppState, error?: Error): void { if (!error) { if (!appState) // Should never happen { throw new Error(`An appState object was expected, not ${appState}`); } PTM.State._appState = appState as PTM.State.AppState; } Utils.log(`checkpointConsumer: ${error ? `Failed (reason: ${error.message})` : "Checkpoint loaded"}`); } return (Streams.simpleCheckpointConsumer<PTM.State.AppState>(PTM.State.AppState, onCheckpointReceived)); } /** This method responds to incoming Ambrosia messages (RPCs and AppEvents). */ export function messageDispatcher(message: Messages.DispatchedMessage): void { // WARNING! Rules for Message Handling: // // Rule 1: Messages must be handled - to completion - in the order received. For application (RPC) messages only, if there are messages that are known to // be commutative then this rule can be relaxed. // Reason: Using Ambrosia requires applications to have deterministic execution. Further, system messages (like TakeCheckpoint) from the IC rely on being // handled in the order they are sent to the app. This means being extremely careful about using non-synchronous code (like awaitable operations // or callbacks) inside message handlers: the safest path is to always only use synchronous code. // // Rule 2: Before a TakeCheckpoint message can be handled, all handlers for previously received messages must have completed (ie. finished executing). // If Rule #1 is followed, the app is automatically in compliance with Rule #2. // Reason: Unless your application has a way to capture (and rehydrate) runtime execution state (specifically the message handler stack) in the serialized // application state (checkpoint), recovery of the checkpoint will not be able to complete the in-flight message handlers. But if there are no // in-flight handlers at the time the checkpoint is taken (because they all completed), then the problem of how to complete them during recovery is moot. // // Rule 3: Avoid sending too many messages in a single message handler. // Reason: Because a message handler always has to run to completion (see Rule #1), if it runs for too long it can monopolize the system leading to performance issues. // Further, this becomes a very costly message to have to replay during recovery. So instead, when an message handler needs to send a large sequence (series) // of independent messages, it should be designed to be restartable so that the sequence can pick up where it left off (rather than starting over) when resuming // execution (ie. after loading a checkpoint that occurred during the long-running - but incomplete - sequence). Restartability is achieved by sending a // application-defined 'sequence continuation' message at the end of each batch, which describes the remaining work to be done. Because the handler for the // 'sequence continuation' message only ever sends the next batch plus the 'sequence continuation' message, it can run to completion quickly, which both keeps // the system responsive (by allowing interleaving I/O) while also complying with Rule #1. // In addition to this "continuation message" technique for sending a series, if any single message handler has to send a large number of messages it should be // sent in batches using either explicit batches (IC.queueFork + IC.flushQueue) or implicit batches (IC.callFork / IC.postFork) inside a setImmediate() callback. // This asynchrony is necessary to allow I/O with the IC to interleave, and is one of the few allowable exceptions to the "always only use asynchronous code" // dictate in Rule #1. Interleaving I/O allows the instance to service self-calls, and allows checkpoints to be taken between batches. dispatcher(message); } /** * Synchronous Ambrosia message dispatcher. * * **WARNING:** Avoid using any asynchronous features (async/await, promises, callbacks, timers, events, etc.). See "Rules for Message Handling" above. */ function dispatcher(message: Messages.DispatchedMessage): void { const loggingPrefix: string = "Dispatcher"; try { switch (message.type) { case Messages.DispatchedMessageType.RPC: let rpc: Messages.IncomingRPC = message as Messages.IncomingRPC; switch (rpc.methodID) { case IC.POST_METHOD_ID: try { let methodName: string = IC.getPostMethodName(rpc); let methodVersion: number = IC.getPostMethodVersion(rpc); // Use this to do version-specific method behavior switch (methodName) { case "incrementValue": { const value: number = IC.getPostMethodArg(rpc, "value"); IC.postResult<number>(rpc, PTM.ServerAPI.incrementValue(value)); } break; default: { let errorMsg: string = `Post method '${methodName}' is not implemented`; Utils.log(`(${errorMsg})`, loggingPrefix) IC.postError(rpc, new Error(errorMsg)); } break; } } catch (error: unknown) { const err: Error = Utils.makeError(error); Utils.log(err); IC.postError(rpc, err); } break; case 1: { const rawParams: Uint8Array = rpc.getRawParams(); PTM.ServerAPI.doWork(rawParams); } break; case 2: { const isFinalState: boolean = rpc.getJsonParam("isFinalState"); PTM.ServerAPI.reportState(isFinalState); } break; case 3: { const currentTime: number = rpc.getJsonParam("currentTime"); PTM.ServerAPI.checkHealth(currentTime); } break; case 4: { const numRPCBytes: number = rpc.getJsonParam("numRPCBytes"); const iterationWithinRound: number = rpc.getJsonParam("iterationWithinRound"); const startTimeOfRound: number = rpc.getJsonParam("startTimeOfRound"); PTM.ClientAPI.continueSendingMessages(numRPCBytes, iterationWithinRound, startTimeOfRound); } break; case 5: { const rawParams: Uint8Array = rpc.getRawParams(); PTM.ClientAPI.doWorkEcho(rawParams); } break; default: Utils.log(`Error: Method dispatch failed (reason: No method is associated with methodID ${rpc.methodID})`); break; } break; case Messages.DispatchedMessageType.AppEvent: let appEvent: Messages.AppEvent = message as Messages.AppEvent; switch (appEvent.eventType) { case Messages.AppEventType.ICStarting: // TODO: Add an exported [non-async] function 'onICStarting(): void' to ./PTI.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICStarted: // TODO: Add an exported [non-async] function 'onICStarted(): void' to ./PTI.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICConnected: // Note: Types and methods are published in this handler so that they're available regardless of the 'icHostingMode' // Code-gen: Published types will go here Meta.publishMethod(1, "doWork", ["rawParams: Uint8Array"]); Meta.publishMethod(2, "reportState", ["isFinalState: boolean"]); Meta.publishMethod(3, "checkHealth", ["currentTime: number"]); Meta.publishPostMethod("incrementValue", 1, ["value: number"], "number"); Meta.publishMethod(4, "continueSendingMessages", ["numRPCBytes: number", "iterationWithinRound: number", "startTimeOfRound: number"]); Meta.publishMethod(5, "doWorkEcho", ["rawParams: Uint8Array"]); PTM.EventHandlers.onICConnected(); break; case Messages.AppEventType.ICStopped: // TODO: Add an exported [non-async] function 'onICStopped(exitCode: number): void' to ./PTI.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.ICReadyForSelfCallRpc: // TODO: Add an exported [non-async] function 'onICReadyForSelfCallRpc(): void' to ./PTI.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.RecoveryComplete: PTM.EventHandlers.onRecoveryComplete(); break; case Messages.AppEventType.UpgradeState: { const upgradeMode: Messages.AppUpgradeMode = appEvent.args[0]; PTM.EventHandlers.onUpgradeState(upgradeMode); } break; case Messages.AppEventType.UpgradeCode: { const upgradeMode: Messages.AppUpgradeMode = appEvent.args[0]; PTM.EventHandlers.onUpgradeCode(upgradeMode); } break; case Messages.AppEventType.IncomingCheckpointStreamSize: // TODO: Add an exported [non-async] function 'onIncomingCheckpointStreamSize(): void' to ./PTI.ts, then (after the next code-gen) a call to it will be generated here break; case Messages.AppEventType.FirstStart: PTM.EventHandlers.onFirstStart(); break; case Messages.AppEventType.BecomingPrimary: PTM.EventHandlers.onBecomingPrimary(); break; case Messages.AppEventType.CheckpointLoaded: { const checkpointSizeInBytes: number = appEvent.args[0]; PTM.EventHandlers.onCheckpointLoaded(checkpointSizeInBytes); } break; case Messages.AppEventType.CheckpointSaved: PTM.EventHandlers.onCheckpointSaved(); break; case Messages.AppEventType.UpgradeComplete: PTM.EventHandlers.onUpgradeComplete(); break; } break; } } catch (error: unknown) { let messageName: string = (message.type === Messages.DispatchedMessageType.AppEvent) ? `AppEvent:${Messages.AppEventType[(message as Messages.AppEvent).eventType]}` : Messages.DispatchedMessageType[message.type]; Utils.log(`Error: Failed to process ${messageName} message`); Utils.log(Utils.makeError(error)); } }
the_stack
import AAC from './aac-helper'; import MP4 from './mp4-generator'; import type { HlsEventEmitter } from '../events'; import { Events } from '../events'; import { ErrorTypes, ErrorDetails } from '../errors'; import { logger } from '../utils/logger'; import { InitSegmentData, Remuxer, RemuxerResult, RemuxedMetadata, RemuxedTrack, RemuxedUserdata, } from '../types/remuxer'; import { PlaylistLevelType } from '../types/loader'; import { toMsFromMpegTsClock } from '../utils/timescale-conversion'; import type { AudioSample, AvcSample, DemuxedAudioTrack, DemuxedAvcTrack, DemuxedMetadataTrack, DemuxedUserdataTrack, } from '../types/demuxer'; import type { TrackSet } from '../types/track'; import type { SourceBufferName } from '../types/buffer'; import type { Fragment } from '../loader/fragment'; import type { HlsConfig } from '../config'; const MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds const AAC_SAMPLES_PER_FRAME = 1024; const MPEG_AUDIO_SAMPLE_PER_FRAME = 1152; let chromeVersion: number | null = null; let safariWebkitVersion: number | null = null; let requiresPositiveDts: boolean = false; export default class MP4Remuxer implements Remuxer { private observer: HlsEventEmitter; private config: HlsConfig; private typeSupported: any; private ISGenerated: boolean = false; private _initPTS!: number; private _initDTS!: number; private nextAvcDts: number | null = null; private nextAudioPts: number | null = null; private isAudioContiguous: boolean = false; private isVideoContiguous: boolean = false; constructor( observer: HlsEventEmitter, config: HlsConfig, typeSupported, vendor = '' ) { this.observer = observer; this.config = config; this.typeSupported = typeSupported; this.ISGenerated = false; if (chromeVersion === null) { const userAgent = navigator.userAgent || ''; const result = userAgent.match(/Chrome\/(\d+)/i); chromeVersion = result ? parseInt(result[1]) : 0; } if (safariWebkitVersion === null) { const result = navigator.userAgent.match(/Safari\/(\d+)/i); safariWebkitVersion = result ? parseInt(result[1]) : 0; } requiresPositiveDts = (!!chromeVersion && chromeVersion < 75) || (!!safariWebkitVersion && safariWebkitVersion < 600); } destroy() {} resetTimeStamp(defaultTimeStamp) { logger.log('[mp4-remuxer]: initPTS & initDTS reset'); this._initPTS = this._initDTS = defaultTimeStamp; } resetNextTimestamp() { logger.log('[mp4-remuxer]: reset next timestamp'); this.isVideoContiguous = false; this.isAudioContiguous = false; } resetInitSegment() { logger.log('[mp4-remuxer]: ISGenerated flag reset'); this.ISGenerated = false; } getVideoStartPts(videoSamples) { let rolloverDetected = false; const startPTS = videoSamples.reduce((minPTS, sample) => { const delta = sample.pts - minPTS; if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation rolloverDetected = true; return normalizePts(minPTS, sample.pts); } else if (delta > 0) { return minPTS; } else { return sample.pts; } }, videoSamples[0].pts); if (rolloverDetected) { logger.debug('PTS rollover detected'); } return startPTS; } remux( audioTrack: DemuxedAudioTrack, videoTrack: DemuxedAvcTrack, id3Track: DemuxedMetadataTrack, textTrack: DemuxedUserdataTrack, timeOffset: number, accurateTimeOffset: boolean, flush: boolean, playlistType: PlaylistLevelType ): RemuxerResult { let video: RemuxedTrack | undefined; let audio: RemuxedTrack | undefined; let initSegment: InitSegmentData | undefined; let text: RemuxedUserdata | undefined; let id3: RemuxedMetadata | undefined; let independent: boolean | undefined; let audioTimeOffset = timeOffset; let videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding. // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid" // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list. // However, if the initSegment has already been generated, or we've reached the end of a segment (flush), // then we can remux one track without waiting for the other. const hasAudio = audioTrack.pid > -1; const hasVideo = videoTrack.pid > -1; const length = videoTrack.samples.length; const enoughAudioSamples = audioTrack.samples.length > 0; const enoughVideoSamples = length > 1; const canRemuxAvc = ((!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples)) || this.ISGenerated || flush; if (canRemuxAvc) { if (!this.ISGenerated) { initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } const isVideoContiguous = this.isVideoContiguous; let firstKeyFrameIndex = -1; if (enoughVideoSamples) { firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples); if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) { independent = true; if (firstKeyFrameIndex > 0) { logger.warn( `[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe` ); const startPTS = this.getVideoStartPts(videoTrack.samples); videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex); videoTrack.dropped += firstKeyFrameIndex; videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000); } else if (firstKeyFrameIndex === -1) { logger.warn( `[mp4-remuxer]: No keyframe found out of ${length} video samples` ); independent = false; } } } if (this.ISGenerated) { if (enoughAudioSamples && enoughVideoSamples) { // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS) // if first audio DTS is not aligned with first video DTS then we need to take that into account // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small // drift between audio and video streams const startPTS = this.getVideoStartPts(videoTrack.samples); const tsDelta = normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS; const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale; audioTimeOffset += Math.max(0, audiovideoTimestampDelta); videoTimeOffset += Math.max(0, -audiovideoTimestampDelta); } // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio. if (enoughAudioSamples) { // if initSegment was generated without audio samples, regenerate it again if (!audioTrack.samplerate) { logger.warn( '[mp4-remuxer]: regenerate InitSegment as audio detected' ); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } audio = this.remuxAudio( audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, hasVideo || enoughVideoSamples || playlistType === PlaylistLevelType.AUDIO ? videoTimeOffset : undefined ); if (enoughVideoSamples) { const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again if (!videoTrack.inputTimeScale) { logger.warn( '[mp4-remuxer]: regenerate InitSegment as video detected' ); initSegment = this.generateIS(audioTrack, videoTrack, timeOffset); } video = this.remuxVideo( videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength ); } } else if (enoughVideoSamples) { video = this.remuxVideo( videoTrack, videoTimeOffset, isVideoContiguous, 0 ); } if (video) { video.firstKeyFrame = firstKeyFrameIndex; video.independent = firstKeyFrameIndex !== -1; } } } // Allow ID3 and text to remux, even if more audio/video samples are required if (this.ISGenerated) { if (id3Track.samples.length) { id3 = this.remuxID3(id3Track, timeOffset); } if (textTrack.samples.length) { text = this.remuxText(textTrack, timeOffset); } } return { audio, video, initSegment, independent, text, id3, }; } generateIS( audioTrack: DemuxedAudioTrack, videoTrack: DemuxedAvcTrack, timeOffset ): InitSegmentData | undefined { const audioSamples = audioTrack.samples; const videoSamples = videoTrack.samples; const typeSupported = this.typeSupported; const tracks: TrackSet = {}; const computePTSDTS = !Number.isFinite(this._initPTS); let container = 'audio/mp4'; let initPTS: number | undefined; let initDTS: number | undefined; let timescale: number | undefined; if (computePTSDTS) { initPTS = initDTS = Infinity; } if (audioTrack.config && audioSamples.length) { // let's use audio sampling rate as MP4 time scale. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC) // using audio sampling rate here helps having an integer MP4 frame duration // this avoids potential rounding issue and AV sync issue audioTrack.timescale = audioTrack.samplerate; if (!audioTrack.isAAC) { if (typeSupported.mpeg) { // Chrome and Safari container = 'audio/mpeg'; audioTrack.codec = ''; } else if (typeSupported.mp3) { // Firefox audioTrack.codec = 'mp3'; } } tracks.audio = { id: 'audio', container: container, codec: audioTrack.codec, initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : MP4.initSegment([audioTrack]), metadata: { channelCount: audioTrack.channelCount, }, }; if (computePTSDTS) { timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset); } } if (videoTrack.sps && videoTrack.pps && videoSamples.length) { // let's use input time scale as MP4 video timescale // we use input time scale straight away to avoid rounding issues on frame duration / cts computation videoTrack.timescale = videoTrack.inputTimeScale; tracks.video = { id: 'main', container: 'video/mp4', codec: videoTrack.codec, initSegment: MP4.initSegment([videoTrack]), metadata: { width: videoTrack.width, height: videoTrack.height, }, }; if (computePTSDTS) { timescale = videoTrack.inputTimeScale; const startPTS = this.getVideoStartPts(videoSamples); const startOffset = Math.round(timescale * timeOffset); initDTS = Math.min( initDTS as number, normalizePts(videoSamples[0].dts, startPTS) - startOffset ); initPTS = Math.min(initPTS as number, startPTS - startOffset); } } if (Object.keys(tracks).length) { this.ISGenerated = true; if (computePTSDTS) { this._initPTS = initPTS as number; this._initDTS = initDTS as number; } return { tracks, initPTS, timescale, }; } } remuxVideo( track: DemuxedAvcTrack, timeOffset: number, contiguous: boolean, audioTrackLength: number ): RemuxedTrack | undefined { const timeScale: number = track.inputTimeScale; const inputSamples: Array<AvcSample> = track.samples; const outputSamples: Array<Mp4Sample> = []; const nbSamples: number = inputSamples.length; const initPTS: number = this._initPTS; let nextAvcDts = this.nextAvcDts; let offset = 8; let mp4SampleDuration!: number; let firstDTS; let lastDTS; let minPTS: number = Number.POSITIVE_INFINITY; let maxPTS: number = Number.NEGATIVE_INFINITY; let ptsDtsShift = 0; let sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference if (!contiguous || nextAvcDts === null) { const pts = timeOffset * timeScale; const cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset nextAvcDts = pts - cts; } // PTS is coded on 33bits, and can loop from -2^32 to 2^32 // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value for (let i = 0; i < nbSamples; i++) { const sample = inputSamples[i]; sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts); sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts); if (sample.dts > sample.pts) { const PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2; ptsDtsShift = Math.max( Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ ); } if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) { sortSamples = true; } } // sort video samples by DTS then PTS then demux id order if (sortSamples) { inputSamples.sort(function (a, b) { const deltadts = a.dts - b.dts; const deltapts = a.pts - b.pts; return deltadts || deltapts; }); } // Get first/last DTS firstDTS = inputSamples[0].dts; lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS // set this constant duration as being the avg delta between consecutive DTS. const averageSampleDuration = Math.round( (lastDTS - firstDTS) / (nbSamples - 1) ); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds if (ptsDtsShift < 0) { if (ptsDtsShift < averageSampleDuration * -2) { // Fix for "CNN special report, with CC" in test-streams (including Safari browser) // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values logger.warn( `PTS < DTS detected in video samples, offsetting DTS from PTS by ${toMsFromMpegTsClock( -averageSampleDuration, true )} ms` ); let lastDts = ptsDtsShift; for (let i = 0; i < nbSamples; i++) { inputSamples[i].dts = lastDts = Math.max( lastDts, inputSamples[i].pts - averageSampleDuration ); inputSamples[i].pts = Math.max(lastDts, inputSamples[i].pts); } } else { // Fix for "Custom IV with bad PTS DTS" in test-streams // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari logger.warn( `PTS < DTS detected in video samples, shifting DTS by ${toMsFromMpegTsClock( ptsDtsShift, true )} ms to overcome this issue` ); for (let i = 0; i < nbSamples; i++) { inputSamples[i].dts = inputSamples[i].dts + ptsDtsShift; } } firstDTS = inputSamples[0].dts; } // if fragment are contiguous, detect hole/overlapping between fragments if (contiguous) { // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole) const delta = firstDTS - nextAvcDts; const foundHole = delta > averageSampleDuration; const foundOverlap = delta < -1; if (foundHole || foundOverlap) { if (foundHole) { logger.warn( `AVC: ${toMsFromMpegTsClock( delta, true )} ms (${delta}dts) hole between fragments detected, filling it` ); } else { logger.warn( `AVC: ${toMsFromMpegTsClock( -delta, true )} ms (${delta}dts) overlapping between fragments detected` ); } firstDTS = nextAvcDts; const firstPTS = inputSamples[0].pts - delta; inputSamples[0].dts = firstDTS; inputSamples[0].pts = firstPTS; logger.log( `Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock( firstPTS, true )}/${toMsFromMpegTsClock( firstDTS, true )}, delta: ${toMsFromMpegTsClock(delta, true)} ms` ); } } if (requiresPositiveDts) { firstDTS = Math.max(0, firstDTS); } let nbNalu = 0; let naluLen = 0; for (let i = 0; i < nbSamples; i++) { // compute total/avc sample length and nb of NAL units const sample = inputSamples[i]; const units = sample.units; const nbUnits = units.length; let sampleLen = 0; for (let j = 0; j < nbUnits; j++) { sampleLen += units[j].data.length; } naluLen += sampleLen; nbNalu += nbUnits; sample.length = sampleLen; // normalize PTS/DTS // ensure sample monotonic DTS sample.dts = Math.max(sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS sample.pts = Math.max(sample.pts, sample.dts, 0); minPTS = Math.min(sample.pts, minPTS); maxPTS = Math.max(sample.pts, maxPTS); } lastDTS = inputSamples[nbSamples - 1].dts; /* concatenate the video data and construct the mdat in place (need 8 more bytes to fill length and mpdat type) */ const mdatSize = naluLen + 4 * nbNalu + 8; let mdat; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}`, }); return; } const view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(MP4.types.mdat, 4); for (let i = 0; i < nbSamples; i++) { const avcSample = inputSamples[i]; const avcSampleUnits = avcSample.units; let mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field) for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) { const unit = avcSampleUnits[j]; const unitData = unit.data; const unitDataLen = unit.data.byteLength; view.setUint32(offset, unitDataLen); offset += 4; mdat.set(unitData, offset); offset += unitDataLen; mp4SampleLength += 4 + unitDataLen; } // expected sample duration is the Decoding Timestamp diff of consecutive samples if (i < nbSamples - 1) { mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts; } else { const config = this.config; const lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts; if (config.stretchShortVideoTrack && this.nextAudioPts !== null) { // In some cases, a segment's audio track duration may exceed the video track duration. // Since we've already remuxed audio, and we know how long the audio track is, we look to // see if the delta to the next segment is longer than maxBufferHole. // If so, playback would potentially get stuck, so we artificially inflate // the duration of the last frame to minimize any potential gap between segments. const gapTolerance = Math.floor(config.maxBufferHole * timeScale); const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts; if (deltaToFrameEnd > gapTolerance) { // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video // frame overlap. maxBufferHole should be >> lastFrameDuration anyway. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration; if (mp4SampleDuration < 0) { mp4SampleDuration = lastFrameDuration; } logger.log( `[mp4-remuxer]: It is approximately ${ deltaToFrameEnd / 90 } ms to the next segment; using duration ${ mp4SampleDuration / 90 } ms for the last video frame.` ); } else { mp4SampleDuration = lastFrameDuration; } } else { mp4SampleDuration = lastFrameDuration; } } const compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); outputSamples.push( new Mp4Sample( avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset ) ); } if (outputSamples.length && chromeVersion && chromeVersion < 70) { // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue // https://code.google.com/p/chromium/issues/detail?id=229412 const flags = outputSamples[0].flags; flags.dependsOn = 2; flags.isNonSync = 0; } console.assert( mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed' ); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale) this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration; this.isVideoContiguous = true; const moof = MP4.moof( track.sequenceNumber++, firstDTS, Object.assign({}, track, { samples: outputSamples, }) ); const type: SourceBufferName = 'video'; const data = { data1: moof, data2: mdat, startPTS: minPTS / timeScale, endPTS: (maxPTS + mp4SampleDuration) / timeScale, startDTS: firstDTS / timeScale, endDTS: (nextAvcDts as number) / timeScale, type, hasAudio: false, hasVideo: true, nb: outputSamples.length, dropped: track.dropped, }; track.samples = []; track.dropped = 0; console.assert(mdat.length, 'MDAT length must not be zero'); return data; } remuxAudio( track: DemuxedAudioTrack, timeOffset: number, contiguous: boolean, accurateTimeOffset: boolean, videoTimeOffset?: number ): RemuxedTrack | undefined { const inputTimeScale: number = track.inputTimeScale; const mp4timeScale: number = track.samplerate ? track.samplerate : inputTimeScale; const scaleFactor: number = inputTimeScale / mp4timeScale; const mp4SampleDuration: number = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME; const inputSampleDuration: number = mp4SampleDuration * scaleFactor; const initPTS: number = this._initPTS; const rawMPEG: boolean = !track.isAAC && this.typeSupported.mpeg; const outputSamples: Array<Mp4Sample> = []; let inputSamples: Array<AudioSample> = track.samples; let offset: number = rawMPEG ? 0 : 8; let nextAudioPts: number = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]); // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs), // for sake of clarity: // consecutive fragments are frags with // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR // - less than 20 audio frames distance // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1) // this helps ensuring audio continuity // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame const timeOffsetMpegTS = timeOffset * inputTimeScale; this.isAudioContiguous = contiguous = contiguous || ((inputSamples.length && nextAudioPts > 0 && ((accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) || Math.abs( normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts ) < 20 * inputSampleDuration)) as boolean); // compute normalized PTS inputSamples.forEach(function (sample) { sample.pts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS); }); if (!contiguous || nextAudioPts < 0) { // filter out sample with negative PTS that are not playable anyway // if we don't remove these negative samples, they will shift all audio samples forward. // leading to audio overlap between current / next fragment inputSamples = inputSamples.filter((sample) => sample.pts >= 0); // in case all samples have negative PTS, and have been filtered out, return now if (!inputSamples.length) { return; } if (videoTimeOffset === 0) { // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence nextAudioPts = 0; } else if (accurateTimeOffset) { // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS nextAudioPts = Math.max(0, timeOffsetMpegTS); } else { // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS nextAudioPts = inputSamples[0].pts; } } // If the audio track is missing samples, the frames seem to get "left-shifted" within the // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment. // In an effort to prevent this from happening, we inject frames here where there are gaps. // When possible, we inject a silent frame; when that's not possible, we duplicate the last // frame. if (track.isAAC) { const alignedWithVideo = videoTimeOffset !== undefined; const maxAudioFramesDrift = this.config.maxAudioFramesDrift; for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) { // First, let's see how far off this frame is from where we expect it to be const sample = inputSamples[i]; const pts = sample.pts; const delta = pts - nextPts; const duration = Math.abs((1000 * delta) / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync if ( delta <= -maxAudioFramesDrift * inputSampleDuration && alignedWithVideo ) { if (i === 0) { logger.warn( `Audio frame @ ${(pts / inputTimeScale).toFixed( 3 )}s overlaps nextAudioPts by ${Math.round( (1000 * delta) / inputTimeScale )} ms.` ); this.nextAudioPts = nextAudioPts = nextPts = pts; } } // eslint-disable-line brace-style // Insert missing frames if: // 1: We're more than maxAudioFramesDrift frame away // 2: Not more than MAX_SILENT_FRAME_DURATION away // 3: currentTime (aka nextPtsNorm) is not 0 // 4: remuxing with video (videoTimeOffset !== undefined) else if ( delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && alignedWithVideo ) { let missing = Math.round(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration. nextPts = pts - missing * inputSampleDuration; if (nextPts < 0) { missing--; nextPts += inputSampleDuration; } if (i === 0) { this.nextAudioPts = nextAudioPts = nextPts; } logger.warn( `[mp4-remuxer]: Injecting ${missing} audio frame @ ${( nextPts / inputTimeScale ).toFixed(3)}s due to ${Math.round( (1000 * delta) / inputTimeScale )} ms gap.` ); for (let j = 0; j < missing; j++) { const newStamp = Math.max(nextPts as number, 0); let fillFrame = AAC.getSilentFrame( track.manifestCodec || track.codec, track.channelCount ); if (!fillFrame) { logger.log( '[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.' ); fillFrame = sample.unit.subarray(); } inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, }); nextPts += inputSampleDuration; i++; } } sample.pts = nextPts; nextPts += inputSampleDuration; } } let firstPTS: number | null = null; let lastPTS: number | null = null; let mdat: any; let mdatSize: number = 0; let sampleLength: number = inputSamples.length; while (sampleLength--) { mdatSize += inputSamples[sampleLength].unit.byteLength; } for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) { const audioSample = inputSamples[j]; const unit = audioSample.unit; let pts = audioSample.pts; if (lastPTS !== null) { // If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with // the previous sample const prevSample = outputSamples[j - 1]; prevSample.duration = Math.round((pts - lastPTS) / scaleFactor); } else { if (contiguous && track.isAAC) { // set PTS/DTS to expected PTS/DTS pts = nextAudioPts; } // remember first PTS of our audioSamples firstPTS = pts; if (mdatSize > 0) { /* concatenate the audio data and construct the mdat in place (need 8 more bytes to fill length and mdat type) */ mdatSize += offset; try { mdat = new Uint8Array(mdatSize); } catch (err) { this.observer.emit(Events.ERROR, Events.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating audio mdat ${mdatSize}`, }); return; } if (!rawMPEG) { const view = new DataView(mdat.buffer); view.setUint32(0, mdatSize); mdat.set(MP4.types.mdat, 4); } } else { // no audio samples return; } } mdat.set(unit, offset); const unitLen = unit.byteLength; offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration // becomes the PTS diff with the previous sample outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0)); lastPTS = pts; } // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones const nbSamples = outputSamples.length; if (!nbSamples) { return; } // The next audio sample PTS should be equal to last sample PTS + duration const lastSample = outputSamples[outputSamples.length - 1]; this.nextAudioPts = nextAudioPts = lastPTS! + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing const moof = rawMPEG ? new Uint8Array(0) : MP4.moof( track.sequenceNumber++, firstPTS! / scaleFactor, Object.assign({}, track, { samples: outputSamples }) ); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared track.samples = []; const start = firstPTS! / inputTimeScale; const end = nextAudioPts / inputTimeScale; const type: SourceBufferName = 'audio'; const audioData = { data1: moof, data2: mdat, startPTS: start, endPTS: end, startDTS: start, endDTS: end, type, hasAudio: true, hasVideo: false, nb: nbSamples, }; this.isAudioContiguous = true; console.assert(mdat.length, 'MDAT length must not be zero'); return audioData; } remuxEmptyAudio( track: DemuxedAudioTrack, timeOffset: number, contiguous: boolean, videoData: Fragment ): RemuxedTrack | undefined { const inputTimeScale: number = track.inputTimeScale; const mp4timeScale: number = track.samplerate ? track.samplerate : inputTimeScale; const scaleFactor: number = inputTimeScale / mp4timeScale; const nextAudioPts: number | null = this.nextAudioPts; // sync with video's timestamp const startDTS: number = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS; const endDTS: number = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value const frameDuration: number = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration const nbSamples: number = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame const silentFrame: Uint8Array | undefined = AAC.getSilentFrame( track.manifestCodec || track.codec, track.channelCount ); logger.warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame... if (!silentFrame) { logger.trace( '[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec' ); return; } const samples: Array<any> = []; for (let i = 0; i < nbSamples; i++) { const stamp = startDTS + i * frameDuration; samples.push({ unit: silentFrame, pts: stamp, dts: stamp }); } track.samples = samples; return this.remuxAudio(track, timeOffset, contiguous, false); } remuxID3( track: DemuxedMetadataTrack, timeOffset: number ): RemuxedMetadata | undefined { const length = track.samples.length; if (!length) { return; } const inputTimeScale = track.inputTimeScale; const initPTS = this._initPTS; const initDTS = this._initDTS; for (let index = 0; index < length; index++) { const sample = track.samples[index]; // setting id3 pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale; } const samples = track.samples; track.samples = []; return { samples, }; } remuxText( track: DemuxedUserdataTrack, timeOffset: number ): RemuxedUserdata | undefined { const length = track.samples.length; if (!length) { return; } const inputTimeScale = track.inputTimeScale; const initPTS = this._initPTS; for (let index = 0; index < length; index++) { const sample = track.samples[index]; // setting text pts, dts to relative time // using this._initPTS and this._initDTS to calculate relative time sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale; } track.samples.sort((a, b) => a.pts - b.pts); const samples = track.samples; track.samples = []; return { samples, }; } } export function normalizePts(value: number, reference: number | null): number { let offset; if (reference === null) { return value; } if (reference < value) { // - 2^33 offset = -8589934592; } else { // + 2^33 offset = 8589934592; } /* PTS is 33bit (from 0 to 2^33 -1) if diff between value and reference is bigger than half of the amplitude (2^32) then it means that PTS looping occured. fill the gap */ while (Math.abs(value - reference) > 4294967296) { value += offset; } return value; } function findKeyframeIndex(samples: Array<AvcSample>): number { for (let i = 0; i < samples.length; i++) { if (samples[i].key) { return i; } } return -1; } class Mp4Sample { public size: number; public duration: number; public cts: number; public flags: Mp4SampleFlags; constructor(isKeyframe: boolean, duration, size, cts) { this.duration = duration; this.size = size; this.cts = cts; this.flags = new Mp4SampleFlags(isKeyframe); } } class Mp4SampleFlags { public isLeading: 0 = 0; public isDependedOn: 0 = 0; public hasRedundancy: 0 = 0; public degradPrio: 0 = 0; public dependsOn: 1 | 2 = 1; public isNonSync: 0 | 1 = 1; constructor(isKeyframe) { this.dependsOn = isKeyframe ? 2 : 1; this.isNonSync = isKeyframe ? 0 : 1; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Disks } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DevTestLabsClient } from "../devTestLabsClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { Disk, DisksListNextOptionalParams, DisksListOptionalParams, DisksListResponse, DisksGetOptionalParams, DisksGetResponse, DisksCreateOrUpdateOptionalParams, DisksCreateOrUpdateResponse, DisksDeleteOptionalParams, DiskFragment, DisksUpdateOptionalParams, DisksUpdateResponse, AttachDiskProperties, DisksAttachOptionalParams, DetachDiskProperties, DisksDetachOptionalParams, DisksListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Disks operations. */ export class DisksImpl implements Disks { private readonly client: DevTestLabsClient; /** * Initialize a new instance of the class Disks class. * @param client Reference to the service client */ constructor(client: DevTestLabsClient) { this.client = client; } /** * List disks in a given user profile. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param options The options parameters. */ public list( resourceGroupName: string, labName: string, userName: string, options?: DisksListOptionalParams ): PagedAsyncIterableIterator<Disk> { const iter = this.listPagingAll( resourceGroupName, labName, userName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage( resourceGroupName, labName, userName, options ); } }; } private async *listPagingPage( resourceGroupName: string, labName: string, userName: string, options?: DisksListOptionalParams ): AsyncIterableIterator<Disk[]> { let result = await this._list( resourceGroupName, labName, userName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, labName, userName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, labName: string, userName: string, options?: DisksListOptionalParams ): AsyncIterableIterator<Disk> { for await (const page of this.listPagingPage( resourceGroupName, labName, userName, options )) { yield* page; } } /** * List disks in a given user profile. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param options The options parameters. */ private _list( resourceGroupName: string, labName: string, userName: string, options?: DisksListOptionalParams ): Promise<DisksListResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, userName, options }, listOperationSpec ); } /** * Get disk. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param options The options parameters. */ get( resourceGroupName: string, labName: string, userName: string, name: string, options?: DisksGetOptionalParams ): Promise<DisksGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, userName, name, options }, getOperationSpec ); } /** * Create or replace an existing disk. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param disk A Disk. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, labName: string, userName: string, name: string, disk: Disk, options?: DisksCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<DisksCreateOrUpdateResponse>, DisksCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<DisksCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, labName, userName, name, disk, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Create or replace an existing disk. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param disk A Disk. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, labName: string, userName: string, name: string, disk: Disk, options?: DisksCreateOrUpdateOptionalParams ): Promise<DisksCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, labName, userName, name, disk, options ); return poller.pollUntilDone(); } /** * Delete disk. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, labName: string, userName: string, name: string, options?: DisksDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, labName, userName, name, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Delete disk. This operation can take a while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, labName: string, userName: string, name: string, options?: DisksDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, labName, userName, name, options ); return poller.pollUntilDone(); } /** * Allows modifying tags of disks. All other properties will be ignored. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param disk A Disk. * @param options The options parameters. */ update( resourceGroupName: string, labName: string, userName: string, name: string, disk: DiskFragment, options?: DisksUpdateOptionalParams ): Promise<DisksUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, userName, name, disk, options }, updateOperationSpec ); } /** * Attach and create the lease of the disk to the virtual machine. This operation can take a while to * complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param attachDiskProperties Properties of the disk to attach. * @param options The options parameters. */ async beginAttach( resourceGroupName: string, labName: string, userName: string, name: string, attachDiskProperties: AttachDiskProperties, options?: DisksAttachOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, labName, userName, name, attachDiskProperties, options }, attachOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Attach and create the lease of the disk to the virtual machine. This operation can take a while to * complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param attachDiskProperties Properties of the disk to attach. * @param options The options parameters. */ async beginAttachAndWait( resourceGroupName: string, labName: string, userName: string, name: string, attachDiskProperties: AttachDiskProperties, options?: DisksAttachOptionalParams ): Promise<void> { const poller = await this.beginAttach( resourceGroupName, labName, userName, name, attachDiskProperties, options ); return poller.pollUntilDone(); } /** * Detach and break the lease of the disk attached to the virtual machine. This operation can take a * while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param detachDiskProperties Properties of the disk to detach. * @param options The options parameters. */ async beginDetach( resourceGroupName: string, labName: string, userName: string, name: string, detachDiskProperties: DetachDiskProperties, options?: DisksDetachOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, labName, userName, name, detachDiskProperties, options }, detachOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Detach and break the lease of the disk attached to the virtual machine. This operation can take a * while to complete. * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param name The name of the disk. * @param detachDiskProperties Properties of the disk to detach. * @param options The options parameters. */ async beginDetachAndWait( resourceGroupName: string, labName: string, userName: string, name: string, detachDiskProperties: DetachDiskProperties, options?: DisksDetachOptionalParams ): Promise<void> { const poller = await this.beginDetach( resourceGroupName, labName, userName, name, detachDiskProperties, options ); return poller.pollUntilDone(); } /** * ListNext * @param resourceGroupName The name of the resource group. * @param labName The name of the lab. * @param userName The name of the user profile. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, labName: string, userName: string, nextLink: string, options?: DisksListNextOptionalParams ): Promise<DisksListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, labName, userName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DiskList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Disk }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion, Parameters.expand], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Disk }, 201: { bodyMapper: Mappers.Disk }, 202: { bodyMapper: Mappers.Disk }, 204: { bodyMapper: Mappers.Disk }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.disk, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.Disk }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.disk1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const attachOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}/attach", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.attachDiskProperties, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const detachOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/users/{userName}/disks/{name}/detach", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.detachDiskProperties, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DiskList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.expand, Parameters.filter, Parameters.top, Parameters.orderby ], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.labName, Parameters.userName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Blueprint, schemas } from '@boost/common/optimal'; import { mockFilePath } from '@boost/common/test'; import { mergeExtends } from '../src/helpers/mergeExtends'; import { mergePlugins } from '../src/helpers/mergePlugins'; import { overwrite } from '../src/helpers/overwrite'; import { Processor } from '../src/Processor'; import { createExtendsSchema, createOverridesSchema, createPluginsSchema } from '../src/schemas'; import { ConfigFile, ExtendsSetting, OverridesSetting, PluginsSetting } from '../src/types'; describe('Processor', () => { interface ConfigShape { // Settings debug: boolean; extends: ExtendsSetting; plugins: PluginsSetting; overrides: OverridesSetting<Omit<ConfigShape, 'extends' | 'overrides'>>; // Types boolean: boolean; string: string; stringList: string[]; number: number; numberList: number[]; object: object; } let processor: Processor<ConfigShape>; function stubConfigFile(config: Partial<ConfigShape>): ConfigFile<ConfigShape> { return { config, path: mockFilePath('.boost.js'), source: 'branch', }; } beforeEach(() => { processor = new Processor({ name: 'boost' }); }); describe('handlers', () => { it('sets a handler', () => { const spy = jest.fn(); processor.addHandler('debug', spy); expect(processor.getHandler('debug')).toBe(spy); }); it('overwrites a handler of the same name', () => { const spy1 = jest.fn(); processor.addHandler('debug', spy1); const spy2 = jest.fn(); processor.addHandler('debug', spy2); expect(processor.getHandler('debug')).toBe(spy2); }); it('returns null if not defined', () => { expect(processor.getHandler('debug')).toBeNull(); }); }); describe('processing', () => { const commonBlueprint = { debug: schemas.bool(false), plugins: createPluginsSchema(), boolean: schemas.bool(true), string: schemas.string(''), stringList: schemas.array(['foo']).of(schemas.string()), number: schemas.number(123), numberList: schemas.array([]).of(schemas.number()), object: schemas.object(), }; const blueprint: Blueprint<ConfigShape> = { ...commonBlueprint, extends: createExtendsSchema(), overrides: createOverridesSchema(commonBlueprint), }; const defaults: ConfigShape = { debug: false, extends: [], plugins: {}, overrides: [], boolean: true, string: '', stringList: ['foo'], number: 123, numberList: [], object: {}, }; it('returns defaults if no configs', async () => { await expect(processor.process(defaults, [], blueprint)).resolves.toEqual(defaults); }); describe('undefined values', () => { it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [stubConfigFile({ debug: true }), stubConfigFile({ debug: undefined })], blueprint, ), ).resolves.toEqual(defaults); }); it('does not reset to default if `defaultWhenUndefined` option is false', async () => { processor.configure({ defaultWhenUndefined: false }); await expect( processor.process( defaults, [stubConfigFile({ debug: true }), stubConfigFile({ debug: undefined })], blueprint, ), ).resolves.toEqual({ ...defaults, debug: undefined, }); }); }); describe('validation', () => { it('validates each config', async () => { await expect( processor.process( defaults, [ stubConfigFile({ debug: true }), stubConfigFile({ // @ts-expect-error Invalid type debug: 123, }), ], blueprint, ), ).rejects.toThrowErrorMatchingSnapshot(); }); it('doesnt validate if the `validate` option is false', async () => { processor.configure({ validate: false }); await expect( processor.process( defaults, [ stubConfigFile({ debug: true }), stubConfigFile({ // @ts-expect-error Invalid type debug: 123, }), ], blueprint, ), ).resolves.not.toThrow(); }); }); describe('extends setting', () => { it('supports extends from multiple configs', async () => { processor.addHandler('extends', mergeExtends); await expect( processor.process( defaults, [ stubConfigFile({ extends: 'foo' }), stubConfigFile({ extends: ['bar', './baz.js'] }), stubConfigFile({ extends: '/qux.js' }), ], blueprint, ), ).resolves.toEqual({ ...defaults, extends: ['foo', 'bar', './baz.js', '/qux.js'], }); }); it('errors for an invalid value', async () => { await expect( processor.process( defaults, [ stubConfigFile({ // @ts-expect-error Invalid type extends: 123, }), ], blueprint, ), ).rejects.toThrowErrorMatchingSnapshot(); }); it('errors for an empty string', async () => { await expect( processor.process(defaults, [stubConfigFile({ extends: '' })], blueprint), ).rejects.toThrowErrorMatchingSnapshot(); }); it('errors for an empty string in an array', async () => { await expect( processor.process(defaults, [stubConfigFile({ extends: ['foo', ''] })], blueprint), ).rejects.toThrowErrorMatchingSnapshot(); }); }); describe('plugins setting', () => { it('supports plugins from multiple configs', async () => { processor.addHandler('plugins', mergePlugins); await expect( processor.process( defaults, [ stubConfigFile({ plugins: { foo: true, qux: { on: true } } }), stubConfigFile({ plugins: [['bar', false]] }), stubConfigFile({ plugins: { foo: { legacy: true }, baz: true, qux: { on: false } } }), stubConfigFile({ plugins: ['oop'] }), ], blueprint, ), ).resolves.toEqual({ ...defaults, plugins: { foo: { legacy: true }, bar: false, baz: true, qux: { on: false }, oop: true, }, }); }); it('errors for an invalid value', async () => { await expect( processor.process( defaults, [ stubConfigFile({ // @ts-expect-error Invalid type plugins: true, }), ], blueprint, ), ).rejects.toThrowErrorMatchingSnapshot(); }); it('errors for an invalid option value', async () => { await expect( processor.process( defaults, [ stubConfigFile({ // @ts-expect-error Invalid type plugins: { foo: 123, }, }), ], blueprint, ), ).rejects.toThrowErrorMatchingSnapshot(); }); }); describe('booleans', () => { it('can overwrite', async () => { await expect( processor.process( defaults, [stubConfigFile({ debug: true }), stubConfigFile({ boolean: false })], blueprint, ), ).resolves.toEqual({ ...defaults, debug: true, boolean: false, }); }); it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [stubConfigFile({ debug: true }), stubConfigFile({ debug: undefined })], blueprint, ), ).resolves.toEqual(defaults); }); }); describe('strings', () => { it('can overwrite', async () => { await expect( processor.process( defaults, [stubConfigFile({ string: 'foo' }), stubConfigFile({ string: 'bar' })], blueprint, ), ).resolves.toEqual({ ...defaults, string: 'bar', }); }); it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [stubConfigFile({ string: 'foo' }), stubConfigFile({ string: undefined })], blueprint, ), ).resolves.toEqual(defaults); }); }); describe('numbers', () => { it('can overwrite', async () => { await expect( processor.process( defaults, [stubConfigFile({ number: 123 }), stubConfigFile({ number: 456 })], blueprint, ), ).resolves.toEqual({ ...defaults, number: 456, }); }); it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [stubConfigFile({ number: 999 }), stubConfigFile({ number: undefined })], blueprint, ), ).resolves.toEqual(defaults); }); }); describe('arrays', () => { it('merges and flattens by default', async () => { await expect( processor.process( defaults, [ stubConfigFile({ stringList: ['foo', 'bar'] }), stubConfigFile({ stringList: [] }), stubConfigFile({ stringList: ['bar', 'baz'] }), ], blueprint, ), ).resolves.toEqual({ ...defaults, stringList: ['foo', 'bar', 'baz'], }); }); it('can overwrite using a custom handler', async () => { processor.addHandler('numberList', overwrite); await expect( processor.process( defaults, [stubConfigFile({ numberList: [1, 2, 3] }), stubConfigFile({ numberList: [4, 5, 6] })], blueprint, ), ).resolves.toEqual({ ...defaults, numberList: [4, 5, 6], }); }); it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [ stubConfigFile({ stringList: ['foo', 'bar', 'baz'] }), stubConfigFile({ stringList: undefined }), ], blueprint, ), ).resolves.toEqual(defaults); }); }); describe('objects', () => { it('shallow merges by default', async () => { await expect( processor.process( defaults, [ stubConfigFile({ object: { foo: 123, nested: { a: true }, baz: false } }), stubConfigFile({ object: {} }), stubConfigFile({ object: { foo: 456, nested: { b: true }, bar: 'abc' } }), ], blueprint, ), ).resolves.toEqual({ ...defaults, object: { foo: 456, nested: { b: true }, bar: 'abc', baz: false }, }); }); it('can overwrite using a custom handler', async () => { processor.addHandler('object', overwrite); await expect( processor.process( defaults, [stubConfigFile({ object: { foo: 123 } }), stubConfigFile({ object: { bar: 456 } })], blueprint, ), ).resolves.toEqual({ ...defaults, object: { bar: 456 }, }); }); it('can reset to default using undefined', async () => { await expect( processor.process( defaults, [stubConfigFile({ object: { bar: 456 } }), stubConfigFile({ object: undefined })], blueprint, ), ).resolves.toEqual(defaults); }); }); }); });
the_stack
interface ModuleResolver { /** * A function used to resolve the exports for a module. * @param uri The name of the module to be resolved. */ (uri: string): any; } /** * An extended JavaScript Error which will have the nativeError property initialized in case the error is caused by executing platform-specific code. */ declare interface NativeScriptError extends Error { /** * Represents the native error object. */ nativeError: any; } //Augment the NodeJS global type with our own extensions declare namespace NodeJS { interface Global { NativeScriptHasInitGlobal?: boolean; NativeScriptGlobals?: { /** * Global framework event handling */ events: { on(eventNames: string, callback: (data: any) => void, thisArg?: any); on(event: 'propertyChange', callback: (data: any) => void, thisArg?: any); off(eventNames: string, callback?: any, thisArg?: any); addEventListener(eventNames: string, callback: (data: any) => void, thisArg?: any); removeEventListener(eventNames: string, callback?: any, thisArg?: any); set(name: string, value: any): void; setProperty(name: string, value: any): void; get(name: string): any; notify<T>(data: any): void; notifyPropertyChange(propertyName: string, value: any, oldValue?: any): void; hasListeners(eventName: string): boolean; }; launched: boolean; // used by various classes to setup callbacks to wire up global app event handling when the app instance is ready appEventWiring: Array<any>; // determines if the app instance is ready upon bootstrap appInstanceReady: boolean; /** * Ability for classes to initialize app event handling early even before the app instance is ready during boot cycle avoiding boot race conditions * @param callback wire up any global event handling inside the callback */ addEventWiring(callback: () => void): void; }; android?: any; require(id: string): any; moduleMerge(sourceExports: any, destExports: any): void; registerModule(name: string, loader: (name: string) => any): void; /** * Register all modules from a webpack context. * The context is one created using the following webpack utility: * https://webpack.js.org/guides/dependency-management/#requirecontext * * The extension map is optional, modules in the webpack context will have their original file extension (e.g. may be ".ts" or ".scss" etc.), * while the built-in module builders in {N} will look for ".js", ".css" or ".xml" files. Adding a map such as: * ``` * { ".ts": ".js" } * ``` * Will resolve lookups for .js to the .ts file. * By default scss and ts files are mapped. */ registerWebpackModules(context: { keys(): string[]; (key: string): any }, extensionMap?: { [originalFileExtension: string]: string }); /** * The NativeScript XML builder, style-scope, application modules use various resources such as: * app.css, page.xml files and modules during the application life-cycle. * The moduleResolvers can be used to provide additional mechanisms to locate such resources. * For example: * ``` * global.moduleResolvers.unshift(uri => uri === "main-page" ? require("main-page") : null); * ``` * More advanced scenarios will allow for specific bundlers to integrate their module resolving mechanisms. * When adding resolvers at the start of the array, avoid throwing and return null instead so subsequent resolvers may try to resolve the resource. * By default the only member of the array is global.require, as last resort - if it fails to find a module it will throw. */ readonly moduleResolvers: ModuleResolver[]; /** * * @param name Name of the module to be loaded * @param loadForUI Is this UI module is being loaded for UI from @nativescript/core/ui/builder. * Xml, css/scss and js/ts modules for pages and custom-components should load with loadForUI=true. * Passing "true" will enable the HMR mechanics this module. Default value is false. */ loadModule(name: string, loadForUI?: boolean): any; /** * Checks if the module has been registered with `registerModule` or in `registerWebpackModules` * @param name Name of the module */ moduleExists(name: string): boolean; getRegisteredModules(): string[]; _unregisterModule(name: string): void; _isModuleLoadedForUI(moduleName: string): boolean; onGlobalLayoutListener: any; zonedCallback(callback: Function): Function; Reflect?: any; Deprecated(target: Object, key?: string | symbol, descriptor?: any): any; Experimental(target: Object, key?: string | symbol, descriptor?: any): any; __native?: any; __inspector?: any; __extends: any; __onLiveSync: (context?: { type: string; path: string }) => void; __onLiveSyncCore: (context?: { type: string; path: string }) => void; __onUncaughtError: (error: NativeScriptError) => void; __onDiscardedError: (error: NativeScriptError) => void; __snapshot?: boolean; TNS_WEBPACK?: boolean; isIOS?: boolean; isAndroid?: boolean; __requireOverride?: (name: string, dir: string) => any; // used to get the rootlayout instance to add/remove childviews rootLayout: any; } } declare const __DEV__: boolean; declare const __CSS_PARSER__: string; declare const __NS_WEBPACK__: boolean; declare const __UI_USE_EXTERNAL_RENDERER__: boolean; declare const __UI_USE_XML_PARSER__: boolean; declare const __ANDROID__: boolean; declare const __IOS__: boolean; declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): number; declare function clearTimeout(timeoutId: number): void; declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): number; declare function clearInterval(intervalId: number): void; declare type ModuleType = 'markup' | 'script' | 'style'; /** * Define a module context for Hot Module Replacement. */ interface ModuleContext { /** * The type of the module for replacement. */ type: ModuleType; /** * The path of the module for replacement. */ path: string; } interface NodeModule { exports: any; id: string; filename: string; } declare enum RequestContext { 'audio', 'beacon', 'cspreport', 'download', 'embed', 'eventsource', 'favicon', 'fetch', 'font', 'form', 'frame', 'hyperlink', 'iframe', 'image', 'imageset', 'import', 'internal', 'location', 'manifest', 'object', 'ping', 'plugin', 'prefetch', 'script', 'serviceworker', 'sharedworker', 'subresource', 'style', 'track', 'video', 'worker', 'xmlhttprequest', 'xslt', } // Extend the lib.dom.d.ts Body interface with `formData` // interface Body { // formData(): Promise<FormData>; // } declare type HeaderInit = Headers | Array<string>; declare function fetch(url: string, init?: RequestInit): Promise<Response>; // declare var console: Console; declare var require: NodeRequire; // Extend NodeRequire with the webpack's require context extension. interface RequireContext { keys(): string[]; (id: string): any; <T>(id: string): T; resolve(id: string): string; } declare var __dirname: string; declare var __filename: string; declare var module: NodeModule; // Same as module.exports declare var exports: any; // Global functions declare function Deprecated(target: Object, key?: string | symbol, value?: any): void; declare function Experimental(target: Object, key?: string | symbol, value?: any): void; declare interface NativeClassOptions { nativeClassName?: string; // for @JavaProxy and protocols?: any[]; interfaces?: any[]; } /** * Decorates class that extends a native class(iOS or Android) */ declare function NativeClass<T extends { new (...args: any[]): {} }>(constructor: T); declare function NativeClass<T extends { new (...args: any[]): {} }>(options?: NativeClassOptions); /** * Decorates class that implements native Java interfaces. * @param interfaces Implemented interfaces. */ declare function Interfaces(...interfaces): ClassDecorator; /** * Important: Not applicable to Objective-C classes (iOS platform) * Decorates class that extends native Java class * @param interfaces An array of fully-classified Java interface names that the class must implement. */ declare function Interfaces(interfaces: any[]): ClassDecorator; /** * Decorates class that extends native Java class * @param nativeClassName The name of the newly generated class. Must be unique in the application. */ declare function JavaProxy(nativeClassName: string): ClassDecorator; /** * Important: Not applicable to Java classes (Android platform) * Decorates a class that implements native Objective-C protocols. * @param protocols An array of fully-classified Objective-C protocol names that the class must implement. */ declare function ObjCClass(...protocols: any[]): ClassDecorator; /** * Important: Not applicable to Java methods (Android platform) * Decorates method that it is exposed in Objective-C. * The JS name of the method will be used as the name of the native method * and the return type will be set to `interop.types.void` */ declare function ObjCMethod(): MethodDecorator; /** * Important: Not applicable to Java methods (Android platform) * Decorates method that it is exposed in Objective-C. * @param name The name of the method to be exposed. * The native return type will be set to `interop.types.void`. */ declare function ObjCMethod(name: string): MethodDecorator; /** * Important: Not applicable to Java methods (Android platform) * Decorates a method to be exposed in Objective-C. * The JS name of the method will be used for the name of the native method. * @param returnType The native type of the result. */ declare function ObjCMethod(returnType: any): MethodDecorator; /** * Important: Not applicable to Java methods (Android platform) * Decorates a method to be exposed in Objective-C. * @param name The name of the method to be exposed. Can be different than the JS function name * and can follow Objective-C colon syntax (for example `tableView:cellForRowAtIndexPath:`). * @param returnType The native type of the result. */ declare function ObjCMethod(name: string, returnType: any): MethodDecorator; /** * Important: Not applicable to Java classes or methods (Android platform) * This is a shorthand decorator that can be used to decorate either a method or a class * to be exposed to Objective-C. * @param params Parameters to send to the ObjCClass or ObjCMethod decorators. */ declare function ObjC(...params: any[]): ClassDecorator & MethodDecorator; /** * Important: Not applicable to Java method parameters (Android platform) * Decorates a parameter in an Objective-C exposed method with its native type. * @param type The native type for the parameter. */ declare function ObjCParam(type: any): ParameterDecorator; declare function Log(data: any): void; declare function log(data: any): void; declare function fail(data: any): void; /** * Calls a function after a specified delay. * @param callback The function to be called. * @param milliseconds The time to wait before the function is called. Defaults to 0. */ // declare function setTimeout(callback: Function, milliseconds?: number): number; /** * Clears the delay set by a call to the setTimeout function. * @param id The identifier returned by the previously called setTimeout() method. */ // declare function clearTimeout(id: number): void; /** * Calls a function repeatedly with a delay between each call. * @param callback The function to be called. * @param milliseconds The delay between each function call. */ // declare function setInterval(callback: Function, milliseconds?: number): number; /** * Clears repeated function which was set up by calling setInterval(). * @param id The identifier returned by the setInterval() method. */ // declare function clearInterval(id: number): void; declare function zonedCallback(callback: Function): Function; declare class WeakRef<T> { constructor(obj: T); get(): T; clear(): void; } /** * Create a Java long from a number */ declare function long(value: number): any; /** * Create a Java byte from a number */ declare function byte(value: number): any; /** * Create a Java short from a number */ declare function short(value: number): any; /** * Create a Java double from a number */ declare function double(value: number): any; /** * Create a Java float from a number */ declare function float(value: number): any; /** * Create a Java char from a string */ declare function char(value: string): any;
the_stack
import time from '../time'; import { revisionService, setupDatabaseAndSynchronizer, switchClient } from '../testing/test-utils'; import Setting from '../models/Setting'; import Note from '../models/Note'; import ItemChange from '../models/ItemChange'; import Revision from '../models/Revision'; import BaseModel from '../BaseModel'; import RevisionService from '../services/RevisionService'; describe('services_Revision', function() { beforeEach(async (done) => { await setupDatabaseAndSynchronizer(1); await switchClient(1); Setting.setValue('revisionService.intervalBetweenRevisions', 0); done(); }); it('should create diff and rebuild notes', (async () => { const service = new RevisionService(); const n1_v1 = await Note.save({ title: '', author: 'testing' }); await service.collectRevisions(); await Note.save({ id: n1_v1.id, title: 'hello', author: 'testing' }); await service.collectRevisions(); await Note.save({ id: n1_v1.id, title: 'hello welcome', author: '' }); await service.collectRevisions(); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions.length).toBe(2); expect(revisions[1].parent_id).toBe(revisions[0].id); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('hello'); expect(rev1.author).toBe('testing'); const rev2 = await service.revisionNote(revisions, 1); expect(rev2.title).toBe('hello welcome'); expect(rev2.author).toBe(''); const time_rev2 = Date.now(); await time.msleep(10); const ttl = Date.now() - time_rev2 - 1; await service.deleteOldRevisions(ttl); const revisions2 = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions2.length).toBe(0); })); // ---------------------------------------------------------------------- // This is to verify that the revision service continues processing // revisions even when it fails on one note. However, now that the // diff-match-patch bug is fixed, it's not possible to create notes that // would make the process fail. Keeping the test anyway in case such case // comes up again. // ---------------------------------------------------------------------- // it('should handle corrupted strings', (async () => { // const service = new RevisionService(); // // Silence the logger because the revision service is going to print // // errors. // // Logger.globalLogger.enabled = false; // const n1 = await Note.save({ body: '' }); // await service.collectRevisions(); // await Note.save({ id: n1.id, body: naughtyStrings[152] }); // REV 1 // await service.collectRevisions(); // await Note.save({ id: n1.id, body: naughtyStrings[153] }); // FAIL (Should have been REV 2) // await service.collectRevisions(); // // Because it fails, only one revision was generated. The second was skipped. // expect((await Revision.all()).length).toBe(1); // // From this point, note 1 will always fail because of a // // diff-match-patch bug: // // https://github.com/JackuB/diff-match-patch/issues/22 // // It will throw "URI malformed". But it shouldn't prevent other notes // // from getting revisions. // const n2 = await Note.save({ body: '' }); // await service.collectRevisions(); // await Note.save({ id: n2.id, body: 'valid' }); // REV 2 // await service.collectRevisions(); // expect((await Revision.all()).length).toBe(2); // Logger.globalLogger.enabled = true; // })); it('should delete old revisions (1 note, 2 rev)', (async () => { const service = new RevisionService(); const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'hello' }); await service.collectRevisions(); const time_v1 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'hello welcome' }); await service.collectRevisions(); expect((await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id)).length).toBe(2); const ttl = Date.now() - time_v1 - 1; await service.deleteOldRevisions(ttl); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions.length).toBe(1); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('hello welcome'); })); it('should delete old revisions (1 note, 3 rev)', (async () => { const service = new RevisionService(); const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'one' }); await service.collectRevisions(); const time_v1 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'one two' }); await service.collectRevisions(); const time_v2 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'one two three' }); await service.collectRevisions(); { const ttl = Date.now() - time_v1 - 1; await service.deleteOldRevisions(ttl); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions.length).toBe(2); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('one two'); const rev2 = await service.revisionNote(revisions, 1); expect(rev2.title).toBe('one two three'); } { const ttl = Date.now() - time_v2 - 1; await service.deleteOldRevisions(ttl); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions.length).toBe(1); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('one two three'); } })); it('should delete old revisions (2 notes, 2 rev)', (async () => { const service = new RevisionService(); const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'note 1' }); const n2_v0 = await Note.save({ title: '' }); const n2_v1 = await Note.save({ id: n2_v0.id, title: 'note 2' }); await service.collectRevisions(); const time_n2_v1 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'note 1 (v2)' }); await Note.save({ id: n2_v1.id, title: 'note 2 (v2)' }); await service.collectRevisions(); expect((await Revision.all()).length).toBe(4); const ttl = Date.now() - time_n2_v1 - 1; await service.deleteOldRevisions(ttl); { const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1_v1.id); expect(revisions.length).toBe(1); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('note 1 (v2)'); } { const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n2_v1.id); expect(revisions.length).toBe(1); const rev1 = await service.revisionNote(revisions, 0); expect(rev1.title).toBe('note 2 (v2)'); } })); it('should handle conflicts', (async () => { const service = new RevisionService(); // A conflict happens in this case: // - Device 1 creates note1 (rev1) // - Device 2 syncs and get note1 // - Device 1 modifies note1 (rev2) // - Device 2 modifies note1 (rev3) // When reconstructing the notes based on the revisions, we need to make sure it follow the right // "path". For example, to reconstruct the note at rev2 it would be: // rev1 => rev2 // To reconstruct the note at rev3 it would be: // rev1 => rev3 // And not, for example, rev1 => rev2 => rev3 const n1_v1 = await Note.save({ title: 'hello' }); const noteId = n1_v1.id; const rev1 = await service.createNoteRevision_(n1_v1); const n1_v2 = await Note.save({ id: noteId, title: 'hello Paul' }); await service.createNoteRevision_(n1_v2, rev1.id); const n1_v3 = await Note.save({ id: noteId, title: 'hello John' }); await service.createNoteRevision_(n1_v3, rev1.id); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, noteId); expect(revisions.length).toBe(3); expect(revisions[1].parent_id).toBe(rev1.id); expect(revisions[2].parent_id).toBe(rev1.id); const revNote1 = await service.revisionNote(revisions, 0); const revNote2 = await service.revisionNote(revisions, 1); const revNote3 = await service.revisionNote(revisions, 2); expect(revNote1.title).toBe('hello'); expect(revNote2.title).toBe('hello Paul'); expect(revNote3.title).toBe('hello John'); })); it('should create a revision for notes that are older than a given interval', (async () => { const n1 = await Note.save({ title: 'hello' }); const noteId = n1.id; await time.msleep(100); // Set the interval in such a way that the note is considered an old one. Setting.setValue('revisionService.oldNoteInterval', 50); // A revision is created the first time a note is overwritten with new content, and // if this note doesn't already have an existing revision. // This is mostly to handle old notes that existed before the revision service. If these // old notes are changed, there's a chance it's accidental or due to some bug, so we // want to preserve a revision just in case. { await Note.save({ id: noteId, title: 'hello 2' }); await revisionService().collectRevisions(); // Rev for old note created + Rev for new note const all = await Revision.allByType(BaseModel.TYPE_NOTE, noteId); expect(all.length).toBe(2); const revNote1 = await revisionService().revisionNote(all, 0); const revNote2 = await revisionService().revisionNote(all, 1); expect(revNote1.title).toBe('hello'); expect(revNote2.title).toBe('hello 2'); } // If the note is saved a third time, we don't automatically create a revision. One // will be created x minutes later when the service collects revisions. { await Note.save({ id: noteId, title: 'hello 3' }); const all = await Revision.allByType(BaseModel.TYPE_NOTE, noteId); expect(all.length).toBe(2); } })); it('should create a revision for notes that get deleted (recyle bin)', (async () => { const n1 = await Note.save({ title: 'hello' }); const noteId = n1.id; await Note.delete(noteId); await revisionService().collectRevisions(); const all = await Revision.allByType(BaseModel.TYPE_NOTE, noteId); expect(all.length).toBe(1); const rev1 = await revisionService().revisionNote(all, 0); expect(rev1.title).toBe('hello'); })); it('should not create a revision for notes that get deleted if there is already a revision', (async () => { const n1 = await Note.save({ title: 'hello' }); await revisionService().collectRevisions(); const noteId = n1.id; await Note.save({ id: noteId, title: 'hello Paul' }); await revisionService().collectRevisions(); // REV 1 expect((await Revision.allByType(BaseModel.TYPE_NOTE, n1.id)).length).toBe(1); await Note.delete(noteId); // At this point there is no need to create a new revision for the deleted note // because we already have the latest version as REV 1 await revisionService().collectRevisions(); expect((await Revision.allByType(BaseModel.TYPE_NOTE, n1.id)).length).toBe(1); })); it('should not create a revision for new note the first time they are saved', (async () => { const n1 = await Note.save({ title: 'hello' }); { const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1.id); expect(revisions.length).toBe(0); } await revisionService().collectRevisions(); { const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1.id); expect(revisions.length).toBe(0); } })); it('should abort collecting revisions when one of them is encrypted', (async () => { const n1 = await Note.save({ title: 'hello' }); // CHANGE 1 await revisionService().collectRevisions(); await Note.save({ id: n1.id, title: 'hello Ringo' }); // CHANGE 2 await revisionService().collectRevisions(); await Note.save({ id: n1.id, title: 'hello George' }); // CHANGE 3 await revisionService().collectRevisions(); const revisions = await Revision.allByType(BaseModel.TYPE_NOTE, n1.id); expect(revisions.length).toBe(2); const encryptedRevId = revisions[0].id; // Simulate receiving an encrypted revision await Revision.save({ id: encryptedRevId, encryption_applied: 1 }); await Note.save({ id: n1.id, title: 'hello Paul' }); // CHANGE 4 await revisionService().collectRevisions(); // Although change 4 is a note update, check that it has not been processed // by the collector, due to one of the revisions being encrypted. expect(await ItemChange.lastChangeId()).toBe(4); expect(Setting.value('revisionService.lastProcessedChangeId')).toBe(3); // Simulate the revision being decrypted by DecryptionService await Revision.save({ id: encryptedRevId, encryption_applied: 0 }); await revisionService().collectRevisions(); // Now that the revision has been decrypted, all the changes can be processed expect(await ItemChange.lastChangeId()).toBe(4); expect(Setting.value('revisionService.lastProcessedChangeId')).toBe(4); })); it('should not delete old revisions if one of them is still encrypted (1)', (async () => { // Test case 1: Two revisions and the first one is encrypted. // Calling deleteOldRevisions() with low TTL, which means all revisions // should be deleted, but they won't be due to the encrypted one. const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 await time.sleep(0.1); await Note.save({ id: n1_v1.id, title: 'hello welcome' }); await revisionService().collectRevisions(); // REV 2 await time.sleep(0.1); expect((await Revision.all()).length).toBe(2); const revisions = await Revision.all(); await Revision.save({ id: revisions[0].id, encryption_applied: 1 }); await revisionService().deleteOldRevisions(0); expect((await Revision.all()).length).toBe(2); await Revision.save({ id: revisions[0].id, encryption_applied: 0 }); await revisionService().deleteOldRevisions(0); expect((await Revision.all()).length).toBe(0); })); it('should not delete old revisions if one of them is still encrypted (2)', (async () => { // Test case 2: Two revisions and the first one is encrypted. // Calling deleteOldRevisions() with higher TTL, which means the oldest // revision should be deleted, but it won't be due to the encrypted one. const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 const timeRev1 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'hello welcome' }); await revisionService().collectRevisions(); // REV 2 expect((await Revision.all()).length).toBe(2); const revisions = await Revision.all(); await Revision.save({ id: revisions[0].id, encryption_applied: 1 }); const ttl = Date.now() - timeRev1 - 1; await revisionService().deleteOldRevisions(ttl); expect((await Revision.all()).length).toBe(2); })); it('should not delete old revisions if one of them is still encrypted (3)', (async () => { // Test case 2: Two revisions and the second one is encrypted. // Calling deleteOldRevisions() with higher TTL, which means the oldest // revision should be deleted, but it won't be due to the encrypted one. const n1_v0 = await Note.save({ title: '' }); const n1_v1 = await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 const timeRev1 = Date.now(); await time.msleep(100); await Note.save({ id: n1_v1.id, title: 'hello welcome' }); await revisionService().collectRevisions(); // REV 2 expect((await Revision.all()).length).toBe(2); const revisions = await Revision.all(); await Revision.save({ id: revisions[1].id, encryption_applied: 1 }); let ttl = Date.now() - timeRev1 - 1; await revisionService().deleteOldRevisions(ttl); expect((await Revision.all()).length).toBe(2); await Revision.save({ id: revisions[1].id, encryption_applied: 0 }); ttl = Date.now() - timeRev1 - 1; await revisionService().deleteOldRevisions(ttl); expect((await Revision.all()).length).toBe(1); })); it('should not create a revision if the note has not changed', (async () => { const n1_v0 = await Note.save({ title: '' }); await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 expect((await Revision.all()).length).toBe(1); await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // Note has not changed (except its timestamp) so don't create a revision expect((await Revision.all()).length).toBe(1); })); it('should preserve user update time', (async () => { // user_updated_time is kind of tricky and can be changed automatically in various // places so make sure it is saved correctly with the revision const n1_v0 = await Note.save({ title: '' }); await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 expect((await Revision.all()).length).toBe(1); const userUpdatedTime = Date.now() - 1000 * 60 * 60; await Note.save({ id: n1_v0.id, title: 'hello', updated_time: Date.now(), user_updated_time: userUpdatedTime }, { autoTimestamp: false }); await revisionService().collectRevisions(); // Only the user timestamp has changed, but that needs to be saved const revisions = await Revision.all(); expect(revisions.length).toBe(2); const revNote = await revisionService().revisionNote(revisions, 1); expect(revNote.user_updated_time).toBe(userUpdatedTime); })); it('should not create a revision if there is already a recent one', (async () => { const n1_v0 = await Note.save({ title: '' }); await Note.save({ id: n1_v0.id, title: 'hello' }); await revisionService().collectRevisions(); // REV 1 const timeRev1 = Date.now(); await time.sleep(2); const timeRev2 = Date.now(); await Note.save({ id: n1_v0.id, title: 'hello 2' }); await revisionService().collectRevisions(); // REV 2 expect((await Revision.all()).length).toBe(2); const interval = Date.now() - timeRev1 + 1; Setting.setValue('revisionService.intervalBetweenRevisions', interval); await Note.save({ id: n1_v0.id, title: 'hello 3' }); await revisionService().collectRevisions(); // No rev because time since last rev is less than the required 'interval between revisions' expect(Date.now() - interval < timeRev2).toBe(true); // check the computer is not too slow for this test expect((await Revision.all()).length).toBe(2); })); });
the_stack
// tslint:disable:no-unused-expression max-func-body-length promise-function-async max-line-length no-http-string no-suspicious-comment // tslint:disable:no-non-null-assertion import { diagnosticSources, IDeploymentParameterDefinition, IDeploymentTemplate, testDiagnostics } from "../support/diagnostics"; import { testWithLanguageServer } from "../support/testWithLanguageServer"; // Note: a lot of these come from TLE.test.ts, but this version goes through the vscode diagnostics and thus tests the language server suite("Expressions functional tests", () => { // testName defaults to expression if left blank function testExpression(testName: string, expression: string, expected: string[]): void { testWithLanguageServer(testName || expression, async () => { let template: IDeploymentTemplate = { $schema: "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", contentVersion: "1.0.0.0", resources: [ { name: "resource1", type: "some type", apiVersion: "xxx", location: "westus", properties: { } } ], variables: { }, parameters: { } }; function addVarIfUsed(varName: string, value: number | unknown[] | string | {}): void { if (expression.match(new RegExp(`variables\\s*\\(\\s*'${varName}'\\s*\\)`, "i"))) { template.variables![varName] = value; } } function addParamIfUsed(paramName: string, definition: IDeploymentParameterDefinition): void { if (expression.match(new RegExp(`parameters\\s*\\(\\s*'${paramName}'\\s*\\)`, "i"))) { template.parameters![paramName] = definition; } } addVarIfUsed("stringVar", "hello"); addVarIfUsed("intVar", "321"); addVarIfUsed("arrayVar", [1, 2, [3, 4, 5]]); addParamIfUsed("intParam", { type: "int" }); addParamIfUsed("arrayParam", { type: "array", defaultValue: [1, 2, 3] }); addParamIfUsed("objParam", { type: "object", defaultValue: { abc: 1, def: "def", ghi: [1, 2, 3], jkl: { a: "hello" } } }); // Add a property with the expression as the value template.resources[0]!.properties![`test`] = expression; await testDiagnostics( template, { includeSources: [diagnosticSources.expressions], includeRange: false }, expected); }); } function testLiteralExpression(literalExpression: string, expected: string[]): void { // Wrap the literal in 'concat' because the extension doesn't currently allow just literals // (https://github.com/microsoft/vscode-azurearmtools/issues/216) testExpression(`testLiteralExpression("${literalExpression}")`, `[concat(${literalExpression})]`, expected); } suite("general issues", () => { testExpression("Empty expression", "[]", [ "Error: Expected a function or property expression. (arm-template (expressions))" ]); testExpression("Missing right bracket", "[", [ "Error: Expected a right square bracket (']'). (arm-template (expressions))", "Error: Expected a function or property expression. (arm-template (expressions))" ]); testExpression("", "[concat('abc')", [ "Error: Expected a right square bracket (']'). (arm-template (expressions))" ]); testExpression("string after function", "[deployment()'world']", [ "Error: Expected the end of the string. (arm-template (expressions)) [11,31]" ]); testExpression("with several invalid literals", ".[]82348923asdglih asl .,'", [ ]); testExpression( "https://github.com/Microsoft/vscode-azurearmtools/issues/34", "[concat(reference(parameters('publicIpName')).dnsSettings.fqdn, '; sudo docker volume rm ''dockercompose_cert-volume''; sudo docker-compose up')]", [ // This should be the only error we get. In particular, no errors with the escaped apostrophes "Error: Undefined parameter reference: 'publicIpName' (arm-template (expressions)) [11,47-11,61]" ]); }); suite("Plain strings vs expressions", () => { // Inferred rules by experimenting with deployments // See https://github.com/microsoft/vscode-azurearmtools/issues/250 suite("1: Starts with [ but doesn't end with ] -> consider a string, don't change", () => { /* TODO: Needs to be fixed: https://github.com/microsoft/vscode-azurearmtools/issues/250 // "[one]two" // -> string: "[one]two" testExpression("[abc]withsuffix", []); */ /* TODO: Needs to be fixed: https://github.com/microsoft/vscode-azurearmtools/issues/250 // testExpression("[abc", []); */ // -> string: "[[one]two" testExpression("", "[[one]two", []); }); suite("2: Starts with [[ -> replace first [[ with [, consider a string", () => { // "[[one]" // -> string: "[one]" testExpression("", "[[one]", []); // "[[one]two]" // -> string: "[one]two]" testExpression("", "[[one]two]", []); // "[[[one]two]" // -> string: "[[one]two]" testExpression("", "[[[one]two]", []); testExpression("", "[[abc", []); testExpression("", "[[[abc", []); }); suite("3: Starts with [ (and ends with ]) -> expression", () => { // "one" // -> string: "one" testExpression("", "[concat('')]", []); }); suite("4: Anything else is a string", () => { /* TODO: Needs to be fixed: https://github.com/microsoft/vscode-azurearmtools/issues/250 // " [one]" // -> string testExpression("Starts with whitespace", " [one]", []); */ /* TODO: Needs to be fixed: https://github.com/microsoft/vscode-azurearmtools/issues/250 // "[one] " // -> string testExpression("Ends with whitespace", "[one] ", []); */ }); testExpression("", "]", []); }); suite("string literals", () => { testLiteralExpression("''", []); testLiteralExpression("'hello'", []); testLiteralExpression(" '123' ", []); suite("Escaped apostrophes", () => { testLiteralExpression("'That''s it!'", []); testLiteralExpression("''''", []); testLiteralExpression(" ' '' ' ", []); testLiteralExpression("'''That''s all, \"folks\"!'''", []); }); testLiteralExpression("'Bad apostrophe's'", [ "Error: Expected a comma (','). (arm-template (expressions))", "Error: Expected a comma (','). (arm-template (expressions))", "Error: Expected a right square bracket (']'). (arm-template (expressions))", ]); suite("Escaped apostrophes", () => { testLiteralExpression("''", []); testLiteralExpression("'That''s it!'", []); }); testLiteralExpression("'Bad apostrophe's'", [ "Error: Expected a comma (','). (arm-template (expressions))", "Error: Expected a comma (','). (arm-template (expressions))", "Error: Expected a right square bracket (']'). (arm-template (expressions))", ]); }); suite("numeric literals", () => { testLiteralExpression("123", []); testLiteralExpression("0", []); testLiteralExpression("-0", []); testLiteralExpression("1", []); testLiteralExpression("-1", []); testLiteralExpression("-1234", []); testLiteralExpression("1234", []); testLiteralExpression("7.8", []); testLiteralExpression("-3.14159265", []); /* CONSIDER: Should this be accepted? testLiteralExpression("+1234", []); testLiteralExpression("+0", []); */ /* CONSIDER: I don't think this is valid, but it is accepted (colorization rejects it) testLiteralExpression("-.14159265", [ ]); */ }); suite("Function calls", () => { suite("Missing left paren", () => { testExpression("", "[concat'abc')]", [ "Error: Expected the end of the string. (arm-template (expressions)) [11,25]", "Error: Expected the end of the string. (arm-template (expressions)) [11,30]", "Error: Missing function argument list. (arm-template (expressions)) [11,19]" ]); testExpression("", "[concat 1,2)]", [ 'Error: Expected the end of the string. (arm-template (expressions)) [11,26]', 'Error: Expected the end of the string. (arm-template (expressions)) [11,27]', 'Error: Expected the end of the string. (arm-template (expressions)) [11,28]', 'Error: Expected the end of the string. (arm-template (expressions)) [11,29]', 'Error: Missing function argument list. (arm-template (expressions)) [11,19]' ]); }); suite("Missing right paren", () => { testExpression("", "[concat('abc']", [ "Error: Expected a right parenthesis (')'). (arm-template (expressions)) [11,31-11,32]" ]); }); // No args testExpression("", "[deployment()]", []); // 1 arg testExpression("", "[string(1)]", []); // 2 args testExpression("", "[equals('abc','bc')]", []); testExpression("", "[ equals ( 'abc', 'bc' ) ]", []); // Missing comma testExpression("", "[equals('abc' 'bc')]", [ "Error: Expected a comma (','). (arm-template (expressions)) [11,32-11,36]", "Error: The function 'equals' takes 2 arguments. (arm-template (expressions)) [11,19-11,37]" ]); // Expected 2 args, has zero testExpression("", "[equals()]", [ "Error: The function 'equals' takes 2 arguments. (arm-template (expressions)) [11,19-11,27]" ]); // Expected 2 args, has one testExpression("", "[equals('a')]", [ "Error: The function 'equals' takes 2 arguments. (arm-template (expressions)) [11,19]" ]); // Expected 2 args, has three testExpression("", "[equals('a', 'b', 'c')]", [ "Error: The function 'equals' takes 2 arguments. (arm-template (expressions)) [11,19]" ]); // Unrecognized function name with arg testExpression("", "[parameter('arrayParam')]", [ "Error: Unrecognized function name 'parameter'. (arm-template (expressions)) [11,19]" ]); }); suite("Variables/Parameters", () => { // Variables testExpression("", "[variables('arrayVar')]", []); // Parameters testExpression("", "[parameters('arrayParam')]", []); /* CONSIDER: Doesn't currently pass (the expression itself gives no errors, but we get a warning that intParam is never used) testExpression("", "[PARAmeters('intParam')]", []); */ suite("Undefined parameters/variables", () => { testExpression("", "[parameters('undefined')]", [ 'Error: Undefined parameter reference: \'undefined\' (arm-template (expressions)) [11,30-11,41]' ]); testExpression("", "[variables('undefined')]", [ "Error: Undefined variable reference: 'undefined' (arm-template (expressions)) [11,29-11,40]" ]); testExpression("", "[parameters('')]", [ "Error: Undefined parameter reference: '' (arm-template (expressions)) [11,30-11,32]" ]); /* CONSIDER: This doesn't give any errors. Should it? testExpression("", "[parameters(1)]", [ ]); */ // No errors should be reported for a property access to an undefined variable, because the top priority error for the developer to address is the undefined variable reference. testExpression("with child property access from undefined variable reference", "[variables('undefVar').apples]", [ "Error: Undefined variable reference: 'undefVar' (arm-template (expressions)) [11,29-11,39]" ]); // No errors should be reported for a property access to an undefined variable, because the top priority error for the developer to address is the undefined variable reference. testExpression("with grandchild property access from undefined variable reference", "[variables('undefVar').apples.bananas]", [ "Error: Undefined variable reference: 'undefVar' (arm-template (expressions)) [11,29]" ]); testExpression("with child property access from variable reference to non-object variable", "[variables('intVar').apples]", [ `Error: Property "apples" is not a defined property of "variables('intVar')". (arm-template (expressions))`]); testExpression("with grandchild property access from variable reference to non-object variable", "[variables('stringVar').apples.bananas]", [ `Error: Property "apples" is not a defined property of "variables('stringVar')". (arm-template (expressions))`]); }); }); suite("Array/Object access", () => { testExpression("", "[parameters('arrayParam')[0]]", []); testExpression("", "[variables('arrayVar')[parameters('intParam')]]", []); testExpression("", "[variables('arrayVar')[1][1]]", []); testExpression("", "[variables('arrayVar')[add(12,3)]]", []); // Object access testExpression("", "[parameters('objParam').abc]", []); testExpression("", "[ parameters ( 'objParam' ) . abc ]", []); // Object and array access testExpression("", "[parameters('objParam').abc[2]]", []); // Array argument testExpression("", "[string(variables('arrayVar')[0])]", []); testExpression("", "[variables('arrayVar')[1][1]", [ "Error: Expected a right square bracket (']'). (arm-template (expressions)) [11,46]" ]); }); suite("Property access", () => { testExpression("", "[resourceGroup().name]", []); // Property access, missing period testExpression("", "[resourceGroup()name]", [ "Error: Expected the end of the string. (arm-template (expressions)) [11,34]" ]); // Property access, quoted property name testExpression("", "[resourceGroup().'name']", [ "Error: Expected a literal value. (arm-template (expressions)) [11,35]" ]); // Property access, numeric property name testExpression("", "[resourceGroup().1]", [ "Error: Expected a literal value. (arm-template (expressions)) [11,35]" ]); // Property access, missing property name testExpression("", "[resourceGroup().]", [ "Error: Expected a literal value. (arm-template (expressions)) [11,35]" ]); // Property access, two deep testExpression("", "[resourceGroup().name.length]", []); }); suite("Miscellaneous and real scenarios", () => { testExpression("", "[concat(parameters('_artifactsLocation'), '/', '/scripts/azuremysql.sh', parameters('_artifactsLocationSasToken'))], )]", [ 'Error: Nothing should exist after the closing \']\' except for whitespace. (arm-template (expressions)) [11,133-11,134]', 'Error: Nothing should exist after the closing \']\' except for whitespace. (arm-template (expressions)) [11,135-11,136]', 'Error: Nothing should exist after the closing \']\' except for whitespace. (arm-template (expressions)) [11,136-11,137]', 'Error: Undefined parameter reference: \'_artifactsLocation\' (arm-template (expressions)) [11,37-11,57]', 'Error: Undefined parameter reference: \'_artifactsLocationSasToken\' (arm-template (expressions)) [11,102-11,130]' ]); }); });
the_stack
import 'chrome://resources/js/action_link.js'; import 'chrome://resources/cr_elements/action_link_css.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js'; import 'chrome://resources/cr_elements/icons.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js'; import '../icons.js'; import '../settings_shared_css.js'; import './all_sites_icons.js'; import './clear_storage_dialog_css.js'; import './site_details_permission.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js'; import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js'; import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {loadTimeData} from '../i18n_setup.js'; import {MetricsBrowserProxyImpl, PrivacyElementInteractions} from '../metrics_browser_proxy.js'; import {routes} from '../route.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; import {ContentSetting, ContentSettingsTypes} from './constants.js'; import {SiteDetailsPermissionElement} from './site_details_permission.js'; import {SiteSettingsMixin, SiteSettingsMixinInterface} from './site_settings_mixin.js'; import {WebsiteUsageBrowserProxy, WebsiteUsageBrowserProxyImpl} from './website_usage_browser_proxy.js'; export interface SiteDetailsElement { $: { confirmClearStorage: CrDialogElement, confirmResetSettings: CrDialogElement, noStorage: HTMLElement, storage: HTMLElement, usage: HTMLElement, }; } const SiteDetailsElementBase = RouteObserverMixin( SiteSettingsMixin(WebUIListenerMixin(I18nMixin(PolymerElement)))) as { new (): PolymerElement & I18nMixinInterface & WebUIListenerMixinInterface & SiteSettingsMixinInterface & RouteObserverMixinInterface }; export class SiteDetailsElement extends SiteDetailsElementBase { static get is() { return 'site-details'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * Whether unified autoplay blocking is enabled. */ blockAutoplayEnabled: Boolean, /** * Use the string representing the origin or extension name as the page * title of the settings-subpage parent. */ pageTitle: { type: String, notify: true, }, /** * The origin that this widget is showing details for. */ origin_: String, /** * The amount of data stored for the origin. */ storedData_: { type: String, value: '', }, /** * The number of cookies stored for the origin. */ numCookies_: { type: String, value: '', }, enableExperimentalWebPlatformFeatures_: { type: Boolean, value() { return loadTimeData.getBoolean( 'enableExperimentalWebPlatformFeatures'); }, }, enableWebBluetoothNewPermissionsBackend_: { type: Boolean, value: () => loadTimeData.getBoolean('enableWebBluetoothNewPermissionsBackend'), }, contentSettingsTypesEnum_: { type: Object, value: ContentSettingsTypes, }, }; } blockAutoplayEnabled: boolean; pageTitle: string; private origin_: string; private storedData_: string; private numCookies_: string; private enableExperimentalWebPlatformFeatures_: boolean; private enableWebBluetoothNewPermissionsBackend_: boolean; private fetchingForHost_: string = ''; private websiteUsageProxy_: WebsiteUsageBrowserProxy = WebsiteUsageBrowserProxyImpl.getInstance(); connectedCallback() { super.connectedCallback(); this.addWebUIListener( 'usage-total-changed', (host: string, data: string, cookies: string) => { this.onUsageTotalChanged_(host, data, cookies); }); this.addWebUIListener( 'contentSettingSitePermissionChanged', (category: ContentSettingsTypes, origin: string) => this.onPermissionChanged_(category, origin)); // Refresh block autoplay status from the backend. this.browserProxy.fetchBlockAutoplayStatus(); } /** * RouteObserverMixin */ currentRouteChanged(route: Route) { if (route !== routes.SITE_SETTINGS_SITE_DETAILS) { return; } const site = Router.getInstance().getQueryParameters().get('site'); if (!site) { return; } this.origin_ = site; this.browserProxy.isOriginValid(this.origin_).then((valid) => { if (!valid) { Router.getInstance().navigateToPreviousRoute(); } else { this.fetchingForHost_ = this.toUrl(this.origin_)!.hostname; this.storedData_ = ''; this.websiteUsageProxy_.fetchUsageTotal(this.fetchingForHost_); this.browserProxy.getCategoryList(this.origin_).then((categoryList) => { this.updatePermissions_(categoryList, /*hideOthers=*/ true); }); } }); } /** * Called when a site within a category has been changed. * @param category The category that changed. * @param origin The origin of the site that changed. */ private onPermissionChanged_(category: ContentSettingsTypes, origin: string) { if (this.origin_ === undefined || this.origin_ === '' || origin === undefined || origin === '') { return; } this.browserProxy.getCategoryList(this.origin_).then((categoryList) => { if (categoryList.includes(category)) { this.updatePermissions_([category], /*hideOthers=*/ false); } }); } /** * Callback for when the usage total is known. * @param host The host that the usage was fetched for. * @param usage The string showing how much data the given host is using. * @param cookies The string showing how many cookies the given host is using. */ private onUsageTotalChanged_(host: string, usage: string, cookies: string) { if (this.fetchingForHost_ === host) { this.storedData_ = usage; this.numCookies_ = cookies; } } /** * Retrieves the permissions listed in |categoryList| from the backend for * |this.origin_|. * @param categoryList The list of categories to update permissions for. * @param hideOthers If true, permissions for categories not in * |categoryList| will be hidden. */ private updatePermissions_( categoryList: Array<ContentSettingsTypes>, hideOthers: boolean) { const permissionsMap: {[key: string]: SiteDetailsPermissionElement} = Array.prototype.reduce.call( this.shadowRoot!.querySelectorAll('site-details-permission'), (map, element) => { if (categoryList.includes(element.category)) { (map as {[key: string]: SiteDetailsPermissionElement})[element.category] = element; } else if (hideOthers) { // This will hide any permission not in the category list. element.site = null; } return map; }, {}) as {[key: string]: SiteDetailsPermissionElement}; this.browserProxy.getOriginPermissions(this.origin_, categoryList) .then((exceptionList) => { exceptionList.forEach((exception, i) => { // |exceptionList| should be in the same order as // |categoryList|. if (permissionsMap[categoryList[i]]) { permissionsMap[categoryList[i]].site = exception; } }); // The displayName won't change, so just use the first // exception. assert(exceptionList.length > 0); this.pageTitle = this.originRepresentation(exceptionList[0].displayName); }); } private onCloseDialog_(e: Event) { (e.target as HTMLElement).closest('cr-dialog')!.close(); } /** * Confirms the resetting of all content settings for an origin. */ private onConfirmClearSettings_(e: Event) { e.preventDefault(); this.$.confirmResetSettings.showModal(); } /** * Confirms the clearing of storage for an origin. */ private onConfirmClearStorage_(e: Event) { e.preventDefault(); this.$.confirmClearStorage.showModal(); } /** * Resets all permissions for the current origin. */ private onResetSettings_(e: Event) { this.browserProxy.setOriginPermissions( this.origin_, null, ContentSetting.DEFAULT); this.onCloseDialog_(e); } /** * Clears all data stored, except cookies, for the current origin. */ private onClearStorage_(e: Event) { MetricsBrowserProxyImpl.getInstance().recordSettingsPageHistogram( PrivacyElementInteractions.SITE_DETAILS_CLEAR_DATA); if (this.hasUsage_(this.storedData_, this.numCookies_)) { this.websiteUsageProxy_.clearUsage(this.toUrl(this.origin_)!.href); this.storedData_ = ''; this.numCookies_ = ''; } this.onCloseDialog_(e); } /** * Checks whether this site has any usage information to show. * @return Whether there is any usage information to show (e.g. disk or * battery). */ private hasUsage_(storage: string, cookies: string): boolean { return storage !== '' || cookies !== ''; } /** * Checks whether this site has both storage and cookies information to show. * @return Whether there are both storage and cookies information to show. */ private hasDataAndCookies_(storage: string, cookies: string): boolean { return storage !== '' && cookies !== ''; } private onResetSettingsDialogClosed_() { focusWithoutInk( assert(this.shadowRoot!.querySelector('#resetSettingsButton')!)); } private onClearStorageDialogClosed_() { focusWithoutInk(assert(this.shadowRoot!.querySelector('#clearStorage')!)); } } declare global { interface HTMLElementTagNameMap { 'site-details': SiteDetailsElement; } } customElements.define(SiteDetailsElement.is, SiteDetailsElement);
the_stack
import _ from 'lodash'; import cytoscape from 'cytoscape'; import { ServiceDependencyGraph } from '../serviceDependencyGraph/ServiceDependencyGraph'; import ParticleEngine from './particle_engine'; import { CyCanvas, Particle, EnGraphNodeType, Particles, IntGraphMetrics, ScaleValue, DrawContext } from '../../types'; import humanFormat from 'human-format'; import assetUtils from '../asset_utils'; const scaleValues: ScaleValue[] = [ { unit: 'ms', factor: 1 }, { unit: 's', factor: 1000 }, { unit: 'm', factor: 60000 }, ]; export default class CanvasDrawer { readonly colors = { default: '#bad5ed', background: '#212121', edge: '#505050', status: { warning: 'orange', }, }; readonly donutRadius: number = 15; controller: ServiceDependencyGraph; cytoscape: cytoscape.Core; context: CanvasRenderingContext2D; cyCanvas: CyCanvas; canvas: HTMLCanvasElement; offscreenCanvas: HTMLCanvasElement; offscreenContext: CanvasRenderingContext2D; frameCounter = 0; fpsCounter = 0; particleImage: HTMLImageElement; pixelRatio: number; imageAssets: any = {}; selectionNeighborhood: cytoscape.Collection; particleEngine: ParticleEngine; lastRenderTime = 0; dashAnimationOffset = 0; constructor(ctrl: ServiceDependencyGraph, cy: cytoscape.Core, cyCanvas: CyCanvas) { this.cytoscape = cy; this.cyCanvas = cyCanvas; this.controller = ctrl; this.particleEngine = new ParticleEngine(this); this.pixelRatio = window.devicePixelRatio || 1; this.canvas = cyCanvas.getCanvas(); const ctx = this.canvas.getContext('2d'); if (ctx) { this.context = ctx; } else { console.error('Could not get 2d canvas context.'); } this.offscreenCanvas = document.createElement('canvas'); this.offscreenContext = this.offscreenCanvas.getContext('2d'); this.repaint(true); } _getTimeScale(timeUnit: string) { const scale: any = {}; for (const scaleValue of scaleValues) { scale[scaleValue.unit] = scaleValue.factor; if (scaleValue.unit === timeUnit) { return scale; } } return scale; } resetAssets() { this.imageAssets = {}; } _loadImage(imageUrl: string, assetName: string) { const that = this; const loadImage = (url: string, asset: keyof typeof that.imageAssets) => { const image = new Image(); that.imageAssets[asset] = { image, loaded: false, }; return new Promise((resolve, reject) => { image.onload = () => resolve(asset); image.onerror = () => reject(new Error(`load ${url} fail`)); image.src = url; }); }; loadImage(imageUrl, assetName).then((asset: any) => { that.imageAssets[asset].loaded = true; }); } _isImageLoaded(assetName: string) { if (_.has(this.imageAssets, assetName) && this.imageAssets[assetName].loaded) { return true; } else { return false; } } _getImageAsset(assetName: string, resolveName = true) { if (!_.has(this.imageAssets, assetName)) { const { externalIcons } = this.controller.getSettings(true); const assetUrl = assetUtils.getTypeSymbol(assetName, externalIcons, resolveName); this._loadImage(assetUrl, assetName); } if (this._isImageLoaded(assetName)) { return this.imageAssets[assetName].image; } else { return null; } } _getAsset(assetName: string, relativeUrl: string) { if (!_.has(this.imageAssets, assetName)) { const assetUrl = assetUtils.getAssetUrl(relativeUrl); this._loadImage(assetUrl, assetName); } if (this._isImageLoaded(assetName)) { return this.imageAssets[assetName].image; } else { return null; } } start() { console.log('Starting graph logic'); const that = this; const repaintWrapper = () => { that.repaint(); window.requestAnimationFrame(repaintWrapper); }; window.requestAnimationFrame(repaintWrapper); setInterval(() => { that.fpsCounter = that.frameCounter; that.frameCounter = 0; }, 1000); } startAnimation() { this.particleEngine.start(); } stopAnimation() { this.particleEngine.stop(); this.repaint(); } _skipFrame() { const now = Date.now(); const elapsedTime = now - this.lastRenderTime; if (this.particleEngine.count() > 0) { return false; } if (!this.controller.getSettings(true).animate && elapsedTime < 1000) { return true; } return false; } repaint(forceRepaint = false) { if (!forceRepaint && this._skipFrame()) { return; } this.lastRenderTime = Date.now(); const ctx = this.context; const cyCanvas = this.cyCanvas; const offscreenCanvas = this.offscreenCanvas; const offscreenContext = this.offscreenContext; offscreenCanvas.width = this.canvas.width; offscreenCanvas.height = this.canvas.height; // offscreen rendering this._setTransformation(offscreenContext); this.selectionNeighborhood = this.cytoscape.collection(); const selection = this.cytoscape.$(':selected'); selection.forEach((element: cytoscape.SingularElementArgument) => { this.selectionNeighborhood.merge(element); if (element.isNode()) { const neighborhood = element.neighborhood(); this.selectionNeighborhood.merge(neighborhood); } else { const source = element.source(); const target = element.target(); this.selectionNeighborhood.merge(source); this.selectionNeighborhood.merge(target); } }); this._drawEdgeAnimation(offscreenContext); this._drawNodes(offscreenContext); // static element rendering // cyCanvas.resetTransform(ctx); cyCanvas.clear(ctx); if (this.controller.getSettings(true).showDebugInformation) { this._drawDebugInformation(); } if (offscreenCanvas.width > 0 && offscreenCanvas.height > 0) { ctx.drawImage(offscreenCanvas, 0, 0); } // baseline animation this.dashAnimationOffset = (Date.now() % 60000) / 250; } _setTransformation(ctx: CanvasRenderingContext2D) { const pan = this.cytoscape.pan(); const zoom = this.cytoscape.zoom(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.translate(pan.x * this.pixelRatio, pan.y * this.pixelRatio); ctx.scale(zoom * this.pixelRatio, zoom * this.pixelRatio); } _drawEdgeAnimation(ctx: CanvasRenderingContext2D) { const now = Date.now(); ctx.save(); const edges = this.cytoscape.edges().toArray(); const hasSelection = this.selectionNeighborhood.size() > 0; const transparentEdges = edges.filter(edge => hasSelection && !this.selectionNeighborhood.has(edge)); const opaqueEdges = edges.filter(edge => !hasSelection || this.selectionNeighborhood.has(edge)); ctx.globalAlpha = 0.25; this._drawEdges(ctx, transparentEdges, now); ctx.globalAlpha = 1; this._drawEdges(ctx, opaqueEdges, now); ctx.restore(); } _drawEdges(ctx: CanvasRenderingContext2D, edges: cytoscape.EdgeSingular[], now: number) { const cy = this.cytoscape; for (const edge of edges) { const sourcePoint = edge.sourceEndpoint(); const targetPoint = edge.targetEndpoint(); this._drawEdgeLine(ctx, edge, sourcePoint, targetPoint); this._drawEdgeParticles(ctx, edge, sourcePoint, targetPoint, now); } const { showConnectionStats } = this.controller.getSettings(true); if (showConnectionStats && cy.zoom() > 1) { for (const edge of edges) { this._drawEdgeLabel(ctx, edge); } } } _drawEdgeLine( ctx: CanvasRenderingContext2D, edge: cytoscape.EdgeSingular, sourcePoint: cytoscape.Position, targetPoint: cytoscape.Position ) { ctx.beginPath(); ctx.moveTo(sourcePoint.x, sourcePoint.y); ctx.lineTo(targetPoint.x, targetPoint.y); const metrics = edge.data('metrics'); const requestCount = _.get(metrics, 'normal', -1); const errorCount = _.get(metrics, 'danger', -1); let base; if (!this.selectionNeighborhood.empty() && this.selectionNeighborhood.has(edge)) { ctx.lineWidth = 3; base = 140; } else { ctx.lineWidth = 1; base = 80; } if (requestCount >= 0 && errorCount >= 0) { const range = 255; const factor = errorCount / requestCount; const color = Math.min(255, base + range * Math.log2(factor + 1)); ctx.strokeStyle = 'rgb(' + color + ',' + base + ',' + base + ')'; } else { ctx.strokeStyle = 'rgb(' + base + ',' + base + ',' + base + ')'; } ctx.stroke(); } _drawEdgeLabel(ctx: CanvasRenderingContext2D, edge: cytoscape.EdgeSingular) { const { timeFormat } = this.controller.getSettings(true); const midpoint = edge.midpoint(); const xMid = midpoint.x; const yMid = midpoint.y; let statistics: string[] = []; const metrics: IntGraphMetrics = edge.data('metrics'); const duration = _.defaultTo(metrics.response_time, -1); const requestCount = _.defaultTo(metrics.rate, -1); const errorCount = _.defaultTo(metrics.error_rate, -1); const timeScale = new humanFormat.Scale(this._getTimeScale(timeFormat)); if (duration >= 0) { const decimals = duration >= 1000 ? 1 : 0; statistics.push(humanFormat(duration, { scale: timeScale, decimals })); } if (requestCount >= 0) { const decimals = requestCount >= 1000 ? 1 : 0; statistics.push(humanFormat(parseFloat(requestCount.toString()), { decimals }) + ' Requests'); } if (errorCount >= 0) { const decimals = errorCount >= 1000 ? 1 : 0; statistics.push(humanFormat(errorCount, { decimals }) + ' Errors'); } if (statistics.length > 0) { const edgeLabel = statistics.join(', '); this._drawLabel(ctx, edgeLabel, xMid, yMid); } } _drawEdgeParticles( ctx: CanvasRenderingContext2D, edge: cytoscape.EdgeSingular, sourcePoint: cytoscape.Position, targetPoint: cytoscape.Position, now: number ) { const particles: Particles = edge.data('particles'); if (particles === undefined) { return; } const xVector = targetPoint.x - sourcePoint.x; const yVector = targetPoint.y - sourcePoint.y; const angle = Math.atan2(yVector, xVector); const xDirection = Math.cos(angle); const yDirection = Math.sin(angle); const xMinLimit = Math.min(sourcePoint.x, targetPoint.x); const xMaxLimit = Math.max(sourcePoint.x, targetPoint.x); const yMinLimit = Math.min(sourcePoint.y, targetPoint.y); const yMaxLimit = Math.max(sourcePoint.y, targetPoint.y); const drawContext: DrawContext = { ctx, now, xDirection, yDirection, xMinLimit, xMaxLimit, yMinLimit, yMaxLimit, sourcePoint, }; // normal particles ctx.beginPath(); let index = particles.normal.length - 1; while (index >= 0) { this._drawParticle(drawContext, particles.normal, index); index--; } ctx.fillStyle = '#d1e2f2'; ctx.fill(); // danger particles ctx.beginPath(); index = particles.danger.length - 1; while (index >= 0) { this._drawParticle(drawContext, particles.danger, index); index--; } const dangerColor = this.controller.getSettings(true).style.dangerColor; ctx.fillStyle = dangerColor; ctx.fill(); } _drawLabel(ctx: CanvasRenderingContext2D, label: string, cX: number, cY: number) { const labelPadding = 1; ctx.font = '6px Arial'; const labelWidth = ctx.measureText(label).width; const xPos = cX - labelWidth / 2; const yPos = cY + 3; ctx.fillStyle = this.colors.default; ctx.fillRect(xPos - labelPadding, yPos - 6 - labelPadding, labelWidth + 2 * labelPadding, 6 + 2 * labelPadding); ctx.fillStyle = this.colors.background; ctx.fillText(label, xPos, yPos); } _drawParticle(drawCtx: DrawContext, particles: Particle[], index: number) { const { ctx, now, xDirection, yDirection, xMinLimit, xMaxLimit, yMinLimit, yMaxLimit, sourcePoint } = drawCtx; const particle = particles[index]; const timeDelta = now - particle.startTime; const xPos = sourcePoint.x + xDirection * timeDelta * particle.velocity; const yPos = sourcePoint.y + yDirection * timeDelta * particle.velocity; if (xPos > xMaxLimit || xPos < xMinLimit || yPos > yMaxLimit || yPos < yMinLimit) { // remove particle particles.splice(index, 1); } else { // draw particle ctx.moveTo(xPos, yPos); ctx.arc(xPos, yPos, 1, 0, 2 * Math.PI, false); } } _drawNodes(ctx: CanvasRenderingContext2D) { const that = this; const cy = this.cytoscape; // Draw model elements const nodes = cy.nodes().toArray(); for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (that.selectionNeighborhood.empty() || that.selectionNeighborhood.has(node)) { ctx.globalAlpha = 1; } else { ctx.globalAlpha = 0.25; } // draw the node that._drawNode(ctx, node); // drawing the node label in case we are not zoomed out if (cy.zoom() > 1) { that._drawNodeLabel(ctx, node); } } } _drawNode(ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular) { const cy = this.cytoscape; const type = node.data('type'); const metrics: IntGraphMetrics = node.data('metrics'); if (type === EnGraphNodeType.INTERNAL) { const requestCount = _.defaultTo(metrics.rate, -1); const errorCount = _.defaultTo(metrics.error_rate, 0); const responseTime = _.defaultTo(metrics.response_time, -1); const threshold = _.defaultTo(metrics.threshold, -1); var unknownPct; var errorPct; var healthyPct; if (requestCount < 0) { healthyPct = 0; errorPct = 0; unknownPct = 1; } else { if (errorCount <= 0) { errorPct = 0.0; } else { errorPct = (1.0 / requestCount) * errorCount; } healthyPct = 1.0 - errorPct; unknownPct = 0; } // drawing the donut this._drawDonut(ctx, node, 15, 5, 0.5, [errorPct, unknownPct, healthyPct]); // drawing the baseline status const { showBaselines } = this.controller.getSettings(true); if (showBaselines && responseTime >= 0 && threshold >= 0) { const thresholdViolation = threshold < responseTime; this._drawThresholdStroke(ctx, node, thresholdViolation, 15, 5, 0.5); } this._drawServiceIcon(ctx, node); } else { this._drawExternalService(ctx, node); } // draw statistics if (cy.zoom() > 1) { this._drawNodeStatistics(ctx, node); } } _drawServiceIcon(ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular) { const nodeId: string = node.id(); const iconMappings = this.controller.getSettings(true).icons; const mapping = _.find(iconMappings, ({ pattern }) => { try { return new RegExp(pattern).test(nodeId); } catch (error) { return false; } }); if (mapping) { const image = this._getAsset(mapping.filename, mapping.filename + '.png'); if (image != null) { const cX = node.position().x; const cY = node.position().y; const iconSize = 16; ctx.drawImage(image, cX - iconSize / 2, cY - iconSize / 2, iconSize, iconSize); } } } _drawNodeStatistics(ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular) { const { timeFormat } = this.controller.getSettings(true); const lines: string[] = []; const metrics: IntGraphMetrics = node.data('metrics'); const requestCount = _.defaultTo(metrics.rate, -1); const errorCount = _.defaultTo(metrics.error_rate, -1); const responseTime = _.defaultTo(metrics.response_time, -1); const timeScale = new humanFormat.Scale(this._getTimeScale(timeFormat)); if (requestCount >= 0) { const decimals = requestCount >= 1000 ? 1 : 0; lines.push('Requests: ' + humanFormat(parseFloat(requestCount.toString()), { decimals })); } if (errorCount >= 0) { const decimals = errorCount >= 1000 ? 1 : 0; lines.push('Errors: ' + humanFormat(errorCount, { decimals })); } if (responseTime >= 0) { const decimals = responseTime >= 1000 ? 1 : 0; lines.push('Avg. Resp. Time: ' + humanFormat(responseTime, { scale: timeScale, decimals })); } const pos = node.position(); const fontSize = 6; const cX = pos.x + this.donutRadius * 1.25; const cY = pos.y + fontSize / 2 - (fontSize / 2) * (lines.length - 1); ctx.font = '6px Arial'; ctx.fillStyle = this.colors.default; for (let i = 0; i < lines.length; i++) { ctx.fillText(lines[i], cX, cY + i * fontSize); } } _drawThresholdStroke( ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular, violation: boolean, radius: number, width: number, baseStrokeWidth: number ) { const pos = node.position(); const cX = pos.x; const cY = pos.y; const strokeWidth = baseStrokeWidth * 2 * (violation ? 1.5 : 1); const offset = strokeWidth * 0.2; ctx.beginPath(); ctx.arc(cX, cY, radius + strokeWidth - offset, 0, 2 * Math.PI, false); ctx.closePath(); ctx.setLineDash([]); ctx.lineWidth = strokeWidth * 1; ctx.strokeStyle = 'white'; ctx.stroke(); ctx.beginPath(); ctx.arc(cX, cY, radius + strokeWidth - offset, 0, 2 * Math.PI, false); ctx.closePath(); ctx.setLineDash([10, 2]); if (violation && this.controller.getSettings(true).animate) { ctx.lineDashOffset = this.dashAnimationOffset; } else { ctx.lineDashOffset = 0; } ctx.lineWidth = strokeWidth; ctx.strokeStyle = violation ? 'rgb(184, 36, 36)' : '#37872d'; ctx.stroke(); // inner ctx.beginPath(); ctx.arc(cX, cY, radius - width - baseStrokeWidth, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fillStyle = violation ? 'rgb(184, 36, 36)' : '#37872d'; ctx.fill(); } _drawExternalService(ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular) { const pos = node.position(); const cX = pos.x; const cY = pos.y; const size = 12; ctx.beginPath(); ctx.arc(cX, cY, 12, 0, 2 * Math.PI, false); ctx.fillStyle = 'white'; ctx.fill(); ctx.beginPath(); ctx.arc(cX, cY, 11.5, 0, 2 * Math.PI, false); ctx.fillStyle = this.colors.background; ctx.fill(); const nodeType = node.data('external_type'); const image = this._getImageAsset(nodeType); if (image != null) { ctx.drawImage(image, cX - size / 2, cY - size / 2, size, size); } } _drawNodeLabel(ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular) { const pos = node.position(); let label: string = node.id(); const labelPadding = 1; if (this.selectionNeighborhood.empty() || !this.selectionNeighborhood.has(node)) { if (label.length > 20) { label = label.substr(0, 7) + '...' + label.slice(-7); } } ctx.font = '6px Arial'; const labelWidth = ctx.measureText(label).width; const xPos = pos.x - labelWidth / 2; const yPos = pos.y + node.height() * 0.8; const { showBaselines } = this.controller.getSettings(true); const metrics: IntGraphMetrics = node.data('metrics'); const responseTime = _.defaultTo(metrics.response_time, -1); const threshold = _.defaultTo(metrics.threshold, -1); if (!showBaselines || threshold < 0 || responseTime < 0 || responseTime <= threshold) { ctx.fillStyle = this.colors.default; } else { ctx.fillStyle = '#FF7383'; } ctx.fillRect(xPos - labelPadding, yPos - 6 - labelPadding, labelWidth + 2 * labelPadding, 6 + 2 * labelPadding); ctx.fillStyle = this.colors.background; ctx.fillText(label, xPos, yPos); } _drawDebugInformation() { const ctx = this.context; this.frameCounter++; ctx.font = '12px monospace'; ctx.fillStyle = 'white'; ctx.fillText('Frames per Second: ' + this.fpsCounter, 10, 12); ctx.fillText('Particles: ' + this.particleEngine.count(), 10, 24); } _drawDonut( ctx: CanvasRenderingContext2D, node: cytoscape.NodeSingular, radius: number, width: number, strokeWidth: number, percentages: number[] ) { const cX = node.position().x; const cY = node.position().y; let currentArc = -Math.PI / 2; // offset ctx.beginPath(); ctx.arc(cX, cY, radius + strokeWidth, 0, 2 * Math.PI, false); ctx.closePath(); ctx.fillStyle = 'white'; ctx.fill(); const { healthyColor, dangerColor, noDataColor } = this.controller.getSettings(true).style; const colors = [dangerColor, noDataColor, healthyColor]; for (let i = 0; i < percentages.length; i++) { let arc = this._drawArc(ctx, currentArc, cX, cY, radius, percentages[i], colors[i]); currentArc += arc; } ctx.beginPath(); ctx.arc(cX, cY, radius - width, 0, 2 * Math.PI, false); ctx.fillStyle = 'white'; ctx.fill(); // cut out an inner-circle == donut ctx.beginPath(); ctx.arc(cX, cY, radius - width - strokeWidth, 0, 2 * Math.PI, false); if (node.selected()) { ctx.fillStyle = 'white'; } else { ctx.fillStyle = this.colors.background; } ctx.fill(); } _drawArc( ctx: CanvasRenderingContext2D, currentArc: number, cX: number, cY: number, radius: number, percent: number, color: string ) { // calc size of our wedge in radians var WedgeInRadians = (percent * 360 * Math.PI) / 180; // draw the wedge ctx.save(); ctx.beginPath(); ctx.moveTo(cX, cY); ctx.arc(cX, cY, radius, currentArc, currentArc + WedgeInRadians, false); ctx.closePath(); ctx.fillStyle = color; ctx.fill(); ctx.restore(); // sum the size of all wedges so far // We will begin our next wedge at this sum return WedgeInRadians; } }
the_stack
import * as byteUtils from "../byte_parsing"; describe("utils - byte parsing", () => { describe("concat", () => { it("should return an empty Uint8Array if no arguments are provided", () => { const res = byteUtils.concat(); expect(res).toBeInstanceOf(Uint8Array); expect(res).toHaveLength(0); }); it("should concatenate multiple Uint8Array in a single Uint8Array", () => { const arr1 = new Uint8Array([54, 255]); const arr2 = new Uint8Array([258, 54]); const arr3 = new Uint8Array([]); const arr4 = new Uint8Array([34, 87]); const expected = new Uint8Array([54, 255, 258, 54, 34, 87]); const res = byteUtils.concat(arr1, arr2, arr3, arr4); expect(res).toHaveLength(arr1.length + arr2.length + arr3.length + arr4.length); res.forEach((x, i) => expect(x).toBe(expected[i])); }); it("should consider number arguments as 0-filled offests", () => { const arr1 = new Uint8Array([54, 255]); const arr2 = new Uint8Array([258, 54]); const arr3 = new Uint8Array([34, 87]); const expected = new Uint8Array( [54, 255, 0, 0, 258, 54, 34, 87, 0].map(e => e & 0xFF) ); const res = byteUtils.concat(0, arr1, 2, arr2, arr3, 1); expect(res).toHaveLength( arr1.length + arr2.length + arr3.length + 0 + 2 + 1 ); res.forEach((x, i) => expect(x).toBe(expected[i])); }); it("should return only 0-filled arrays if only numbers are provided", () => { const res = byteUtils.concat(0); expect(res).toHaveLength(0); const res2 = byteUtils.concat(10, 2); expect(res2).toHaveLength(10 + 2); res2.forEach(x => expect(x).toBe(0)); }); }); describe("be2toi", () => { it("should return 0 for an empty TypedArray", () => { expect(byteUtils.be2toi(new Uint8Array(0), 0)).toBe(0); }); it("should return 0 for an out-of-bound offset", () => { const arr = new Uint8Array([255, 255, 1, 8]); expect(byteUtils.be2toi(arr, -45)).toBe(0); expect(byteUtils.be2toi(arr, 45)).toBe(0); }); /* eslint-disable max-len */ it("should return the number value for the 2 first elements of an Uint8Array from the offset", () => { /* eslint-enable max-len */ // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([255, 255, 1, 8]); const expected = [65535, 65281, 264, 2048]; expect(byteUtils.be2toi(arr, 0)).toBe(expected[0]); expect(byteUtils.be2toi(arr, 1)).toBe(expected[1]); expect(byteUtils.be2toi(arr, 2)).toBe(expected[2]); expect(byteUtils.be2toi(arr, 3)).toBe(expected[3]); }); }); describe("be3toi", () => { /* eslint-disable max-len */ it("should return the number value for the 2 first elements of an Uint8Array from the offset", () => { /* eslint-enable max-len */ // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([255, 255, 255, 1, 8, 17]); const expected = [16777215, 16776961, 16711944, 67601]; expect(byteUtils.be3toi(arr, 0)).toBe(expected[0]); expect(byteUtils.be3toi(arr, 1)).toBe(expected[1]); expect(byteUtils.be3toi(arr, 2)).toBe(expected[2]); expect(byteUtils.be3toi(arr, 3)).toBe(expected[3]); }); }); describe("be4toi", () => { /* eslint-disable max-len */ it("should return the number value for the 4 first elements of an Uint8Array from the offset", () => { /* eslint-enable max-len */ // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([ 0, 0, 0, 1, 255, 3, 2 ]); const expected = [ 1, 511, 130819, 33489666 ]; expect(byteUtils.be4toi(arr, 0)).toBe(expected[0]); expect(byteUtils.be4toi(arr, 1)).toBe(expected[1]); expect(byteUtils.be4toi(arr, 2)).toBe(expected[2]); expect(byteUtils.be4toi(arr, 3)).toBe(expected[3]); }); }); describe("be8toi", () => { /* eslint-disable max-len */ it("should return the number value for the 8 first elements of an Uint8Array from the offset", () => { /* eslint-enable max-len */ // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 255, 0, 255, 0, 255, 0 ]); // I can't set the top-most byte or I // go over MAX_SAFE_INTEGER const expected = [ 1, 280379743338240 ]; expect(byteUtils.be8toi(arr, 0)).toBe(expected[0]); expect(byteUtils.be8toi(arr, 8)).toBe(expected[1]); }); }); describe("le2toi", () => { it("should return 0 for an empty TypedArray", () => { expect(byteUtils.le2toi(new Uint8Array(0), 0)).toBe(0); }); it("should return 0 for an out-of-bound offset", () => { const arr = new Uint8Array([255, 255, 1, 8]); expect(byteUtils.le2toi(arr, -45)).toBe(0); expect(byteUtils.le2toi(arr, 45)).toBe(0); }); it( /* eslint-disable max-len */ "should return the number value for the 2 first elements of an Uint8Array from the offset, little-endian style", /* eslint-enable max-len */ () => { // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([8, 1, 255, 255]); const expected = [264, 65281, 65535, 255]; expect(byteUtils.le2toi(arr, 0)).toBe(expected[0]); expect(byteUtils.le2toi(arr, 1)).toBe(expected[1]); expect(byteUtils.le2toi(arr, 2)).toBe(expected[2]); expect(byteUtils.le2toi(arr, 3)).toBe(expected[3]); }); }); describe("le4toi", () => { it( /* eslint-disable max-len */ "should return the number value for the 4 first elements of an Uint8Array from the offset, little-endian style", /* eslint-enable max-len */ () => { // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([2, 3, 255, 1, 0, 0, 0]); const expected = [ 33489666, 130819, 511, 1 ]; expect(byteUtils.le4toi(arr, 0)).toBe(expected[0]); expect(byteUtils.le4toi(arr, 1)).toBe(expected[1]); expect(byteUtils.le4toi(arr, 2)).toBe(expected[2]); expect(byteUtils.le4toi(arr, 3)).toBe(expected[3]); }); }); describe("le8toi", () => { it( /* eslint-disable max-len */ "should return the number value for the 8 first elements of an Uint8Array from the offset, little-endian style", /* eslint-enable max-len */ () => { // as the test would be equivalent to re-implement the function, I // directly take the expected result (number to hex and hex to // number) and compare const arr = new Uint8Array([ 1, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 255, 0, 255, 0, 0 ]); // I can't set the top-most byte or I // go over MAX_SAFE_INTEGER const expected = [ 1, 280379743338240 ]; expect(byteUtils.le8toi(arr, 0)).toBe(expected[0]); expect(byteUtils.le8toi(arr, 8)).toBe(expected[1]); }); }); describe("itobe2", () => { /* eslint-disable max-len */ it("should convert the number given into two elements in a Uint8Array", () => { /* eslint-enable max-len */ expect(byteUtils.itobe2(65535)) .toEqual(new Uint8Array([255, 255])); expect(byteUtils.itobe2(65281)) .toEqual(new Uint8Array([255, 1])); expect(byteUtils.itobe2(264)) .toEqual(new Uint8Array([1, 8])); }); }); describe("itobe4", () => { /* eslint-disable max-len */ it("should convert the number given into four elements in a Uint8Array", () => { /* eslint-enable max-len */ expect(byteUtils.itobe4(1)) .toEqual(new Uint8Array([0, 0, 0, 1])); expect(byteUtils.itobe4(511)) .toEqual(new Uint8Array([0, 0, 1, 255])); expect(byteUtils.itobe4(130819)) .toEqual(new Uint8Array([0, 1, 255, 3])); expect(byteUtils.itobe4(33489666)) .toEqual(new Uint8Array([1, 255, 3, 2])); }); }); describe("itobe8", () => { /* eslint-disable max-len */ it("should return the number value for the 8 first elements of an Uint8Array from the offset", () => { /* eslint-enable max-len */ expect(byteUtils.itobe8(1)) .toEqual(new Uint8Array([0, 0, 0, 0, 0, 0, 0, 1])); expect(byteUtils.itobe8(1237106686452549)) .toEqual(new Uint8Array([0x00, 0x04, 0x65, 0x24, 0x58, 0x98, 0x63, 0x45])); }); }); describe("itole2", () => { /* eslint-disable max-len */ it("should return a little-endian style Uint8Array of length 2 translated from the number given", () => { /* eslint-enable max-len */ const values = [264, 65281, 65535, 255]; expect(byteUtils.itole2(values[0])).toEqual(new Uint8Array([8, 1])); expect(byteUtils.itole2(values[1])).toEqual(new Uint8Array([1, 255])); expect(byteUtils.itole2(values[2])).toEqual(new Uint8Array([255, 255])); }); }); describe("itole4", () => { /* eslint-disable max-len */ it("should return a little-endian style Uint8Array of length 4 translated from the number given", () => { /* eslint-enable max-len */ const values = [ 33489666, 130819, 511, 1 ]; expect(byteUtils.itole4(values[0])) .toEqual(new Uint8Array([2, 3, 255, 1])); expect(byteUtils.itole4(values[1])) .toEqual(new Uint8Array([3, 255, 1, 0])); expect(byteUtils.itole4(values[2])) .toEqual(new Uint8Array([255, 1, 0, 0])); expect(byteUtils.itole4(values[3])) .toEqual(new Uint8Array([1, 0, 0, 0])); }); }); });
the_stack
import axios, { AxiosResponse, CancelTokenSource, AxiosRequestConfig } from 'axios' import objectAssignDeep from 'object-assign-deep' import MegalodonEntity from '../entity' import PleromaEntity from './entity' import Response from '../response' import { RequestCanceledError } from '../cancel' import proxyAgent, { ProxyConfig } from '../proxy_config' import { NO_REDIRECT, DEFAULT_SCOPE, DEFAULT_UA } from '../default' import WebSocket from './web_socket' import NotificationType from '../notification' import PleromaNotificationType from './notification' namespace PleromaAPI { export namespace Entity { export type Account = PleromaEntity.Account export type Activity = PleromaEntity.Activity export type Application = PleromaEntity.Application export type Attachment = PleromaEntity.Attachment export type Card = PleromaEntity.Card export type Context = PleromaEntity.Context export type Conversation = PleromaEntity.Conversation export type Emoji = PleromaEntity.Emoji export type FeaturedTag = PleromaEntity.FeaturedTag export type Field = PleromaEntity.Field export type Filter = PleromaEntity.Filter export type History = PleromaEntity.History export type IdentityProof = PleromaEntity.IdentityProof export type Instance = PleromaEntity.Instance export type List = PleromaEntity.List export type Marker = PleromaEntity.Marker export type Mention = PleromaEntity.Mention export type Notification = PleromaEntity.Notification export type Poll = PleromaEntity.Poll export type PollOption = PleromaEntity.PollOption export type Preferences = PleromaEntity.Preferences export type PushSubscription = PleromaEntity.PushSubscription export type Reaction = PleromaEntity.Reaction export type Relationship = PleromaEntity.Relationship export type Report = PleromaEntity.Report export type Results = PleromaEntity.Results export type ScheduledStatus = PleromaEntity.ScheduledStatus export type Source = PleromaEntity.Source export type Stats = PleromaEntity.Stats export type Status = PleromaEntity.Status export type StatusParams = PleromaEntity.StatusParams export type Tag = PleromaEntity.Tag export type Token = PleromaEntity.Token export type URLs = PleromaEntity.URLs } export namespace Converter { export const decodeNotificationType = (t: PleromaEntity.NotificationType): MegalodonEntity.NotificationType => { switch (t) { case PleromaNotificationType.Mention: return NotificationType.Mention case PleromaNotificationType.Reblog: return NotificationType.Reblog case PleromaNotificationType.Favourite: return NotificationType.Favourite case PleromaNotificationType.Follow: return NotificationType.Follow case PleromaNotificationType.Poll: return NotificationType.PollExpired case PleromaNotificationType.PleromaEmojiReaction: return NotificationType.EmojiReaction case PleromaNotificationType.FollowRequest: return NotificationType.FollowRequest default: return t } } export const encodeNotificationType = (t: MegalodonEntity.NotificationType): PleromaEntity.NotificationType => { switch (t) { case NotificationType.Follow: return PleromaNotificationType.Follow case NotificationType.Favourite: return PleromaNotificationType.Favourite case NotificationType.Reblog: return PleromaNotificationType.Reblog case NotificationType.Mention: return PleromaNotificationType.Mention case NotificationType.PollExpired: return PleromaNotificationType.Poll case NotificationType.EmojiReaction: return PleromaNotificationType.PleromaEmojiReaction case NotificationType.FollowRequest: return PleromaNotificationType.FollowRequest default: return t } } export const account = (a: Entity.Account): MegalodonEntity.Account => a export const activity = (a: Entity.Activity): MegalodonEntity.Activity => a export const application = (a: Entity.Application): MegalodonEntity.Application => a export const attachment = (a: Entity.Attachment): MegalodonEntity.Attachment => a export const card = (c: Entity.Card): MegalodonEntity.Card => c export const context = (c: Entity.Context): MegalodonEntity.Context => ({ ancestors: c.ancestors.map(a => status(a)), descendants: c.descendants.map(d => status(d)) }) export const conversation = (c: Entity.Conversation): MegalodonEntity.Conversation => ({ id: c.id, accounts: c.accounts.map(a => account(a)), last_status: c.last_status ? status(c.last_status) : null, unread: c.unread }) export const emoji = (e: Entity.Emoji): MegalodonEntity.Emoji => e export const featured_tag = (f: Entity.FeaturedTag): MegalodonEntity.FeaturedTag => f export const field = (f: Entity.Field): MegalodonEntity.Field => f export const filter = (f: Entity.Filter): MegalodonEntity.Filter => f export const history = (h: Entity.History): MegalodonEntity.History => h export const identity_proof = (i: Entity.IdentityProof): MegalodonEntity.IdentityProof => i export const instance = (i: Entity.Instance): MegalodonEntity.Instance => i export const list = (l: Entity.List): MegalodonEntity.List => l export const marker = (m: Entity.Marker): MegalodonEntity.Marker => m export const mention = (m: Entity.Mention): MegalodonEntity.Mention => m export const notification = (n: Entity.Notification): MegalodonEntity.Notification => { if (n.status && n.emoji) { return { id: n.id, account: n.account, created_at: n.created_at, status: status(n.status), emoji: n.emoji, type: decodeNotificationType(n.type) } } else if (n.status) { return { id: n.id, account: n.account, created_at: n.created_at, status: status(n.status), type: decodeNotificationType(n.type) } } else { return { id: n.id, account: n.account, created_at: n.created_at, type: decodeNotificationType(n.type) } } } export const poll = (p: Entity.Poll): MegalodonEntity.Poll => p export const pollOption = (p: Entity.PollOption): MegalodonEntity.PollOption => p export const preferences = (p: Entity.Preferences): MegalodonEntity.Preferences => p export const push_subscription = (p: Entity.PushSubscription): MegalodonEntity.PushSubscription => p export const reaction = (r: Entity.Reaction): MegalodonEntity.Reaction => r export const relationship = (r: Entity.Relationship): MegalodonEntity.Relationship => ({ id: r.id, following: r.following, followed_by: r.followed_by, blocking: r.blocking, blocked_by: r.blocked_by, muting: r.muting, muting_notifications: r.muting_notifications, requested: r.requested, domain_blocking: r.domain_blocking, showing_reblogs: r.showing_reblogs, endorsed: r.endorsed, notifying: r.subscribing }) export const report = (r: Entity.Report): MegalodonEntity.Report => r export const results = (r: Entity.Results): MegalodonEntity.Results => ({ accounts: r.accounts.map(a => account(a)), statuses: r.statuses.map(s => status(s)), hashtags: r.hashtags.map(h => tag(h)) }) export const scheduled_status = (s: Entity.ScheduledStatus): MegalodonEntity.ScheduledStatus => ({ id: s.id, scheduled_at: s.scheduled_at, params: s.params, media_attachments: s.media_attachments.map(m => attachment(m)) }) export const source = (s: Entity.Source): MegalodonEntity.Source => s export const stats = (s: Entity.Stats): MegalodonEntity.Stats => s export const status = (s: Entity.Status): MegalodonEntity.Status => ({ id: s.id, uri: s.uri, url: s.url, account: account(s.account), in_reply_to_id: s.in_reply_to_id, in_reply_to_account_id: s.in_reply_to_account_id, reblog: s.reblog ? status(s.reblog) : null, content: s.content, plain_content: s.pleroma.context?.['text/plain'] ? s.pleroma.context['text/plain'] : null, created_at: s.created_at, emojis: s.emojis.map(e => emoji(e)), replies_count: s.replies_count, reblogs_count: s.reblogs_count, favourites_count: s.favourites_count, reblogged: s.reblogged, favourited: s.favourited, muted: s.muted, sensitive: s.sensitive, spoiler_text: s.spoiler_text, visibility: s.visibility, media_attachments: s.media_attachments.map(m => attachment(m)), mentions: s.mentions.map(m => mention(m)), tags: s.tags.map(t => tag(t)), card: s.card ? card(s.card) : null, poll: s.poll ? poll(s.poll) : null, application: s.application ? application(s.application) : null, language: s.language, pinned: s.pinned, emoji_reactions: s.pleroma.emoji_reactions ? s.pleroma.emoji_reactions.map(r => reaction(r)) : [], bookmarked: s.bookmarked, quote: s.reblog !== null && s.reblog.content !== s.content }) export const status_params = (s: Entity.StatusParams): MegalodonEntity.StatusParams => s export const tag = (t: Entity.Tag): MegalodonEntity.Tag => t export const token = (t: Entity.Token): MegalodonEntity.Token => t export const urls = (u: Entity.URLs): MegalodonEntity.URLs => u } /** * Interface */ export interface Interface { get<T = any>(path: string, params?: any, headers?: { [key: string]: string }): Promise<Response<T>> put<T = any>(path: string, params?: any, headers?: { [key: string]: string }): Promise<Response<T>> patch<T = any>(path: string, params?: any, headers?: { [key: string]: string }): Promise<Response<T>> post<T = any>(path: string, params?: any, headers?: { [key: string]: string }): Promise<Response<T>> del<T = any>(path: string, params?: any, headers?: { [key: string]: string }): Promise<Response<T>> cancel(): void socket(path: string, stream: string, params?: string): WebSocket } /** * Mastodon API client. * * Using axios for request, you will handle promises. */ export class Client implements Interface { static DEFAULT_SCOPE = DEFAULT_SCOPE static DEFAULT_URL = 'https://pleroma.io' static NO_REDIRECT = NO_REDIRECT private accessToken: string | null private baseUrl: string private userAgent: string private cancelTokenSource: CancelTokenSource private proxyConfig: ProxyConfig | false = false /** * @param baseUrl hostname or base URL * @param accessToken access token from OAuth2 authorization * @param userAgent UserAgent is specified in header on request. * @param proxyConfig Proxy setting, or set false if don't use proxy. */ constructor( baseUrl: string, accessToken: string | null = null, userAgent: string = DEFAULT_UA, proxyConfig: ProxyConfig | false = false ) { this.accessToken = accessToken this.baseUrl = baseUrl this.userAgent = userAgent this.cancelTokenSource = axios.CancelToken.source() this.proxyConfig = proxyConfig // https://github.com/axios/axios/issues/978 this.cancelTokenSource.token.throwIfRequested = this.cancelTokenSource.token.throwIfRequested this.cancelTokenSource.token.promise.then = this.cancelTokenSource.token.promise.then.bind(this.cancelTokenSource.token.promise) this.cancelTokenSource.token.promise.catch = this.cancelTokenSource.token.promise.catch.bind(this.cancelTokenSource.token.promise) } /** * GET request to mastodon REST API. * @param path relative path from baseUrl * @param params Query parameters * @param headers Request header object */ public async get<T>(path: string, params = {}, headers: { [key: string]: string } = {}): Promise<Response<T>> { let options: AxiosRequestConfig = { cancelToken: this.cancelTokenSource.token, params: params, headers: headers } if (this.accessToken) { options = objectAssignDeep({}, options, { headers: { Authorization: `Bearer ${this.accessToken}` } }) } if (this.proxyConfig) { options = Object.assign(options, { httpAgent: proxyAgent(this.proxyConfig), httpsAgent: proxyAgent(this.proxyConfig) }) } return axios .get<T>(this.baseUrl + path, options) .catch((err: Error) => { if (axios.isCancel(err)) { throw new RequestCanceledError(err.message) } else { throw err } }) .then((resp: AxiosResponse<T>) => { const res: Response<T> = { data: resp.data, status: resp.status, statusText: resp.statusText, headers: resp.headers } return res }) } /** * PUT request to mastodon REST API. * @param path relative path from baseUrl * @param params Form data. If you want to post file, please use FormData() * @param headers Request header object */ public async put<T>(path: string, params = {}, headers: { [key: string]: string } = {}): Promise<Response<T>> { let options: AxiosRequestConfig = { cancelToken: this.cancelTokenSource.token, headers: headers } if (this.accessToken) { options = objectAssignDeep({}, options, { headers: { Authorization: `Bearer ${this.accessToken}` } }) } if (this.proxyConfig) { options = Object.assign(options, { httpAgent: proxyAgent(this.proxyConfig), httpsAgent: proxyAgent(this.proxyConfig) }) } return axios .put<T>(this.baseUrl + path, params, options) .catch((err: Error) => { if (axios.isCancel(err)) { throw new RequestCanceledError(err.message) } else { throw err } }) .then((resp: AxiosResponse<T>) => { const res: Response<T> = { data: resp.data, status: resp.status, statusText: resp.statusText, headers: resp.headers } return res }) } /** * PATCH request to mastodon REST API. * @param path relative path from baseUrl * @param params Form data. If you want to post file, please use FormData() * @param headers Request header object */ public async patch<T>(path: string, params = {}, headers: { [key: string]: string } = {}): Promise<Response<T>> { let options: AxiosRequestConfig = { cancelToken: this.cancelTokenSource.token, headers: headers } if (this.accessToken) { options = objectAssignDeep({}, options, { headers: { Authorization: `Bearer ${this.accessToken}` } }) } if (this.proxyConfig) { options = Object.assign(options, { httpAgent: proxyAgent(this.proxyConfig), httpsAgent: proxyAgent(this.proxyConfig) }) } return axios .patch<T>(this.baseUrl + path, params, options) .catch((err: Error) => { if (axios.isCancel(err)) { throw new RequestCanceledError(err.message) } else { throw err } }) .then((resp: AxiosResponse<T>) => { const res: Response<T> = { data: resp.data, status: resp.status, statusText: resp.statusText, headers: resp.headers } return res }) } /** * POST request to mastodon REST API. * @param path relative path from baseUrl * @param params Form data * @param headers Request header object */ public async post<T>(path: string, params = {}, headers: { [key: string]: string } = {}): Promise<Response<T>> { let options: AxiosRequestConfig = { cancelToken: this.cancelTokenSource.token, headers: headers } if (this.accessToken) { options = objectAssignDeep({}, options, { headers: { Authorization: `Bearer ${this.accessToken}` } }) } if (this.proxyConfig) { options = Object.assign(options, { httpAgent: proxyAgent(this.proxyConfig), httpsAgent: proxyAgent(this.proxyConfig) }) } return axios.post<T>(this.baseUrl + path, params, options).then((resp: AxiosResponse<T>) => { const res: Response<T> = { data: resp.data, status: resp.status, statusText: resp.statusText, headers: resp.headers } return res }) } /** * DELETE request to mastodon REST API. * @param path relative path from baseUrl * @param params Form data * @param headers Request header object */ public async del<T>(path: string, params = {}, headers: { [key: string]: string } = {}): Promise<Response<T>> { let options: AxiosRequestConfig = { cancelToken: this.cancelTokenSource.token, data: params, headers: headers } if (this.accessToken) { options = objectAssignDeep({}, options, { headers: { Authorization: `Bearer ${this.accessToken}` } }) } if (this.proxyConfig) { options = Object.assign(options, { httpAgent: proxyAgent(this.proxyConfig), httpsAgent: proxyAgent(this.proxyConfig) }) } return axios .delete(this.baseUrl + path, options) .catch((err: Error) => { if (axios.isCancel(err)) { throw new RequestCanceledError(err.message) } else { throw err } }) .then((resp: AxiosResponse) => { const res: Response<T> = { data: resp.data, status: resp.status, statusText: resp.statusText, headers: resp.headers } return res }) } /** * Cancel all requests in this instance. * @returns void */ public cancel(): void { return this.cancelTokenSource.cancel('Request is canceled by user') } /** * Get connection and receive websocket connection for Pleroma API. * * @param path relative path from baseUrl: normally it is `/streaming`. * @param stream Stream name, please refer: https://git.pleroma.social/pleroma/pleroma/blob/develop/lib/pleroma/web/mastodon_api/mastodon_socket.ex#L19-28 * @returns WebSocket, which inherits from EventEmitter */ public socket(path: string, stream: string, params?: string): WebSocket { if (!this.accessToken) { throw new Error('accessToken is required') } const url = this.baseUrl + path const streaming = new WebSocket(url, stream, params, this.accessToken, this.userAgent, this.proxyConfig) process.nextTick(() => { streaming.start() }) return streaming } } } export default PleromaAPI
the_stack
import ts from 'typescript'; import {ErrorCode, ngErrorCode} from '../../diagnostics'; import {findFlatIndexEntryPoint, FlatIndexGenerator} from '../../entry_point'; import {AbsoluteFsPath, resolve} from '../../file_system'; import {FactoryGenerator, isShim, ShimAdapter, ShimReferenceTagger, SummaryGenerator} from '../../shims'; import {FactoryTracker, PerFileShimGenerator, TopLevelShimGenerator} from '../../shims/api'; import {TypeCheckShimGenerator} from '../../typecheck'; import {normalizeSeparators} from '../../util/src/path'; import {getRootDirs, isNonDeclarationTsPath, RequiredDelegations} from '../../util/src/typescript'; import {ExtendedTsCompilerHost, NgCompilerAdapter, NgCompilerOptions, UnifiedModulesHost} from '../api'; // A persistent source of bugs in CompilerHost delegation has been the addition by TS of new, // optional methods on ts.CompilerHost. Since these methods are optional, it's not a type error that // the delegating host doesn't implement or delegate them. This causes subtle runtime failures. No // more. This infrastructure ensures that failing to delegate a method is a compile-time error. /** * Delegates all methods of `ExtendedTsCompilerHost` to a delegate, with the exception of * `getSourceFile` and `fileExists` which are implemented in `NgCompilerHost`. * * If a new method is added to `ts.CompilerHost` which is not delegated, a type error will be * generated for this class. */ export class DelegatingCompilerHost implements Omit<RequiredDelegations<ExtendedTsCompilerHost>, 'getSourceFile'|'fileExists'> { constructor(protected delegate: ExtendedTsCompilerHost) {} private delegateMethod<M extends keyof ExtendedTsCompilerHost>(name: M): ExtendedTsCompilerHost[M] { return this.delegate[name] !== undefined ? (this.delegate[name] as any).bind(this.delegate) : undefined; } // Excluded are 'getSourceFile' and 'fileExists', which are actually implemented by NgCompilerHost // below. createHash = this.delegateMethod('createHash'); directoryExists = this.delegateMethod('directoryExists'); fileNameToModuleName = this.delegateMethod('fileNameToModuleName'); getCancellationToken = this.delegateMethod('getCancellationToken'); getCanonicalFileName = this.delegateMethod('getCanonicalFileName'); getCurrentDirectory = this.delegateMethod('getCurrentDirectory'); getDefaultLibFileName = this.delegateMethod('getDefaultLibFileName'); getDefaultLibLocation = this.delegateMethod('getDefaultLibLocation'); getDirectories = this.delegateMethod('getDirectories'); getEnvironmentVariable = this.delegateMethod('getEnvironmentVariable'); getModifiedResourceFiles = this.delegateMethod('getModifiedResourceFiles'); getNewLine = this.delegateMethod('getNewLine'); getParsedCommandLine = this.delegateMethod('getParsedCommandLine'); getSourceFileByPath = this.delegateMethod('getSourceFileByPath'); readDirectory = this.delegateMethod('readDirectory'); readFile = this.delegateMethod('readFile'); readResource = this.delegateMethod('readResource'); transformResource = this.delegateMethod('transformResource'); realpath = this.delegateMethod('realpath'); resolveModuleNames = this.delegateMethod('resolveModuleNames'); resolveTypeReferenceDirectives = this.delegateMethod('resolveTypeReferenceDirectives'); resourceNameToFileName = this.delegateMethod('resourceNameToFileName'); trace = this.delegateMethod('trace'); useCaseSensitiveFileNames = this.delegateMethod('useCaseSensitiveFileNames'); writeFile = this.delegateMethod('writeFile'); getModuleResolutionCache = this.delegateMethod('getModuleResolutionCache'); } /** * A wrapper around `ts.CompilerHost` (plus any extension methods from `ExtendedTsCompilerHost`). * * In order for a consumer to include Angular compilation in their TypeScript compiler, the * `ts.Program` must be created with a host that adds Angular-specific files (e.g. factories, * summaries, the template type-checking file, etc) to the compilation. `NgCompilerHost` is the * host implementation which supports this. * * The interface implementations here ensure that `NgCompilerHost` fully delegates to * `ExtendedTsCompilerHost` methods whenever present. */ export class NgCompilerHost extends DelegatingCompilerHost implements RequiredDelegations<ExtendedTsCompilerHost>, ExtendedTsCompilerHost, NgCompilerAdapter { readonly factoryTracker: FactoryTracker|null = null; readonly entryPoint: AbsoluteFsPath|null = null; readonly constructionDiagnostics: ts.Diagnostic[]; readonly inputFiles: ReadonlyArray<string>; readonly rootDirs: ReadonlyArray<AbsoluteFsPath>; constructor( delegate: ExtendedTsCompilerHost, inputFiles: ReadonlyArray<string>, rootDirs: ReadonlyArray<AbsoluteFsPath>, private shimAdapter: ShimAdapter, private shimTagger: ShimReferenceTagger, entryPoint: AbsoluteFsPath|null, factoryTracker: FactoryTracker|null, diagnostics: ts.Diagnostic[]) { super(delegate); this.factoryTracker = factoryTracker; this.entryPoint = entryPoint; this.constructionDiagnostics = diagnostics; this.inputFiles = [...inputFiles, ...shimAdapter.extraInputFiles]; this.rootDirs = rootDirs; if (this.resolveModuleNames === undefined) { // In order to reuse the module resolution cache during the creation of the type-check // program, we'll need to provide `resolveModuleNames` if the delegate did not provide one. this.resolveModuleNames = this.createCachedResolveModuleNamesFunction(); } } /** * Retrieves a set of `ts.SourceFile`s which should not be emitted as JS files. * * Available after this host is used to create a `ts.Program` (which causes all the files in the * program to be enumerated). */ get ignoreForEmit(): Set<ts.SourceFile> { return this.shimAdapter.ignoreForEmit; } /** * Retrieve the array of shim extension prefixes for which shims were created for each original * file. */ get shimExtensionPrefixes(): string[] { return this.shimAdapter.extensionPrefixes; } /** * Performs cleanup that needs to happen after a `ts.Program` has been created using this host. */ postProgramCreationCleanup(): void { this.shimTagger.finalize(); } /** * Create an `NgCompilerHost` from a delegate host, an array of input filenames, and the full set * of TypeScript and Angular compiler options. */ static wrap( delegate: ts.CompilerHost, inputFiles: ReadonlyArray<string>, options: NgCompilerOptions, oldProgram: ts.Program|null): NgCompilerHost { // TODO(alxhub): remove the fallback to allowEmptyCodegenFiles after verifying that the rest of // our build tooling is no longer relying on it. const allowEmptyCodegenFiles = options.allowEmptyCodegenFiles || false; const shouldGenerateFactoryShims = options.generateNgFactoryShims !== undefined ? options.generateNgFactoryShims : allowEmptyCodegenFiles; const shouldGenerateSummaryShims = options.generateNgSummaryShims !== undefined ? options.generateNgSummaryShims : allowEmptyCodegenFiles; const topLevelShimGenerators: TopLevelShimGenerator[] = []; const perFileShimGenerators: PerFileShimGenerator[] = []; if (shouldGenerateSummaryShims) { // Summary generation. perFileShimGenerators.push(new SummaryGenerator()); } let factoryTracker: FactoryTracker|null = null; if (shouldGenerateFactoryShims) { const factoryGenerator = new FactoryGenerator(); perFileShimGenerators.push(factoryGenerator); factoryTracker = factoryGenerator; } const rootDirs = getRootDirs(delegate, options as ts.CompilerOptions); perFileShimGenerators.push(new TypeCheckShimGenerator()); let diagnostics: ts.Diagnostic[] = []; const normalizedTsInputFiles: AbsoluteFsPath[] = []; for (const inputFile of inputFiles) { if (!isNonDeclarationTsPath(inputFile)) { continue; } normalizedTsInputFiles.push(resolve(inputFile)); } let entryPoint: AbsoluteFsPath|null = null; if (options.flatModuleOutFile != null && options.flatModuleOutFile !== '') { entryPoint = findFlatIndexEntryPoint(normalizedTsInputFiles); if (entryPoint === null) { // This error message talks specifically about having a single .ts file in "files". However // the actual logic is a bit more permissive. If a single file exists, that will be taken, // otherwise the highest level (shortest path) "index.ts" file will be used as the flat // module entry point instead. If neither of these conditions apply, the error below is // given. // // The user is not informed about the "index.ts" option as this behavior is deprecated - // an explicit entrypoint should always be specified. diagnostics.push({ category: ts.DiagnosticCategory.Error, code: ngErrorCode(ErrorCode.CONFIG_FLAT_MODULE_NO_INDEX), file: undefined, start: undefined, length: undefined, messageText: 'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.', }); } else { const flatModuleId = options.flatModuleId || null; const flatModuleOutFile = normalizeSeparators(options.flatModuleOutFile); const flatIndexGenerator = new FlatIndexGenerator(entryPoint, flatModuleOutFile, flatModuleId); topLevelShimGenerators.push(flatIndexGenerator); } } const shimAdapter = new ShimAdapter( delegate, normalizedTsInputFiles, topLevelShimGenerators, perFileShimGenerators, oldProgram); const shimTagger = new ShimReferenceTagger(perFileShimGenerators.map(gen => gen.extensionPrefix)); return new NgCompilerHost( delegate, inputFiles, rootDirs, shimAdapter, shimTagger, entryPoint, factoryTracker, diagnostics); } /** * Check whether the given `ts.SourceFile` is a shim file. * * If this returns false, the file is user-provided. */ isShim(sf: ts.SourceFile): boolean { return isShim(sf); } getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void)|undefined, shouldCreateNewSourceFile?: boolean|undefined): ts.SourceFile|undefined { // Is this a previously known shim? const shimSf = this.shimAdapter.maybeGenerate(resolve(fileName)); if (shimSf !== null) { // Yes, so return it. return shimSf; } // No, so it's a file which might need shims (or a file which doesn't exist). const sf = this.delegate.getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); if (sf === undefined) { return undefined; } this.shimTagger.tag(sf); return sf; } fileExists(fileName: string): boolean { // Consider the file as existing whenever // 1) it really does exist in the delegate host, or // 2) at least one of the shim generators recognizes it // Note that we can pass the file name as branded absolute fs path because TypeScript // internally only passes POSIX-like paths. // // Also note that the `maybeGenerate` check below checks for both `null` and `undefined`. return this.delegate.fileExists(fileName) || this.shimAdapter.maybeGenerate(resolve(fileName)) != null; } get unifiedModulesHost(): UnifiedModulesHost|null { return this.fileNameToModuleName !== undefined ? this as UnifiedModulesHost : null; } private createCachedResolveModuleNamesFunction(): ts.CompilerHost['resolveModuleNames'] { const moduleResolutionCache = ts.createModuleResolutionCache( this.getCurrentDirectory(), this.getCanonicalFileName.bind(this)); return (moduleNames, containingFile, reusedNames, redirectedReference, options) => { return moduleNames.map(moduleName => { const module = ts.resolveModuleName( moduleName, containingFile, options, this, moduleResolutionCache, redirectedReference); return module.resolvedModule; }); }; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { NetworkWatchers } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { NetworkManagementClient } from "../networkManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { NetworkWatcher, NetworkWatchersListOptionalParams, NetworkWatchersListAllOptionalParams, NetworkWatchersCreateOrUpdateOptionalParams, NetworkWatchersCreateOrUpdateResponse, NetworkWatchersGetOptionalParams, NetworkWatchersGetResponse, NetworkWatchersDeleteOptionalParams, TagsObject, NetworkWatchersUpdateTagsOptionalParams, NetworkWatchersUpdateTagsResponse, NetworkWatchersListResponse, NetworkWatchersListAllResponse, TopologyParameters, NetworkWatchersGetTopologyOptionalParams, NetworkWatchersGetTopologyResponse, VerificationIPFlowParameters, NetworkWatchersVerifyIPFlowOptionalParams, NetworkWatchersVerifyIPFlowResponse, NextHopParameters, NetworkWatchersGetNextHopOptionalParams, NetworkWatchersGetNextHopResponse, SecurityGroupViewParameters, NetworkWatchersGetVMSecurityRulesOptionalParams, NetworkWatchersGetVMSecurityRulesResponse, TroubleshootingParameters, NetworkWatchersGetTroubleshootingOptionalParams, NetworkWatchersGetTroubleshootingResponse, QueryTroubleshootingParameters, NetworkWatchersGetTroubleshootingResultOptionalParams, NetworkWatchersGetTroubleshootingResultResponse, FlowLogInformation, NetworkWatchersSetFlowLogConfigurationOptionalParams, NetworkWatchersSetFlowLogConfigurationResponse, FlowLogStatusParameters, NetworkWatchersGetFlowLogStatusOptionalParams, NetworkWatchersGetFlowLogStatusResponse, ConnectivityParameters, NetworkWatchersCheckConnectivityOptionalParams, NetworkWatchersCheckConnectivityResponse, AzureReachabilityReportParameters, NetworkWatchersGetAzureReachabilityReportOptionalParams, NetworkWatchersGetAzureReachabilityReportResponse, AvailableProvidersListParameters, NetworkWatchersListAvailableProvidersOptionalParams, NetworkWatchersListAvailableProvidersResponse, NetworkConfigurationDiagnosticParameters, NetworkWatchersGetNetworkConfigurationDiagnosticOptionalParams, NetworkWatchersGetNetworkConfigurationDiagnosticResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing NetworkWatchers operations. */ export class NetworkWatchersImpl implements NetworkWatchers { private readonly client: NetworkManagementClient; /** * Initialize a new instance of the class NetworkWatchers class. * @param client Reference to the service client */ constructor(client: NetworkManagementClient) { this.client = client; } /** * Gets all network watchers by resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ public list( resourceGroupName: string, options?: NetworkWatchersListOptionalParams ): PagedAsyncIterableIterator<NetworkWatcher> { const iter = this.listPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, options); } }; } private async *listPagingPage( resourceGroupName: string, options?: NetworkWatchersListOptionalParams ): AsyncIterableIterator<NetworkWatcher[]> { let result = await this._list(resourceGroupName, options); yield result.value || []; } private async *listPagingAll( resourceGroupName: string, options?: NetworkWatchersListOptionalParams ): AsyncIterableIterator<NetworkWatcher> { for await (const page of this.listPagingPage(resourceGroupName, options)) { yield* page; } } /** * Gets all network watchers by subscription. * @param options The options parameters. */ public listAll( options?: NetworkWatchersListAllOptionalParams ): PagedAsyncIterableIterator<NetworkWatcher> { const iter = this.listAllPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAllPagingPage(options); } }; } private async *listAllPagingPage( options?: NetworkWatchersListAllOptionalParams ): AsyncIterableIterator<NetworkWatcher[]> { let result = await this._listAll(options); yield result.value || []; } private async *listAllPagingAll( options?: NetworkWatchersListAllOptionalParams ): AsyncIterableIterator<NetworkWatcher> { for await (const page of this.listAllPagingPage(options)) { yield* page; } } /** * Creates or updates a network watcher in the specified resource group. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the network watcher resource. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, networkWatcherName: string, parameters: NetworkWatcher, options?: NetworkWatchersCreateOrUpdateOptionalParams ): Promise<NetworkWatchersCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, networkWatcherName, parameters, options }, createOrUpdateOperationSpec ); } /** * Gets the specified network watcher by resource group. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param options The options parameters. */ get( resourceGroupName: string, networkWatcherName: string, options?: NetworkWatchersGetOptionalParams ): Promise<NetworkWatchersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, networkWatcherName, options }, getOperationSpec ); } /** * Deletes the specified network watcher resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, networkWatcherName: string, options?: NetworkWatchersDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Deletes the specified network watcher resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, networkWatcherName: string, options?: NetworkWatchersDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, networkWatcherName, options ); return poller.pollUntilDone(); } /** * Updates a network watcher tags. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters supplied to update network watcher tags. * @param options The options parameters. */ updateTags( resourceGroupName: string, networkWatcherName: string, parameters: TagsObject, options?: NetworkWatchersUpdateTagsOptionalParams ): Promise<NetworkWatchersUpdateTagsResponse> { return this.client.sendOperationRequest( { resourceGroupName, networkWatcherName, parameters, options }, updateTagsOperationSpec ); } /** * Gets all network watchers by resource group. * @param resourceGroupName The name of the resource group. * @param options The options parameters. */ private _list( resourceGroupName: string, options?: NetworkWatchersListOptionalParams ): Promise<NetworkWatchersListResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listOperationSpec ); } /** * Gets all network watchers by subscription. * @param options The options parameters. */ private _listAll( options?: NetworkWatchersListAllOptionalParams ): Promise<NetworkWatchersListAllResponse> { return this.client.sendOperationRequest({ options }, listAllOperationSpec); } /** * Gets the current network topology by resource group. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the representation of topology. * @param options The options parameters. */ getTopology( resourceGroupName: string, networkWatcherName: string, parameters: TopologyParameters, options?: NetworkWatchersGetTopologyOptionalParams ): Promise<NetworkWatchersGetTopologyResponse> { return this.client.sendOperationRequest( { resourceGroupName, networkWatcherName, parameters, options }, getTopologyOperationSpec ); } /** * Verify IP flow from the specified VM to a location given the currently configured NSG rules. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the IP flow to be verified. * @param options The options parameters. */ async beginVerifyIPFlow( resourceGroupName: string, networkWatcherName: string, parameters: VerificationIPFlowParameters, options?: NetworkWatchersVerifyIPFlowOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersVerifyIPFlowResponse>, NetworkWatchersVerifyIPFlowResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersVerifyIPFlowResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, verifyIPFlowOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Verify IP flow from the specified VM to a location given the currently configured NSG rules. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the IP flow to be verified. * @param options The options parameters. */ async beginVerifyIPFlowAndWait( resourceGroupName: string, networkWatcherName: string, parameters: VerificationIPFlowParameters, options?: NetworkWatchersVerifyIPFlowOptionalParams ): Promise<NetworkWatchersVerifyIPFlowResponse> { const poller = await this.beginVerifyIPFlow( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Gets the next hop from the specified VM. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the source and destination endpoint. * @param options The options parameters. */ async beginGetNextHop( resourceGroupName: string, networkWatcherName: string, parameters: NextHopParameters, options?: NetworkWatchersGetNextHopOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetNextHopResponse>, NetworkWatchersGetNextHopResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetNextHopResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getNextHopOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Gets the next hop from the specified VM. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the source and destination endpoint. * @param options The options parameters. */ async beginGetNextHopAndWait( resourceGroupName: string, networkWatcherName: string, parameters: NextHopParameters, options?: NetworkWatchersGetNextHopOptionalParams ): Promise<NetworkWatchersGetNextHopResponse> { const poller = await this.beginGetNextHop( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Gets the configured and effective security group rules on the specified VM. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the VM to check security groups for. * @param options The options parameters. */ async beginGetVMSecurityRules( resourceGroupName: string, networkWatcherName: string, parameters: SecurityGroupViewParameters, options?: NetworkWatchersGetVMSecurityRulesOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetVMSecurityRulesResponse>, NetworkWatchersGetVMSecurityRulesResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetVMSecurityRulesResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getVMSecurityRulesOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Gets the configured and effective security group rules on the specified VM. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters that define the VM to check security groups for. * @param options The options parameters. */ async beginGetVMSecurityRulesAndWait( resourceGroupName: string, networkWatcherName: string, parameters: SecurityGroupViewParameters, options?: NetworkWatchersGetVMSecurityRulesOptionalParams ): Promise<NetworkWatchersGetVMSecurityRulesResponse> { const poller = await this.beginGetVMSecurityRules( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Initiate troubleshooting on a specified resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the resource to troubleshoot. * @param options The options parameters. */ async beginGetTroubleshooting( resourceGroupName: string, networkWatcherName: string, parameters: TroubleshootingParameters, options?: NetworkWatchersGetTroubleshootingOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetTroubleshootingResponse>, NetworkWatchersGetTroubleshootingResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetTroubleshootingResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getTroubleshootingOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Initiate troubleshooting on a specified resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the resource to troubleshoot. * @param options The options parameters. */ async beginGetTroubleshootingAndWait( resourceGroupName: string, networkWatcherName: string, parameters: TroubleshootingParameters, options?: NetworkWatchersGetTroubleshootingOptionalParams ): Promise<NetworkWatchersGetTroubleshootingResponse> { const poller = await this.beginGetTroubleshooting( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Get the last completed troubleshooting result on a specified resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the resource to query the troubleshooting result. * @param options The options parameters. */ async beginGetTroubleshootingResult( resourceGroupName: string, networkWatcherName: string, parameters: QueryTroubleshootingParameters, options?: NetworkWatchersGetTroubleshootingResultOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetTroubleshootingResultResponse>, NetworkWatchersGetTroubleshootingResultResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetTroubleshootingResultResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getTroubleshootingResultOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Get the last completed troubleshooting result on a specified resource. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the resource to query the troubleshooting result. * @param options The options parameters. */ async beginGetTroubleshootingResultAndWait( resourceGroupName: string, networkWatcherName: string, parameters: QueryTroubleshootingParameters, options?: NetworkWatchersGetTroubleshootingResultOptionalParams ): Promise<NetworkWatchersGetTroubleshootingResultResponse> { const poller = await this.beginGetTroubleshootingResult( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Configures flow log and traffic analytics (optional) on a specified resource. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the configuration of flow log. * @param options The options parameters. */ async beginSetFlowLogConfiguration( resourceGroupName: string, networkWatcherName: string, parameters: FlowLogInformation, options?: NetworkWatchersSetFlowLogConfigurationOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersSetFlowLogConfigurationResponse>, NetworkWatchersSetFlowLogConfigurationResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersSetFlowLogConfigurationResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, setFlowLogConfigurationOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Configures flow log and traffic analytics (optional) on a specified resource. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define the configuration of flow log. * @param options The options parameters. */ async beginSetFlowLogConfigurationAndWait( resourceGroupName: string, networkWatcherName: string, parameters: FlowLogInformation, options?: NetworkWatchersSetFlowLogConfigurationOptionalParams ): Promise<NetworkWatchersSetFlowLogConfigurationResponse> { const poller = await this.beginSetFlowLogConfiguration( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Queries status of flow log and traffic analytics (optional) on a specified resource. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define a resource to query flow log and traffic analytics * (optional) status. * @param options The options parameters. */ async beginGetFlowLogStatus( resourceGroupName: string, networkWatcherName: string, parameters: FlowLogStatusParameters, options?: NetworkWatchersGetFlowLogStatusOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetFlowLogStatusResponse>, NetworkWatchersGetFlowLogStatusResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetFlowLogStatusResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getFlowLogStatusOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Queries status of flow log and traffic analytics (optional) on a specified resource. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that define a resource to query flow log and traffic analytics * (optional) status. * @param options The options parameters. */ async beginGetFlowLogStatusAndWait( resourceGroupName: string, networkWatcherName: string, parameters: FlowLogStatusParameters, options?: NetworkWatchersGetFlowLogStatusOptionalParams ): Promise<NetworkWatchersGetFlowLogStatusResponse> { const poller = await this.beginGetFlowLogStatus( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given * endpoint including another VM or an arbitrary remote server. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that determine how the connectivity check will be performed. * @param options The options parameters. */ async beginCheckConnectivity( resourceGroupName: string, networkWatcherName: string, parameters: ConnectivityParameters, options?: NetworkWatchersCheckConnectivityOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersCheckConnectivityResponse>, NetworkWatchersCheckConnectivityResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersCheckConnectivityResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, checkConnectivityOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Verifies the possibility of establishing a direct TCP connection from a virtual machine to a given * endpoint including another VM or an arbitrary remote server. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that determine how the connectivity check will be performed. * @param options The options parameters. */ async beginCheckConnectivityAndWait( resourceGroupName: string, networkWatcherName: string, parameters: ConnectivityParameters, options?: NetworkWatchersCheckConnectivityOptionalParams ): Promise<NetworkWatchersCheckConnectivityResponse> { const poller = await this.beginCheckConnectivity( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * NOTE: This feature is currently in preview and still being tested for stability. Gets the relative * latency score for internet service providers from a specified location to Azure regions. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that determine Azure reachability report configuration. * @param options The options parameters. */ async beginGetAzureReachabilityReport( resourceGroupName: string, networkWatcherName: string, parameters: AzureReachabilityReportParameters, options?: NetworkWatchersGetAzureReachabilityReportOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersGetAzureReachabilityReportResponse>, NetworkWatchersGetAzureReachabilityReportResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetAzureReachabilityReportResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getAzureReachabilityReportOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * NOTE: This feature is currently in preview and still being tested for stability. Gets the relative * latency score for internet service providers from a specified location to Azure regions. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that determine Azure reachability report configuration. * @param options The options parameters. */ async beginGetAzureReachabilityReportAndWait( resourceGroupName: string, networkWatcherName: string, parameters: AzureReachabilityReportParameters, options?: NetworkWatchersGetAzureReachabilityReportOptionalParams ): Promise<NetworkWatchersGetAzureReachabilityReportResponse> { const poller = await this.beginGetAzureReachabilityReport( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * NOTE: This feature is currently in preview and still being tested for stability. Lists all available * internet service providers for a specified Azure region. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that scope the list of available providers. * @param options The options parameters. */ async beginListAvailableProviders( resourceGroupName: string, networkWatcherName: string, parameters: AvailableProvidersListParameters, options?: NetworkWatchersListAvailableProvidersOptionalParams ): Promise< PollerLike< PollOperationState<NetworkWatchersListAvailableProvidersResponse>, NetworkWatchersListAvailableProvidersResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersListAvailableProvidersResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, listAvailableProvidersOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * NOTE: This feature is currently in preview and still being tested for stability. Lists all available * internet service providers for a specified Azure region. * @param resourceGroupName The name of the network watcher resource group. * @param networkWatcherName The name of the network watcher resource. * @param parameters Parameters that scope the list of available providers. * @param options The options parameters. */ async beginListAvailableProvidersAndWait( resourceGroupName: string, networkWatcherName: string, parameters: AvailableProvidersListParameters, options?: NetworkWatchersListAvailableProvidersOptionalParams ): Promise<NetworkWatchersListAvailableProvidersResponse> { const poller = await this.beginListAvailableProviders( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } /** * Gets Network Configuration Diagnostic data to help customers understand and debug network behavior. * It provides detailed information on what security rules were applied to a specified traffic flow and * the result of evaluating these rules. Customers must provide details of a flow like source, * destination, protocol, etc. The API returns whether traffic was allowed or denied, the rules * evaluated for the specified flow and the evaluation results. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters to get network configuration diagnostic. * @param options The options parameters. */ async beginGetNetworkConfigurationDiagnostic( resourceGroupName: string, networkWatcherName: string, parameters: NetworkConfigurationDiagnosticParameters, options?: NetworkWatchersGetNetworkConfigurationDiagnosticOptionalParams ): Promise< PollerLike< PollOperationState< NetworkWatchersGetNetworkConfigurationDiagnosticResponse >, NetworkWatchersGetNetworkConfigurationDiagnosticResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<NetworkWatchersGetNetworkConfigurationDiagnosticResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, networkWatcherName, parameters, options }, getNetworkConfigurationDiagnosticOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs, lroResourceLocationConfig: "location" }); } /** * Gets Network Configuration Diagnostic data to help customers understand and debug network behavior. * It provides detailed information on what security rules were applied to a specified traffic flow and * the result of evaluating these rules. Customers must provide details of a flow like source, * destination, protocol, etc. The API returns whether traffic was allowed or denied, the rules * evaluated for the specified flow and the evaluation results. * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param parameters Parameters to get network configuration diagnostic. * @param options The options parameters. */ async beginGetNetworkConfigurationDiagnosticAndWait( resourceGroupName: string, networkWatcherName: string, parameters: NetworkConfigurationDiagnosticParameters, options?: NetworkWatchersGetNetworkConfigurationDiagnosticOptionalParams ): Promise<NetworkWatchersGetNetworkConfigurationDiagnosticResponse> { const poller = await this.beginGetNetworkConfigurationDiagnostic( resourceGroupName, networkWatcherName, parameters, options ); return poller.pollUntilDone(); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.NetworkWatcher }, 201: { bodyMapper: Mappers.NetworkWatcher }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters21, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NetworkWatcher }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept], serializer }; const updateTagsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.NetworkWatcher }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NetworkWatcherListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listAllOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Network/networkWatchers", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.NetworkWatcherListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const getTopologyOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/topology", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.Topology }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters22, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const verifyIPFlowOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/ipFlowVerify", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.VerificationIPFlowResult }, 201: { bodyMapper: Mappers.VerificationIPFlowResult }, 202: { bodyMapper: Mappers.VerificationIPFlowResult }, 204: { bodyMapper: Mappers.VerificationIPFlowResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters23, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getNextHopOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/nextHop", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.NextHopResult }, 201: { bodyMapper: Mappers.NextHopResult }, 202: { bodyMapper: Mappers.NextHopResult }, 204: { bodyMapper: Mappers.NextHopResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters24, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getVMSecurityRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/securityGroupView", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.SecurityGroupViewResult }, 201: { bodyMapper: Mappers.SecurityGroupViewResult }, 202: { bodyMapper: Mappers.SecurityGroupViewResult }, 204: { bodyMapper: Mappers.SecurityGroupViewResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters25, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getTroubleshootingOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/troubleshoot", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.TroubleshootingResult }, 201: { bodyMapper: Mappers.TroubleshootingResult }, 202: { bodyMapper: Mappers.TroubleshootingResult }, 204: { bodyMapper: Mappers.TroubleshootingResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters26, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getTroubleshootingResultOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryTroubleshootResult", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.TroubleshootingResult }, 201: { bodyMapper: Mappers.TroubleshootingResult }, 202: { bodyMapper: Mappers.TroubleshootingResult }, 204: { bodyMapper: Mappers.TroubleshootingResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters27, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const setFlowLogConfigurationOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/configureFlowLog", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.FlowLogInformation }, 201: { bodyMapper: Mappers.FlowLogInformation }, 202: { bodyMapper: Mappers.FlowLogInformation }, 204: { bodyMapper: Mappers.FlowLogInformation }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters28, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getFlowLogStatusOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/queryFlowLogStatus", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.FlowLogInformation }, 201: { bodyMapper: Mappers.FlowLogInformation }, 202: { bodyMapper: Mappers.FlowLogInformation }, 204: { bodyMapper: Mappers.FlowLogInformation }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters29, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const checkConnectivityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectivityCheck", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.ConnectivityInformation }, 201: { bodyMapper: Mappers.ConnectivityInformation }, 202: { bodyMapper: Mappers.ConnectivityInformation }, 204: { bodyMapper: Mappers.ConnectivityInformation }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters30, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getAzureReachabilityReportOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/azureReachabilityReport", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AzureReachabilityReport }, 201: { bodyMapper: Mappers.AzureReachabilityReport }, 202: { bodyMapper: Mappers.AzureReachabilityReport }, 204: { bodyMapper: Mappers.AzureReachabilityReport }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters31, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listAvailableProvidersOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/availableProvidersList", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AvailableProvidersList }, 201: { bodyMapper: Mappers.AvailableProvidersList }, 202: { bodyMapper: Mappers.AvailableProvidersList }, 204: { bodyMapper: Mappers.AvailableProvidersList }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters32, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getNetworkConfigurationDiagnosticOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/networkConfigurationDiagnostic", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.NetworkConfigurationDiagnosticResponse }, 201: { bodyMapper: Mappers.NetworkConfigurationDiagnosticResponse }, 202: { bodyMapper: Mappers.NetworkConfigurationDiagnosticResponse }, 204: { bodyMapper: Mappers.NetworkConfigurationDiagnosticResponse }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters33, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.networkWatcherName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer };
the_stack
// Fixture taken from https://github.com/jcingroup/C551608_Roki/blob/master/Work.WebProj/Scripts/src/tsx/m-parm.tsx import $ = require('jquery'); import React = require('react'); import ReactDOM = require('react-dom'); import Moment = require('moment'); import ReactBootstrap = require("react-bootstrap"); import CommCmpt = require('comm-cmpt'); import CommFunc = require('comm-func'); namespace Parm { interface ParamData { Email?: string; PurchaseTotal?: number; HomoiothermyFee?: number; RefrigerFee?: number; AccountName?: string; BankName?: string; BankCode?: string; AccountNumber?: string; Fee?: number; } export class GridForm extends React.Component<any, { param?: ParamData }>{ constructor() { super(); this.queryInitData = this.queryInitData.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.componentDidMount = this.componentDidMount.bind(this); this.setInputValue = this.setInputValue.bind(this); this.render = this.render.bind(this); this.state = { param: { Email: null, PurchaseTotal: 0, HomoiothermyFee: 0, RefrigerFee:0, AccountName: null, BankName: null, BankCode: null, AccountNumber: null, Fee: 0 } } } static defaultProps = { apiInitPath: gb_approot + 'Active/ParmData/aj_ParamInit', apiPath: gb_approot + 'api/GetAction/PostParamData' } componentDidMount() { this.queryInitData(); } queryInitData() { CommFunc.jqGet(this.props.apiInitPath, {}) .done((data, textStatus, jqXHRdata) => { this.setState({ param: data }); }) .fail((jqXHR, textStatus, errorThrown) => { CommFunc.showAjaxError(errorThrown); }); } handleSubmit(e: React.FormEvent) { e.preventDefault(); CommFunc.jqPost(this.props.apiPath, this.state.param) .done((data, textStatus, jqXHRdata) => { if (data.result) { CommFunc.tosMessage(null, '修改完成', 1); } else { alert(data.message); } }) .fail((jqXHR, textStatus, errorThrown) => { CommFunc.showAjaxError(errorThrown); }); return; } handleOnBlur(date) { } setInputValue(name: string, e: React.SyntheticEvent) { let input: HTMLInputElement = e.target as HTMLInputElement; let obj = this.state.param; obj[name] = input.value; this.setState({ param: obj }); } render() { var outHtml: JSX.Element = null; let param = this.state.param; let InputDate = CommCmpt.InputDate; outHtml = ( <div> <ul className="breadcrumb"> <li><i className="fa-list-alt"></i> {this.props.menuName} </li> </ul> <h4 className="title"> {this.props.caption} 基本資料維護</h4> <form className="form-horizontal" onSubmit={this.handleSubmit}> <div className="col-xs-12"> <div className="item-box"> {/*--email--*/} <div className="item-title text-center"> <h5>Email信箱設定</h5> </div> <div className="alert alert-warning" role="alert"> <ol> <li>多筆信箱請用「<strong className="text-danger">, </strong>」逗號分開。<br />ex.<strong>user1 @demo.com.tw, user2 @demo.com.tw</strong></li> <li>Email 前面可填收件人姓名,用「<strong className="text-danger">: </strong>」冒號分隔姓名和信箱,此項非必要,可省略。<br />ex.<strong>收件人A: user1 @demo.com.tw, 收件人B: user2 @demo.com.tw</strong></li> </ol> </div> <div className="form-group"> <label className="col-xs-1 control-label">收件信箱</label> <div className="col-xs-9"> <input className="form-control" type="text" value={param.Email} onChange={this.setInputValue.bind(this, 'Email') } maxLength={500} required/> </div> </div> {/*--email end--*/} {/*--shoppingCost--*/} <div className="item-title text-center"> <h5>訂單運費設定</h5> </div> <div className="form-group"> <label className="col-xs-3 control-label">會員下訂單,當訂單金額少於NT$</label> <div className="col-xs-1"> <input className="form-control" type="number" value={param.PurchaseTotal} onChange={this.setInputValue.bind(this, 'PurchaseTotal') } min={0} required/> </div> <label className="col-xs-2 control-label">元時須付常溫運費NT$</label> <div className="col-xs-1"> <input className="form-control" type="number" value={param.HomoiothermyFee} onChange={this.setInputValue.bind(this, 'HomoiothermyFee') } min={0} required/> </div> <label className="col-xs-2 control-label">元或冷凍(冷藏)運費NT$</label> <div className="col-xs-1"> <input className="form-control" type="number" value={param.RefrigerFee} onChange={this.setInputValue.bind(this, 'RefrigerFee') } min={0} required/> </div> <label className="col-xs-1 control-label">元</label> </div> {/*--shoppingCost end--*/} {/*--Payment--*/} <div className="item-title text-center"> <h5>付款方式</h5> </div> <div className="form-group"> <label className="col-xs-4 control-label">當付款方式選擇『ATM轉帳』時,銀行帳號資料為: </label> </div> <div className="form-group"> <label className="col-xs-2 control-label">戶名: </label> <div className="col-xs-3"> <input className="form-control" type="text" value={param.AccountName} onChange={this.setInputValue.bind(this, 'AccountName') } maxLength={16} required/> </div> </div> <div className="form-group"> <label className="col-xs-2 control-label">銀行: </label> <div className="col-xs-3"> <input className="form-control" type="text" value={param.BankName} onChange={this.setInputValue.bind(this, 'BankName') } maxLength={16} required/> </div> </div> <div className="form-group"> <label className="col-xs-2 control-label">代碼: </label> <div className="col-xs-3"> <input className="form-control" type="text" value={param.BankCode} onChange={this.setInputValue.bind(this, 'BankCode') } maxLength={5} required/> </div> </div> <div className="form-group"> <label className="col-xs-2 control-label">帳號: </label> <div className="col-xs-3"> <input className="form-control" type="text" value={param.AccountNumber} onChange={this.setInputValue.bind(this, 'AccountNumber') } maxLength={16} required/> </div> </div> {/*<div className="form-group"> <label className="col-xs-4 control-label">當付款方式選擇『貨到付款』時,須加NT$ </label> <div className="col-xs-1"> <input className="form-control" type="number" value={param.Fee} onChange={this.setInputValue.bind(this, 'Fee') } min={0} required/> </div> <label className="control-label">元手續費</label> </div>*/} {/*--Payment end--*/} </div> <div className="form-action"> <div className="col-xs-4 col-xs-offset-5"> <button type="submit" className="btn-primary"><i className="fa-check"></i> 儲存</button> </div> </div> </div> </form> </div> ); return outHtml; } } } var dom = document.getElementById('page_content'); ReactDOM.render(<Parm.GridForm caption={gb_caption} menuName={gb_menuname} iconClass="fa-list-alt" />, dom);
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [mobiletargeting](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonpinpoint.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Mobiletargeting extends PolicyStatement { public servicePrefix = 'mobiletargeting'; /** * Statement provider for service [mobiletargeting](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonpinpoint.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Create an app. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-app.html#rest-api-app-methods */ public toCreateApp() { return this.to('CreateApp'); } /** * Create a campaign for an app. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaigns.html#rest-api-campaigns-methods */ public toCreateCampaign() { return this.to('CreateCampaign'); } /** * Create an email template. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-email.html#templates-template-name-email-http-methods */ public toCreateEmailTemplate() { return this.to('CreateEmailTemplate'); } /** * Create an export job that exports endpoint definitions to Amazon S3. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-export-jobs.html#rest-api-export-jobs-methods */ public toCreateExportJob() { return this.to('CreateExportJob'); } /** * Import endpoint definitions from to create a segment. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-import-jobs.html#rest-api-import-jobs-methods */ public toCreateImportJob() { return this.to('CreateImportJob'); } /** * Create a Journey for an app. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id.html#apps-application-id-journeys-journey-id-http-methods */ public toCreateJourney() { return this.to('CreateJourney'); } /** * Create a push notification template. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html#templates-template-name-push-http-methods */ public toCreatePushTemplate() { return this.to('CreatePushTemplate'); } /** * Create an Amazon Pinpoint configuration for a recommender model. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders.html#CreateRecommenderConfiguration */ public toCreateRecommenderConfiguration() { return this.to('CreateRecommenderConfiguration'); } /** * Create a segment that is based on endpoint data reported to Pinpoint by your app. To allow a user to create a segment by importing endpoint data from outside of Pinpoint, allow the mobiletargeting:CreateImportJob action. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segments.html#rest-api-segments-methods */ public toCreateSegment() { return this.to('CreateSegment'); } /** * Create an sms message template. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-sms.html#templates-template-name-sms-http-methods */ public toCreateSmsTemplate() { return this.to('CreateSmsTemplate'); } /** * Create a voice message template. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-voice.html#templates-template-name-voice-http-methods */ public toCreateVoiceTemplate() { return this.to('CreateVoiceTemplate'); } /** * Delete the ADM channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-adm-channel.html#rest-api-adm-channel-methods */ public toDeleteAdmChannel() { return this.to('DeleteAdmChannel'); } /** * Delete the APNs channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-channel.html#rest-api-apns-channel-methods */ public toDeleteApnsChannel() { return this.to('DeleteApnsChannel'); } /** * Delete the APNs sandbox channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-sandbox-channel.html#rest-api-apns-sandbox-channel-methods */ public toDeleteApnsSandboxChannel() { return this.to('DeleteApnsSandboxChannel'); } /** * Delete the APNs VoIP channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-channel.html#rest-api-apns-voip-channel-methods */ public toDeleteApnsVoipChannel() { return this.to('DeleteApnsVoipChannel'); } /** * Delete the APNs VoIP sandbox channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-sandbox-channel.html#rest-api-apns-voip-sandbox-channel-methods */ public toDeleteApnsVoipSandboxChannel() { return this.to('DeleteApnsVoipSandboxChannel'); } /** * Delete a specific campaign. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-app.html#rest-api-app-methods */ public toDeleteApp() { return this.to('DeleteApp'); } /** * Delete the Baidu channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-baidu-channel.html#rest-api-baidu-channel-methods */ public toDeleteBaiduChannel() { return this.to('DeleteBaiduChannel'); } /** * Delete a specific campaign. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign.html#rest-api-campaign-methods */ public toDeleteCampaign() { return this.to('DeleteCampaign'); } /** * Delete the email channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-email-channel.html#rest-api-email-channel-methods */ public toDeleteEmailChannel() { return this.to('DeleteEmailChannel'); } /** * Delete an email template or an email template version. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-email.html#templates-template-name-email-http-methods */ public toDeleteEmailTemplate() { return this.to('DeleteEmailTemplate'); } /** * Delete an endpoint. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-endpoint.html#rest-api-endpoint-methods */ public toDeleteEndpoint() { return this.to('DeleteEndpoint'); } /** * Delete the event stream for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-event-stream.html#rest-api-event-stream-methods */ public toDeleteEventStream() { return this.to('DeleteEventStream'); } /** * Delete the GCM channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-gcm-channel.html#rest-api-gcm-channel-methods */ public toDeleteGcmChannel() { return this.to('DeleteGcmChannel'); } /** * Delete a specific journey. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id.html#apps-application-id-journeys-journey-id-http-methods */ public toDeleteJourney() { return this.to('DeleteJourney'); } /** * Delete a push notification template or a push notification template version. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html#templates-template-name-push-http-methods */ public toDeletePushTemplate() { return this.to('DeletePushTemplate'); } /** * Delete an Amazon Pinpoint configuration for a recommender model. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders-recommender-id.html#DeleteRecommenderConfiguration */ public toDeleteRecommenderConfiguration() { return this.to('DeleteRecommenderConfiguration'); } /** * Delete a specific segment. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segment.html#rest-api-segment-methods */ public toDeleteSegment() { return this.to('DeleteSegment'); } /** * Delete the SMS channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-sms-channel.html#rest-api-sms-channel-methods */ public toDeleteSmsChannel() { return this.to('DeleteSmsChannel'); } /** * Delete an sms message template or an sms message template version. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-sms.html#templates-template-name-sms-http-methods */ public toDeleteSmsTemplate() { return this.to('DeleteSmsTemplate'); } /** * Delete all of the endpoints that are associated with a user ID. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-user.html#rest-api-user-methods */ public toDeleteUserEndpoints() { return this.to('DeleteUserEndpoints'); } /** * Delete the Voice channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-voice-channel.html#rest-api-voice-channel-methods */ public toDeleteVoiceChannel() { return this.to('DeleteVoiceChannel'); } /** * Delete a voice message template or a voice message template version. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-voice.html#templates-template-name-voice-http-methods */ public toDeleteVoiceTemplate() { return this.to('DeleteVoiceTemplate'); } /** * Retrieve information about the Amazon Device Messaging (ADM) channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-adm-channel.html#rest-api-adm-channel-methods */ public toGetAdmChannel() { return this.to('GetAdmChannel'); } /** * Retrieve information about the APNs channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-channel.html#rest-api-apns-channel-methods */ public toGetApnsChannel() { return this.to('GetApnsChannel'); } /** * Retrieve information about the APNs sandbox channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-sandbox-channel.html#rest-api-apns-sandbox-channel-methods */ public toGetApnsSandboxChannel() { return this.to('GetApnsSandboxChannel'); } /** * Retrieve information about the APNs VoIP channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-channel.html#rest-api-apns-voip-channel-methods */ public toGetApnsVoipChannel() { return this.to('GetApnsVoipChannel'); } /** * Retrieve information about the APNs VoIP sandbox channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-sandbox-channel.html#rest-api-apns-voip-sandbox-channel-methods */ public toGetApnsVoipSandboxChannel() { return this.to('GetApnsVoipSandboxChannel'); } /** * Retrieve information about a specific app in your Amazon Pinpoint account. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-app.html#rest-api-app-methods */ public toGetApp() { return this.to('GetApp'); } /** * Retrieves (queries) pre-aggregated data for a standard metric that applies to an application. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-kpis-daterange-kpi-name.html#GetApplicationDateRangeKpi */ public toGetApplicationDateRangeKpi() { return this.to('GetApplicationDateRangeKpi'); } /** * Retrieve the default settings for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-settings.html#rest-api-settings-methods */ public toGetApplicationSettings() { return this.to('GetApplicationSettings'); } /** * Retrieve a list of apps in your Amazon Pinpoint account. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apps.html#rest-api-apps-methods */ public toGetApps() { return this.to('GetApps'); } /** * Retrieve information about the Baidu channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-baidu-channel.html#rest-api-baidu-channel-methods */ public toGetBaiduChannel() { return this.to('GetBaiduChannel'); } /** * Retrieve information about a specific campaign. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign.html#rest-api-campaign-methods */ public toGetCampaign() { return this.to('GetCampaign'); } /** * Retrieve information about the activities performed by a campaign. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign-activities.html#rest-api-campaign-activities-methods */ public toGetCampaignActivities() { return this.to('GetCampaignActivities'); } /** * Retrieves (queries) pre-aggregated data for a standard metric that applies to a campaign. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-campaigns-campaign-id-kpis-daterange-kpi-name.html#GetCampaignDateRangeKpi */ public toGetCampaignDateRangeKpi() { return this.to('GetCampaignDateRangeKpi'); } /** * Retrieve information about a specific campaign version. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign-version.html#rest-api-campaign-version-methods */ public toGetCampaignVersion() { return this.to('GetCampaignVersion'); } /** * Retrieve information about the current and prior versions of a campaign. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign-versions.html#rest-api-campaign-versions-methods */ public toGetCampaignVersions() { return this.to('GetCampaignVersions'); } /** * Retrieve information about all campaigns for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaigns.html#rest-api-campaigns-methods */ public toGetCampaigns() { return this.to('GetCampaigns'); } /** * Get all channels information for your app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-channels.html#rest-api-channels-methods */ public toGetChannels() { return this.to('GetChannels'); } /** * Obtain information about the email channel in an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-email-channel.html#rest-api-email-channel-methods */ public toGetEmailChannel() { return this.to('GetEmailChannel'); } /** * Retrieve information about a specific or the active version of an email template. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-email.html#templates-template-name-email-http-methods */ public toGetEmailTemplate() { return this.to('GetEmailTemplate'); } /** * Retrieve information about a specific endpoint. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-endpoint.html#rest-api-endpoint-methods */ public toGetEndpoint() { return this.to('GetEndpoint'); } /** * Retrieve information about the event stream for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-event-stream.html#rest-api-event-stream-methods */ public toGetEventStream() { return this.to('GetEventStream'); } /** * Obtain information about a specific export job. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-export-jobs.html#rest-api-export-jobs-methods */ public toGetExportJob() { return this.to('GetExportJob'); } /** * Retrieve a list of all of the export jobs for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-export-jobs.html#rest-api-export-jobs-methods */ public toGetExportJobs() { return this.to('GetExportJobs'); } /** * Retrieve information about the GCM channel for an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-gcm-channel.html#rest-api-gcm-channel-methods */ public toGetGcmChannel() { return this.to('GetGcmChannel'); } /** * Retrieve information about a specific import job. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-import-job.html#rest-api-import-job-methods */ public toGetImportJob() { return this.to('GetImportJob'); } /** * Retrieve information about all import jobs for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-import-jobs.html#rest-api-import-jobs-methods */ public toGetImportJobs() { return this.to('GetImportJobs'); } /** * Retrieve information about a specific journey. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id.html#apps-application-id-journeys-journey-id-http-methods */ public toGetJourney() { return this.to('GetJourney'); } /** * Retrieves (queries) pre-aggregated data for a standard engagement metric that applies to a journey. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id-kpis-daterange-kpi-name.html#GetJourneyDateRangeKpi */ public toGetJourneyDateRangeKpi() { return this.to('GetJourneyDateRangeKpi'); } /** * Retrieves (queries) pre-aggregated data for a standard execution metric that applies to a journey activity. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id-activities-journey-activity-id-execution-metrics.html#GetJourneyExecutionActivityMetrics */ public toGetJourneyExecutionActivityMetrics() { return this.to('GetJourneyExecutionActivityMetrics'); } /** * Retrieves (queries) pre-aggregated data for a standard execution metric that applies to a journey. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id-execution-metrics.html#GetJourneyExecutionMetrics */ public toGetJourneyExecutionMetrics() { return this.to('GetJourneyExecutionMetrics'); } /** * Retrieve information about a specific or the active version of an push notification template. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html#templates-template-name-push-http-methods */ public toGetPushTemplate() { return this.to('GetPushTemplate'); } /** * Retrieve information about an Amazon Pinpoint configuration for a recommender model. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders-recommender-id.html#GetRecommenderConfiguration */ public toGetRecommenderConfiguration() { return this.to('GetRecommenderConfiguration'); } /** * Retrieve information about all the recommender model configurations that are associated with an Amazon Pinpoint account. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders.html#GetRecommenderConfigurations */ public toGetRecommenderConfigurations() { return this.to('GetRecommenderConfigurations'); } /** * Grants permission to mobiletargeting:GetReports * * Access Level: Read */ public toGetReports() { return this.to('GetReports'); } /** * Retrieve information about a specific segment. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segment.html#rest-api-segment-methods */ public toGetSegment() { return this.to('GetSegment'); } /** * Retrieve information about jobs that export endpoint definitions from segments to Amazon S3. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-export-jobs.html#rest-api-export-jobs-methods */ public toGetSegmentExportJobs() { return this.to('GetSegmentExportJobs'); } /** * Retrieve information about jobs that create segments by importing endpoint definitions from . * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-import-jobs.html#rest-api-import-jobs-methods */ public toGetSegmentImportJobs() { return this.to('GetSegmentImportJobs'); } /** * Retrieve information about a specific segment version. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segment-version.html#rest-api-segment-version-methods */ public toGetSegmentVersion() { return this.to('GetSegmentVersion'); } /** * Retrieve information about the current and prior versions of a segment. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segment-versions.html#rest-api-segment-versions-methods */ public toGetSegmentVersions() { return this.to('GetSegmentVersions'); } /** * Retrieve information about the segments for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segments.html#rest-api-segments-methods */ public toGetSegments() { return this.to('GetSegments'); } /** * Obtain information about the SMS channel in an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-sms-channel.html#rest-api-sms-channel-methods */ public toGetSmsChannel() { return this.to('GetSmsChannel'); } /** * Retrieve information about a specific or the active version of an sms message template. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-sms.html#templates-template-name-sms-http-methods */ public toGetSmsTemplate() { return this.to('GetSmsTemplate'); } /** * Retrieve information about the endpoints that are associated with a user ID. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-user.html#rest-api-user-methods */ public toGetUserEndpoints() { return this.to('GetUserEndpoints'); } /** * Obtain information about the Voice channel in an app. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-voice-channel.html#rest-api-voice-channel-methods */ public toGetVoiceChannel() { return this.to('GetVoiceChannel'); } /** * Retrieve information about a specific or the active version of a voice message template. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-voice.html#templates-template-name-voice-http-methods */ public toGetVoiceTemplate() { return this.to('GetVoiceTemplate'); } /** * Retrieve information about all journeys for an app. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys.html#apps-application-id-journeys-http-methods */ public toListJourneys() { return this.to('ListJourneys'); } /** * List tags for a resource. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-tags.html#rest-api-tags-methods-get */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Retrieve all versions about a specific template. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-template-type-versions.html#templates-template-name-template-type-versions-http-methods */ public toListTemplateVersions() { return this.to('ListTemplateVersions'); } /** * Retrieve metadata about the queried templates. * * Access Level: List * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates.html#templates-http-methods */ public toListTemplates() { return this.to('ListTemplates'); } /** * Obtain metadata for a phone number, such as the number type (mobile, landline, or VoIP), location, and provider. * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-phone-number-validate.html#rest-api-phone-number-validate-methods */ public toPhoneNumberValidate() { return this.to('PhoneNumberValidate'); } /** * Create or update an event stream for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-event-stream.html#rest-api-event-stream-methods */ public toPutEventStream() { return this.to('PutEventStream'); } /** * Create or update events for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-events.html#rest-api-events-methods */ public toPutEvents() { return this.to('PutEvents'); } /** * Used to remove the attributes for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-app.html#rest-api-app-methods */ public toRemoveAttributes() { return this.to('RemoveAttributes'); } /** * Send an SMS message or push notification to specific endpoints. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-messages.html#rest-api-messages-methods */ public toSendMessages() { return this.to('SendMessages'); } /** * Send an SMS message or push notification to all endpoints that are associated with a specific user ID. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-users-messages.html#rest-api-users-messages-methods */ public toSendUsersMessages() { return this.to('SendUsersMessages'); } /** * Adds tags to a resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-tags.html#rest-api-tags-methods-post */ public toTagResource() { return this.to('TagResource'); } /** * Removes tags from a resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-tags.html#rest-api-tags-methods-delete */ public toUntagResource() { return this.to('UntagResource'); } /** * Update the Amazon Device Messaging (ADM) channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-adm-channel.html#rest-api-adm-channel-methods */ public toUpdateAdmChannel() { return this.to('UpdateAdmChannel'); } /** * Update the Apple Push Notification service (APNs) channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-channel.html#rest-api-apns-channel-methods */ public toUpdateApnsChannel() { return this.to('UpdateApnsChannel'); } /** * Update the Apple Push Notification service (APNs) sandbox channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-sandbox-channel.html#rest-api-apns-sandbox-channel-methods */ public toUpdateApnsSandboxChannel() { return this.to('UpdateApnsSandboxChannel'); } /** * Update the Apple Push Notification service (APNs) VoIP channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-channel.html#rest-api-apns-voip-channel-methods */ public toUpdateApnsVoipChannel() { return this.to('UpdateApnsVoipChannel'); } /** * Update the Apple Push Notification service (APNs) VoIP sandbox channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-apns-voip-sandbox-channel.html#rest-api-apns-voip-sandbox-channel-methods */ public toUpdateApnsVoipSandboxChannel() { return this.to('UpdateApnsVoipSandboxChannel'); } /** * Update the default settings for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-settings.html#rest-api-settings-methods */ public toUpdateApplicationSettings() { return this.to('UpdateApplicationSettings'); } /** * Update the Baidu channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-baidu-channel.html#rest-api-baidu-channel-methods */ public toUpdateBaiduChannel() { return this.to('UpdateBaiduChannel'); } /** * Update a specific campaign. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaign.html#rest-api-campaign-methods */ public toUpdateCampaign() { return this.to('UpdateCampaign'); } /** * Update the email channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-email-channel.html#rest-api-email-channel-methods */ public toUpdateEmailChannel() { return this.to('UpdateEmailChannel'); } /** * Update a specific email template under the same version or generate a new version. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-email.html#templates-template-name-email-http-methods */ public toUpdateEmailTemplate() { return this.to('UpdateEmailTemplate'); } /** * Create an endpoint or update the information for an endpoint. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-endpoint.html#rest-api-endpoint-methods */ public toUpdateEndpoint() { return this.to('UpdateEndpoint'); } /** * Create or update endpoints as a batch operation. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-endpoints.html#rest-api-endpoints-methods */ public toUpdateEndpointsBatch() { return this.to('UpdateEndpointsBatch'); } /** * Update the Firebase Cloud Messaging (FCM) or Google Cloud Messaging (GCM) API key that allows to send push notifications to your Android app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-gcm-channel.html#rest-api-gcm-channel-methods */ public toUpdateGcmChannel() { return this.to('UpdateGcmChannel'); } /** * Update a specific journey. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id.html#apps-application-id-journeys-journey-id-http-methods */ public toUpdateJourney() { return this.to('UpdateJourney'); } /** * Update a specific journey state. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys-journey-id-state.html#apps-application-id-journeys-journey-id-state-http-methods */ public toUpdateJourneyState() { return this.to('UpdateJourneyState'); } /** * Update a specific push notification template under the same version or generate a new version. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html#templates-template-name-push-http-methods */ public toUpdatePushTemplate() { return this.to('UpdatePushTemplate'); } /** * Update an Amazon Pinpoint configuration for a recommender model. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders-recommender-id.html#UpdateRecommenderConfiguration */ public toUpdateRecommenderConfiguration() { return this.to('UpdateRecommenderConfiguration'); } /** * Update a specific segment. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segment.html#rest-api-segment-methods */ public toUpdateSegment() { return this.to('UpdateSegment'); } /** * Update the SMS channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-sms-channel.html#rest-api-sms-channel-methods */ public toUpdateSmsChannel() { return this.to('UpdateSmsChannel'); } /** * Update a specific sms message template under the same version or generate a new version. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-sms.html#templates-template-name-sms-http-methods */ public toUpdateSmsTemplate() { return this.to('UpdateSmsTemplate'); } /** * Upate the active version parameter of a specific template. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-template-type-versions.html#templates-template-name-template-type-versions-http-methods */ public toUpdateTemplateActiveVersion() { return this.to('UpdateTemplateActiveVersion'); } /** * Update the Voice channel for an app. * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-voice-channel.html#rest-api-voice-channel-methods */ public toUpdateVoiceChannel() { return this.to('UpdateVoiceChannel'); } /** * Update a specific voice message template under the same version or generate a new version. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-voice.html#templates-template-name-voice-http-methods */ public toUpdateVoiceTemplate() { return this.to('UpdateVoiceTemplate'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateApp", "CreateCampaign", "CreateEmailTemplate", "CreateExportJob", "CreateImportJob", "CreateJourney", "CreatePushTemplate", "CreateRecommenderConfiguration", "CreateSegment", "CreateSmsTemplate", "CreateVoiceTemplate", "DeleteAdmChannel", "DeleteApnsChannel", "DeleteApnsSandboxChannel", "DeleteApnsVoipChannel", "DeleteApnsVoipSandboxChannel", "DeleteApp", "DeleteBaiduChannel", "DeleteCampaign", "DeleteEmailChannel", "DeleteEmailTemplate", "DeleteEndpoint", "DeleteEventStream", "DeleteGcmChannel", "DeleteJourney", "DeletePushTemplate", "DeleteRecommenderConfiguration", "DeleteSegment", "DeleteSmsChannel", "DeleteSmsTemplate", "DeleteUserEndpoints", "DeleteVoiceChannel", "DeleteVoiceTemplate", "PutEventStream", "PutEvents", "RemoveAttributes", "SendMessages", "SendUsersMessages", "UpdateAdmChannel", "UpdateApnsChannel", "UpdateApnsSandboxChannel", "UpdateApnsVoipChannel", "UpdateApnsVoipSandboxChannel", "UpdateApplicationSettings", "UpdateBaiduChannel", "UpdateCampaign", "UpdateEmailChannel", "UpdateEmailTemplate", "UpdateEndpoint", "UpdateEndpointsBatch", "UpdateGcmChannel", "UpdateJourney", "UpdateJourneyState", "UpdatePushTemplate", "UpdateRecommenderConfiguration", "UpdateSegment", "UpdateSmsChannel", "UpdateSmsTemplate", "UpdateTemplateActiveVersion", "UpdateVoiceChannel", "UpdateVoiceTemplate" ], "Read": [ "GetAdmChannel", "GetApnsChannel", "GetApnsSandboxChannel", "GetApnsVoipChannel", "GetApnsVoipSandboxChannel", "GetApp", "GetApplicationDateRangeKpi", "GetApps", "GetBaiduChannel", "GetCampaign", "GetCampaignDateRangeKpi", "GetCampaignVersion", "GetEmailChannel", "GetEmailTemplate", "GetEndpoint", "GetEventStream", "GetExportJob", "GetGcmChannel", "GetImportJob", "GetJourney", "GetJourneyDateRangeKpi", "GetJourneyExecutionActivityMetrics", "GetJourneyExecutionMetrics", "GetPushTemplate", "GetRecommenderConfiguration", "GetReports", "GetSegment", "GetSegmentVersion", "GetSmsChannel", "GetSmsTemplate", "GetUserEndpoints", "GetVoiceChannel", "GetVoiceTemplate", "ListTagsForResource", "PhoneNumberValidate" ], "List": [ "GetApplicationSettings", "GetCampaignActivities", "GetCampaignVersions", "GetCampaigns", "GetChannels", "GetExportJobs", "GetImportJobs", "GetRecommenderConfigurations", "GetSegmentExportJobs", "GetSegmentImportJobs", "GetSegmentVersions", "GetSegments", "ListJourneys", "ListTemplateVersions", "ListTemplates" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type apps to the statement * * https://docs.aws.amazon.com/pinpoint/latest/developerguide/gettingstarted.html#gettingstarted-addapp * * @param appId - Identifier for the appId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onApps(appId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:apps/${AppId}'; arn = arn.replace('${AppId}', appId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type campaigns to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-campaigns.html * * @param appId - Identifier for the appId. * @param campaignId - Identifier for the campaignId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onCampaigns(appId: string, campaignId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:apps/${AppId}/campaigns/${CampaignId}'; arn = arn.replace('${AppId}', appId); arn = arn.replace('${CampaignId}', campaignId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type journeys to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/apps-application-id-journeys.html * * @param appId - Identifier for the appId. * @param journeyId - Identifier for the journeyId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onJourneys(appId: string, journeyId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:apps/${AppId}/journeys/${JourneyId}'; arn = arn.replace('${AppId}', appId); arn = arn.replace('${JourneyId}', journeyId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type segments to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/rest-api-segments.html * * @param appId - Identifier for the appId. * @param segmentId - Identifier for the segmentId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onSegments(appId: string, segmentId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:apps/${AppId}/segments/${SegmentId}'; arn = arn.replace('${AppId}', appId); arn = arn.replace('${SegmentId}', segmentId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type templates to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/templates.html * * @param templateName - Identifier for the templateName. * @param channelType - Identifier for the channelType. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onTemplates(templateName: string, channelType: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:templates/${TemplateName}/${ChannelType}'; arn = arn.replace('${TemplateName}', templateName); arn = arn.replace('${ChannelType}', channelType); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type recommenders to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/recommenders.html * * @param recommenderId - Identifier for the recommenderId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onRecommenders(recommenderId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:recommenders/${RecommenderId}'; arn = arn.replace('${RecommenderId}', recommenderId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type phone-number-validate to the statement * * https://docs.aws.amazon.com/pinpoint/latest/apireference/phone-number-validate.html * * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onPhoneNumberValidate(account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mobiletargeting:${Region}:${Account}:phone/number/validate'; arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as fs from 'fs'; import { generateHTMLPage } from '@hint/utils-create-server'; import { getHintPath, HintTest, testHint } from '@hint/utils-tests-helpers'; import { Severity } from '@hint/utils-types'; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const hintPath = getHintPath(__filename); // Images const appleTouchIconLinkTag = '<link rel="apple-touch-icon" href="/apple-touch-icon.png">'; /* eslint-disable no-sync */ const image152x152 = fs.readFileSync(`${__dirname}/fixtures/apple-touch-icon152x152.png`); const image167x167 = fs.readFileSync(`${__dirname}/fixtures/apple-touch-icon167x167.png`); const image180x180 = fs.readFileSync(`${__dirname}/fixtures/apple-touch-icon180x180.png`); const imageThatIsNotSquare = fs.readFileSync(`${__dirname}/fixtures/not-square.png`); const imageWithIncorrectDimensions100x100 = fs.readFileSync(`${__dirname}/fixtures/incorrect-dimensions100x100.png`); const imageWithIncorrectDimensions200x200 = fs.readFileSync(`${__dirname}/fixtures/incorrect-dimensions200x200.png`); const imageWithIncorrectFileFormat = fs.readFileSync(`${__dirname}/fixtures/incorrect-file-format.png`); /* eslint-enable no-sync */ // Error messages const elementHasEmptyHrefAttributeErrorMessage = `The 'apple-touch-icon' link element should have a non-empty 'href' attribute.`; const elementHasIncorrectRelAttributeErrorMessage = `The 'apple-touch-icon' link element should have 'rel="apple-touch-icon"'.`; const elementNotSpecifiedErrorMessage = `The 'apple-touch-icon' link element was not specified.`; const elementNotSpecifiedInHeadErrorMessage = `The 'apple-touch-icon' link element should be specified in the '<head>'.`; const fileCouldNotBeFetchedErrorMessage = `The 'apple-touch-icon' could not be fetched (status code: 404).`; const fileHasIncorrectSizeErrorMessage = `The 'apple-touch-icon' size is not recommended. Size should be 120x120, 152x152, 167x167, or 180x180.`; const fileIsInvalidPNGErrorMessage = `The 'apple-touch-icon' should be a valid PNG image.`; const fileIsNotPNGErrorMessage = `The 'apple-touch-icon' should be a PNG image.`; const fileRequestFailedErrorMessage = `The 'apple-touch-icon' could not be fetched (request failed).`; const elementDuplicatedErrorMessage = `The 'apple-touch-icon' link element is not needed as one was already specified.`; const generateImageData = (content: Buffer = image180x180): Object => { return { content, headers: { 'Content-Type': 'image/png' } }; }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const tests: HintTest[] = [ { name: `Resource is not an HTML document`, serverConfig: { '/': { headers: { 'Content-Type': 'image/png' } } } }, { name: `'apple-touch-icon' is not specified and no manifest in page`, serverConfig: generateHTMLPage('<link>') }, { name: `'apple-touch-icon' is not specified and manifest in page`, reports: [{ message: elementNotSpecifiedErrorMessage, severity: Severity.error }], serverConfig: generateHTMLPage('<link rel="manifest" href="manifest.webmanifest">') }, { name: `'apple-touch-icon' has 'rel="apple-touch-icon-precomposed"`, reports: [{ message: elementHasIncorrectRelAttributeErrorMessage, severity: Severity.warning }], serverConfig: { '/': generateHTMLPage('<link rel="apple-touch-icon-precomposed" href="/apple-touch-icon-precomposed.png">'), '/apple-touch-icon-precomposed.png': generateImageData() } }, { name: `'apple-touch-icon' has 'rel="apple-touch-icon-precomposed apple-touch-icon"`, reports: [{ message: elementHasIncorrectRelAttributeErrorMessage, severity: Severity.warning }], serverConfig: { '/': generateHTMLPage('<link rel="apple-touch-icon-precomposed apple-touch-icon" href="/apple-touch-icon-precomposed.png">'), '/apple-touch-icon-precomposed.png': generateImageData() } }, { name: `'apple-touch-icon' has no 'href' attribute`, reports: [{ message: elementHasEmptyHrefAttributeErrorMessage, severity: Severity.error }], serverConfig: generateHTMLPage('<link rel="apple-touch-icon">') }, { name: `'apple-touch-icon' has 'href' attribute with no value`, reports: [{ message: elementHasEmptyHrefAttributeErrorMessage, severity: Severity.error }], serverConfig: generateHTMLPage('<link rel="apple-touch-icon" href>') }, { name: `'apple-touch-icon' has 'href' attribute with the value of empty string`, reports: [{ message: elementHasEmptyHrefAttributeErrorMessage, severity: Severity.error }], serverConfig: generateHTMLPage('<link rel="apple-touch-icon" href="">') }, { name: `'apple-touch-icon' is used correctly`, serverConfig: { '/': generateHTMLPage('<LINk ReL=" APPLE-touch-ICON" HrEf="/apple-touch-icon.png">'), '/apple-touch-icon.png': generateImageData() } }, { name: `'apple-touch-icon' is not PNG`, reports: [{ message: fileIsNotPNGErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': generateImageData(imageWithIncorrectFileFormat) } }, { name: `'apple-touch-icon' is not an image`, reports: [{ message: fileIsInvalidPNGErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': generateHTMLPage() } }, { name: `'apple-touch-icon' is not 180x180px`, reports: [{ message: fileHasIncorrectSizeErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': generateImageData(imageWithIncorrectDimensions100x100) } }, { name: `'apple-touch-icon' is not 180x180px and it's also not square`, reports: [{ message: fileHasIncorrectSizeErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': generateImageData(imageThatIsNotSquare) } }, { name: `'apple-touch-icon' could not be fetched`, reports: [{ message: fileCouldNotBeFetchedErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': { status: 404 } } }, { name: `'apple-touch-icon' file request failed`, reports: [{ message: fileRequestFailedErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(appleTouchIconLinkTag), '/apple-touch-icon.png': null } }, { name: `'apple-touch-icon' is specified in the '<body>'`, reports: [{ message: elementNotSpecifiedInHeadErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(undefined, appleTouchIconLinkTag), '/apple-touch-icon.png': generateImageData() } }, { name: `Multiple 'apple-touch-icon's are specified`, serverConfig: { '/': generateHTMLPage(` <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> `), '/apple-touch-icon-152x152.png': generateImageData(image152x152), '/apple-touch-icon-180x180.png': generateImageData(image180x180), '/apple-touch-icon.png': generateImageData(image167x167) } }, { name: `Multiple 'apple-touch-icon's are specified (one with not recommended size)`, reports: [{ message: fileHasIncorrectSizeErrorMessage, severity: Severity.warning }], serverConfig: { '/': generateHTMLPage(` <link rel="apple-touch-icon" sizes="100x100" href="/apple-touch-icon-100x100.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> `), '/apple-touch-icon-100x100.png': generateImageData(imageWithIncorrectDimensions100x100), '/apple-touch-icon.png': generateImageData() } }, { name: `Multiple 'apple-touch-icon's are specified (no recommended sizes)`, reports: [{ message: fileHasIncorrectSizeErrorMessage, severity: Severity.error }, { message: fileHasIncorrectSizeErrorMessage, severity: Severity.error }], serverConfig: { '/': generateHTMLPage(` <link rel="apple-touch-icon" sizes="100x100" href="/apple-touch-icon-100x100.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> `), '/apple-touch-icon-100x100.png': generateImageData(imageWithIncorrectDimensions100x100), '/apple-touch-icon.png': generateImageData(imageWithIncorrectDimensions200x200) } }, { name: `Duplicated 'apple-touch-icon's are specified`, reports: [{ message: elementDuplicatedErrorMessage, severity: Severity.warning }], serverConfig: { '/': generateHTMLPage(` <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> `), '/apple-touch-icon-152x152.png': generateImageData(image152x152), '/apple-touch-icon.png': generateImageData() } } ]; testHint(hintPath, tests);
the_stack
import * as chai from "chai"; import * as types from "../../src/constants/ActionTypes"; import getStore, { IObservableAppStore } from "../observableAppStore"; import MlsClientSimulator from "../mlsClient/mlsClient.simulator"; import actions from "../../src/actionCreators/actions"; import { defaultWorkspace } from "../testResources"; import { configureWorkspace, setInstrumentation, applyScaffolding } from "../../src/actionCreators/workspaceActionCreators"; import { suite } from "mocha-typescript"; import { encodeWorkspace, cloneWorkspace } from "../../src/workspaces"; import { IGistWorkspace } from "../../src/IMlsClient"; chai.should(); chai.use(require("chai-exclude")); suite("Workspace Action Creators", () => { var store: IObservableAppStore; beforeEach(() => { store = getStore(); }); it("initialise with default workspace", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace({ workspaceType: "script", files: [], buffers: [{ id: "Program.cs", content: "", position: 0 }], usings: [], language: "csharp" }), actions.setActiveBuffer("Program.cs") ]; configureWorkspace({ store }); store.getActions().should.deep.equal(expectedActions); }); it("initialise with workspace parameter", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(defaultWorkspace), actions.setActiveBuffer("Program.cs"), actions.setCodeSource("workspace") ]; configureWorkspace({ store, workspaceParameter: encodeWorkspace(defaultWorkspace) }); store.getActions().should.deep.equal(expectedActions); }); it("sets instrumentation", () => { const expectedAction = { type: types.SET_INSTRUMENTATION, enabled: true }; setInstrumentation(true).should.deep.equal(expectedAction); }); it("initialise with from parameter", () => { const expectedActions = [ actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace({ workspaceType: "script", files: [], buffers: [{ id: "Program.cs", content: "", position: 0 }], usings: [], language: "csharp" }), actions.setActiveBuffer("Program.cs"), actions.setCodeSource("http://www.microsoft.com") ]; configureWorkspace({ store, fromParameter: encodeURIComponent("http://www.microsoft.com") }); store.getActions().should.deep.equal(expectedActions); }); it("reports error if both workspace and from parameters are defined and defaults to workspace based initialization", () => { var newWorkSpace = cloneWorkspace(defaultWorkspace); const expectedActions = [ actions.error("parameter loading", "cannot define `workspace` and `from` simultaneously"), actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(newWorkSpace), actions.setActiveBuffer("Program.cs"), actions.setCodeSource("workspace") ]; configureWorkspace({ store, workspaceParameter: encodeWorkspace(newWorkSpace), fromParameter: encodeURIComponent("http://www.microsoft.com") }); store.getActions().should.deep.equal(expectedActions); }); it("reports error if both workspace and workspaceType parameters are defined and defaults to workspace based initialization", () => { var newWorkSpace = cloneWorkspace(defaultWorkspace); const expectedActions = [ actions.error("parameter loading", "cannot define `workspace` and `workspaceTypeParameter` simultaneously"), actions.setWorkspaceType("script"), actions.setWorkspaceLanguage("csharp"), actions.setWorkspace(newWorkSpace), actions.setActiveBuffer("Program.cs"), actions.setCodeSource("workspace") ]; configureWorkspace({ store, workspaceParameter: encodeWorkspace(newWorkSpace), workspaceTypeParameter: encodeURIComponent("console") }); store.getActions().should.deep.equal(expectedActions); }); it("loads a workspace from a Gist URL", async () => { const workspaceInfo: IGistWorkspace = { htmlUrl: "https://gist.github.com/df44833326fcc575e8169fccb9d41fc7", originType: "gist", rawFileUrls: [ { fileName: "Program.cs", url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/35765c05ddb54bc827419211a6b645473cdda7f9/FibonacciGenerator.cs" }, { fileName: "FibonacciGenerator.cs", url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/700a834733fa650d2a663ccd829f8a9d09b44642/Program.cs" }], workspace: { workspaceType: "console", buffers: [ { id: "Program.cs", content: "console code", position: 0 }, { id: "FibonacciGenerator.cs", content: "generator code", position: 0 }], } }; const expectedActions = [ actions.setWorkspaceInfo(workspaceInfo), actions.canShowGitHubPanel(false), actions.setWorkspace(workspaceInfo.workspace), actions.setWorkspaceLanguage("csharp"), actions.setActiveBuffer("FibonacciGenerator.cs"), actions.setCodeSource("workspace"), actions.loadCodeRequest("workspace"), actions.loadCodeSuccess(workspaceInfo.workspace.buffers[1].content, workspaceInfo.workspace.buffers[1].id) ]; store.configure([ actions.setClient(new MlsClientSimulator()) ]); await store.dispatch(actions.LoadWorkspaceFromGist("df44833326fcc575e8169fccb9d41fc7", "FibonacciGenerator.cs", "console")); store.getActions().should.deep.equal(expectedActions); }); it("loads a workspace from a Gist URL and select first buffer if not speficied", async () => { const workspaceInfo: IGistWorkspace = { htmlUrl: "https://gist.github.com/df44833326fcc575e8169fccb9d41fc7", originType: "gist", rawFileUrls: [ { fileName: "Program.cs", url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/35765c05ddb54bc827419211a6b645473cdda7f9/FibonacciGenerator.cs" }, { fileName: "FibonacciGenerator.cs", url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/700a834733fa650d2a663ccd829f8a9d09b44642/Program.cs" }], workspace: { workspaceType: "console", buffers: [ { id: "Program.cs", content: "console code", position: 0 }, { id: "FibonacciGenerator.cs", content: "generator code", position: 0 }], } }; const expectedActions = [ actions.setWorkspaceInfo(workspaceInfo), actions.canShowGitHubPanel(false), actions.setWorkspace(workspaceInfo.workspace), actions.setWorkspaceLanguage("csharp"), actions.setActiveBuffer(workspaceInfo.workspace.buffers[0].id), actions.setCodeSource("workspace"), actions.loadCodeRequest("workspace"), actions.loadCodeSuccess(workspaceInfo.workspace.buffers[0].content, workspaceInfo.workspace.buffers[0].id) ]; store.configure([ actions.setClient(new MlsClientSimulator()) ]); await store.dispatch(actions.LoadWorkspaceFromGist("df44833326fcc575e8169fccb9d41fc7", null, "console")); store.getActions().should.deep.equal(expectedActions); }); it("can apply scaffolding.None", () => { const expectedActions = [ actions.setWorkspace({ activeBufferId: "foo.cs", buffers: [{ content: "", id: "foo.cs", position: 0 }], files: [{ name: "foo.cs", text: "" }], workspaceType: "script", }), actions.setActiveBuffer("foo.cs"), actions.setCodeSource("workspace"), actions.loadCodeRequest("workspace"), actions.loadCodeSuccess("", "foo.cs") ]; store.dispatch(applyScaffolding("None", "foo.cs")) store.getActions().should.deep.equal(expectedActions); }); it("can apply scaffolding.Class", () => { const expectedActions = [ actions.setWorkspace({ activeBufferId: "foo.cs@scaffold", buffers: [{ content: "", id: "foo.cs@scaffold", position: 0 }], files: [{ name: "foo.cs", text: `using System; class C { #region scaffold #endregion }` }], workspaceType: "script", }), actions.setActiveBuffer("foo.cs@scaffold"), actions.setCodeSource("workspace"), actions.loadCodeRequest("workspace"), actions.loadCodeSuccess("", "foo.cs@scaffold") ]; store.dispatch(applyScaffolding("Class", "foo.cs", ["System"])) store.getActions().should.deep.equal(expectedActions); }); it("can apply scaffolding.Method", () => { const expectedActions = [ actions.setWorkspace({ activeBufferId: "foo.cs@scaffold", buffers: [{ content: "", id: "foo.cs@scaffold", position: 0 }], files: [{ name: "foo.cs", text: `using System; class C { public static void Main() { #region scaffold #endregion } }` }], workspaceType: "script", }), actions.setActiveBuffer("foo.cs@scaffold"), actions.setCodeSource("workspace"), actions.loadCodeRequest("workspace"), actions.loadCodeSuccess("", "foo.cs@scaffold") ]; store.dispatch(applyScaffolding("Method", "foo.cs", ["System"])) store.getActions().should.deep.equal(expectedActions); }); });
the_stack
import { DefinePlugin, DllReferencePlugin, DllPlugin } from "webpack"; import { AureliaDependenciesPlugin } from "./AureliaDependenciesPlugin"; import { ConventionDependenciesPlugin, Convention } from "./ConventionDependenciesPlugin"; import { DistPlugin } from "./DistPlugin"; import { GlobDependenciesPlugin } from "./GlobDependenciesPlugin"; import { HtmlDependenciesPlugin } from "./HtmlDependenciesPlugin"; import { InlineViewDependenciesPlugin } from "./InlineViewDependenciesPlugin"; import { ModuleDependenciesPlugin, ModuleDependenciesPluginOptions } from "./ModuleDependenciesPlugin"; import { PreserveExportsPlugin } from "./PreserveExportsPlugin"; import { PreserveModuleNamePlugin } from "./PreserveModuleNamePlugin"; import { SubFolderPlugin } from "./SubFolderPlugin"; import * as Webpack from 'webpack'; import { DependencyOptionsEx } from "./interfaces"; export type Polyfills = "es2015" | "es2016" | "esnext" | "none"; export type AureliaModuleConfig = keyof typeof configModuleNames | 'standard' | 'basic'; export interface Options { /** * if a string is given, include everything inside that folder, recursively. */ includeAll: false | string; aureliaApp?: string; /** * A single config or a list of configurations to ensure the AureliaPlugin can bundle appropriate modules for * the aurelia-loader to load at runtime. * * `aurelia-framework` exposes configuration helpers like `.standardConfiguration()` etc..., * that load plugins (`aurelia-templating-binding`, `aurelia-templating-resources`, `aurelia-templating-router` etc...), * but we can't know if they are actually used or not at build time. * * This config gives users the ability to indicate what are used at build time. * Custom config is performed in use code and can use `.moduleName()` like normal. */ aureliaConfig: AureliaModuleConfig | AureliaModuleConfig[]; /** * An application can use this config to specify what PAL module to use. * * Possible values are: * - aurelia-pal-browser * - aurelia-pal-worker * - aurelia-pal-nodejs * * By default, it'll be determined based on the webpack configuration. */ pal?: string; /** * A dist folder to look for in *all* modules. Possible values for * the core Aurelia modules are: * - es2015 * - commonjs * - amd * - native-modules * * Note: application may choose to have a different dist types for their modules, and not use the above modules. * * Note: In the future, multiple dist with fallback may be supported to help application specify the dist with as latest syntaxes as possible. */ dist: string; entry?: string | string[]; features: { ie?: boolean; svg?: boolean; unparser?: boolean; polyfills?: Polyfills; }, noHtmlLoader: boolean; noInlineView: boolean; noModulePathResolve: boolean; noWebpackLoader: boolean; moduleMethods: string[]; viewsFor: string; viewsExtensions: string | Convention | (string|Convention)[]; } // See comments inside the module to understand why this is used const emptyEntryModule = "aurelia-webpack-plugin/runtime/empty-entry"; export class AureliaPlugin { options: Options; constructor(options: Partial<Options> = {}) { const opts = this.options = Object.assign({ includeAll: <false>false, aureliaConfig: ["standard", "developmentLogging"], dist: "native-modules", features: {}, moduleMethods: [], noHtmlLoader: false, // Undocumented safety switch noInlineView: false, noModulePathResolve: false, noWebpackLoader: false, // Ideally we would like _not_ to process conventions in node_modules, // because they should be using @useView and not rely in convention in // the first place. Unfortunately at this point many libs do use conventions // so it's just more helpful for users to process them. // As unlikely as it may seem, a common offender here is tslib, which has // matching (yet unrelated) html files in its distribution. So I am making // a quick exception for that. viewsFor: "**/!(tslib)*.{ts,js}", viewsExtensions: ".html", }, options); if (opts.entry) { opts.entry = Array.isArray(opts.entry) ? opts.entry : [opts.entry]; } opts.features = Object.assign({ ie: true, svg: true, unparser: true, polyfills: <"es2015">"es2015", }, options.features); } apply(compiler: Webpack.Compiler) { const opts = this.options; const features = opts.features; let needsEmptyEntry = false; let dllPlugin = compiler.options.plugins.some(p => p instanceof DllPlugin); let dllRefPlugins = compiler.options.plugins.filter(p => p instanceof DllReferencePlugin); // Make sure the loaders are easy to load at the root like `aurelia-webpack-plugin/html-resource-loader` let resolveLoader = compiler.options.resolveLoader; let alias = resolveLoader.alias || (resolveLoader.alias = {}); alias["aurelia-webpack-plugin"] = "aurelia-webpack-plugin/dist"; // Our async! loader is in fact just bundle-loader!. alias["async"] = "bundle-loader"; // For my own sanity when working on this plugin with `yarn link`, // make sure neither webpack nor Node resolve symlinks. if ("NODE_PRESERVE_SYMLINKS" in process.env) { resolveLoader.symlinks = false; compiler.options.resolve.symlinks = false; } // If we aren't building a DLL, "main" is the default entry point // Note that the 'in' check is because someone may explicitly set aureliaApp to undefined if (!dllPlugin && !("aureliaApp" in opts)) { opts.aureliaApp = "main"; } // Uses DefinePlugin to cut out optional features const defines: any = { AURELIA_WEBPACK_2_0: "true" }; if (!features.ie) defines.FEATURE_NO_IE = "true"; if (!features.svg) defines.FEATURE_NO_SVG = "true"; if (!features.unparser) defines.FEATURE_NO_UNPARSER = "true"; definePolyfills(defines, features.polyfills!); // Add some dependencies that are not documented with PLATFORM.moduleName // because they are determined at build-time. const dependencies: ModuleDependenciesPluginOptions = { // PAL for target "aurelia-bootstrapper": "pal" in opts ? opts.pal : { name: getPAL(compiler.options.target), exports: ['initialize'] }, // `aurelia-framework` exposes configuration helpers like `.standardConfiguration()`, // that load plugins, but we can't know if they are actually used or not. // User indicates what he uses at build time in `aureliaConfig` option. // Custom config is performed in use code and can use `.moduleName()` like normal. "aurelia-framework": getConfigModules(opts.aureliaConfig), }; let globalDependencies: (string|DependencyOptionsEx)[] = []; if (opts.dist) { // This plugin enables easy switching to a different module distribution (default for Aurelia is dist/commonjs). let resolve = compiler.options.resolve; let plugins = resolve.plugins || (resolve.plugins = []); plugins.push(new DistPlugin(opts.dist)); } if (!opts.noModulePathResolve) { // This plugin enables sub-path in modules that are not at the root (e.g. in a /dist folder), // for example aurelia-chart/pie might resolve to aurelia-chart/dist/commonjs/pie let resolve = compiler.options.resolve; let plugins = resolve.plugins || (resolve.plugins = []); plugins.push(new SubFolderPlugin()); } if (opts.includeAll) { // Grab everything approach // This plugin ensures that everything in /src is included in the bundle. // This prevents splitting in several chunks but is super easy to use and setup, // no change in existing code or PLATFORM.nameModule() calls are required. new GlobDependenciesPlugin({ [emptyEntryModule]: opts.includeAll + "/**" }).apply(compiler); needsEmptyEntry = true; } else if (opts.aureliaApp) { // Add aurelia-app entry point. // When using includeAll, we assume it's already included globalDependencies.push({ name: opts.aureliaApp, exports: ["configure"] }); } if (!dllPlugin && dllRefPlugins.length > 0) { // Creates delegated entries for all Aurelia modules in DLLs. // This is required for aurelia-loader-webpack to find them. let aureliaModules = dllRefPlugins.map(plugin => { let content = plugin["options"].manifest.content; return Object.keys(content) .map(k => content[k].buildMeta["aurelia-id"]) .filter(id => !!id) as string[]; }); globalDependencies = globalDependencies.concat(...aureliaModules); } if (!dllPlugin && !opts.noWebpackLoader) { // Setup aurelia-loader-webpack as the module loader this.addEntry(compiler.options, ["aurelia-webpack-plugin/runtime/pal-loader-entry"]); } if (!opts.noHtmlLoader) { // Ensure that we trace HTML dependencies (always required because of 3rd party libs) // Note that this loader will be in last place, which is important // because it will process the file first, before any other loader. compiler.options.module.rules.push({ test: /\.html?$/i, use: "aurelia-webpack-plugin/html-requires-loader" }); } if (!opts.noInlineView) { new InlineViewDependenciesPlugin().apply(compiler); } if (globalDependencies.length > 0) { dependencies[emptyEntryModule] = globalDependencies; needsEmptyEntry = true; } if (needsEmptyEntry) { this.addEntry(compiler.options, emptyEntryModule); } compiler.hooks.compilation.tap('AureliaPlugin', (compilation, params) => { compilation.hooks.runtimeRequirementInTree .for(Webpack.RuntimeGlobals.require) .tap('AureliaPlugin', (chunk) => { compilation.addRuntimeModule(chunk, new AureliaExposeWebpackInternal()); }); }); // Aurelia libs contain a few global defines to cut out unused features new DefinePlugin(defines).apply(compiler); // Adds some dependencies that are not documented by `PLATFORM.moduleName` new ModuleDependenciesPlugin(dependencies).apply(compiler); // This plugin traces dependencies in code that are wrapped in PLATFORM.moduleName() calls new AureliaDependenciesPlugin(...opts.moduleMethods).apply(compiler); // This plugin adds dependencies traced by html-requires-loader // Note: the config extension point for this one is html-requires-loader.attributes. new HtmlDependenciesPlugin().apply(compiler); // This plugin looks for companion files by swapping extensions, // e.g. the view of a ViewModel. @useView and co. should use PLATFORM.moduleName(). // We use it always even with `includeAll` because libs often don't `@useView` (they should). new ConventionDependenciesPlugin(opts.viewsFor, opts.viewsExtensions).apply(compiler); // This plugin preserves module names for dynamic loading by aurelia-loader new PreserveModuleNamePlugin(dllPlugin).apply(compiler); // This plugin supports preserving specific exports names when dynamically loading modules // with aurelia-loader, while still enabling tree shaking all other exports. new PreserveExportsPlugin().apply(compiler); } addEntry(options: Webpack.WebpackOptionsNormalized, modules: string|string[]) { let webpackEntry = options.entry; let entries = Array.isArray(modules) ? modules : [modules]; // todo: // probably cant do much here? if (typeof webpackEntry === 'function') { return; } // If entry point unspecified in plugin options; use the first webpack entry point const pluginEntry = this.options.entry ?? [Object.keys(webpackEntry)[0]]; // Ensure array const pluginEntries = Array.isArray(pluginEntry) ? pluginEntry : [pluginEntry]; // Add runtime to each entry for (const k of pluginEntries) { // Verify that plugin options entry points are defined in webpack entry points if (!(k in webpackEntry)) { throw new Error('entry key "' + k + '" is not defined in Webpack build, cannot apply runtime.'); } let entry = webpackEntry[k]; entry.import?.unshift(...entries); } } }; function getPAL(target?: string | string[] | false) { if (target instanceof Array) { if (target.includes('web') || target.includes('es5')) { return 'aurelia-pal-browser'; } // not really sure what to pick from an array target = target[0]; } if (target === false) { throw new Error('Invalid target to build for AureliaPlugin.'); } switch (target) { case undefined: case "es5": case "web": return "aurelia-pal-browser"; case "webworker": return "aurelia-pal-worker"; case "electron-renderer": return "aurelia-pal-browser"; default: return "aurelia-pal-nodejs"; } } const configModules: { [config: string]: DependencyOptionsEx } = {}; let configModuleNames = { "defaultBindingLanguage": "aurelia-templating-binding", "router": "aurelia-templating-router", "history": "aurelia-history-browser", "defaultResources": "aurelia-templating-resources", "eventAggregator": "aurelia-event-aggregator", "developmentLogging": "aurelia-logging-console", }; // "configure" is the only method used by .plugin() for (let c in configModuleNames) configModules[c] = { name: configModuleNames[c], exports: ["configure"] }; // developmentLogging has a pre-task that uses ConsoleAppender configModules["developmentLogging"].exports!.push("ConsoleAppender"); function getConfigModules(config: string | string[]) { if (!config) return undefined; if (!Array.isArray(config)) config = [config]; // Expand "standard" let i = config.indexOf("standard"); if (i >= 0) config.splice(i, 1, "basic", "history", "router"); // Expand "basic" i = config.indexOf("basic"); if (i >= 0) config.splice(i, 1, "defaultBindingLanguage", "defaultResources", "eventAggregator"); return config.map(c => configModules[c]); } function definePolyfills(defines: any, polyfills: Polyfills) { if (polyfills === "es2015") return; defines.FEATURE_NO_ES2015 = "true"; if (polyfills === "es2016") return; defines.FEATURE_NO_ES2016 = "true"; if (polyfills === "esnext") return; defines.FEATURE_NO_ESNEXT = "true"; // "none" or invalid option. } class AureliaExposeWebpackInternal extends Webpack.RuntimeModule { constructor() { super("Aurelia expose webpack internal"); } /** * @returns {string} runtime code */ generate() { return Webpack.Template.asString([ "if (typeof __webpack_modules__ !== 'undefined') {", "__webpack_require__.m = __webpack_require__.m || __webpack_modules__;", "__webpack_require__.c = __webpack_require__.c || __webpack_module_cache__;", "}", ]); } }
the_stack
import ProtocolManager from "./protocolManager"; import AirUnpacker from "./airUnpacker"; import {UAParser} from "ua-parser-js"; import pako from "pako"; import {getInstallationID} from "../../util/installationUtils"; import AirPacker from "./airPacker"; import { AttachmentItem, ChatRenameAction, Conversation, ConversationItem, ConversationPreviewMessage, LinkedConversation, MessageItem, MessageModifier, ParticipantAction, StatusUpdate, StickerItem, TapbackItem } from "../../data/blocks"; import { AttachmentRequestErrorCode, ConnectionErrorCode, ConversationItemType, ConversationPreviewType, CreateChatErrorCode, MessageError, MessageErrorCode, MessageModifierType, MessageStatusCode, ParticipantActionType, TapbackType } from "../../data/stateCodes"; import {arrayBufferToHex, blobToArrayBuffer} from "../../util/fileUtils"; import SparkMD5 from "spark-md5"; import {BasicAccumulator} from "../transferAccumulator"; import {encryptData} from "shared/util/encryptionUtils"; import {generateConversationLocalID} from "shared/util/conversationUtils"; import ConversationTarget from "shared/data/conversationTarget"; const attachmentChunkSize = 2 * 1024 * 1024; //2 MiB //Top-level net header type values const nhtClose = 0; const nhtPing = 1; const nhtPong = 2; const nhtAuthentication = 101; const nhtMessageUpdate = 200; const nhtTimeRetrieval = 201; const nhtMassRetrieval = 202; const nhtMassRetrievalFile = 203; const nhtMassRetrievalFinish = 204; const nhtConversationUpdate = 205; const nhtModifierUpdate = 206; const nhtAttachmentReq = 207; const nhtAttachmentReqConfirm = 208; const nhtAttachmentReqFail = 209; const nhtLiteConversationRetrieval = 300; const nhtLiteThreadRetrieval = 301; const nhtSendResult = 400; const nhtSendTextExisting = 401; const nhtSendTextNew = 402; const nhtSendFileExisting = 403; const nhtSendFileNew = 404; const nhtCreateChat = 405; //State codes enum NRCMessageReceiptState { Idle = 0, Sent = 1, Delivered = 2, Read = 3 } enum NRCMessageDBState { OK, Unknown, //Unknown error code Network, //Network error Unregistered //Not registered with iMessage } //Result codes enum NRCAuthenticationResult { OK = 0, Unauthorized = 1, BadRequest = 2 } enum NRCAttachmentError { NotFound = 1, //File GUID not found NotSaved = 2, //File (on disk) not found Unreadable = 3, //No access to file IOError = 4 //I/O error } enum NRCSendResult { OK = 0, //Message sent successfully ScriptError = 1, //Some unknown AppleScript error BadRequest = 2, //Invalid data received Unauthorized = 3, //System rejected request to send message NoConversation = 4, //A valid conversation wasn't found RequestTimeout = 5 //File data blocks stopped being received } enum NRCCreateChatResult { OK = 0, ScriptError = 1, //Some unknown AppleScript error BadRequest = 2, //Invalid data received Unauthorized = 3 //System rejected request to send message } //Item types enum NSTConversationItemType { Message = 0, ParticipantAction = 1, ChatRename = 2 } enum NSTModifierType { Activity, Sticker, Tapback } enum NSTGroupActionType { Unknown = 0, Join = 1, Leave = 2 } type AMBrowser = "chrome" | "safari" | "firefox" | "edge" | "browser"; export default class ClientProtocol1 extends ProtocolManager { processData(data: ArrayBuffer, wasEncrypted: boolean): void { //Notifying the communications manager of a new incoming message this.communicationsManager.listener?.onPacket(); //Unpacking the message const unpacker = new AirUnpacker(data); const messageType = unpacker.unpackInt(); //Processing the message data if(wasEncrypted) { this.processDataSecure(messageType, unpacker); } else { this.processDataInsecure(messageType, unpacker); } } private processDataInsecure(messageType: number, unpacker: AirUnpacker) { switch(messageType) { case nhtClose: this.communicationsManager.disconnect(ConnectionErrorCode.Connection); break; case nhtPing: { //Replying with a pong const packer = AirPacker.get(); try { packer.packInt(nhtPong); this.dataProxy.send(packer.toArrayBuffer(), false); } finally { packer.reset(); } break; } case nhtAuthentication: this.handleMessageAuthentication(unpacker); break; } } private processDataSecure(messageType: number, unpacker: AirUnpacker) { switch(messageType) { case nhtMessageUpdate: case nhtTimeRetrieval: this.handleMessageUpdate(unpacker); break; case nhtConversationUpdate: this.handleConversationUpdate(unpacker); break; case nhtModifierUpdate: this.handleModifierUpdate(unpacker); break; case nhtAttachmentReq: this.handleMessageAttachmentRequest(unpacker); break; case nhtAttachmentReqConfirm: this.handleMessageAttachmentRequestConfirm(unpacker); break; case nhtAttachmentReqFail: this.handleMessageAttachmentRequestFail(unpacker); break; case nhtLiteConversationRetrieval: this.handleMessageLiteConversationRetrieval(unpacker); break; case nhtLiteThreadRetrieval: this.handleMessageLiteThreadRetrieval(unpacker); break; case nhtSendResult: this.handleMessageSendResult(unpacker); break; case nhtCreateChat: this.handleMessageCreateChat(unpacker); break; default: this.processDataInsecure(messageType, unpacker); break; } } private handleMessageAuthentication(unpacker: AirUnpacker) { //Stopping the timeout timer this.communicationsManager.stopTimeoutTimer(); //Reading the result code const resultCode = unpacker.unpackInt(); //Disconnecting if the authentication didn't go through if(resultCode !== NRCAuthenticationResult.OK) { switch(resultCode) { case NRCAuthenticationResult.BadRequest: this.communicationsManager.disconnect(ConnectionErrorCode.BadRequest); break; case NRCAuthenticationResult.Unauthorized: this.communicationsManager.disconnect(ConnectionErrorCode.Unauthorized); break; default: this.communicationsManager.disconnect(ConnectionErrorCode.Connection); break; } return; } //Reading the server's information const installationID = unpacker.unpackString(); const deviceName = unpacker.unpackString(); const systemVersion = unpacker.unpackString(); const softwareVersion = unpacker.unpackString(); //Notifying the communications manager this.communicationsManager.onHandshake(installationID, deviceName, systemVersion, softwareVersion); } private handleMessageUpdate(unpacker: AirUnpacker) { const messages = unpackArray(unpacker, unpackConversationItem).reverse(); this.communicationsManager.listener?.onMessageUpdate(messages); } private handleConversationUpdate(unpacker: AirUnpacker) { const conversations = unpackArray(unpacker, unpackRequestedConversation); this.communicationsManager.listener?.onConversationUpdate(conversations); } private handleModifierUpdate(unpacker: AirUnpacker) { const modifiers = unpackArray(unpacker, unpackModifier); this.communicationsManager.listener?.onModifierUpdate(modifiers); } private handleMessageAttachmentRequest(unpacker: AirUnpacker) { //Reading the response data const requestID = unpacker.unpackShort(); const requestIndex = unpacker.unpackInt(); const fileLength = requestIndex === 0 ? unpacker.unpackLong() : undefined; const isLast = unpacker.unpackBoolean(); const fileGUID = unpacker.unpackString(); const fileData = pako.ungzip(new Uint8Array(unpacker.unpackPayload())); if(requestIndex === 0) this.communicationsManager.listener?.onFileRequestStart(requestID, undefined, undefined, fileLength!, new BasicAccumulator(fileLength!)); this.communicationsManager.listener?.onFileRequestData(requestID, fileData); if(isLast) this.communicationsManager.listener?.onFileRequestComplete(requestID); } private handleMessageAttachmentRequestConfirm(unpacker: AirUnpacker) { //Reading the response data //const requestID = unpacker.unpackShort(); } private handleMessageAttachmentRequestFail(unpacker: AirUnpacker) { //Reading the response data const requestID = unpacker.unpackShort(); const errorCode = mapAttachmentErrorCode(unpacker.unpackInt()); //Notifying the communications manager this.communicationsManager.listener?.onFileRequestFail(requestID, errorCode); } private handleMessageLiteConversationRetrieval(unpacker: AirUnpacker) { const conversations = unpackArray(unpacker, unpackPreviewConversation); this.communicationsManager.listener?.onMessageConversations(conversations); } private handleMessageLiteThreadRetrieval(unpacker: AirUnpacker) { const chatGUID = unpacker.unpackString(); const firstMessageID: number | undefined = unpacker.unpackBoolean() ? unpacker.unpackLong() : undefined; //Unlike Android, the bottom of the chat is index 0 const conversationItems = unpackArray(unpacker, unpackConversationItem).reverse(); this.communicationsManager.listener?.onMessageThread(chatGUID, firstMessageID, conversationItems); } private handleMessageSendResult(unpacker: AirUnpacker) { const requestID = unpacker.unpackShort(); const errorCode = mapMessageErrorCode(unpacker.unpackInt()); const details = unpacker.unpackNullableString(); const messageError: MessageError | undefined = errorCode === undefined ? undefined : {code: errorCode, detail: details}; this.communicationsManager.listener?.onSendMessageResponse(requestID, messageError); } private handleMessageCreateChat(unpacker: AirUnpacker) { const requestID = unpacker.unpackShort(); const errorCode = mapCreateChatCode(unpacker.unpackInt()); const details = unpacker.unpackNullableString(); this.communicationsManager.listener?.onCreateChatResponse(requestID, errorCode, details); } sendPing(): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtPing); this.dataProxy.send(packer.toArrayBuffer(), false); } finally { packer.reset(); } return true; } async sendAuthenticationRequest(unpacker: AirUnpacker): Promise<boolean> { //Assembling the device information const uaParser = new UAParser(); const browser = uaParser.getBrowser(); const os = uaParser.getOS(); const browserName = (browser.name && browser.version) ? `${browser.name} ${browser.version}` : null; const platformName = (os.name && os.version) ? `${os.name} ${os.version}` : null; const installationID = getInstallationID(); let clientName: string; if(browserName && platformName) clientName = browserName + " — " + platformName; else if(browserName) clientName = browserName; else if(platformName) clientName = platformName; else clientName = "Unknown browser"; const platformID = mapBrowserAM(browser.name ?? "browser"); //Checking if the current protocol requires authentication if(unpacker.unpackBoolean()) { //Reading the transmission check const transmissionCheck = unpacker.unpackPayload(); const packer = AirPacker.get(); try { packer.packInt(nhtAuthentication); //Building the secure data let secureData: ArrayBuffer; { const securePacker = AirPacker.initialize(1024); securePacker.packPayload(transmissionCheck); securePacker.packString(installationID); securePacker.packString(clientName); securePacker.packString(platformID); secureData = securePacker.toArrayBuffer(); } //Encrypting the secure data and adding it to the original message packer.packPayload(await encryptData(secureData)); this.dataProxy.send(packer.toArrayBuffer(), false); } finally { packer.reset(); } } //Sending a response const packer = AirPacker.get(); try { packer.packInt(nhtAuthentication); packer.packString(installationID); packer.packString(clientName); packer.packString(platformID); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } sendMessage(requestID: number, conversation: ConversationTarget, message: string): boolean { const packer = AirPacker.get(); try { if(conversation.type === "linked") packer.packInt(nhtSendTextExisting); else packer.packInt(nhtSendTextNew); packer.packShort(requestID); if(conversation.type === "linked") packer.packString(conversation.guid); else { packer.packStringArray(conversation.members); packer.packString(conversation.service); } packer.packString(message); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } async sendFile(requestID: number, conversation: ConversationTarget, file: File, progressCallback: (bytesUploaded: number) => void): Promise<string> { const spark = new SparkMD5.ArrayBuffer(); try { //Reading the file let chunkIndex = 0; let readOffset = 0; while(readOffset < file.size) { const newOffset = readOffset + attachmentChunkSize; const chunkData: ArrayBuffer = await blobToArrayBuffer(file.slice(readOffset, newOffset)); //Uploading the data const packer = AirPacker.get(); try { if(conversation.type === "linked") packer.packInt(nhtSendFileExisting); else packer.packInt(nhtSendFileNew); packer.packShort(requestID); packer.packInt(chunkIndex); packer.packBoolean(newOffset >= file.size); //Is this the last part? if(conversation.type === "linked") packer.packString(conversation.guid); else packer.packStringArray(conversation.members); packer.packPayload(pako.gzip(new Uint8Array(chunkData))); if(chunkIndex === 0) { packer.packString(file.name); if(conversation.type === "unlinked") packer.packString(conversation.service); } this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } //Hashing the data spark.append(chunkData); //Updating the index and read offset chunkIndex++; readOffset = newOffset; //Updating the progress progressCallback(Math.min(readOffset, file.size)); } } catch(error) { return Promise.reject({code: MessageErrorCode.LocalIO} as MessageError); } //Returning with the file's MD5 hash return spark.end(false); } requestAttachmentDownload(requestID: number, attachmentGUID: string): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtAttachmentReq); packer.packShort(requestID); packer.packInt(attachmentChunkSize); packer.packString(attachmentGUID); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestLiteConversation(): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtLiteConversationRetrieval); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestConversationInfo(chatGUIDs: string[]): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtConversationUpdate); packer.packArrayHeader(chatGUIDs.length); for(const chatGUID of chatGUIDs) packer.packString(chatGUID); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestLiteThread(chatGUID: string, firstMessageID?: number): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtLiteThreadRetrieval); packer.packString(chatGUID); if(firstMessageID) { packer.packBoolean(true); packer.packLong(firstMessageID); } else { packer.packBoolean(false); } this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestChatCreation(requestID: number, members: string[], service: string): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtCreateChat); packer.packShort(requestID); packer.packArrayHeader(members.length); for(const member of members) packer.packString(member); packer.packString(service); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestRetrievalTime(timeLower: Date, timeUpper: Date): boolean { const packer = AirPacker.get(); try { packer.packInt(nhtTimeRetrieval); packer.packLong(timeLower.getTime()); packer.packLong(timeUpper.getTime()); this.dataProxy.send(packer.toArrayBuffer(), true); } finally { packer.reset(); } return true; } requestRetrievalID(idLower: number, timeLower: Date, timeUpper: Date): boolean { console.warn("Request retrieval ID not supported"); return false; } requestInstallRemoteUpdate(updateID: number): boolean { //Not supported return false; } requestFaceTimeLink(): boolean { //Not supported return false; } initiateFaceTimeCall(addresses: string[]): boolean { //Not supported return false; } handleIncomingFaceTimeCall(caller: string, accept: boolean): boolean { //Not supported return false; } dropFaceTimeCallServer(): boolean { //Not supported return false; } } function mapBrowserAM(browser: string): AMBrowser { switch(browser) { case "Chrome": case "Chromium": return "chrome"; case "Safari": case "Mobile Safari": return "safari"; case "Firefox": return "firefox"; case "Edge": return "edge"; default: return "browser"; } } function unpackPreviewConversation(unpacker: AirUnpacker): LinkedConversation { const guid = unpacker.unpackString(); const service = unpacker.unpackString(); const name = unpacker.unpackNullableString(); const membersLength = unpacker.unpackArrayHeader(); const members: string[] = []; for(let i = 0; i < membersLength; i++) members[i] = unpacker.unpackString(); const previewDate = new Date(unpacker.unpackLong()); /*const previewSender = */unpacker.unpackNullableString(); const previewText = unpacker.unpackNullableString(); const previewSendStyle = unpacker.unpackNullableString(); const previewAttachmentsLength = unpacker.unpackArrayHeader(); const previewAttachments: string[] = []; for(let i = 0; i < previewAttachmentsLength; i++) previewAttachments[i] = unpacker.unpackString(); return { localID: generateConversationLocalID(), guid: guid, service: service, name: name, members: members, preview: { type: ConversationPreviewType.Message, date: previewDate, text: previewText, sendStyle: previewSendStyle, attachments: previewAttachments }, unreadMessages: false, localOnly: false }; } function unpackRequestedConversation(unpacker: AirUnpacker): [string, LinkedConversation | undefined] { const guid = unpacker.unpackString(); const available = unpacker.unpackBoolean(); if(available) { //Unpack the rest of the conversation data and return it const service = unpacker.unpackString(); const name = unpacker.unpackNullableString(); const membersLength = unpacker.unpackArrayHeader(); const members: string[] = []; for(let i = 0; i < membersLength; i++) members[i] = unpacker.unpackString(); return [guid, { localID: generateConversationLocalID(), guid: guid, service: service, name: name, members: members, //Placeholder preview: { type: ConversationPreviewType.ChatCreation, date: new Date() }, unreadMessages: false, localOnly: false }]; } else { //Conversation not available return [guid, undefined]; } } function unpackArray<T>(unpacker: AirUnpacker, unpackerFunction: (unpacker: AirUnpacker) => T | null): T[] { //Creating the array const array: T[] = []; //Reading the items const count = unpacker.unpackArrayHeader(); for(let i = 0; i < count; i++) { const item = unpackerFunction(unpacker); if(item) array.push(item); } return array; } function unpackConversationItem(unpacker: AirUnpacker): ConversationItem | null { //Unpacking the shared data const itemType = mapCodeConversationItemType(unpacker.unpackInt()); const serverID = unpacker.unpackLong(); const guid = unpacker.unpackString(); const chatGuid = unpacker.unpackString(); const date = new Date(unpacker.unpackLong()); switch(itemType) { default: { console.warn(`Unknown conversation item type ${itemType}`); return null; } case ConversationItemType.Message: { const text = unpacker.unpackNullableString(); const subject = unpacker.unpackNullableString(); const sender = unpacker.unpackNullableString(); const attachments = unpackArray(unpacker, unpackAttachment); const stickers = unpackArray(unpacker, unpackModifier) as StickerItem[]; const tapbacks = unpackArray(unpacker, unpackModifier) as TapbackItem[]; const sendStyle = unpacker.unpackNullableString(); const statusCode = mapCodeMessageStatus(unpacker.unpackInt()); const errorCode = mapCodeDBError(unpacker.unpackInt()); const error: MessageError | undefined = errorCode ? {code: errorCode} : undefined; const dateRead = new Date(unpacker.unpackLong()); return { itemType: itemType, serverID: serverID, guid: guid, chatGuid: chatGuid, date: date, text: text, subject: subject, sender: sender, attachments: attachments, stickers: stickers, tapbacks: tapbacks, sendStyle: sendStyle, status: statusCode, error: error, statusDate: dateRead } as MessageItem; } case ConversationItemType.ParticipantAction: { const user = unpacker.unpackNullableString(); const target = unpacker.unpackNullableString(); const actionType = mapParticipantActionType(unpacker.unpackInt()); return { itemType: itemType, serverID: serverID, guid: guid, chatGuid: chatGuid, date: date, type: actionType, user: user, target: target } as ParticipantAction; } case ConversationItemType.ChatRenameAction: { const user = unpacker.unpackNullableString(); const chatName = unpacker.unpackNullableString(); return { itemType: itemType, serverID: serverID, guid: guid, chatGuid: chatGuid, date: date, user: user, chatName: chatName } as ChatRenameAction; } } } function unpackAttachment(unpacker: AirUnpacker): AttachmentItem { const guid = unpacker.unpackString(); const name = unpacker.unpackString(); const type = unpacker.unpackNullableString() ?? "application/octet-stream"; const size = unpacker.unpackLong(); const checksum = unpacker.unpackNullablePayload(); const checksumString = checksum && arrayBufferToHex(checksum); return { guid: guid, name: name, type: type, size: size, checksum: checksumString }; } function unpackModifier(unpacker: AirUnpacker): MessageModifier | null { //Unpacking the shared data const type = unpacker.unpackInt(); const messageGuid = unpacker.unpackString(); switch(type) { default: console.warn(`Unknown modifier item type ${type}`); return null; case NSTModifierType.Activity: { const status = mapCodeMessageStatus(unpacker.unpackInt()); const date = new Date(unpacker.unpackLong()); return { type: MessageModifierType.StatusUpdate, messageGuid: messageGuid, status: status, date: date } as StatusUpdate; } case NSTModifierType.Sticker: { const index = unpacker.unpackInt(); /*const fileGUID = */unpacker.unpackString(); const sender = unpacker.unpackNullableString(); const date = new Date(unpacker.unpackLong()); const data = pako.ungzip(new Uint8Array(unpacker.unpackPayload())); const dataType = unpacker.unpackString(); return { type: MessageModifierType.Sticker, messageGuid: messageGuid, messageIndex: index, sender: sender, date: date, dataType: dataType, data: data } as StickerItem; } case NSTModifierType.Tapback: { const index = unpacker.unpackInt(); const sender = unpacker.unpackNullableString(); const isAddition = unpacker.unpackBoolean(); const dbTapbackType = unpacker.unpackInt(); const tapbackType = mapTapbackType(dbTapbackType); if(tapbackType === undefined) { console.warn(`Unknown Apple tapback type ${dbTapbackType}`); return null; } return { type: MessageModifierType.Tapback, messageGuid: messageGuid, messageIndex: index, sender: sender, isAddition: isAddition, tapbackType: tapbackType } as TapbackItem; } } } function mapCodeConversationItemType(code: number): ConversationItemType | undefined { switch(code) { case NSTConversationItemType.Message: return ConversationItemType.Message; case NSTConversationItemType.ParticipantAction: return ConversationItemType.ParticipantAction; case NSTConversationItemType.ChatRename: return ConversationItemType.ChatRenameAction; default: return undefined; } } function mapCodeMessageStatus(code: number): MessageStatusCode { switch(code) { default: case NRCMessageReceiptState.Idle: return MessageStatusCode.Idle; case NRCMessageReceiptState.Sent: return MessageStatusCode.Sent; case NRCMessageReceiptState.Delivered: return MessageStatusCode.Delivered; case NRCMessageReceiptState.Read: return MessageStatusCode.Read; } } function mapCodeDBError(code: number): MessageErrorCode | undefined { switch(code) { case NRCMessageDBState.OK: return undefined; case NRCMessageDBState.Unknown: default: return MessageErrorCode.ServerUnknown; case NRCMessageDBState.Network: return MessageErrorCode.AppleNetwork; case NRCMessageDBState.Unregistered: return MessageErrorCode.AppleUnregistered; } } function mapParticipantActionType(code: number): ParticipantActionType { switch(code) { case NSTGroupActionType.Unknown: default: return ParticipantActionType.Unknown; case NSTGroupActionType.Join: return ParticipantActionType.Join; case NSTGroupActionType.Leave: return ParticipantActionType.Leave; } } function mapAttachmentErrorCode(code: number): AttachmentRequestErrorCode { switch(code) { case NRCAttachmentError.NotFound: return AttachmentRequestErrorCode.ServerNotFound; case NRCAttachmentError.NotSaved: return AttachmentRequestErrorCode.ServerNotSaved; case NRCAttachmentError.Unreadable: return AttachmentRequestErrorCode.ServerUnreadable; case NRCAttachmentError.IOError: return AttachmentRequestErrorCode.ServerIO; default: return AttachmentRequestErrorCode.ServerUnknown; } } function mapMessageErrorCode(code: number): MessageErrorCode | undefined { switch(code) { case NRCSendResult.OK: return undefined; case NRCSendResult.ScriptError: return MessageErrorCode.ServerExternal; case NRCSendResult.BadRequest: return MessageErrorCode.ServerBadRequest; case NRCSendResult.Unauthorized: return MessageErrorCode.ServerUnauthorized; case NRCSendResult.NoConversation: return MessageErrorCode.AppleNoConversation; case NRCSendResult.RequestTimeout: return MessageErrorCode.ServerTimeout; default: return MessageErrorCode.ServerUnknown; } } function mapCreateChatCode(code: number): CreateChatErrorCode | undefined { switch(code) { case NRCCreateChatResult.OK: return undefined; case NRCCreateChatResult.ScriptError: return CreateChatErrorCode.ScriptError; case NRCCreateChatResult.BadRequest: return CreateChatErrorCode.BadRequest; case NRCCreateChatResult.Unauthorized: return CreateChatErrorCode.Unauthorized; default: return CreateChatErrorCode.UnknownExternal; } } function mapTapbackType(code: number): TapbackType | undefined { switch(code) { case 0: return TapbackType.Love; case 1: return TapbackType.Like; case 2: return TapbackType.Dislike; case 3: return TapbackType.Laugh; case 4: return TapbackType.Emphasis; case 5: return TapbackType.Question; default: return undefined; } }
the_stack
import { Signal } from 'signals' import { ComponentRegistry, MeasurementDefaultParams } from '../globals' import { defaults, /*deepEqual, */createRingBuffer, RingBuffer, createSimpleDict, SimpleDict } from '../utils' import { smoothstep } from '../math/math-utils' import Component, { ComponentSignals, ComponentDefaultParameters } from './component' import RepresentationCollection from './representation-collection' import TrajectoryElement from './trajectory-element' import RepresentationElement from './representation-element' import { makeTrajectory } from '../trajectory/trajectory-utils' import { TrajectoryParameters } from '../trajectory/trajectory' import Selection from '../selection/selection' import Structure from '../structure/structure' import StructureView from '../structure/structure-view' import { superpose } from '../align/align-utils' import Stage from '../stage/stage' import StructureRepresentation, { StructureRepresentationParameters } from '../representation/structure-representation' import AtomProxy from '../proxy/atom-proxy' import { Vector3, Box3 } from 'three'; import { AngleRepresentationParameters } from '../representation/angle-representation'; import { AxesRepresentationParameters } from '../representation/axes-representation'; import { BallAndStickRepresentationParameters } from '../representation/ballandstick-representation'; import { CartoonRepresentationParameters } from '../representation/cartoon-representation'; import { ContactRepresentationParameters } from '../representation/contact-representation'; import { DihedralRepresentationParameters } from '../representation/dihedral-representation'; import { DihedralHistogramRepresentationParameters } from '../representation/dihedral-histogram-representation'; import { DistanceRepresentationParameters } from '../representation/distance-representation'; import { HyperballRepresentationParameters } from '../representation/hyperball-representation'; import { LabelRepresentationParameters } from '../representation/label-representation'; import { LineRepresentationParameters } from '../representation/line-representation'; import { PointRepresentationParameters } from '../representation/point-representation'; import { SurfaceRepresentationParameters } from '../representation/surface-representation'; import { RibbonRepresentationParameters } from '../representation/ribbon-representation'; import { RocketRepresentationParameters } from '../representation/rocket-representation'; import { TraceRepresentationParameters } from '../representation/trace-representation'; import { UnitcellRepresentationParameters } from '../representation/unitcell-representation'; import { SliceRepresentationParameters } from '../representation/slice-representation' import { MolecularSurfaceRepresentationParameters } from '../representation/molecularsurface-representation' import { DotRepresentationParameters } from '../representation/dot-representation' export type StructureRepresentationType = keyof StructureRepresentationParametersMap interface StructureRepresentationParametersMap { 'angle': AngleRepresentationParameters, 'axes' : AxesRepresentationParameters, 'backbone': BallAndStickRepresentationParameters, 'ball+stick': BallAndStickRepresentationParameters, 'base': BallAndStickRepresentationParameters, 'cartoon': CartoonRepresentationParameters, 'contact': ContactRepresentationParameters, 'dihedral': DihedralRepresentationParameters, 'dihedral-histogram': DihedralHistogramRepresentationParameters, 'distance': DistanceRepresentationParameters, 'dot': DotRepresentationParameters, 'helixorient': StructureRepresentationParameters, 'hyperball': HyperballRepresentationParameters, 'label': LabelRepresentationParameters, 'licorice': BallAndStickRepresentationParameters, 'line': LineRepresentationParameters, 'molecularsurface': MolecularSurfaceRepresentationParameters, 'point': PointRepresentationParameters, 'ribbon': RibbonRepresentationParameters, 'rocket': RocketRepresentationParameters, 'rope': CartoonRepresentationParameters, 'slice': SliceRepresentationParameters, 'spacefill': BallAndStickRepresentationParameters, 'surface': SurfaceRepresentationParameters, 'trace': TraceRepresentationParameters, 'tube': CartoonRepresentationParameters, 'unitcell': UnitcellRepresentationParameters, 'validation': StructureRepresentationParameters } export const StructureComponentDefaultParameters = Object.assign({ sele: '', defaultAssembly: '' }, ComponentDefaultParameters) export type StructureComponentParameters = typeof StructureComponentDefaultParameters export interface StructureComponentSignals extends ComponentSignals { trajectoryAdded: Signal // when a trajectory is added trajectoryRemoved: Signal // when a trajectory is removed defaultAssemblyChanged: Signal // on default assembly change } /** * Component wrapping a {@link Structure} object * * @example * // get a structure component by loading a structure file into the stage * stage.loadFile( "rcsb://4opj" ).then( function( structureComponent ){ * structureComponent.addRepresentation( "cartoon" ); * structureComponent.autoView(); * } ); */ class StructureComponent extends Component { readonly signals: StructureComponentSignals readonly parameters: StructureComponentParameters get defaultParameters () { return StructureComponentDefaultParameters } selection: Selection structureView: StructureView readonly trajList: TrajectoryElement[] = [] pickBuffer: RingBuffer<number> pickDict: SimpleDict<number[], number[]> lastPick?: number spacefillRepresentation: RepresentationElement distanceRepresentation: RepresentationElement angleRepresentation: RepresentationElement dihedralRepresentation: RepresentationElement measureRepresentations: RepresentationCollection constructor (stage: Stage, readonly structure: Structure, params: Partial<StructureComponentParameters> = {}) { super(stage, structure, Object.assign({ name: structure.name }, params)) this.signals = Object.assign(this.signals, { trajectoryAdded: new Signal(), trajectoryRemoved: new Signal(), defaultAssemblyChanged: new Signal() }) this.initSelection(this.parameters.sele) // this.pickBuffer = createRingBuffer(4) this.pickDict = createSimpleDict() this.spacefillRepresentation = this.addRepresentation('spacefill', { sele: 'none', opacity: MeasurementDefaultParams.opacity, color: MeasurementDefaultParams.color, disablePicking: true, radiusType: 'data' }, true) this.distanceRepresentation = this.addRepresentation( 'distance', MeasurementDefaultParams, true ) this.angleRepresentation = this.addRepresentation( 'angle', MeasurementDefaultParams, true ) this.dihedralRepresentation = this.addRepresentation( 'dihedral', MeasurementDefaultParams, true ) this.measureRepresentations = new RepresentationCollection([ this.spacefillRepresentation, this.distanceRepresentation, this.angleRepresentation, this.dihedralRepresentation ]) // this.setDefaultAssembly(this.parameters.defaultAssembly) } /** * Component type * @type {String} */ get type () { return 'structure' } /** * Initialize selection * @private * @param {String} sele - selection string * @return {undefined} */ initSelection (sele: string) { /** * Selection for {@link StructureComponent#structureView} * @private * @type {Selection} */ this.selection = new Selection(sele) /** * View on {@link StructureComponent#structure}. * Change its selection via {@link StructureComponent#setSelection}. * @type {StructureView} */ this.structureView = new StructureView( this.structure, this.selection ) this.selection.signals.stringChanged.add(() => { this.structureView.setSelection(this.selection) this.rebuildRepresentations() this.rebuildTrajectories() }) } /** * Set selection of {@link StructureComponent#structureView} * @param {String} string - selection string * @return {StructureComponent} this object */ setSelection (string: string) { this.parameters.sele = string this.selection.setString(string) return this } /** * Set the default assembly * @param {String} value - assembly name * @return {undefined} */ setDefaultAssembly (value:string) { // filter out non-exsisting assemblies if (this.structure.biomolDict[value] === undefined) value = '' // only set default assembly when changed if (this.parameters.defaultAssembly !== value) { const reprParams = { defaultAssembly: value } this.reprList.forEach(repr => repr.setParameters(reprParams)) this.measureRepresentations.setParameters(reprParams) this.parameters.defaultAssembly = value this.signals.defaultAssemblyChanged.dispatch(value) } return this } /** * Rebuild all representations * @return {undefined} */ rebuildRepresentations () { this.reprList.forEach((repr: RepresentationElement) => { repr.build() }) this.measureRepresentations.build() } /** * Rebuild all trajectories * @return {undefined} */ rebuildTrajectories () { this.trajList.forEach(trajComp => { trajComp.trajectory.setStructure(this.structureView) }) } updateRepresentations (what: any) { super.updateRepresentations(what) this.measureRepresentations.update(what) } /** * Overrides {@link Component.updateRepresentationMatrices} * to also update matrix for measureRepresentations */ updateRepresentationMatrices () { super.updateRepresentationMatrices() this.measureRepresentations.setParameters({ matrix: this.matrix }) } addRepresentation <K extends keyof StructureRepresentationParametersMap>( type: K, params: Partial<StructureRepresentationParametersMap[K]>|{defaultAssembly: string} = {}, hidden = false ) { params.defaultAssembly = this.parameters.defaultAssembly const reprComp = this._addRepresentation(type, this.structureView, params, hidden) if (!hidden) { reprComp.signals.parametersChanged.add(() => this.measureUpdate()) } return reprComp } /** * Add a new trajectory component to the structure */ addTrajectory (trajPath = '', params: { [k: string]: any } = {}) { const traj = makeTrajectory(trajPath, this.structureView, params as TrajectoryParameters) traj.signals.frameChanged.add(() => { this.updateRepresentations({ 'position': true }) }) const trajComp = new TrajectoryElement(this.stage, traj, params) this.trajList.push(trajComp) this.signals.trajectoryAdded.dispatch(trajComp) return trajComp } removeTrajectory (traj: TrajectoryElement) { const idx = this.trajList.indexOf(traj) if (idx !== -1) { this.trajList.splice(idx, 1) } traj.dispose() this.signals.trajectoryRemoved.dispatch(traj) } dispose () { // copy via .slice because side effects may change trajList this.trajList.slice().forEach(traj => traj.dispose()) this.trajList.length = 0 this.structure.dispose() this.measureRepresentations.dispose() super.dispose() } /** * Automatically center and zoom the component * @param {String|Integer} [sele] - selection string or duration if integer * @param {Integer} [duration] - duration of the animation, defaults to 0 * @return {undefined} */ autoView (duration?: number): any autoView (sele?: string|number, duration?: number) { if (typeof sele === 'number') { duration = sele sele = '' } this.stage.animationControls.zoomMove( this.getCenter(sele), this.getZoom(sele), defaults(duration, 0) ) } getBoxUntransformed (sele: string): Box3 { let bb if (sele) { bb = this.structureView.getBoundingBox(new Selection(sele)) } else { bb = this.structureView.boundingBox } return bb } getCenterUntransformed (sele: string): Vector3 { if (sele && typeof sele === 'string') { return this.structure.atomCenter(new Selection(sele)) } else { return this.structure.center } } superpose (component: StructureComponent, align: boolean, sele1: string, sele2: string) { superpose( this.structureView, component.structureView, align, sele1, sele2 ) this.updateRepresentations({ 'position': true }) return this } getMaxRepresentationRadius (atomIndex: number) { let maxRadius = 0 const atom = this.structure.getAtomProxy(atomIndex) this.eachRepresentation(reprElem => { if (reprElem.getVisibility()) { const repr: StructureRepresentation = reprElem.repr as any // TODO maxRadius = Math.max(repr.getAtomRadius(atom), maxRadius) } }) return maxRadius } measurePick (atom: AtomProxy) { const pickCount = this.pickBuffer.count if (this.lastPick === atom.index && pickCount >= 1) { if (pickCount > 1) { const atomList = this.pickBuffer.data const atomListSorted = this.pickBuffer.data.sort() if (this.pickDict.has(atomListSorted)) { this.pickDict.del(atomListSorted) } else { this.pickDict.add(atomListSorted, atomList) } if (pickCount === 2) { this.distanceRepresentation.setParameters({ atomPair: this.pickDict.values.filter(l => l.length === 2) }) } else if (pickCount === 3) { this.angleRepresentation.setParameters({ atomTriple: this.pickDict.values.filter(l => l.length === 3) }) } else if (pickCount === 4) { this.dihedralRepresentation.setParameters({ atomQuad: this.pickDict.values.filter(l => l.length === 4) }) } } this.pickBuffer.clear() this.lastPick = undefined } else { if (!this.pickBuffer.has(atom.index)) { this.pickBuffer.push(atom.index) } this.lastPick = atom.index } this.measureUpdate() } measureClear () { this.pickBuffer.clear() this.lastPick = undefined this.spacefillRepresentation.setSelection('none') } measureBuild () { const md = this.measureData() this.distanceRepresentation.setParameters({ atomPair: md.distance }) this.angleRepresentation.setParameters({ atomTriple: md.angle }) this.dihedralRepresentation.setParameters({ atomQuad: md.dihedral }) } measureUpdate () { const pickData = this.pickBuffer.data const radiusData: { [k: number]: number } = {} pickData.forEach(ai => { const r = Math.max(0.1, this.getMaxRepresentationRadius(ai)) radiusData[ ai ] = r * (2.3 - smoothstep(0.1, 2, r)) }) this.spacefillRepresentation.setSelection( pickData.length ? ( '@' + pickData.join(',') ) : 'none' ) if (pickData.length) this.spacefillRepresentation.setParameters({ radiusData }) } measureData () { const pv = this.pickDict.values return { distance: pv.filter(l => l.length === 2), angle: pv.filter(l => l.length === 3), dihedral: pv.filter(l => l.length === 4) } } /** * Remove all measurements, optionally limit to distance, angle or dihedral */ removeAllMeasurements (type?: MeasurementFlags) { const pd = this.pickDict const pv = pd.values const remove = function (len: number) { pv.filter(l => l.length === len).forEach(l => pd.del(l.slice().sort())) } if (!type || type & MeasurementFlags.Distance) remove(2) if (!type || type & MeasurementFlags.Angle) remove(3) if (!type || type & MeasurementFlags.Dihedral) remove(4) this.measureBuild() } /** * Remove a measurement given as a pair, triple, quad of atom indices */ removeMeasurement (atomList: number[]) { this.pickDict.del(atomList.slice().sort()) this.measureBuild() } /** * Add a measurement given as a pair, triple, quad of atom indices */ addMeasurement (atomList: number[]) { if (atomList.length < 2 || atomList.length > 4) return const atomListSorted = atomList.slice().sort() if (!this.pickDict.has(atomListSorted)) { this.pickDict.add(atomListSorted, atomList) } this.measureBuild() } } export const enum MeasurementFlags { Distance = 0x1, Angle = 0x2, Dihedral = 0x4 } ComponentRegistry.add('structure', StructureComponent) ComponentRegistry.add('structureview', StructureComponent) export default StructureComponent
the_stack
import * as angular from 'angular'; import { PersonaStyleEnum } from '../../core/personaStyleEnum'; import { PersonaSize } from '../persona/sizeEnum'; import { IPerson } from '../../core/person'; import { IconEnum } from '../icon/iconEnum'; let peopleSearchEventName: string = 'uif-people-search'; /** * @ngdoc interface * @name IPersonPicker * @module officeuifabric.components.peoplepicker * * @description * Helper interface used by the people picker directive. * * @property {interface} group - Reference to person's group * @property {Array of IPersonPicker} additionalData - Additional persons to populate under current person */ export interface IPersonPicker extends IPerson { group: IGroup; additionalData: IPersonPicker[]; } /** * @ngdoc interface * @name IGroup * @module officeuifabric.components.peoplepicker * * @description * Helper interface used by the people picker directive. * * @property {string} name - Reference to person's group * @property {number} order - Group order, used when displaying search result with groups */ export interface IGroup { name: string; order: number; } /** * @ngdoc class * @name GroupedPeopleData * @module officeuifabric.components.peoplepicker * * @description * Helper class used by the people picker directive. * * @property {interface} group - Group reference * @property {Array of IPersonPicker} people - Persons who belongs to this particular group */ export class GroupedPeopleData { public group: IGroup; public people: IPersonPicker[] = []; } /** * @ngdoc controller * @name PeoplePickerController * @module officeuifabric.components.peoplepicker * * @description * Controller used for the `<uif-people-picker>` directive. */ export class PeoplePickerController { public static $inject: string[] = ['$scope', '$filter', '$element']; constructor( private $scope: IPeoplePickerScope, private $filter: angular.IFilterService, private $element: angular.IAugmentedJQuery) { } public getSelectedPersons(): IPersonPicker[] { return this.$scope.selectedPersons; } public pickerType(): string { let type: string = this.$scope.type; if (angular.isUndefined(type)) { return PeoplePickerTypes[PeoplePickerTypes.grouped]; } return this.$scope.type; } public searchQuery(): string { return this.$scope.searchQuery; } public search(): void { this.bindPeople(this.$scope.searchQuery); this.$scope.$broadcast(peopleSearchEventName, this.searchQuery()); } public bindPeople(query?: string): void { let peopleData: IPersonPicker[] | angular.IPromise<IPersonPicker[]> = this.$scope.peopleCallback()(query); peopleData = peopleData || []; if (peopleData instanceof Array) { // array this.$scope.groups = this.createPeopleDataStructure(peopleData); } else if (typeof peopleData.then === 'function') { // promise, async scenario let searchMoreCtrl: PeopleSearchMoreController = angular.element(this.$element[0].querySelector('.ms-PeoplePicker-searchMore')) .controller(`${PeopleSearchMoreDirective.directiveName}`); if (searchMoreCtrl) { searchMoreCtrl.isSearching(true); } let that: PeoplePickerController = this; peopleData .then(data => { that.$scope.groups = this.createPeopleDataStructure(data); }) .finally(() => { if (searchMoreCtrl) { searchMoreCtrl.isSearching(false); } }); } } private createPeopleDataStructure(people: IPersonPicker[]): GroupedPeopleData[] { let peopleData: GroupedPeopleData[] = []; angular.forEach(people, (person: IPersonPicker) => { let existingGroups: GroupedPeopleData[] = this.$filter('filter')(peopleData, { group: person.group }); let hasGroup: boolean = existingGroups.length === 1; if (!hasGroup) { let newPeopleData: GroupedPeopleData = new GroupedPeopleData(); newPeopleData.group = person.group; newPeopleData.people.push(person); peopleData.push(newPeopleData); } else { let existingData: GroupedPeopleData = existingGroups[0]; existingData.people.push(person); } }); return peopleData; } } /** * @ngdoc enum * @name PeoplePickerTypes * @module officeuifabric.components.peoplepicker * * @description * Determines people picker type */ enum PeoplePickerTypes { grouped = 0, compact = 1, memberList = 2, facePile = 3 } /** * @ngdoc interface * @name IPeoplePickerAttributes * @module officeuifabric.components.peoplepicker * * @description * Interface describing attributes for people picker directive * * @property {string} uifType - People picker type * @property {string} ngDisabled - Disabled state varible name * @property {string} uifSingle - Allow only one person to be selected */ interface IPeoplePickerAttributes extends angular.IAttributes { uifType: string; ngDisabled: string; uifSingle: string; } /** * @ngdoc interface * @name IPeoplePickerScope * @module officeuifabric.components.peoplepicker * * @description * Interface describing scope for people picker directive * * @property {object} ngModel - Reference to NgModelController * @property {function} peopleCallback - Function called every time when search event occur * @property {string} searchQuery - Search query typed into the search input * @property {string} placeholder - Placeholder for the search input * @property {string} type - People picker type, based on PeoplePickerTypes enum * @property {number} delay - Used by type-ahead scenario, dealy after which search query will be run * @property {object} groups - Groups used by the people picker * @property {function} onPeoplePickerActive - Reference to NgModelController * @property {function} addPersonToSelectedPeople - Function called when user click on person in search results * @property {function} removePersonFromSelectedPeople - Function called when user click on close icon under selected persons * @property {array} selectedPersons - People picker's selected persons * @property {function} removePersonFromSearchResults - Function called when user click on close icon under search results * @property {function} onSearchKeyUp - Callback for the keyup event * @property {string} facePileHeader - FacePile header, used only in face pile mode * @property {boolean} ngDisabled - Support for ng-disabled directive * @property {string} ngChange - Expression to evaluate when selectedPersons changes */ export interface IPeoplePickerScope extends angular.IScope { ngModel: angular.INgModelController; peopleCallback: () => (query: string) => IPersonPicker[] | angular.IPromise<IPersonPicker[]>; searchQuery: string; placeholder: string; type: string; delay: number; groups: GroupedPeopleData[]; onPeoplePickerActive: ($event: KeyboardEvent | MouseEvent) => void; addPersonToSelectedPeople: (person: IPersonPicker) => void; removePersonFromSelectedPeople: (person: IPersonPicker, $event: MouseEvent) => void; selectedPersons: IPersonPicker[]; removePersonFromSearchResults: (people: IPersonPicker[], person: IPersonPicker, $event: MouseEvent) => void; onSearchKeyUp: ($event: KeyboardEvent) => void; facePileHeader: string; ngDisabled: boolean; ngChange: () => () => void; } /** * @ngdoc directive * @name uifPeoplePicker * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-people-picker>` directive. * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-people-picker * uif-people="onSearch(query)" * ng-model="selectedPeople" * placeholder="Search for people" * uif-selected-person-click="personClicked"> * <uif-people-search-more> * <uif-secondary-text>Showing {{sourcePeople.length}} results</uif-secondary-text> * <uif-primary-text uif-search-for-text="You are searching for: ">Search organization people</uif-primary-text> * </uif-people-search-more> * </uif-people-picker> */ export class PeoplePickerDirective implements angular.IDirective { public static directiveName: string = 'uifPeoplePicker'; public replace: boolean = true; public require: string[] = ['ngModel', `${PeoplePickerDirective.directiveName}`]; public restrict: string = 'E'; public transclude: boolean = true; public controller: any = PeoplePickerController; public scope: {} = { delay: '@uifSearchDelay', facePileHeader: '@?uifFacepileHeader', ngChange: '&?', ngDisabled: '=?', ngModel: '=', onSelectedPersonClick: '&?uifSelectedPersonClick', peopleCallback: '&uifPeople', placeholder: '@?', type: '@?uifType' }; private templateTypes: { [peoplePickerType: number]: string } = {}; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ( $document: angular.IDocumentService, $timeout: angular.ITimeoutService, $log: angular.ILogService, $window: angular.IWindowService) => new PeoplePickerDirective($document, $timeout, $log, $window); directive.$inject = ['$document', '$timeout', '$log', '$window']; return directive; } constructor( private $document: angular.IDocumentService, private $timeout: angular.ITimeoutService, private $log: angular.ILogService, private $window: angular.IWindowService) { this.templateTypes[PeoplePickerTypes.grouped] = `<div class="ms-PeoplePicker"> <div class="ms-PeoplePicker-searchBox"> <div class="ms-PeoplePicker-persona" ng-repeat="person in selectedPersons track by $index"> <uif-persona ng-click="onSelectedPersonClick()(person)" uif-style="${PersonaStyleEnum[PersonaStyleEnum.square]}" uif-size="${PersonaSize[PersonaSize.xsmall]}" uif-presence="{{person.presence}}" uif-image-url="{{person.icon}}"> <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials> <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text> </uif-persona> <button ng-if="!ngDisabled" type="button" ng-click="removePersonFromSelectedPeople(person, $event)" class="ms-PeoplePicker-personaRemove"> <uif-icon uif-type="${IconEnum[IconEnum.x]}"></uif-icon> </button> </div> <input ng-click="onPeoplePickerActive($event)" placeholder="{{placeholder}}" ng-model="searchQuery" class="ms-PeoplePicker-searchField" ng-focus="onPeoplePickerActive($event)" ng-keyup="onSearchKeyUp($event)" type="text"> </div> <div class="ms-PeoplePicker-results"> <div class="ms-PeoplePicker-resultGroups"> <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:'-order'"> <div class="ms-PeoplePicker-resultGroupTitle">{{groupData.group.name}}</div> <uif-people-picker-result-list ng-model="groupData.people" uif-person-click="addPersonToSelectedPeople" uif-person-close-click="removePersonFromSearchResults" uif-style="${PersonaStyleEnum[PersonaStyleEnum.square]}" uif-size="${PersonaSize[PersonaSize.medium]}"></uif-people-picker-result-list> </div> </div> <ng-transclude /> </div> </div>`; this.templateTypes[PeoplePickerTypes.compact] = `<div class="ms-PeoplePicker ms-PeoplePicker--compact"> <div class="ms-PeoplePicker-searchBox"> <div class="ms-PeoplePicker-persona" ng-repeat="person in selectedPersons track by $index"> <uif-persona ng-click="onSelectedPersonClick()(person)" uif-style="${PersonaStyleEnum[PersonaStyleEnum.square]}" uif-size="${PersonaSize[PersonaSize.xsmall]}" uif-presence="{{person.presence}}" uif-image-url="{{person.icon}}"> <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials> <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text> </uif-persona> <button ng-if="!ngDisabled" type="button" ng-click="removePersonFromSelectedPeople(person, $event)" class="ms-PeoplePicker-personaRemove"> <uif-icon uif-type="${IconEnum[IconEnum.x]}"></uif-icon> </button> </div> <input ng-click="onPeoplePickerActive($event)" ng-model="searchQuery" placeholder="{{placeholder}}" class="ms-PeoplePicker-searchField" ng-focus="onPeoplePickerActive($event)" ng-keyup="onSearchKeyUp($event)" type="text"> </div> <div class="ms-PeoplePicker-results"> <div class="ms-PeoplePicker-resultGroups"> <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:'-order'"> <div class="ms-PeoplePicker-resultGroupTitle">{{groupData.group.name}}</div> <uif-people-picker-result-list ng-model="groupData.people" uif-picker-type="${PeoplePickerTypes[PeoplePickerTypes.compact]}" uif-person-click="addPersonToSelectedPeople" uif-person-close-click="removePersonFromSearchResults" uif-style="${PersonaStyleEnum[PersonaStyleEnum.square]}" uif-size="${PersonaSize[PersonaSize.xsmall]}"></uif-people-picker-result-list> </div> </div> <ng-transclude /> </div> </div>`; this.templateTypes[PeoplePickerTypes.memberList] = ` <div class="ms-PeoplePicker ms-PeoplePicker--membersList"> <div class="ms-PeoplePicker-searchBox"> <input ng-click="onPeoplePickerActive($event)" placeholder="{{placeholder}}" ng-model="searchQuery" class="ms-PeoplePicker-searchField" ng-focus="onPeoplePickerActive($event)" ng-keyup="onSearchKeyUp($event)" type="text"> </div> <div class="ms-PeoplePicker-results"> <div class="ms-PeoplePicker-resultGroups"> <div class="ms-PeoplePicker-resultGroup" ng-repeat="groupData in groups | orderBy:'-order'"> <uif-people-picker-result-list ng-model="groupData.people" uif-person-click="addPersonToSelectedPeople" uif-style="${PersonaStyleEnum[PersonaStyleEnum.round]}" uif-size="${PersonaSize[PersonaSize.medium]}"></uif-people-picker-result-list> </div> </div> </div> <uif-people-picker-selected ng-model="selectedPersons" uif-selected-person-click="onSelectedPersonClick()" uif-person-close="removePersonFromSelectedPeople"> <ng-transclude></ng-transclude> </uif-people-picker-selected> </div>`; this.templateTypes[PeoplePickerTypes.facePile] = ` <div class="ms-PeoplePicker ms-PeoplePicker--Facepile"> <div class="ms-PeoplePicker-searchBox"> <input ng-click="onPeoplePickerActive($event)" placeholder="{{placeholder}}" ng-model="searchQuery" class="ms-PeoplePicker-searchField" ng-focus="onPeoplePickerActive($event)" ng-keyup="onSearchKeyUp($event)" type="text"> </div> <div class="ms-PeoplePicker-results"> <div class="ms-PeoplePicker-peopleListHeader"> <span>{{facePileHeader}}</span> </div> <div ng-repeat="groupData in groups | orderBy:'-order'"> <uif-people-picker-result-list ng-model="groupData.people" uif-person-click="addPersonToSelectedPeople" uif-style="${PersonaStyleEnum[PersonaStyleEnum.round]}" uif-size="${PersonaSize[PersonaSize.small]}"></uif-people-picker-result-list> </div> <div class="uif-search-more"></div> </div> <uif-people-picker-selected ng-model="selectedPersons" uif-selected-person-click="onSelectedPersonClick()" uif-person-close="removePersonFromSelectedPeople"> <div class="uif-people-header"></div> </uif-people-picker-selected> </div>`; } public template: any = ($element: angular.IAugmentedJQuery, $attrs: IPeoplePickerAttributes) => { let type: string = $attrs.uifType; if (angular.isUndefined(type)) { return this.templateTypes[PeoplePickerTypes.grouped]; } if (PeoplePickerTypes[type] === undefined) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.peoplepicker - unsupported people picker type:\n' + 'the type \'' + type + '\' is not supported by ng-Office UI Fabric as valid type for people picker.' + 'Supported types can be found under PeoplePickerTypes enum here:\n' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/peoplepicker/peoplePickerDirective.ts'); throw '[ngOfficeUiFabric] - Error'; } return this.templateTypes[PeoplePickerTypes[type]]; } public link: angular.IDirectiveLinkFn = ( $scope: IPeoplePickerScope, $element: angular.IAugmentedJQuery, $attrs: IPeoplePickerAttributes, ctrls: [angular.INgModelController, PeoplePickerController], $transclude: angular.ITranscludeFunction): void => { let ngModelCtrl: angular.INgModelController = ctrls[0]; let peoplePickerCtrl: PeoplePickerController = ctrls[1]; this.initDisabledState($element, $scope, $attrs); $scope.facePileHeader = $scope.facePileHeader || 'Suggested contacts'; $scope.$watchCollection('selectedPersons', (data: any, data2: any, data3: any) => { this.resizeSearchField($element); if ($scope.ngChange) { $scope.ngChange(); } }); ngModelCtrl.$render = () => { if (ngModelCtrl.$viewValue) { $scope.selectedPersons = ngModelCtrl.$viewValue; } else { $scope.selectedPersons = []; } this.resizeSearchField($element); }; peoplePickerCtrl.search(); let searchTimeout: angular.IPromise<void> = null; $scope.onSearchKeyUp = ($event: KeyboardEvent) => { let $searchMore: JQuery = angular.element($element[0].querySelector('.ms-PeoplePicker-searchMore')); if ($searchMore.length !== 0) { $scope.searchQuery ? $element.addClass('is-searching') : $element.removeClass('is-searching'); $scope.searchQuery ? $searchMore.addClass('is-active') : $searchMore.removeClass('is-active'); this.animateSelectedPeople($element); } if (!$scope.delay) { return; } if (searchTimeout != null) { this.$timeout.cancel(searchTimeout); } searchTimeout = this.$timeout( () => { peoplePickerCtrl.search(); }, $scope.delay); }; $scope.onPeoplePickerActive = ($event: KeyboardEvent | MouseEvent) => { this.smoothScrollTo($element[0]); if ($scope.type !== PeoplePickerTypes[PeoplePickerTypes.facePile]) { let $results: JQuery = angular.element($element[0].querySelector('.ms-PeoplePicker-results')); $results[0].style.width = $element[0].clientWidth - 2 + 'px'; } else if ($scope.type === PeoplePickerTypes[PeoplePickerTypes.facePile]) { this.animateSelectedPeople($element); } $event.stopPropagation(); $element.addClass('is-active'); }; $scope.addPersonToSelectedPeople = (person) => { if ($scope.selectedPersons.indexOf(person) !== -1) { return; } if (angular.isDefined($attrs.uifSingle) && $scope.selectedPersons.length > 0) { $scope.selectedPersons.length = 0; } $scope.selectedPersons.push(person); ngModelCtrl.$setViewValue($scope.selectedPersons); }; $scope.removePersonFromSelectedPeople = (person: IPersonPicker, $event: MouseEvent) => { let indx: number = $scope.selectedPersons.indexOf(person); $scope.selectedPersons.splice(indx, 1); ngModelCtrl.$setViewValue($scope.selectedPersons); $event.stopPropagation(); }; $scope.removePersonFromSearchResults = (people: IPersonPicker[], person: IPersonPicker, $event: MouseEvent) => { $event.stopPropagation(); let indx: number = people.indexOf(person); people.splice(indx, 1); }; this.$document.on('click', () => { $element.removeClass('is-active'); }); if ($scope.type === PeoplePickerTypes[PeoplePickerTypes.facePile]) { $transclude((clone: angular.IAugmentedJQuery) => { this.insertFacePileHeader(clone, $scope, $element); this.insertFacePileSearchMore(clone, $scope, $element); }); } } private initDisabledState($element: JQuery, $scope: IPeoplePickerScope, $attrs: IPeoplePickerAttributes): void { let $searchField: JQuery = angular.element($element[0].querySelector('.ms-PeoplePicker-searchField')); $attrs.$observe('disabled', (disabled) => { if (disabled) { $searchField.attr('disabled', 'disabled'); } else { $searchField.removeAttr('disabled'); } }); } private animateSelectedPeople($element: JQuery): void { let $selectedPeople: JQuery = angular.element($element[0].querySelector('.ms-PeoplePicker-selectedPeople')); $selectedPeople.addClass('ms-u-slideDownIn20'); setTimeout(() => { $selectedPeople.removeClass('ms-u-slideDownIn20'); }, 1000); } private currentYPosition(): number { if (this.$window.pageYOffset) { return this.$window.pageYOffset; } let body: HTMLElement = angular.element(this.$document[0]).find('body')[0]; if (body.scrollTop) { return body.scrollTop; } return 0; } private elmYPosition(element: HTMLElement): number { let y: number = element.offsetTop; let node: any = element; while (node.offsetParent && node.offsetParent !== document.body) { node = <Element>(node.offsetParent); y += node.offsetTop; } return y; } private smoothScrollTo(element: HTMLElement): void { let startY: number = this.currentYPosition(); let stopY: number = this.elmYPosition(element); let distance: number = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { window.scrollTo(0, stopY); return; } let speed: number = Math.round(distance / 30); if (speed >= 20) { speed = 20; } let step: number = Math.round(distance / 25); let leapY: number = stopY > startY ? startY + step : startY - step; let timer: number = 0; if (stopY > startY) { for (let i: number = startY; i < stopY; i += step) { ((lY: number, t: number) => { setTimeout( () => { window.scrollTo(0, lY); }, t * speed); })(leapY, timer); leapY += step; if (leapY > stopY) { leapY = stopY; } timer++; } return; } for (let i: number = startY; i > stopY; i -= step) { ((lY: number, t: number) => { setTimeout( () => { window.scrollTo(0, lY); }, t * speed); })(leapY, timer); leapY -= step; if (leapY < stopY) { leapY = stopY; } timer++; } } private insertFacePileHeader(clone: angular.IAugmentedJQuery, $scope: IPeoplePickerScope, $element: angular.IAugmentedJQuery): void { let elementToReplace: JQuery = angular.element($element[0].querySelector('.uif-people-header')); for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('ms-PeoplePicker-selectedCount')) { elementToReplace.replaceWith(element); break; } } } private insertFacePileSearchMore(clone: angular.IAugmentedJQuery, $scope: IPeoplePickerScope, $element: angular.IAugmentedJQuery): void { let elementToReplace: JQuery = angular.element($element[0].querySelector('.uif-search-more')); for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('ms-PeoplePicker-searchMore')) { elementToReplace.replaceWith(element); break; } } } private resizeSearchField($peoplePicker: JQuery): void { let $searchBox: JQuery = angular.element($peoplePicker[0].querySelector('.ms-PeoplePicker-searchBox')); let $searchField: JQuery = angular.element($peoplePicker[0].querySelector('.ms-PeoplePicker-searchField')); let searchBoxLeftEdge: number = $searchBox.prop('offsetLeft'); let searchBoxWidth: number = $searchBox[0].clientWidth; let searchBoxRightEdge: number = searchBoxLeftEdge + searchBoxWidth; let $personaNodes: NodeListOf<Element> = $searchBox[0].querySelectorAll('.ms-PeoplePicker-persona'); if ($personaNodes.length === 0) { $searchField[0].style.width = '100%'; return; } let $lastPersona: JQuery = angular.element($personaNodes[$personaNodes.length - 1]); let lastPersonaLeftEdge: number = $lastPersona.prop('offsetLeft'); let lastPersonaWidth: number = $lastPersona[0].clientWidth; let lastPersonaRightEdge: number = lastPersonaLeftEdge + lastPersonaWidth; let newFieldWidth: number | string = searchBoxRightEdge - lastPersonaRightEdge - 5; if (newFieldWidth < 100) { newFieldWidth = '100%'; $searchField[0].style.width = '100%'; } else { $searchField[0].style.width = newFieldWidth + 'px'; } } } /** * @ngdoc interface * @name IPeoplePickerResultListScope * @module officeuifabric.components.peoplepicker * * @description * Interface used by the people picker result list directive. * * @property {array} people - Persons in search results * @property {function} expandAdditionalData - Callback when clicking on "expand" button under search results */ export interface IPeoplePickerResultListScope extends angular.IScope { people: IPersonPicker[]; expandAdditionalData: ($event: MouseEvent) => void; } /** * @ngdoc directive * @name uifPeoplePickerResultList * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-people-picker-result-list>` is a helper directive used by people picker. * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-people-picker-result-list * ng-model="groupData.people" * uif-person-click="addPersonToSelectedPeople" * uif-person-close-click="removePersonFromSearchResults" * uif-style="${PersonaStyleEnum[PersonaStyleEnum.square]}" * uif-size="${PersonaSize[PersonaSize.medium]}"> * </uif-people-picker-result-list> */ export class PeoplePickerResultListDirective implements angular.IDirective { public static directiveName: string = 'uifPeoplePickerResultList'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public template: string = ` <ul class="ms-PeoplePicker-resultList"> <li class="ms-PeoplePicker-result" ng-repeat="person in people track by $index"> <div role="button" class="ms-PeoplePicker-resultBtn" ng-class="{'ms-PeoplePicker-resultBtn--compact': pickerType === 'compact'}" ng-click="onPersonClick()(person)"> <uif-persona uif-style="{{personStyle}}" uif-size="{{personSize}}" uif-presence="{{person.presence}}" uif-image-url="{{person.icon}}"> <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials> <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text> <uif-persona-secondary-text>{{person.secondaryText}}</uif-persona-secondary-text> </uif-persona> <button type="button" ng-if="!person.additionalData && onPersonCloseClick()" ng-click="onPersonCloseClick()(people, person, $event)" class="ms-PeoplePicker-resultAction js-resultRemove"> <uif-icon uif-type="${IconEnum[IconEnum.x]}"></uif-icon> </button> <button type="button" ng-if="person.additionalData" ng-click="expandAdditionalData($event)" class="ms-PeoplePicker-resultAction js-resultRemove"> <uif-icon uif-type="${IconEnum[IconEnum.chevronsDown]}"></uif-icon> </button> </div> <div ng-if="person.additionalData" class="ms-PeoplePicker-resultAdditionalContent"> <uif-people-picker-result-list ng-model="person.additionalData" uif-person-click="onPersonClick()" uif-person-close-click="onPersonCloseClick()" uif-picker-type="{{pickerType}}" uif-style="{{personStyle}}" uif-size="{{personSize}}"></uif-people-picker-result-list> </div> </li> </ul>`; public scope: {} = { onPersonClick: '&uifPersonClick', onPersonCloseClick: '&uifPersonCloseClick', people: '=ngModel', personSize: '@uifSize', personStyle: '@uifStyle', pickerType: '@uifPickerType' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PeoplePickerResultListDirective(); return directive; } constructor() { // } public link: angular.IDirectiveLinkFn = ( $scope: IPeoplePickerResultListScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, peoplePickerCtrl: PeoplePickerController, $transclude: angular.ITranscludeFunction): void => { $scope.expandAdditionalData = ($event: MouseEvent) => { $event.stopPropagation(); let $button: JQuery = angular.element($event.target); for (let i: number = 0; i < 10; i++) { let $parent: JQuery = $button.parent(); if ($parent.hasClass('ms-PeoplePicker-result')) { $parent.toggleClass('is-expanded'); break; } $button = $parent; } }; } } /** * @ngdoc interface * @name IPeopleSearchMoreScope * @module officeuifabric.components.peoplepicker * * @description * Interface used by the scope for people search more directive. * * @property {function} onSearch - Function called when user click by "search more" component * @property {boolean} processing - Boolean indicating that search in progress (in async scenarious) * @property {string} pickerType - Determines people picker type (from parent directive people picker) * @property {boolean} disconnected - Boolean indicating disconnected scenario */ export interface IPeopleSearchMoreScope extends angular.IScope { onSearch: ($event: MouseEvent) => void; processing: boolean; pickerType: string; disconnected: boolean; } /** * @ngdoc controller * @name PeopleSearchMoreController * @module officeuifabric.components.peoplepicker * * @description * Controller used for the `<uif-people-search-more>` directive. */ export class PeopleSearchMoreController { public static $inject: string[] = ['$scope', '$element']; public searchCallbacks: { (): void; }[] = []; constructor( private $scope: IPeopleSearchMoreScope, private $element: angular.IAugmentedJQuery) { } public isSearching(searching: boolean): void { this.$scope.processing = searching; searching ? this.$element.addClass('is-searching') : this.$element.removeClass('is-searching'); } } export class PeopleSearchMoreDirective implements angular.IDirective { public static directiveName: string = 'uifPeopleSearchMore'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public require: string = `^^${PeoplePickerDirective.directiveName}`; public controller: any = PeopleSearchMoreController; public template: string = ` <div class="ms-PeoplePicker-searchMore js-searchMore" ng-class="{'ms-PeoplePicker-searchMore--disconnected': disconnected}"> <button type="button" ng-if="pickerType === '${PeoplePickerTypes[PeoplePickerTypes.grouped]}' && !disconnected" ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn"> <div class="ms-PeoplePicker-searchMoreIcon"> <uif-icon ng-if="!disconnected" uif-type="${IconEnum[IconEnum.search]}"></uif-icon> <uif-icon ng-if="disconnected" uif-type="${IconEnum[IconEnum.alert]}"></uif-icon> </div> <ng-transclude /> </button> <div role="button" ng-if="pickerType === '${PeoplePickerTypes[PeoplePickerTypes.compact]}' && !disconnected" ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn ms-PeoplePicker-searchMoreBtn--compact"> <div class="ms-PeoplePicker-searchMoreIcon"> <uif-icon ng-if="!disconnected" uif-type="${IconEnum[IconEnum.search]}"></uif-icon> <uif-icon ng-if="disconnected" uif-type="${IconEnum[IconEnum.alert]}"></uif-icon> </div> <ng-transclude /> </div> <div role="button" ng-if="pickerType === '${PeoplePickerTypes[PeoplePickerTypes.facePile]}' && !disconnected" ng-click="onSearch($event)" class="ms-PeoplePicker-searchMoreBtn ms-PeoplePicker-searchMoreBtn--compact"> <div class="ms-PeoplePicker-searchMoreIcon"> <uif-icon ng-if="!disconnected" uif-type="${IconEnum[IconEnum.search]}"></uif-icon> <uif-icon ng-if="disconnected" uif-type="${IconEnum[IconEnum.alert]}"></uif-icon> </div> <ng-transclude /> </div> <div role="button" ng-if="disconnected" class="ms-PeoplePicker-searchMoreBtn"> <div class="ms-PeoplePicker-searchMoreIcon"> <uif-icon uif-type="${IconEnum[IconEnum.alert]}"></uif-icon> </div> <ng-transclude /> </div> <uif-spinner ng-show="processing"></uif-spinner> </div>`; public scope: {} = { disconnected: '=uifDisconnected' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PeopleSearchMoreDirective(); return directive; } constructor() { // } public link: angular.IDirectiveLinkFn = ( $scope: IPeopleSearchMoreScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, peoplePickerCtrl: PeoplePickerController, $transclude: angular.ITranscludeFunction): void => { $scope.pickerType = peoplePickerCtrl.pickerType(); $scope.onSearch = ($event: MouseEvent) => { $event.stopPropagation(); peoplePickerCtrl.search(); $scope.$broadcast(peopleSearchEventName, peoplePickerCtrl.searchQuery()); }; } } /** * @ngdoc interface * @name IPrimaryTextScope * @module officeuifabric.components.peoplepicker * * @description * Interface used by the primary text directive. * * @property {string} searchingForText - Template for label "Search for" * @property {string} searchQuery - Search query from parent directive, i.e. people picker */ export interface IPrimaryTextScope extends angular.IScope { searchingForText: string; searchQuery: string; } /** * @ngdoc controller * @name PrimaryTextController * @module officeuifabric.components.peoplepicker * * @description * Controller used for the `<uif-primary-text>` directive. */ export class PrimaryTextController { public static $inject: string[] = ['$scope']; constructor( private $scope: IPrimaryTextScope) { this.$scope.$on(peopleSearchEventName, ($event: angular.IAngularEvent, query: string) => { this.$scope.searchQuery = query; }); } } /** * @ngdoc directive * @name uifPrimaryText * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-primary-text>` is a helper directive for search more component * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-primary-text uif-search-for-text="You are searching for: ">Search organization people</uif-primary-text> */ export class PrimaryTextDirective implements angular.IDirective { public static directiveName: string = 'uifPrimaryText'; public replace: boolean = true; public restrict: string = 'E'; public require: string[] = [`^^${PeopleSearchMoreDirective.directiveName}`, `^^${PeoplePickerDirective.directiveName}`]; public transclude: boolean = true; public controller: any = PrimaryTextController; public template: string = ` <div ng-show="!$parent.$parent.disconnected" class="ms-PeoplePicker-searchMorePrimary"> <div ng-show="$parent.$parent.processing">{{searchingForText}} {{searchQuery}}</div> <ng-transclude ng-show="!$parent.$parent.processing"></ng-transclude> </div>`; public scope: {} = { searchingForText: '@?uifSearchForText' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PrimaryTextDirective(); return directive; } constructor() { // } public link: angular.IDirectiveLinkFn = ( $scope: IPrimaryTextScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, ctrls: [PeopleSearchMoreController, PeoplePickerController], $transclude: angular.ITranscludeFunction): void => { $scope.searchingForText = $scope.searchingForText || 'Searching for'; } } /** * @ngdoc directive * @name uifSecondaryText * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-secondary-text>` is a helper directive for search more component * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-secondary-text>Showing {{sourcePeople.length}} results</uif-secondary-text> */ export class SecondaryTextDirective implements angular.IDirective { public static directiveName: string = 'uifSecondaryText'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public template: string = ` <div ng-show="!$parent.$parent.disconnected" class="ms-PeoplePicker-searchMoreSecondary"> <ng-transclude></ng-transclude> </div>`; public scope: boolean = true; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new SecondaryTextDirective(); return directive; } constructor() { // } } /** * @ngdoc directive * @name uifDisconnectedText * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-disconnected-text>` is a helper directive for search more component * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-disconnected-text> We are having trouble connecting to the server. * <br> Please try again in a few minutes. * </uif-disconnected-text> */ export class DisconnectedTextDirective implements angular.IDirective { public static directiveName: string = 'uifDisconnectedText'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public template: string = ` <div ng-show="$parent.$parent.disconnected" class="ms-PeoplePicker-searchMorePrimary"> <ng-transclude></ng-transclude> </div>`; public scope: boolean = true; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new DisconnectedTextDirective(); return directive; } constructor() { // } } /** * @ngdoc directive * @name uifPeoplePickerSelected * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-people-picker-selected>` is a helper directive used in memeberList and facePile modes * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-people-picker-selected ng-model="selectedPersons" * uif-selected-person-click="onSelectedPersonClick()" * uif-person-close="removePersonFromSelectedPeople"> * <ng-transclude></ng-transclude> * </uif-people-picker-selected> */ export class PeoplePickerSelectedDirective implements angular.IDirective { public static directiveName: string = 'uifPeoplePickerSelected'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public template: string = ` <div class="ms-PeoplePicker-selected" ng-class="{'is-active': selectedPeople && selectedPeople.length > 0}"> <div class="ms-PeoplePicker-selectedHeader"> <ng-transclude></ng-transclude> </div> <ul class="ms-PeoplePicker-selectedPeople"> <li class="ms-PeoplePicker-selectedPerson" ng-repeat="person in selectedPeople track by $index"> <uif-persona ng-click="onSelectedPersonClick()(person)" uif-style="${PersonaStyleEnum[PersonaStyleEnum.round]}" uif-size="${PersonaSize[PersonaSize.small]}" uif-presence="{{person.presence}}" uif-image-url="{{person.icon}}"> <uif-persona-initials uif-color="{{person.color}}">{{person.initials}}</uif-persona-initials> <uif-persona-primary-text>{{person.primaryText}}</uif-persona-primary-text> <uif-persona-secondary-text>{{person.secondaryText}}</uif-persona-secondary-text> </uif-persona> <button type="button" ng-click="removePersonFromSelectedPeople()(person, $event)" class="ms-PeoplePicker-resultAction js-resultRemove"> <uif-icon uif-type="${IconEnum[IconEnum.x]}"></uif-icon> </button> </li> </ul> </div>`; public scope: {} = { onSelectedPersonClick: '&?uifSelectedPersonClick', removePersonFromSelectedPeople: '&uifPersonClose', selectedPeople: '=ngModel' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new PeoplePickerSelectedDirective(); return directive; } constructor() { // } } /** * @ngdoc interface * @name IGroup * @module officeuifabric.components.peoplepicker * * @description * Helper interface used by the people picker directive. * * @property {Array} selectedPersons - Persons selected in people picker */ export interface ISelectedPeopleHeaderScope extends angular.IScope { selectedPersons: IPersonPicker[]; } /** * @ngdoc directive * @name uifSelectedPeopleHeader * @module officeuifabric.components.peoplepicker * * @restrict E * * @description * `<uif-selected-people-header>` is a helper directive used in memeberList and facePile modes * * @see {link http://dev.office.com/fabric/components/peoplepicker} * * @usage * * <uif-selected-people-header>{{selectedPeople.length}} selected person(s)</uif-selected-people-header> */ export class SelectedPeopleHeaderDirective implements angular.IDirective { public static directiveName: string = 'uifSelectedPeopleHeader'; public require: string = `^^${PeoplePickerDirective.directiveName}`; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public scope: boolean = true; public template: string = `<span class="ms-PeoplePicker-selectedCount" ng-transclude></span>`; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new SelectedPeopleHeaderDirective(); return directive; } public link: angular.IDirectiveLinkFn = ( $scope: ISelectedPeopleHeaderScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, peoplePickerCtrl: PeoplePickerController, $transclude: angular.ITranscludeFunction): void => { $scope.selectedPersons = peoplePickerCtrl.getSelectedPersons(); } } export let module: angular.IModule = angular.module('officeuifabric.components.peoplepicker', [ 'officeuifabric.components']) .directive(PeoplePickerDirective.directiveName, PeoplePickerDirective.factory()) .directive(PrimaryTextDirective.directiveName, PrimaryTextDirective.factory()) .directive(SecondaryTextDirective.directiveName, SecondaryTextDirective.factory()) .directive(PeoplePickerResultListDirective.directiveName, PeoplePickerResultListDirective.factory()) .directive(DisconnectedTextDirective.directiveName, DisconnectedTextDirective.factory()) .directive(PeoplePickerSelectedDirective.directiveName, PeoplePickerSelectedDirective.factory()) .directive(SelectedPeopleHeaderDirective.directiveName, SelectedPeopleHeaderDirective.factory()) .directive(PeopleSearchMoreDirective.directiveName, PeopleSearchMoreDirective.factory());
the_stack