text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { isLang, Lang } from '../../resources/languages'; import { UnreachableCode } from '../../resources/not_reached'; import PartyTracker from '../../resources/party'; import Regexes from '../../resources/regexes'; import { triggerOutputFunctions } from '../../resources/responses'; import UserConfig, { ConfigValue, OptionsTemplate, UserFileCallback, } from '../../resources/user_config'; import { BaseOptions, RaidbossData } from '../../types/data'; import { SavedConfigEntry } from '../../types/event'; import { Job, Role } from '../../types/job'; import { Matches } from '../../types/net_matches'; import { LocaleText, LooseTrigger, Output, OutputStrings, RaidbossFileData, TriggerAutoConfig, } from '../../types/trigger'; import { CactbotConfigurator, ConfigLooseTrigger, ConfigLooseTriggerSet, ConfigProcessedFileMap, } from '../config/config'; import raidbossFileData from './data/raidboss_manifest.txt'; import { RaidbossTriggerField, RaidbossTriggerOutput } from './popup-text'; import raidbossOptions, { RaidbossOptions } from './raidboss_options'; const kOptionKeys = { output: 'Output', duration: 'Duration', beforeSeconds: 'BeforeSeconds', outputStrings: 'OutputStrings', } as const; type TriggerSoundOption = { label: LocaleText; debugOnly?: boolean; }; // No sound only option, because that's silly. const kTriggerOptions = { default: { label: { en: '✔ Defaults', de: '✔ Standards', fr: '✔ Défauts', ja: '✔ 初期設定', cn: '✔ 默认设置', ko: '✔ 기본', }, }, textAndSound: { label: { en: '🆙🔊 Text and Sound', de: '🆙🔊 Text und Ton', fr: '🆙🔊 Texte et son', ja: '🆙🔊 テキストと音声', cn: '🆙🔊 文字显示与提示音', ko: '🆙🔊 텍스트와 소리', }, }, ttsAndText: { label: { en: '🆙💬 Text and TTS', de: '🆙💬 Text und TTS', fr: '🆙💬 Texte et TTS', ja: '🆙💬 テキストとTTS', cn: '🆙💬 文字显示与TTS', ko: '🆙💬 텍스트와 TTS', }, }, ttsOnly: { label: { en: '💬 TTS Only', de: '💬 Nur TTS', fr: '💬 TTS Seulement', ja: '💬 TTSのみ', cn: '💬 只使用TTS', ko: '💬 TTS만', }, }, textOnly: { label: { en: '🆙 Text Only', de: '🆙 Nur Text', fr: '🆙 Texte seulement', ja: '🆙 テキストのみ', cn: '🆙 只使用文字显示', ko: '🆙 텍스트만', }, }, disabled: { label: { en: '❌ Disabled', de: '❌ Deaktiviert', fr: '❌ Désactivé', ja: '❌ 無効', cn: '❌ 禁用', ko: '❌ 비활성화', }, }, } as const; const triggerSoundOptions: { [key: string]: TriggerSoundOption } = kTriggerOptions; type DetailKey = { label: LocaleText; cls: string; debugOnly?: boolean; generatedManually?: boolean; }; const kDetailKeys = { 'triggerRegex': { label: { en: 'regex', de: 'regex', fr: 'regex', ja: '正規表現', cn: '正则表达式', ko: '정규식', }, cls: 'regex-text', debugOnly: true, }, 'triggerNetRegex': { label: { en: 'netregex', de: 'netregex', fr: 'netregex', ja: 'ネット正規表現', cn: '网络日志正则表达式', ko: '정규표현식', }, cls: 'regex-text', debugOnly: true, }, 'timelineRegex': { label: { en: 'timeline', de: 'timeline', fr: 'timeline', ja: 'タイムライン', cn: '时间轴', ko: '타임라인', }, cls: 'regex-text', debugOnly: true, }, 'beforeSeconds': { label: { en: 'before (sec)', de: 'Vorher (Sekunden)', fr: 'avant (seconde)', ja: 'その前に (秒)', cn: '提前 (秒)', ko: '앞당김 (초)', }, cls: 'before-seconds-text', generatedManually: true, }, 'condition': { label: { en: 'condition', de: 'condition', fr: 'condition', ja: '条件', cn: '条件', ko: '조건', }, cls: 'condition-text', debugOnly: true, }, 'duration': { label: { en: 'duration (sec)', de: 'Dauer (Sekunden)', fr: 'Durée (secondes)', ja: '存続時間 (秒)', cn: '持续时间 (秒)', ko: '지속 시간 (초)', }, cls: 'duration-text', generatedManually: true, }, 'preRun': { label: { en: 'preRun', de: 'preRun', fr: 'preRun', ja: 'プレ実行', cn: '预运行', ko: '사전 실행', }, cls: 'prerun-text', debugOnly: true, }, 'alarmText': { label: { en: 'alarm', de: 'alarm', fr: 'alarme', ja: '警報', cn: '警报文本', ko: '경고', }, cls: 'alarm-text', }, 'alertText': { label: { en: 'alert', de: 'alert', fr: 'alerte', ja: '警告', cn: '警告文本', ko: '주의', }, cls: 'alert-text', }, 'infoText': { label: { en: 'info', de: 'info', fr: 'info', ja: '情報', cn: '信息文本', ko: '안내', }, cls: 'info-text', }, 'tts': { label: { en: 'tts', de: 'tts', fr: 'tts', ja: 'TTS', cn: 'TTS', ko: 'TTS', }, cls: 'tts-text', }, 'sound': { label: { en: 'sound', de: 'sound', fr: 'son', ja: '音声', cn: '提示音', ko: '소리', }, cls: 'sound-text', }, 'run': { label: { en: 'run', de: 'run', fr: 'run', ja: '実行', cn: '运行', ko: '실행', }, cls: 'run-text', debugOnly: true, }, } as const; const detailKeys: { [key in keyof LooseTrigger]: DetailKey } = kDetailKeys; const kMiscTranslations = { // Shows up for un-set values. valueDefault: { en: '(default)', de: '(Standard)', fr: '(Défaut)', ja: '(初期値)', cn: '(默认值)', ko: '(기본값)', }, // Shown when the UI can't decipher the output of a function. valueIsFunction: { en: '(function)', de: '(Funktion)', fr: '(Fonction)', ja: '(関数)', cn: '(函数)', ko: '(함수)', }, // Warning label for triggers without ids or overridden triggers. warning: { en: '⚠️ warning', de: '⚠️ Warnung', fr: '⚠️ Attention', ja: '⚠️ 警告', cn: '⚠️ 警告', ko: '⚠️ 주의', }, // Shows up for triggers without ids. missingId: { en: 'missing id field', de: 'Fehlendes ID Feld', fr: 'Champ ID manquant', ja: 'idがありません', cn: '缺少id属性', ko: 'ID 필드값 없음', }, // Shows up for triggers that are overridden by other triggers. overriddenByFile: { en: 'overridden by "${file}"', de: 'Überschrieben durch "${file}"', fr: 'Écrasé(e) par "${file}"', ja: '"${file}"に上書きました', cn: '被"${file}"文件覆盖', ko: '"${file}" 파일에서 덮어씌움', }, // Opens trigger file on Github. viewTriggerSource: { en: 'View Trigger Source', de: 'Zeige Trigger Quelle', fr: 'Afficher la source du Trigger', ja: 'トリガーのコードを表示', cn: '显示触发器源码', ko: '트리거 출처 열기', }, }; const validDurationOrUndefined = (valEntry?: SavedConfigEntry) => { if (typeof valEntry !== 'string' && typeof valEntry !== 'number') return undefined; const val = parseFloat(valEntry.toString()); if (!isNaN(val) && val >= 0) return val; return undefined; }; const canBeConfigured = (trig: ConfigLooseTrigger) => !trig.isMissingId && !trig.overriddenByFile; const addTriggerDetail = ( container: HTMLElement, labelText: string, detailText: string, detailCls?: string[], ): void => { const label = document.createElement('div'); label.innerText = labelText; label.classList.add('trigger-label'); container.appendChild(label); const detail = document.createElement('div'); detail.classList.add('trigger-detail'); detail.innerText = detailText; container.appendChild(detail); if (detailCls) detail.classList.add(...detailCls); }; // This is used both for top level Options and for PerTriggerAutoConfig settings. // Unfortunately due to poor decisions in the past, PerTriggerOptions has different // fields here. This should be fixed. const setOptionsFromOutputValue = ( options: BaseOptions | TriggerAutoConfig, value: SavedConfigEntry, ) => { if (value === 'default') { // Nothing. } else if (value === 'textAndSound') { options.TextAlertsEnabled = true; options.SoundAlertsEnabled = true; options.SpokenAlertsEnabled = false; } else if (value === 'ttsAndText') { options.TextAlertsEnabled = true; options.SoundAlertsEnabled = true; options.SpokenAlertsEnabled = true; } else if (value === 'ttsOnly') { options.TextAlertsEnabled = false; options.SoundAlertsEnabled = true; options.SpokenAlertsEnabled = true; } else if (value === 'textOnly') { options.TextAlertsEnabled = true; options.SoundAlertsEnabled = false; options.SpokenAlertsEnabled = false; } else if (value === 'disabled') { options.TextAlertsEnabled = false; options.SoundAlertsEnabled = false; options.SpokenAlertsEnabled = false; } else { console.error(`unknown output type: ${value.toString()}`); } }; // Helper for doing nothing during trigger eval, but still recording any // calls to `output.responseOutputStrings = x;` via callback. class DoNothingFuncProxy { constructor(outputStringsCallback: (outputStrings: OutputStrings) => void) { return new Proxy(this, { set(target, property, value): boolean { if (property === 'responseOutputStrings') { // TODO: need some way of verifying that a value is an OutputStrings. outputStringsCallback(value as OutputStrings); return true; } // Ignore other property setting here. return false; }, get(_target, _name) { return () => {/* noop */}; }, }); } } const makeLink = (href: string) => { return `<a href="${href}" target="_blank">${href}</a>`; }; const langOrEn = (lang: ConfigValue): Lang => { return typeof lang === 'string' && isLang(lang) ? lang : 'en'; }; class RaidbossConfigurator { private base: CactbotConfigurator; private alertsLang: Lang; private timelineLang: Lang; constructor(cactbotConfigurator: CactbotConfigurator) { this.base = cactbotConfigurator; // TODO: is it worth adding the complexity to reflect this change in triggers that use it? // This is probably where using something like vue or react would be easier. // For the moment, folks can just reload, for real. this.alertsLang = langOrEn(this.base.getOption('raidboss', 'AlertsLanguage', this.base.lang)); this.timelineLang = langOrEn( this.base.getOption('raidboss', 'TimelineLanguage', this.base.lang), ); } buildUI(container: HTMLElement, raidbossFiles: RaidbossFileData, userOptions: RaidbossOptions) { const fileMap = this.processRaidbossFiles(raidbossFiles, userOptions); const expansionDivs: { [expansion: string]: HTMLElement } = {}; for (const [key, info] of Object.entries(fileMap)) { // "expansion" here is technically section, which includes "general triggers" // and one section per user file. const expansion = info.section; if (!info.triggers || Object.keys(info.triggers).length === 0) continue; let expansionDiv = expansionDivs[expansion]; if (!expansionDiv) { const expansionContainer = document.createElement('div'); expansionContainer.classList.add('trigger-expansion-container', 'collapsed'); container.appendChild(expansionContainer); const expansionHeader = document.createElement('div'); expansionHeader.classList.add('trigger-expansion-header'); expansionHeader.onclick = () => { expansionContainer.classList.toggle('collapsed'); }; expansionHeader.innerText = expansion; expansionContainer.appendChild(expansionHeader); expansionDiv = expansionDivs[expansion] = expansionContainer; } const triggerContainer = document.createElement('div'); triggerContainer.classList.add('trigger-file-container', 'collapsed'); expansionDiv.appendChild(triggerContainer); const headerDiv = document.createElement('div'); headerDiv.classList.add('trigger-file-header'); headerDiv.onclick = () => { triggerContainer.classList.toggle('collapsed'); }; const parts = [info.title, info.type, info.prefix]; for (const part of parts) { if (!part) continue; const partDiv = document.createElement('div'); partDiv.classList.add('trigger-file-header-part'); // Use innerHTML here because of <Emphasis>Whorleater</Emphasis>. partDiv.innerHTML = part; headerDiv.appendChild(partDiv); } triggerContainer.appendChild(headerDiv); const triggerOptions = document.createElement('div'); triggerOptions.classList.add('trigger-file-options'); triggerContainer.appendChild(triggerOptions); for (const [trigId, trig] of Object.entries(info.triggers ?? {})) { // Don't construct triggers that won't show anything. let hasOutputFunc = false; for (const func of triggerOutputFunctions) { if (func in trig) { hasOutputFunc = true; break; } } if (!hasOutputFunc && !this.base.developerOptions) continue; // Build the trigger label. const triggerDiv = document.createElement('div'); triggerDiv.innerHTML = trig.isMissingId ? '(???)' : trigId; triggerDiv.classList.add('trigger'); triggerOptions.appendChild(triggerDiv); // Container for the right side ui (select boxes, all of the info). const triggerDetails = document.createElement('div'); triggerDetails.classList.add('trigger-details'); triggerOptions.appendChild(triggerDetails); if (canBeConfigured(trig)) triggerDetails.appendChild(this.buildTriggerOptions(trig, triggerDiv)); if (trig.isMissingId) { addTriggerDetail( triggerDetails, this.base.translate(kMiscTranslations.warning), this.base.translate(kMiscTranslations.missingId), ); } if (trig.overriddenByFile) { const baseText = this.base.translate(kMiscTranslations.overriddenByFile); const detailText = baseText.replace('${file}', trig.overriddenByFile); addTriggerDetail( triggerDetails, this.base.translate(kMiscTranslations.warning), detailText, ); } // Append some details about the trigger so it's more obvious what it is. for (const [detailStringKey, opt] of Object.entries(detailKeys)) { // Object.entries coerces to a string, but the detailKeys definition makes this true. const detailKey = detailStringKey as keyof LooseTrigger; if (opt.generatedManually) continue; if (!this.base.developerOptions && opt.debugOnly) continue; const trigOutput = trig.configOutput?.[detailKey]; const trigFunc = trig[detailKey]; if (!trigFunc) continue; const detailCls = [opt.cls]; let detailText: string | undefined; if (trigOutput) { detailText = trigOutput; } else if (typeof trigFunc === 'function') { detailText = this.base.translate(kMiscTranslations.valueIsFunction); detailCls.push('function-text'); } else { detailText = trigFunc.toString(); } addTriggerDetail( triggerDetails, this.base.translate(opt.label), detailText, detailCls, ); } if (!canBeConfigured(trig)) continue; // Add beforeSeconds manually for timeline triggers. if (trig.isTimelineTrigger) { const detailKey = 'beforeSeconds'; const optionKey = kOptionKeys.beforeSeconds; const label = document.createElement('div'); label.innerText = this.base.translate(kDetailKeys[detailKey].label); label.classList.add('trigger-label'); triggerDetails.appendChild(label); const div = document.createElement('div'); div.classList.add('option-input-container', 'trigger-before-seconds'); const input = document.createElement('input'); div.appendChild(input); input.type = 'text'; input.step = 'any'; // Say "(default)" for more complicated things like functions. let defaultValue = this.base.translate(kMiscTranslations.valueDefault); if (trig.beforeSeconds === undefined) defaultValue = '0'; else if (typeof trig.beforeSeconds === 'number') defaultValue = trig.beforeSeconds.toString(); input.placeholder = defaultValue; input.value = this.base.getStringOption('raidboss', ['triggers', trigId, optionKey], ''); const setFunc = () => { const val = validDurationOrUndefined(input.value) || ''; this.base.setOption('raidboss', ['triggers', trigId, optionKey], val); }; input.onchange = setFunc; input.oninput = setFunc; triggerDetails.appendChild(div); } // Add duration manually with an input to override. if (hasOutputFunc) { const detailKey = 'duration'; const optionKey = kOptionKeys.duration; const label = document.createElement('div'); label.innerText = this.base.translate(kDetailKeys[detailKey].label); label.classList.add('trigger-label'); triggerDetails.appendChild(label); const div = document.createElement('div'); div.classList.add('option-input-container', 'trigger-duration'); const input = document.createElement('input'); div.appendChild(input); input.type = 'text'; input.step = 'any'; if (typeof trig.durationSeconds === 'number') input.placeholder = `${trig.durationSeconds}`; else input.placeholder = this.base.translate(kMiscTranslations.valueDefault); input.value = this.base.getStringOption('raidboss', ['triggers', trigId, optionKey], ''); const setFunc = () => { const val = validDurationOrUndefined(input.value) || ''; this.base.setOption('raidboss', ['triggers', trigId, optionKey], val); }; input.onchange = setFunc; input.oninput = setFunc; triggerDetails.appendChild(div); } // Add output strings manually const outputStrings = trig.outputStrings || {}; for (const [key, outputString] of Object.entries(outputStrings)) { const optionKey = kOptionKeys.outputStrings; const template = typeof outputString === 'string' ? outputString : this.base.translate(outputString); const label = document.createElement('div'); label.innerText = key; label.classList.add('trigger-outputstring-label'); triggerDetails.appendChild(label); const div = document.createElement('div'); div.classList.add('option-input-container', 'trigger-outputstring'); const input = document.createElement('input'); div.appendChild(input); input.type = 'text'; input.placeholder = template; input.value = this.base.getStringOption( 'raidboss', ['triggers', trigId, optionKey, key], '', ); const setFunc = () => this.base.setOption('raidboss', ['triggers', trigId, optionKey, key], input.value); input.onchange = setFunc; input.oninput = setFunc; triggerDetails.appendChild(div); } const label = document.createElement('div'); triggerDetails.appendChild(label); const path = key.split('-'); const [p0, p1, p2] = path; if (p0 !== undefined && p1 !== undefined && p2 !== undefined) { const div = document.createElement('div'); div.classList.add('option-input-container', 'trigger-source'); const baseUrl = 'https://github.com/quisquous/cactbot/blob/triggers'; let urlFilepath; if (path.length === 3) { // 00-misc/general.js urlFilepath = `${p0}-${p1}/${[...path].slice(2).join('-')}`; } else { // 02-arr/raids/t1.js urlFilepath = `${p0}-${p1}/${p2}/${[...path].slice(3).join('-')}`; } const escapedTriggerId = trigId.replace(/'/g, '\\\''); const uriComponent = encodeURIComponent(`id: '${escapedTriggerId}'`).replace(/'/g, '%27'); const urlString = `${baseUrl}/${urlFilepath}.js#:~:text=${uriComponent}`; div.innerHTML = `<a href="${urlString}" target="_blank">(${ this.base.translate(kMiscTranslations.viewTriggerSource) })</a>`; triggerDetails.appendChild(div); } } } } // This duplicates the raidboss function of the same name. valueOrFunction( f: RaidbossTriggerField, data: RaidbossData, matches: Matches, output: Output, ): RaidbossTriggerOutput { const result = (typeof f === 'function') ? f(data, matches, output) : f; if (result !== Object(result)) return result; if (typeof result !== 'object' || result === null) return result; if (result[this.alertsLang]) return this.valueOrFunction(result[this.alertsLang], data, matches, output); if (result[this.timelineLang]) return this.valueOrFunction(result[this.timelineLang], data, matches, output); // For partially localized results where this localization doesn't // exist, prefer English over nothing. return this.valueOrFunction(result['en'], data, matches, output); } processTrigger(trig: ConfigLooseTrigger): ConfigLooseTrigger { // TODO: with some hackiness (e.g. regexes?) we could figure out which // output string came from which alert type (alarm, alert, info, tts). // See `makeOutput` comments for why this needs a type assertion to be an Output. const fakeOutputProxy = new DoNothingFuncProxy((outputStrings: OutputStrings) => { trig.outputStrings = trig.outputStrings || {}; Object.assign(trig.outputStrings, outputStrings); }) as Output; const baseFakeData: RaidbossData = { me: '', job: 'NONE', role: 'none', party: new PartyTracker(), lang: this.base.lang, currentHP: 1000, options: this.base.configOptions, ShortName: (x?: string) => x ?? '???', StopCombat: () => {/* noop */}, ParseLocaleFloat: parseFloat, CanStun: () => false, CanSilence: () => false, CanSleep: () => false, CanCleanse: () => false, CanFeint: () => false, CanAddle: () => false, parserLang: this.base.lang, displayLang: this.base.lang, }; type PartialFakeDataEntry = { me: string; job: Job; role: Role }; const partialFakeDataEntries: PartialFakeDataEntry[] = [ { me: 'Tini Poutini', job: 'GNB', role: 'tank', }, { me: 'Potato Chippy', job: 'WHM', role: 'healer', }, { me: 'Tater Tot', job: 'BLM', role: 'dps', }, { me: 'Hash Brown', job: 'DRG', role: 'dps', }, { me: 'Aloo Gobi', job: 'BLU', role: 'dps', }, ]; const fakeDataEntries: RaidbossData[] = partialFakeDataEntries.map((x) => { return Object.assign({}, x, baseFakeData); }); const firstData = fakeDataEntries[0]; if (!firstData) throw new UnreachableCode(); const kFakeMatches = { // TODO: really should convert all triggers to use regexes.js. // Mooooost triggers use matches[1] to be a name. 1: firstData.me, sourceId: '41234567', source: 'Enemy', id: '1234', ability: 'Ability', targetId: '1234567', target: firstData.me, flags: '', x: '100', y: '100', z: '0', heading: '0', npcId: '', effect: 'Effect', duration: '30', code: '00', line: '', name: 'Name', }; const output: { [key in keyof LooseTrigger]: string } = {}; const outputKeys = ['alarmText', 'alertText', 'infoText', 'tts', 'sound'] as const; type OutputKey = typeof outputKeys[number]; // Try to determine some sample output? // This could get much more complicated if we wanted it to. const evalTrigger = (trig: LooseTrigger, key: OutputKey, data: RaidbossData) => { try { const result = this.valueOrFunction(trig[key], data, kFakeMatches, fakeOutputProxy); if (!result) return false; // Super hack: const resultStr = result.toString(); if (resultStr.includes('undefined') || resultStr.includes('NaN')) return false; output[key] = resultStr; return true; } catch (e) { // This is all totally bogus. Many triggers assume fields on data // are properly defined when these calls happen, so will throw errors. // So just silently ignore. return false; } }; // Handle 'response' first. if (trig.response) { const r = trig.response; for (const data of fakeDataEntries) { try { // Can't use ValueOrFunction here as r returns a non-localizable object. // FIXME: this hackily replicates some raidboss logic too. let response: typeof trig.response | undefined = r; while (typeof response === 'function') { // TODO: check if this has builtInResponseStr first. response = response(data, kFakeMatches, fakeOutputProxy); } if (!response) continue; if (!trig.outputStrings) { for (const key of outputKeys) evalTrigger(response, key, data); } break; } catch (e) { continue; } } } // Only evaluate fields if there are not outputStrings. // outputStrings will indicate more clearly what the trigger says. if (!trig.outputStrings) { for (const key of outputKeys) { if (!(key in trig)) continue; for (const data of fakeDataEntries) { if (evalTrigger(trig, key, data)) break; } } } trig.configOutput = output; const lang = this.base.lang; const langSpecificRegexes = [ 'netRegexDe', 'netRegexFr', 'netRegexJa', 'netRegexCn', 'netRegexKo', 'regexDe', 'regexFr', 'regexJa', 'regexCn', 'regexKo', ] as const; const getRegex = (baseField: 'regex' | 'netRegex') => { const shortLanguage = lang.charAt(0).toUpperCase() + lang.slice(1); const concatStr = langSpecificRegexes.find((x) => x === `${baseField}${shortLanguage}`); if (!concatStr) return; const langSpecificRegex = trig[concatStr] ?? trig[baseField]; if (!langSpecificRegex) return; const baseRegex = Regexes.parse(langSpecificRegex); if (!baseRegex) return; return Regexes.parse(baseRegex); }; if (trig.isTimelineTrigger) { trig.timelineRegex = getRegex('regex'); } else { trig.triggerRegex = getRegex('regex'); trig.triggerNetRegex = getRegex('netRegex'); } return trig; } processRaidbossFiles( files: RaidbossFileData, userOptions: RaidbossOptions, ): ConfigProcessedFileMap<ConfigLooseTriggerSet> { // `files` is map of filename => triggerSet (for trigger files) // `map` is a sorted map of shortened zone key => { various fields, triggerSet } const triggerFiles: { [filename: string]: ConfigLooseTriggerSet } = {}; for (const [filename, triggerSetOrString] of Object.entries(files)) { if (typeof triggerSetOrString === 'string') continue; triggerFiles[filename] = triggerSetOrString; } const map = this.base.processFiles<ConfigLooseTriggerSet>(triggerFiles, userOptions.Triggers); let triggerIdx = 0; // While walking through triggers, record any previous triggers with the same // id so that the ui can disable overriding information. const previousTriggerWithId: { [id: string]: ConfigLooseTrigger } = {}; for (const item of Object.values(map)) { // TODO: maybe each trigger set needs a zone name, and we should // use that instead of the filename??? const rawTriggers: { trigger: LooseTrigger[]; timeline: LooseTrigger[] } = { trigger: [], timeline: [], }; const triggerSet = item.triggerSet; if (triggerSet.triggers) rawTriggers.trigger.push(...triggerSet.triggers); if (triggerSet.timelineTriggers) rawTriggers.timeline.push(...triggerSet.timelineTriggers); item.triggers = {}; for (const [key, triggerArr] of Object.entries(rawTriggers)) { for (const baseTrig of triggerArr) { const trig: ConfigLooseTrigger = baseTrig; triggerIdx++; if (!trig.id) { // Give triggers with no id some "unique" string so that they can // still be added to the set and show up in the ui. trig.id = `!!NoIdTrigger${triggerIdx}`; trig.isMissingId = true; } // Track if this trigger overrides any previous trigger. const previous = previousTriggerWithId[trig.id]; if (previous) previous.overriddenByFile = triggerSet.filename; previousTriggerWithId[trig.id] = trig; trig.isTimelineTrigger = key === 'timeline'; // Also, if a user has two of the same id in the same triggerSet (?!) // then only the second trigger will show up. item.triggers[trig.id] = this.processTrigger(trig); } } } return map; } buildTriggerOptions(trig: LooseTrigger, labelDiv: HTMLElement) { // This shouldn't happen, as all triggers should be processed with a unique id. const trigId = trig.id; if (!trigId) throw new UnreachableCode(); const optionKey = kOptionKeys.output; const div = document.createElement('div'); div.classList.add('trigger-options'); const updateLabel = (input: HTMLOptionElement | HTMLSelectElement) => { if (input.value === 'hidden' || input.value === 'disabled') labelDiv.classList.add('disabled'); else labelDiv.classList.remove('disabled'); }; const input = document.createElement('select'); div.appendChild(input); const selectValue = this.base.getOption( 'raidboss', ['triggers', trigId, optionKey], 'default', ); for (const [key, opt] of Object.entries(triggerSoundOptions)) { // Hide debug only options unless they are selected. // Otherwise, it will look weird to pick something like 'Disabled', // but then not show it when developer options are turned off. if (!this.base.developerOptions && opt.debugOnly && key !== selectValue) continue; const elem = document.createElement('option'); elem.innerHTML = this.base.translate(opt.label); elem.value = key; elem.selected = key === selectValue; input.appendChild(elem); updateLabel(input); input.onchange = () => { updateLabel(input); let value = input.value; if (value.includes('default')) value = 'default'; this.base.setOption('raidboss', ['triggers', trigId, optionKey], input.value); }; } return div; } } // Raidboss needs to do some extra processing of user files. const userFileHandler: UserFileCallback = ( name: string, files: { [filename: string]: string }, baseOptions: BaseOptions, basePath: string, ) => { // TODO: Rewrite user_config to be templated on option type so that this function knows // what type of options it is using. const options = baseOptions as RaidbossOptions; if (!options.Triggers) return; for (const baseTriggerSet of options.Triggers) { const set: ConfigLooseTriggerSet = baseTriggerSet; // Annotate triggers with where they came from. Note, options is passed in repeatedly // as multiple sets of user files add triggers, so only process each file once. if (set.isUserTriggerSet) continue; // `filename` here is just cosmetic for better debug printing to make it more clear // where a trigger or an override is coming from. set.filename = `${basePath}${name}`; set.isUserTriggerSet = true; // Convert set.timelineFile to set.timeline. if (set.timelineFile) { const lastIndex = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); // If lastIndex === -1, truncate name to the empty string. // if lastIndex > -1, truncate name after the final slash. const dir = name.substring(0, lastIndex + 1); const timelineFile = `${dir}${set.timelineFile}`; delete set.timelineFile; if (!(timelineFile in files)) { console.log(`ERROR: '${name}' specifies non-existent timeline file '${timelineFile}'.`); continue; } // set.timeline is processed recursively. set.timeline = [set.timeline, files[timelineFile]]; } } }; const templateOptions: OptionsTemplate = { buildExtraUI: (base, container) => { const builder = new RaidbossConfigurator(base); const userOptions = { ...raidbossOptions }; UserConfig.loadUserFiles('raidboss', userOptions, () => { builder.buildUI(container, raidbossFileData, userOptions); }); }, processExtraOptions: (baseOptions, savedConfig) => { // raidboss will look up this.options.PerTriggerAutoConfig to find these values. const optionName = 'PerTriggerAutoConfig'; // TODO: Rewrite user_config to be templated on option type so that this function knows // what type of options it is using. Without this, perTriggerAutoConfig is unknown. const options = baseOptions as RaidbossOptions; const perTriggerAutoConfig = options[optionName] ??= {}; if (typeof savedConfig !== 'object' || Array.isArray(savedConfig)) return; const triggers = savedConfig['triggers']; if (!triggers || typeof triggers !== 'object' || Array.isArray(triggers)) return; const outputObjs: { [key: string]: TriggerAutoConfig } = {}; const keys = Object.keys(kTriggerOptions); for (const key of keys) { const obj = outputObjs[key] = {}; setOptionsFromOutputValue(obj, key); } for (const [id, entry] of Object.entries(triggers)) { if (typeof entry !== 'object' || Array.isArray(entry)) return; const autoConfig: TriggerAutoConfig = {}; const output = entry[kOptionKeys.output]?.toString(); if (output) Object.assign(autoConfig, outputObjs[output]); const duration = validDurationOrUndefined(entry[kOptionKeys.duration]); if (duration) autoConfig[kOptionKeys.duration] = duration; const beforeSeconds = validDurationOrUndefined(entry[kOptionKeys.beforeSeconds]); if (beforeSeconds) autoConfig[kOptionKeys.beforeSeconds] = beforeSeconds; const outputStrings = entry[kOptionKeys.outputStrings]; // Validate that the SavedConfigEntry is an an object with string values, // which is a subset of the OutputStrings type. if ( ((entry?: SavedConfigEntry): entry is { [key: string]: string } => { if (typeof entry !== 'object' || Array.isArray(entry)) return false; for (const value of Object.values(entry)) { if (typeof value !== 'string') return false; } return true; })(outputStrings) ) autoConfig[kOptionKeys.outputStrings] = outputStrings; if (output || duration || outputStrings) perTriggerAutoConfig[id] = autoConfig; } }, options: [ { id: 'Coverage', name: { en: 'Supported content (latest version)', de: 'Unterstützte Inhalte (aktuellste Version)', fr: 'Contenu supporté (dernière version)', ja: '対応コンテンツ一覧 (最新バージョン)', cn: '支持副本一览 (含未发布更新)', ko: '지원하는 컨텐츠 (릴리즈버전보다 최신)', }, type: 'html', html: { // TODO: it'd be nice if OverlayPlugin could open links on the system outside of ACT. en: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=en'), de: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=de'), fr: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=fr'), ja: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=ja'), cn: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=cn'), ko: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=ko'), }, default: makeLink('https://quisquous.github.io/cactbot/util/coverage/coverage.html?lang=en'), }, { id: 'Debug', name: { en: 'Enable debug mode', de: 'Aktiviere Debugmodus', fr: 'Activer le mode debug', ja: 'デバッグモードを有効にする', cn: '启用调试模式', ko: '디버그 모드 활성화', }, type: 'checkbox', debugOnly: true, default: false, }, { id: 'DefaultAlertOutput', name: { en: 'Default alert output', de: 'Standard Alert Ausgabe', fr: 'Alerte par défaut', ja: '警告情報出力既定値', cn: '默认警报提示信息输出方式', ko: '기본 알람 출력 방식', }, type: 'select', options: { en: { '🆙🔊 Text and Sound': 'textAndSound', '🆙💬 Text and TTS': 'ttsAndText', '💬 TTS Only': 'ttsOnly', '🆙 Text Only': 'textOnly', '❌ Disabled': 'disabled', }, de: { '🆙🔊 Text und Ton': 'textAndSound', '🆙💬 Text und TTS': 'ttsAndText', '💬 Nur TTS': 'ttsOnly', '🆙 Nur Text': 'textOnly', '❌ Deaktiviert': 'disabled', }, fr: { '🆙🔊 Texte et son': 'textAndSound', '🆙💬 Texte et TTS': 'ttsAndText', '💬 TTS seulement': 'ttsOnly', '🆙 Texte seulement': 'textOnly', '❌ Désactivé': 'disabled', }, ja: { '🆙🔊 テキストと音声': 'textAndSound', '🆙💬 テキストとTTS': 'ttsAndText', '💬 TTSのみ': 'ttsOnly', '🆙 テキストのみ': 'textOnly', '❌ 無効': 'disabled', }, cn: { '🆙🔊 文字显示与提示音': 'textAndSound', '🆙💬 文字显示与TTS': 'ttsAndText', '💬 只使用TTS': 'ttsOnly', '🆙 只使用文字显示': 'textOnly', '❌ 禁用': 'disabled', }, ko: { '🆙🔊 텍스트와 소리': 'textAndSound', '🆙💬 텍스트와 TTS': 'ttsAndText', '💬 TTS만': 'ttsOnly', '🆙 텍스트만': 'textOnly', '❌ 비활성화': 'disabled', }, }, default: 'textAndSound', setterFunc: setOptionsFromOutputValue, }, { id: 'AlertsLanguage', name: { en: 'Alerts language', de: 'Alert Sprache', fr: 'Langue des alertes', ja: '警告情報の言語', cn: '警报提示文字的语言', ko: '알람 언어', }, type: 'select', options: { en: { 'Use Display Language': 'default', 'English (en)': 'en', 'Chinese (cn)': 'cn', 'German (de)': 'de', 'French (fr)': 'fr', 'Japanese (ja)': 'ja', 'Korean (ko)': 'ko', }, fr: { 'Utiliser la langue d\'affichage': 'default', 'Anglais (en)': 'en', 'Chinois (cn)': 'cn', 'Allemand (de)': 'de', 'Français (fr)': 'fr', 'Japonais (ja)': 'ja', 'Coréen (ko)': 'ko', }, ja: { '表示言語既定値': 'default', '英語 (en)': 'en', '中国語 (cn)': 'cn', 'ドイツ語 (de)': 'de', 'フランス語 (fr)': 'fr', '日本語 (ja)': 'ja', '韓国語 (ko)': 'ko', }, cn: { '使用显示语言': 'default', '英语 (en)': 'en', '汉语 (cn)': 'cn', '德语 (de)': 'de', '法语 (fr)': 'fr', '日语 (ja)': 'ja', '韩语 (ko)': 'ko', }, ko: { '주 사용 언어 사용': 'default', '영어 (en)': 'en', '중국어 (cn)': 'cn', '독일어 (de)': 'de', '프랑스어 (fr)': 'fr', '일본어 (ja)': 'ja', '한국어 (ko)': 'ko', }, }, default: 'default', debug: true, setterFunc: (options, value) => { if (value === 'default') return; options['AlertsLanguage'] = value; }, }, { id: 'TimelineLanguage', name: { en: 'Timeline language', de: 'Timeline Sprache', fr: 'Langue de la timeline', ja: 'タイムラインの言語', cn: '时间轴文本的语言', ko: '타임라인 언어', }, type: 'select', options: { en: { 'Use FFXIV Plugin Language': 'default', 'English (en)': 'en', 'Chinese (cn)': 'cn', 'German (de)': 'de', 'French (fr)': 'fr', 'Japanese (ja)': 'ja', 'Korean (ko)': 'ko', }, de: { 'Benutze FFXIV Plugin Sprache': 'default', 'Englisch (en)': 'en', 'Chinesisch (cn)': 'cn', 'Deutsch (de)': 'de', 'Französisch (fr)': 'fr', 'Japanisch (ja)': 'ja', 'Koreanisch (ko)': 'ko', }, fr: { 'Utiliser la langue du Plugin FFXIV': 'default', 'Anglais (en)': 'en', 'Chinois (cn)': 'cn', 'Allemand (de)': 'de', 'Français (fr)': 'fr', 'Japonais (ja)': 'ja', 'Coréen (ko)': 'ko', }, ja: { 'FFXIV Pluginの言語設定': 'default', '英語 (en)': 'en', '中国語 (cn)': 'cn', 'ドイツ語 (de)': 'de', 'フランス語 (fr)': 'fr', '日本語 (ja)': 'ja', '韓国語 (ko)': 'ko', }, cn: { '使用最终幻想XIV解析插件设置的语言': 'default', '英语 (en)': 'en', '汉语 (cn)': 'cn', '德语 (de)': 'de', '法语 (fr)': 'fr', '日语 (ja)': 'ja', '韩语 (ko)': 'ko', }, ko: { 'FFXIV Plugin 언어 사용': 'default', '영어 (en)': 'en', '중국어 (cn)': 'cn', '독일어 (de)': 'de', '프랑스어 (fr)': 'fr', '일본어 (ja)': 'ja', '한국어 (ko)': 'ko', }, }, default: 'default', debug: true, setterFunc: (options, value) => { if (value === 'default') return; options['TimelineLanguage'] = value; }, }, { id: 'Skin', name: { en: 'Raidboss Skin', de: 'Raidboss Skin', fr: 'Raidboss Skin', ja: 'Raidbossのスキン', cn: 'Raidboss皮肤', ko: 'Raidboss 스킨', }, type: 'select', options: { en: { 'Default': 'default', 'lippe': 'lippe', }, de: { 'Default': 'default', 'lippe': 'lippe', }, fr: { 'Défaut': 'default', 'lippe': 'lippe', }, ja: { '初期設定': 'default', 'lippe': 'lippe', }, cn: { '默认': 'default', 'lippe': 'lippe', }, ko: { '기본': 'default', 'lippe': 'lippe', }, }, default: 'default', }, { id: 'TimelineEnabled', name: { en: 'Timeline enabled', de: 'Timeline aktiviert', fr: 'Timeline activée', ja: 'タイムラインを有効にする', cn: '启用时间轴', ko: '타임라인 활성화', }, type: 'checkbox', default: true, }, { id: 'AlertsEnabled', name: { en: 'Alerts enabled', de: 'Alerts aktiviert', fr: 'Alertes activées', ja: '警告情報を有効にする', cn: '启用提示文本显示', ko: '알람 활성화', }, type: 'checkbox', default: true, }, { id: 'ShowTimerBarsAtSeconds', name: { en: 'Timer bar show window (seconds)', de: 'Timer-Bar Anzeigedauer (in Sekunden)', fr: 'Fenêtre d\'affichage de la barre de temps (secondes)', ja: 'タイムバーに時間表示 (秒)', cn: '计时条显示时长 (秒)', ko: '타임라인을 표시할 기준 시간 (초 이하)', }, type: 'float', default: 30, }, { id: 'KeepExpiredTimerBarsForSeconds', name: { en: 'Keep expired timer bar (seconds)', de: 'Behalte abgelaufene Timer-Bar (in Sekunden)', fr: 'Garder la barre de temps expirée (secondes)', ja: '終了したタイムバーが消えるまでの待ち時間 (秒)', cn: '已失效的计时条的淡出时间 (秒)', ko: '만료된 타임라인이 사라지기까지의 시간 (초)', }, type: 'float', default: 0.7, }, { id: 'BarExpiresSoonSeconds', name: { en: 'Time to recolor timer as expiring soon (seconds)', de: 'Zeit bis ein bald auslaufender Timer umgefärbt wird (in Sekunden)', fr: 'Recolorisation de la barre de temps avant expiration (secondes)', ja: 'タイムバーが終了前に再度色付けの残り時間 (秒)', cn: '倒计时小于该值时当前计时条变色 (秒)', ko: '타임라인의 색상을 바꿀 기준 시간 (초 이하)', }, type: 'integer', default: 6, }, { id: 'MaxNumberOfTimerBars', name: { en: 'Max number of timer bars', de: 'Max Anzahl an Timer-Bars', fr: 'Nombre max de barres de temps', ja: 'タイムバーの最大数', cn: '计时条最大数量', ko: '표시할 타임라인의 최대 개수', }, type: 'integer', default: 6, }, { id: 'DisplayAlarmTextForSeconds', name: { en: 'Alarm text display duration (seconds)', de: 'Alarm-Text Anzeigedauer (in Sekunden)', fr: 'Durée d\'affichage du texte d\'alarme (secondes)', ja: '警報テキスト表示時間の長さ (秒)', cn: '警报文字显示持续时间 (秒)', ko: '경고 텍스트를 표시할 시간 (초)', }, type: 'float', default: 3, }, { id: 'DisplayAlertTextForSeconds', name: { en: 'Alert text display duration (seconds)', de: 'Alert-Text Anzeigedauer (in Sekunden)', fr: 'Durée d\'affichage du texte d\'alerte (secondes)', ja: '警告テキスト表示時間の長さ (秒)', cn: '警告文字显示持续时间 (秒)', ko: '주의 텍스트를 표시할 시간 (초)', }, type: 'float', default: 3, }, { id: 'DisplayInfoTextForSeconds', name: { en: 'Info text display duration (seconds)', de: 'Info-Text Anzeigedauer (in Sekunden)', fr: 'Durée d\'affichage du texte d\'information (secondes)', ja: '情報テキスト表示時間の長さ (秒)', cn: '信息文字显示持续时间 (秒)', ko: '안내 텍스트를 표시할 시간 (초)', }, type: 'float', default: 3, }, { id: 'AlarmSoundVolume', name: { en: 'Alarm sound volume (0-1)', de: 'Alarm Lautstärke (0-1)', fr: 'Volume de l\'alarme (0-1)', ja: '警報音声の音量 (0-1)', cn: '警报提示音的音量 (0-1)', ko: '경고 소리 크기 (0-1)', }, type: 'float', default: 1, }, { id: 'AlertSoundVolume', name: { en: 'Alert sound volume (0-1)', de: 'Alert Lautstärke (0-1)', fr: 'Volume de l\'alerte (0-1)', ja: '警告音声の音量 (0-1)', cn: '警告提示音的音量 (0-1)', ko: '주의 소리 크기 (0-1)', }, type: 'float', default: 1, }, { id: 'InfoSoundVolume', name: { en: 'Info sound volume (0-1)', de: 'Info Lautstärke (0-1)', fr: 'Volume de l\'info (0-1)', ja: '情報音声の音量 (0-1)', cn: '信息提示音的音量 (0-1)', ko: '안내 소리 크기 (0-1)', }, type: 'float', default: 1, }, { id: 'LongSoundVolume', name: { en: 'Long sound volume (0-1)', de: 'Langer Ton Lautstärke (0-1)', fr: 'Volume du son long (0-1)', ja: '長い音声の音量 (0-1)', cn: '长提示音的音量 (0-1)', ko: '긴 소리 크기 (0-1)', }, type: 'float', default: 1, }, { id: 'PullSoundVolume', name: { en: 'Pull sound volume (0-1)', de: 'Pull Lautstärke (0-1)', fr: 'Volume du son de pull (0-1)', ja: 'タゲ取る効果音の音量 (0-1)', cn: '开怪提示音的音量 (0-1)', ko: '풀링 소리 크기 (0-1)', }, type: 'float', default: 1, }, { id: 'cactbotWormholeStrat', // TODO: maybe need some way to group these kinds of // options if we end up having a lot? name: { en: 'Alex Ultimate: enable cactbot Wormhole strat', de: 'Alex Ultimate: aktiviere cactbot Wormhole Strategie', fr: 'Alex fatal : activer cactbot pour la strat Wormhole', ja: '絶アレキサンダー討滅戦:cactbot「次元断絶のマーチ」ギミック', cn: '亚历山大绝境战:cactbot灵泉辅助功能', ko: '절 알렉: cactbot 웜홀 공략방식 활성화', }, type: 'checkbox', default: false, }, { id: 'cactbote8sUptimeKnockbackStrat', name: { en: 'e8s: enable cactbot Uptime Knockback strat', de: 'e8s: aktiviere cactbot Uptime Knockback Strategie', fr: 'e8s : activer cactbot pour la strat Uptime Knockback', ja: 'エデン零式共鳴編4層:cactbot「ヘヴンリーストライク (ノックバック)」ギミック', cn: 'E8S: 启用cactbot的击退提示功能', ko: '공명 영웅 4층: cactbot 정확한 타이밍 넉백방지 공략 활성화', }, type: 'checkbox', default: false, }, ], }; UserConfig.registerOptions('raidboss', templateOptions, userFileHandler);
the_stack
import { SwaggerSailsModel, NameKeyMap, SwaggerRouteInfo, BlueprintActionTemplates, Defaults, Action2Response } from './interfaces'; import { Reference, Tag } from 'swagger-schema-official'; import { swaggerTypes, sailsAttributePropertiesMap, validationsMap, actions2Responses, blueprintParameterTemplates } from './type-formatter'; import assign from 'lodash/assign'; import defaults from 'lodash/defaults'; import mapKeys from 'lodash/mapKeys'; import pick from 'lodash/pick'; import keys from 'lodash/keys'; import cloneDeep from 'lodash/cloneDeep'; import isFunction from 'lodash/isFunction'; import forEach from 'lodash/forEach'; import { OpenApi } from '../types/openapi'; import set from 'lodash/set'; import { map, omit, isEqual, reduce, uniq } from 'lodash'; import { attributeValidations, resolveRef, unrollSchema, deriveSwaggerTypeFromExample } from './utils'; /** * Generate Swagger schema content describing the specified Sails attribute. * * XXX TODO: add test to this function * * @see https://swagger.io/docs/specification/data-models/ * @param {Record<string, any>} attribute Sails model attribute specification as per `Model.js` file */ export const generateAttributeSchema = (attribute: Sails.AttributeDefinition): OpenApi.UpdatedSchema => { const ai = attribute || {}, sts = swaggerTypes; const type = ai.type || 'string'; const columnType = ai.autoMigrations?.columnType; const autoIncrement = ai.autoMigrations?.autoIncrement; let schema: OpenApi.UpdatedSchema = {}; const formatDesc = (extra: string): string => { const ret: string[] = []; if(ai.description) ret.push(ai.description); if(extra) ret.push(extra); return ret.join(' '); } if (ai.meta?.swagger && 'type' in ai.meta.swagger) { // OpenAPI 3 stipulates NO type as 'any', allow this by 'type' present but null to achieve this if(ai.meta.swagger.type) schema.type = ai.meta.swagger.type; } else if (ai.model) { assign(schema, { description: formatDesc(`JSON dictionary representing the **${ai.model}** instance or FK when creating / updating / not populated`), // '$ref': '#/components/schemas/' + ai.model, oneOf: [ // we use oneOf (rather than simple ref) so description rendered (!) (at least in redocly) { '$ref': '#/components/schemas/' + ai.model }, ], }); } else if (ai.collection) { assign(schema, { description: formatDesc(`Array of **${ai.collection}**'s or array of FK's when creating / updating / not populated`), type: 'array', items: { '$ref': '#/components/schemas/' + ai.collection }, }); } else if (type == 'number') { let t = autoIncrement ? sts.integer : sts.double; if (ai.validations?.isInteger) { t = sts.integer; } else if (columnType) { const ct = columnType; if (ct.match(/int/i)) t = sts.integer; else if (ct.match(/long/i)) t = sts.long; else if (ct.match(/float/i)) t = sts.float; else if (ct.match(/double/i)) t = sts.double; else if (ct.match(/decimal/i)) t = sts.double; } assign(schema, t); } else if (type == 'boolean') { assign(schema, sts.boolean); } else if (type == 'json') { assign(schema, deriveSwaggerTypeFromExample(ai.example || ai.defaultsTo)); } else if (type == 'ref') { let t: OpenApi.UpdatedSchema | undefined; if (columnType) { const ct = columnType; if (ct.match(/timestamp/i)) t = sts.datetime; else if (ct.match(/datetime/i)) t = sts.datetime; else if (ct.match(/date/i)) t = sts.date; } if(t === undefined) t = deriveSwaggerTypeFromExample(ai.example || ai.defaultsTo); assign(schema, t); } else { // includes =='string' assign(schema, sts.string); } let isIP = false; if (schema.type == 'string') { const v = ai.validations; if (v) { if (v.isEmail) schema.format = 'email'; if (v.isIP) { isIP = true; schema.format = 'ipv4'; } if (v.isURL) schema.format = 'uri'; if (v.isUUID) schema.format = 'uuid'; if (v.regex) schema.pattern = v.regex.toString().slice(1, -1); } } const annotations = []; // annotate format with Sails autoCreatedAt/autoUpdatedAt if (schema.type == 'string' && schema.format == 'date-time') { if (ai.autoCreatedAt) annotations.push('autoCreatedAt'); else if (ai.autoUpdatedAt) annotations.push('autoUpdatedAt'); } // process Sails --> Swagger attribute mappings as per sailAttributePropertiesMap defaults(schema, mapKeys(pick(ai, keys(sailsAttributePropertiesMap)), (v, k: keyof Sails.AttributeDefinition) => sailsAttributePropertiesMap[k])); // process Sails --> Swagger attribute mappings as per validationsMap defaults(schema, mapKeys(pick(ai.validations, keys(validationsMap)), (v, k: keyof Sails.AttributeValidation) => validationsMap[k])); // copy default into example if present if (schema.default && !schema.example) { schema.example = schema.default; } // process final autoMigrations: autoIncrement, unique if (autoIncrement) { annotations.push('autoIncrement'); } if (ai.autoMigrations?.unique) { schema.uniqueItems = true; } // represent Sails `isIP` as one of ipv4/ipv6 if (schema.type == 'string' && isIP) { schema = { description: formatDesc('ipv4 or ipv6 address'), oneOf: [ cloneDeep(schema), assign(cloneDeep(schema), { format: 'ipv6' }), ] } } if (annotations.length > 0) { const s = `Note Sails special attributes: ${annotations.join(', ')}`; schema.description = schema.description ? `${schema.description}\n\n${s}` : s; } if(schema.description) schema.description = schema.description.trim(); // note: required --> required[] (not here, needs to be done at model level) // finally, overwrite in custom swagger if(ai.meta?.swagger) { // note: 'type' handled above assign(schema, omit(ai.meta.swagger, 'exclude', 'type', 'in')); } return schema; } /** * Generate the OpenAPI schemas for the foreign key values used to reference * ORM records for the associations of the specified Sails Model. * * Used for 'replace' REST blueprint. * * @param model * @param models */ export const generateModelAssociationFKAttributeSchemas = (model: SwaggerSailsModel, aliasesToInclude: string[] | undefined, models: NameKeyMap<SwaggerSailsModel>): OpenApi.UpdatedSchema[] => { if (!model.associations) { return []; } return model.associations.map(association => { if (!aliasesToInclude || aliasesToInclude.indexOf(association.alias) < 0) return; const targetModelIdentity = association.type === 'model' ? association.model : association.collection; const targetModel = models[targetModelIdentity!]; if (!targetModel) { return; // data structure integrity issue should not occur } const description = association.type === 'model' ? `**${model.globalId}** record's foreign key value to use as the replacement for this attribute` : `**${model.globalId}** record's foreign key values to use as the replacement for this collection`; const targetFKAttribute = targetModel.attributes[targetModel.primaryKey]; return generateAttributeSchema({ ...targetFKAttribute, autoMigrations: { ...(targetFKAttribute.autoMigrations || {}), autoIncrement: false, // autoIncrement not relevant for FK parameter }, description: `${description} (**${association.alias}** association${targetFKAttribute.description ? '; ' + targetFKAttribute.description : ''})` }); }) .filter(parameter => parameter) as OpenApi.UpdatedSchema[]; } /** * Generate the OpenAPI parameters for the foreign key values used to reference * ORM records for the associations of the specified Sails Model. * * Used for 'replace' shortcut blueprint. * * @param model * @param aliasesToInclude * @param models */ export const generateModelAssociationFKAttributeParameters = (model: SwaggerSailsModel, aliasesToInclude: string[] | undefined, models: NameKeyMap<SwaggerSailsModel>): OpenApi.Parameter[] => { if (!model.associations) { return []; } return model.associations.map(association => { if (!aliasesToInclude || aliasesToInclude.indexOf(association.alias) < 0) return; const targetModelIdentity = association.type === 'model' ? association.model : association.collection; const targetModel = models[targetModelIdentity!]; if (!targetModel) { return; // data structure integrity issue should not occur } const description = association.type === 'model' ? `**${model.globalId}** record's foreign key value to use as the replacement for this attribute` : `**${model.globalId}** record's foreign key values to use as the replacement for this collection`; const targetFKAttribute = targetModel.attributes[targetModel.primaryKey]; const targetFKAttributeSchema = generateAttributeSchema({ ...targetFKAttribute, autoMigrations: { ...(targetFKAttribute.autoMigrations || {}), autoIncrement: false, // autoIncrement not relevant for FK parameter }, description: `${description} (**${association.alias}** association${targetFKAttribute.description ? '; ' + targetFKAttribute.description : ''})` }); return { in: 'query' as OpenApi.ParameterLocation, name: association.alias, description: targetFKAttributeSchema.description, schema: { type: 'array', items: targetFKAttributeSchema, }, } as OpenApi.Parameter; }) .filter(parameter => parameter) as OpenApi.Parameter[]; } export const generateSchemaAsQueryParameters = (schema: OpenApi.UpdatedSchema): OpenApi.Parameter[] => { const required = schema.required || []; return map(schema.properties || {}, (property, name) => { const parameter = { in: 'query' as OpenApi.ParameterLocation, name: name, schema: property, } as OpenApi.Parameter; if((property as OpenApi.UpdatedSchema).description) { parameter.description = (property as OpenApi.UpdatedSchema).description; } if(required.indexOf(name) >= 0) { parameter.required = true; } return parameter; }); } /** * Generate Swagger schema content describing specified Sails models. * * @see https://swagger.io/docs/specification/data-models/ * * @param models parsed Sails models as per `parsers.parseModels()` * @returns */ export const generateSchemas = (models: NameKeyMap<SwaggerSailsModel>): NameKeyMap<OpenApi.UpdatedSchema | Reference> => { return Object.keys(models) .reduce((schemas, identity) => { const model = models[identity] if(model.swagger?.modelSchema?.exclude === true) { return schemas; } const schemaWithoutRequired: OpenApi.UpdatedSchema = { type: 'object', description: model.swagger.modelSchema?.description || `Sails ORM Model **${model.globalId}**`, properties: {}, ...omit(model.swagger?.modelSchema || {}, 'exclude', 'description', 'required', 'tags'), } let required: string[] = []; const attributes = model.attributes || {} defaults( schemaWithoutRequired.properties, Object.keys(attributes).reduce((props, attributeName) => { const attribute = model.attributes[attributeName]; if (attribute.meta?.swagger?.exclude !== true) { props[attributeName] = generateAttributeSchema(attribute); if (attribute.required) required!.push(attributeName); } return props }, {} as NameKeyMap<OpenApi.UpdatedSchema>) ); const withoutRequiredName = `${model.identity}-without-required-constraint`; const schema: OpenApi.UpdatedSchema = { type: 'object', allOf: [ { '$ref': `#/components/schemas/${withoutRequiredName}` }, ], }; if(model.swagger?.modelSchema?.required) { required = [ ...model.swagger.modelSchema.required ]; } if(required.length > 0) { schema.allOf!.push({ required: required }); } schemas[model.identity] = schema; schemas[withoutRequiredName] = schemaWithoutRequired; return schemas }, {} as NameKeyMap<OpenApi.UpdatedSchema | Reference>) } /** * Generate Swagger schema content describing specified Sails routes/actions. * * @see https://swagger.io/docs/specification/paths-and-operations/ * * TODO: break down this function into smaller methods and add tests separately * * @param routes * @param templates * @param defaultsValues * @param models */ export const generatePaths = (routes: SwaggerRouteInfo[], templates: BlueprintActionTemplates, defaultsValues: Defaults, specification: OpenApi.OpenApi, models: NameKeyMap<SwaggerSailsModel>, sails: Sails.Sails): OpenApi.Paths => { const paths = {}; const tags = specification.tags!; const components = specification.components!; if (!components.parameters) { components.parameters = {} } forEach(routes, route => { if(route.swagger?.exclude === true) { return; } /* overwrite: summary, description, externalDocs, operationId, tags, requestBody, servers, security * merge: parameters (by in+name), responses (by statusCode) */ const pathEntry: OpenApi.Operation = { summary: undefined, description: undefined, externalDocs: undefined, operationId: undefined, tags: undefined, parameters: [], responses: {}, ...cloneDeep(omit(route.swagger || {}, 'exclude')), }; const resolveParameterRef = (p: OpenApi.Parameter | Reference): OpenApi.Parameter | Reference => { const specWithDefaultParametersToBeMerged = { components: { parameters: blueprintParameterTemplates } } as OpenApi.OpenApi; // resolve first with current spec, then try template params to be added later return (resolveRef(specification, p) || resolveRef(specWithDefaultParametersToBeMerged, p)) as OpenApi.Parameter | Reference; }; const isParam = (inType: string, name: string): boolean => { return !!pathEntry.parameters .map(parameter => resolveParameterRef(parameter)) .find(parameter => parameter && 'in' in parameter && parameter.in == inType && parameter.name == name); }; const addParamIfDne = (p: OpenApi.Parameter | Reference) => { const resolved = resolveParameterRef(p); if (resolved && 'in' in resolved) { if (!isParam(resolved.in, resolved.name)) { pathEntry.parameters.push(p); } } }; if (route.actionType === 'actions2') { // note: check before blueprint template as these may override template for specific action(s) const patternVariables = route.variables || []; if (route.actions2Machine?.inputs) { forEach(route.actions2Machine.inputs, (value, key) => { if(value.meta?.swagger?.exclude === true) { return; } let _in = value.meta?.swagger?.in; if(!_in) { _in = patternVariables.indexOf(key) >= 0 ? 'path' : 'query'; } // compose attribute definition const { description, ..._attribute } = value; const attribute = { ...omit(_attribute, attributeValidations), validations: pick(_attribute, attributeValidations), } as Sails.AttributeDefinition; if(!attribute.type && 'example' in attribute) { // derive type if not specified (optional for actions2) defaults(attribute, deriveSwaggerTypeFromExample(attribute.example || attribute.defaultsTo)); } if(_in === 'body') { if(!['put', 'post', 'patch'].includes(route.verb)) { sails.log.warn(`WARNING: sails-hook-swagger-generator: Route '${route.verb} ${route.path}' cannot contain 'requestBody'; ignoring input '${key} for generated Swagger`); return; } // add to request body if we can do so cleanly if(!pathEntry.requestBody) { pathEntry.requestBody = { content: {} }; } if (!('content' in pathEntry.requestBody)) { return; // could be reference --> in which case do not override } const rbc = pathEntry.requestBody.content; if (!rbc['application/json']) { rbc['application/json'] = {}; } if (!rbc['application/json'].schema) { rbc['application/json'].schema = { type:'object', properties:{} }; } if ('type' in rbc['application/json'].schema && rbc['application/json'].schema.type === 'object' && rbc['application/json'].schema.properties) { // if not reference and of type 'object' --> consider adding new property (but don't overwrite) defaults( rbc['application/json'].schema.properties, { [key]: generateAttributeSchema(attribute) } ); } } else { // otherwise, handle path|query|cookie|header parameters if (isParam(_in, key)) { return; } pathEntry.parameters.push({ in: _in, name: key, required: value.required || false, schema: generateAttributeSchema(attribute), description }); } }); } if (route.actions2Machine?.exits) { const exitResponses: NameKeyMap<OpenApi.Response> = {}; // status to determine whether 'content' can be removed in simple cases const defaultOnly: NameKeyMap<boolean> = {}; // actions2 may specify more than one 'exit' per 'statusCode' --> use oneOf (and attempt to merge) forEach(route.actions2Machine.exits, (exit, exitName) => { if(exit.meta?.swagger?.exclude === true) { return; } let { statusCode, description } = actions2Responses[exitName as keyof Action2Response] || actions2Responses.success; const defaultDescription = description; statusCode = exit.statusCode || statusCode; description = exit.description || description; const schema: OpenApi.UpdatedSchema = { example: exit.outputExample, ...deriveSwaggerTypeFromExample(exit.outputExample || ''), description: description, }; // XXX TODO review support for responseType, viewTemplatePath const addToContentJsonSchemaOneOfIfDne = (): void => { const r = exitResponses[statusCode]; // add to response if can do so cleanly if (!r.content) r.content = {}; if (!r.content['application/json']) r.content['application/json'] = {}; if (!r.content['application/json'].schema) r.content['application/json'].schema = { oneOf: [] }; // if schema with 'oneOf' exists, add new schema content const existingSchema = r.content?.['application/json']?.schema; if (existingSchema && 'oneOf' in existingSchema) { existingSchema.oneOf?.push(schema); } else { // skip --> custom schema overrides auto-generated } } if (exitResponses[statusCode]) { // this statusCode already exists --> add as alternative if 'oneOf' present (or can be cleanly added) addToContentJsonSchemaOneOfIfDne(); defaultOnly[statusCode] = false; } else if(pathEntry.responses[statusCode]) { // if not exists, check for response defined in source swagger and merge/massage to suit 'application/json' oneOf exitResponses[statusCode] = cloneDeep(pathEntry.responses[statusCode]); addToContentJsonSchemaOneOfIfDne(); defaultOnly[statusCode] = false; } else { // dne, so add exitResponses[statusCode] = { description: defaultDescription, content: { 'application/json': { schema: { oneOf: [schema] } }, } }; defaultOnly[statusCode] = exit.outputExample === undefined; } }); // remove oneOf for single entries and move description back to top-level forEach(exitResponses, (resp, statusCode) => { if ((resp.content?.['application/json'].schema as OpenApi.UpdatedSchema)?.oneOf) { const arr = (resp.content!['application/json'].schema as OpenApi.UpdatedSchema)!.oneOf; if (arr!.length === 1) { resp.content!['application/json'].schema = arr![0]; if ('description' in arr![0]) resp.description = arr![0].description as string; if (defaultOnly[statusCode]) delete resp.content; } } }); pathEntry.responses = { ...pathEntry.responses, ...exitResponses, } forEach(pathEntry.responses, (resp, statusCode) => { // ensure description if (!resp.description) resp.description = exitResponses[statusCode]?.description || '-'; }); } // merge actions2 summary and description defaults( pathEntry, { summary: route.actions2Machine?.friendlyName || undefined, description: route.actions2Machine?.description || undefined, } ); } // of if(actions2) // handle blueprint actions and related documentation (from model and blueprint template) if (route.model && route.blueprintAction) { if (route.model.swagger?.modelSchema?.exclude === true || route.model.swagger.actions?.[route.blueprintAction]?.exclude === true) { return; } const template = templates[route.blueprintAction as keyof BlueprintActionTemplates] || {}; const subst = (str: string) => str ? str.replace('{globalId}', route.model!.globalId) : undefined; /* overwrite: summary, description, externalDocs, operationId, tags, requestBody, servers, security * merge: parameters (by in+name), responses (by statusCode) */ defaults( pathEntry, { summary: subst(template.summary), description: subst(template.description), externalDocs: template.externalDocs || undefined, tags: route.model.swagger.modelSchema?.tags || route.model.swagger.actions?.allactions?.tags || [route.model.globalId], ...cloneDeep(omit({ ...route.model.swagger.actions?.allactions || {}, ...route.model.swagger.actions?.[route.blueprintAction] || {}, }, 'exclude')), } ); // merge parameters from model actions and template (in that order) (route.model.swagger.actions?.[route.blueprintAction]?.parameters || []).map(p => addParamIfDne(p)); (route.model.swagger.actions?.allactions?.parameters || []).map(p => addParamIfDne(p)); (template.parameters || []).map(parameter => { // handle special case of PK parameter if (parameter === 'primaryKeyPathParameter') { const primaryKey = route.model!.primaryKey; const attributeInfo = route.model!.attributes[primaryKey]; const pname = 'ModelPKParam-' + route.model!.identity; if (components.parameters && !components.parameters[pname]) { components.parameters[pname] = { in: 'path', name: '_' + primaryKey, // note '_' as per transformSailsPathsToSwaggerPaths() required: true, schema: generateAttributeSchema(attributeInfo), description: subst('The desired **{globalId}** record\'s primary key value'), }; } parameter = { $ref: '#/components/parameters/' + pname }; } addParamIfDne(parameter); }); // merge responses from model actions defaults( pathEntry.responses, (route.model.swagger.actions?.[route.blueprintAction]?.responses || {}), (route.model.swagger.actions?.allactions?.responses || {}), ); const modifiers = { addPopulateQueryParam: () => { const assoc = route.model?.associations || []; if (isParam('query', 'populate') || assoc.length == 0) return; pathEntry.parameters.push({ in: 'query', name: 'populate', required: false, schema: { type: 'string', example: ['false', ...(assoc.map(row => row.alias) || [])].join(','), }, description: 'If specified, overide the default automatic population process.' + ' Accepts a comma-separated list of attribute names for which to populate record values,' + ' or specify `false` to have no attributes populated.', }); }, addSelectQueryParam: () => { if (isParam('query', 'select')) return; const attributes = route.model!.attributes || {}; const csv = reduce(attributes, (acc, a, n) => ((a.meta?.swagger?.exclude === true) ? acc : [...acc, n]), [] as string[]); pathEntry.parameters.push({ in: 'query', name: 'select', required: false, schema: { type: 'string', example: csv.join(','), }, description: 'The attributes to include in the result, specified as a comma-delimited list.' + ' By default, all attributes are selected.' + ' Not valid for plural (“collection”) association attributes.', }); }, addOmitQueryParam: () => { if (isParam('query', 'omit')) return; const attributes = route.model!.attributes || {}; const csv = reduce(attributes, (acc, a, n) => ((a.meta?.swagger?.exclude === true) ? acc : [...acc, n]), [] as string[]); pathEntry.parameters.push({ in: 'query', name: 'omit', required: false, schema: { type: 'string', example: csv.join(','), }, description: 'The attributes to exclude from the result, specified as a comma-delimited list.' + ' Cannot be used in conjuction with `select`.' + ' Not valid for plural (“collection”) association attributes.', }); }, addModelBodyParam: () => { if(route.isShortcutBlueprintRoute) { const schema = specification!.components!.schemas?.[route.model!.identity]; if (schema) { const resolvedSchema = unrollSchema(specification, schema); if (resolvedSchema) { generateSchemaAsQueryParameters(resolvedSchema as OpenApi.UpdatedSchema).map(p => { if (isParam('query', p.name)) return; pathEntry.parameters.push(p); }); } } } else { if (pathEntry.requestBody) return; pathEntry.requestBody = { description: subst('JSON dictionary representing the {globalId} instance to create.'), // XXX TODO Incorporate model description? required: true, content: { 'application/json': { schema: { '$ref': `#/components/schemas/${route.model!.identity}` } }, }, }; } }, addModelBodyParamUpdate: () => { if (route.isShortcutBlueprintRoute) { const schema = specification!.components!.schemas?.[route.model!.identity+'-without-required-constraint']; if (schema) { const resolvedSchema = resolveRef(specification, schema); if (resolvedSchema) { generateSchemaAsQueryParameters(resolvedSchema as OpenApi.UpdatedSchema).map(p => { if (isParam('query', p.name)) return; pathEntry.parameters.push(p); }); } } } else { if (pathEntry.requestBody) return; pathEntry.requestBody = { description: subst('JSON dictionary representing the {globalId} instance to update.'), // XXX TODO Incorporate model description? required: true, content: { 'application/json': { schema: { '$ref': `#/components/schemas/${route.model!.identity}-without-required-constraint` } }, }, } } }, addResultOfArrayOfModels: () => { defaults(pathEntry.responses, { '200': { description: subst(template.resultDescription || 'Array of **{globalId}** records'), content: { 'application/json': { schema: { type: 'array', items: { '$ref': '#/components/schemas/' + route.model!.identity }, }, }, }, } }); }, addAssociationPathParam: () => { if (isParam('path', 'association')) return; pathEntry.parameters.splice(1, 0, { in: 'path', name: 'association', required: true, schema: { type: 'string', enum: route.associationAliases, }, description: 'The name of the association', }); }, addAssociationFKPathParam: () => { if (isParam('path', 'childid')) return; // pre-defined/pre-configured --> skip pathEntry.parameters.push({ in: 'path', name: 'childid', required: true, schema: { oneOf: generateModelAssociationFKAttributeSchemas(route.model!, route.associationAliases, models), } as OpenApi.UpdatedSchema, description: 'The desired target association record\'s foreign key value' }); }, addAssociationResultOfArray: () => { const associations = route.model?.associations || []; const models = (route.associationAliases || []).map(a => { const assoc = associations.find(_assoc => _assoc.alias == a); return assoc ? (assoc.collection || assoc.model) : a; }); defaults(pathEntry.responses, { '200': { description: subst(template.resultDescription), content: { 'application/json': { schema: { type: 'array', // items: { type: 'any' }, items: { oneOf: uniq(models).map(model => { return { '$ref': '#/components/schemas/' + model }; }), }, }, }, }, } }); }, addResultOfModel: () => { defaults(pathEntry.responses, { '200': { description: subst(template.resultDescription || '**{globalId}** record'), content: { 'application/json': { schema: { '$ref': '#/components/schemas/' + route.model!.identity }, }, }, } }); }, addResultNotFound: () => { defaults(pathEntry.responses, { '404': { description: subst(template.notFoundDescription || 'Not found'), } }); }, addResultValidationError: () => { defaults(pathEntry.responses, { '400': { description: subst('Validation errors; details in JSON response'), } }); }, addFksBodyParam: () => { if(route.isShortcutBlueprintRoute) { generateModelAssociationFKAttributeParameters(route.model!, route.associationAliases, models).map(p => { if(!route.associationAliases || route.associationAliases.indexOf(p.name) < 0) return; if (isParam('query', p.name)) return; pathEntry.parameters.push(p); }); } else { if (pathEntry.requestBody) return; pathEntry.requestBody = { description: 'The primary key values (usually IDs) of the child records to use as the new members of this collection', required: true, content: { 'application/json': { schema: { type: 'array', items: { oneOf: generateModelAssociationFKAttributeSchemas(route.model!, route.associationAliases, models), } } as OpenApi.UpdatedSchema, }, }, }; } }, addShortCutBlueprintRouteNote: () => { if(!route.isShortcutBlueprintRoute) { return; } pathEntry.summary += ' *'; if(route.blueprintAction === 'replace') { pathEntry.description += `\n\nOnly one of the query parameters, that matches the **association** path parameter, should be specified.`; } pathEntry.description += `\n\n(\\*) Note that this is a` + ` [Sails blueprint shortcut route](https://sailsjs.com/documentation/concepts/blueprints/blueprint-routes#?shortcut-blueprint-routes)` + ` (recommended for **development-mode only**)`; }, }; // apply changes for blueprint action (template.modifiers || []).map(modifier => { if (isFunction(modifier)) modifier(template, route, pathEntry, tags, components); // custom modifier else modifiers[modifier](); // standard modifier }); } // of if (route.model && route.blueprintAction) // final populate noting others above defaults( pathEntry, { summary: route.path || '', tags: [route.actions2Machine?.friendlyName || route.defaultTagName], } ); defaults( pathEntry.responses, defaultsValues.responses, { '500': { description: 'Internal server error' } }, ); // catch the case where defaultTagName not defined if (isEqual(pathEntry.tags, [undefined])) pathEntry.tags = []; if (route.variables) { // now add patternVariables that don't already exist route.variables.map(v => { const existing = isParam('path', v); if (existing) return; pathEntry.parameters.push({ in: 'path', name: v, required: true, schema: { type: 'string' }, description: `Route pattern variable \`${v}\``, }); }); } if(pathEntry.tags) { pathEntry.tags.sort(); } set(paths, [route.path, route.verb], pathEntry); }); return paths } export const generateDefaultModelTags = (models: NameKeyMap<SwaggerSailsModel>): Tag[] => { return map(models, model => { const defaultDescription = `Sails blueprint actions for the **${model.globalId}** model`; const tagDef: Tag = { name: model.globalId, description: model.swagger.modelSchema?.description || defaultDescription, }; if(model.swagger.modelSchema?.externalDocs) { tagDef.externalDocs = { ...model.swagger.modelSchema.externalDocs }; } return tagDef; }); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages an App Service (within an App Service Plan). * * > **Note:** When using Slots - the `appSettings`, `connectionString` and `siteConfig` blocks on the `azure.appservice.AppService` resource will be overwritten when promoting a Slot using the `azure.appservice.ActiveSlot` resource. * * ## Example Usage * * This example provisions a Windows App Service. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const examplePlan = new azure.appservice.Plan("examplePlan", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * sku: { * tier: "Standard", * size: "S1", * }, * }); * const exampleAppService = new azure.appservice.AppService("exampleAppService", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * appServicePlanId: examplePlan.id, * siteConfig: { * dotnetFrameworkVersion: "v4.0", * scmType: "LocalGit", * }, * appSettings: { * SOME_KEY: "some-value", * }, * connectionStrings: [{ * name: "Database", * type: "SQLServer", * value: "Server=some-server.mydomain.com;Integrated Security=SSPI", * }], * }); * ``` * * ## Import * * App Services can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:appservice/appService:AppService instance1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Web/sites/instance1 * ``` */ export class AppService extends pulumi.CustomResource { /** * Get an existing AppService 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?: AppServiceState, opts?: pulumi.CustomResourceOptions): AppService { return new AppService(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:appservice/appService:AppService'; /** * Returns true if the given object is an instance of AppService. 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 AppService { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AppService.__pulumiType; } /** * The ID of the App Service Plan within which to create this App Service. */ public readonly appServicePlanId!: pulumi.Output<string>; /** * A key-value pair of App Settings. */ public readonly appSettings!: pulumi.Output<{[key: string]: string}>; /** * A `authSettings` block as defined below. */ public readonly authSettings!: pulumi.Output<outputs.appservice.AppServiceAuthSettings>; /** * A `backup` block as defined below. */ public readonly backup!: pulumi.Output<outputs.appservice.AppServiceBackup | undefined>; /** * Should the App Service send session affinity cookies, which route client requests in the same session to the same instance? */ public readonly clientAffinityEnabled!: pulumi.Output<boolean | undefined>; /** * Does the App Service require client certificates for incoming requests? Defaults to `false`. */ public readonly clientCertEnabled!: pulumi.Output<boolean | undefined>; /** * Mode of client certificates for this App Service. Possible values are `Required`, `Optional` and `OptionalInteractiveUser`. If this parameter is set, `clientCertEnabled` must be set to `true`, otherwise this parameter is ignored. */ public readonly clientCertMode!: pulumi.Output<string>; /** * One or more `connectionString` blocks as defined below. */ public readonly connectionStrings!: pulumi.Output<outputs.appservice.AppServiceConnectionString[]>; /** * An identifier used by App Service to perform domain ownership verification via DNS TXT record. */ public /*out*/ readonly customDomainVerificationId!: pulumi.Output<string>; /** * The Default Hostname associated with the App Service - such as `mysite.azurewebsites.net` */ public /*out*/ readonly defaultSiteHostname!: pulumi.Output<string>; /** * Is the App Service Enabled? */ public readonly enabled!: pulumi.Output<boolean | undefined>; /** * Can the App Service only be accessed via HTTPS? Defaults to `false`. */ public readonly httpsOnly!: pulumi.Output<boolean | undefined>; /** * An `identity` block as defined below. */ public readonly identity!: pulumi.Output<outputs.appservice.AppServiceIdentity>; /** * The User Assigned Identity Id used for looking up KeyVault secrets. The identity must be assigned to the application. [For more information see - Access vaults with a user-assigned identity](https://docs.microsoft.com/en-us/azure/app-service/app-service-key-vault-references#access-vaults-with-a-user-assigned-identity) */ public readonly keyVaultReferenceIdentityId!: pulumi.Output<string>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ public readonly location!: pulumi.Output<string>; /** * A `logs` block as defined below. */ public readonly logs!: pulumi.Output<outputs.appservice.AppServiceLogs>; /** * Specifies the name of the App Service. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * A list of outbound IP addresses - such as `["52.23.25.3", "52.143.43.12"]` */ public /*out*/ readonly outboundIpAddressLists!: pulumi.Output<string[]>; /** * A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12` */ public /*out*/ readonly outboundIpAddresses!: pulumi.Output<string>; /** * A list of outbound IP addresses - such as `["52.23.25.3", "52.143.43.12", "52.143.43.17"]` - not all of which are necessarily in use. Superset of `outboundIpAddressList`. */ public /*out*/ readonly possibleOutboundIpAddressLists!: pulumi.Output<string[]>; /** * A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12,52.143.43.17` - not all of which are necessarily in use. Superset of `outboundIpAddresses`. */ public /*out*/ readonly possibleOutboundIpAddresses!: pulumi.Output<string>; /** * The name of the resource group in which to create the App Service. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * A `siteConfig` block as defined below. */ public readonly siteConfig!: pulumi.Output<outputs.appservice.AppServiceSiteConfig>; /** * A `siteCredential` block as defined below, which contains the site-level credentials used to publish to this App Service. */ public /*out*/ readonly siteCredentials!: pulumi.Output<outputs.appservice.AppServiceSiteCredential[]>; /** * A Source Control block as defined below */ public readonly sourceControl!: pulumi.Output<outputs.appservice.AppServiceSourceControl>; /** * One or more `storageAccount` blocks as defined below. */ public readonly storageAccounts!: pulumi.Output<outputs.appservice.AppServiceStorageAccount[]>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Create a AppService 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: AppServiceArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AppServiceArgs | AppServiceState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AppServiceState | undefined; inputs["appServicePlanId"] = state ? state.appServicePlanId : undefined; inputs["appSettings"] = state ? state.appSettings : undefined; inputs["authSettings"] = state ? state.authSettings : undefined; inputs["backup"] = state ? state.backup : undefined; inputs["clientAffinityEnabled"] = state ? state.clientAffinityEnabled : undefined; inputs["clientCertEnabled"] = state ? state.clientCertEnabled : undefined; inputs["clientCertMode"] = state ? state.clientCertMode : undefined; inputs["connectionStrings"] = state ? state.connectionStrings : undefined; inputs["customDomainVerificationId"] = state ? state.customDomainVerificationId : undefined; inputs["defaultSiteHostname"] = state ? state.defaultSiteHostname : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["httpsOnly"] = state ? state.httpsOnly : undefined; inputs["identity"] = state ? state.identity : undefined; inputs["keyVaultReferenceIdentityId"] = state ? state.keyVaultReferenceIdentityId : undefined; inputs["location"] = state ? state.location : undefined; inputs["logs"] = state ? state.logs : undefined; inputs["name"] = state ? state.name : undefined; inputs["outboundIpAddressLists"] = state ? state.outboundIpAddressLists : undefined; inputs["outboundIpAddresses"] = state ? state.outboundIpAddresses : undefined; inputs["possibleOutboundIpAddressLists"] = state ? state.possibleOutboundIpAddressLists : undefined; inputs["possibleOutboundIpAddresses"] = state ? state.possibleOutboundIpAddresses : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["siteConfig"] = state ? state.siteConfig : undefined; inputs["siteCredentials"] = state ? state.siteCredentials : undefined; inputs["sourceControl"] = state ? state.sourceControl : undefined; inputs["storageAccounts"] = state ? state.storageAccounts : undefined; inputs["tags"] = state ? state.tags : undefined; } else { const args = argsOrState as AppServiceArgs | undefined; if ((!args || args.appServicePlanId === undefined) && !opts.urn) { throw new Error("Missing required property 'appServicePlanId'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["appServicePlanId"] = args ? args.appServicePlanId : undefined; inputs["appSettings"] = args ? args.appSettings : undefined; inputs["authSettings"] = args ? args.authSettings : undefined; inputs["backup"] = args ? args.backup : undefined; inputs["clientAffinityEnabled"] = args ? args.clientAffinityEnabled : undefined; inputs["clientCertEnabled"] = args ? args.clientCertEnabled : undefined; inputs["clientCertMode"] = args ? args.clientCertMode : undefined; inputs["connectionStrings"] = args ? args.connectionStrings : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["httpsOnly"] = args ? args.httpsOnly : undefined; inputs["identity"] = args ? args.identity : undefined; inputs["keyVaultReferenceIdentityId"] = args ? args.keyVaultReferenceIdentityId : undefined; inputs["location"] = args ? args.location : undefined; inputs["logs"] = args ? args.logs : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["siteConfig"] = args ? args.siteConfig : undefined; inputs["sourceControl"] = args ? args.sourceControl : undefined; inputs["storageAccounts"] = args ? args.storageAccounts : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["customDomainVerificationId"] = undefined /*out*/; inputs["defaultSiteHostname"] = undefined /*out*/; inputs["outboundIpAddressLists"] = undefined /*out*/; inputs["outboundIpAddresses"] = undefined /*out*/; inputs["possibleOutboundIpAddressLists"] = undefined /*out*/; inputs["possibleOutboundIpAddresses"] = undefined /*out*/; inputs["siteCredentials"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AppService.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AppService resources. */ export interface AppServiceState { /** * The ID of the App Service Plan within which to create this App Service. */ appServicePlanId?: pulumi.Input<string>; /** * A key-value pair of App Settings. */ appSettings?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `authSettings` block as defined below. */ authSettings?: pulumi.Input<inputs.appservice.AppServiceAuthSettings>; /** * A `backup` block as defined below. */ backup?: pulumi.Input<inputs.appservice.AppServiceBackup>; /** * Should the App Service send session affinity cookies, which route client requests in the same session to the same instance? */ clientAffinityEnabled?: pulumi.Input<boolean>; /** * Does the App Service require client certificates for incoming requests? Defaults to `false`. */ clientCertEnabled?: pulumi.Input<boolean>; /** * Mode of client certificates for this App Service. Possible values are `Required`, `Optional` and `OptionalInteractiveUser`. If this parameter is set, `clientCertEnabled` must be set to `true`, otherwise this parameter is ignored. */ clientCertMode?: pulumi.Input<string>; /** * One or more `connectionString` blocks as defined below. */ connectionStrings?: pulumi.Input<pulumi.Input<inputs.appservice.AppServiceConnectionString>[]>; /** * An identifier used by App Service to perform domain ownership verification via DNS TXT record. */ customDomainVerificationId?: pulumi.Input<string>; /** * The Default Hostname associated with the App Service - such as `mysite.azurewebsites.net` */ defaultSiteHostname?: pulumi.Input<string>; /** * Is the App Service Enabled? */ enabled?: pulumi.Input<boolean>; /** * Can the App Service only be accessed via HTTPS? Defaults to `false`. */ httpsOnly?: pulumi.Input<boolean>; /** * An `identity` block as defined below. */ identity?: pulumi.Input<inputs.appservice.AppServiceIdentity>; /** * The User Assigned Identity Id used for looking up KeyVault secrets. The identity must be assigned to the application. [For more information see - Access vaults with a user-assigned identity](https://docs.microsoft.com/en-us/azure/app-service/app-service-key-vault-references#access-vaults-with-a-user-assigned-identity) */ keyVaultReferenceIdentityId?: pulumi.Input<string>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * A `logs` block as defined below. */ logs?: pulumi.Input<inputs.appservice.AppServiceLogs>; /** * Specifies the name of the App Service. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A list of outbound IP addresses - such as `["52.23.25.3", "52.143.43.12"]` */ outboundIpAddressLists?: pulumi.Input<pulumi.Input<string>[]>; /** * A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12` */ outboundIpAddresses?: pulumi.Input<string>; /** * A list of outbound IP addresses - such as `["52.23.25.3", "52.143.43.12", "52.143.43.17"]` - not all of which are necessarily in use. Superset of `outboundIpAddressList`. */ possibleOutboundIpAddressLists?: pulumi.Input<pulumi.Input<string>[]>; /** * A comma separated list of outbound IP addresses - such as `52.23.25.3,52.143.43.12,52.143.43.17` - not all of which are necessarily in use. Superset of `outboundIpAddresses`. */ possibleOutboundIpAddresses?: pulumi.Input<string>; /** * The name of the resource group in which to create the App Service. */ resourceGroupName?: pulumi.Input<string>; /** * A `siteConfig` block as defined below. */ siteConfig?: pulumi.Input<inputs.appservice.AppServiceSiteConfig>; /** * A `siteCredential` block as defined below, which contains the site-level credentials used to publish to this App Service. */ siteCredentials?: pulumi.Input<pulumi.Input<inputs.appservice.AppServiceSiteCredential>[]>; /** * A Source Control block as defined below */ sourceControl?: pulumi.Input<inputs.appservice.AppServiceSourceControl>; /** * One or more `storageAccount` blocks as defined below. */ storageAccounts?: pulumi.Input<pulumi.Input<inputs.appservice.AppServiceStorageAccount>[]>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a AppService resource. */ export interface AppServiceArgs { /** * The ID of the App Service Plan within which to create this App Service. */ appServicePlanId: pulumi.Input<string>; /** * A key-value pair of App Settings. */ appSettings?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `authSettings` block as defined below. */ authSettings?: pulumi.Input<inputs.appservice.AppServiceAuthSettings>; /** * A `backup` block as defined below. */ backup?: pulumi.Input<inputs.appservice.AppServiceBackup>; /** * Should the App Service send session affinity cookies, which route client requests in the same session to the same instance? */ clientAffinityEnabled?: pulumi.Input<boolean>; /** * Does the App Service require client certificates for incoming requests? Defaults to `false`. */ clientCertEnabled?: pulumi.Input<boolean>; /** * Mode of client certificates for this App Service. Possible values are `Required`, `Optional` and `OptionalInteractiveUser`. If this parameter is set, `clientCertEnabled` must be set to `true`, otherwise this parameter is ignored. */ clientCertMode?: pulumi.Input<string>; /** * One or more `connectionString` blocks as defined below. */ connectionStrings?: pulumi.Input<pulumi.Input<inputs.appservice.AppServiceConnectionString>[]>; /** * Is the App Service Enabled? */ enabled?: pulumi.Input<boolean>; /** * Can the App Service only be accessed via HTTPS? Defaults to `false`. */ httpsOnly?: pulumi.Input<boolean>; /** * An `identity` block as defined below. */ identity?: pulumi.Input<inputs.appservice.AppServiceIdentity>; /** * The User Assigned Identity Id used for looking up KeyVault secrets. The identity must be assigned to the application. [For more information see - Access vaults with a user-assigned identity](https://docs.microsoft.com/en-us/azure/app-service/app-service-key-vault-references#access-vaults-with-a-user-assigned-identity) */ keyVaultReferenceIdentityId?: pulumi.Input<string>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * A `logs` block as defined below. */ logs?: pulumi.Input<inputs.appservice.AppServiceLogs>; /** * Specifies the name of the App Service. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The name of the resource group in which to create the App Service. */ resourceGroupName: pulumi.Input<string>; /** * A `siteConfig` block as defined below. */ siteConfig?: pulumi.Input<inputs.appservice.AppServiceSiteConfig>; /** * A Source Control block as defined below */ sourceControl?: pulumi.Input<inputs.appservice.AppServiceSourceControl>; /** * One or more `storageAccount` blocks as defined below. */ storageAccounts?: pulumi.Input<pulumi.Input<inputs.appservice.AppServiceStorageAccount>[]>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import { DeepImmutable } from "../types"; import { ArrayTools } from "../Misc/arrayTools"; import { Matrix, Vector3 } from "../Maths/math.vector"; import { BoundingSphere } from "../Culling/boundingSphere"; import { ICullable } from "./boundingInfo"; import { Epsilon } from '../Maths/math.constants'; import { Plane } from '../Maths/math.plane'; /** * Class used to store bounding box information */ export class BoundingBox implements ICullable { /** * Gets the 8 vectors representing the bounding box in local space */ public readonly vectors: Vector3[] = ArrayTools.BuildArray(8, Vector3.Zero); /** * Gets the center of the bounding box in local space */ public readonly center: Vector3 = Vector3.Zero(); /** * Gets the center of the bounding box in world space */ public readonly centerWorld: Vector3 = Vector3.Zero(); /** * Gets the extend size in local space */ public readonly extendSize: Vector3 = Vector3.Zero(); /** * Gets the extend size in world space */ public readonly extendSizeWorld: Vector3 = Vector3.Zero(); /** * Gets the OBB (object bounding box) directions */ public readonly directions: Vector3[] = ArrayTools.BuildArray(3, Vector3.Zero); /** * Gets the 8 vectors representing the bounding box in world space */ public readonly vectorsWorld: Vector3[] = ArrayTools.BuildArray(8, Vector3.Zero); /** * Gets the minimum vector in world space */ public readonly minimumWorld: Vector3 = Vector3.Zero(); /** * Gets the maximum vector in world space */ public readonly maximumWorld: Vector3 = Vector3.Zero(); /** * Gets the minimum vector in local space */ public readonly minimum: Vector3 = Vector3.Zero(); /** * Gets the maximum vector in local space */ public readonly maximum: Vector3 = Vector3.Zero(); private _worldMatrix: DeepImmutable<Matrix>; private static readonly TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero); /** * @hidden */ public _tag: number; /** * Creates a new bounding box * @param min defines the minimum vector (in local space) * @param max defines the maximum vector (in local space) * @param worldMatrix defines the new world matrix */ constructor(min: DeepImmutable<Vector3>, max: DeepImmutable<Vector3>, worldMatrix?: DeepImmutable<Matrix>) { this.reConstruct(min, max, worldMatrix); } // Methods /** * Recreates the entire bounding box from scratch as if we call the constructor in place * @param min defines the new minimum vector (in local space) * @param max defines the new maximum vector (in local space) * @param worldMatrix defines the new world matrix */ public reConstruct(min: DeepImmutable<Vector3>, max: DeepImmutable<Vector3>, worldMatrix?: DeepImmutable<Matrix>) { const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; const vectors = this.vectors; this.minimum.copyFromFloats(minX, minY, minZ); this.maximum.copyFromFloats(maxX, maxY, maxZ); vectors[0].copyFromFloats(minX, minY, minZ); vectors[1].copyFromFloats(maxX, maxY, maxZ); vectors[2].copyFromFloats(maxX, minY, minZ); vectors[3].copyFromFloats(minX, maxY, minZ); vectors[4].copyFromFloats(minX, minY, maxZ); vectors[5].copyFromFloats(maxX, maxY, minZ); vectors[6].copyFromFloats(minX, maxY, maxZ); vectors[7].copyFromFloats(maxX, minY, maxZ); // OBB max.addToRef(min, this.center).scaleInPlace(0.5); max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly; this._update(this._worldMatrix); } /** * Scale the current bounding box by applying a scale factor * @param factor defines the scale factor to apply * @returns the current bounding box */ public scale(factor: number): BoundingBox { const tmpVectors = BoundingBox.TmpVector3; const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); const len = diff.length(); diff.normalizeFromLength(len); const distance = len * factor; const newRadius = diff.scaleInPlace(distance * 0.5); const min = this.center.subtractToRef(newRadius, tmpVectors[1]); const max = this.center.addToRef(newRadius, tmpVectors[2]); this.reConstruct(min, max, this._worldMatrix); return this; } /** * Gets the world matrix of the bounding box * @returns a matrix */ public getWorldMatrix(): DeepImmutable<Matrix> { return this._worldMatrix; } /** @hidden */ public _update(world: DeepImmutable<Matrix>): void { const minWorld = this.minimumWorld; const maxWorld = this.maximumWorld; const directions = this.directions; const vectorsWorld = this.vectorsWorld; const vectors = this.vectors; if (!world.isIdentity()) { minWorld.setAll(Number.MAX_VALUE); maxWorld.setAll(-Number.MAX_VALUE); for (let index = 0; index < 8; ++index) { const v = vectorsWorld[index]; Vector3.TransformCoordinatesToRef(vectors[index], world, v); minWorld.minimizeInPlace(v); maxWorld.maximizeInPlace(v); } // Extend maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5); maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5); } else { minWorld.copyFrom(this.minimum); maxWorld.copyFrom(this.maximum); for (let index = 0; index < 8; ++index) { vectorsWorld[index].copyFrom(vectors[index]); } // Extend this.extendSizeWorld.copyFrom(this.extendSize); this.centerWorld.copyFrom(this.center); } Vector3.FromArrayToRef(world.m, 0, directions[0]); Vector3.FromArrayToRef(world.m, 4, directions[1]); Vector3.FromArrayToRef(world.m, 8, directions[2]); this._worldMatrix = world; } /** * Tests if the bounding box is intersecting the frustum planes * @param frustumPlanes defines the frustum planes to test * @returns true if there is an intersection */ public isInFrustum(frustumPlanes: Array<DeepImmutable<Plane>>): boolean { return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes); } /** * Tests if the bounding box is entirely inside the frustum planes * @param frustumPlanes defines the frustum planes to test * @returns true if there is an inclusion */ public isCompletelyInFrustum(frustumPlanes: Array<DeepImmutable<Plane>>): boolean { return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes); } /** * Tests if a point is inside the bounding box * @param point defines the point to test * @returns true if the point is inside the bounding box */ public intersectsPoint(point: DeepImmutable<Vector3>): boolean { const min = this.minimumWorld; const max = this.maximumWorld; const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; const pointX = point.x, pointY = point.y, pointZ = point.z; var delta = -Epsilon; if (maxX - pointX < delta || delta > pointX - minX) { return false; } if (maxY - pointY < delta || delta > pointY - minY) { return false; } if (maxZ - pointZ < delta || delta > pointZ - minZ) { return false; } return true; } /** * Tests if the bounding box intersects with a bounding sphere * @param sphere defines the sphere to test * @returns true if there is an intersection */ public intersectsSphere(sphere: DeepImmutable<BoundingSphere>): boolean { return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld); } /** * Tests if the bounding box intersects with a box defined by a min and max vectors * @param min defines the min vector to use * @param max defines the max vector to use * @returns true if there is an intersection */ public intersectsMinMax(min: DeepImmutable<Vector3>, max: DeepImmutable<Vector3>): boolean { const myMin = this.minimumWorld; const myMax = this.maximumWorld; const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; if (myMaxX < minX || myMinX > maxX) { return false; } if (myMaxY < minY || myMinY > maxY) { return false; } if (myMaxZ < minZ || myMinZ > maxZ) { return false; } return true; } // Statics /** * Tests if two bounding boxes are intersections * @param box0 defines the first box to test * @param box1 defines the second box to test * @returns true if there is an intersection */ public static Intersects(box0: DeepImmutable<BoundingBox>, box1: DeepImmutable<BoundingBox>): boolean { return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld); } /** * Tests if a bounding box defines by a min/max vectors intersects a sphere * @param minPoint defines the minimum vector of the bounding box * @param maxPoint defines the maximum vector of the bounding box * @param sphereCenter defines the sphere center * @param sphereRadius defines the sphere radius * @returns true if there is an intersection */ public static IntersectsSphere(minPoint: DeepImmutable<Vector3>, maxPoint: DeepImmutable<Vector3>, sphereCenter: DeepImmutable<Vector3>, sphereRadius: number): boolean { const vector = BoundingBox.TmpVector3[0]; Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector); var num = Vector3.DistanceSquared(sphereCenter, vector); return (num <= (sphereRadius * sphereRadius)); } /** * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes * @param boundingVectors defines an array of 8 vectors representing a bounding box * @param frustumPlanes defines the frustum planes to test * @return true if there is an inclusion */ public static IsCompletelyInFrustum(boundingVectors: Array<DeepImmutable<Vector3>>, frustumPlanes: Array<DeepImmutable<Plane>>): boolean { for (var p = 0; p < 6; ++p) { const frustumPlane = frustumPlanes[p]; for (var i = 0; i < 8; ++i) { if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) { return false; } } } return true; } /** * Tests if a bounding box defined with 8 vectors intersects frustum planes * @param boundingVectors defines an array of 8 vectors representing a bounding box * @param frustumPlanes defines the frustum planes to test * @return true if there is an intersection */ public static IsInFrustum(boundingVectors: Array<DeepImmutable<Vector3>>, frustumPlanes: Array<DeepImmutable<Plane>>): boolean { for (var p = 0; p < 6; ++p) { let canReturnFalse = true; const frustumPlane = frustumPlanes[p]; for (var i = 0; i < 8; ++i) { if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { canReturnFalse = false; break; } } if (canReturnFalse) { return false; } } return true; } }
the_stack
import { Log } from '../util/log'; import { PendingRequest } from '../util/pendingRequests'; let log = Log.create('ThreadPauseCoordinator'); export type PauseType = 'auto' | 'user'; /** * This class coordinates the states of all attached * ["threads"](https://github.com/mozilla/gecko-dev/blob/master/devtools/docs/backend/protocol.md#interacting-with-thread-like-actors). * When debugging multiple threads, some thread pauses may block other threads from being resumed: * when thread A is paused and then thread B is paused, thread A can't be resumed before thread B * is resumed. * * This class distinguishes between automatic and user-visible pauses: * * automatic pauses are requested in order to run some task on the paused thread and automatically * resume it afterwards. These pauses are not visible to the user and are usually short-lived. * * user-visible pauses are triggered by hitting a breakpoint or by a user request to interrupt the * thread. * * This class tries its best to ensure that resuming an automatically-paused thread is not blocked * by another thread that is in a user-visible pause, although this can't always be guaranteed * (e.g. when one thread hits a breakpoint while another thread is in an automatic pause). * It does so by delaying the request for a user-visible pause until all automatically paused threads * have been resumed. */ export class ThreadPauseCoordinator { private currentPauses: ThreadPauseInfo[] = []; private requestedPauses: PendingThreadPauseRequest[] = []; private requestedResumes: PendingThreadResumeRequest[] = []; private interruptingThread?: ThreadPauseInfo; private resumingThread?: ThreadInfo; /** * This method is called when a thread should be interrupted and returns a Promise that is * resolved when this class considers it to be "safe" to interrupt the thread. * In particular, if a thread should be interrupted due to a user request while another thread is * in an automatic pause (i.e. some actions are running on the paused thread and it will be * automatically resumed when they have finished), the returned Promise will only be resolved * once the automatically paused thread is resumed because otherwise the requested pause will * block the other thread from being resumed. */ public requestInterrupt(threadId: number, threadName: string, pauseType: PauseType): Promise<void> { if (log.isDebugEnabled()) { log.debug(`Requesting ${pauseType} interrupt for ${threadName}`); } if (this.findPauseIndex(threadId) !== undefined) { log.warn(`Requesting ${threadName} to be interrupted but it seems to be paused already`); return Promise.resolve(undefined); } let promise = new Promise<void>((resolve, reject) => { let pendingRequest = { resolve, reject }; this.requestedPauses.push({ threadId, threadName, pauseType, pendingRequest }); }); this.doNext(); return promise; } /** * This method is called when a thread should be resumed and returns a Promise that is * resolved when resuming it is not blocked by another thread's pause. * If resuming the thread was requested by the user, but it is blocked by another thread's * pause which was also requested by the user, the Promise will be rejected with a message * to be shown to the user to tell him which threads need to be resumed first. */ public requestResume(threadId: number, threadName: string): Promise<void> { if (log.isDebugEnabled()) { log.debug(`Requesting resume for ${threadName}`); } let pause: ThreadPauseInfo | undefined; if ((this.interruptingThread !== undefined) && (this.interruptingThread.threadId == threadId)) { pause = this.interruptingThread; } else { let pauseIndex = this.findPauseIndex(threadId); if (pauseIndex !== undefined) { pause = this.currentPauses[pauseIndex]; } } if (pause === undefined) { log.warn(`Requesting ${threadName} to be resumed but it doesn't seem to be paused`); return Promise.resolve(); } if (pause.pauseType === 'user') { let hinderingPauses = this.findHinderingPauses(threadId); if (hinderingPauses.length > 0) { let msg = `${threadName} can't be resumed because you need to resume ${hinderingPauses.map((pauseInfo) => pauseInfo.threadName).join(', ')} first`; log.info(msg); return Promise.reject(msg); } } let promise = new Promise<void>((resolve, reject) => { let pendingRequest = { resolve, reject }; this.requestedResumes.push({ threadId, threadName, pendingRequest }); }); this.doNext(); return promise; } /** * This method is called whenever a thread was interrupted. */ public notifyInterrupted(threadId: number, threadName: string, pauseType: PauseType): void { if (log.isDebugEnabled()) { log.debug(`${threadName} interrupted, type ${pauseType}`); } if ((this.interruptingThread !== undefined) && (this.interruptingThread.threadId === threadId)) { this.interruptingThread = undefined; } if (this.findPauseIndex(threadId) === undefined) { this.currentPauses.push({ threadId, threadName, pauseType }); if ((this.interruptingThread !== undefined) || (this.resumingThread !== undefined)) { log.warn(`Received paused notification from ${threadName} while waiting for a notification from another thread`); } } this.doNext(); } /** * This method is called whenever a thread was requested to be interrupted, but the request failed. */ public notifyInterruptFailed(threadId: number, threadName: string): void { if (log.isDebugEnabled()) { log.debug(`Interrupting ${threadName} failed`); } if ((this.interruptingThread !== undefined) && (this.interruptingThread.threadId === threadId)) { this.interruptingThread = undefined; } } /** * This method is called whenever a thread was resumed. */ public notifyResumed(threadId: number, threadName: string): void { if (log.isDebugEnabled()) { log.debug(`${threadName} resumed`); } let pauseIndex = this.findPauseIndex(threadId); if (pauseIndex === undefined) { log.warn(`Received resumed notification from ${threadName} but it doesn't seem to be paused`); } else if (pauseIndex === this.currentPauses.length - 1) { this.currentPauses.pop(); } else { log.warn(`Received resumed notification from ${threadName} even though it is not the most recently paused thread`); this.currentPauses.splice(pauseIndex, 1); } if ((this.resumingThread !== undefined) && (this.resumingThread.threadId === threadId)) { this.resumingThread = undefined; } if ((this.interruptingThread !== undefined) || (this.resumingThread !== undefined)) { log.warn(`Received resumed notification from ${threadName} while waiting for a notification from another thread`); } this.doNext(); } /** * This method is called whenever a thread was requested to be resumed, but the request failed. */ public notifyResumeFailed(threadId: number, threadName: string): void { if (log.isDebugEnabled()) { log.debug(`Resuming ${threadName} failed`); } if ((this.resumingThread !== undefined) && (this.resumingThread.threadId === threadId)) { this.resumingThread = undefined; } } /** * This method is called whenever a thread was detached. */ public threadTerminated(threadId: number, threadName: string) { if (log.isDebugEnabled()) { log.debug(`Removing ${threadName}`); } if (this.interruptingThread && (this.interruptingThread.threadId === threadId)) { this.interruptingThread = undefined; } if (this.resumingThread && (this.resumingThread.threadId === threadId)) { this.resumingThread = undefined; } this.requestedPauses = this.requestedPauses.filter((pauseRequest) => { if (pauseRequest.threadId === threadId) { pauseRequest.pendingRequest.reject('Thread terminated'); return false; } return true; }); this.requestedResumes = this.requestedResumes.filter((requestedResume) => { if (requestedResume.threadId === threadId) { requestedResume.pendingRequest.reject('Thread terminated'); return false; } return true; }); this.currentPauses = this.currentPauses.filter( (currentPause) => (currentPause.threadId !== threadId)); this.doNext(); } /** * This method is called whenever `requestedPauses` or `requestedResumes` changed and decides * what should be done next (if anything) and will do it by calling `pauseThread()` or * `resumeThread()`. */ private doNext(): void { if (log.isDebugEnabled()) { let msg = ''; if (this.interruptingThread !== undefined) { msg += `Interrupting ${this.interruptingThread.threadName}, `; } if (this.resumingThread !== undefined) { msg += `Resuming ${this.resumingThread.threadName}, `; } msg += `current pauses: [${ this.currentPauses.map((info) => info.threadName + '/' + info.pauseType).join(',') }], requested pauses: [${ this.requestedPauses.map((info) => info.threadName + '/' + info.pauseType).join(',') }], requested resumes: [${ this.requestedResumes.map((info) => info.threadName).join(',') }]`; log.debug(msg); } if ((this.interruptingThread !== undefined) || (this.resumingThread !== undefined)) { return; } if (this.currentPauses.length > 0) { let mostRecentPause = this.currentPauses[this.currentPauses.length - 1]; let resumeRequestIndex = this.findResumeRequestIndex(mostRecentPause.threadId); if (resumeRequestIndex !== undefined) { this.resumeThread(resumeRequestIndex); return; } if (mostRecentPause.pauseType === 'auto') { let automaticPauseRequestIndex = this.findAutomaticPauseRequestIndex(); if (automaticPauseRequestIndex !== undefined) { this.pauseThread(automaticPauseRequestIndex); } return; } } //TODO should we block requested pauses if there is a resume waiting? if (this.requestedPauses.length > 0) { this.pauseThread(this.requestedPauses.length - 1); } } private pauseThread(pauseRequestIndex: number) { let pauseRequest = this.requestedPauses[pauseRequestIndex]; log.debug(`Interrupting ${pauseRequest.threadName}`); this.requestedPauses.splice(pauseRequestIndex, 1); if (this.findPauseIndex(pauseRequest.threadId) === undefined) { this.interruptingThread = { threadId: pauseRequest.threadId, threadName: pauseRequest.threadName, pauseType: pauseRequest.pauseType }; } else { log.warn(`Executing pause request for ${pauseRequest.threadName} but it seems to be paused already`); } pauseRequest.pendingRequest.resolve(undefined); } private resumeThread(resumeRequestIndex: number) { let resumeRequest = this.requestedResumes[resumeRequestIndex]; log.debug(`Resuming ${resumeRequest.threadName}`); this.requestedResumes.splice(resumeRequestIndex, 1); this.resumingThread = { threadId: resumeRequest.threadId, threadName: resumeRequest.threadName }; resumeRequest.pendingRequest.resolve(undefined); } private findPauseIndex(threadId: number): number | undefined { for (let i = this.currentPauses.length - 1; i >= 0; i--) { if (this.currentPauses[i].threadId === threadId) { return i; } } return undefined; } private findResumeRequestIndex(threadId: number): number | undefined { for (let i = 0; i < this.requestedResumes.length; i++) { if (this.requestedResumes[i].threadId === threadId) { return i; } } return undefined; } private findAutomaticPauseRequestIndex(): number | undefined { for (let i = 0; i < this.requestedPauses.length; i++) { if (this.requestedPauses[i].pauseType === 'auto') { return i; } } return undefined; } private findHinderingPauses(resumeThreadId: number): ThreadPauseInfo[] { let hinderingPauses: ThreadPauseInfo[] = []; if ((this.interruptingThread !== undefined) && (this.interruptingThread.threadId !== resumeThreadId) && (this.interruptingThread.pauseType === 'user')) { hinderingPauses.push(this.interruptingThread); } for (let i = this.currentPauses.length - 1; i >= 0; i--) { let pause = this.currentPauses[i]; if (pause.threadId === resumeThreadId) { break; } if (pause.pauseType === 'user') { hinderingPauses.push(pause); } } return hinderingPauses; } } interface ThreadInfo { threadId: number; threadName: string; } interface ThreadPauseInfo extends ThreadInfo { pauseType: PauseType; } interface PendingThreadPauseRequest extends ThreadPauseInfo { pendingRequest: PendingRequest<void>; } interface PendingThreadResumeRequest extends ThreadInfo { pendingRequest: PendingRequest<void>; }
the_stack
import automl from '@google-cloud/automl'; import * as dayjs from 'dayjs'; import * as express from 'express'; import { auth } from 'google-auth-library'; import * as morgan from 'morgan'; import { AUTOML_API_SCOPE, AUTOML_API_URL, AUTOML_BUCKET_URL, LOCATION, PROJECT_ID, } from './constants'; import { OperationMetadata } from './types'; export const app = express(); app.use(express.json()); app.use(morgan('combined')); const client = new automl.v1beta1.AutoMlClient(); // Controls model type. For more options, see: // https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models#imageclassificationmodelmetadata const DEFAULT_MODEL_TYPE = 'mobile-high-accuracy-1'; const DEFAULT_TRAIN_BUDGET = 1; const DATASET_NAME_REGEX = new RegExp('^[a-zA-Z_0-9]+$'); const MODEL_VERSION_FORMAT = 'vYYYYMMDDHHmmss'; const parent = client.locationPath(PROJECT_ID, LOCATION); // A model as returned by AutoML /models response interface Model { name: string; datasetId: string; displayName: string; createTime: string; updateTime: string; imageClassificationModelMetadata: { trainBudget: string; trainCost: string; stopReason: string; modelType: string; }; } interface ModelResp { model: Model[]; } /// create a new dataset function createDataset(displayName: String): Promise<any> { const dataset = { name: displayName, displayName, imageClassificationDatasetMetadata: { classificationType: 'MULTICLASS', }, }; return client.createDataset({ parent, dataset }); } const extractIdFromName = (datasetName: string): string => { const parts = datasetName.split('/'); return parts[parts.length - 1]; }; /// returns the ID of a dataset of the format ICN** or null if not found function getDatasetName(automlId: string): Promise<string | null> { return client.listDatasets({ parent }).then((responses: any[]) => { const datasets = responses[0]; for (const dataset of datasets) { if (extractIdFromName(dataset['name']) === automlId) { return dataset['name']; } } return null; }); } /// initiates an operation on automl to start importing data for a dataset async function importDataset( name: string, displayName: string, labels: string ): Promise<OperationMetadata> { const inputConfig = { gcsSource: { inputUris: [`${AUTOML_BUCKET_URL}/${displayName}/${labels}`], }, }; return client .importData({ name, inputConfig }) .then((responses: any[]) => responses[1]); // initial api response with operation metadata } /** * List all datasets */ app.get('/datasets', async (req, res, next) => { try { const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/datasets`; const resp = await authClient.request({ url }); res.json(resp.data); } catch (err) { console.error(err); next(err); } }); /** * Endpoint to create a new dataset in automl. Requires a name parameter */ app.post('/datasets', async (req, res, next) => { try { const { displayName } = req.body; if (displayName === undefined) { res.status(400).send('Expected a dataset `displayName`'); return; } if (!displayName.match(DATASET_NAME_REGEX)) { res .status(400) .send( 'The displayName contains a not allowed character, the' + ' only allowed ones are ASCII Latin letters A-Z and a-z, an underscore (_),' + ' and ASCII digits 0-9' ); return; } console.info(`Attempting to create dataset: ${displayName}`); const [response] = await createDataset(displayName); res.json(response); } catch (err) { res.status(500); res.json({message: err.message}); console.error(err); } }); /** * Endpoint to delete dataset from automl */ app.delete('/datasets/:datasetId', async (req, res, next) => { try { const { datasetId } = req.params; if (!datasetId) { res.status(400).send(`Expected datasetId: ${datasetId}`); return; } const name = await getDatasetName(datasetId); if (name === null) { res.status(404).send(`No dataset found for id: ${datasetId}`); return; } const resp = await client.deleteDataset({ name }); console.log(resp); res.json(); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** * Endpoint to initiate importing data for a dataset in automl. * * Inputs: * - datasetId: string - automl ID of the dataset * - name: string - display name of the dataset * - labels: string - file name containing the labels information. e.g * labels.csv */ app.post('/import', async (req, res, next) => { const { name, labels, datasetId } = req.body; if (!name) { res.status(400).json({ error: 'Need a dataset name' }); return; } if (!datasetId) { res.status(400).json({ error: 'Need a dataset Id' }); return; } if (!labels) { res.status(400).json({ error: 'Need a path for labels file' }); return; } try { const datasetName = await getDatasetName(datasetId); if (datasetName === null) { res.status(400).json({ error: 'Dataset not found' }); return; } const operationMetadata = await importDataset(datasetName, name, labels); res.json(operationMetadata); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** * Endpoint to initiate creation of a new model for the provided dataset * * Inputs * - datasetId: string - automl ID of the dataset * - trainBudget (optional) * - modelType (optional) * Calls the create model api on AutoML * https://cloud.google.com/vision/automl/alpha/docs/reference/rest/v1beta1/projects.locations.models/create * * Uses the rest API */ app.post('/train', async (req, res, next) => { const { datasetId } = req.body; if (!datasetId) { res.status(400).json({ error: 'Need a dataset Id' }); return; } let { trainBudget, modelType } = req.body; trainBudget = trainBudget === undefined ? DEFAULT_TRAIN_BUDGET : trainBudget; modelType = modelType === undefined ? DEFAULT_MODEL_TYPE : modelType; console.log( `Using train budget: ${trainBudget}, and model type: ${modelType}` ); try { const datasetName = await getDatasetName(datasetId); if (datasetName === null) { res.status(400).json({ error: 'Dataset not found' }); return; } const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/models`; const resp = await authClient.request({ method: 'POST', data: { displayName: `${dayjs().format(MODEL_VERSION_FORMAT)}`, dataset_id: datasetId, imageClassificationModelMetadata: { trainBudget, modelType }, }, url, }); const operationMetadata = resp.data as OperationMetadata; res.json(operationMetadata); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** * Exports a model in tflite format to a gcspath * * modelId - AutoML model ID: "ICN1119584480450950787", * gcsPath - Path to which model is exported * "gs://${AUTOML_BUCKET}/models/on-device/<folder_name>" * * Note the model will be generated in a folder with timestamp as name. For * more, refer to * https://cloud.google.com/vision/automl/alpha/docs/deploy#deployment_on_mobile_models_not_core_ml */ app.post('/export', async (req, res, next) => { const { modelId, gcsPath } = req.body; if (!modelId) { res.status(400).send('need a model id: modelId'); return; } if (!gcsPath) { res.status(400).send('need a gcs path: gcsPath'); return; } const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/models/${modelId}:export`; try { const operationMetadata = await authClient .request({ method: 'POST', url, data: { output_config: { model_format: 'tflite', gcs_destination: { output_uri_prefix: gcsPath, }, }, }, }) .then(resp => resp.data as OperationMetadata); res.json(operationMetadata); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** * Exports the latest generated model for the dataset */ app.post('/exportlatestmodel', async (req, res, next) => { const { datasetId, gcsPath } = req.body; if (!datasetId) { res.status(400).send('need a dataset id: datasetId'); return; } if (!gcsPath) { res.status(400).send('need a gcs path: gcsPath'); return; } try { // 1. Get all the models const modelsResp = (await getAllModels()).data as ModelResp; // 2. Filter the models for the provided dataset and get the latest model const datasetModels = modelsResp.model.filter( m => m.datasetId === datasetId && m.imageClassificationModelMetadata.modelType.startsWith('mobile-') ); if (datasetModels === undefined) { throw new Error('No models found for this dataset'); } // 3. Find the latest (based on createTime) model const latestModel = datasetModels.sort( (m1, m2) => new Date(m2.createTime).getTime() - new Date(m1.createTime).getTime() )[0]; // 3. Initiate its export console.log('Initiating export for the latest model', latestModel); const modelId = extractIdFromName(latestModel.name); const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/models/${modelId}:export`; const operationMetadata = await authClient .request({ method: 'POST', url, data: { output_config: { model_format: 'tflite', gcs_destination: { output_uri_prefix: gcsPath, }, }, }, }) .then(resp => resp.data as OperationMetadata); res.json(operationMetadata); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** * List all models - trying out the REST API */ app.get('/models', async (req, res, next) => { try { const resp = await getAllModels(); res.json(resp.data); } catch (err) { console.error(err); res.status(500); res.json({message: err.message}); } }); /** Queries all models from AutoML */ async function getAllModels() { const authClient = await auth.getClient({ scopes: [AUTOML_API_SCOPE] }); const url = `${AUTOML_API_URL}/models`; return authClient.request({ url }); }
the_stack
import { DefaultNetEventHandler } from "./default-net-event-handler"; import { PackageType } from "./pkg-type"; import { SocketState } from "./socketStateType"; import { WSocket } from "./wsocket"; export class NetNode<ProtoKeyType> implements enet.INode<ProtoKeyType> { /** * 套接字实现 */ protected _socket: enet.ISocket; public get socket(): enet.ISocket { return this._socket; } /** * 网络事件处理器 */ protected _netEventHandler: enet.INetEventHandler; public get netEventHandler(): enet.INetEventHandler<any> { return this._netEventHandler; } /** * 协议处理器 */ protected _protoHandler: enet.IProtoHandler; public get protoHandler(): enet.IProtoHandler<any> { return this._protoHandler; } /** * 当前重连次数 */ protected _curReconnectCount: number = 0; /** * 重连配置 */ protected _reConnectCfg: enet.IReconnectConfig; /** * 是否初始化 */ protected _inited: boolean; /** * 连接参数对象 */ protected _connectOpt: enet.IConnectOptions; /** * 是否正在重连 */ protected _isReconnecting: boolean; /** * 计时器id */ protected _reconnectTimerId: any; /** * 请求id * 会自增 */ protected _reqId: number = 1; /** * 永久监听处理器字典 * key为请求key = protoKey * value为 回调处理器或回调函数 */ protected _pushHandlerMap: { [key: string]: enet.AnyCallback[] }; /** * 一次监听推送处理器字典 * key为请求key = protoKey * value为 回调处理器或回调函数 */ protected _oncePushHandlerMap: { [key: string]: enet.AnyCallback[] }; /** * 请求响应回调字典 * key为请求key = protoKey_reqId * value为 回调处理器或回调函数 */ protected _reqCfgMap: { [key: number]: enet.IRequestConfig }; /**socket事件处理器 */ protected _socketEventHandler: enet.ISocketEventHandler; /** * 获取socket事件处理器 */ protected get socketEventHandler(): enet.ISocketEventHandler { if (!this._socketEventHandler) { this._socketEventHandler = { onSocketClosed: this._onSocketClosed.bind(this), onSocketConnected: this._onSocketConnected.bind(this), onSocketError: this._onSocketError.bind(this), onSocketMsg: this._onSocketMsg.bind(this) }; } return this._socketEventHandler; } /**数据包类型处理 */ protected _pkgTypeHandlers: { [key: number]: (dpkg: enet.IDecodePackage) => void }; /**心跳配置 */ protected _heartbeatConfig: enet.IHeartBeatConfig; /**心跳间隔阈值 默认100毫秒 */ protected _gapThreashold: number; /**使用加密 */ protected _useCrypto: boolean; public init(config?: enet.INodeConfig): void { if (this._inited) return; this._protoHandler = config && config.protoHandler ? config.protoHandler : new DefaultProtoHandler(); this._socket = config && config.socket ? config.socket : new WSocket(); this._netEventHandler = config && config.netEventHandler ? config.netEventHandler : new DefaultNetEventHandler(); this._pushHandlerMap = {}; this._oncePushHandlerMap = {}; this._reqCfgMap = {}; const reConnectCfg = config && config.reConnectCfg; if (!reConnectCfg) { this._reConnectCfg = { reconnectCount: 4, connectTimeout: 60000 }; } else { this._reConnectCfg = reConnectCfg; if (isNaN(reConnectCfg.reconnectCount)) { this._reConnectCfg.reconnectCount = 4; } if (isNaN(reConnectCfg.connectTimeout)) { this._reConnectCfg.connectTimeout = 60000; } } this._gapThreashold = config && !isNaN(config.heartbeatGapThreashold) ? config.heartbeatGapThreashold : 100; this._useCrypto = config && config.useCrypto; this._inited = true; this._socket.setEventHandler(this.socketEventHandler); this._pkgTypeHandlers = {}; this._pkgTypeHandlers[PackageType.HANDSHAKE] = this._onHandshake.bind(this); this._pkgTypeHandlers[PackageType.HEARTBEAT] = this._heartbeat.bind(this); this._pkgTypeHandlers[PackageType.DATA] = this._onData.bind(this); this._pkgTypeHandlers[PackageType.KICK] = this._onKick.bind(this); } public connect(option: string | enet.IConnectOptions, connectEnd?: VoidFunction): void { const socket = this._socket; const socketInCloseState = socket && (socket.state === SocketState.CLOSING || socket.state === SocketState.CLOSED); if (this._inited && socketInCloseState) { if (typeof option === "string") { option = { url: option, connectEnd: connectEnd }; } if (connectEnd) { option.connectEnd = connectEnd; } this._connectOpt = option; this._socket.connect(option); const netEventHandler = this._netEventHandler; netEventHandler.onStartConnenct && netEventHandler.onStartConnenct(option); } else { console.error(`is not inited${socket ? " , socket state" + socket.state : ""}`); } } public disConnect(): void { this._socket.close(true); //清理心跳定时器 if (this._heartbeatTimeId) { clearTimeout(this._heartbeatTimeId); this._heartbeatTimeId = undefined; } if (this._heartbeatTimeoutId) { clearTimeout(this._heartbeatTimeoutId); this._heartbeatTimeoutId = undefined; } } public reConnect(): void { if (!this._inited || !this._socket) { return; } if (this._curReconnectCount > this._reConnectCfg.reconnectCount) { this._stopReconnect(false); return; } if (!this._isReconnecting) { const netEventHandler = this._netEventHandler; netEventHandler.onStartReconnect && netEventHandler.onStartReconnect(this._reConnectCfg, this._connectOpt); } this._isReconnecting = true; this.connect(this._connectOpt); this._curReconnectCount++; const netEventHandler = this._netEventHandler; netEventHandler.onReconnecting && netEventHandler.onReconnecting(this._curReconnectCount, this._reConnectCfg, this._connectOpt); this._reconnectTimerId = setTimeout(() => { this.reConnect(); }, this._reConnectCfg.connectTimeout); } public request<ReqData = any, ResData = any>( protoKey: ProtoKeyType, data: ReqData, resHandler: | enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>>, arg?: any ): void { if (!this._isSocketReady()) return; const reqId = this._reqId; const protoHandler = this._protoHandler; const encodePkg = protoHandler.encodeMsg({ key: protoKey, reqId: reqId, data: data }, this._useCrypto); if (encodePkg) { let reqCfg: enet.IRequestConfig = { reqId: reqId, protoKey: protoHandler.protoKey2Key(protoKey), data: data, resHandler: resHandler }; if (arg) reqCfg = Object.assign(reqCfg, arg); this._reqCfgMap[reqId] = reqCfg; this._reqId++; this._netEventHandler.onStartRequest && this._netEventHandler.onStartRequest(reqCfg, this._connectOpt); this.send(encodePkg); } } public notify<T>(protoKey: ProtoKeyType, data?: T): void { if (!this._isSocketReady()) return; const encodePkg = this._protoHandler.encodeMsg( { key: protoKey, data: data } as enet.IMessage, this._useCrypto ); this.send(encodePkg); } public send(netData: enet.NetData): void { this._socket.send(netData); } public onPush<ResData = any>( protoKey: ProtoKeyType, handler: enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>> ): void { const key = this._protoHandler.protoKey2Key(protoKey); if (!this._pushHandlerMap[key]) { this._pushHandlerMap[key] = [handler]; } else { this._pushHandlerMap[key].push(handler); } } public oncePush<ResData = any>( protoKey: ProtoKeyType, handler: enet.ICallbackHandler<enet.IDecodePackage<ResData>> | enet.ValueCallback<enet.IDecodePackage<ResData>> ): void { const key = this._protoHandler.protoKey2Key(protoKey); if (!this._oncePushHandlerMap[key]) { this._oncePushHandlerMap[key] = [handler]; } else { this._oncePushHandlerMap[key].push(handler); } } public offPush(protoKey: ProtoKeyType, callbackHandler: enet.AnyCallback, context?: any, onceOnly?: boolean): void { const key = this._protoHandler.protoKey2Key(protoKey); let handlers: enet.AnyCallback[]; if (onceOnly) { handlers = this._oncePushHandlerMap[key]; } else { handlers = this._pushHandlerMap[key]; } if (handlers) { let handler: enet.AnyCallback; let isEqual: boolean; for (let i = handlers.length - 1; i > -1; i--) { handler = handlers[i]; isEqual = false; if (typeof handler === "function" && handler === callbackHandler) { isEqual = true; } else if ( typeof handler === "object" && handler.method === callbackHandler && (!context || context === handler.context) ) { isEqual = true; } if (isEqual) { if (i !== handlers.length) { handlers[i] = handlers[handlers.length - 1]; handlers[handlers.length - 1] = handler; } handlers.pop(); } } } } public offPushAll(protoKey?: ProtoKeyType): void { if (protoKey) { const key = this._protoHandler.protoKey2Key(protoKey); delete this._pushHandlerMap[key]; delete this._oncePushHandlerMap[key]; } else { this._pushHandlerMap = {}; this._oncePushHandlerMap = {}; } } /** * 握手包处理 * @param dpkg */ protected _onHandshake(dpkg: enet.IDecodePackage) { if (dpkg.errorMsg) { return; } this._handshakeInit(dpkg); const ackPkg = this._protoHandler.encodePkg({ type: PackageType.HANDSHAKE_ACK }); this.send(ackPkg); const connectOpt = this._connectOpt; const handshakeRes = this._protoHandler.handShakeRes; connectOpt.connectEnd && connectOpt.connectEnd(handshakeRes); this._netEventHandler.onConnectEnd && this._netEventHandler.onConnectEnd(connectOpt, handshakeRes); } /** * 握手初始化 * @param dpkg */ protected _handshakeInit(dpkg: enet.IDecodePackage) { const heartbeatCfg = this.protoHandler.heartbeatConfig; this._heartbeatConfig = heartbeatCfg; } /**心跳超时定时器id */ protected _heartbeatTimeoutId: number; /**心跳定时器id */ protected _heartbeatTimeId: number; /**最新心跳超时时间 */ protected _nextHeartbeatTimeoutTime: number; /** * 心跳包处理 * @param dpkg */ protected _heartbeat(dpkg: enet.IDecodePackage) { const heartbeatCfg = this._heartbeatConfig; const protoHandler = this._protoHandler; if (!heartbeatCfg || !heartbeatCfg.heartbeatInterval) { return; } if (this._heartbeatTimeoutId) { return; } this._heartbeatTimeId = setTimeout(() => { this._heartbeatTimeId = undefined; const heartbeatPkg = protoHandler.encodePkg({ type: PackageType.HEARTBEAT }, this._useCrypto); this.send(heartbeatPkg); this._nextHeartbeatTimeoutTime = Date.now() + heartbeatCfg.heartbeatTimeout; this._heartbeatTimeoutId = setTimeout( this._heartbeatTimeoutCb.bind(this), heartbeatCfg.heartbeatTimeout ) as any; }, heartbeatCfg.heartbeatInterval) as any; } /** * 心跳超时处理 */ protected _heartbeatTimeoutCb() { var gap = this._nextHeartbeatTimeoutTime - Date.now(); if (gap > this._reConnectCfg) { this._heartbeatTimeoutId = setTimeout(this._heartbeatTimeoutCb.bind(this), gap) as any; } else { console.error("server heartbeat timeout"); this.disConnect(); } } /** * 数据包处理 * @param dpkg */ protected _onData(dpkg: enet.IDecodePackage) { if (dpkg.errorMsg) { return; } let reqCfg: enet.IRequestConfig; if (!isNaN(dpkg.reqId) && dpkg.reqId > 0) { //请求 const reqId = dpkg.reqId; reqCfg = this._reqCfgMap[reqId]; if (!reqCfg) return; reqCfg.decodePkg = dpkg; this._runHandler(reqCfg.resHandler, dpkg); } else { const pushKey = dpkg.key; //推送 let handlers = this._pushHandlerMap[pushKey]; const onceHandlers = this._oncePushHandlerMap[pushKey]; if (!handlers) { handlers = onceHandlers; } else if (onceHandlers) { handlers = handlers.concat(onceHandlers); } delete this._oncePushHandlerMap[pushKey]; if (handlers) { for (let i = 0; i < handlers.length; i++) { this._runHandler(handlers[i], dpkg); } } } const netEventHandler = this._netEventHandler; netEventHandler.onData && netEventHandler.onData(dpkg, this._connectOpt, reqCfg); } /** * 踢下线数据包处理 * @param dpkg */ protected _onKick(dpkg: enet.IDecodePackage) { this._netEventHandler.onKick && this._netEventHandler.onKick(dpkg, this._connectOpt); } /** * socket状态是否准备好 */ protected _isSocketReady(): boolean { const socket = this._socket; const socketIsReady = socket && (socket.state === SocketState.CONNECTING || socket.state === SocketState.OPEN); if (this._inited && socketIsReady) { return true; } else { console.error( `${ this._inited ? socketIsReady ? "socket is ready" : "socket is null or unready" : "netNode is unInited" }` ); return false; } } /** * 当socket连接成功 * @param event */ protected _onSocketConnected(event: any): void { if (this._isReconnecting) { this._stopReconnect(); } else { const handler = this._netEventHandler; const connectOpt = this._connectOpt; const protoHandler = this._protoHandler; if (protoHandler && connectOpt.handShakeReq) { const handShakeNetData = protoHandler.encodePkg({ type: PackageType.HANDSHAKE, data: connectOpt.handShakeReq }); this.send(handShakeNetData); } else { connectOpt.connectEnd && connectOpt.connectEnd(); handler.onConnectEnd && handler.onConnectEnd(connectOpt); } } } /** * 当socket报错 * @param event */ protected _onSocketError(event: any): void { const eventHandler = this._netEventHandler; eventHandler.onError && eventHandler.onError(event, this._connectOpt); } /** * 当socket有消息 * @param event */ protected _onSocketMsg(event: { data: enet.NetData }) { const depackage = this._protoHandler.decodePkg(event.data); const netEventHandler = this._netEventHandler; const pkgTypeHandler = this._pkgTypeHandlers[depackage.type]; if (pkgTypeHandler) { pkgTypeHandler(depackage); } else { console.error(`There is no handler of this type:${depackage.type}`); } if (depackage.errorMsg) { netEventHandler.onCustomError && netEventHandler.onCustomError(depackage, this._connectOpt); } //更新心跳超时时间 if (this._nextHeartbeatTimeoutTime) { this._nextHeartbeatTimeoutTime = Date.now() + this._heartbeatConfig.heartbeatTimeout; } } /** * 当socket关闭 * @param event */ protected _onSocketClosed(event: any): void { const netEventHandler = this._netEventHandler; if (this._isReconnecting) { clearTimeout(this._reconnectTimerId); this.reConnect(); } else { netEventHandler.onClosed && netEventHandler.onClosed(event, this._connectOpt); } } /** * 执行回调,会并接上透传数据 * @param handler 回调 * @param depackage 解析完成的数据包 */ protected _runHandler(handler: enet.AnyCallback, depackage: enet.IDecodePackage) { if (typeof handler === "function") { handler(depackage); } else if (typeof handler === "object") { handler.method && handler.method.apply(handler.context, handler.args ? [depackage].concat(handler.args) : [depackage]); } } /** * 停止重连 * @param isOk 重连是否成功 */ protected _stopReconnect(isOk = true) { if (this._isReconnecting) { this._isReconnecting = false; clearTimeout(this._reconnectTimerId); this._curReconnectCount = 0; const eventHandler = this._netEventHandler; eventHandler.onReconnectEnd && eventHandler.onReconnectEnd(isOk, this._reConnectCfg, this._connectOpt); } } } class DefaultProtoHandler<ProtoKeyType> implements enet.IProtoHandler<ProtoKeyType> { private _heartbeatCfg: enet.IHeartBeatConfig; public get handShakeRes(): any { return undefined; } public get heartbeatConfig(): enet.IHeartBeatConfig { return this._heartbeatCfg; } encodePkg(pkg: enet.IPackage<any>, useCrypto?: boolean): enet.NetData { return JSON.stringify(pkg); } protoKey2Key(protoKey: ProtoKeyType): string { return protoKey as any; } encodeMsg<T>(msg: enet.IMessage<T, ProtoKeyType>, useCrypto?: boolean): enet.NetData { return JSON.stringify({ type: PackageType.DATA, data: msg } as enet.IPackage); } decodePkg(data: enet.NetData): enet.IDecodePackage<any> { const parsedData: enet.IDecodePackage = JSON.parse(data as string); const pkgType = parsedData.type; if (parsedData.type === PackageType.DATA) { const msg: enet.IMessage = parsedData.data; return { key: msg && msg.key, type: pkgType, data: msg.data, reqId: parsedData.data && parsedData.data.reqId } as enet.IDecodePackage; } else { if (pkgType === PackageType.HANDSHAKE) { this._heartbeatCfg = parsedData.data; } return { type: pkgType, data: parsedData.data } as enet.IDecodePackage; } } }
the_stack
import { log, assign, omit, hashMap, getPropertyDescriptor, getBaseClass, defaults, transform } from './tools' import { __extends } from 'tslib' export interface Subclass< T > extends MixableConstructor { new ( ...args ) : T prototype : T } export interface MixableConstructor extends Function{ __super__? : object; mixins? : MixinsState; onExtend? : ( BaseClass : Function ) => void; onDefine? : ( definition : object, BaseClass : Function ) => void; define? : ( definition? : object, statics? : object ) => MixableConstructor; extend? : <T extends object>( definition? : T, statics? : object ) => Subclass<T>; } export interface MixableDefinition { mixins? : Mixin[] } /** * Base class, holding metaprogramming class extensions. * Supports mixins and Class.define metaprogramming method. */ export class Mixable { static onExtend : ( BaseClass : Function ) => void; static onDefine : ( definition : object, BaseClass : Function ) => object; static __super__ : object static mixins : MixinsState; /** * Must be called after inheritance and before 'define'. */ static define( protoProps : MixableDefinition = {}, staticProps? : object ) : MixableConstructor { const BaseClass : MixableConstructor = getBaseClass( this ); // Assign statics. staticProps && assign( this, staticProps ); // Extract and apply mixins from the definition. const { mixins, ...defineMixin } = protoProps; mixins && this.mixins.merge( mixins ); // Unshift definition to the the prototype. this.mixins.mergeObject( this.prototype, defineMixin, true ); // Unshift definition from statics to the prototype. this.mixins.mergeObject( this.prototype, this.mixins.getStaticDefinitions( BaseClass ), true ); // Call onDefine hook, if it's present. this.onDefine && this.onDefine( this.mixins.definitions, BaseClass ); // Apply merge rules to inherited members. No mixins can be added after this point. this.mixins.mergeInheritedMembers( BaseClass ); return this; } /** Backbone-compatible extend method to be used in ES5 and for backward compatibility */ static extend< T extends object>(spec? : T, statics? : {} ) : Subclass< T > { let TheSubclass : Subclass< T >; // 1. Create the subclass (ES5 compatibility shim). // If constructor function is given... if( spec && spec.hasOwnProperty( 'constructor' ) ){ // ...we need to manually call internal TypeScript __extend function. Hack! Hack! TheSubclass = spec.constructor as any; __extends( TheSubclass, this ); } // Otherwise, create the subclall in usual way. else{ TheSubclass = class Subclass extends this {} as any; } predefine( TheSubclass ); spec && TheSubclass.define( spec, statics ); return TheSubclass; } } /** @decorator `@predefine` for forward definitions. Can be used with [[Mixable]] classes only. * Forwards the call to the [[Mixable.predefine]]; */ export function predefine( Constructor : MixableConstructor ) : void { const BaseClass : MixableConstructor = getBaseClass( Constructor ); // Legacy systems support Constructor.__super__ = BaseClass.prototype; // Initialize mixins structures... Constructor.define || MixinsState.get( Mixable ).populate( Constructor ); // Make sure Ctor.mixins are ready before the callback... MixinsState.get( Constructor ); // Call extend hook. Constructor.onExtend && Constructor.onExtend( BaseClass ); } /** @decorator `@define` for metaprogramming magic. Can be used with [[Mixable]] classes only. * Forwards the call to [[Mixable.define]]. */ export function define( ClassOrDefinition : Function ) : void; export function define( ClassOrDefinition : object ) : ClassDecorator; export function define( ClassOrDefinition : object | MixableConstructor ){ // @define class if( typeof ClassOrDefinition === 'function' ){ predefine( ClassOrDefinition ); ClassOrDefinition.define(); } // @define({ prop : val, ... }) class else{ return function( Ctor : MixableConstructor ){ predefine( Ctor ); Ctor.define( ClassOrDefinition ); } } } export function definitions( rules : MixinMergeRules ) : ClassDecorator { return ( Class : Function ) => { const mixins = MixinsState.get( Class ); mixins.definitionRules = defaults( hashMap(), rules, mixins.definitionRules ); } } // Create simple property list decorator export function propertyListDecorator( listName: string ) : PropertyDecorator { return function propList(proto, name : string) { const list = proto.hasOwnProperty( listName ) ? proto[ listName ] : (proto[ listName ] = (proto[ listName ] || []).slice()); list.push(name); } } export function definitionDecorator( definitionKey, value ){ return ( proto : object, name : string ) => { MixinsState .get( proto.constructor ) .mergeObject( proto, { [ definitionKey ] : { [ name ] : value } }); } } export class MixinsState { mergeRules : MixinMergeRules; definitionRules : MixinMergeRules; definitions : object = {}; appliedMixins : Mixin[]; // Return mixins state for the class. Initialize if it's not exist. static get( Class ) : MixinsState { const { mixins } = Class; return mixins && Class === mixins.Class ? mixins : Class.mixins = new MixinsState( Class ); } constructor( public Class : MixableConstructor ){ const { mixins } = getBaseClass( Class ); this.mergeRules = ( mixins && mixins.mergeRules ) || hashMap(); this.definitionRules = ( mixins && mixins.definitionRules ) || hashMap(); this.appliedMixins = ( mixins && mixins.appliedMixins ) || []; } getStaticDefinitions( BaseClass : Function ){ const definitions = hashMap(), { Class } = this; return transform( definitions, this.definitionRules, ( rule, name ) =>{ if( BaseClass[ name ] !== Class[ name ]){ return Class[ name ]; } }); } merge( mixins : Mixin[] ){ const proto = this.Class.prototype, { mergeRules } = this; // Copy applied mixins array as it's going to be updated. const appliedMixins = this.appliedMixins = this.appliedMixins.slice(); // Apply mixins in sequence... for( let mixin of mixins ) { // Mixins array should be flattened. if( Array.isArray( mixin ) ) { this.merge( mixin ); } // Don't apply mixins twice. else if( appliedMixins.indexOf( mixin ) < 0 ){ appliedMixins.push( mixin ); // For constructors, merge _both_ static and prototype members. if( typeof mixin === 'function' ){ // Merge static members this.mergeObject( this.Class, mixin ); // merge definitionRules and mergeRules const sourceMixins = ( mixin as any ).mixins; if( sourceMixins ){ this.mergeRules = defaults( hashMap(), this.mergeRules, sourceMixins.mergeRules ); this.definitionRules = defaults( hashMap(), this.definitionRules, sourceMixins.definitionRules ); this.appliedMixins = this.appliedMixins.concat( sourceMixins.appliedMixins ); } // Prototypes are merged according with rules. this.mergeObject( proto, mixin.prototype ); } // Handle plain object mixins. else { this.mergeObject( proto, mixin ); } } } } populate( ...ctors : Function[] ){ for( let Ctor of ctors ) { MixinsState.get( Ctor ).merge([ this.Class ]); } } mergeObject( dest : object, source : object, unshift? : boolean ) { forEachOwnProp( source, name => { const sourceProp = Object.getOwnPropertyDescriptor( source, name ); let rule : MixinMergeRule; if( rule = this.definitionRules[ name ] ){ assignProperty( this.definitions, name, sourceProp, rule, unshift ); } if( !rule || rule === mixinRules.protoValue ){ assignProperty( dest, name, sourceProp, this.mergeRules[ name ], unshift ); } }); } mergeInheritedMembers( BaseClass : Function ){ const { mergeRules, Class } = this; if( mergeRules ){ const proto = Class.prototype, baseProto = BaseClass.prototype; for( let name in mergeRules ) { const rule = mergeRules[ name ]; if( proto.hasOwnProperty( name ) && name in baseProto ){ proto[ name ] = resolveRule( proto[ name ], baseProto[ name ], rule ); } } } } } const dontMix = { function : hashMap({ length : true, prototype : true, caller : true, arguments : true, name : true, __super__ : true }), object : hashMap({ constructor : true }) } function forEachOwnProp( object : object, fun : ( name : string ) => void ){ const ignore = dontMix[ typeof object ]; for( let name of Object.keys( object ) ) { ignore[ name ] || fun( name ); } } export interface MixinMergeRules { [ name : string ] : MixinMergeRule } export type MixinMergeRule = ( a : any, b : any ) => any export type Mixin = { [ key : string ] : any } | Function // @mixins( A, B, ... ) decorator. export interface MixinRulesDecorator { ( rules : MixinMergeRules ) : ClassDecorator value( a : object, b : object) : object; protoValue( a : object, b : object) : object; merge( a : object, b : object ) : object; pipe( a: Function, b : Function ) : Function; defaults( a: Function, b : Function ) : Function; classFirst( a: Function, b : Function ) : Function; classLast( a: Function, b : Function ) : Function; every( a: Function, b : Function ) : Function; some( a: Function, b : Function ) : Function; } export const mixins = ( ...list : Mixin[] ) => ( ( Class : Function ) => MixinsState.get( Class ).merge( list ) ); // @mixinRules({ name : rule, ... }) decorator. export const mixinRules = ( ( rules : MixinMergeRules ) => ( ( Class : Function ) => { const mixins = MixinsState.get( Class ); mixins.mergeRules = defaults( rules, mixins.mergeRules ); } ) ) as MixinRulesDecorator; // Pre-defined mixin merge rules mixinRules.value = ( a, b ) => a; mixinRules.protoValue = ( a, b ) => a; // Recursively merge members mixinRules.merge = ( a, b ) => defaults( {}, a, b ); // Execute methods in pipe, with the class method executed last. mixinRules.pipe = ( a, b ) => ( function( x : any ) : any { return a.call( this, b.call( this, x ) ); } ); // Assume methods return an object, and merge results with defaults (class method executed first) mixinRules.defaults = ( a : Function, b : Function ) => ( function() : object { return defaults( a.apply( this, arguments ), b.apply( this, arguments ) ); } ); // Execute methods in sequence staring with the class method. mixinRules.classFirst = ( a : Function, b : Function ) => ( function() : void { a.apply( this, arguments ); b.apply( this, arguments ); } ); // Execute methods in sequence ending with the class method. mixinRules.classLast = ( a : Function, b : Function ) => ( function() : void { b.apply( this, arguments ); a.apply( this, arguments ); } ) // Execute methods in sequence returning the first falsy result. mixinRules.every = ( a : Function, b : Function ) =>( function() : any { return a.apply( this, arguments ) && b.apply( this, arguments ); } ); // Execute methods in sequence returning the first truthy result. mixinRules.some = ( a : Function, b : Function ) =>( function() : any { return a.apply( this, arguments ) || b.apply( this, arguments ); } ); /** * Helpers */ function assignProperty( dest : object, name : string, sourceProp : PropertyDescriptor, rule : MixinMergeRule, unshift? : boolean ){ // Destination prop is defined, thus the merge rules must be applied. if( dest.hasOwnProperty( name ) ){ const destProp = Object.getOwnPropertyDescriptor( dest, name ); if( destProp.configurable && 'value' in destProp ){ dest[ name ] = unshift ? resolveRule( sourceProp.value, destProp.value, rule ) : resolveRule( destProp.value, sourceProp.value, rule ) ; } } // If destination is empty, just copy the prop over. else{ Object.defineProperty( dest, name, sourceProp ); } } function resolveRule( dest, source, rule : MixinMergeRule ){ // When destination is empty, take the source. if( dest === void 0 ) return source; // In these cases we take non-empty destination: if( !rule || source === void 0 ) return dest; // In other cases we must merge values. return rule( dest, source ); }
the_stack
export interface FileSystemEntries { files: string[] directories: string[] } export function matchFiles( path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string, getFileSystemEntries: (path: string) => FileSystemEntries ): string[] { path = normalizePath(path) currentDirectory = normalizePath(currentDirectory) const patterns = getFileMatcherPatterns( path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory ) const regexFlag = useCaseSensitiveFileNames ? '' : 'i' const includeFileRegex = patterns.includeFilePattern && new RegExp(patterns.includeFilePattern, regexFlag) const includeDirectoryRegex = patterns.includeDirectoryPattern && new RegExp(patterns.includeDirectoryPattern, regexFlag) const excludeRegex = patterns.excludePattern && new RegExp(patterns.excludePattern, regexFlag) const result: string[] = [] for (const basePath of patterns.basePaths) { visitDirectory(basePath, combinePaths(currentDirectory, basePath)) } return result function visitDirectory(path: string, absolutePath: string) { const { files, directories } = getFileSystemEntries(path) for (const current of files) { const name = combinePaths(path, current) const absoluteName = combinePaths(absolutePath, current) if ( (!extensions || fileExtensionIsAny(name, extensions)) && (!includeFileRegex || includeFileRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName)) ) { result.push(name) } } for (const current of directories) { const name = combinePaths(path, current) const absoluteName = combinePaths(absolutePath, current) if ( (!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName)) ) { visitDirectory(name, absoluteName) } } } } const directorySeparator = '/' export function combinePaths(path1: string, path2: string) { if (!(path1 && path1.length)) return path2 if (!(path2 && path2.length)) return path1 if (getRootLength(path2) !== 0) return path2 if (path1.charAt(path1.length - 1) === directorySeparator) return path1 + path2 return path1 + directorySeparator + path2 } function normalizePath(path: string): string { path = normalizeSlashes(path) const rootLength = getRootLength(path) const root = path.substr(0, rootLength) const normalized = getNormalizedParts(path, rootLength) if (normalized.length) { const joinedParts = root + normalized.join(directorySeparator) return pathEndsWithDirectorySeparator(path) ? joinedParts + directorySeparator : joinedParts } else { return root } } function getFileMatcherPatterns( path: string, extensions: string[], excludes: string[], includes: string[], useCaseSensitiveFileNames: boolean, currentDirectory: string ): FileMatcherPatterns { path = normalizePath(path) currentDirectory = normalizePath(currentDirectory) const absolutePath = combinePaths(currentDirectory, path) return { includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, 'files') || '', includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, 'directories') || '', excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, 'exclude') || '', basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames) || [], } } function fileExtensionIs(path: string, extension: string): boolean { return path.length > extension.length && endsWith(path, extension) } function fileExtensionIsAny(path: string, extensions: string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { return true } } return false } function getRegularExpressionForWildcard( specs: string[], basePath: string, usage: 'files' | 'directories' | 'exclude' ) { if (specs === undefined || specs.length === 0) { return undefined } const replaceWildcardCharacter = usage === 'files' ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther const singleAsteriskRegexFragment = usage === 'files' ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther /** * Regex for the ** wildcard. Matches any number of subdirectories. When used for including * files or directories, does not match subdirectories that start with a . character */ const doubleAsteriskRegexFragment = usage === 'exclude' ? '(/.+?)?' : '(/[^/.][^/]*)*?' let pattern = '' let hasWrittenSubpattern = false spec: for (const spec of specs) { if (!spec) { continue } let subpattern = '' let hasRecursiveDirectoryWildcard = false let hasWrittenComponent = false const components = getNormalizedPathComponents(spec, basePath) if (usage !== 'exclude' && components[components.length - 1] === '**') { continue spec } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. components[0] = removeTrailingDirectorySeparator(components[0]) let optionalCount = 0 for (let component of components) { if (component === '**') { if (hasRecursiveDirectoryWildcard) { continue spec } subpattern += doubleAsteriskRegexFragment hasRecursiveDirectoryWildcard = true hasWrittenComponent = true } else { if (usage === 'directories') { subpattern += '(' optionalCount++ } if (hasWrittenComponent) { subpattern += directorySeparator } if (usage !== 'exclude') { // The * and ? wildcards should not match directories or files that start with . if they // appear first in a component. Dotted directories and files can be included explicitly // like so: **/.*/.* if (component.charCodeAt(0) === CharacterCodes.asterisk) { subpattern += '([^./]' + singleAsteriskRegexFragment + ')?' component = component.substr(1) } else if (component.charCodeAt(0) === CharacterCodes.question) { subpattern += '[^./]' component = component.substr(1) } } subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter) hasWrittenComponent = true } } while (optionalCount > 0) { subpattern += ')?' optionalCount-- } if (hasWrittenSubpattern) { pattern += '|' } pattern += '(' + subpattern + ')' hasWrittenSubpattern = true } if (!pattern) { return undefined } return '^(' + pattern + (usage === 'exclude' ? ')($|/)' : ')$') } function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1 const p1 = path.indexOf('/', 2) if (p1 < 0) return 2 const p2 = path.indexOf('/', p1 + 1) if (p2 < 0) return p1 + 1 return p2 + 1 } if (path.charCodeAt(1) === CharacterCodes.colon) { if (path.charCodeAt(2) === CharacterCodes.slash) return 3 return 2 } // Per RFC 1738 'file' URI schema has the shape file://<host>/<path> // if <host> is omitted then it is assumed that host value is 'localhost', // however slash after the omitted <host> is not removed. // file:///folder1/file1 - this is a correct URI // file://folder2/file2 - this is an incorrect URI if (path.lastIndexOf('file:///', 0) === 0) { return 'file:///'.length } const idx = path.indexOf('://') if (idx !== -1) { return idx + '://'.length } return 0 } function getNormalizedParts(normalizedSlashedPath: string, rootLength: number): string[] { const parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator) const normalized: string[] = [] for (const part of parts) { if (part !== '.') { if (part === '..' && normalized.length > 0 && lastOrUndefined(normalized) !== '..') { normalized.pop() } else { // A part may be an empty string (which is 'falsy') if the path had consecutive slashes, // e.g. "path//file.ts". Drop these before re-joining the parts. if (part) { normalized.push(part) } } } } return normalized } function pathEndsWithDirectorySeparator(path: string): boolean { return path.charCodeAt(path.length - 1) === directorySeparatorCharCode } function replaceWildCardCharacterFiles(match: string) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentFiles) } function replaceWildCardCharacterOther(match: string) { return replaceWildcardCharacter(match, singleAsteriskRegexFragmentOther) } function replaceWildcardCharacter(match: string, singleAsteriskRegexFragment: string) { return match === '*' ? singleAsteriskRegexFragment : match === '?' ? '[^/]' : '\\' + match } function getBasePaths(path: string, includes: string[], useCaseSensitiveFileNames: boolean) { // Storage for our results in the form of literal paths (e.g. the paths as written by the user). const basePaths: string[] = [path] if (includes) { // Storage for literal base paths amongst the include patterns. const includeBasePaths: string[] = [] for (const include of includes) { // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") const absolute: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include)) const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes) const includeBasePath = wildcardOffset < 0 ? removeTrailingDirectorySeparator(getDirectoryPath(absolute)) : absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset)) // Append the literal and canonical candidate base paths. includeBasePaths.push(includeBasePath) } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(useCaseSensitiveFileNames ? compareStrings : compareStringsCaseInsensitive) // Iterate over each include base path and include unique base paths that are not a // subpath of an existing base path include: for (let i = 0; i < includeBasePaths.length; i++) { const includeBasePath = includeBasePaths[i] for (let j = 0; j < basePaths.length; j++) { if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) { continue include } } basePaths.push(includeBasePath) } } return basePaths } function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos } function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison { if (a === b) return Comparison.EqualTo if (a === undefined) return Comparison.LessThan if (b === undefined) return Comparison.GreaterThan if (ignoreCase) { if (String.prototype.localeCompare) { const result = a.localeCompare(b, /*locales*/ undefined, { usage: 'sort', sensitivity: 'accent' }) return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo } a = a.toUpperCase() b = b.toUpperCase() if (a === b) return Comparison.EqualTo } return a < b ? Comparison.LessThan : Comparison.GreaterThan } function compareStringsCaseInsensitive(a: string, b: string) { return compareStrings(a, b, /*ignoreCase*/ true) } const singleAsteriskRegexFragmentFiles = '([^./]|(\\.(?!min\\.js$))?)*' const singleAsteriskRegexFragmentOther = '[^/]*' function getNormalizedPathComponents(path: string, currentDirectory: string) { path = normalizeSlashes(path) let rootLength = getRootLength(path) if (rootLength === 0) { // If the path is not rooted it is relative to current directory path = combinePaths(normalizeSlashes(currentDirectory), path) rootLength = getRootLength(path) } return normalizedPathComponents(path, rootLength) } function normalizedPathComponents(path: string, rootLength: number) { const normalizedParts = getNormalizedParts(path, rootLength) return [path.substr(0, rootLength)].concat(normalizedParts) } function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean) { if (parent === undefined || child === undefined) return false if (parent === child) return true parent = removeTrailingDirectorySeparator(parent) child = removeTrailingDirectorySeparator(child) if (parent === child) return true const parentComponents = getNormalizedPathComponents(parent, currentDirectory) const childComponents = getNormalizedPathComponents(child, currentDirectory) if (childComponents.length < parentComponents.length) { return false } for (let i = 0; i < parentComponents.length; i++) { const result = compareStrings(parentComponents[i], childComponents[i], ignoreCase) if (result !== Comparison.EqualTo) { return false } } return true } function removeTrailingDirectorySeparator(path: string) { if (path.charAt(path.length - 1) === directorySeparator) { return path.substr(0, path.length - 1) } return path } function lastOrUndefined<T>(array: T[]): T | void { return array && array.length > 0 ? array[array.length - 1] : undefined } interface FileMatcherPatterns { includeFilePattern: string includeDirectoryPattern: string excludePattern: string basePaths: string[] } const enum Comparison { LessThan = -1, EqualTo = 0, GreaterThan = 1, } const enum CharacterCodes { nullCharacter = 0, maxAsciiCharacter = 0x7f, lineFeed = 0x0a, // \n carriageReturn = 0x0d, // \r lineSeparator = 0x2028, paragraphSeparator = 0x2029, nextLine = 0x0085, // Unicode 3.0 space characters space = 0x0020, // " " nonBreakingSpace = 0x00a0, // enQuad = 0x2000, emQuad = 0x2001, enSpace = 0x2002, emSpace = 0x2003, threePerEmSpace = 0x2004, fourPerEmSpace = 0x2005, sixPerEmSpace = 0x2006, figureSpace = 0x2007, punctuationSpace = 0x2008, thinSpace = 0x2009, hairSpace = 0x200a, zeroWidthSpace = 0x200b, narrowNoBreakSpace = 0x202f, ideographicSpace = 0x3000, mathematicalSpace = 0x205f, ogham = 0x1680, _ = 0x5f, $ = 0x24, _0 = 0x30, _1 = 0x31, _2 = 0x32, _3 = 0x33, _4 = 0x34, _5 = 0x35, _6 = 0x36, _7 = 0x37, _8 = 0x38, _9 = 0x39, a = 0x61, b = 0x62, c = 0x63, d = 0x64, e = 0x65, f = 0x66, g = 0x67, h = 0x68, i = 0x69, j = 0x6a, k = 0x6b, l = 0x6c, m = 0x6d, n = 0x6e, o = 0x6f, p = 0x70, q = 0x71, r = 0x72, s = 0x73, t = 0x74, u = 0x75, v = 0x76, w = 0x77, x = 0x78, y = 0x79, z = 0x7a, A = 0x41, B = 0x42, C = 0x43, D = 0x44, E = 0x45, F = 0x46, G = 0x47, H = 0x48, I = 0x49, J = 0x4a, K = 0x4b, L = 0x4c, M = 0x4d, N = 0x4e, O = 0x4f, P = 0x50, Q = 0x51, R = 0x52, S = 0x53, T = 0x54, U = 0x55, V = 0x56, W = 0x57, X = 0x58, Y = 0x59, Z = 0x5a, ampersand = 0x26, // & asterisk = 0x2a, // * at = 0x40, // @ backslash = 0x5c, // \ backtick = 0x60, // ` bar = 0x7c, // | caret = 0x5e, // ^ closeBrace = 0x7d, // } closeBracket = 0x5d, // ] closeParen = 0x29, // ) colon = 0x3a, // : comma = 0x2c, // , dot = 0x2e, // . doubleQuote = 0x22, // " equals = 0x3d, // = exclamation = 0x21, // ! greaterThan = 0x3e, // > hash = 0x23, // # lessThan = 0x3c, // < minus = 0x2d, // - openBrace = 0x7b, // { openBracket = 0x5b, // [ openParen = 0x28, // ( percent = 0x25, // % plus = 0x2b, // + question = 0x3f, // ? semicolon = 0x3b, // ; singleQuote = 0x27, // ' slash = 0x2f, // / tilde = 0x7e, // ~ backspace = 0x08, // \b formFeed = 0x0c, // \f byteOrderMark = 0xfeff, tab = 0x09, // \t verticalTab = 0x0b, // \v } const reservedCharacterPattern = /[^\w\s\/]/g const directorySeparatorCharCode = CharacterCodes.slash function isRootedDiskPath(path: string) { return getRootLength(path) !== 0 } function indexOfAnyCharCode(text: string, charCodes: number[], start?: number): number { for (let i = start || 0, len = text.length; i < len; i++) { if (contains(charCodes, text.charCodeAt(i))) { return i } } return -1 } const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question] function getDirectoryPath(path: string): any { return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator))) } function contains<T>(array: T[], value: T): boolean { if (array) { for (const v of array) { if (v === value) { return true } } } return false } function normalizeSlashes(path: string): string { return path.replace(/\\/g, '/') }
the_stack
import * as anchor from '@project-serum/anchor'; import { assert } from 'chai'; import { BN, getMarketOrderParams, ONE, ZERO } from '../sdk'; import { Program } from '@project-serum/anchor'; import { PublicKey } from '@solana/web3.js'; import { Admin, MARK_PRICE_PRECISION, calculateMarkPrice, calculateTradeSlippage, PositionDirection, } from '../sdk/src'; import { Markets } from '../sdk/src/constants/markets'; import { mockUSDCMint, mockUserUSDCAccount, mockOracle } from './testHelpers'; describe('clearing_house', () => { const provider = anchor.AnchorProvider.local(); const connection = provider.connection; anchor.setProvider(provider); const chProgram = anchor.workspace.ClearingHouse as Program; let clearingHouse: Admin; let userAccountPublicKey: PublicKey; let usdcMint; let userUSDCAccount; // ammInvariant == k == x * y const mantissaSqrtScale = new BN(Math.sqrt(MARK_PRICE_PRECISION.toNumber())); const ammInitialQuoteAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const ammInitialBaseAssetAmount = new anchor.BN(5 * 10 ** 13).mul( mantissaSqrtScale ); const usdcAmount = new BN(10 * 10 ** 6); before(async () => { usdcMint = await mockUSDCMint(provider); userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider); clearingHouse = Admin.from( connection, provider.wallet, chProgram.programId, { commitment: 'confirmed', } ); await clearingHouse.initialize(usdcMint.publicKey, true); await clearingHouse.subscribeToAll(); const solUsd = await mockOracle(1); const periodicity = new BN(60 * 60); // 1 HOUR await clearingHouse.initializeMarket( Markets[0].marketIndex, solUsd, ammInitialBaseAssetAmount, ammInitialQuoteAssetAmount, periodicity ); [, userAccountPublicKey] = await clearingHouse.initializeUserAccountAndDepositCollateral( usdcAmount, userUSDCAccount.publicKey ); }); after(async () => { await clearingHouse.unsubscribe(); }); it('Long from 0 position', async () => { const marketIndex = new BN(0); const baseAssetAmount = new BN(497450503674885); const orderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(orderParams); const user: any = await clearingHouse.program.account.user.fetch( userAccountPublicKey ); assert(user.collateral.eq(new BN(9950250))); assert(user.totalFeePaid.eq(new BN(49750))); assert(user.cumulativeDeposits.eq(usdcAmount)); const userPositionsAccount: any = await clearingHouse.program.account.userPositions.fetch(user.positions); assert.ok( userPositionsAccount.positions[0].quoteAssetAmount.eq(new BN(49750001)) ); console.log(userPositionsAccount.positions[0].baseAssetAmount); assert.ok( userPositionsAccount.positions[0].baseAssetAmount.eq(baseAssetAmount) ); const marketsAccount = clearingHouse.getMarketsAccount(); const market = marketsAccount.markets[0]; console.log(market.baseAssetAmount.toNumber()); assert.ok(market.baseAssetAmount.eq(new BN(497450503674885))); assert.ok(market.baseAssetAmountLong.eq(new BN(497450503674885))); assert.ok(market.baseAssetAmountShort.eq(ZERO)); assert.ok(market.openInterest.eq(ONE)); assert.ok(market.amm.totalFee.eq(new BN(49750))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(49750))); const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount(); assert.ok(tradeHistoryAccount.head.toNumber() === 1); assert.ok( tradeHistoryAccount.tradeRecords[0].user.equals(userAccountPublicKey) ); assert.ok(tradeHistoryAccount.tradeRecords[0].recordId.eq(new BN(1))); assert.ok( JSON.stringify(tradeHistoryAccount.tradeRecords[0].direction) === JSON.stringify(PositionDirection.LONG) ); assert.ok( tradeHistoryAccount.tradeRecords[0].baseAssetAmount.eq( new BN(497450503674885) ) ); assert.ok(tradeHistoryAccount.tradeRecords[0].liquidation == false); assert.ok( tradeHistoryAccount.tradeRecords[0].quoteAssetAmount.eq(new BN(49750001)) ); assert.ok(tradeHistoryAccount.tradeRecords[0].marketIndex.eq(marketIndex)); }); it('Order fails due to unrealiziable limit price ', async () => { // Should be a better a way to catch an exception with chai but wasn't working for me try { const newUSDCNotionalAmount = usdcAmount.div(new BN(2)).mul(new BN(5)); const marketIndex = new BN(0); const market = clearingHouse.getMarket(marketIndex); const estTradePrice = calculateTradeSlippage( PositionDirection.SHORT, newUSDCNotionalAmount, market )[2]; // trying to sell at price too high const limitPriceTooHigh = calculateMarkPrice(market); console.log( 'failed order:', estTradePrice.toNumber(), limitPriceTooHigh.toNumber() ); const baseAssetAmount = new BN(497450503674885).div(new BN(2)); const orderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false, limitPriceTooHigh ); await clearingHouse.placeAndFillOrder(orderParams); } catch (e) { assert(true); return; } assert(false, 'Order succeeded'); }); it('Reduce long position', async () => { const marketIndex = new BN(0); const baseAssetAmount = new BN(497450503674885).div(new BN(2)); const orderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(orderParams); const user: any = await clearingHouse.program.account.user.fetch( userAccountPublicKey ); const userPositionsAccount: any = await clearingHouse.program.account.userPositions.fetch(user.positions); assert.ok( userPositionsAccount.positions[0].quoteAssetAmount.eq(new BN(24875001)) ); console.log(userPositionsAccount.positions[0].baseAssetAmount.toNumber()); assert.ok( userPositionsAccount.positions[0].baseAssetAmount.eq( new BN(248725251837443) ) ); console.log(user.collateral.toString()); console.log(user.totalFeePaid.toString()); assert.ok(user.collateral.eq(new BN(9926611))); assert(user.totalFeePaid.eq(new BN(74626))); assert(user.cumulativeDeposits.eq(usdcAmount)); const marketsAccount = clearingHouse.getMarketsAccount(); const market: any = marketsAccount.markets[0]; console.log(market.baseAssetAmount.toString()); assert.ok(market.baseAssetAmount.eq(new BN(248725251837443))); assert.ok(market.baseAssetAmountLong.eq(new BN(248725251837443))); assert.ok(market.baseAssetAmountShort.eq(ZERO)); assert.ok(market.openInterest.eq(ONE)); assert.ok(market.amm.totalFee.eq(new BN(74626))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(74626))); const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount(); assert.ok(tradeHistoryAccount.head.toNumber() === 2); assert.ok( tradeHistoryAccount.tradeRecords[1].user.equals(userAccountPublicKey) ); assert.ok(tradeHistoryAccount.tradeRecords[1].recordId.eq(new BN(2))); assert.ok( JSON.stringify(tradeHistoryAccount.tradeRecords[1].direction) === JSON.stringify(PositionDirection.SHORT) ); console.log(tradeHistoryAccount.tradeRecords[1].baseAssetAmount.toNumber()); assert.ok( tradeHistoryAccount.tradeRecords[1].baseAssetAmount.eq( new BN(248725251837442) ) ); assert.ok(tradeHistoryAccount.tradeRecords[1].liquidation == false); assert.ok( tradeHistoryAccount.tradeRecords[1].quoteAssetAmount.eq(new BN(24876237)) ); assert.ok(tradeHistoryAccount.tradeRecords[1].marketIndex.eq(new BN(0))); }); it('Reverse long position', async () => { const marketIndex = new BN(0); const baseAssetAmount = new BN(497450503674885); const orderParams = getMarketOrderParams( marketIndex, PositionDirection.SHORT, ZERO, baseAssetAmount, false ); await clearingHouse.placeAndFillOrder(orderParams); const user: any = await clearingHouse.program.account.user.fetch( userAccountPublicKey ); const userPositionsAccount: any = await clearingHouse.program.account.userPositions.fetch(user.positions); assert.ok(user.collateral.eq(new BN(9875627))); assert(user.totalFeePaid.eq(new BN(124371))); assert.ok( userPositionsAccount.positions[0].quoteAssetAmount.eq(new BN(24871287)) ); console.log(userPositionsAccount.positions[0].baseAssetAmount.toString()); assert.ok( userPositionsAccount.positions[0].baseAssetAmount.eq( new BN(-248725251837442) ) ); const marketsAccount = clearingHouse.getMarketsAccount(); const market: any = marketsAccount.markets[0]; assert.ok(market.baseAssetAmount.eq(new BN(-248725251837442))); assert.ok(market.baseAssetAmountLong.eq(ZERO)); assert.ok(market.baseAssetAmountShort.eq(new BN(-248725251837442))); assert.ok(market.openInterest.eq(ONE)); assert.ok(market.amm.totalFee.eq(new BN(124371))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(124371))); const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount(); assert.ok(tradeHistoryAccount.head.toNumber() === 3); assert.ok( tradeHistoryAccount.tradeRecords[2].user.equals(userAccountPublicKey) ); assert.ok(tradeHistoryAccount.tradeRecords[2].recordId.eq(new BN(3))); assert.ok( JSON.stringify(tradeHistoryAccount.tradeRecords[2].direction) === JSON.stringify(PositionDirection.SHORT) ); console.log(tradeHistoryAccount.tradeRecords[2].baseAssetAmount.toNumber()); assert.ok( tradeHistoryAccount.tradeRecords[2].baseAssetAmount.eq( new BN(497450503674885) ) ); assert.ok( tradeHistoryAccount.tradeRecords[2].quoteAssetAmount.eq(new BN(49745049)) ); assert.ok(tradeHistoryAccount.tradeRecords[2].marketIndex.eq(new BN(0))); }); it('Close position', async () => { const marketIndex = new BN(0); const baseAssetAmount = new BN(248725251837442); const orderParams = getMarketOrderParams( marketIndex, PositionDirection.LONG, ZERO, baseAssetAmount, true ); await clearingHouse.placeAndFillOrder(orderParams); const user: any = await clearingHouse.program.account.user.fetch( userAccountPublicKey ); const userPositionsAccount: any = await clearingHouse.program.account.userPositions.fetch(user.positions); assert.ok(userPositionsAccount.positions[0].quoteAssetAmount.eq(new BN(0))); assert.ok(userPositionsAccount.positions[0].baseAssetAmount.eq(new BN(0))); assert.ok(user.collateral.eq(new BN(9850755))); assert(user.totalFeePaid.eq(new BN(149242))); const marketsAccount = clearingHouse.getMarketsAccount(); const market: any = marketsAccount.markets[0]; assert.ok(market.baseAssetAmount.eq(new BN(0))); assert.ok(market.amm.totalFee.eq(new BN(149242))); assert.ok(market.amm.totalFeeMinusDistributions.eq(new BN(149242))); const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount(); assert.ok(tradeHistoryAccount.head.toNumber() === 4); assert.ok( tradeHistoryAccount.tradeRecords[3].user.equals(userAccountPublicKey) ); assert.ok(tradeHistoryAccount.tradeRecords[3].recordId.eq(new BN(4))); assert.ok( JSON.stringify(tradeHistoryAccount.tradeRecords[3].direction) === JSON.stringify(PositionDirection.LONG) ); assert.ok( tradeHistoryAccount.tradeRecords[3].baseAssetAmount.eq( new BN(248725251837442) ) ); assert.ok(tradeHistoryAccount.tradeRecords[2].liquidation == false); assert.ok( tradeHistoryAccount.tradeRecords[3].quoteAssetAmount.eq(new BN(24871288)) ); assert.ok(tradeHistoryAccount.tradeRecords[3].marketIndex.eq(new BN(0))); }); });
the_stack
import * as core from '@actions/core'; import * as io from '@actions/io'; import * as tc from '@actions/tool-cache'; import fs from 'fs'; import cp from 'child_process'; import osm from 'os'; import path from 'path'; import * as main from '../src/main'; import * as im from '../src/installer'; let goJsonData = require('./data/golang-dl.json'); let matchers = require('../matchers.json'); let goTestManifest = require('./data/versions-manifest.json'); let matcherPattern = matchers.problemMatcher[0].pattern[0]; let matcherRegExp = new RegExp(matcherPattern.regexp); describe('setup-go', () => { let inputs = {} as any; let os = {} as any; let inSpy: jest.SpyInstance; let findSpy: jest.SpyInstance; let cnSpy: jest.SpyInstance; let logSpy: jest.SpyInstance; let getSpy: jest.SpyInstance; let platSpy: jest.SpyInstance; let archSpy: jest.SpyInstance; let dlSpy: jest.SpyInstance; let exSpy: jest.SpyInstance; let cacheSpy: jest.SpyInstance; let dbgSpy: jest.SpyInstance; let whichSpy: jest.SpyInstance; let existsSpy: jest.SpyInstance; let mkdirpSpy: jest.SpyInstance; let execSpy: jest.SpyInstance; let getManifestSpy: jest.SpyInstance; beforeAll(() => { process.env['GITHUB_PATH'] = ''; // Stub out ENV file functionality so we can verify it writes to standard out console.log('::stop-commands::stoptoken'); // Disable executing of runner commands when running tests in actions }); beforeEach(() => { // @actions/core inputs = {}; inSpy = jest.spyOn(core, 'getInput'); inSpy.mockImplementation(name => inputs[name]); // node os = {}; platSpy = jest.spyOn(osm, 'platform'); platSpy.mockImplementation(() => os['platform']); archSpy = jest.spyOn(osm, 'arch'); archSpy.mockImplementation(() => os['arch']); execSpy = jest.spyOn(cp, 'execSync'); // @actions/tool-cache findSpy = jest.spyOn(tc, 'find'); dlSpy = jest.spyOn(tc, 'downloadTool'); exSpy = jest.spyOn(tc, 'extractTar'); cacheSpy = jest.spyOn(tc, 'cacheDir'); getSpy = jest.spyOn(im, 'getVersionsDist'); getManifestSpy = jest.spyOn(tc, 'getManifestFromRepo'); // io whichSpy = jest.spyOn(io, 'which'); existsSpy = jest.spyOn(fs, 'existsSync'); mkdirpSpy = jest.spyOn(io, 'mkdirP'); // gets getManifestSpy.mockImplementation(() => <tc.IToolRelease[]>goTestManifest); // writes cnSpy = jest.spyOn(process.stdout, 'write'); logSpy = jest.spyOn(core, 'info'); dbgSpy = jest.spyOn(core, 'debug'); getSpy.mockImplementation(() => <im.IGoVersion[] | null>goJsonData); cnSpy.mockImplementation(line => { // uncomment to debug // process.stderr.write('write:' + line + '\n'); }); logSpy.mockImplementation(line => { // uncomment to debug // process.stderr.write('log:' + line + '\n'); }); dbgSpy.mockImplementation(msg => { // uncomment to see debug output // process.stderr.write(msg + '\n'); }); }); afterEach(() => { jest.resetAllMocks(); jest.clearAllMocks(); //jest.restoreAllMocks(); }); afterAll(async () => { console.log('::stoptoken::'); // Re-enable executing of runner commands when running tests in actions }, 100000); it('can find 1.9.7 from manifest on osx', async () => { os.platform = 'darwin'; os.arch = 'x64'; let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); expect(match).toBeDefined(); expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.type).toBe('manifest'); expect(match!.downloadUrl).toBe( 'https://github.com/actions/go-versions/releases/download/1.9.7/go-1.9.7-darwin-x64.tar.gz' ); }); it('can find 1.9 from manifest on linux', async () => { os.platform = 'linux'; os.arch = 'x64'; let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); expect(match).toBeDefined(); expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.type).toBe('manifest'); expect(match!.downloadUrl).toBe( 'https://github.com/actions/go-versions/releases/download/1.9.7/go-1.9.7-linux-x64.tar.gz' ); }); it('can find 1.9 from manifest on windows', async () => { os.platform = 'win32'; os.arch = 'x64'; let match = await im.getInfoFromManifest('1.9.7', true, 'mocktoken'); expect(match).toBeDefined(); expect(match!.resolvedVersion).toBe('1.9.7'); expect(match!.type).toBe('manifest'); expect(match!.downloadUrl).toBe( 'https://github.com/actions/go-versions/releases/download/1.9.7/go-1.9.7-win32-x64.zip' ); }); it('finds stable match for exact dot zero version', async () => { os.platform = 'darwin'; os.arch = 'x64'; // spec: 1.13.0 => 1.13 let match: im.IGoVersion | undefined = await im.findMatch('1.13.0', true); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13'); let fileName = match ? match.files[0].filename : ''; expect(fileName).toBe('go1.13.darwin-amd64.tar.gz'); }); it('finds latest patch version for minor version spec', async () => { os.platform = 'linux'; os.arch = 'x64'; // spec: 1.13 => 1.13.7 (latest) let match: im.IGoVersion | undefined = await im.findMatch('1.13', true); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); let fileName = match ? match.files[0].filename : ''; expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz'); }); it('finds latest patch version for caret version spec', async () => { os.platform = 'linux'; os.arch = 'x64'; // spec: ^1.13.6 => 1.13.7 let match: im.IGoVersion | undefined = await im.findMatch('^1.13.6', true); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); let fileName = match ? match.files[0].filename : ''; expect(fileName).toBe('go1.13.7.linux-amd64.tar.gz'); }); it('finds latest version for major version spec', async () => { os.platform = 'win32'; os.arch = 'x32'; // spec: 1 => 1.13.7 (latest) let match: im.IGoVersion | undefined = await im.findMatch('1', true); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.13.7'); let fileName = match ? match.files[0].filename : ''; expect(fileName).toBe('go1.13.7.windows-386.zip'); }); it('finds unstable pre-release version', async () => { os.platform = 'linux'; os.arch = 'x64'; // spec: 1.14, stable=false => go1.14rc1 let match: im.IGoVersion | undefined = await im.findMatch( '1.14.0-rc1', false ); expect(match).toBeDefined(); let version: string = match ? match.version : ''; expect(version).toBe('go1.14rc1'); let fileName = match ? match.files[0].filename : ''; expect(fileName).toBe('go1.14rc1.linux-amd64.tar.gz'); }); it('evaluates to stable with input as true', async () => { inputs['go-version'] = '1.13.0'; inputs.stable = 'true'; let toolPath = path.normalize('/cache/go/1.13.0/x64'); findSpy.mockImplementation(() => toolPath); await main.run(); expect(logSpy).toHaveBeenCalledWith(`Setup go stable version spec 1.13.0`); }); it('evaluates to stable with no input', async () => { inputs['go-version'] = '1.13.0'; inSpy.mockImplementation(name => inputs[name]); let toolPath = path.normalize('/cache/go/1.13.0/x64'); findSpy.mockImplementation(() => toolPath); await main.run(); expect(logSpy).toHaveBeenCalledWith(`Setup go stable version spec 1.13.0`); }); it('finds a version of go already in the cache', async () => { inputs['go-version'] = '1.13.0'; let toolPath = path.normalize('/cache/go/1.13.0/x64'); findSpy.mockImplementation(() => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(logSpy).toHaveBeenCalledWith(`Found in cache @ ${toolPath}`); }); it('finds a version in the cache and adds it to the path', async () => { inputs['go-version'] = '1.13.0'; let toolPath = path.normalize('/cache/go/1.13.0/x64'); findSpy.mockImplementation(() => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); }); it('handles unhandled error and reports error', async () => { let errMsg = 'unhandled error message'; inputs['go-version'] = '1.13.0'; findSpy.mockImplementation(() => { throw new Error(errMsg); }); await main.run(); expect(cnSpy).toHaveBeenCalledWith('::error::' + errMsg + osm.EOL); }); it('downloads a version not in the cache', async () => { os.platform = 'linux'; os.arch = 'x64'; inputs['go-version'] = '1.13.1'; findSpy.mockImplementation(() => ''); dlSpy.mockImplementation(() => '/some/temp/path'); let toolPath = path.normalize('/cache/go/1.13.0/x64'); exSpy.mockImplementation(() => '/some/other/temp/path'); cacheSpy.mockImplementation(() => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(dlSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled(); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); }); it('does not find a version that does not exist', async () => { os.platform = 'linux'; os.arch = 'x64'; inputs['go-version'] = '9.99.9'; findSpy.mockImplementation(() => ''); await main.run(); expect(cnSpy).toHaveBeenCalledWith( `::error::Unable to find Go version '9.99.9' for platform linux and architecture x64.${osm.EOL}` ); }); it('downloads a version from a manifest match', async () => { os.platform = 'linux'; os.arch = 'x64'; // a version which is in the manifest let versionSpec = '1.12.16'; inputs['go-version'] = versionSpec; inputs['token'] = 'faketoken'; let expectedUrl = 'https://github.com/actions/go-versions/releases/download/1.12.16-20200616.20/go-1.12.16-linux-x64.tar.gz'; // ... but not in the local cache findSpy.mockImplementation(() => ''); dlSpy.mockImplementation(async () => '/some/temp/path'); let toolPath = path.normalize('/cache/go/1.12.16/x64'); exSpy.mockImplementation(async () => '/some/other/temp/path'); cacheSpy.mockImplementation(async () => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(dlSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled(); expect(logSpy).not.toHaveBeenCalledWith( 'Not found in manifest. Falling back to download directly from Go' ); expect(logSpy).toHaveBeenCalledWith( `Acquiring 1.12.16 from ${expectedUrl}` ); expect(logSpy).toHaveBeenCalledWith(`Added go to the path`); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); }); it('downloads a major and minor from a manifest match', async () => { os.platform = 'linux'; os.arch = 'x64'; // a version which is in the manifest let versionSpec = '1.12'; inputs['go-version'] = versionSpec; inputs['token'] = 'faketoken'; let expectedUrl = 'https://github.com/actions/go-versions/releases/download/1.12.17-20200616.21/go-1.12.17-linux-x64.tar.gz'; // ... but not in the local cache findSpy.mockImplementation(() => ''); dlSpy.mockImplementation(async () => '/some/temp/path'); let toolPath = path.normalize('/cache/go/1.12.17/x64'); exSpy.mockImplementation(async () => '/some/other/temp/path'); cacheSpy.mockImplementation(async () => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(dlSpy).toHaveBeenCalled(); expect(exSpy).toHaveBeenCalled(); expect(logSpy).not.toHaveBeenCalledWith( 'Not found in manifest. Falling back to download directly from Go' ); expect(logSpy).toHaveBeenCalledWith( `Acquiring 1.12.17 from ${expectedUrl}` ); expect(logSpy).toHaveBeenCalledWith(`Added go to the path`); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); }); it('falls back to a version from node dist', async () => { os.platform = 'linux'; os.arch = 'x64'; // a version which is not in the manifest but is in node dist let versionSpec = '1.12.14'; inputs['go-version'] = versionSpec; inputs['token'] = 'faketoken'; let expectedUrl = 'https://github.com/actions/go-versions/releases/download/1.12.14-20200616.18/go-1.12.14-linux-x64.tar.gz'; // ... but not in the local cache findSpy.mockImplementation(() => ''); dlSpy.mockImplementation(async () => '/some/temp/path'); let toolPath = path.normalize('/cache/go/1.12.14/x64'); exSpy.mockImplementation(async () => '/some/other/temp/path'); cacheSpy.mockImplementation(async () => toolPath); await main.run(); let expPath = path.join(toolPath, 'bin'); expect(logSpy).toHaveBeenCalledWith('Setup go stable version spec 1.12.14'); expect(findSpy).toHaveBeenCalled(); expect(logSpy).toHaveBeenCalledWith('Attempting to download 1.12.14...'); expect(dlSpy).toHaveBeenCalled(); expect(logSpy).toHaveBeenCalledWith('matching 1.12.14...'); expect(exSpy).toHaveBeenCalled(); expect(logSpy).toHaveBeenCalledWith( 'Not found in manifest. Falling back to download directly from Go' ); expect(logSpy).toHaveBeenCalledWith(`Install from dist`); expect(logSpy).toHaveBeenCalledWith(`Added go to the path`); expect(cnSpy).toHaveBeenCalledWith(`::add-path::${expPath}${osm.EOL}`); }); it('reports a failed download', async () => { let errMsg = 'unhandled download message'; os.platform = 'linux'; os.arch = 'x64'; inputs['go-version'] = '1.13.1'; findSpy.mockImplementation(() => ''); dlSpy.mockImplementation(() => { throw new Error(errMsg); }); await main.run(); expect(cnSpy).toHaveBeenCalledWith( `::error::Failed to download version 1.13.1: Error: ${errMsg}${osm.EOL}` ); }); it('does not add BIN if go is not in path', async () => { whichSpy.mockImplementation(async () => { return ''; }); let added = await main.addBinToPath(); expect(added).toBeFalsy(); }); it('adds bin if dir not exists', async () => { whichSpy.mockImplementation(async () => { return '/usr/local/go/bin/go'; }); execSpy.mockImplementation(() => { return '/Users/testuser/go'; }); mkdirpSpy.mockImplementation(async () => {}); existsSpy.mockImplementation(path => { return false; }); let added = await main.addBinToPath(); expect(added).toBeTruthy; }); interface Annotation { file: string; line: number; column: number; message: string; } // // problem matcher regex pattern tests function testMatch(line: string): Annotation { let annotation = <Annotation>{}; let match = matcherRegExp.exec(line); if (match) { annotation.line = parseInt(match[matcherPattern.line], 10); annotation.column = parseInt(match[matcherPattern.column], 10); annotation.file = match[matcherPattern.file].trim(); annotation.message = match[matcherPattern.message].trim(); } return annotation; } it('matches on relative unix path', async () => { let line = './main.go:13:2: undefined: fmt.Printl'; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(13); expect(annotation.column).toBe(2); expect(annotation.file).toBe('./main.go'); expect(annotation.message).toBe('undefined: fmt.Printl'); }); it('matches on unix path up the tree', async () => { let line = '../main.go:13:2: undefined: fmt.Printl'; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(13); expect(annotation.column).toBe(2); expect(annotation.file).toBe('../main.go'); expect(annotation.message).toBe('undefined: fmt.Printl'); }); it('matches on rooted unix path', async () => { let line = '/assert.go:4:1: missing return at end of function'; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(4); expect(annotation.column).toBe(1); expect(annotation.file).toBe('/assert.go'); expect(annotation.message).toBe('missing return at end of function'); }); it('matches on unix path with spaces', async () => { let line = ' ./assert.go:5:2: missing return at end of function '; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(5); expect(annotation.column).toBe(2); expect(annotation.file).toBe('./assert.go'); expect(annotation.message).toBe('missing return at end of function'); }); it('matches on unix path with tabs', async () => { let line = '\t./assert.go:5:2: missing return at end of function '; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(5); expect(annotation.column).toBe(2); expect(annotation.file).toBe('./assert.go'); expect(annotation.message).toBe('missing return at end of function'); }); it('matches on relative windows path', async () => { let line = '.\\main.go:13:2: undefined: fmt.Printl'; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(13); expect(annotation.column).toBe(2); expect(annotation.file).toBe('.\\main.go'); expect(annotation.message).toBe('undefined: fmt.Printl'); }); it('matches on windows path up the tree', async () => { let line = '..\\main.go:13:2: undefined: fmt.Printl'; let annotation = testMatch(line); expect(annotation).toBeDefined(); expect(annotation.line).toBe(13); expect(annotation.column).toBe(2); expect(annotation.file).toBe('..\\main.go'); expect(annotation.message).toBe('undefined: fmt.Printl'); }); // 1.13.1 => 1.13.1 // 1.13 => 1.13.0 // 1.10beta1 => 1.10.0-beta1, 1.10rc1 => 1.10.0-rc1 // 1.8.5beta1 => 1.8.5-beta1, 1.8.5rc1 => 1.8.5-rc1 it('converts prerelease versions', async () => { expect(im.makeSemver('1.10beta1')).toBe('1.10.0-beta1'); expect(im.makeSemver('1.10rc1')).toBe('1.10.0-rc1'); }); it('converts dot zero versions', async () => { expect(im.makeSemver('1.13')).toBe('1.13.0'); }); it('does not convert exact versions', async () => { expect(im.makeSemver('1.13.1')).toBe('1.13.1'); }); });
the_stack
import * as nacl from './nacl/naclWrappers'; import * as address from './encoding/address'; import * as encoding from './encoding/encoding'; import * as logic from './logic/logic'; import * as multisig from './multisig'; import * as utils from './utils/utils'; import * as txnBuilder from './transaction'; import { EncodedLogicSig, EncodedLogicSigAccount, EncodedMultisig, EncodedSignedTransaction, } from './types/transactions/encoded'; import { MultisigMetadata } from './types/multisig'; interface LogicSigStorageStructure { logic: Uint8Array; args: Uint8Array[]; sig?: Uint8Array; msig?: EncodedMultisig; } /** LogicSig implementation */ export class LogicSig implements LogicSigStorageStructure { tag = Buffer.from('Program'); logic: Uint8Array; args: Uint8Array[]; sig?: Uint8Array; msig?: EncodedMultisig; constructor( program: Uint8Array, programArgs?: Array<Uint8Array | Buffer> | null ) { if ( programArgs && (!Array.isArray(programArgs) || !programArgs.every( (arg) => arg.constructor === Uint8Array || Buffer.isBuffer(arg) )) ) { throw new TypeError('Invalid arguments'); } let args: Uint8Array[] | undefined; if (programArgs != null) args = programArgs.map((arg) => new Uint8Array(arg)); if (!logic.checkProgram(program, args)) { throw new Error('Invalid program'); } this.logic = program; this.args = args; this.sig = undefined; this.msig = undefined; } // eslint-disable-next-line camelcase get_obj_for_encoding() { const obj: EncodedLogicSig = { l: this.logic, }; if (this.args) { obj.arg = this.args; } if (this.sig) { obj.sig = this.sig; } else if (this.msig) { obj.msig = this.msig; } return obj; } // eslint-disable-next-line camelcase static from_obj_for_encoding(encoded: EncodedLogicSig) { const lsig = new LogicSig(encoded.l, encoded.arg); lsig.sig = encoded.sig; lsig.msig = encoded.msig; return lsig; } /** * Performs signature verification * @param publicKey - Verification key (derived from sender address or escrow address) */ verify(publicKey: Uint8Array) { if (this.sig && this.msig) { return false; } try { logic.checkProgram(this.logic, this.args); } catch (e) { return false; } const toBeSigned = utils.concatArrays(this.tag, this.logic); if (!this.sig && !this.msig) { const hash = nacl.genericHash(toBeSigned); return utils.arrayEqual(hash, publicKey); } if (this.sig) { return nacl.verify(toBeSigned, this.sig, publicKey); } return multisig.verifyMultisig(toBeSigned, this.msig, publicKey); } /** * Compute hash of the logic sig program (that is the same as escrow account address) as string address * @returns String representation of the address */ address() { const toBeSigned = utils.concatArrays(this.tag, this.logic); const hash = nacl.genericHash(toBeSigned); return address.encodeAddress(new Uint8Array(hash)); } /** * Creates signature (if no msig provided) or multi signature otherwise * @param secretKey - Secret key to sign with * @param msig - Multisig account as \{version, threshold, addrs\} */ sign(secretKey: Uint8Array, msig?: MultisigMetadata) { if (msig == null) { this.sig = this.signProgram(secretKey); } else { const subsigs = msig.addrs.map((addr) => ({ pk: address.decodeAddress(addr).publicKey, })); this.msig = { v: msig.version, thr: msig.threshold, subsig: subsigs, }; const [sig, index] = this.singleSignMultisig(secretKey, this.msig); this.msig.subsig[index].s = sig; } } /** * Appends a signature to multi signature * @param secretKey - Secret key to sign with */ appendToMultisig(secretKey: Uint8Array) { if (this.msig === undefined) { throw new Error('no multisig present'); } const [sig, index] = this.singleSignMultisig(secretKey, this.msig); this.msig.subsig[index].s = sig; } signProgram(secretKey: Uint8Array) { const toBeSigned = utils.concatArrays(this.tag, this.logic); const sig = nacl.sign(toBeSigned, secretKey); return sig; } singleSignMultisig( secretKey: Uint8Array, msig: EncodedMultisig ): [sig: Uint8Array, index: number] { let index = -1; const myPk = nacl.keyPairFromSecretKey(secretKey).publicKey; for (let i = 0; i < msig.subsig.length; i++) { const { pk } = msig.subsig[i]; if (utils.arrayEqual(pk, myPk)) { index = i; break; } } if (index === -1) { throw new Error('invalid secret key'); } const sig = this.signProgram(secretKey); return [sig, index]; } toByte() { return encoding.encode(this.get_obj_for_encoding()); } static fromByte(encoded: ArrayLike<any>) { const decodedObj = encoding.decode(encoded) as EncodedLogicSig; return LogicSig.from_obj_for_encoding(decodedObj); } } /** * Represents an account that can sign with a LogicSig program. */ export class LogicSigAccount { lsig: LogicSig; sigkey?: Uint8Array; /** * Create a new LogicSigAccount. By default this will create an escrow * LogicSig account. Call `sign` or `signMultisig` on the newly created * LogicSigAccount to make it a delegated account. * * @param program - The compiled TEAL program which contains the logic for * this LogicSig. * @param args - An optional array of arguments for the program. */ constructor(program: Uint8Array, args?: Array<Uint8Array | Buffer> | null) { this.lsig = new LogicSig(program, args); this.sigkey = undefined; } // eslint-disable-next-line camelcase get_obj_for_encoding() { const obj: EncodedLogicSigAccount = { lsig: this.lsig.get_obj_for_encoding(), }; if (this.sigkey) { obj.sigkey = this.sigkey; } return obj; } // eslint-disable-next-line camelcase static from_obj_for_encoding(encoded: EncodedLogicSigAccount) { const lsigAccount = new LogicSigAccount(encoded.lsig.l, encoded.lsig.arg); lsigAccount.lsig = LogicSig.from_obj_for_encoding(encoded.lsig); lsigAccount.sigkey = encoded.sigkey; return lsigAccount; } /** * Encode this object into msgpack. */ toByte() { return encoding.encode(this.get_obj_for_encoding()); } /** * Decode a msgpack object into a LogicSigAccount. * @param encoded - The encoded LogicSigAccount. */ static fromByte(encoded: ArrayLike<any>) { const decodedObj = encoding.decode(encoded) as EncodedLogicSigAccount; return LogicSigAccount.from_obj_for_encoding(decodedObj); } /** * Check if this LogicSigAccount has been delegated to another account with a * signature. * * Note this function only checks for the presence of a delegation signature. * To verify the delegation signature, use `verify`. */ isDelegated() { return !!(this.lsig.sig || this.lsig.msig); } /** * Verifies this LogicSig's program and signatures. * @returns true if and only if the LogicSig program and signatures are valid. */ verify() { const addr = this.address(); return this.lsig.verify(address.decodeAddress(addr).publicKey); } /** * Get the address of this LogicSigAccount. * * If the LogicSig is delegated to another account, this will return the * address of that account. * * If the LogicSig is not delegated to another account, this will return an * escrow address that is the hash of the LogicSig's program code. */ address() { if (this.lsig.sig && this.lsig.msig) { throw new Error( 'LogicSig has too many signatures. At most one of sig or msig may be present' ); } if (this.lsig.sig) { if (!this.sigkey) { throw new Error('Signing key for delegated account is missing'); } return address.encodeAddress(this.sigkey); } if (this.lsig.msig) { const msigMetadata = { version: this.lsig.msig.v, threshold: this.lsig.msig.thr, pks: this.lsig.msig.subsig.map((subsig) => subsig.pk), }; return address.encodeAddress(address.fromMultisigPreImg(msigMetadata)); } return this.lsig.address(); } /** * Turns this LogicSigAccount into a delegated LogicSig. This type of LogicSig * has the authority to sign transactions on behalf of another account, called * the delegating account. Use this function if the delegating account is a * multisig account. * * @param msig - The multisig delegating account * @param secretKey - The secret key of one of the members of the delegating * multisig account. Use `appendToMultisig` to add additional signatures * from other members. */ signMultisig(msig: MultisigMetadata, secretKey: Uint8Array) { this.lsig.sign(secretKey, msig); } /** * Adds an additional signature from a member of the delegating multisig * account. * * @param secretKey - The secret key of one of the members of the delegating * multisig account. */ appendToMultisig(secretKey: Uint8Array) { this.lsig.appendToMultisig(secretKey); } /** * Turns this LogicSigAccount into a delegated LogicSig. This type of LogicSig * has the authority to sign transactions on behalf of another account, called * the delegating account. If the delegating account is a multisig account, * use `signMultisig` instead. * * @param secretKey - The secret key of the delegating account. */ sign(secretKey: Uint8Array) { this.lsig.sign(secretKey); this.sigkey = nacl.keyPairFromSecretKey(secretKey).publicKey; } } /** * makeLogicSig creates LogicSig object from program and arguments * * @deprecated Use new LogicSigAccount(...) instead * * @param program - Program to make LogicSig from * @param args - Arguments as array of Uint8Array * @returns LogicSig object */ export function makeLogicSig(program: Uint8Array, args?: Uint8Array[]) { return new LogicSig(program, args); } function signLogicSigTransactionWithAddress( txn: txnBuilder.Transaction, lsig: LogicSig, lsigAddress: Uint8Array ) { if (!lsig.verify(lsigAddress)) { throw new Error( 'Logic signature verification failed. Ensure the program and signature are valid.' ); } const signedTxn: EncodedSignedTransaction = { lsig: lsig.get_obj_for_encoding(), txn: txn.get_obj_for_encoding(), }; if (!nacl.bytesEqual(lsigAddress, txn.from.publicKey)) { signedTxn.sgnr = Buffer.from(lsigAddress); } return { txID: txn.txID().toString(), blob: encoding.encode(signedTxn), }; } /** * signLogicSigTransactionObject takes a transaction and a LogicSig object and * returns a signed transaction. * * @param txn - The transaction to sign. * @param lsigObject - The LogicSig object that will sign the transaction. * * @returns Object containing txID and blob representing signed transaction. */ export function signLogicSigTransactionObject( txn: txnBuilder.Transaction, lsigObject: LogicSig | LogicSigAccount ) { let lsig: LogicSig; let lsigAddress: Uint8Array; if (lsigObject instanceof LogicSigAccount) { lsig = lsigObject.lsig; lsigAddress = address.decodeAddress(lsigObject.address()).publicKey; } else { lsig = lsigObject; if (lsig.sig) { // For a LogicSig with a non-multisig delegating account, we cannot derive // the address of that account from only its signature, so assume the // delegating account is the sender. If that's not the case, the signing // will fail. lsigAddress = txn.from.publicKey; } else if (lsig.msig) { const msigMetadata = { version: lsig.msig.v, threshold: lsig.msig.thr, pks: lsig.msig.subsig.map((subsig) => subsig.pk), }; lsigAddress = address.fromMultisigPreImg(msigMetadata); } else { lsigAddress = address.decodeAddress(lsig.address()).publicKey; } } return signLogicSigTransactionWithAddress(txn, lsig, lsigAddress); } /** * signLogicSigTransaction takes a transaction and a LogicSig object and returns * a signed transaction. * * @param txn - The transaction to sign. * @param lsigObject - The LogicSig object that will sign the transaction. * * @returns Object containing txID and blob representing signed transaction. * @throws error on failure */ export function signLogicSigTransaction( txn: txnBuilder.TransactionLike, lsigObject: LogicSig | LogicSigAccount ) { const algoTxn = txnBuilder.instantiateTxnIfNeeded(txn); return signLogicSigTransactionObject(algoTxn, lsigObject); } /** * logicSigFromByte accepts encoded logic sig bytes and attempts to call logicsig.fromByte on it, * returning the result */ export function logicSigFromByte(encoded: Uint8Array) { return LogicSig.fromByte(encoded); } const SIGN_PROGRAM_DATA_PREFIX = Buffer.from('ProgData'); /** * tealSign creates a signature compatible with ed25519verify opcode from contract address * @param sk - uint8array with secret key * @param data - buffer with data to sign * @param contractAddress - string representation of teal contract address (program hash) */ export function tealSign( sk: Uint8Array, data: Uint8Array | Buffer, contractAddress: string ) { const parts = utils.concatArrays( address.decodeAddress(contractAddress).publicKey, data ); const toBeSigned = Buffer.from( utils.concatArrays(SIGN_PROGRAM_DATA_PREFIX, parts) ); return nacl.sign(toBeSigned, sk); } /** * tealSignFromProgram creates a signature compatible with ed25519verify opcode from raw program bytes * @param sk - uint8array with secret key * @param data - buffer with data to sign * @param program - buffer with teal program */ export function tealSignFromProgram( sk: Uint8Array, data: Uint8Array | Buffer, program: Uint8Array ) { const lsig = new LogicSig(program); const contractAddress = lsig.address(); return tealSign(sk, data, contractAddress); }
the_stack
import type { Maybe, MessageOrCCLogEntry, ValueID } from "@zwave-js/core"; import { CommandClasses, enumValuesToMetadataStates, parseBitMask, validatePayload, ValueMetadata, ZWaveError, ZWaveErrorCodes, } from "@zwave-js/core"; import { getEnumMemberName, pick } from "@zwave-js/shared"; import type { Driver } from "../driver/Driver"; import { MessagePriority } from "../message/Constants"; import { CCAPI, PollValueImplementation, POLL_VALUE, SetValueImplementation, SET_VALUE, throwMissingPropertyKey, throwUnsupportedProperty, throwUnsupportedPropertyKey, throwWrongValueType, } from "./API"; import { API, CCCommand, CCCommandOptions, ccValue, ccValueMetadata, CommandClass, commandClass, CommandClassDeserializationOptions, expectedCCResponse, gotDeserializationOptions, implementedVersion, } from "./CommandClass"; // @publicAPI export enum SubsystemType { Audible = 0x01, Visual = 0x02, } // @publicAPI export enum SubsystemState { Off = 0x00, On = 0xff, } function getSignalingStateValueId( endpoint: number | undefined, subsystemType: SubsystemType, ): ValueID { return { commandClass: CommandClasses["Barrier Operator"], endpoint, property: "signalingState", propertyKey: subsystemType, }; } function getSignalingStateMetadata( subsystemType: SubsystemType, ): ValueMetadata { return { ...ValueMetadata.UInt8, label: `Signaling State (${getEnumMemberName( SubsystemType, subsystemType, )})`, states: enumValuesToMetadataStates(SubsystemState), }; } function getSupportedSubsystemTypesValueId(endpoint?: number): ValueID { return { commandClass: CommandClasses["Barrier Operator"], endpoint, property: "supportedSubsystemTypes", }; } function getTargetStateValueId(endpoint: number | undefined): ValueID { return { commandClass: CommandClasses["Barrier Operator"], endpoint, property: "targetState", }; } // All the supported commands export enum BarrierOperatorCommand { Set = 0x01, Get = 0x02, Report = 0x03, SignalingCapabilitiesGet = 0x04, SignalingCapabilitiesReport = 0x05, EventSignalingSet = 0x06, EventSignalingGet = 0x07, EventSignalingReport = 0x08, } /** * @publicAPI */ export enum BarrierState { Closed = 0x00, Closing = 0xfc, Stopped = 0xfd, Opening = 0xfe, Open = 0xff, } @API(CommandClasses["Barrier Operator"]) export class BarrierOperatorCCAPI extends CCAPI { public supportsCommand(cmd: BarrierOperatorCommand): Maybe<boolean> { switch (cmd) { case BarrierOperatorCommand.Get: case BarrierOperatorCommand.Set: case BarrierOperatorCommand.SignalingCapabilitiesGet: case BarrierOperatorCommand.EventSignalingGet: case BarrierOperatorCommand.EventSignalingSet: return true; // This is mandatory } return super.supportsCommand(cmd); } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types public async get() { this.assertSupportsCommand( BarrierOperatorCommand, BarrierOperatorCommand.Get, ); const cc = new BarrierOperatorCCGet(this.driver, { nodeId: this.endpoint.nodeId, endpoint: this.endpoint.index, }); const response = await this.driver.sendCommand<BarrierOperatorCCReport>( cc, this.commandOptions, ); if (response) { return pick(response, ["currentState", "position"]); } } public async set( targetState: BarrierState.Open | BarrierState.Closed, ): Promise<void> { this.assertSupportsCommand( BarrierOperatorCommand, BarrierOperatorCommand.Set, ); const cc = new BarrierOperatorCCSet(this.driver, { nodeId: this.endpoint.nodeId, endpoint: this.endpoint.index, targetState, }); await this.driver.sendCommand(cc, this.commandOptions); } public async getSignalingCapabilities(): Promise< readonly SubsystemType[] | undefined > { this.assertSupportsCommand( BarrierOperatorCommand, BarrierOperatorCommand.SignalingCapabilitiesGet, ); const cc = new BarrierOperatorCCSignalingCapabilitiesGet(this.driver, { nodeId: this.endpoint.nodeId, endpoint: this.endpoint.index, }); const response = await this.driver.sendCommand<BarrierOperatorCCSignalingCapabilitiesReport>( cc, this.commandOptions, ); return response?.supportedSubsystemTypes; } public async getEventSignaling( subsystemType: SubsystemType, ): Promise<SubsystemState | undefined> { this.assertSupportsCommand( BarrierOperatorCommand, BarrierOperatorCommand.EventSignalingGet, ); const cc = new BarrierOperatorCCEventSignalingGet(this.driver, { nodeId: this.endpoint.nodeId, endpoint: this.endpoint.index, subsystemType, }); const response = await this.driver.sendCommand<BarrierOperatorCCEventSignalingReport>( cc, this.commandOptions, ); return response?.subsystemState; } public async setEventSignaling( subsystemType: SubsystemType, subsystemState: SubsystemState, ): Promise<void> { this.assertSupportsCommand( BarrierOperatorCommand, BarrierOperatorCommand.EventSignalingSet, ); const cc = new BarrierOperatorCCEventSignalingSet(this.driver, { nodeId: this.endpoint.nodeId, endpoint: this.endpoint.index, subsystemType, subsystemState, }); await this.driver.sendCommand(cc, this.commandOptions); } protected [SET_VALUE]: SetValueImplementation = async ( { property, propertyKey }, value, ): Promise<void> => { if (property === "targetState") { if (typeof value !== "number") { throwWrongValueType( this.ccId, property, "number", typeof value, ); } const targetValue = value === BarrierState.Closed ? BarrierState.Closed : BarrierState.Open; await this.set(targetValue); // Verify the change after a delay if (this.isSinglecast()) { this.schedulePoll({ property }); } } else if (property === "signalingState") { if (propertyKey == undefined) { throwMissingPropertyKey(this.ccId, property); } else if (typeof propertyKey !== "number") { throwUnsupportedPropertyKey(this.ccId, property, propertyKey); } if (typeof value !== "number") { throwWrongValueType( this.ccId, property, "number", typeof value, ); } await this.setEventSignaling(propertyKey, value); } else { throwUnsupportedProperty(this.ccId, property); } }; protected [POLL_VALUE]: PollValueImplementation = async ({ property, propertyKey, }): Promise<unknown> => { switch (property) { case "currentState": case "position": return (await this.get())?.[property]; case "signalingState": if (propertyKey == undefined) { throwMissingPropertyKey(this.ccId, property); } else if (typeof propertyKey !== "number") { throwUnsupportedPropertyKey( this.ccId, property, propertyKey, ); } return this.getEventSignaling(propertyKey); default: throwUnsupportedProperty(this.ccId, property); } }; } @commandClass(CommandClasses["Barrier Operator"]) @implementedVersion(1) export class BarrierOperatorCC extends CommandClass { declare ccCommand: BarrierOperatorCommand; public async interview(): Promise<void> { const node = this.getNode()!; const endpoint = this.getEndpoint()!; const api = endpoint.commandClasses["Barrier Operator"].withOptions({ priority: MessagePriority.NodeQuery, }); this.driver.controllerLog.logNode(node.id, { endpoint: this.endpointIndex, message: `Interviewing ${this.ccName}...`, direction: "none", }); // Create targetState value if it does not exist const targetStateValueID = getTargetStateValueId(this.endpointIndex); if (!node.valueDB.hasMetadata(targetStateValueID)) { node.valueDB.setMetadata(targetStateValueID, { ...ValueMetadata.UInt8, label: "Target Barrier State", states: enumValuesToMetadataStates(BarrierState, [ BarrierState.Open, BarrierState.Closed, ]), }); } this.driver.controllerLog.logNode(node.id, { message: "Querying signaling capabilities...", direction: "outbound", }); const resp = await api.getSignalingCapabilities(); if (resp) { this.driver.controllerLog.logNode(node.id, { message: `Received supported subsystem types: ${resp .map((t) => `\n· ${getEnumMemberName(SubsystemType, t)}`) .join("")}`, direction: "inbound", }); } await this.refreshValues(); // Remember that the interview is complete this.interviewComplete = true; } public async refreshValues(): Promise<void> { const node = this.getNode()!; const endpoint = this.getEndpoint()!; const api = endpoint.commandClasses["Barrier Operator"].withOptions({ priority: MessagePriority.NodeQuery, }); const supportedSubsystems = this.getValueDB().getValue<SubsystemType[]>( getSupportedSubsystemTypesValueId(this.endpointIndex), ) ?? []; for (const subsystemType of supportedSubsystems) { this.driver.controllerLog.logNode(node.id, { message: `Querying event signaling state for subsystem ${getEnumMemberName( SubsystemType, subsystemType, )}...`, direction: "outbound", }); const state = await api.getEventSignaling(subsystemType); if (state != undefined) { this.driver.controllerLog.logNode(node.id, { message: `Subsystem ${getEnumMemberName( SubsystemType, subsystemType, )} has state ${getEnumMemberName(SubsystemState, state)}`, direction: "inbound", }); } } this.driver.controllerLog.logNode(node.id, { message: "querying current barrier state...", direction: "outbound", }); await api.get(); } } interface BarrierOperatorCCSetOptions extends CCCommandOptions { targetState: BarrierState.Open | BarrierState.Closed; } @CCCommand(BarrierOperatorCommand.Set) export class BarrierOperatorCCSet extends BarrierOperatorCC { public constructor( driver: Driver, options: | CommandClassDeserializationOptions | BarrierOperatorCCSetOptions, ) { super(driver, options); if (gotDeserializationOptions(options)) { throw new ZWaveError( `${this.constructor.name}: deserialization not implemented`, ZWaveErrorCodes.Deserialization_NotImplemented, ); } else { this.targetState = options.targetState; } } public targetState: BarrierState.Open | BarrierState.Closed; public serialize(): Buffer { this.payload = Buffer.from([this.targetState]); return super.serialize(); } public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "target state": this.targetState }, }; } } @CCCommand(BarrierOperatorCommand.Report) export class BarrierOperatorCCReport extends BarrierOperatorCC { public constructor( driver: Driver, options: CommandClassDeserializationOptions, ) { super(driver, options); validatePayload(this.payload.length >= 1); // return values state and position value // if state is 0 - 99 or FF (100%) return the appropriate values. // if state is different just use the table and // return undefined position const payloadValue = this.payload[0]; this.currentState = payloadValue; this.position = undefined; if (payloadValue <= 99) { this.position = payloadValue; if (payloadValue > 0) { this.currentState = undefined; } } else if (payloadValue === 255) { this.position = 100; this.currentState = payloadValue; } this.persistValues(); } @ccValue() @ccValueMetadata({ ...ValueMetadata.ReadOnlyUInt8, label: "Current Barrier State", states: enumValuesToMetadataStates(BarrierState), }) public readonly currentState: BarrierState | undefined; @ccValue() @ccValueMetadata({ ...ValueMetadata.ReadOnlyUInt8, label: "Barrier Position", unit: "%", max: 100, }) public readonly position: number | undefined; public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "barrier position": this.position, "barrier state": this.currentState != undefined ? getEnumMemberName(BarrierState, this.currentState) : "unknown", }, }; } } @CCCommand(BarrierOperatorCommand.Get) @expectedCCResponse(BarrierOperatorCCReport) export class BarrierOperatorCCGet extends BarrierOperatorCC {} @CCCommand(BarrierOperatorCommand.SignalingCapabilitiesReport) export class BarrierOperatorCCSignalingCapabilitiesReport extends BarrierOperatorCC { public constructor( driver: Driver, options: CommandClassDeserializationOptions, ) { super(driver, options); this._supportedsubsystemTypes = parseBitMask( this.payload, SubsystemType.Audible, ); this.persistValues(); } private _supportedsubsystemTypes: SubsystemType[]; @ccValue({ internal: true }) public get supportedSubsystemTypes(): readonly SubsystemType[] { return this._supportedsubsystemTypes; } public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "supported types": this.supportedSubsystemTypes .map((t) => `\n· ${getEnumMemberName(SubsystemType, t)}`) .join(""), }, }; } } @CCCommand(BarrierOperatorCommand.SignalingCapabilitiesGet) @expectedCCResponse(BarrierOperatorCCSignalingCapabilitiesReport) export class BarrierOperatorCCSignalingCapabilitiesGet extends BarrierOperatorCC {} interface BarrierOperatorCCEventSignalingSetOptions extends CCCommandOptions { subsystemType: SubsystemType; subsystemState: SubsystemState; } @CCCommand(BarrierOperatorCommand.EventSignalingSet) export class BarrierOperatorCCEventSignalingSet extends BarrierOperatorCC { public constructor( driver: Driver, options: | CommandClassDeserializationOptions | BarrierOperatorCCEventSignalingSetOptions, ) { super(driver, options); if (gotDeserializationOptions(options)) { // TODO: Deserialize payload throw new ZWaveError( `${this.constructor.name}: deserialization not implemented`, ZWaveErrorCodes.Deserialization_NotImplemented, ); } else { this.subsystemType = options.subsystemType; this.subsystemState = options.subsystemState; } } public subsystemType: SubsystemType; public subsystemState: SubsystemState; public serialize(): Buffer { this.payload = Buffer.from([this.subsystemType, this.subsystemState]); return super.serialize(); } public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "subsystem type": getEnumMemberName( SubsystemType, this.subsystemType, ), "subsystem state": getEnumMemberName( SubsystemState, this.subsystemState, ), }, }; } } @CCCommand(BarrierOperatorCommand.EventSignalingReport) export class BarrierOperatorCCEventSignalingReport extends BarrierOperatorCC { public constructor( driver: Driver, options: CommandClassDeserializationOptions, ) { super(driver, options); validatePayload(this.payload.length >= 2); this.subsystemType = this.payload[0]; this.subsystemState = this.payload[1]; this.persistValues(); } public persistValues(): boolean { if (!super.persistValues()) return false; const valueId = getSignalingStateValueId( this.endpointIndex, this.subsystemType, ); const valueDB = this.getValueDB(); // Create metadata if it does not exist if (!valueDB.hasMetadata(valueId)) { valueDB.setMetadata( valueId, getSignalingStateMetadata(this.subsystemType), ); } valueDB.setValue(valueId, this.subsystemState); return true; } public readonly subsystemType: SubsystemType; public readonly subsystemState: SubsystemState; public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "subsystem type": getEnumMemberName( SubsystemType, this.subsystemType, ), "subsystem state": getEnumMemberName( SubsystemState, this.subsystemState, ), }, }; } } interface BarrierOperatorCCEventSignalingGetOptions extends CCCommandOptions { subsystemType: SubsystemType; } @CCCommand(BarrierOperatorCommand.EventSignalingGet) @expectedCCResponse(BarrierOperatorCCEventSignalingReport) export class BarrierOperatorCCEventSignalingGet extends BarrierOperatorCC { public constructor( driver: Driver, options: | CommandClassDeserializationOptions | BarrierOperatorCCEventSignalingGetOptions, ) { super(driver, options); if (gotDeserializationOptions(options)) { // TODO: Deserialize payload throw new ZWaveError( `${this.constructor.name}: deserialization not implemented`, ZWaveErrorCodes.Deserialization_NotImplemented, ); } else { this.subsystemType = options.subsystemType; } } public subsystemType: SubsystemType; public serialize(): Buffer { this.payload = Buffer.from([this.subsystemType]); return super.serialize(); } public toLogEntry(): MessageOrCCLogEntry { return { ...super.toLogEntry(), message: { "subsystem type": getEnumMemberName( SubsystemType, this.subsystemType, ), }, }; } }
the_stack
import * as React from 'react'; import { composeEventHandlers } from '@radix-ui/primitive'; import { createContextScope } from '@radix-ui/react-context'; import { useControllableState } from '@radix-ui/react-use-controllable-state'; import { useComposedRefs } from '@radix-ui/react-compose-refs'; import * as PopperPrimitive from '@radix-ui/react-popper'; import { createPopperScope } from '@radix-ui/react-popper'; import { Portal } from '@radix-ui/react-portal'; import { Presence } from '@radix-ui/react-presence'; import { Primitive } from '@radix-ui/react-primitive'; import { DismissableLayer } from '@radix-ui/react-dismissable-layer'; import type * as Radix from '@radix-ui/react-primitive'; import type { Scope } from '@radix-ui/react-context'; /* ------------------------------------------------------------------------------------------------- * HoverCard * -----------------------------------------------------------------------------------------------*/ const HOVERCARD_NAME = 'HoverCard'; type ScopedProps<P> = P & { __scopeHoverCard?: Scope }; const [createHoverCardContext, createHoverCardScope] = createContextScope(HOVERCARD_NAME, [ createPopperScope, ]); const usePopperScope = createPopperScope(); type HoverCardContextValue = { open: boolean; onOpenChange(open: boolean): void; onOpen(): void; onClose(): void; onDismiss(): void; }; const [HoverCardProvider, useHoverCardContext] = createHoverCardContext<HoverCardContextValue>(HOVERCARD_NAME); interface HoverCardProps { open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; openDelay?: number; closeDelay?: number; children?: React.ReactNode; } const HoverCard: React.FC<HoverCardProps> = (props: ScopedProps<HoverCardProps>) => { const { __scopeHoverCard, children, open: openProp, defaultOpen, onOpenChange, openDelay = 700, closeDelay = 300, } = props; const popperScope = usePopperScope(__scopeHoverCard); const openTimerRef = React.useRef(0); const closeTimerRef = React.useRef(0); const [open = false, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen, onChange: onOpenChange, }); const handleOpen = React.useCallback(() => { clearTimeout(closeTimerRef.current); openTimerRef.current = window.setTimeout(() => setOpen(true), openDelay); }, [openDelay, setOpen]); const handleClose = React.useCallback(() => { clearTimeout(openTimerRef.current); closeTimerRef.current = window.setTimeout(() => setOpen(false), closeDelay); }, [closeDelay, setOpen]); const handleDismiss = React.useCallback(() => setOpen(false), [setOpen]); // cleanup any queued state updates on unmount React.useEffect(() => { return () => { clearTimeout(openTimerRef.current); clearTimeout(closeTimerRef.current); }; }, []); return ( <HoverCardProvider scope={__scopeHoverCard} open={open} onOpenChange={setOpen} onOpen={handleOpen} onClose={handleClose} onDismiss={handleDismiss} > <PopperPrimitive.Root {...popperScope}>{children}</PopperPrimitive.Root> </HoverCardProvider> ); }; HoverCard.displayName = HOVERCARD_NAME; /* ------------------------------------------------------------------------------------------------- * HoverCardTrigger * -----------------------------------------------------------------------------------------------*/ const TRIGGER_NAME = 'HoverCardTrigger'; type HoverCardTriggerElement = React.ElementRef<typeof Primitive.a>; type PrimitiveLinkProps = Radix.ComponentPropsWithoutRef<typeof Primitive.a>; interface HoverCardTriggerProps extends PrimitiveLinkProps {} const HoverCardTrigger = React.forwardRef<HoverCardTriggerElement, HoverCardTriggerProps>( (props: ScopedProps<HoverCardTriggerProps>, forwardedRef) => { const { __scopeHoverCard, ...triggerProps } = props; const context = useHoverCardContext(TRIGGER_NAME, __scopeHoverCard); const popperScope = usePopperScope(__scopeHoverCard); return ( <PopperPrimitive.Anchor asChild {...popperScope}> <Primitive.a data-state={context.open ? 'open' : 'closed'} {...triggerProps} ref={forwardedRef} onPointerEnter={composeEventHandlers(props.onPointerEnter, excludeTouch(context.onOpen))} onPointerLeave={composeEventHandlers(props.onPointerLeave, excludeTouch(context.onClose))} onFocus={composeEventHandlers(props.onFocus, context.onOpen)} onBlur={composeEventHandlers(props.onBlur, context.onClose)} // prevent focus event on touch devices onTouchStart={composeEventHandlers(props.onTouchStart, (event) => event.preventDefault())} /> </PopperPrimitive.Anchor> ); } ); HoverCardTrigger.displayName = TRIGGER_NAME; /* ------------------------------------------------------------------------------------------------- * HoverCardContent * -----------------------------------------------------------------------------------------------*/ const CONTENT_NAME = 'HoverCardContent'; type HoverCardContentElement = HoverCardContentImplElement; interface HoverCardContentProps extends HoverCardContentImplProps { /** * Used to force mounting when more control is needed. Useful when * controlling animation with React animation libraries. */ forceMount?: true; } const HoverCardContent = React.forwardRef<HoverCardContentElement, HoverCardContentProps>( (props: ScopedProps<HoverCardContentProps>, forwardedRef) => { const { forceMount, ...contentProps } = props; const context = useHoverCardContext(CONTENT_NAME, props.__scopeHoverCard); return ( <Presence present={forceMount || context.open}> <HoverCardContentImpl data-state={context.open ? 'open' : 'closed'} {...contentProps} onPointerEnter={composeEventHandlers(props.onPointerEnter, excludeTouch(context.onOpen))} onPointerLeave={composeEventHandlers(props.onPointerLeave, excludeTouch(context.onClose))} ref={forwardedRef} /> </Presence> ); } ); HoverCardContent.displayName = CONTENT_NAME; /* ---------------------------------------------------------------------------------------------- */ type HoverCardContentImplElement = React.ElementRef<typeof PopperPrimitive.Content>; type DismissableLayerProps = Radix.ComponentPropsWithoutRef<typeof DismissableLayer>; type PopperContentProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Content>; interface HoverCardContentImplProps extends PopperContentProps { /** * Event handler called when the escape key is down. * Can be prevented. */ onEscapeKeyDown?: DismissableLayerProps['onEscapeKeyDown']; /** * Event handler called when the a `pointerdown` event happens outside of the `HoverCard`. * Can be prevented. */ onPointerDownOutside?: DismissableLayerProps['onPointerDownOutside']; /** * Event handler called when the focus moves outside of the `HoverCard`. * Can be prevented. */ onFocusOutside?: DismissableLayerProps['onFocusOutside']; /** * Event handler called when an interaction happens outside the `HoverCard`. * Specifically, when a `pointerdown` event happens outside or focus moves outside of it. * Can be prevented. */ onInteractOutside?: DismissableLayerProps['onInteractOutside']; /** * Whether the `HoverCard` should render in a `Portal` * (default: `true`) */ portalled?: boolean; } const HoverCardContentImpl = React.forwardRef< HoverCardContentImplElement, HoverCardContentImplProps >((props: ScopedProps<HoverCardContentImplProps>, forwardedRef) => { const { __scopeHoverCard, portalled = true, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, ...contentProps } = props; const context = useHoverCardContext(CONTENT_NAME, __scopeHoverCard); const popperScope = usePopperScope(__scopeHoverCard); const ref = React.useRef<HoverCardContentImplElement>(null); const composedRefs = useComposedRefs(forwardedRef, ref); const PortalWrapper = portalled ? Portal : React.Fragment; React.useEffect(() => { if (ref.current) { const tabbables = getTabbableNodes(ref.current); tabbables.forEach((tabbable) => tabbable.setAttribute('tabindex', '-1')); } }); return ( <PortalWrapper> <DismissableLayer asChild disableOutsidePointerEvents={false} onInteractOutside={onInteractOutside} onEscapeKeyDown={onEscapeKeyDown} onPointerDownOutside={onPointerDownOutside} onFocusOutside={onFocusOutside} onDismiss={context.onDismiss} > <PopperPrimitive.Content {...popperScope} {...contentProps} ref={composedRefs} style={{ ...contentProps.style, // re-namespace exposed content custom property ['--radix-hover-card-content-transform-origin' as any]: 'var(--radix-popper-transform-origin)', }} /> </DismissableLayer> </PortalWrapper> ); }); /* ------------------------------------------------------------------------------------------------- * HoverCardArrow * -----------------------------------------------------------------------------------------------*/ const ARROW_NAME = 'HoverCardArrow'; type HoverCardArrowElement = React.ElementRef<typeof PopperPrimitive.Arrow>; type PopperArrowProps = Radix.ComponentPropsWithoutRef<typeof PopperPrimitive.Arrow>; interface HoverCardArrowProps extends PopperArrowProps {} const HoverCardArrow = React.forwardRef<HoverCardArrowElement, HoverCardArrowProps>( (props: ScopedProps<HoverCardArrowProps>, forwardedRef) => { const { __scopeHoverCard, ...arrowProps } = props; const popperScope = usePopperScope(__scopeHoverCard); return <PopperPrimitive.Arrow {...popperScope} {...arrowProps} ref={forwardedRef} />; } ); HoverCardArrow.displayName = ARROW_NAME; /* -----------------------------------------------------------------------------------------------*/ function excludeTouch<E>(eventHandler: () => void) { return (event: React.PointerEvent<E>) => event.pointerType === 'touch' ? undefined : eventHandler(); } /** * Returns a list of nodes that can be in the tab sequence. * @see: https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker */ function getTabbableNodes(container: HTMLElement) { const nodes: HTMLElement[] = []; const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { acceptNode: (node: any) => { // `.tabIndex` is not the same as the `tabindex` attribute. It works on the // runtime's understanding of tabbability, so this automatically accounts // for any kind of element that could be tabbed to. return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; }, }); while (walker.nextNode()) nodes.push(walker.currentNode as HTMLElement); return nodes; } const Root = HoverCard; const Trigger = HoverCardTrigger; const Content = HoverCardContent; const Arrow = HoverCardArrow; export { createHoverCardScope, // HoverCard, HoverCardTrigger, HoverCardContent, HoverCardArrow, // Root, Trigger, Content, Arrow, }; export type { HoverCardProps, HoverCardTriggerProps, HoverCardContentProps, HoverCardArrowProps };
the_stack
import React, { FC, useState, useEffect } from 'react'; import { render, cleanup } from '@testing-library/react'; import { makeJestMoveTimeTo } from '../../test-utils/makeJestMoveTimeTo'; import { ActJestMoveTimeTo, makeActJestMoveTimeTo } from '../../test-utils/makeActJestMoveTimeTo'; import { ENTERED, ENTERING, EXITING, EXITED, STAGGER, SEQUENCE, AnimatorSettingsManagerCustom, AnimatorSettingsManagerStatus, AnimatorChildActivations } from '../constants'; import { useAnimator } from '../useAnimator'; import { Animator } from './Animator.component'; let actJestMoveTimeTo: ActJestMoveTimeTo; jest.useFakeTimers(); beforeEach(() => { const jestMoveTimeTo = makeJestMoveTimeTo(); actJestMoveTimeTo = makeActJestMoveTimeTo(jestMoveTimeTo); }); afterEach(cleanup); test('Should parent node combine children (diverse) durations if "combine" and "manager=parallel" (this case also applies to all managers on EXITING)', () => { let f0: any; const ExampleParent: FC = () => { f0 = useAnimator()?.flow.value; return null; }; let f1: any; const ExampleChild1: FC = () => { f1 = useAnimator()?.flow.value; return null; }; let f2: any; const ExampleChild2: FC = () => { f2 = useAnimator()?.flow.value; return null; }; let f3: any; const ExampleChild3: FC = () => { f3 = useAnimator()?.flow.value; return null; }; const Example: FC = () => { const [activate, setActivate] = useState(true); useEffect(() => { setTimeout(() => setActivate(false), 1000); }, []); return ( <Animator animator={{ activate, combine: true }}> <ExampleParent /> <Animator animator={{ duration: { enter: 200, exit: 200 } }}> <ExampleChild1 /> </Animator> <Animator animator={{ duration: { enter: 250, exit: 250 } }}> <ExampleChild2 /> </Animator> <Animator animator={{ duration: { enter: 150, exit: 150 } }}> <ExampleChild3 /> </Animator> </Animator> ); }; render(<Example />); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); actJestMoveTimeTo(1); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, ENTERING, ENTERING]); actJestMoveTimeTo(151); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, ENTERING, ENTERED]); actJestMoveTimeTo(201); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERING, ENTERED]); // Just before the last child is ENTERED. actJestMoveTimeTo(249); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERING, ENTERED]); actJestMoveTimeTo(251); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(999); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(1001); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITING, EXITING, EXITING]); actJestMoveTimeTo(1151); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITING, EXITING, EXITED]); actJestMoveTimeTo(1201); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITED, EXITING, EXITED]); actJestMoveTimeTo(1251); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); }); test('Should parent node combine children durations if "combine" and "manager=stagger"', () => { let f0: any; const ExampleParent: FC = () => { f0 = useAnimator()?.flow.value; return null; }; let f1: any; const ExampleChild1: FC = () => { f1 = useAnimator()?.flow.value; return null; }; let f2: any; const ExampleChild2: FC = () => { f2 = useAnimator()?.flow.value; return null; }; let f3: any; const ExampleChild3: FC = () => { f3 = useAnimator()?.flow.value; return null; }; const Example: FC = () => { const [activate, setActivate] = useState(true); useEffect(() => { setTimeout(() => setActivate(false), 1000); }, []); return ( <Animator animator={{ activate, combine: true, manager: STAGGER }}> <ExampleParent /> <Animator> <ExampleChild1 /> </Animator> <Animator> <ExampleChild2 /> </Animator> <Animator> <ExampleChild3 /> </Animator> </Animator> ); }; render(<Example />); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); actJestMoveTimeTo(1); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, EXITED, EXITED]); actJestMoveTimeTo(26); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, ENTERING, EXITED]); actJestMoveTimeTo(51); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, ENTERING, ENTERING]); // Just before the last child is ENTERED. actJestMoveTimeTo(149); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERED, ENTERING]); actJestMoveTimeTo(151); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(999); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(1001); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITING, EXITING, EXITING]); actJestMoveTimeTo(1101); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); }); test('Should parent node combine children durations if "combine" and "manager=sequence"', () => { let f0: any; const ExampleParent: FC = () => { f0 = useAnimator()?.flow.value; return null; }; let f1: any; const ExampleChild1: FC = () => { f1 = useAnimator()?.flow.value; return null; }; let f2: any; const ExampleChild2: FC = () => { f2 = useAnimator()?.flow.value; return null; }; let f3: any; const ExampleChild3: FC = () => { f3 = useAnimator()?.flow.value; return null; }; const Example: FC = () => { const [activate, setActivate] = useState(true); useEffect(() => { setTimeout(() => setActivate(false), 1000); }, []); return ( <Animator animator={{ activate, combine: true, manager: SEQUENCE }}> <ExampleParent /> <Animator> <ExampleChild1 /> </Animator> <Animator> <ExampleChild2 /> </Animator> <Animator> <ExampleChild3 /> </Animator> </Animator> ); }; render(<Example />); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); actJestMoveTimeTo(1); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, EXITED, EXITED]); actJestMoveTimeTo(101); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERING, EXITED]); actJestMoveTimeTo(201); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERED, ENTERING]); // Just before the last child is ENTERED. actJestMoveTimeTo(299); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERED, ENTERING]); actJestMoveTimeTo(301); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(999); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(1001); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITING, EXITING, EXITING]); actJestMoveTimeTo(1101); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); }); test('Should parent node combine children durations if "combine" and "manager" custom', () => { let f0: any; const ExampleParent: FC = () => { f0 = useAnimator()?.flow.value; return null; }; let f1: any; const ExampleChild1: FC = () => { f1 = useAnimator()?.flow.value; return null; }; let f2: any; const ExampleChild2: FC = () => { f2 = useAnimator()?.flow.value; return null; }; let f3: any; const ExampleChild3: FC = () => { f3 = useAnimator()?.flow.value; return null; }; const manager: AnimatorSettingsManagerCustom = (status: AnimatorSettingsManagerStatus): AnimatorChildActivations => ({ duration: 500, times: status.nodes.map(node => ({ node, time: 50 })) }); const Example: FC = () => { const [activate, setActivate] = useState(true); useEffect(() => { setTimeout(() => setActivate(false), 1000); }, []); return ( <Animator animator={{ activate, combine: true, manager }}> <ExampleParent /> <Animator> <ExampleChild1 /> </Animator> <Animator> <ExampleChild2 /> </Animator> <Animator> <ExampleChild3 /> </Animator> </Animator> ); }; render(<Example />); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); actJestMoveTimeTo(1); expect([f0, f1, f2, f3]).toEqual([ENTERING, EXITED, EXITED, EXITED]); actJestMoveTimeTo(51); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERING, ENTERING, ENTERING]); actJestMoveTimeTo(151); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(499); expect([f0, f1, f2, f3]).toEqual([ENTERING, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(501); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(999); expect([f0, f1, f2, f3]).toEqual([ENTERED, ENTERED, ENTERED, ENTERED]); actJestMoveTimeTo(1001); expect([f0, f1, f2, f3]).toEqual([EXITING, EXITING, EXITING, EXITING]); actJestMoveTimeTo(1101); expect([f0, f1, f2, f3]).toEqual([EXITED, EXITED, EXITED, EXITED]); }); test('Should console.log() manager total duration missing error if "combine" and "manager" custom does not provide child activations "duration"', () => { const consoleError = jest.spyOn(console, 'error').mockImplementation(); // No total duration provided. const manager: AnimatorSettingsManagerCustom = (status: AnimatorSettingsManagerStatus): AnimatorChildActivations => ({ duration: undefined, times: status.nodes.map(node => ({ node, time: 0 })) }); render( <Animator animator={{ combine: true, manager }}> <Animator /> <Animator /> <Animator /> </Animator> ); actJestMoveTimeTo(1); expect(consoleError).toHaveBeenCalledWith( expect.stringMatching('Animator with custom "manager" and "combine" enabled should return') ); consoleError.mockRestore(); }); test('Should console.log() error if updateDuration() is called if "combine"', () => { const consoleError = jest.spyOn(console, 'error').mockImplementation(); const Example: FC = () => { useAnimator()?.updateDuration({ enter: 200 }); return null; }; render( <Animator animator={{ combine: true }}> <Example /> </Animator> ); actJestMoveTimeTo(1); expect(consoleError).toHaveBeenCalledWith( 'Animator can not update duration dynamically when "combine" is enabled.' ); consoleError.mockRestore(); });
the_stack
import Player from '@vimeo/player'; // based on README.md of @vimeo/player >> https://github.com/vimeo/player.js let player: Player ; player = new Player('handstick', { id: 19231868, width: 640, // Use default values for settings, to test typings autopause: true, autoplay: false, background: false, byline: true, color: '#00adef', loop: false, muted: false, playsinline: true, portrait: true, speed: false, title: true, transparent: true }); const onPlay = (data: any) => { // data is an object containing properties specific to that event }; player.on('play', onPlay); // If later on you decide that you don’t need to listen for play anymore. player.off('play', onPlay); // Alternatively, `off` can be called with just the event name to remove all // listeners. player.off('play'); player.loadVideo(76979871).then((id) => { // the video successfully loaded }).catch((error) => { switch (error.name) { case 'TypeError': // the id was not a number break; case 'PasswordError': // the video is password-protected and the viewer needs to enter the // password first break; case 'PrivacyError': // the video is password-protected or private break; default: // some other error occurred break; } }); player.ready().then(() => { // the player is ready }); player.enableTextTrack('en').then((track) => { console.log(track.label); console.log(track.kind); console.log(track.language); // track.language = the iso code for the language // track.kind = 'captions' or 'subtitles' // track.label = the human-readable label }).catch((error) => { switch (error.name) { case 'InvalidTrackLanguageError': // no track was available with the specified language break; case 'InvalidTrackError': // no track was available with the specified language and kind break; default: // some other error occurred break; } }); player.disableTextTrack().then(() => { // the track was disabled }).catch((error) => { // an error occurred }); player.pause().then(() => { // the video was paused }).catch((error) => { switch (error.name) { case 'PasswordError': // the video is password-protected and the viewer needs to enter the // password first break; case 'PrivacyError': // the video is private break; default: // some other error occurred break; } }); player.play().then(() => { // the video was played }).catch((error) => { switch (error.name) { case 'PasswordError': // the video is password-protected and the viewer needs to enter the // password first break; case 'PrivacyError': // the video is private break; default: // some other error occurred break; } }); player.unload().then(() => { // the video was unloaded }).catch((error) => { // an error occurred }); player.getAutopause().then((autopause) => { // autopause = whether autopause is turned on or off }).catch((error) => { switch (error.name) { case 'UnsupportedError': // Autopause is not supported with the current player or browser break; default: // some other error occurred break; } }); player.setAutopause(false).then((autopause) => { // autopause was turned off }).catch((error) => { switch (error.name) { case 'UnsupportedError': // Autopause is not supported with the current player or browser break; default: // some other error occurred break; } }); player.getColor().then((color) => { // color = the hex color of the player }).catch((error) => { // an error occurred }); player.setColor('#00adef').then((color) => { // color was successfully set }).catch((error) => { switch (error.name) { case 'ContrastError': // the color was set, but the contrast is outside of the acceptable // range break; case 'TypeError': // the string was not a valid hex or rgb color break; case 'EmbedSettingsError': // the owner of the video has chosen to use a specific color break; default: // some other error occurred break; } }); player.addCuePoint(15, { customKey: 'customValue' }).then((id) => { // cue point was added successfully }).catch((error) => { switch (error.name) { case 'UnsupportedError': // cue points are not supported with the current player or browser break; case 'RangeError': // the time was less than 0 or greater than the video’s duration break; default: // some other error occurred break; } }); player.removeCuePoint('09ecf4e4-b587-42cf-ad9f-e666b679c9ab').then((id) => { // cue point was removed successfully }).catch((error) => { switch (error.name) { case 'UnsupportedError': // cue points are not supported with the current player or browser break; case 'InvalidCuePoint': // a cue point with the id passed wasn’t found break; default: // some other error occurred break; } }); player.getCuePoints().then((cuePoints) => { // cuePoints = an array of cue point objects }).catch((error) => { switch (error.name) { case 'UnsupportedError': // cue points are not supported with the current player or browser break; default: // some other error occurred break; } }); player.getCurrentTime().then((seconds) => { // seconds = the current playback position }).catch((error) => { // an error occurred }); player.setCurrentTime(30.456).then((seconds) => { // seconds = the actual time that the player seeked to }).catch((error) => { switch (error.name) { case 'RangeError': // the time was less than 0 or greater than the video’s duration break; default: // some other error occurred break; } }); player.getDuration().then((duration) => { // duration = the duration of the video in seconds }).catch((error) => { // an error occurred }); player.getEnded().then((ended) => { // ended = whether or not the video has ended }).catch((error) => { // an error occurred }); player.getLoop().then((loop) => { // loop = whether loop is turned on or not }).catch((error) => { // an error occurred }); player.setLoop(true).then((loop) => { // loop was turned on }).catch((error) => { // an error occurred }); player.getMuted().then((muted) => { // muted = whether muted is turned on or not }).catch((error) => { // an error occurred }); player.setMuted(true).then((muted) => { // muted was turned on }).catch((error) => { // an error occurred }); player.getPaused().then((paused) => { // paused = whether or not the player is paused }).catch((error) => { // an error occurred }); player.getPlaybackRate().then((playbackRate) => { // playbackRate = a numeric value of the current playback rate }).catch((error) => { // an error occurred }); player.setPlaybackRate(0.5).then((playbackRate) => { // playback rate was set }).catch((error) => { switch (error.name) { case 'RangeError': // the playback rate was less than 0.5 or greater than 2 break; default: // some other error occurred break; } }); player.getTextTracks().then((tracks) => { // tracks = an array of track objects tracks.forEach((track) => { console.log(track.label); console.log(track.kind); console.log(track.language); console.log(track.mode); }); }).catch((error) => { // an error occurred error.name; }); player.getVideoEmbedCode().then((embedCode) => { // embedCode = <iframe> embed code }).catch((error) => { // an error occurred }); player.getVideoId().then((id) => { // id = the video id }).catch((error) => { // an error occurred }); player.getVideoTitle().then((title) => { // title = the title of the video }).catch((error) => { // an error occurred }); player.getVideoWidth().then((width) => { // width = the width of the video that is currently playing }).catch((error) => { // an error occurred }); player.getVideoHeight().then((height) => { // height = the height of the video that is currently playing }).catch((error) => { // an error occurred }); Promise.all([player.getVideoWidth(), player.getVideoHeight()]).then((dimensions) => { const width = dimensions[0]; const height = dimensions[1]; }); player.getVideoUrl().then((url) => { // url = the vimeo.com url for the video }).catch((error) => { switch (error.name) { case 'PrivacyError': // the url isn’t available because of the video’s privacy setting break; default: // some other error occurred break; } }); player.getVolume().then((volume) => { // volume = the volume level of the player }).catch((error) => { // an error occurred }); player.setVolume(0.5).then((volume) => { // volume was set }).catch((error) => { switch (error.name) { case 'RangeError': // the volume was less than 0 or greater than 1 break; default: // some other error occurred break; } }); player.getSeeking().then((seeking) => { // seeking = whether the player is seeking or not }).catch((error) => { // an error occurred }); player.getBuffered().then((buffered) => { // buffered = an array of the buffered video time ranges. }).catch((error) => { // an error occurred }); player.getPlayed().then((played) => { // played = array values of the played video time ranges. }).catch((error) => { // an error occurred }); player.getSeekable().then((seekable) => { // seekable = array values of the seekable video time ranges. }).catch((error) => { // an error occurred }); // EVENTS player.on('play', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0 console.log(data.seconds); // 0 }); player.on('pause', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0 console.log(data.seconds); // 0 }); player.on('ended', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 1 console.log(data.seconds); // 61.857 }); player.on('timeupdate', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0.049 console.log(data.seconds); // 3.034 }); player.on('progress', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0.502 console.log(data.seconds); // 31.052 }); player.on('seeked', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0.485 console.log(data.seconds); // 30 }); player.on('texttrackchange', (data) => { // data is an object containing properties specific to that event console.log(data.kind); console.log(data.label); console.log(data.language); }); player.on('cuechange', (data) => { // data is an object containing properties specific to that event console.log(data.cues); // Array of Cues console.log(data.cues[0].html); console.log(data.cues[0].text); console.log(data.label); console.log(data.kind); console.log(data.language); }); player.on('cuepoint', (data) => { // data is an object containing properties specific to that event console.log(data.time); console.log(data.data); console.log(data.data.customKey); console.log(data.id); }); player.on('volumechange', (data) => { // data is an object containing properties specific to that event console.log(data.volume); }); player.on('playbackratechange', (data) => { // data is an object containing properties specific to that event console.log(data.playbackRate); }); player.on('bufferstart', (data) => { // no associated data with this event }); player.on('bufferend', (data) => { // no associated data with this event }); player.on('seeking', (data) => { // data is an object containing properties specific to that event console.log(data.duration); // 61.857 console.log(data.percent); // 0.485 console.log(data.seconds); // 30 }); player.on('error', (data) => { // data is an object containing properties specific to that event console.log(data.message); console.log(data.method); console.log(data.name); }); player.on('loaded', (data) => { // data is an object containing properties specific to that event console.log(data.id); });
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class AmplifyBackend extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AmplifyBackend.Types.ClientConfiguration) config: Config & AmplifyBackend.Types.ClientConfiguration; /** * This operation clones an existing backend. */ cloneBackend(params: AmplifyBackend.Types.CloneBackendRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CloneBackendResponse) => void): Request<AmplifyBackend.Types.CloneBackendResponse, AWSError>; /** * This operation clones an existing backend. */ cloneBackend(callback?: (err: AWSError, data: AmplifyBackend.Types.CloneBackendResponse) => void): Request<AmplifyBackend.Types.CloneBackendResponse, AWSError>; /** * This operation creates a backend for an Amplify app. Backends are automatically created at the time of app creation. */ createBackend(params: AmplifyBackend.Types.CreateBackendRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendResponse) => void): Request<AmplifyBackend.Types.CreateBackendResponse, AWSError>; /** * This operation creates a backend for an Amplify app. Backends are automatically created at the time of app creation. */ createBackend(callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendResponse) => void): Request<AmplifyBackend.Types.CreateBackendResponse, AWSError>; /** * Creates a new backend API resource. */ createBackendAPI(params: AmplifyBackend.Types.CreateBackendAPIRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendAPIResponse) => void): Request<AmplifyBackend.Types.CreateBackendAPIResponse, AWSError>; /** * Creates a new backend API resource. */ createBackendAPI(callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendAPIResponse) => void): Request<AmplifyBackend.Types.CreateBackendAPIResponse, AWSError>; /** * Creates a new backend authentication resource. */ createBackendAuth(params: AmplifyBackend.Types.CreateBackendAuthRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendAuthResponse) => void): Request<AmplifyBackend.Types.CreateBackendAuthResponse, AWSError>; /** * Creates a new backend authentication resource. */ createBackendAuth(callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendAuthResponse) => void): Request<AmplifyBackend.Types.CreateBackendAuthResponse, AWSError>; /** * Creates a config object for a backend. */ createBackendConfig(params: AmplifyBackend.Types.CreateBackendConfigRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendConfigResponse) => void): Request<AmplifyBackend.Types.CreateBackendConfigResponse, AWSError>; /** * Creates a config object for a backend. */ createBackendConfig(callback?: (err: AWSError, data: AmplifyBackend.Types.CreateBackendConfigResponse) => void): Request<AmplifyBackend.Types.CreateBackendConfigResponse, AWSError>; /** * Generates a one-time challenge code to authenticate a user into your Amplify Admin UI. */ createToken(params: AmplifyBackend.Types.CreateTokenRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.CreateTokenResponse) => void): Request<AmplifyBackend.Types.CreateTokenResponse, AWSError>; /** * Generates a one-time challenge code to authenticate a user into your Amplify Admin UI. */ createToken(callback?: (err: AWSError, data: AmplifyBackend.Types.CreateTokenResponse) => void): Request<AmplifyBackend.Types.CreateTokenResponse, AWSError>; /** * Removes an existing environment from your Amplify project. */ deleteBackend(params: AmplifyBackend.Types.DeleteBackendRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendResponse) => void): Request<AmplifyBackend.Types.DeleteBackendResponse, AWSError>; /** * Removes an existing environment from your Amplify project. */ deleteBackend(callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendResponse) => void): Request<AmplifyBackend.Types.DeleteBackendResponse, AWSError>; /** * Deletes an existing backend API resource. */ deleteBackendAPI(params: AmplifyBackend.Types.DeleteBackendAPIRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendAPIResponse) => void): Request<AmplifyBackend.Types.DeleteBackendAPIResponse, AWSError>; /** * Deletes an existing backend API resource. */ deleteBackendAPI(callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendAPIResponse) => void): Request<AmplifyBackend.Types.DeleteBackendAPIResponse, AWSError>; /** * Deletes an existing backend authentication resource. */ deleteBackendAuth(params: AmplifyBackend.Types.DeleteBackendAuthRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendAuthResponse) => void): Request<AmplifyBackend.Types.DeleteBackendAuthResponse, AWSError>; /** * Deletes an existing backend authentication resource. */ deleteBackendAuth(callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteBackendAuthResponse) => void): Request<AmplifyBackend.Types.DeleteBackendAuthResponse, AWSError>; /** * Deletes the challenge token based on the given appId and sessionId. */ deleteToken(params: AmplifyBackend.Types.DeleteTokenRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteTokenResponse) => void): Request<AmplifyBackend.Types.DeleteTokenResponse, AWSError>; /** * Deletes the challenge token based on the given appId and sessionId. */ deleteToken(callback?: (err: AWSError, data: AmplifyBackend.Types.DeleteTokenResponse) => void): Request<AmplifyBackend.Types.DeleteTokenResponse, AWSError>; /** * Generates a model schema for an existing backend API resource. */ generateBackendAPIModels(params: AmplifyBackend.Types.GenerateBackendAPIModelsRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GenerateBackendAPIModelsResponse) => void): Request<AmplifyBackend.Types.GenerateBackendAPIModelsResponse, AWSError>; /** * Generates a model schema for an existing backend API resource. */ generateBackendAPIModels(callback?: (err: AWSError, data: AmplifyBackend.Types.GenerateBackendAPIModelsResponse) => void): Request<AmplifyBackend.Types.GenerateBackendAPIModelsResponse, AWSError>; /** * Provides project-level details for your Amplify UI project. */ getBackend(params: AmplifyBackend.Types.GetBackendRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendResponse) => void): Request<AmplifyBackend.Types.GetBackendResponse, AWSError>; /** * Provides project-level details for your Amplify UI project. */ getBackend(callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendResponse) => void): Request<AmplifyBackend.Types.GetBackendResponse, AWSError>; /** * Gets the details for a backend API. */ getBackendAPI(params: AmplifyBackend.Types.GetBackendAPIRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAPIResponse) => void): Request<AmplifyBackend.Types.GetBackendAPIResponse, AWSError>; /** * Gets the details for a backend API. */ getBackendAPI(callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAPIResponse) => void): Request<AmplifyBackend.Types.GetBackendAPIResponse, AWSError>; /** * Generates a model schema for existing backend API resource. */ getBackendAPIModels(params: AmplifyBackend.Types.GetBackendAPIModelsRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAPIModelsResponse) => void): Request<AmplifyBackend.Types.GetBackendAPIModelsResponse, AWSError>; /** * Generates a model schema for existing backend API resource. */ getBackendAPIModels(callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAPIModelsResponse) => void): Request<AmplifyBackend.Types.GetBackendAPIModelsResponse, AWSError>; /** * Gets backend auth details. */ getBackendAuth(params: AmplifyBackend.Types.GetBackendAuthRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAuthResponse) => void): Request<AmplifyBackend.Types.GetBackendAuthResponse, AWSError>; /** * Gets backend auth details. */ getBackendAuth(callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendAuthResponse) => void): Request<AmplifyBackend.Types.GetBackendAuthResponse, AWSError>; /** * Returns information about a specific job. */ getBackendJob(params: AmplifyBackend.Types.GetBackendJobRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendJobResponse) => void): Request<AmplifyBackend.Types.GetBackendJobResponse, AWSError>; /** * Returns information about a specific job. */ getBackendJob(callback?: (err: AWSError, data: AmplifyBackend.Types.GetBackendJobResponse) => void): Request<AmplifyBackend.Types.GetBackendJobResponse, AWSError>; /** * Gets the challenge token based on the given appId and sessionId. */ getToken(params: AmplifyBackend.Types.GetTokenRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.GetTokenResponse) => void): Request<AmplifyBackend.Types.GetTokenResponse, AWSError>; /** * Gets the challenge token based on the given appId and sessionId. */ getToken(callback?: (err: AWSError, data: AmplifyBackend.Types.GetTokenResponse) => void): Request<AmplifyBackend.Types.GetTokenResponse, AWSError>; /** * Lists the jobs for the backend of an Amplify app. */ listBackendJobs(params: AmplifyBackend.Types.ListBackendJobsRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.ListBackendJobsResponse) => void): Request<AmplifyBackend.Types.ListBackendJobsResponse, AWSError>; /** * Lists the jobs for the backend of an Amplify app. */ listBackendJobs(callback?: (err: AWSError, data: AmplifyBackend.Types.ListBackendJobsResponse) => void): Request<AmplifyBackend.Types.ListBackendJobsResponse, AWSError>; /** * Removes all backend environments from your Amplify project. */ removeAllBackends(params: AmplifyBackend.Types.RemoveAllBackendsRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.RemoveAllBackendsResponse) => void): Request<AmplifyBackend.Types.RemoveAllBackendsResponse, AWSError>; /** * Removes all backend environments from your Amplify project. */ removeAllBackends(callback?: (err: AWSError, data: AmplifyBackend.Types.RemoveAllBackendsResponse) => void): Request<AmplifyBackend.Types.RemoveAllBackendsResponse, AWSError>; /** * Removes the AWS resources that are required to access the Amplify Admin UI. */ removeBackendConfig(params: AmplifyBackend.Types.RemoveBackendConfigRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.RemoveBackendConfigResponse) => void): Request<AmplifyBackend.Types.RemoveBackendConfigResponse, AWSError>; /** * Removes the AWS resources that are required to access the Amplify Admin UI. */ removeBackendConfig(callback?: (err: AWSError, data: AmplifyBackend.Types.RemoveBackendConfigResponse) => void): Request<AmplifyBackend.Types.RemoveBackendConfigResponse, AWSError>; /** * Updates an existing backend API resource. */ updateBackendAPI(params: AmplifyBackend.Types.UpdateBackendAPIRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendAPIResponse) => void): Request<AmplifyBackend.Types.UpdateBackendAPIResponse, AWSError>; /** * Updates an existing backend API resource. */ updateBackendAPI(callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendAPIResponse) => void): Request<AmplifyBackend.Types.UpdateBackendAPIResponse, AWSError>; /** * Updates an existing backend authentication resource. */ updateBackendAuth(params: AmplifyBackend.Types.UpdateBackendAuthRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendAuthResponse) => void): Request<AmplifyBackend.Types.UpdateBackendAuthResponse, AWSError>; /** * Updates an existing backend authentication resource. */ updateBackendAuth(callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendAuthResponse) => void): Request<AmplifyBackend.Types.UpdateBackendAuthResponse, AWSError>; /** * Updates the AWS resources that are required to access the Amplify Admin UI. */ updateBackendConfig(params: AmplifyBackend.Types.UpdateBackendConfigRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendConfigResponse) => void): Request<AmplifyBackend.Types.UpdateBackendConfigResponse, AWSError>; /** * Updates the AWS resources that are required to access the Amplify Admin UI. */ updateBackendConfig(callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendConfigResponse) => void): Request<AmplifyBackend.Types.UpdateBackendConfigResponse, AWSError>; /** * Updates a specific job. */ updateBackendJob(params: AmplifyBackend.Types.UpdateBackendJobRequest, callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendJobResponse) => void): Request<AmplifyBackend.Types.UpdateBackendJobResponse, AWSError>; /** * Updates a specific job. */ updateBackendJob(callback?: (err: AWSError, data: AmplifyBackend.Types.UpdateBackendJobResponse) => void): Request<AmplifyBackend.Types.UpdateBackendJobResponse, AWSError>; } declare namespace AmplifyBackend { export type AuthResources = "USER_POOL_ONLY"|"IDENTITY_POOL_AND_USER_POOL"|string; export interface BackendAPIAppSyncAuthSettings { /** * The Amazon Cognito user pool ID, if Amazon Cognito is used as an authentication setting to access your data models. */ CognitoUserPoolId?: __string; /** * The API key description for API_KEY, if it is used as an authentication mechanism to access your data models. */ Description?: __string; /** * The API key expiration time for API_KEY, if it is used as an authentication mechanism to access your data models. */ ExpirationTime?: __double; /** * The expiry time for the OpenID authentication mechanism. */ OpenIDAuthTTL?: __string; /** * The clientID for openID, if openID is used as an authentication setting to access your data models. */ OpenIDClientId?: __string; /** * The expiry time for the OpenID authentication mechanism. */ OpenIDIatTTL?: __string; /** * The openID issuer URL, if openID is used as an authentication setting to access your data models. */ OpenIDIssueURL?: __string; /** * The openID provider name, if openID is used as an authentication mechanism to access your data models. */ OpenIDProviderName?: __string; } export interface BackendAPIAuthType { /** * Describes the authentication mode. */ Mode?: Mode; /** * Describes settings for the authentication mode. */ Settings?: BackendAPIAppSyncAuthSettings; } export interface BackendAPIConflictResolution { /** * The strategy for conflict resolution. */ ResolutionStrategy?: ResolutionStrategy; } export interface BackendAPIResourceConfig { /** * Additional authentication methods used to interact with your data models. */ AdditionalAuthTypes?: ListOfBackendAPIAuthType; /** * The API name used to interact with the data model, configured as a part of the Amplify project. */ ApiName?: __string; /** * The conflict resolution strategy for your data stored in the data models. */ ConflictResolution?: BackendAPIConflictResolution; /** * The default authentication type for interacting with the configured data models in your Amplify project. */ DefaultAuthType?: BackendAPIAuthType; /** * The service used to provision and interact with the data model. */ Service?: __string; /** * The definition of the data model in the annotated transform of the GraphQL schema. */ TransformSchema?: __string; } export interface BackendAuthSocialProviderConfig { /** * Describes the client_id that can be obtained from the third-party social federation provider. */ ClientId?: __string; /** * Describes the client_secret that can be obtained from third-party social federation providers. */ ClientSecret?: __string; } export interface BackendJobRespObj { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The time when the job was created. */ CreateTime?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; /** * The time when the job was last updated. */ UpdateTime?: __string; } export interface CloneBackendRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The name of the destination backend environment to be created. */ TargetEnvironmentName: __string; } export interface CloneBackendResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface CreateBackendAPIRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The resource configuration for this request. */ ResourceConfig: BackendAPIResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface CreateBackendAPIResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface CreateBackendAuthForgotPasswordConfig { /** * Describes which method to use (either SMS or email) to deliver messages to app users that want to recover their password. */ DeliveryMethod: DeliveryMethod; /** * The configuration for the email sent when an app user forgets their password. */ EmailSettings?: EmailSettings; /** * The configuration for the SMS message sent when an app user forgets their password. */ SmsSettings?: SmsSettings; } export interface CreateBackendAuthIdentityPoolConfig { /** * Name of the identity pool used for authorization. */ IdentityPoolName: __string; /** * Set to true or false based on whether you want to enable guest authorization to your Amplify app. */ UnauthenticatedLogin: __boolean; } export interface CreateBackendAuthMFAConfig { /** * Describes whether MFA should be [ON, OFF, or OPTIONAL] for authentication in your Amplify project. */ MFAMode: MFAMode; /** * Describes the configuration settings and methods for your Amplify app users to use MFA. */ Settings?: Settings; } export interface CreateBackendAuthOAuthConfig { /** * The domain prefix for your Amplify app. */ DomainPrefix?: __string; /** * The OAuth grant type that you use to allow app users to authenticate from your Amplify app. */ OAuthGrantType: OAuthGrantType; /** * List of OAuth-related flows that allow your app users to authenticate from your Amplify app. */ OAuthScopes: ListOfOAuthScopesElement; /** * The redirected URI for signing in to your Amplify app. */ RedirectSignInURIs: ListOf__string; /** * Redirect URLs that OAuth uses when a user signs out of an Amplify app. */ RedirectSignOutURIs: ListOf__string; /** * The settings for using social identity providers for access to your Amplify app. */ SocialProviderSettings?: SocialProviderSettings; } export interface CreateBackendAuthPasswordPolicyConfig { /** * Additional constraints for the password used to access the backend of your Amplify project. */ AdditionalConstraints?: ListOfAdditionalConstraintsElement; /** * The minimum length of the password used to access the backend of your Amplify project. */ MinimumLength: __double; } export interface CreateBackendAuthRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The resource configuration for this request object. */ ResourceConfig: CreateBackendAuthResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface CreateBackendAuthResourceConfig { /** * Defines whether you want to configure only authentication or both authentication and authorization settings. */ AuthResources: AuthResources; /** * Describes the authorization configuration for the Amazon Cognito identity pool, provisioned as a part of the auth resource in your Amplify project. */ IdentityPoolConfigs?: CreateBackendAuthIdentityPoolConfig; /** * Defines the service name to use when configuring an authentication resource in your Amplify project. */ Service: Service; /** * Describes the authentication configuration for the Amazon Cognito user pool, provisioned as a part of the auth resource in your Amplify project. */ UserPoolConfigs: CreateBackendAuthUserPoolConfig; } export interface CreateBackendAuthResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface CreateBackendAuthUserPoolConfig { /** * Describes the forgotten password policy for your Amazon Cognito user pool, configured as a part of your Amplify project. */ ForgotPassword?: CreateBackendAuthForgotPasswordConfig; /** * Describes whether to apply multi-factor authentication (MFA) policies for your Amazon Cognito user pool that's configured as a part of your Amplify project. */ Mfa?: CreateBackendAuthMFAConfig; /** * Describes the OAuth policy and rules for your Amazon Cognito user pool, configured as a part of your Amplify project. */ OAuth?: CreateBackendAuthOAuthConfig; /** * Describes the password policy for your Amazon Cognito user pool, configured as a part of your Amplify project. */ PasswordPolicy?: CreateBackendAuthPasswordPolicyConfig; /** * The required attributes to sign up new users in the Amazon Cognito user pool. */ RequiredSignUpAttributes: ListOfRequiredSignUpAttributesElement; /** * Describes the sign-in methods that your Amplify app users to log in using the Amazon Cognito user pool that's configured as a part of your Amplify project. */ SignInMethod: SignInMethod; /** * The Amazon Cognito user pool name. */ UserPoolName: __string; } export interface CreateBackendConfigRequest { /** * The app ID. */ AppId: __string; /** * The app ID for the backend manager. */ BackendManagerAppId?: __string; } export interface CreateBackendConfigResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * The ID for the job. */ JobId?: __string; /** * The current status of the request. */ Status?: __string; } export interface CreateBackendRequest { /** * The app ID. */ AppId: __string; /** * The name of the app. */ AppName: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The resource configuration for the backend creation request. */ ResourceConfig?: ResourceConfig; /** * The name of the resource. */ ResourceName?: __string; } export interface CreateBackendResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface CreateTokenRequest { /** * The app ID. */ AppId: __string; } export interface CreateTokenResponse { /** * The app ID. */ AppId?: __string; /** * One-time challenge code for authenticating into the Amplify Admin UI. */ ChallengeCode?: __string; /** * A unique ID provided when creating a new challenge token. */ SessionId?: __string; /** * The expiry time for the one-time generated token code. */ Ttl?: __string; } export interface DeleteBackendAPIRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * Defines the resource configuration for the data model in your Amplify project. */ ResourceConfig?: BackendAPIResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface DeleteBackendAPIResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface DeleteBackendAuthRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The name of this resource. */ ResourceName: __string; } export interface DeleteBackendAuthResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface DeleteBackendRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; } export interface DeleteBackendResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface DeleteTokenRequest { /** * The app ID. */ AppId: __string; /** * The session ID. */ SessionId: __string; } export interface DeleteTokenResponse { /** * Indicates whether the request succeeded or failed. */ IsSuccess?: __boolean; } export type DeliveryMethod = "EMAIL"|"SMS"|string; export interface EmailSettings { /** * The body of the email. */ EmailMessage?: __string; /** * The subject of the email. */ EmailSubject?: __string; } export interface GenerateBackendAPIModelsRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The name of this resource. */ ResourceName: __string; } export interface GenerateBackendAPIModelsResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface GetBackendAPIModelsRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The name of this resource. */ ResourceName: __string; } export interface GetBackendAPIModelsResponse { /** * Stringified JSON of the DataStore model. */ Models?: __string; /** * The current status of the request. */ Status?: Status; } export interface GetBackendAPIRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * Defines the resource configuration for the data model in your Amplify project. */ ResourceConfig?: BackendAPIResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface GetBackendAPIResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The resource configuration for this response object. */ ResourceConfig?: BackendAPIResourceConfig; /** * The name of this resource. */ ResourceName?: __string; } export interface GetBackendAuthRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The name of this resource. */ ResourceName: __string; } export interface GetBackendAuthResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The resource configuration for authorization requests to the backend of your Amplify project. */ ResourceConfig?: CreateBackendAuthResourceConfig; /** * The name of this resource. */ ResourceName?: __string; } export interface GetBackendJobRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The ID for the job. */ JobId: __string; } export interface GetBackendJobResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * The time when the job was created. */ CreateTime?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; /** * The time when the job was last updated. */ UpdateTime?: __string; } export interface GetBackendRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; } export interface GetBackendResponse { /** * A stringified version of the current configurations for your Amplify project. */ AmplifyMetaConfig?: __string; /** * The app ID. */ AppId?: __string; /** * The name of the app. */ AppName?: __string; /** * A list of backend environments in an array. */ BackendEnvironmentList?: ListOf__string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; } export interface GetTokenRequest { /** * The app ID. */ AppId: __string; /** * The session ID. */ SessionId: __string; } export interface GetTokenResponse { /** * The app ID. */ AppId?: __string; /** * The one-time challenge code for authenticating into the Amplify Admin UI. */ ChallengeCode?: __string; /** * A unique ID provided when creating a new challenge token. */ SessionId?: __string; /** * The expiry time for the one-time generated token code. */ Ttl?: __string; } export interface ListBackendJobsRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The ID for the job. */ JobId?: __string; /** * The maximum number of results that you want in the response. */ MaxResults?: __integerMin1Max25; /** * The token for the next set of results. */ NextToken?: __string; /** * Filters the list of response objects to include only those with the specified operation name. */ Operation?: __string; /** * Filters the list of response objects to include only those with the specified status. */ Status?: __string; } export interface ListBackendJobsResponse { /** * An array of jobs and their properties. */ Jobs?: ListOfBackendJobRespObj; /** * The token for the next set of results. */ NextToken?: __string; } export interface LoginAuthConfigReqObj { /** * The Amazon Cognito identity pool ID used for Amplify Admin UI login authorization. */ AwsCognitoIdentityPoolId?: __string; /** * The AWS Region for the Amplify Admin UI login. */ AwsCognitoRegion?: __string; /** * The Amazon Cognito user pool ID used for Amplify Admin UI login authentication. */ AwsUserPoolsId?: __string; /** * The web client ID for the Amazon Cognito user pools. */ AwsUserPoolsWebClientId?: __string; } export type MFAMode = "ON"|"OFF"|"OPTIONAL"|string; export type Mode = "API_KEY"|"AWS_IAM"|"AMAZON_COGNITO_USER_POOLS"|"OPENID_CONNECT"|string; export type OAuthGrantType = "CODE"|"IMPLICIT"|string; export interface RemoveAllBackendsRequest { /** * The app ID. */ AppId: __string; /** * Cleans up the Amplify Console app if this value is set to true. */ CleanAmplifyApp?: __boolean; } export interface RemoveAllBackendsResponse { /** * The app ID. */ AppId?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface RemoveBackendConfigRequest { /** * The app ID. */ AppId: __string; } export interface RemoveBackendConfigResponse { /** * If the request failed, this is the returned error. */ Error?: __string; } export type ResolutionStrategy = "OPTIMISTIC_CONCURRENCY"|"LAMBDA"|"AUTOMERGE"|"NONE"|string; export interface ResourceConfig { } export type Service = "COGNITO"|string; export interface Settings { /** * The supported MFA types. */ MfaTypes?: ListOfMfaTypesElement; /** * The body of the SMS message. */ SmsMessage?: __string; } export type SignInMethod = "EMAIL"|"EMAIL_AND_PHONE_NUMBER"|"PHONE_NUMBER"|"USERNAME"|string; export interface SmsSettings { /** * The body of the SMS message. */ SmsMessage?: __string; } export interface SocialProviderSettings { Facebook?: BackendAuthSocialProviderConfig; Google?: BackendAuthSocialProviderConfig; LoginWithAmazon?: BackendAuthSocialProviderConfig; } export type Status = "LATEST"|"STALE"|string; export interface UpdateBackendAPIRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * Defines the resource configuration for the data model in your Amplify project. */ ResourceConfig?: BackendAPIResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface UpdateBackendAPIResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface UpdateBackendAuthForgotPasswordConfig { /** * Describes which method to use (either SMS or email) to deliver messages to app users that want to recover their password. */ DeliveryMethod?: DeliveryMethod; /** * The configuration for the email sent when an app user forgets their password. */ EmailSettings?: EmailSettings; /** * The configuration for the SMS message sent when an Amplify app user forgets their password. */ SmsSettings?: SmsSettings; } export interface UpdateBackendAuthIdentityPoolConfig { /** * A Boolean value that you can set to allow or disallow guest-level authorization into your Amplify app. */ UnauthenticatedLogin?: __boolean; } export interface UpdateBackendAuthMFAConfig { /** * The MFA mode for the backend of your Amplify project. */ MFAMode?: MFAMode; /** * The settings of your MFA configuration for the backend of your Amplify project. */ Settings?: Settings; } export interface UpdateBackendAuthOAuthConfig { /** * The Amazon Cognito domain prefix used to create a hosted UI for authentication. */ DomainPrefix?: __string; /** * The OAuth grant type to allow app users to authenticate from your Amplify app. */ OAuthGrantType?: OAuthGrantType; /** * The list of OAuth-related flows that can allow users to authenticate from your Amplify app. */ OAuthScopes?: ListOfOAuthScopesElement; /** * Redirect URLs that OAuth uses when a user signs in to an Amplify app. */ RedirectSignInURIs?: ListOf__string; /** * Redirect URLs that OAuth uses when a user signs out of an Amplify app. */ RedirectSignOutURIs?: ListOf__string; /** * Describes third-party social federation configurations for allowing your users to sign in with OAuth. */ SocialProviderSettings?: SocialProviderSettings; } export interface UpdateBackendAuthPasswordPolicyConfig { /** * Describes additional constrains on the password requirements to sign in to the auth resource, configured as a part of your Amplify project. */ AdditionalConstraints?: ListOfAdditionalConstraintsElement; /** * Describes the minimum length of the password required to sign in to the auth resource, configured as a part of your Amplify project. */ MinimumLength?: __double; } export interface UpdateBackendAuthRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The resource configuration for this request object. */ ResourceConfig: UpdateBackendAuthResourceConfig; /** * The name of this resource. */ ResourceName: __string; } export interface UpdateBackendAuthResourceConfig { /** * Defines the service name to use when configuring an authentication resource in your Amplify project. */ AuthResources: AuthResources; /** * Describes the authorization configuration for the Amazon Cognito identity pool, provisioned as a part of the auth resource in your Amplify project. */ IdentityPoolConfigs?: UpdateBackendAuthIdentityPoolConfig; /** * Defines the service name to use when configuring an authentication resource in your Amplify project. */ Service: Service; /** * Describes the authentication configuration for the Amazon Cognito user pool, provisioned as a part of the auth resource in your Amplify project. */ UserPoolConfigs: UpdateBackendAuthUserPoolConfig; } export interface UpdateBackendAuthResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; } export interface UpdateBackendAuthUserPoolConfig { /** * Describes the forgot password policy for your Amazon Cognito user pool, configured as a part of your Amplify project. */ ForgotPassword?: UpdateBackendAuthForgotPasswordConfig; /** * Describes whether to apply multi-factor authentication (MFA) policies for your Amazon Cognito user pool that's configured as a part of your Amplify project. */ Mfa?: UpdateBackendAuthMFAConfig; /** * Describes the OAuth policy and rules for your Amazon Cognito user pool, configured as a part of your Amplify project. */ OAuth?: UpdateBackendAuthOAuthConfig; /** * Describes the password policy for your Amazon Cognito user pool, configured as a part of your Amplify project. */ PasswordPolicy?: UpdateBackendAuthPasswordPolicyConfig; } export interface UpdateBackendConfigRequest { /** * The app ID. */ AppId: __string; /** * Describes the Amazon Cognito configuration for Admin UI access. */ LoginAuthConfig?: LoginAuthConfigReqObj; } export interface UpdateBackendConfigResponse { /** * The app ID. */ AppId?: __string; /** * The app ID for the backend manager. */ BackendManagerAppId?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * Describes the Amazon Cognito configurations for the Admin UI auth resource to log in with. */ LoginAuthConfig?: LoginAuthConfigReqObj; } export interface UpdateBackendJobRequest { /** * The app ID. */ AppId: __string; /** * The name of the backend environment. */ BackendEnvironmentName: __string; /** * The ID for the job. */ JobId: __string; /** * Filters the list of response objects to include only those with the specified operation name. */ Operation?: __string; /** * Filters the list of response objects to include only those with the specified status. */ Status?: __string; } export interface UpdateBackendJobResponse { /** * The app ID. */ AppId?: __string; /** * The name of the backend environment. */ BackendEnvironmentName?: __string; /** * The time when the job was created. */ CreateTime?: __string; /** * If the request failed, this is the returned error. */ Error?: __string; /** * The ID for the job. */ JobId?: __string; /** * The name of the operation. */ Operation?: __string; /** * The current status of the request. */ Status?: __string; /** * The time when the job was last updated. */ UpdateTime?: __string; } export type AdditionalConstraintsElement = "REQUIRE_DIGIT"|"REQUIRE_LOWERCASE"|"REQUIRE_SYMBOL"|"REQUIRE_UPPERCASE"|string; export type MfaTypesElement = "SMS"|"TOTP"|string; export type OAuthScopesElement = "PHONE"|"EMAIL"|"OPENID"|"PROFILE"|"AWS_COGNITO_SIGNIN_USER_ADMIN"|string; export type RequiredSignUpAttributesElement = "ADDRESS"|"BIRTHDATE"|"EMAIL"|"FAMILY_NAME"|"GENDER"|"GIVEN_NAME"|"LOCALE"|"MIDDLE_NAME"|"NAME"|"NICKNAME"|"PHONE_NUMBER"|"PICTURE"|"PREFERRED_USERNAME"|"PROFILE"|"UPDATED_AT"|"WEBSITE"|"ZONE_INFO"|string; export type __boolean = boolean; export type __double = number; export type __integerMin1Max25 = number; export type ListOfBackendAPIAuthType = BackendAPIAuthType[]; export type ListOfBackendJobRespObj = BackendJobRespObj[]; export type ListOfAdditionalConstraintsElement = AdditionalConstraintsElement[]; export type ListOfMfaTypesElement = MfaTypesElement[]; export type ListOfOAuthScopesElement = OAuthScopesElement[]; export type ListOfRequiredSignUpAttributesElement = RequiredSignUpAttributesElement[]; export type ListOf__string = __string[]; export type __string = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-08-11"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the AmplifyBackend client. */ export import Types = AmplifyBackend; } export = AmplifyBackend;
the_stack
import * as github from '@actions/github' import * as core from '@actions/core' import { Context } from '@actions/github/lib/context' import * as handler from '../src/handler' jest.mock('@actions/core') jest.mock('@actions/github') describe('handlePullRequest', () => { let context: Context beforeEach(async () => { context = { eventName: '', workflow: '', action: '', actor: '', payload: { action: 'opened', number: '1', pull_request: { number: 1, labels: [], title: 'test', user: { login: 'pr-creator', }, }, repository: { name: 'auto-assign', owner: { login: 'kentaro-m', }, }, }, repo: { owner: 'kentaro-m', repo: 'auto-assign', }, issue: { owner: 'kentaro-m', repo: 'auto-assign', number: 1, }, sha: '', ref: '', } }) test('responds with an error if the webhook payload is not exist', async () => { delete context.payload.pull_request const client = new github.GitHub('token') const config = { addAssignees: true, addReviewers: true, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], skipKeywords: ['wip'], } as any expect(handler.handlePullRequest(client, context, config)).rejects.toThrow( 'the webhook payload is not exist' ) }) test('exits the process if pull requests include skip words in the title', async () => { const spy = jest.spyOn(core, 'info') context.payload.pull_request.title = 'wip test' const client = new github.GitHub('token') const config = { addAssignees: true, addReviewers: true, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], skipKeywords: ['wip'], } as any await handler.handlePullRequest(client, context, config) expect(spy.mock.calls[0][0]).toEqual( 'Skips the process to add reviewers/assignees since PR title includes skip-keywords' ) }) test.each` runOnDraft ${true} ${false} `('skips drafts', async ({ runOnDraft }) => { const spy = jest.spyOn(core, 'info') context.payload.pull_request.draft = true const client = new github.GitHub('token') const config = { addAssignees: true, addReviewers: true, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], skipKeywords: ['wip'], runOnDraft, } as any await handler.handlePullRequest(client, context, config) runOnDraft ? expect(spy.mock.calls[0][0]).not.toEqual( 'Skips the process to add reviewers/assignees since PR type is draft' ) : expect(spy.mock.calls[0][0]).toEqual( 'Skips the process to add reviewers/assignees since PR type is draft' ) }) test('adds reviewers to pull requests if the configuration is enabled, but no assignees', async () => { const config = { addAssignees: false, addReviewers: true, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3', 'pr-creator'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy).not.toBeCalled() expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(3) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /reviewer/ ) }) test('adds pr-creator as assignee if addAssignees is set to author', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: 'author', } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(1) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch('pr-creator') expect(createReviewRequestSpy).not.toBeCalled() }) test('responds with error if addAssignees is not set to boolean or author', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any // GIVEN const config = { addAssignees: 'test', } as any try { await handler.handlePullRequest(client, context, config) } catch (error) { expect(error).toEqual( new Error( "Error in configuration file to do with using addAssignees. Expected 'addAssignees' variable to be either boolean or 'author'" ) ) } }) test('adds reviewers to assignees to pull requests if the configuration is enabled ', async () => { const config = { addAssignees: true, addReviewers: false, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3', 'pr-creator'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(3) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/reviewer/) expect(addAssigneesSpy.mock.calls[0][0].assignees).toEqual( expect.arrayContaining(['reviewer1', 'reviewer2', 'reviewer3']) ) expect(createReviewRequestSpy).not.toBeCalled() }) test('adds assignees to pull requests if the assigness are enabled explicitly', async () => { const config = { addAssignees: true, addReviewers: false, assignees: ['assignee1', 'pr-creator'], numberOfAssignees: 2, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(1) expect(addAssigneesSpy.mock.calls[0][0].assignees).toEqual( expect.arrayContaining(['assignee1']) ) expect(createReviewRequestSpy).not.toBeCalled() }) test('adds assignees to pull requests using the numberOfReviewers when numberOfAssignees is unspecified', async () => { const config = { addAssignees: true, addReviewers: true, assignees: ['assignee1', 'assignee2', 'assignee3'], numberOfReviewers: 2, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(2) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/assignee/) expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(2) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /reviewer/ ) }) test("doesn't add assignees if the reviewers contain only a pr creator and assignees are not explicit", async () => { const config = { addAssignees: true, addReviewers: true, numberOfReviewers: 0, reviewers: ['pr-creator'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy).not.toHaveBeenCalled() expect(createReviewRequestSpy).not.toHaveBeenCalled() }) test('adds assignees to pull requests if throws error to add reviewers', async () => { const config = { addAssignees: true, addReviewers: true, assignees: ['maintainerX', 'maintainerY'], numberOfReviewers: 0, reviewers: ['reviewerA', 'reviewerB'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { // tslint:disable-next-line:no-empty addAssignees: jest.fn().mockImplementation(async () => {}), } as any client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => { throw new Error('Review cannot be requested from pull request author.') }), } as any const spy = jest.spyOn(client.issues, 'addAssignees') await handler.handlePullRequest(client, context, config) expect(spy.mock.calls[0][0].assignees).toHaveLength(2) expect(spy.mock.calls[0][0].assignees[0]).toMatch(/maintainer/) }) test('adds reviewers to pull requests if throws error to add assignees', async () => { const config = { addAssignees: true, addReviewers: true, assignees: ['maintainerX', 'maintainerY'], numberOfReviewers: 0, reviewers: ['reviewerA', 'reviewerB'], skipKeywords: ['wip'], } as any const client = new github.GitHub('token') client.issues = { addAssignees: jest.fn().mockImplementation(async () => { throw new Error('failed to add assignees.') }), } as any client.pulls = { // tslint:disable-next-line:no-empty createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const spy = jest.spyOn(client.pulls, 'createReviewRequest') await handler.handlePullRequest(client, context, config) expect(spy.mock.calls[0][0].reviewers).toHaveLength(2) expect(spy.mock.calls[0][0].reviewers[0]).toMatch(/reviewer/) }) /* * If 'useReviewGroups' == true, then use the 'groups' object to select reviewers and assignees. * The new functionality will still decide to add reviewers and assignees based on the 'addReviewers' * and 'addAssignees' flags. * * Use Cases for group reviews: * - if the groups are not present or an empty list, then use normal reviewer functionality * - if 'addReviewers' == true * - if #reviewers is 0, follow default behavior (add all users to review) * - if #reviewers is > 0, select #reviewers randomly (exclude self) from each group * + if #peopleInGroup is < #reviewers, select all people in that group to review * * - if 'addAssignees' == true * - var assignees = #reviewers || #assignees * - if assignees is 0, follow default behavior (add all users to review) * - if assignees is > 0, select assignees randomly (exclude self) from each group * - if #peopleInGroup is < assignees, select all people in that group to be assignees */ test('responds with the error if review groups are enabled, but no reviewGroups variable is defined in configuration', async () => { try { // GIVEN const config = { useReviewGroups: true, } as any const client = new github.GitHub('token') // WHEN await handler.handlePullRequest(client, context, config) } catch (error) { // THEN expect(error).toEqual( new Error( "Error in configuration file to do with using review groups. Expected 'reviewGroups' variable to be set because the variable 'useReviewGroups' = true." ) ) } }) test('responds with the error if assignee groups are enabled, but no assigneeGroups variable is defined in configuration', async () => { try { // GIVEN const config = { useAssigneeGroups: true, } as any const client = new github.GitHub('token') // WHEN await handler.handlePullRequest(client, context, config) } catch (error) { // THEN expect(error).toEqual( new Error( "Error in configuration file to do with using review groups. Expected 'assigneeGroups' variable to be set because the variable 'useAssigneeGroups' = true." ) ) } }) test('adds reviewers to pull request from reviewers if groups are enabled and empty', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: false, addReviewers: true, useReviewGroups: true, numberOfReviewers: 1, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], reviewGroups: [], } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(1) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /reviewer/ ) expect(addAssigneesSpy).not.toBeCalled() }) test('adds reviewers to pull request from two different groups if review groups are enabled', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: false, addReviewers: true, useReviewGroups: true, numberOfReviewers: 1, reviewGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1', 'group2-user2', 'group2-user3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(2) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /group1/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[1]).toMatch( /group2/ ) expect(addAssigneesSpy).not.toBeCalled() }) test('adds all reviewers from a group that has less members than the number of reviews requested', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: false, addReviewers: true, useReviewGroups: true, numberOfReviewers: 2, reviewGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(3) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /group1/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[1]).toMatch( /group1/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[2]).toMatch( /group2-user1/ ) expect(addAssigneesSpy).not.toBeCalled() }) test('adds assignees to pull request from two different groups if groups are enabled and number of assignees is specified', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: true, addReviewers: false, useAssigneeGroups: true, numberOfAssignees: 1, numberOfReviewers: 2, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], assigneeGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1'], groupC: ['group3-user1', 'group3-user2', 'group3-user3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(3) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/group1/) expect(addAssigneesSpy.mock.calls[0][0].assignees[1]).toMatch(/group2/) expect(addAssigneesSpy.mock.calls[0][0].assignees[2]).toMatch(/group3/) expect(createReviewRequestSpy).not.toBeCalled() }) test('adds assignees to pull request from two different groups using numberOfReviewers if groups are enabled and number of assignees is not specified', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: true, addReviewers: false, useAssigneeGroups: true, numberOfReviewers: 1, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], assigneeGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1'], groupC: ['group3-user1', 'group3-user2', 'group3-user3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(3) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/group1/) expect(addAssigneesSpy.mock.calls[0][0].assignees[1]).toMatch(/group2/) expect(addAssigneesSpy.mock.calls[0][0].assignees[2]).toMatch(/group3/) expect(createReviewRequestSpy).not.toBeCalled() }) test('adds assignees to pull request from two different groups and reviewers are not specified', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: true, addReviewers: false, useAssigneeGroups: true, numberOfAssignees: 1, numberOfReviewers: 2, assigneeGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1'], groupC: ['group3-user1', 'group3-user2', 'group3-user3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(3) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/group1/) expect(addAssigneesSpy.mock.calls[0][0].assignees[1]).toMatch(/group2/) expect(addAssigneesSpy.mock.calls[0][0].assignees[2]).toMatch(/group3/) expect(createReviewRequestSpy).not.toBeCalled() }) test('adds normal reviewers and assignees from groups into the pull request', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: true, addReviewers: true, useAssigneeGroups: true, numberOfAssignees: 1, numberOfReviewers: 2, reviewers: ['reviewer1', 'reviewer2', 'reviewer3'], assigneeGroups: { groupA: ['group1-user1', 'group1-user2', 'group1-user3'], groupB: ['group2-user1'], groupC: ['group3-user1', 'group3-user2', 'group3-user3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(3) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/group1/) expect(addAssigneesSpy.mock.calls[0][0].assignees[1]).toMatch(/group2/) expect(addAssigneesSpy.mock.calls[0][0].assignees[2]).toMatch(/group3/) expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(2) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /reviewer/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[1]).toMatch( /reviewer/ ) }) test('adds normal assignees and reviewers from groups into the pull request', async () => { const client = new github.GitHub('token') // MOCKS client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) client.issues = { addAssignees: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') // GIVEN const config = { addAssignees: true, addReviewers: true, useReviewGroups: true, numberOfAssignees: 1, numberOfReviewers: 2, assignees: ['assignee1', 'assignee2', 'assignee3'], reviewGroups: { groupA: ['group1-reviewer1', 'group1-reviewer2', 'group1-reviewer3'], groupB: ['group2-reviewer1'], groupC: ['group3-reviewer1', 'group3-reviewer2', 'group3-reviewer3'], }, } as any // WHEN await handler.handlePullRequest(client, context, config) // THEN expect(addAssigneesSpy.mock.calls[0][0].assignees).toHaveLength(1) expect(addAssigneesSpy.mock.calls[0][0].assignees[0]).toMatch(/assignee/) expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(5) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /group1-reviewer/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[2]).toMatch( /group2-reviewer/ ) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[3]).toMatch( /group3-reviewer/ ) }) test('skips pull requests that do not have any of the filterLabels.include labels', async () => { const spy = jest.spyOn(core, 'info') const client = new github.GitHub('token') const config = { filterLabels: { include: ['test_label'] }, } as any context.payload.pull_request.labels = [{ name: 'some_label' }] await handler.handlePullRequest(client, context, config) expect(spy.mock.calls[0][0]).toEqual( 'Skips the process to add reviewers/assignees since PR is not tagged with any of the filterLabels.include' ) }) test('skips pull requests that have any of the filterLabels.exclude labels', async () => { const spy = jest.spyOn(core, 'info') const client = new github.GitHub('token') const config = { filterLabels: { include: ['test_label'], exclude: ['wip'] }, } as any context.payload.pull_request.labels = [ { name: 'test_label' }, { name: 'wip' }, ] await handler.handlePullRequest(client, context, config) expect(spy.mock.calls[0][0]).toEqual( 'Skips the process to add reviewers/assignees since PR is tagged with any of the filterLabels.exclude' ) }) test('adds reviewers to the pull request when it has any of the configured labels', async () => { const config = { addAssignees: false, addReviewers: true, filterLabels: { include: ['some_label', 'another_label'] }, numberOfReviewers: 0, reviewers: ['reviewer1', 'reviewer2', 'reviewer3', 'pr-creator'], } as any const client = new github.GitHub('token') context.payload.pull_request.labels = [{ name: 'some_label' }] client.pulls = { createReviewRequest: jest.fn().mockImplementation(async () => {}), } as any const addAssigneesSpy = jest.spyOn(client.issues, 'addAssignees') const createReviewRequestSpy = jest.spyOn( client.pulls, 'createReviewRequest' ) await handler.handlePullRequest(client, context, config) expect(addAssigneesSpy).not.toBeCalled() expect(createReviewRequestSpy.mock.calls[0][0].reviewers).toHaveLength(3) expect(createReviewRequestSpy.mock.calls[0][0].reviewers[0]).toMatch( /reviewer/ ) }) })
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 // WARNING: At the breakpoint, the extension will be in an inactivate state (i.e., if you make changes in the editor, diagnostics, // formatting, etc. will not be updated until you F5 again) import * as assert from 'assert'; import * as fse from 'fs-extra'; import * as vscode from "vscode"; // tslint:disable-next-line:no-duplicate-imports import { window, workspace } from "vscode"; import { IAzureUserInput, PromptResult } from 'vscode-azureextensionui'; import { DeploymentTemplateDoc, InsertItem, TemplateSectionType } from '../../extension.bundle'; import { getActionContext } from '../support/getActionContext'; import { getTempFilePath } from "../support/getTempFilePath"; import { removeApiVersions } from '../support/removeApiVersions'; import { testWithRealSnippets } from '../support/TestSnippets'; suite("InsertItem", async (): Promise<void> => { function assertTemplate(actual: string, expected: string, textEditor: vscode.TextEditor, options?: { ignoreWhiteSpace?: boolean; ignoreApiVersions?: boolean }): void { if (textEditor.options.insertSpaces === true) { expected = expected.replace(/ {4}/g, ' '.repeat(Number(textEditor.options.tabSize))); if (options?.ignoreWhiteSpace) { expected = expected.replace(/ +/g, ' '); actual = actual.replace(/ +/g, ' '); } } else { expected = expected.replace(/ {4}/g, '\t'); if (options?.ignoreWhiteSpace) { expected = expected.replace(/\t+/g, '\t'); actual = actual.replace(/\t+/g, '\t'); } } if (textEditor.document.eol === vscode.EndOfLine.CRLF) { expected = expected.replace(/\n/g, '\r\n'); } if (options?.ignoreApiVersions) { actual = removeApiVersions(actual); expected = removeApiVersions(expected); } assert.strictEqual(actual, expected); } function testInsertItem(template: string, expected: string, action: (insertItem: InsertItem, deploymentTemplate: DeploymentTemplateDoc, textEditor: vscode.TextEditor) => Promise<void>, showInputBox: string[], textToInsert: string = '', ignoreWhiteSpace: boolean = false): void { testWithRealSnippets("Tabs CRLF", async () => { await testInsertItemWithSettings(template, expected, false, 4, true, action, showInputBox, textToInsert, ignoreWhiteSpace); }); testWithRealSnippets("Spaces CRLF", async () => { await testInsertItemWithSettings(template, expected, true, 4, true, action, showInputBox, textToInsert, ignoreWhiteSpace); }); testWithRealSnippets("Spaces (2) CRLF", async () => { await testInsertItemWithSettings(template, expected, true, 2, true, action, showInputBox, textToInsert, ignoreWhiteSpace); }); testWithRealSnippets("Spaces LF", async () => { await testInsertItemWithSettings(template, expected, true, 4, false, action, showInputBox, textToInsert, ignoreWhiteSpace); }); testWithRealSnippets("Tabs LF", async () => { await testInsertItemWithSettings(template, expected, false, 4, false, action, showInputBox, textToInsert, ignoreWhiteSpace); }); testWithRealSnippets("Spaces (2) LF", async () => { await testInsertItemWithSettings(template, expected, true, 2, false, action, showInputBox, textToInsert, ignoreWhiteSpace); }); } async function testInsertItemWithSettings(template: string, expected: string, insertSpaces: boolean, tabSize: number, eolAsCRLF: boolean, action: (insertItem: InsertItem, deploymentTemplate: DeploymentTemplateDoc, textEditor: vscode.TextEditor) => Promise<void>, showInputBox: string[], textToInsert: string = '', ignoreWhiteSpace: boolean = false): Promise<void> { if (eolAsCRLF) { template = template.replace(/\n/g, '\r\n'); } if (insertSpaces && tabSize !== 4) { template = template.replace(/ {4}/g, ' '.repeat(tabSize)); } if (!insertSpaces) { template = template.replace(/ {4}/g, '\t'); } const tempPath = getTempFilePath(`insertItem`, '.azrm'); fse.writeFileSync(tempPath, template); let document = await workspace.openTextDocument(tempPath); let textEditor = await window.showTextDocument(document); let ui = new MockUserInput(showInputBox); let insertItem = new InsertItem(ui); let deploymentTemplate = new DeploymentTemplateDoc(document.getText(), document.uri, document.version); await action(insertItem, deploymentTemplate, textEditor); await textEditor.edit(builder => builder.insert(textEditor.selection.active, textToInsert)); const docTextAfterInsertion = document.getText(); assertTemplate(docTextAfterInsertion, expected, textEditor, { ignoreWhiteSpace, ignoreApiVersions: true }); } const totallyEmptyTemplate = `{}`; function createInsertItemTests(startTemplate: string, expectedTemplate: string, sectionType: TemplateSectionType, showInputBox: string[] = [], textToInsert: string = '', ignoreWhiteSpace: boolean = false): void { testInsertItem(startTemplate, expectedTemplate, async (insertItem, template, editor) => await insertItem.insertItem(template, sectionType, editor, getActionContext()), showInputBox, textToInsert, ignoreWhiteSpace); } suite("Variables", async () => { const emptyTemplate = `{ "variables": {} }`; const oneVariableTemplate = `{ "variables": { "variable1": "[resourceGroup()]" } }`; const twoVariablesTemplate = `{ "variables": { "variable1": "[resourceGroup()]", "variable2": "[resourceGroup()]" } }`; const threeVariablesTemplate = `{ "variables": { "variable1": "[resourceGroup()]", "variable2": "[resourceGroup()]", "variable3": "[resourceGroup()]" } }`; suite("Insert one variable", async () => { createInsertItemTests(emptyTemplate, oneVariableTemplate, TemplateSectionType.Variables, ["variable1"], 'resourceGroup()'); }); suite("Insert one more variable", async () => { createInsertItemTests(oneVariableTemplate, twoVariablesTemplate, TemplateSectionType.Variables, ["variable2"], 'resourceGroup()'); }); suite("Insert even one more variable", async () => { createInsertItemTests(twoVariablesTemplate, threeVariablesTemplate, TemplateSectionType.Variables, ["variable3"], 'resourceGroup()'); }); suite("Insert one variable in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneVariableTemplate, TemplateSectionType.Variables, ["variable1"], 'resourceGroup()'); }); }); suite("Resources", async () => { const emptyTemplate = `{ "resources": [] }`; const oneResourceTemplate = `{ "resources": [ { "name": "keyVault1/keyVaultSecret1", "type": "Microsoft.KeyVault/vaults/secrets", "apiVersion": "xxxx-xx-xx", "properties": { "value": "secretValue" } } ] }`; const twoResourcesTemplate = `{ "resources": [ { "name": "keyVault1/keyVaultSecret1", "type": "Microsoft.KeyVault/vaults/secrets", "apiVersion": "xxxx-xx-xx", "properties": { "value": "secretValue" } }, { "name": "applicationSecurityGroup1", "type": "Microsoft.Network/applicationSecurityGroups", "apiVersion": "xxxx-xx-xx", "location": "[resourceGroup().location]", "tags": {}, "properties": {} } ] }`; suite("Insert one resource (KeyVault Secret) into totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneResourceTemplate, TemplateSectionType.Resources, ["KeyVault Secret"], '', true); }); suite("Insert one resource (KeyVault Secret)", async () => { createInsertItemTests(emptyTemplate, oneResourceTemplate, TemplateSectionType.Resources, ["KeyVault Secret"], '', true); }); suite("Insert one more resource (Application Security Group)", async () => { createInsertItemTests(oneResourceTemplate, twoResourcesTemplate, TemplateSectionType.Resources, ["Application Security Group"], '', true); }); }); suite("Functions", async () => { const emptyTemplate = `{ "functions": [] }`; const namespaceTemplate = `{ "functions": [ { "namespace": "ns" } ] }`; const membersTemplate = `{ "functions": [ { "namespace": "ns", "members": {} } ] }`; const oneFunctionTemplate = `{ "functions": [ { "namespace": "ns", "members": { "function1": { "parameters": [ { "name": "parameter1", "type": "string" } ], "output": { "type": "string", "value": "[resourceGroup()]" } } } } ] }`; const twoFunctionsTemplate = `{ "functions": [ { "namespace": "ns", "members": { "function1": { "parameters": [ { "name": "parameter1", "type": "string" } ], "output": { "type": "string", "value": "[resourceGroup()]" } }, "function2": { "parameters": [], "output": { "type": "string", "value": "[resourceGroup()]" } } } } ] }`; const threeFunctionsTemplate = `{ "functions": [ { "namespace": "ns", "members": { "function1": { "parameters": [ { "name": "parameter1", "type": "string" } ], "output": { "type": "string", "value": "[resourceGroup()]" } }, "function2": { "parameters": [], "output": { "type": "string", "value": "[resourceGroup()]" } }, "function3": { "parameters": [ { "name": "parameter1", "type": "string" }, { "name": "parameter2", "type": "bool" } ], "output": { "type": "securestring", "value": "[resourceGroup()]" } } } } ] }`; suite("Insert function", async () => { createInsertItemTests(emptyTemplate, oneFunctionTemplate, TemplateSectionType.Functions, ["ns", "function1", "String", "parameter1", "String", ""], "resourceGroup()"); }); suite("Insert one more function", async () => { createInsertItemTests(oneFunctionTemplate, twoFunctionsTemplate, TemplateSectionType.Functions, ["function2", "String", ""], "resourceGroup()"); }); suite("Insert one function in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneFunctionTemplate, TemplateSectionType.Functions, ["ns", "function1", "String", "parameter1", "String", ""], "resourceGroup()"); }); suite("Insert function in namespace", async () => { createInsertItemTests(namespaceTemplate, oneFunctionTemplate, TemplateSectionType.Functions, ["function1", "String", "parameter1", "String", ""], "resourceGroup()"); }); suite("Insert function in members", async () => { createInsertItemTests(membersTemplate, oneFunctionTemplate, TemplateSectionType.Functions, ["function1", "String", "parameter1", "String", ""], "resourceGroup()"); }); suite("Insert even one more function", async () => { createInsertItemTests(twoFunctionsTemplate, threeFunctionsTemplate, TemplateSectionType.Functions, ["function3", "Secure string", "parameter1", "String", "parameter2", "Bool", ""], "resourceGroup()"); }); }); suite("Parameters", async () => { const emptyTemplate = `{ "parameters": {} }`; const oneParameterTemplate = `{ "parameters": { "parameter1": { "type": "string", "defaultValue": "default", "metadata": { "description": "description" } } } }`; const twoParametersTemplate = `{ "parameters": { "parameter1": { "type": "string", "defaultValue": "default", "metadata": { "description": "description" } }, "parameter2": { "type": "string" } } }`; const threeParametersTemplate = `{ "parameters": { "parameter1": { "type": "string", "defaultValue": "default", "metadata": { "description": "description" } }, "parameter2": { "type": "string" }, "parameter3": { "type": "securestring", "metadata": { "description": "description3" } } } }`; const oneParameterTemplateInt = `{ "parameters": { "parameter1": { "type": "int", "defaultValue": 42 } } }`; const oneParameterTemplateArray = `{ "parameters": { "parameter1": { "type": "array", "defaultValue": [] } } }`; const oneParameterTemplateBool = `{ "parameters": { "parameter1": { "type": "bool", "defaultValue": true } } }`; const oneParameterTemplateObject = `{ "parameters": { "parameter1": { "type": "object", "defaultValue": {} } } }`; const oneParameterTemplateSecureObject = `{ "parameters": { "parameter1": { "type": "secureobject", "defaultValue": {} } } }`; suite("Insert one parameter", async () => { createInsertItemTests(emptyTemplate, oneParameterTemplate, TemplateSectionType.Parameters, ["parameter1", "String", "default", "description"]); }); suite("Insert one more parameter", async () => { createInsertItemTests(oneParameterTemplate, twoParametersTemplate, TemplateSectionType.Parameters, ["parameter2", "String", "", ""]); }); suite("Insert even one more parameter", async () => { createInsertItemTests(twoParametersTemplate, threeParametersTemplate, TemplateSectionType.Parameters, ["parameter3", "Secure string", "", "description3"]); }); suite("Insert one parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplate, TemplateSectionType.Parameters, ["parameter1", "String", "default", "description"]); }); suite("Insert one int parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplateInt, TemplateSectionType.Parameters, ["parameter1", "Int", "42", ""]); }); suite("Insert one array parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplateArray, TemplateSectionType.Parameters, ["parameter1", "Array", "[]", ""]); }); suite("Insert one bool parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplateBool, TemplateSectionType.Parameters, ["parameter1", "Bool", "true", ""]); }); suite("Insert one object parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplateObject, TemplateSectionType.Parameters, ["parameter1", "Object", "{}", ""]); }); suite("Insert one secure object parameter in totally empty template", async () => { createInsertItemTests(totallyEmptyTemplate, oneParameterTemplateSecureObject, TemplateSectionType.Parameters, ["parameter1", "Secure object", "{}", ""]); }); }); suite("Outputs", async () => { const emptyTemplate = `{ "outputs": {} }`; const oneOutputTemplate = `{ "outputs": { "output1": { "type": "string", "value": "[resourceGroup()]" } } }`; const twoOutputsTemplate = `{ "outputs": { "output1": { "type": "string", "value": "[resourceGroup()]" }, "output2": { "type": "string", "value": "[resourceGroup()]" } } }`; const threeOutputsTemplate = `{ "outputs": { "output1": { "type": "string", "value": "[resourceGroup()]" }, "output2": { "type": "string", "value": "[resourceGroup()]" }, "output3": { "type": "securestring", "value": "[resourceGroup()]" } } }`; suite("Insert one output", async () => { createInsertItemTests(emptyTemplate, oneOutputTemplate, TemplateSectionType.Outputs, ["output1", "String"], 'resourceGroup()'); }); suite("Insert one more output", async () => { createInsertItemTests(oneOutputTemplate, twoOutputsTemplate, TemplateSectionType.Outputs, ["output2", "String"], 'resourceGroup()'); }); suite("Insert even one more output", async () => { createInsertItemTests(twoOutputsTemplate, threeOutputsTemplate, TemplateSectionType.Outputs, ["output3", "Secure string"], 'resourceGroup()'); }); suite("Insert one output in totally empty template", async () => { createInsertItemTests(emptyTemplate, oneOutputTemplate, TemplateSectionType.Outputs, ["output1", "String"], 'resourceGroup()'); }); }); }); // CONSIDER: Switch to using TestUserInput from vscode-azureextensiondev class MockUserInput implements IAzureUserInput { private showInputBoxTexts: string[] = []; private _onDidFinishPromptEmitter: vscode.EventEmitter<PromptResult> = new vscode.EventEmitter<PromptResult>(); constructor(showInputBox: string[]) { this.showInputBoxTexts = Object.assign([], showInputBox); } public get onDidFinishPrompt(): vscode.Event<PromptResult> { return this._onDidFinishPromptEmitter.event; } public async showQuickPick<T extends vscode.QuickPickItem>(items: T[] | Thenable<T[]>, options: import("vscode-azureextensionui").IAzureQuickPickOptions): Promise<T> { let result = await items; let label = this.showInputBoxTexts.shift()!; let item = result.find(x => x.label === label)!; return item; } public async showInputBox(options: vscode.InputBoxOptions): Promise<string> { return this.showInputBoxTexts.shift()!; } public async showWarningMessage<T extends vscode.MessageItem>(message: string, options: import("vscode-azureextensionui").IAzureMessageOptions, ...items: T[]): Promise<T> { return items[0]; } public async showOpenDialog(options: vscode.OpenDialogOptions): Promise<vscode.Uri[]> { return [vscode.Uri.file("c:\\some\\path")]; } }
the_stack
import last from 'lodash-es/last'; import { warn } from '../../utils/utils'; const SWIND_API_REGEX = /^swind/; export class CSSGen { // stores the theme config object private config: any; // classes which need no regex matching private staticClasses = { container: 'width: 100%;', clearfix: `content: ""; display: table; clear: both;`, // font smoothing antialiased: `-webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;`, 'subpixel-antialiased': `-webkit-font-smoothing: auto; -moz-osx-font-smoothing: auto;`, 'break-normal': `overflow-wrap: normal; word-break: normal;`, 'break-words': `overflow-wrap: break-word;`, 'break-all': `word-break: break-all;`, truncate: `overflow: hidden; text-overflow: ellipsis; white-space: nowrap;`, 'box-border': 'box-sizing: border-box;', 'box-content': 'box-sizing: content-box;', hidden: 'display: none;', block: 'display: block;', inline: 'display: inline;', 'inline-block': 'display: inline-block;', flex: 'display: flex;', 'inline-flex': 'display: inline-flex;', table: 'display: table-cell;', 'table-column': 'display: table-column;', 'table-column-group': 'display: table-column-group;', 'table-footer-group': 'display: table-footer-group;', 'table-header-group': 'display: table-header-group;', 'table-row-group': 'display: table-row-group;', 'table-row': 'display: table-row;', 'flow-root': 'display: flow-root;', grid: 'display: grid;', static: 'position: static;', fixed: 'position: fixed;', absolute: 'position: absolute;', relative: 'position: relative;', sticky: 'position: sticky;', visible: 'visibility: visible;', invisible: 'visibility: hidden;', italic: 'font-style: italic;', 'non-italic': 'font-style: normal;', underline: 'text-decoration: underline;', 'line-through': 'text-decoration: line-through;', 'no-underline': 'text-decoration: none;', uppercase: 'text-transform: uppercase;', lowercase: 'text-transform: lowercase;', capitalize: 'text-transform: capitalize;', 'normal-case': 'text-transform: none;', 'sr-only': `position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0;`, 'not-sr-only': `position: static; width: auto; height: auto; padding: 0; margin: 0; overflow: visible; clip: auto; white-space: normal;`, 'inset-0': `top: 0; right: 0; bottom: 0; left: 0;`, 'inset-y-0': `top: 0; bottom: 0;`, 'inset-x-0': `right: 0; left: 0;`, 'inset-auto': ` top: auto; right: auto; bottom: auto; left: auto;`, 'inset-x-auto': `right: auto; left: auto;`, 'inset-y-auto': `top: auto; bottom: auto;`, 'flex-shrink': `flex-shrink: 1;`, 'flex-shrink-0': `flex-shrink: 0;`, 'flex-grow': `flex-grow: 1;`, 'flex-grow-0': `flex-shrink: 0;`, 'object-contain': 'object-fit: contain;', 'object-cover': 'object-fit: cover;', 'object-fill': 'object-fit: fill;', 'object-none': 'object-fit: none;', 'object-scale-down': 'object-fit: scale-down;', 'object-bottom': 'object-position: bottom;', 'object-center': 'object-position: center;', 'object-left': 'object-position: left;', 'object-left-bottom': 'object-position: left bottom;', 'object-left-top': 'object-position: left top;', 'object-right': 'object-position: right;', 'object-right-bottom': 'object-position: right bottom;', 'object-right-top': 'object-position: right top;', 'object-top': 'object-position: top;', 'bg-fixed': 'background-attachment: fixed;', 'bg-local': 'background-attachment: local;', 'bg-scroll': 'background-attachment: scroll;', 'bg-bottom': 'background-position: bottom;', 'bg-center': 'background-position: center;', 'bg-left': 'background-position: center;', 'bg-left-bottom': 'background-position: center;', 'bg-left-top': 'background-position: center;', 'bg-right': 'background-position: center;', 'bg-right-bottom': 'background-position: center;', 'bg-right-top': 'background-position: center;', 'bg-top': 'background-position: top;', 'bg-repeat': 'background-repeat: repeat;', 'bg-no-repeat': 'background-repeat: no-repeat;', 'bg-repeat-x': 'background-repeat: repeat-x;', 'bg-repeat-y': 'background-repeat: repeat-y;', 'bg-repeat-round': 'background-repeat: repeat-round;', 'bg-repeat-space': 'background-repeat: space;', 'bg-auto': 'background-size: auto;', 'bg-cover': 'background-size: cover;', 'bg-contain': 'background-size: contain;', 'flex-row': 'flex-direction: row;', 'flex-row-reverse': 'flex-direction: row;', 'flex-col': 'flex-direction: column;', 'flex-col-reverse': 'flex-direction: column-reverse;', 'flex-wrap': 'flex-wrap: wrap;', 'flex-wrap-reverse': 'flex-wrap: wrap-reverse;', 'flex-no-wrap': 'flex-wrap: nowrap;', 'items-stretch': 'align-items: stretch;', 'items-start': 'align-items: flex-start;', 'items-center': 'align-items: center;', 'items-end': 'align-items: flex-end;', 'items-baseline': 'align-items: baseline;', 'content-start': 'align-content: flex-start;', 'content-center': 'align-content: center;', 'content-end': 'align-content: flex-end;', 'content-between': 'align-content: space-between;', 'content-around': 'align-content: space-around;', 'self-auto': 'align-self: auto;', 'self-start': 'align-self: flex-start;', 'self-end': 'align-self: flex-end;', 'self-center': 'align-self: center;', 'self-stretch': 'align-self: stretch;', 'justify-start': 'justify-content: flex-start;', 'justify-end': 'justify-content: flex-end;', 'justify-center': 'justify-content: center;', 'justify-between': 'justify-content: space-between;', 'justify-around': 'justify-content: space-around;', 'justify-evenly': 'justify-content: space-evenly;', border: 'border-width: 1px;', 'border-solid': 'border-style: solid;', 'border-dashed': 'border-style: dashed;', 'border-dotted': 'border-style: dotted;', 'border-double': 'border-style: double;', 'border-none': 'border-style: none;', 'border-transparent': 'border-color: transparent;', 'border-current': 'border-color: currentColor;', 'select-none': 'user-select: none;', 'select-text': 'user-select: text;', 'select-all': 'user-select: all;', 'select-auto': 'user-select: auto;', 'border-collapse': 'border-collapse: collapse;', 'border-separate': 'border-collapse: separate;', 'shadow-xs': 'box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05);', 'shadow-sm': 'box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);', shadow: 'box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);', 'shadow-md': 'box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);', 'shadow-lg': 'box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);', 'shadow-xl': 'box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);', 'shadow-2xl': 'box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);', 'shadow-inner': 'box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06);', 'shadow-outline': 'box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5);', 'shadow-none': 'box-shadow: none;', 'font-sans': 'font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";', 'font-serif': 'font-family: Georgia, Cambria, "Times New Roman", Times, serif;', 'font-mono': 'font-family: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;', 'list-none': 'list-style-type: none;', 'list-disc': 'list-style-type: disc;', 'list-decimal': 'list-style-type: decimal;', 'list-inside': 'list-style-position: inside;', 'list-outside': 'list-style-position: outside;', 'text-left': 'text-align: left;', 'text-center': 'text-align: center;', 'text-right': 'text-align: right;', 'text-justify': 'text-align: justify;', 'align-baseline': 'vertical-align: baseline;', 'align-top': 'vertical-align: top;', 'align-middle': 'vertical-align: middle;', 'align-bottom': 'vertical-align: bottom;', 'align-text-top': 'vertical-align: text-top;', 'align-text-bottom': 'vertical-align: text-bottom;', 'whitespace-normal': 'white-space: normal;', 'whitespace-no-wrap': 'white-space: nowrap;', 'whitespace-pre': 'white-space: pre;', 'whitespace-pre-line': 'white-space: pre-line;', 'whitespace-pre-wrap': 'white-space: pre-wrap;', 'resize-none': 'resize: none;', 'resize-y': 'resize: vertical;', 'resize-x': 'resize: horizontal;', resize: 'resize: both;', 'fill-current': 'fill: currentColor;', 'stroke-current': 'stroke: currentColor;', 'grid-flow-row': 'grid-auto-flow: row;', 'grid-flow-col': 'grid-auto-flow: column;', 'grid-flow-row-dense': 'grid-auto-flow: row dense;', 'grid-flow-col-dense': 'grid-auto-flow: column dense;', 'table-auto': 'table-layout: auto;', 'table-fixed': 'table-layout: fixed;' }; private staticPropertyClassesRegEx = { float: /^float-(.*)/, overflow: /^overflow-(.*)/, appearance: /^appearance-(.*)/, pointerEvents: /^pointer-events-(.*)/, top: /^top-(.*)/, bottom: /^bottom-(.*)/, right: /^right-(.*)/, left: /^left-(.*)/, clear: /^clear-(.*)/ }; private static isStyleWindClass(classNameOrStyle: string) { return ( this.usesDotNotationAPI(classNameOrStyle) || this.usesSwindAPI(classNameOrStyle) ); } private staticPropertyClasses = Object.values( this.staticPropertyClassesRegEx ); private dynamicPropertyClassesRegEx = { MARGIN: /^m(.)?-(.*)/, PADDING: /^p(.)?-(.*)/, SCALE: /^scale-(.*)/, BORDER: /^border-[0-9]/, BORDER_OPACITY: /^border-opacity-[0-9]/, BORDER_COLOR: /^border-(?!opacity)(.*)-[0-9]/, BORDER_WITH_DIRECTION: /^border-(.)-[0-9]/, TEXT_SIZE: /^text-(xs|sm|base|lg|xl|[2-9]xl)$/, TEXT_WEIGHT: /^font-(hairline|thin|light|normal|medium|semibold|bold|extrabold|black)$/, TEXT_OPACITY: /^text-opacity-[0-9]/, TEXT_COLOR: /^text-(?!opacity)(.*)/, PLACEHOLDER_OPACITY: /^placeholder-opacity-[0-9]/, PLACEHOLDER_COLOR: /^placeholder-(?!opacity)(.*)/, STROKE: /^stroke-[0-9]/, LETTER_SPACING: /^tracking-(tighter|tight|normal|wide|wider|widest)/, LINE_HEIGHT: /^leading-(.*)/, OPACITY: /^opacity-[0-9]/, MAX_WIDTH: /^max-w-(.*)/, MIN_WIDTH: /^min-w-(.*)/, WIDTH: /^w-(.*)/, MAX_HEIGHT: /^max-h-(.*)/, MIN_HEIGHT: /^min-h-(.*)/, HEIGHT: /^h-(.*)/, GRID_TEMPLATE_COLS: /^grid-cols-(.*)/, GRID_TEMPLATE_ROWS: /^grid-rows-(.*)/, GRID_ROW: /^((row-(start|end|span)-(.*))|row-auto)$/, GRID_COL: /^((col-(start|end|span)-(.*))|col-auto)$/, GRID_GAP: /^gap-[0-9]/, GRID_ROW_GAP: /^row-gap-[0-9]/, GRID_COL_GAP: /^col-gap-[0-9]/, BORDER_RADIUS: /^(rounded$|(rounded-(.*)$)|(rounded-(.*)-(.*)))/, BG_OPACITY: /^bg-opacity-[0-9]/, BG: /bg-(?!opacity)(.*)/, ZINDEX: /z-(.*)/, CURSOR: /cursor-(.*)/ }; private dynamicPropertyClasses = Object.values( this.dynamicPropertyClassesRegEx ); constructor(config: any) { this.config = config; } // classes like clearfix, word-wrap etc. private hydrateStaticClasses(className: string) { return this.staticClasses[CSSGen.getClassName(className)] || className; } // float-left => flat: left; // overflow-x-hidden => overflow-x: hidden; private hydratePropertyValueClasses(className: string) { const styledClassName = CSSGen.getClassName(className); const propertyValueClass = this.staticPropertyClasses.find( (propertyValueClass) => propertyValueClass.test(styledClassName) ); if (propertyValueClass) { // overflow-x-hidden // property = overflow, valueWithProperty => x-hidden; const [property, ...valueWithProperty] = styledClassName.split('-'); // allProprty = overflow-x const allProperties = [ property, ...valueWithProperty.slice(0, valueWithProperty.length - 1) ].join('-'); return `${allProperties}: ${last(valueWithProperty)};`; } else { return className; } } // mt-10, m-10, p-10, pb-10 private hydrateDynamicPropertyClasses(className: string) { const styledClassName = CSSGen.getClassName(className); const dyanmicPopertyClass = this.dynamicPropertyClasses.find( (dynamicPropertyClass) => dynamicPropertyClass.test(styledClassName) ); if (dyanmicPopertyClass) { // scale if (styledClassName.match(this.dynamicPropertyClassesRegEx.MARGIN)) { const [, direction, value] = styledClassName.match( dyanmicPopertyClass ) as any; const themeValue = this.config.theme.margin[value]; const directionStringorArray = CSSGen.expandDirectionChar(direction); if (Array.isArray(directionStringorArray)) { return directionStringorArray.reduce((prev, direction) => { return `${prev} margin${direction}: ${themeValue}; `; }, ''); } return `margin${directionStringorArray}: ${themeValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.PADDING) ) { const [, direction, value] = styledClassName.match( dyanmicPopertyClass ) as any; const themeValue = this.config.theme.spacing[value]; const directionStringorArray = CSSGen.expandDirectionChar(direction); if (Array.isArray(directionStringorArray)) { return directionStringorArray.reduce((prev, direction) => { return `${prev} padding${direction}: ${themeValue}; `; }, ''); } return `padding${directionStringorArray}: ${themeValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.BORDER_OPACITY) ) { const [, , opacity] = styledClassName.split('-'); const opacityValue = parseInt(opacity) / 100; return `--border-opacity: ${opacityValue}`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.BORDER) || styledClassName.match( this.dynamicPropertyClassesRegEx.BORDER_WITH_DIRECTION ) ) { const props = styledClassName.split('-'); // border-10 if (props.length === 2) { const [, valueString] = props; const value = `${parseInt(valueString)}px`; return `border-width: ${value};`; } // border-t-10 or border-b-100 else if (props.length === 3) { const [, direction, valueString] = props; const value = `${parseInt(valueString)}px`; const directionStringorArray = CSSGen.expandDirectionChar(direction); if (Array.isArray(directionStringorArray)) { return directionStringorArray.reduce((prev, direction) => { return `${prev} border${direction}-width: ${value}; `; }, ''); } return `border${directionStringorArray}-width: ${value};`; } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.TEXT_SIZE) ) { const [, size] = styledClassName.split('-'); const fontSize = this.config.theme.fontSize[size]; return `font-size: ${fontSize};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.TEXT_WEIGHT) ) { const [, weight] = styledClassName.split('-'); const fontWeight = this.config.theme.fontWeight[weight]; return `font-weight: ${fontWeight};`; } else if ( styledClassName.match( this.dynamicPropertyClassesRegEx.PLACEHOLDER_OPACITY ) ) { const [, , opacity] = styledClassName.split('-'); const opacityValue = parseInt(opacity) / 100; return `::placeholder { opacity: ${opacityValue}; }`; } // for text-black, placeholder-black else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.TEXT_COLOR) || styledClassName.match( this.dynamicPropertyClassesRegEx.PLACEHOLDER_COLOR ) ) { const props = styledClassName.split('-'); // text-black, text-transparent if (props.length === 2) { const [textOrPlaceholder, colorString] = props; const colorHex = this.config.theme.colors[colorString]; return textOrPlaceholder === 'text' ? `color: ${colorHex};` : `::placeholder { color: ${colorHex}; }`; } // text-red-100, text-green-200 else if (props.length === 3) { const [textOrPlaceholder, colorString, contrast] = props; const colorHex = this.config.theme.colors[colorString][contrast]; return textOrPlaceholder === 'text' ? `color: ${colorHex};` : `::placeholder { color: ${colorHex}; }`; } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.LETTER_SPACING) ) { const [, spacing] = styledClassName.split('-'); const spacingValue = this.config.theme.letterSpacing[spacing]; return `letter-spacing: ${spacingValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.STROKE) ) { const [, value] = styledClassName.split('-'); return `stroke-width: ${value};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.LINE_HEIGHT) ) { const [, height] = styledClassName.split('-'); const lineHeight = this.config.theme.lineHeight[height]; return `line-height: ${lineHeight};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.OPACITY) ) { const [, opacity] = styledClassName.split('-'); const opacityValue = parseInt(opacity) / 100; return `opacity: ${opacityValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.TEXT_OPACITY) ) { const [, , opacity] = styledClassName.split('-'); const opacityValue = parseInt(opacity) / 100; return `opacity: ${opacityValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.BORDER_COLOR) ) { const props = styledClassName.split('-'); if (props.length === 2) { const [, color] = props; const colorHex = this.config.theme.colors[color]; return `border-color: ${colorHex};`; } else if (props.length === 3) { const [, color, contrast] = props; const colorHex = this.config.theme.colors[color][contrast]; return `border-color: ${colorHex};`; } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.MAX_WIDTH) ) { const [, , breakpoint] = styledClassName.split('-'); const size = this.config.theme.maxWidth[breakpoint]; return `max-width: ${size};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.MIN_WIDTH) ) { const [, , breakpoint] = styledClassName.split('-'); const size = this.config.theme.minWidth[breakpoint]; return `min-width: ${size};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.WIDTH) ) { const [, width] = styledClassName.split('-'); const widthValue = this.config.theme.width[width]; return `width: ${widthValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.MAX_HEIGHT) ) { const [, , breakpoint] = styledClassName.split('-'); const size = this.config.theme.maxHeight[breakpoint]; return `max-height: ${size};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.MIN_HEIGHT) ) { const [, , breakpoint] = styledClassName.split('-'); const size = this.config.theme.minHeight[breakpoint]; return `min-height: ${size};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.HEIGHT) ) { const [, height] = styledClassName.split('-'); const heightValue = this.config.theme.height[height]; return `height: ${heightValue};`; } else if ( styledClassName.match( this.dynamicPropertyClassesRegEx.GRID_TEMPLATE_COLS ) ) { const [, , templateValue] = styledClassName.split('-'); if (templateValue.trim() === 'none') { return 'grid-template-columns: none;'; } else { return `grid-template-columns: repeat(${templateValue}, minmax(0, 1fr));`; } } else if ( styledClassName.match( this.dynamicPropertyClassesRegEx.GRID_TEMPLATE_ROWS ) ) { const [, , templateValue] = styledClassName.split('-'); if (templateValue.trim() === 'none') { return 'grid-template-rows: none;'; } else { return `grid-template-rows: repeat(${templateValue}, minmax(0, 1fr));`; } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.GRID_ROW) ) { const props = styledClassName.split('-'); if (props.length === 2) { const [, value] = props; return value.trim() === 'auto' ? `grid-row: auto;` : styledClassName; } else if (props.length === 3) { const [, type, value] = props; if (type === 'span') { return `grid-row: span ${value} / span ${value};`; } else if (type === 'end' || type === 'start') { return `grid-row-${type}: ${value};`; } } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.GRID_COL) ) { const props = styledClassName.split('-'); if (props.length === 2) { const [, value] = props; return value.trim() === 'auto' ? `grid-col: auto;` : styledClassName; } else if (props.length === 3) { const [, type, value] = props; if (type === 'span') { return `grid-col: span ${value} / span ${value};`; } else if (type === 'end' || type === 'start') { return `grid-col-${type}: ${value};`; } } } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.GRID_GAP) ) { const [, gap] = styledClassName.split('-'); const gapValue = this.config.theme.gap[gap]; return `gap: ${gapValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.GRID_ROW_GAP) ) { const [, , gap] = styledClassName.split('-'); const gapValue = this.config.theme.gap[gap]; return `row-gap: ${gapValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.GRID_COL_GAP) ) { const [, , gap] = styledClassName.split('-'); const gapValue = this.config.theme.gap[gap]; return `col-gap: ${gapValue};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.BORDER_RADIUS) ) { const props = styledClassName.split('-'); const defaultRadius = this.config.theme.borderRadius.default; const directions = ['t', 'b', 'r', 'l', 'tr', 'tl', 'br', 'bl']; const getBorderRadiusForDirection = ( direction: string, radiusValue: string ) => { switch (direction) { case 't': { return ` border-top-left-radius: ${radiusValue}; border-top-right-radius: ${radiusValue}; `; } case 'b': { return ` border-bottom-right-radius: ${radiusValue}; border-bottom-left-radius: ${radiusValue}; `; } case 'l': { return ` border-top-left-radius: ${radiusValue}; border-bottom-left-radius: ${radiusValue}; `; } case 'r': { return ` border-top-right-radius: ${radiusValue}; border-bottom-right-radius: ${radiusValue}; `; } case 'tl': { return ` border-top-left-radius: ${radiusValue}; `; } case 'tr': { return ` border-top-right-radius: ${radiusValue}; `; } case 'bl': { return ` border-bottom-left-radius: ${radiusValue}; `; } case 'br': { return ` border-bottom-right-radius: ${radiusValue}; `; } default: return ''; } }; if (props.length === 1) { return `border-radius: ${defaultRadius};`; } else if (props.length === 2) { const [, sizeOrDirection] = props; if (directions.includes(sizeOrDirection.trim())) { return getBorderRadiusForDirection( sizeOrDirection.trim(), defaultRadius ); } else { const radiusValue = this.config.theme.borderRadius[sizeOrDirection]; return `border-radius: ${radiusValue};`; } } else if (props.length === 3) { const [, direction, size] = props; const radiusValue = this.config.theme.borderRadius[size]; return getBorderRadiusForDirection(direction, radiusValue); } else { return styledClassName; } } else if (styledClassName.match(this.dynamicPropertyClassesRegEx.BG)) { // color => red-500; const [, colorName, contrast] = styledClassName.split('-'); let themeColor; if (contrast) { themeColor = this.config.theme.colors[colorName][contrast]; } else { themeColor = this.config.theme.colors[colorName]; } return `background: ${themeColor};`; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.BG_OPACITY) ) { const [, , opacity] = styledClassName.split('-'); const opacityValue = parseInt(opacity) / 100; return ` opacity: ${opacityValue}; `; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.ZINDEX) ) { const [, zindex] = styledClassName.split('-'); const zindexValue = zindex !== 'auto' ? parseInt(zindex) : zindex; return ` z-index: ${zindexValue}; `; } else if ( styledClassName.match(this.dynamicPropertyClassesRegEx.CURSOR) ) { const [, cursor] = styledClassName.split('-'); const cursorValue = cursor; return ` cursor: ${cursorValue}; `; } return className; } else { return className; } } private static expandDirectionChar(direction: string) { // TODO: change this switch to if else with pattern matching switch (direction) { case 'y': return ['-top', '-bottom']; case 'x': return ['-left', '-right']; case 't': return '-top'; case 'b': return '-bottom'; case 'r': return '-right'; case 'l': return '-left'; } return ''; } private static getClassName(className: string) { if (this.usesSwindAPI(className)) { const [, classNamePart] = className.split(':'); return classNamePart.trim().split(';')[0]; } else { return className.substr(1); } } private hydrateNormalClasses(className: string): string { if (!CSSGen.isStyleWindClass(className)) return className; // it may be static class let css = this.hydrateStaticClasses(className); if (CSSGen.isStyleWindClass(css)) { // if it is not static it may be property value type css = this.hydratePropertyValueClasses(className); // fuck it, it must be atleast dynamic property class if (CSSGen.isStyleWindClass(css)) { css = this.hydrateDynamicPropertyClasses(className); } } if (CSSGen.isStyleWindClass(css)) { // well we did our best but we don't support this class name warn(`unknown class name ${css}`); } return css; } private hydratePseudoClasses(pseudoClass: string) { if (!CSSGen.isStyleWindClass(pseudoClass)) return `${pseudoClass};`; const sm = this.config.theme.screens.sm; const md = this.config.theme.screens.md; const lg = this.config.theme.screens.lg; const [prefix, className] = CSSGen.getPseudoAndClassName(pseudoClass); switch (prefix.trim()) { case 'hover': { const hydratedHoverClasses = this.hydrateNormalClasses( `.${className.trim()}` ); return `&:hover { ${hydratedHoverClasses} }`; } case 'active': { const hydratedActiveClasses = this.hydrateNormalClasses( `.${className.trim()}` ); return `&:active { ${hydratedActiveClasses} }`; } case 'sm': { const hydratedSmClasses = this.hydrateNormalClasses( `.${className.trim()}` ); return `@media (min-width: ${sm}) { ${hydratedSmClasses} }`; } case 'lg': { const hydratedMdClasses = this.hydrateNormalClasses( `.${className.trim()}` ); return `@media (min-width: ${md}) { ${hydratedMdClasses} }`; } case 'md': { const hydrateLgClasses = this.hydrateNormalClasses( `.${className.trim()}` ); return `@media (min-width: ${lg}) { ${hydrateLgClasses} }`; } default: { warn(`unknown pseudo class ${prefix}`); return className; } } } private static isPseudoClass(className: string) { if (CSSGen.usesSwindAPI(className)) { const [keyword] = className.trim().split(':'); return keyword.split('-').length > 1; } else { return className.split(':').length > 1; } } private static getPseudoAndClassName(pseudoClassName: string) { if (CSSGen.usesSwindAPI(pseudoClassName)) { const [keyword] = pseudoClassName.split(':'); const [, pseudo] = keyword.trim().split('-'); return [pseudo, CSSGen.getClassName(pseudoClassName)]; } else { return CSSGen.getClassName(pseudoClassName).split(':'); } } // check if it is like swind: bg-red-200; private static usesSwindAPI(className: string) { const [keyword] = className.trim().split(':'); return keyword.trim().match(SWIND_API_REGEX); } private static usesDotNotationAPI(className: string) { return className.trim().startsWith('.'); } genCSS(classes: string[] | string): string { if (!Array.isArray(classes)) { return CSSGen.isPseudoClass(classes) ? this.hydratePseudoClasses(classes) : this.hydrateNormalClasses(classes); } else { const normalClasses = classes.filter( (className) => !CSSGen.isPseudoClass(className) ); const pseudoClasses = classes.filter(CSSGen.isPseudoClass); const normalCSS = normalClasses .map(this.hydrateNormalClasses, this) .join(''); const pseudoCSS = pseudoClasses .map(this.hydratePseudoClasses, this) .join(''); return ` ${normalCSS} ${pseudoCSS} `; } } }
the_stack
import { Grid } from '../../../src/grid/base/grid'; import { Page } from '../../../src/grid/actions/page'; import { Selection } from '../../../src/grid/actions/selection'; import { Group } from '../../../src/grid/actions/group'; import { Toolbar } from '../../../src/grid/actions/toolbar'; import { DetailRow } from '../../../src/grid/actions/detail-row'; import { ForeignKey } from '../../../src/grid/actions/foreign-key'; import { data, employeeData, customerData } from '../base/datasource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { ExcelExport } from '../../../src/grid/actions/excel-export'; import { createGrid, destroy} from '../base/specutil.spec'; import { DataManager } from '@syncfusion/ej2-data'; import { Workbook } from '@syncfusion/ej2-excel-export'; import { ExcelRow, ExcelExportProperties } from '../../../src'; import {profile , inMB, getMemoryProfile} from '../base/common.spec'; Grid.Inject(Page, Group, Selection, Toolbar, ExcelExport, DetailRow, ForeignKey); describe('excel Export =>', () => { let exportComplete: () => void = () => true; describe('Single Grid excel Export =>', () => { let gridObj: Grid; beforeAll((done: Function) => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) } gridObj = createGrid( { dataSource: employeeData, allowExcelExport: true, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'city', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], excelExportComplete: exportComplete, beforeExcelExport: () => true }, done); }); it("Export cancel Check", (done: Function) => { gridObj.beforeExcelExport = (args: any) => { gridObj.beforeExcelExport = undefined; args.cancel = true; }; gridObj.excelExport().then((doc) => { expect(doc).toBeUndefined(); done(); }); }); it('grid exporting(Check with multiple exporting)', (done) => { spyOn(gridObj, 'excelExportComplete'); gridObj.excelExport({}, true).then((excelDoc: Workbook) => { expect(gridObj.excelExportComplete).toHaveBeenCalled(); expect(excelDoc).not.toBeUndefined(); done(); }); }); it('Excel grid Check column length', () => { let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, {}, {result: gridObj.dataSource }); expect((<any>gridObj.excelExportModule).columns.length).toBe(10); expect(excelRows.length).toBe((<any>gridObj.dataSource).length + 1); expect(excelRows[0].cells.length).toBe(5); }); it("hide a column", () => { gridObj.hideColumns('Title'); expect(gridObj.getVisibleColumns().length).toBe(4); }); it('visibility check', () => { let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, {}, {result: gridObj.dataSource }); expect(excelRows[0].cells.length).toBe(4); }); it('visibility check include hidden column', () => { (<any>gridObj.excelExportModule).includeHiddenColumn = true; let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, {includeHiddenColumn: true}, {result: gridObj.dataSource }); expect(excelRows[0].cells.length).toBe(5); }); it('check cell with value 0', () => { var data: Object = [gridObj.dataSource[0]]; data[0]['EmployeeID'] = 0; gridObj.excelQueryCellInfo = (args) => { if(args.column.field == 'EmployeeID' && args.data['FirstName'] == 'Nancy') { expect(args.value).toBe(0); } } let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, undefined, {result: data }); }); it('check cell with value null', () => { var data: Object = [gridObj.dataSource[0]]; data[0]['FirstName'] = null; gridObj.excelQueryCellInfo = (args) => { if(args.column.field == 'FirstName' && args.data['EmployeeID'] == 0) { expect(args.value).toBe(''); } } let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, undefined, {result: data }); }); it('check cell with empty string value', () => { var data: Object = [gridObj.dataSource[0]]; data[0]['FirstName'] = ''; gridObj.excelQueryCellInfo = (args) => { if(args.column.field == 'FirstName' && args.data['EmployeeID'] == 0) { expect(args.value).toBe(''); } } let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, undefined, {result: data }); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); describe('Stacked Header Grid Excel Export =>', () => { let gridObj: Grid; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: data, allowExcelExport: true, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', dataSource: employeeData, foreignKeyValue: 'FirstName', width: 120 }, { headerText: 'Order Details', columns: [ { field: 'OrderDate', headerText: 'Order Date', textAlign: 'Right', width: 135, format: 'yMd' }, { field: 'Freight', headerText: 'Freight($)', textAlign: 'Right', width: 120, format: 'C2' }, ] }, { headerText: 'Ship Details', columns: [ { field: 'ShippedDate', headerText: 'Shipped Date', textAlign: 'Right', width: 145, format: 'yMd' }, { field: 'ShipCountry', headerText: 'Ship Country', width: 140 }, ] } ], excelExportComplete: exportComplete, }, done); }); it('grid exporting(Check with multiple exporting)', (done) => { gridObj.excelExport({dataSource: data}, true).then((Doc: Workbook) => { expect(Doc).not.toBeUndefined(); done(); }); }); it('Excel grid header length', () => { let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, {}, {result: gridObj.dataSource }); expect(excelRows.length).toBe((<any>gridObj.dataSource).length + 2); expect((<any>excelRows[0]).cells.length).toBe(3); expect((<any>excelRows[1]).cells.length).toBe(4); expect((<any>excelRows[0]).cells[0].rowSpan).toBe(2); expect((<any>excelRows[0]).cells[1].colSpan).toBe(2); }); it("hide a column", () => { gridObj.hideColumns('Freight', 'field'); expect(gridObj.getVisibleColumns().length).toBe(4); }); it('stacked header visibility check', () => { let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, undefined, {result: gridObj.dataSource }); expect((<any>excelRows[0]).cells.length).toBe(3); expect((<any>excelRows[1]).cells.length).toBe(3); }); it('stacked header visibility check for include hidden column', () => { (<any>gridObj.excelExportModule).includeHiddenColumn = true; let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, {includeHiddenColumn: true}, {result: gridObj.dataSource } ); expect((<any>excelRows[0]).cells.length).toBe(3); expect((<any>excelRows[1]).cells.length).toBe(4); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); describe('Custom font in Grid excel Export =>', () => { let gridObj: Grid; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: employeeData, allowExcelExport: true, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'city', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], excelExportComplete: exportComplete, }, done); }); it('grid exporting(Check with multiple exporting)', (done) => { gridObj.excelExport({dataSource: new DataManager(data)}, true).then((doc: Workbook) => { expect(doc).not.toBeUndefined(); done(); }); }); it('Excel grid Check column length', () => { (<any>gridObj.excelExportModule).styles = []; (<any>gridObj.excelExportModule).theme = { header: { bold: false, fontSize: 15 }, caption: { bold: true, fontSize: 10 }, record: { fontName: "TimesRoman", fontColor: "#FFFFFF", fontSize: 12 } } let excelRows: ExcelRow[] = (<any>gridObj.excelExportModule).processGridExport(gridObj, { theme: { header: { bold: false, fontSize: 15 }, caption: { bold: true, fontSize: 10 }, record: { fontName: "TimesRoman", fontColor: "#FFFFFF", fontSize: 12 } }, } as ExcelExportProperties, {result: gridObj.dataSource }); expect((<any>excelRows[0]).cells[0].style.fontSize).toBe(15); expect((<any>excelRows[0]).cells[0].style.bold).toBeFalsy(); expect((<any>excelRows[0]).cells[0].style.hAlign).toBe('right'); let style: any = (<any>gridObj.excelExportModule).styles[(<any>gridObj.excelExportModule).getColumnStyle(gridObj, 1)]; expect(style.bold).toBeFalsy(); expect(style.fontSize).toBe(12); expect(style.fontName).toBe("TimesRoman"); expect(style.fontColor).toBe("#FFFFFF"); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); describe('Hierarchy Excel export => ', () => { let gridObj: Grid; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: employeeData, allowSorting: true, allowFiltering: true, allowGrouping: true, allowPaging: true, pageSettings: {pageSize: 4}, allowExcelExport: true, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'city', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], childGrid: { dataSource: data, queryString: 'EmployeeID', columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 }, { field: 'ShipCity', headerText: 'Ship City', width: 120 }, { field: 'Freight', headerText: 'Freight', width: 120 }, { field: 'ShipName', headerText: 'Ship Name', width: 150 } ], childGrid: { dataSource: customerData, queryString: 'CustomerID', columns: [ { field: 'CustomerID', headerText: 'Customer ID', textAlign: 'Right', width: 75 }, { field: 'Phone', headerText: 'Phone', width: 100 }, { field: 'Address', headerText: 'Address', width: 120 }, { field: 'Country', headerText: 'Country', width: 100 } ] } }, excelExportComplete: exportComplete, }, done); }); it('grid exporting(Check with multiple exporting)', (done) => { gridObj.excelExport({}, true).then((Doc: Workbook) => { expect(Doc).not.toBeUndefined(); done(); }); }); it('Expand a detail row', (done) => { gridObj.childGrid.dataBound = () => { expect(gridObj.getRowsObject().filter((row: any) => row.isExpand && !row.isDetailRow).length).toBe(1); done(); } gridObj.detailRowModule.expand(0); }); it('Hierarchy grid exporting', (done) => { gridObj.excelExport({}, true).then((doc) => { expect(doc).not.toBeUndefined(); done(); }); }); it('Hierarchy grid exporting', (done) => { gridObj.excelExport({hierarchyExportMode: 'All'}, true).then((doc) => { expect(doc).not.toBeUndefined(); done(); }); }); it('Hierarchy grid exporting', (done) => { gridObj.excelExport({hierarchyExportMode: 'None'}, true).then((doc) => { expect(doc).not.toBeUndefined(); done(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); describe('EJ2-36327 exportGrooupCaption event in excel export =>', () => { let gridObj: Grid; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: employeeData, allowExcelExport: true, allowGrouping:true, groupSettings:{columns:["FirstName"]}, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'city', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], }, done); }); it('grid excel exportGroupCaption check', (done) => { let exportGroupCaption = (args?: any): void => { expect(args.type).toBe("Excel"); gridObj.exportGroupCaption = null; done(); }; gridObj.exportGroupCaption = exportGroupCaption; gridObj.excelExport(); }); it('grid csv exportGroupCaption check', (done) => { let exportGroupCaption = (args?: any): void => { expect(args.type).toBe("CSV"); gridObj.exportGroupCaption = null; done(); }; gridObj.exportGroupCaption = exportGroupCaption; gridObj.csvExport(); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); describe('EJ2-40200 internal exportDataBound event in excel export =>', () => { let gridObj: Grid; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: employeeData, allowExcelExport: true, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'city', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], }, done); }); it('grid excel exportGroupCaption check', (done) => { gridObj.on('export-DataBound', function(args: {excelRows: ExcelRow[]}){ expect(args.excelRows.length).toBe((gridObj.dataSource as any).length+1); done(); }); gridObj.excelExport(); }); afterAll(() => { destroy(gridObj); gridObj = null; }); }); }); // /** // * Grid Excel Export spec document // */ // import { EmitType, EventHandler } from '@syncfusion/ej2-base'; // import { extend } from '@syncfusion/ej2-base'; // import { createElement, remove } from '@syncfusion/ej2-base'; // import { Grid } from '../../../src/grid/base/grid'; // import { Page } from '../../../src/grid/actions/page'; // import { Selection } from '../../../src/grid/actions/selection'; // import { Group } from '../../../src/grid/actions/group'; // import { Aggregate } from '../../../src/grid/actions/aggregate'; // import { Toolbar } from '../../../src/grid/actions/toolbar'; // import { ItemModel } from '@syncfusion/ej2-navigations'; // import { data } from '../base/datasource.spec'; // import { DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data'; // import { ExcelExport } from '../../../src/grid/actions/excel-export'; // import { createGrid, destroy, getKeyUpObj, getClickObj, getKeyActionObj } from '../base/specutil.spec'; // import '../../../node_modules/es6-promise/dist/es6-promise'; // Grid.Inject(Page, Group, Selection, Toolbar, ExcelExport, Aggregate); // function excelQueryCellInfo(args: any): void { // if ((args.column.field === 'OrderID') && (args.value > 10250)) { // args.style = { fontName: 'Tahoma', bold: true, italic: true, backColor: '#C67890', leftBorder: { color: '#C67878', lineStyle: 'thick' } }; // } // if (args.column.field === 'ShipCountry' && args.value === 'Switzerland') { // args.style = { textAlignment: 'right', backColor: '#C67890', verticalAlignment: 'bottom', fontStyle: 'Bold', fontSize: 15, fontFamily: 'TimesRoman' }; // } // if (args.column.field === 'OrderDate') { // args.style = { name: 'colm', textAlignment: 'right', backColor: '#C67890', verticalAlignment: 'bottom', fontStyle: 'Bold', fontSize: 15, fontFamily: 'TimesRoman' }; // } // } // let customDataProperties: any = { // dataSource: data.slice(10, 15) // } // let customAggregateFn = (data: Object[]) => data.filter((item: any) => item.ShipCountry === 'France').length; // let excelExportProperties: any = { // header: { // headerRows: 3, // rows: [ // { cells: [{ colSpan: 6, value: "Northwind Traders", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "2501 Aerial Center Parkway", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Suite 200 Morrisville, NC 27560 USA", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Tel +1 888.936.8638 Fax +1 919.573.0306", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'https://www.northwind.com/', displayText: 'www.northwind.com' }, style: { hAlign: 'Center' } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'mailto:support@northwind.com' }, style: { hAlign: 'Center' } }] }, // ] // }, // footer: { // footerRows: 4, // rows: [ // { cells: [{ colSpan: 6, value: "Thank you for your business!", style: { hAlign: 'Center', bold: true } }] }, // { cells: [{ colSpan: 6, value: "!Visit Again!", style: { hAlign: 'Center', bold: true } }] } // ] // }, // exportType: 'CurrentPage' // }; // describe('Blob data excel export => ', () => { // let gridObj: Grid; // let checkBoxFilter: Element; // let exportComplete: () => void; // beforeAll((done: Function) => { // gridObj = createGrid( // { // dataSource: data, // allowPaging: true, // filterSettings: { type: 'Menu', showFilterBarStatus: true }, // columns: [{ field: 'OrderID', type: 'number', visible: true }, // { field: 'CustomerID', type: 'string', filter: {type: 'CheckBox'} }, // { field: 'Freight', format: 'C2', type: 'number' } // ], // allowExcelExport: true, // excelExportComplete: exportComplete // }, done); // }); // it('blob csv export testing', (done) => { // let exportComplete: any = (e: any)=>{ // expect(e.promise).not.toBeUndefined(); // gridObj.excelExportComplete = null; // done(); // }; // gridObj.excelExportComplete = exportComplete; // gridObj.csvExport(null,null,null,true); // }); // it('blob excel export testing', (done) => { // let exportComplete: any = (e: any)=>{ // expect(e.promise).not.toBeUndefined(); // gridObj.excelExportComplete = null; // done(); // }; // gridObj.excelExportComplete = exportComplete; // gridObj.excelExport(null,null,null,true); // }); // afterAll(() => { // destroy(gridObj); // }); // }); // describe('excel export', () => { // let gridObj: Grid; // let elem: HTMLElement = createElement('div', { id: 'Grid' }); // let actionBegin: (e?: Object) => void; // let actionComplete: (e?: Object) => void; // afterAll(() => { // remove(elem); // }); // beforeEach(() => { // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // document.body.appendChild(elem); // gridObj = new Grid( // { // dataSource: data, // allowExcelExport: true, // allowPdfExport: true, // allowPaging: true, // allowGrouping: true, // groupSettings: { columns: ['Verified', 'ShipRegion', 'ShipCountry'] }, // toolbar: ['ExcelExport'], // pageSettings: { pageCount: 5 }, // excelQueryCellInfo: excelQueryCellInfo, // columns: [ // { // field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: '120px' // , columns: [ // { field: 'OrderID1', headerText: 'Shipped Date', textAlign: 'Right', width: 145, format: 'yMd' }, // { field: 'OrderID2', headerText: 'Ship Country', width: 140 }, // ] // }, // { field: 'OrderDate', headerText: 'Order Date', headerTextAlign: 'Right', textAlign: 'Right', width: '15%', format: 'yMd' }, // { field: 'Freight', headerText: 'Freight($)', textAlign: 'Right', width: 120, format: 'C2' }, // { field: 'ShipCountry', headerText: 'Ship Country', width: 140 }, // { field: 'ShipRegion', width: 140 }, // { field: 'Verified', width: 140 }, // { field: 'ProductName', headerText: 'Product Name', textAlign: 'Right' }, // { field: 'OrderDate', headerText: 'short-skeleton-date', format: { skeleton: 'short' } }, // { field: 'OrderDate', headerText: 'short-format-date', format: 'short', type: 'date' }, // { field: 'OrderDate', headerText: 'medium-format-date', format: 'medium', type: 'date' }, // { field: 'OrderDate', headerText: 'long-format-date', format: 'long', type: 'date' }, // { field: 'OrderDate', headerText: 'full-format-date', format: 'full', type: 'date' }, // { field: 'OrderDate', headerText: 'short-format-time', format: 'short', type: 'time' }, // { field: 'OrderDate', headerText: 'medium-format-time', format: 'medium', type: 'time' }, // { field: 'OrderDate', headerText: 'long-format-time', format: 'long', type: 'time' }, // { field: 'OrderDate', headerText: 'full-format-time', format: 'full', type: 'time' }, // { field: 'OrderDate', headerText: 'short-format-datetime', format: 'short', type: 'datetime' }, // { field: 'OrderDate', headerText: 'medium-format-datetime', format: 'medium', type: 'datetime' }, // { field: 'OrderDate', headerText: 'long-format-datetime', format: 'long', type: 'datetime' }, // { field: 'OrderDate', headerText: 'full-format-datetime', format: 'full', type: 'datetime' }, // { field: 'OrderDate', headerText: 'short-skeleton-date', format: { skeleton: 'short', type: 'date' } }, // { field: 'OrderDate', headerText: 'medium-skeleton-date', format: { skeleton: 'medium', type: 'date' } }, // { field: 'OrderDate', headerText: 'long-skeleton-date', format: { skeleton: 'long', type: 'date' } }, // { field: 'OrderDate', headerText: 'full-skeleton-date', format: { skeleton: 'full', type: 'date' } }, // { field: 'OrderDate', headerText: 'short-skeleton-time', format: { skeleton: 'short', type: 'time' } }, // { field: 'OrderDate', headerText: 'medium-skeleton-time', format: { skeleton: 'medium', type: 'time' } }, // { field: 'OrderDate', headerText: 'long-skeleton-time', format: { skeleton: 'long', type: 'time' } }, // { field: 'OrderDate', headerText: 'full-skeleton-time', format: { skeleton: 'full', type: 'time' } }, // ], // aggregates: [{ // columns: [ // { // type: 'Min', // field: 'Freight', // format: 'C2', // groupFooterTemplate: 'Min: ${min}' // }, // { // type: 'Max', // field: 'OrderDate', // format: { type: 'date', skeleton: 'medium' }, // groupFooterTemplate: 'Max: ${max}' // }, { // type: 'Max', // field: 'Freight', // format: 'C2', // groupCaptionTemplate: 'Max: ${max}' // }, { // type: 'Max', // field: 'OrderDate', // format: { type: 'date', skeleton: 'medium' }, // groupCaptionTemplate: 'Max: ${max}' // }, { // type: 'Custom', // customAggregate: customAggregateFn, // field: 'ShipCountry', // } // ] // }, { // columns: [{ // type: 'Custom', // customAggregate: customAggregateFn, // columnName: 'ShipCountry', // }] // }] // }); // gridObj.appendTo('#Grid'); // gridObj.dataBind(); // }); // it('material', (done) => { // gridObj.excelExport(); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('bootstrap', (done) => { // gridObj.excelExport({ // theme: // { // header: { fontName: 'Segoe UI', fontColor: '#666666' }, // record: { fontName: 'Segoe UI', fontColor: '#666666' }, // caption: { fontName: 'Segoe UI', fontColor: '#666666' } // } // }); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('header and footer', (done) => { // gridObj.excelExport(excelExportProperties); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('custom data source', (done) => { // gridObj.excelExport(customDataProperties); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('remote data', (done) => { // gridObj.excelExport(new DataManager(data.slice(10, 15) as JSON[])); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('material-csv', (done) => { // gridObj.csvExport(); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('bootstrap - csv', (done) => { // gridObj.csvExport({ // theme: // { // header: { fontName: 'Segoe UI', fontColor: '#666666' }, // record: { fontName: 'Segoe UI', fontColor: '#666666' }, // caption: { fontName: 'Segoe UI', fontColor: '#666666' } // } // }); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('header and footer - csv', (done) => { // gridObj.csvExport(excelExportProperties); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('custom data source - csv', (done) => { // gridObj.csvExport(customDataProperties); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // it('remote data - csv', (done) => { // gridObj.csvExport(new DataManager(data.slice(10, 15) as JSON[])); // setTimeout(() => { // expect('').toBe(''); // done(); // }, 500); // }); // }); // describe('multiple-grid-exporting', () => { // let gridObj1: Grid; // let elem1: HTMLElement = createElement('div', { id: 'Grid1' }); // let gridObj3: Grid; // let elem3: HTMLElement = createElement('div', { id: 'Grid3' }); // let actionBegin: (e?: Object) => void; // let actionComplete: (e?: Object) => void; // let excelExportPropertiesHeader: any = { // multipleExport: {}, // includeHiddenColumn: true, // header: { // headerRows: 7, // rows: [ // { cells: [{ colSpan: 6, value: "Northwind Traders", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "2501 Aerial Center Parkway", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Suite 200 Morrisville, NC 27560 USA", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Tel +1 888.936.8638 Fax +1 919.573.0306", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'https://www.northwind.com/', displayText: 'www.northwind.com' }, style: { hAlign: 'Center' } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'mailto:support@northwind.com' }, style: { hAlign: 'Center' } }] }, // ] // } // }; // let appendExcelExportProperties: any = { // multipleExport: { blankRows: 3 }, // includeHiddenColumn: true, // header: { // headerRows: 7, // rows: [ // { cells: [{ colSpan: 6, value: "Northwind Traders", style: { fontColor: '#C67878', fontSize: 20, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "2501 Aerial Center Parkway", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Suite 200 Morrisville, NC 27560 USA", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, value: "Tel +1 888.936.8638 Fax +1 919.573.0306", style: { fontColor: '#C67878', fontSize: 15, hAlign: 'Center', bold: true, } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'https://www.northwind.com/', displayText: 'www.northwind.com' }, style: { hAlign: 'Center' } }] }, // { cells: [{ colSpan: 6, hyperlink: { target: 'mailto:support@northwind.com' }, style: { hAlign: 'Center' } }] }, // ] // }, // footer: { // footerRows: 4, // rows: [ // { cells: [{ colSpan: 6, value: "Thank you for your business!", style: { hAlign: 'Center', bold: true } }] }, // { cells: [{ colSpan: 6, value: "!Visit Again!", style: { hAlign: 'Center', bold: true } }] } // ] // }, // }; // beforeEach(function () { // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // }); // beforeAll(() => { // document.body.appendChild(elem1); // document.body.appendChild(elem3); // gridObj1 = new Grid( // { // dataSource: data.slice(0, 2), // allowExcelExport: true, // toolbar: ['ExcelExport'], // columns: [ // { field: 'OrderID', headerText: 'Order ID', width: 120 }, // { field: 'OrderDate', format: { skeleton: 'full', type: 'date' }, visible: false }, // ], // }); // gridObj3 = new Grid( // { // dataSource: data.slice(0, 2), // allowExcelExport: true, // columns: [ // { field: 'OrderID', headerText: 'Order ID', width: 120 }, // { field: 'OrderDate', format: { skeleton: 'full', type: 'time' } }, // ], // }); // gridObj1.appendTo('#Grid1'); // gridObj3.appendTo('#Grid3'); // }); // afterAll(() => { // remove(elem1); // remove(elem3); // }); // let gBook: any; // it('multiexport without saving the book', (done) => { // let excelExp: Promise<any> = gridObj1.excelExport(excelExportPropertiesHeader, true); // excelExp.then((data: any) => { // gBook = data; // done(); // }); // }); // it('multiexport with saving the book', (done) => { // let excelExp: Promise<any> = gridObj3.excelExport(appendExcelExportProperties, false, gBook); // excelExp.then((data: any) => { // done(); // }); // }); // it('multiexport without saving the book-csv', (done) => { // let excelExp: Promise<any> = gridObj1.csvExport(excelExportPropertiesHeader, true); // excelExp.then((data: any) => { // gBook = data; // done(); // }); // }); // it('multiexport with saving the book-csv', (done) => { // let excelExp: Promise<any> = gridObj3.csvExport(appendExcelExportProperties, false, gBook); // excelExp.then((data: any) => { // done(); // }); // }); // });
the_stack
import { Route } from "./navigation.js"; import { QueryString } from "./query-string.js"; /** * @alpha */ export type RouteParameterConverter = (value: string | undefined) => any | Promise<any>; const defaultParameterConverter: RouteParameterConverter = (value: string | undefined) => value; /** * @alpha */ export class ConfigurableRoute implements Route { public constructor( public readonly path: string, public readonly name: string, public readonly caseSensitive: boolean ) {} } /** * @alpha */ export class Endpoint<TSettings = any> { public constructor( public readonly route: ConfigurableRoute, public readonly paramNames: readonly string[], public readonly paramTypes: readonly string[], public readonly settings: TSettings | null ) {} public get path() { return this.route.path; } } /** * @alpha */ export class RecognizedRoute<TSettings = any> { public readonly allParams: Readonly<Record<string, string | undefined>>; public readonly allTypedParams: Readonly<Record<string, any>>; public constructor( public readonly endpoint: Endpoint<TSettings>, public readonly params: Readonly<Record<string, string | undefined>>, public readonly typedParams: Readonly<Record<string, any>>, public readonly queryParams: Readonly<Record<string, string>> ) { this.allParams = { ...params, ...queryParams, }; this.allTypedParams = { ...typedParams, ...queryParams, }; } public get settings() { return this.endpoint.settings; } } class Candidate<T> { public head: AnyState<T>; public endpoint: Endpoint<T>; public constructor( private readonly chars: string[], private readonly states: AnyState<T>[], private readonly skippedStates: DynamicState<T>[], private readonly result: RecognizeResult<T> ) { this.head = states[states.length - 1]; // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain this.endpoint = this.head?.endpoint!; } public advance(ch: string): void { const { chars, states, skippedStates, result } = this; let stateToAdd: AnyState<T> | null = null; let matchCount = 0; const state = states[states.length - 1]; function $process( nextState: AnyState<T>, skippedState: DynamicState<T> | null ): void { if (nextState.isMatch(ch)) { if (++matchCount === 1) { stateToAdd = nextState; } else { result.add( new Candidate( chars.concat(ch), states.concat(nextState), skippedState === null ? skippedStates : skippedStates.concat(skippedState), result ) ); } } if ( state.segment === null && nextState.isOptional && nextState.nextStates !== null ) { if (nextState.nextStates.length > 1) { throw new Error(`${nextState.nextStates.length} nextStates`); } const separator = nextState.nextStates[0]; if (!separator.isSeparator) { throw new Error(`Not a separator`); } if (separator.nextStates !== null) { for (const $nextState of separator.nextStates) { $process($nextState, nextState); } } } } if (state.isDynamic) { $process(state, null); } if (state.nextStates !== null) { for (const nextState of state.nextStates) { $process(nextState, null); } } if (stateToAdd !== null) { states.push((this.head = stateToAdd)); chars.push(ch); if ((stateToAdd as AnyState<T>).endpoint !== null) { this.endpoint = (stateToAdd as AnyState<T>).endpoint!; } } if (matchCount === 0) { result.remove(this); } } public finalize(): void { function collectSkippedStates( skippedStates: DynamicState<T>[], state: AnyState<T> ): void { const nextStates = state.nextStates; if (nextStates !== null) { if (nextStates.length === 1 && nextStates[0].segment === null) { collectSkippedStates(skippedStates, nextStates[0]); } else { for (const nextState of nextStates) { if (nextState.isOptional && nextState.endpoint !== null) { skippedStates.push(nextState); if (nextState.nextStates !== null) { for (const $nextState of nextState.nextStates) { collectSkippedStates(skippedStates, $nextState); } } break; } } } } } collectSkippedStates(this.skippedStates, this.head); } public getParams(): Record<string, string | undefined> { const { states, chars, endpoint } = this; const params: Record<string, string | undefined> = {}; // First initialize all properties with undefined so they all exist (even if they're not filled, e.g. non-matched optional params) for (const name of endpoint.paramNames) { params[name] = void 0; } for (let i = 0, ii = states.length; i < ii; ++i) { const state = states[i]; if (state.isDynamic) { const name = state.segment.name; if (params[name] === void 0) { params[name] = chars[i]; } else { params[name] += chars[i]; } } } return params; } /** * Compares this candidate to another candidate to determine the correct sorting order. * * This algorithm is different from `sortSolutions` in v1's route-recognizer in that it compares * the candidates segment-by-segment, rather than merely comparing the cumulative of segment types * * This resolves v1's ambiguity in situations like `/foo/:id/bar` vs. `/foo/bar/:id`, which had the * same sorting value because they both consist of two static segments and one dynamic segment. * * With this algorithm, `/foo/bar/:id` would always be sorted first because the second segment is different, * and static wins over dynamic. * * ### NOTE * This algorithm violates some of the invariants of v1's algorithm, * but those invariants were arguably not very sound to begin with. Example: * * `/foo/*path/bar/baz` vs. `/foo/bar/*path1/*path2` * - in v1, the first would win because that match has fewer stars * - in v2, the second will win because there is a bigger static match at the start of the pattern * * The algorithm should be more logical and easier to reason about in v2, but it's important to be aware of * subtle difference like this which might surprise some users who happened to rely on this behavior from v1, * intentionally or unintentionally. * * @param b - The candidate to compare this to. * Parameter name is `b` because the method should be used like so: `states.sort((a, b) => a.compareTo(b))`. * This will bring the candidate with the highest score to the first position of the array. */ public compareTo(b: Candidate<T>): -1 | 1 | 0 { const statesA = this.states; const statesB = b.states; for ( let iA = 0, iB = 0, ii = Math.max(statesA.length, statesB.length); iA < ii; ++iA ) { let stateA = statesA[iA]; if (stateA === void 0) { return 1; } let stateB = statesB[iB]; if (stateB === void 0) { return -1; } let segmentA = stateA.segment; let segmentB = stateB.segment; if (segmentA === null) { if (segmentB === null) { ++iB; continue; } if ((stateA = statesA[++iA]) === void 0) { return 1; } segmentA = stateA.segment!; } else if (segmentB === null) { if ((stateB = statesB[++iB]) === void 0) { return -1; } segmentB = stateB.segment!; } if (segmentA.kind < segmentB.kind) { return 1; } if (segmentA.kind > segmentB.kind) { return -1; } ++iB; } const skippedStatesA = this.skippedStates; const skippedStatesB = b.skippedStates; const skippedStatesALen = skippedStatesA.length; const skippedStatesBLen = skippedStatesB.length; if (skippedStatesALen < skippedStatesBLen) { return 1; } if (skippedStatesALen > skippedStatesBLen) { return -1; } for (let i = 0; i < skippedStatesALen; ++i) { const skippedStateA = skippedStatesA[i]; const skippedStateB = skippedStatesB[i]; if (skippedStateA.length < skippedStateB.length) { return 1; } if (skippedStateA.length > skippedStateB.length) { return -1; } } // This should only be possible with a single pattern with multiple consecutive star segments. // TODO: probably want to warn or even throw here, but leave it be for now. return 0; } } function hasEndpoint<T>(candidate: Candidate<T>): boolean { return candidate.head.endpoint !== null; } function compareChains<T>(a: Candidate<T>, b: Candidate<T>): -1 | 1 | 0 { return a.compareTo(b); } class RecognizeResult<T> { private readonly candidates: Candidate<T>[] = []; public get isEmpty(): boolean { return this.candidates.length === 0; } public constructor(rootState: SeparatorState<T>) { this.candidates = [new Candidate([""], [rootState], [], this)]; } public getSolution(): Candidate<T> | null { const candidates = this.candidates.filter(hasEndpoint); if (candidates.length === 0) { return null; } for (const candidate of candidates) { candidate.finalize(); } candidates.sort(compareChains); return candidates[0]; } public add(candidate: Candidate<T>): void { this.candidates.push(candidate); } public remove(candidate: Candidate<T>): void { this.candidates.splice(this.candidates.indexOf(candidate), 1); } public advance(ch: string): void { const candidates = this.candidates.slice(); for (const candidate of candidates) { candidate.advance(ch); } } } /** * @alpha */ export interface RouteRecognizer<TSettings> { add(routeOrRoutes: Route | readonly Route[], settings?: TSettings): void; recognize( path: string, converters?: Readonly<Record<string, RouteParameterConverter>> ): Promise<RecognizedRoute<TSettings> | null>; generateFromName(name: string, params: object): string | null; generateFromPath(path: string, params: object): string | null; } /** * @alpha */ export class DefaultRouteRecognizer<TSettings> implements RouteRecognizer<TSettings> { private names = new Map<string, AnySegment<any>[]>(); private paths = new Map<string, AnySegment<any>[]>(); private readonly rootState: SeparatorState<TSettings> = new State( null, null, "" ) as SeparatorState<TSettings>; public add(routeOrRoutes: Route | readonly Route[], settings?: TSettings): void { if (routeOrRoutes instanceof Array) { for (const route of routeOrRoutes) { this.$add(route, settings); } } else { this.$add(routeOrRoutes as Route, settings); } } private $add(route: Route, settings?: TSettings): void { const path = route.path; const $route = new ConfigurableRoute( route.path, route.name || "", route.caseSensitive === true ); // Normalize leading, trailing and double slashes by ignoring empty segments const parts = path === "" ? [""] : path.split("/").filter(isNotEmpty); const paramNames: string[] = []; const paramTypes: string[] = []; let state = this.rootState as AnyState<TSettings>; const segments: AnySegment<any>[] = []; for (const part of parts) { // Each segment always begins with a slash, so we represent this with a non-segment state state = state.append(null, "/"); switch (part.charAt(0)) { case "{": { // route parameter const nameAndType = part .slice(1, -1) .split(":") .map(x => x.trim()); if (nameAndType.length === 2) { paramTypes.push(nameAndType[1]); } else { paramTypes.push("string"); } const isOptional = nameAndType[0].endsWith("?"); const name = isOptional ? nameAndType[0].slice(0, -1) : nameAndType[0]; paramNames.push(name); const segment = new DynamicSegment<TSettings>(name, isOptional); segments.push(segment); state = segment.appendTo(state); break; } case "*": { // dynamic route const name = part.slice(1); paramNames.push(name); paramTypes.push("string"); const segment = new StarSegment<TSettings>(name); segments.push(segment); state = segment.appendTo(state); break; } default: { // standard path route const segment = new StaticSegment<TSettings>( part, $route.caseSensitive ); segments.push(segment); state = segment.appendTo(state); break; } } } const endpoint = new Endpoint<TSettings>( $route, paramNames, paramTypes, settings || null ); state.setEndpoint(endpoint); this.paths.set(path, segments); if (route.name) { this.names.set(route.name, segments); } } public async recognize( path: string, converters: Readonly<Record<string, RouteParameterConverter>> = {} ): Promise<RecognizedRoute<TSettings> | null> { const separated = QueryString.separate(path); const queryParams = QueryString.parse(separated.queryString); path = decodeURI(separated.path); if (!path.startsWith("/")) { path = `/${path}`; } if (path.length > 1 && path.endsWith("/")) { path = path.slice(0, -1); } const result = new RecognizeResult(this.rootState); for (let i = 0, ii = path.length; i < ii; ++i) { const ch = path.charAt(i); result.advance(ch); if (result.isEmpty) { return null; } } const candidate = result.getSolution(); if (candidate === null) { return null; } const { endpoint } = candidate; const paramNames = endpoint.paramNames; const paramTypes = endpoint.paramTypes; const params = candidate.getParams(); const typedParams = {}; for (let i = 0, ii = paramNames.length; i < ii; ++i) { const name = paramNames[i]; const convert = converters[paramTypes[i]] || defaultParameterConverter; const untypedValue = params[name]; const typedValue = await convert(untypedValue); typedParams[name] = typedValue; } return new RecognizedRoute<TSettings>(endpoint, params, typedParams, queryParams); } /** * Generate a path and query string from a route name and params object. * * @param name - The name of the route to generate from. * @param params - The route params to use when populating the pattern. * Properties not required by the pattern will be appended to the query string. * @returns The generated absolute path and query string. */ public generateFromName(name: string, params: object): string | null { return this.generate(this.names.get(name), params); } /** * Generate a path and query string from a route path and params object. * * @param path - The path of the route to generate from. * @param params - The route params to use when populating the pattern. * Properties not required by the pattern will be appended to the query string. * @returns The generated absolute path and query string. */ public generateFromPath(path: string, params: object): string | null { return this.generate(this.paths.get(path), params); } private generate( segments: AnySegment<any>[] | undefined, params: object ): string | null { if (!segments) { return null; } const routeParams = Object.assign({}, params); const consumed = {}; let output = ""; for (let i = 0, l = segments.length; i < l; i++) { const segment = segments[i]; const segmentValue = segment.generate(routeParams, consumed); if (segmentValue === null || segmentValue === undefined) { if (segment instanceof DynamicSegment && !segment.optional) { throw new Error( `A value is required for route parameter '${segment.name}'.` ); } } else { output += "/"; output += segmentValue; } } if (output.charAt(0) !== "/") { output = "/" + output; } // remove params used in the path and add the rest to the querystring for (const param in consumed) { delete routeParams[param]; } const queryString = QueryString.build(routeParams); output += queryString ? `?${queryString}` : ""; return output; } } type StaticState<T> = State<T> & { readonly isSeparator: false; readonly isDynamic: false; readonly isOptional: false; readonly prevState: StaticState<T> | SeparatorState<T>; readonly segment: StaticSegment<T>; }; type DynamicState<T> = State<T> & { readonly isSeparator: false; readonly isDynamic: true; readonly isOptional: true | false; readonly prevState: SeparatorState<T>; readonly segment: DynamicSegment<T>; }; type StarState<T> = State<T> & { readonly isSeparator: false; readonly isDynamic: true; readonly isOptional: false; readonly prevState: SeparatorState<T>; readonly segment: StarSegment<T>; }; type SeparatorState<T> = State<T> & { readonly isSeparator: true; readonly isDynamic: false; readonly isOptional: false; readonly path: null; readonly segment: null; }; type AnyState<T> = StaticState<T> | DynamicState<T> | StarState<T> | SeparatorState<T>; type SegmentToState<S, T> = S extends StaticSegment<T> ? StaticState<T> : S extends DynamicSegment<T> ? DynamicState<T> : S extends StarSegment<T> ? StarState<T> : S extends null ? SeparatorState<T> : never; class State<T> { public nextStates: AnyState<T>[] | null = null; public readonly isSeparator: boolean; public readonly isDynamic: boolean; public readonly isOptional: boolean; public endpoint: Endpoint<T> | null = null; public readonly length: number; public constructor( public readonly prevState: AnyState<T> | null, public readonly segment: AnySegment<T> | null, public readonly value: string ) { switch (segment?.kind) { case SegmentKind.dynamic: this.length = prevState!.length + 1; this.isSeparator = false; this.isDynamic = true; this.isOptional = segment.optional; break; case SegmentKind.star: this.length = prevState!.length + 1; this.isSeparator = false; this.isDynamic = true; this.isOptional = false; break; case SegmentKind.static: this.length = prevState!.length + 1; this.isSeparator = false; this.isDynamic = false; this.isOptional = false; break; case undefined: this.length = prevState === null ? 0 : prevState.length; this.isSeparator = true; this.isDynamic = false; this.isOptional = false; break; } } public append<S extends AnySegment<T> | null>( segment: S, value: string ): SegmentToState<S, T> { let state: AnyState<T> | undefined; let nextStates = this.nextStates; if (nextStates === null) { state = void 0; nextStates = this.nextStates = []; } else if (segment === null) { state = nextStates.find(s => s.value === value); } else { state = nextStates.find(s => s.segment?.equals(segment!)); } if (state === void 0) { nextStates.push( (state = new State(this as AnyState<T>, segment, value) as AnyState<T>) ); } return state as SegmentToState<S, T>; } public setEndpoint(this: AnyState<T>, endpoint: Endpoint<T>): void { if (this.endpoint !== null) { throw new Error( `Cannot add ambiguous route. The pattern '${endpoint.route.path}' clashes with '${this.endpoint.route.path}'` ); } this.endpoint = endpoint; if (this.isOptional) { this.prevState.setEndpoint(endpoint); if (this.prevState.isSeparator && this.prevState.prevState !== null) { this.prevState.prevState.setEndpoint(endpoint); } } } public isMatch(ch: string): boolean { const segment = this.segment; switch (segment?.kind) { case SegmentKind.dynamic: return !this.value.includes(ch); case SegmentKind.star: return true; case SegmentKind.static: case undefined: // segment separators (slashes) are non-segments. We could say return ch === '/' as well, technically. return this.value.includes(ch); } } } function isNotEmpty(segment: string): boolean { return segment.length > 0; } type AnySegment<T> = StaticSegment<T> | DynamicSegment<T> | StarSegment<T>; const enum SegmentKind { star = 1, dynamic = 2, static = 3, } class StaticSegment<T> { public get kind(): SegmentKind.static { return SegmentKind.static; } public constructor( public readonly value: string, public readonly caseSensitive: boolean ) {} public appendTo(state: AnyState<T>): StaticState<T> { const { value, value: { length }, } = this; if (this.caseSensitive) { for (let i = 0; i < length; ++i) { state = state.append(/* segment */ this, /* value */ value.charAt(i)); } } else { for (let i = 0; i < length; ++i) { const ch = value.charAt(i); state = state.append( /* segment */ this, /* value */ ch.toUpperCase() + ch.toLowerCase() ); } } return state as StaticState<T>; } public generate(): string { return this.value; } public equals(b: AnySegment<T>): boolean { return ( b.kind === SegmentKind.static && b.caseSensitive === this.caseSensitive && b.value === this.value ); } } class DynamicSegment<T> { public get kind(): SegmentKind.dynamic { return SegmentKind.dynamic; } public constructor(public readonly name: string, public readonly optional: boolean) {} public appendTo(state: AnyState<T>): DynamicState<T> { state = state.append(/* segment */ this, /* value */ "/"); return state; } public generate(params: Object, consumed: Object): string { consumed[this.name] = true; return params[this.name]; } public equals(b: AnySegment<T>): boolean { return ( b.kind === SegmentKind.dynamic && b.optional === this.optional && b.name === this.name ); } } class StarSegment<T> { public get kind(): SegmentKind.star { return SegmentKind.star; } public constructor(public readonly name: string) {} public appendTo(state: AnyState<T>): StarState<T> { state = state.append(/* segment */ this, /* value */ ""); return state; } public generate(params: Object, consumed: Object): string { consumed[this.name] = true; return params[this.name]; } public equals(b: AnySegment<T>): boolean { return b.kind === SegmentKind.star && b.name === this.name; } }
the_stack
declare const enum DAL { // /main/configkeys.h CFG_PIN_NAME_MSK = 65535, CFG_PIN_CONFIG_MSK = 4294901760, CFG_PIN_CONFIG_ACTIVE_LO = 65536, CFG_MAGIC0 = 513675505, CFG_MAGIC1 = 539130489, CFG_PIN_ACCELEROMETER_INT = 1, CFG_PIN_ACCELEROMETER_SCL = 2, CFG_PIN_ACCELEROMETER_SDA = 3, CFG_PIN_BTN_A = 4, CFG_PIN_BTN_B = 5, CFG_PIN_BTN_SLIDE = 6, CFG_PIN_DOTSTAR_CLOCK = 7, CFG_PIN_DOTSTAR_DATA = 8, CFG_PIN_FLASH_CS = 9, CFG_PIN_FLASH_MISO = 10, CFG_PIN_FLASH_MOSI = 11, CFG_PIN_FLASH_SCK = 12, CFG_PIN_LED = 13, CFG_PIN_LIGHT = 14, CFG_PIN_MICROPHONE = 15, CFG_PIN_MIC_CLOCK = 16, CFG_PIN_MIC_DATA = 17, CFG_PIN_MISO = 18, CFG_PIN_MOSI = 19, CFG_PIN_NEOPIXEL = 20, CFG_PIN_RX = 21, CFG_PIN_RXLED = 22, CFG_PIN_SCK = 23, CFG_PIN_SCL = 24, CFG_PIN_SDA = 25, CFG_PIN_SPEAKER_AMP = 26, CFG_PIN_TEMPERATURE = 27, CFG_PIN_TX = 28, CFG_PIN_TXLED = 29, CFG_PIN_IR_OUT = 30, CFG_PIN_IR_IN = 31, CFG_PIN_DISPLAY_SCK = 32, CFG_PIN_DISPLAY_MISO = 33, CFG_PIN_DISPLAY_MOSI = 34, CFG_PIN_DISPLAY_CS = 35, CFG_PIN_DISPLAY_DC = 36, CFG_DISPLAY_WIDTH = 37, CFG_DISPLAY_HEIGHT = 38, CFG_DISPLAY_CFG0 = 39, CFG_DISPLAY_CFG1 = 40, CFG_DISPLAY_CFG2 = 41, CFG_DISPLAY_CFG3 = 42, CFG_PIN_DISPLAY_RST = 43, CFG_PIN_DISPLAY_BL = 44, CFG_PIN_SERVO_1 = 45, CFG_PIN_SERVO_2 = 46, CFG_PIN_BTN_LEFT = 47, CFG_PIN_BTN_RIGHT = 48, CFG_PIN_BTN_UP = 49, CFG_PIN_BTN_DOWN = 50, CFG_PIN_BTN_MENU = 51, CFG_PIN_LED_R = 52, CFG_PIN_LED_G = 53, CFG_PIN_LED_B = 54, CFG_PIN_LED1 = 55, CFG_PIN_LED2 = 56, CFG_PIN_LED3 = 57, CFG_PIN_LED4 = 58, CFG_SPEAKER_VOLUME = 59, CFG_PIN_JACK_TX = 60, CFG_PIN_JACK_SENSE = 61, CFG_PIN_JACK_HPEN = 62, CFG_PIN_JACK_BZEN = 63, CFG_PIN_JACK_PWREN = 64, CFG_PIN_JACK_SND = 65, CFG_PIN_JACK_BUSLED = 66, CFG_PIN_JACK_COMMLED = 67, CFG_PIN_BTN_SOFT_RESET = 69, CFG_ACCELEROMETER_TYPE = 70, CFG_PIN_BTNMX_LATCH = 71, CFG_PIN_BTNMX_CLOCK = 72, CFG_PIN_BTNMX_DATA = 73, CFG_PIN_BTN_MENU2 = 74, CFG_PIN_BATTSENSE = 75, CFG_PIN_VIBRATION = 76, CFG_PIN_PWREN = 77, CFG_DISPLAY_TYPE = 78, CFG_PIN_ROTARY_ENCODER_A = 79, CFG_PIN_ROTARY_ENCODER_B = 80, CFG_ACCELEROMETER_SPACE = 81, CFG_PIN_WIFI_MOSI = 82, CFG_PIN_WIFI_MISO = 83, CFG_PIN_WIFI_SCK = 84, CFG_PIN_WIFI_TX = 85, CFG_PIN_WIFI_RX = 86, CFG_PIN_WIFI_CS = 87, CFG_PIN_WIFI_BUSY = 88, CFG_PIN_WIFI_RESET = 89, CFG_PIN_WIFI_GPIO0 = 90, CFG_PIN_WIFI_AT_TX = 91, CFG_PIN_WIFI_AT_RX = 92, CFG_PIN_USB_POWER = 93, ACCELEROMETER_TYPE_LIS3DH = 50, ACCELEROMETER_TYPE_LIS3DH_ALT = 48, ACCELEROMETER_TYPE_MMA8453 = 56, ACCELEROMETER_TYPE_FXOS8700 = 60, ACCELEROMETER_TYPE_MMA8653 = 58, ACCELEROMETER_TYPE_MSA300 = 76, ACCELEROMETER_TYPE_MPU6050 = 104, DISPLAY_TYPE_ST7735 = 7735, DISPLAY_TYPE_ILI9341 = 9341, DISPLAY_TYPE_SMART = 4242, CFG_PIN_A0 = 100, CFG_PIN_A1 = 101, CFG_PIN_A2 = 102, CFG_PIN_A3 = 103, CFG_PIN_A4 = 104, CFG_PIN_A5 = 105, CFG_PIN_A6 = 106, CFG_PIN_A7 = 107, CFG_PIN_A8 = 108, CFG_PIN_A9 = 109, CFG_PIN_A10 = 110, CFG_PIN_A11 = 111, CFG_PIN_A12 = 112, CFG_PIN_A13 = 113, CFG_PIN_A14 = 114, CFG_PIN_A15 = 115, CFG_PIN_A16 = 116, CFG_PIN_A17 = 117, CFG_PIN_A18 = 118, CFG_PIN_A19 = 119, CFG_PIN_A20 = 120, CFG_PIN_A21 = 121, CFG_PIN_A22 = 122, CFG_PIN_A23 = 123, CFG_PIN_A24 = 124, CFG_PIN_A25 = 125, CFG_PIN_A26 = 126, CFG_PIN_A27 = 127, CFG_PIN_A28 = 128, CFG_PIN_A29 = 129, CFG_PIN_A30 = 130, CFG_PIN_A31 = 131, CFG_PIN_D0 = 150, CFG_PIN_D1 = 151, CFG_PIN_D2 = 152, CFG_PIN_D3 = 153, CFG_PIN_D4 = 154, CFG_PIN_D5 = 155, CFG_PIN_D6 = 156, CFG_PIN_D7 = 157, CFG_PIN_D8 = 158, CFG_PIN_D9 = 159, CFG_PIN_D10 = 160, CFG_PIN_D11 = 161, CFG_PIN_D12 = 162, CFG_PIN_D13 = 163, CFG_PIN_D14 = 164, CFG_PIN_D15 = 165, CFG_PIN_D16 = 166, CFG_PIN_D17 = 167, CFG_PIN_D18 = 168, CFG_PIN_D19 = 169, CFG_PIN_D20 = 170, CFG_PIN_D21 = 171, CFG_PIN_D22 = 172, CFG_PIN_D23 = 173, CFG_PIN_D24 = 174, CFG_PIN_D25 = 175, CFG_PIN_D26 = 176, CFG_PIN_D27 = 177, CFG_PIN_D28 = 178, CFG_PIN_D29 = 179, CFG_PIN_D30 = 180, CFG_PIN_D31 = 181, CFG_NUM_NEOPIXELS = 200, CFG_NUM_DOTSTARS = 201, CFG_DEFAULT_BUTTON_MODE = 202, CFG_SWD_ENABLED = 203, CFG_FLASH_BYTES = 204, CFG_RAM_BYTES = 205, CFG_SYSTEM_HEAP_BYTES = 206, CFG_LOW_MEM_SIMULATION_KB = 207, CFG_BOOTLOADER_BOARD_ID = 208, CFG_UF2_FAMILY = 209, CFG_PINS_PORT_SIZE = 210, CFG_BOOTLOADER_PROTECTION = 211, CFG_POWER_DEEPSLEEP_TIMEOUT = 212, CFG_ANALOG_BUTTON_THRESHOLD = 213, CFG_CPU_MHZ = 214, CFG_CONTROLLER_LIGHT_MAX_BRIGHTNESS = 215, CFG_ANALOG_JOYSTICK_MIN = 216, CFG_ANALOG_JOYSTICK_MAX = 217, CFG_TIMERS_TO_USE = 218, CFG_PIN_ONBOARD_DOTSTAR_CLOCK = 219, CFG_PIN_ONBOARD_DOTSTAR_DATA = 220, CFG_NUM_ONBOARD_DOTSTARS = 221, CFG_PIN_ONBOARD_NEOPIXEL = 222, CFG_NUM_ONBOARD_NEOPIXELS = 223, CFG_MATRIX_KEYPAD_MESSAGE_ID = 239, CFG_NUM_MATRIX_KEYPAD_ROWS = 240, CFG_PIN_MATRIX_KEYPAD_ROW0 = 241, CFG_PIN_MATRIX_KEYPAD_ROW1 = 242, CFG_PIN_MATRIX_KEYPAD_ROW2 = 243, CFG_PIN_MATRIX_KEYPAD_ROW3 = 244, CFG_PIN_MATRIX_KEYPAD_ROW4 = 245, CFG_PIN_MATRIX_KEYPAD_ROW5 = 246, CFG_PIN_MATRIX_KEYPAD_ROW6 = 247, CFG_PIN_MATRIX_KEYPAD_ROW7 = 248, CFG_NUM_MATRIX_KEYPAD_COLS = 250, CFG_PIN_MATRIX_KEYPAD_COL0 = 251, CFG_PIN_MATRIX_KEYPAD_COL1 = 252, CFG_PIN_MATRIX_KEYPAD_COL2 = 253, CFG_PIN_MATRIX_KEYPAD_COL3 = 254, CFG_PIN_MATRIX_KEYPAD_COL4 = 255, CFG_PIN_MATRIX_KEYPAD_COL5 = 256, CFG_PIN_MATRIX_KEYPAD_COL6 = 257, CFG_PIN_MATRIX_KEYPAD_COL7 = 258, CFG_PIN_B0 = 300, CFG_PIN_B1 = 301, CFG_PIN_B2 = 302, CFG_PIN_B3 = 303, CFG_PIN_B4 = 304, CFG_PIN_B5 = 305, CFG_PIN_B6 = 306, CFG_PIN_B7 = 307, CFG_PIN_B8 = 308, CFG_PIN_B9 = 309, CFG_PIN_B10 = 310, CFG_PIN_B11 = 311, CFG_PIN_B12 = 312, CFG_PIN_B13 = 313, CFG_PIN_B14 = 314, CFG_PIN_B15 = 315, CFG_PIN_B16 = 316, CFG_PIN_B17 = 317, CFG_PIN_B18 = 318, CFG_PIN_B19 = 319, CFG_PIN_B20 = 320, CFG_PIN_B21 = 321, CFG_PIN_B22 = 322, CFG_PIN_B23 = 323, CFG_PIN_B24 = 324, CFG_PIN_B25 = 325, CFG_PIN_B26 = 326, CFG_PIN_B27 = 327, CFG_PIN_B28 = 328, CFG_PIN_B29 = 329, CFG_PIN_B30 = 330, CFG_PIN_B31 = 331, CFG_PIN_C0 = 350, CFG_PIN_C1 = 351, CFG_PIN_C2 = 352, CFG_PIN_C3 = 353, CFG_PIN_C4 = 354, CFG_PIN_C5 = 355, CFG_PIN_C6 = 356, CFG_PIN_C7 = 357, CFG_PIN_C8 = 358, CFG_PIN_C9 = 359, CFG_PIN_C10 = 360, CFG_PIN_C11 = 361, CFG_PIN_C12 = 362, CFG_PIN_C13 = 363, CFG_PIN_C14 = 364, CFG_PIN_C15 = 365, CFG_PIN_C16 = 366, CFG_PIN_C17 = 367, CFG_PIN_C18 = 368, CFG_PIN_C19 = 369, CFG_PIN_C20 = 370, CFG_PIN_C21 = 371, CFG_PIN_C22 = 372, CFG_PIN_C23 = 373, CFG_PIN_C24 = 374, CFG_PIN_C25 = 375, CFG_PIN_C26 = 376, CFG_PIN_C27 = 377, CFG_PIN_C28 = 378, CFG_PIN_C29 = 379, CFG_PIN_C30 = 380, CFG_PIN_C31 = 381, CFG_PIN_P0 = 400, CFG_PIN_P1 = 401, CFG_PIN_P2 = 402, CFG_PIN_P3 = 403, CFG_PIN_P4 = 404, CFG_PIN_P5 = 405, CFG_PIN_P6 = 406, CFG_PIN_P7 = 407, CFG_PIN_P8 = 408, CFG_PIN_P9 = 409, CFG_PIN_P10 = 410, CFG_PIN_P11 = 411, CFG_PIN_P12 = 412, CFG_PIN_P13 = 413, CFG_PIN_P14 = 414, CFG_PIN_P15 = 415, CFG_PIN_P16 = 416, CFG_PIN_P17 = 417, CFG_PIN_P18 = 418, CFG_PIN_P19 = 419, CFG_PIN_P20 = 420, CFG_PIN_P21 = 421, CFG_PIN_P22 = 422, CFG_PIN_P23 = 423, CFG_PIN_P24 = 424, CFG_PIN_P25 = 425, CFG_PIN_P26 = 426, CFG_PIN_P27 = 427, CFG_PIN_P28 = 428, CFG_PIN_P29 = 429, CFG_PIN_P30 = 430, CFG_PIN_P31 = 431, CFG_PIN_P32 = 432, CFG_PIN_P33 = 433, CFG_PIN_P34 = 434, CFG_PIN_P35 = 435, CFG_PIN_P36 = 436, CFG_PIN_P37 = 437, CFG_PIN_P38 = 438, CFG_PIN_P39 = 439, CFG_PIN_P40 = 440, CFG_PIN_P41 = 441, CFG_PIN_P42 = 442, CFG_PIN_P43 = 443, CFG_PIN_P44 = 444, CFG_PIN_P45 = 445, CFG_PIN_P46 = 446, CFG_PIN_P47 = 447, CFG_PIN_P48 = 448, CFG_PIN_P49 = 449, CFG_PIN_P50 = 450, CFG_PIN_P51 = 451, CFG_PIN_P52 = 452, CFG_PIN_P53 = 453, CFG_PIN_P54 = 454, CFG_PIN_P55 = 455, CFG_PIN_P56 = 456, CFG_PIN_P57 = 457, CFG_PIN_P58 = 458, CFG_PIN_P59 = 459, CFG_PIN_P60 = 460, CFG_PIN_P61 = 461, CFG_PIN_P62 = 462, CFG_PIN_P63 = 463, CFG_PIN_LORA_MISO = 1001, CFG_PIN_LORA_MOSI = 1002, CFG_PIN_LORA_SCK = 1003, CFG_PIN_LORA_CS = 1004, CFG_PIN_LORA_BOOT = 1005, CFG_PIN_LORA_RESET = 1006, CFG_PIN_IRRXLED = 1007, CFG_PIN_IRTXLED = 1008, CFG_PIN_LCD_RESET = 1009, CFG_PIN_LCD_ENABLE = 1010, CFG_PIN_LCD_DATALINE4 = 1011, CFG_PIN_LCD_DATALINE5 = 1012, CFG_PIN_LCD_DATALINE6 = 1013, CFG_PIN_LCD_DATALINE7 = 1014, CFG_NUM_LCD_COLUMNS = 1015, CFG_NUM_LCD_ROWS = 1016, CFG_PIN_RCC0 = 1017, CFG_PIN_RCC1 = 1018, CFG_PIN_RCC2 = 1019, CFG_PIN_RCC3 = 1020, CFG_PIN_RCC4 = 1021, CFG_PIN_RCC5 = 1022, CFG_PIN_RCC6 = 1023, CFG_PIN_RCC7 = 1024, CFG_PIN_SERVO0 = 1025, CFG_PIN_SERVO1 = 1026, CFG_PIN_SERVO2 = 1027, CFG_PIN_SERVO3 = 1028, CFG_PIN_SERVO4 = 1029, CFG_PIN_SERVO5 = 1030, CFG_PIN_SERVO6 = 1031, CFG_PIN_SERVO7 = 1032, CFG_PIN_SERVO8 = 1033, CFG_PIN_PI_TX = 1034, CFG_PIN_PI_RX = 1035, CFG_PIN_GPS_SDA = 1036, CFG_PIN_GPS_SCL = 1037, CFG_PIN_GPS_TX = 1038, CFG_PIN_GPS_RX = 1039, CFG_PIN_GROVE0 = 1040, CFG_PIN_GROVE1 = 1041, CFG_PIN_SS = 1042, CFG_PIN_D33 = 183, CFG_PIN_D34 = 184, CFG_PIN_D35 = 185, CFG_PIN_D36 = 186, CFG_PIN_D37 = 187, CFG_PIN_D38 = 188, CFG_PIN_D39 = 189, CFG_PIN_D40 = 190, CFG_PIN_D41 = 191, CFG_PIN_D42 = 192, CFG_PIN_D43 = 193, CFG_PIN_D44 = 194, CFG_PIN_D45 = 195, CFG_PIN_D46 = 196, CFG_PIN_D47 = 197, CFG_PIN_D48 = 198, CFG_PIN_D49 = 199, CFG_PIN_D50 = 259, CFG_PIN_D51 = 260, CFG_PIN_D52 = 261, CFG_PIN_D53 = 262, CFG_PIN_TX1 = 263, CFG_PIN_TX2 = 264, CFG_PIN_TX3 = 265, CFG_PIN_RX1 = 266, CFG_PIN_RX2 = 267, CFG_PIN_RX3 = 268, CFG_PIN_SCL1 = 269, CFG_PIN_SDA1 = 270, CFG_PIN_PCC_D0 = 271, CFG_PIN_PCC_D1 = 272, CFG_PIN_PCC_D2 = 273, CFG_PIN_PCC_D3 = 274, CFG_PIN_PCC_D4 = 275, CFG_PIN_PCC_D5 = 276, CFG_PIN_PCC_D6 = 277, CFG_PIN_PCC_D7 = 278, CFG_PIN_PCC_D8 = 279, CFG_PIN_PCC_D9 = 280, CFG_PIN_PCC_D10 = 281, CFG_PIN_PCC_D11 = 282, CFG_PIN_PCC_D12 = 283, CFG_PIN_PCC_D13 = 284, CFG_PIN_CC_DEN1 = 285, CFG_PIN_CC_DEN2 = 286, CFG_PIN_CC_CLK = 287, CFG_PIN_XCC_CLK = 288, CFG_PIN_JDPWR_PRE_SENSE = 1100, CFG_PIN_JDPWR_GND_SENSE = 1101, CFG_PIN_JDPWR_PULSE = 1102, CFG_PIN_JDPWR_OVERLOAD_LED = 1103, CFG_PIN_JDPWR_ENABLE = 1104, CFG_PIN_JDPWR_FAULT = 1105, // /main/jacdac/JacdacBLE.h JACDAC_BLE_BUFFER_SIZE = 254, MICROBIT_JACDAC_S_EVT_RX = 1, MICROBIT_JACDAC_S_EVT_TX = 1, DEVICE_ID_JACDAC_BLE = 3056, JD_BLE_STATUS_IN_USE = 8, // /main/jacdac/jdprotocol.h JD_SERIAL_PAYLOAD_SIZE = 236, JD_SERIAL_FULL_HEADER_SIZE = 16, JD_SERVICE_CLASS_CTRL = 0, JD_SERVICE_NUMBER_CTRL = 0, JD_SERVICE_NUMBER_MASK = 63, JD_SERVICE_NUMBER_CRC_ACK = 63, JD_FRAME_FLAG_COMMAND = 1, JD_FRAME_FLAG_ACK_REQUESTED = 2, JD_FRAME_FLAG_IDENTIFIER_IS_SERVICE_CLASS = 4, JD_REG_INTENSITY = 1, JD_REG_VALUE = 2, JD_REG_IS_STREAMING = 3, JD_REG_STREAMING_INTERVAL = 4, JD_REG_LOW_THRESHOLD = 5, JD_REG_HIGH_THRESHOLD = 6, JD_REG_MAX_POWER = 7, JD_REG_READING = 257, JD_CMD_GET_REG = 4096, JD_CMD_SET_REG = 8192, JD_CMD_ADVERTISEMENT_DATA = 0, JD_CMD_EVENT = 1, JD_CMD_CALIBRATE = 2, JD_CMD_GET_DESCRIPTION = 3, JD_CMD_CTRL_NOOP = 128, JD_CMD_CTRL_IDENTIFY = 129, JD_CMD_CTRL_RESET = 130, JD_REG_CTRL_DEVICE_DESCRIPTION = 384, JD_REG_CTRL_DEVICE_CLASS = 385, JD_REG_CTRL_TEMPERATURE = 386, JD_REG_CTRL_LIGHT_LEVEL = 387, JD_REG_CTRL_BL_DEVICE_CLASS = 388, JDSPI_MAGIC = 31437, JDSPI_MAGIC_NOOP = 46029, // /main/pintarget.h DEVICE_PIN_EVT_RISE = 2, DEVICE_PIN_EVT_FALL = 3, DEVICE_PIN_EVT_PULSE_HI = 4, DEVICE_PIN_EVT_PULSE_LO = 5, DEVICE_PIN_EVENT_NONE = 0, DEVICE_PIN_EVENT_ON_EDGE = 1, DEVICE_PIN_EVENT_ON_PULSE = 2, DEVICE_PIN_EVENT_ON_TOUCH = 3, // /main/platform.h PXT_ESP32 = 1, PAGE_SIZE = 1024, DEV_NUM_PINS = 50, IMAGE_BITS = 4, // /main/pxt.h OUTPUT_BITS = 12, DEVICE_EVT_ANY = 0, DEVICE_ID_NOTIFY_ONE = 1022, DEVICE_ID_NOTIFY = 1023, DEVICE_ID_JACDAC = 30, DEVICE_ID_JACDAC_PHYS = 31, // /main/pxtbase.h PXT32 = 1, PXT64 = 1, PXT_REFCNT_FLASH = 65534, VTABLE_MAGIC = 249, VTABLE_MAGIC2 = 248, Undefined = 0, Boolean = 1, Number = 2, String = 3, Object = 4, BoxedString = 1, BoxedNumber = 2, BoxedBuffer = 3, RefAction = 4, RefImage = 5, RefCollection = 6, RefRefLocal = 7, RefMap = 8, RefMImage = 9, MMap = 10, BoxedString_SkipList = 11, BoxedString_ASCII = 12, ZPin = 13, User0 = 16, IMAGE_HEADER_MAGIC = 135, Int8LE = 1, UInt8LE = 2, Int16LE = 3, UInt16LE = 4, Int32LE = 5, Int8BE = 6, UInt8BE = 7, Int16BE = 8, UInt16BE = 9, Int32BE = 10, UInt32LE = 11, UInt32BE = 12, Float32LE = 13, Float64LE = 14, Float32BE = 15, Float64BE = 16, NUM_TRY_FRAME_REGS = 3, GC = 0, PXT_STRING_SKIP_INCR = 16, // /main/pxtconfig.h PXT_VM = 1, PXT_UF2_FAMILY = 3218951918, // /main/pxtcore.h PXT_HARD_FLOAT = 1, // /main/uf2hid.h UF2_HID_H = 1, HF2_CMD_BININFO = 1, HF2_MODE_BOOTLOADER = 1, HF2_MODE_USERSPACE = 2, HF2_CMD_INFO = 2, HF2_CMD_RESET_INTO_APP = 3, HF2_CMD_RESET_INTO_BOOTLOADER = 4, HF2_CMD_START_FLASH = 5, HF2_CMD_WRITE_FLASH_PAGE = 6, HF2_CMD_CHKSUM_PAGES = 7, HF2_CMD_READ_WORDS = 8, HF2_CMD_WRITE_WORDS = 9, HF2_CMD_DMESG = 16, HF2_EV_MASK = 8388608, HF2_CMD_JDS_CONFIG = 32, HF2_CMD_JDS_SEND = 33, HF2_EV_JDS_PACKET = 8388640, HF2_FLAG_SERIAL_OUT = 128, HF2_FLAG_SERIAL_ERR = 192, HF2_FLAG_CMDPKT_LAST = 64, HF2_FLAG_CMDPKT_BODY = 0, HF2_FLAG_MASK = 192, HF2_SIZE_MASK = 63, HF2_STATUS_OK = 0, HF2_STATUS_INVALID_CMD = 1, HF2_STATUS_INVALID_STATE = 2, // /main/vm.h VM_OPCODE_BASE_SIZE = 6, VM_OPCODE_ARG_POS = 7, VM_RTCALL_PUSH_MASK = 8192, VM_MAX_FUNCTION_STACK = 200, VM_STACK_SIZE = 1000, Invalid = 0, InfoHeader = 1, OpCodeMap = 2, NumberLiterals = 3, ConfigData = 4, IfaceMemberNames = 5, NumberBoxes = 6, Literal = 33, VTable = 34, PXT_WAIT_SOURCE_PROMISE = 131056, }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [cloudhsm](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscloudhsm.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Cloudhsm extends PolicyStatement { public servicePrefix = 'cloudhsm'; /** * Statement provider for service [cloudhsm](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscloudhsm.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); } /** * Adds or overwrites one or more tags for the specified AWS CloudHSM resource * * Access Level: Tagging * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_AddTagsToResource.html */ public toAddTagsToResource() { return this.to('AddTagsToResource'); } /** * Creates a copy of a backup in the specified region * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CopyBackupToRegion.html */ public toCopyBackupToRegion() { return this.to('CopyBackupToRegion'); } /** * Creates a new AWS CloudHSM cluster * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CreateCluster.html */ public toCreateCluster() { return this.to('CreateCluster'); } /** * Creates a high-availability partition group * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_CreateHapg.html */ public toCreateHapg() { return this.to('CreateHapg'); } /** * Creates a new hardware security module (HSM) in the specified AWS CloudHSM cluster * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_CreateHsm.html */ public toCreateHsm() { return this.to('CreateHsm'); } /** * Creates an HSM client * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_CreateLunaClient.html */ public toCreateLunaClient() { return this.to('CreateLunaClient'); } /** * Deletes the specified CloudHSM backup * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DeleteBackup.html */ public toDeleteBackup() { return this.to('DeleteBackup'); } /** * Deletes the specified AWS CloudHSM cluster * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DeleteCluster.html */ public toDeleteCluster() { return this.to('DeleteCluster'); } /** * Deletes a high-availability partition group * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_DeleteHapg.html */ public toDeleteHapg() { return this.to('DeleteHapg'); } /** * Deletes the specified HSM * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DeleteHsm.html */ public toDeleteHsm() { return this.to('DeleteHsm'); } /** * Deletes a client * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_DeleteLunaClient.html */ public toDeleteLunaClient() { return this.to('DeleteLunaClient'); } /** * Gets information about backups of AWS CloudHSM clusters * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeBackups.html */ public toDescribeBackups() { return this.to('DescribeBackups'); } /** * Gets information about AWS CloudHSM clusters * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_DescribeClusters.html */ public toDescribeClusters() { return this.to('DescribeClusters'); } /** * Retrieves information about a high-availability partition group * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_DescribeHapg.html */ public toDescribeHapg() { return this.to('DescribeHapg'); } /** * Retrieves information about an HSM. You can identify the HSM by its ARN or its serial number * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_DescribeHsm.html */ public toDescribeHsm() { return this.to('DescribeHsm'); } /** * Retrieves information about an HSM client * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_DescribeLunaClient.html */ public toDescribeLunaClient() { return this.to('DescribeLunaClient'); } /** * Gets the configuration files necessary to connect to all high availability partition groups the client is associated with * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_GetConfig.html */ public toGetConfig() { return this.to('GetConfig'); } /** * Claims an AWS CloudHSM cluster * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_InitializeCluster.html */ public toInitializeCluster() { return this.to('InitializeCluster'); } /** * Lists the Availability Zones that have available AWS CloudHSM capacity * * Access Level: List * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ListAvailableZones.html */ public toListAvailableZones() { return this.to('ListAvailableZones'); } /** * Lists the high-availability partition groups for the account * * Access Level: List * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ListHapgs.html */ public toListHapgs() { return this.to('ListHapgs'); } /** * Retrieves the identifiers of all of the HSMs provisioned for the current customer * * Access Level: List * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ListHsms.html */ public toListHsms() { return this.to('ListHsms'); } /** * Lists all of the clients * * Access Level: List * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ListLunaClients.html */ public toListLunaClients() { return this.to('ListLunaClients'); } /** * Gets a list of tags for the specified AWS CloudHSM cluster * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_ListTags.html */ public toListTags() { return this.to('ListTags'); } /** * Returns a list of all tags for the specified AWS CloudHSM resource * * Access Level: Read * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Modifies attributes for AWS CloudHSM backup * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_ModifyBackupAttributes.html */ public toModifyBackupAttributes() { return this.to('ModifyBackupAttributes'); } /** * Modifies AWS CloudHSM cluster. * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_ModifyCluster.html */ public toModifyCluster() { return this.to('ModifyCluster'); } /** * Modifies an existing high-availability partition group * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ModifyHapg.html */ public toModifyHapg() { return this.to('ModifyHapg'); } /** * Modifies an HSM * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ModifyHsm.html */ public toModifyHsm() { return this.to('ModifyHsm'); } /** * Modifies the certificate used by the client * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_ModifyLunaClient.html */ public toModifyLunaClient() { return this.to('ModifyLunaClient'); } /** * Removes one or more tags from the specified AWS CloudHSM resource * * Access Level: Tagging * * https://docs.aws.amazon.com/cloudhsm/classic/APIReference/API_RemoveTagsFromResource.html */ public toRemoveTagsFromResource() { return this.to('RemoveTagsFromResource'); } /** * Restores the specified CloudHSM backup * * Access Level: Write * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_RestoreBackup.html */ public toRestoreBackup() { return this.to('RestoreBackup'); } /** * Adds or overwrites one or more tags for the specified AWS CloudHSM cluster * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Removes the specified tag or tags from the specified AWS CloudHSM cluster * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/cloudhsm/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } protected accessLevelList: AccessLevelList = { "Tagging": [ "AddTagsToResource", "RemoveTagsFromResource", "TagResource", "UntagResource" ], "Write": [ "CopyBackupToRegion", "CreateCluster", "CreateHapg", "CreateHsm", "CreateLunaClient", "DeleteBackup", "DeleteCluster", "DeleteHapg", "DeleteHsm", "DeleteLunaClient", "InitializeCluster", "ModifyBackupAttributes", "ModifyCluster", "ModifyHapg", "ModifyHsm", "ModifyLunaClient", "RestoreBackup" ], "Read": [ "DescribeBackups", "DescribeClusters", "DescribeHapg", "DescribeHsm", "DescribeLunaClient", "GetConfig", "ListTags", "ListTagsForResource" ], "List": [ "ListAvailableZones", "ListHapgs", "ListHsms", "ListLunaClients" ] }; /** * Adds a resource of type backup to the statement * * https://docs.aws.amazon.com/cloudhsm/latest/userguide/backups.html * * @param cloudHsmBackupInstanceName - Identifier for the cloudHsmBackupInstanceName. * @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 onBackup(cloudHsmBackupInstanceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:cloudhsm:${Region}:${Account}:backup/${CloudHsmBackupInstanceName}'; arn = arn.replace('${CloudHsmBackupInstanceName}', cloudHsmBackupInstanceName); 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 cluster to the statement * * https://docs.aws.amazon.com/cloudhsm/latest/userguide/clusters.html * * @param cloudHsmClusterInstanceName - Identifier for the cloudHsmClusterInstanceName. * @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 onCluster(cloudHsmClusterInstanceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:cloudhsm:${Region}:${Account}:cluster/${CloudHsmClusterInstanceName}'; arn = arn.replace('${CloudHsmClusterInstanceName}', cloudHsmClusterInstanceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as SubscriptionUtil from "../../../../../main/js/joynr/dispatching/subscription/util/SubscriptionUtil"; import SubscriptionInformation from "../../../../../main/js/joynr/dispatching/types/SubscriptionInformation"; import SubscriptionRequest from "../../../../../main/js/joynr/dispatching/types/SubscriptionRequest"; import PeriodicSubscriptionQos from "../../../../../main/js/joynr/proxy/PeriodicSubscriptionQos"; import OnChangeSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeSubscriptionQos"; import OnChangeWithKeepAliveSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeWithKeepAliveSubscriptionQos"; import nanoid from "nanoid"; describe("libjoynr-js.joynr.dispatching.subscription.types.SubscriptionUtil", () => { let proxyId: any; let providerId: any; let testAttributeName: string; function createSubscriptionInformation( proxy: any, provider: any, periodMs: number, subscriptionLength: any, onChange: any, minIntervalMs: number ) { let qosSettings: any; if (onChange) { if (periodMs !== undefined) { qosSettings = new OnChangeWithKeepAliveSubscriptionQos({ minIntervalMs: minIntervalMs || 0, maxIntervalMs: periodMs, expiryDateMs: Date.now() + subscriptionLength, alertAfterIntervalMs: 0, publicationTtlMs: 1000 }); } else { qosSettings = new OnChangeSubscriptionQos({ minIntervalMs: minIntervalMs || 0, expiryDateMs: Date.now() + subscriptionLength, publicationTtlMs: 1000 }); } } else { qosSettings = new PeriodicSubscriptionQos({ periodMs, expiryDateMs: Date.now() + subscriptionLength, alertAfterIntervalMs: 0, publicationTtlMs: 1000 }); } return new SubscriptionInformation( SubscriptionInformation.SUBSCRIPTION_TYPE_ATTRIBUTE, proxy, provider, new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testAttributeName, qos: qosSettings }) ); } function buildString(info: any) { return `${'{"subscriptionType":"'}${info.subscriptionType}","proxyParticipantId":"${ info.proxyParticipantId }","providerParticipantId":"${info.providerParticipantId}","subscriptionId":"${ info.subscriptionId }","subscribedToName":"${ info.subscribedToName }","qos":{"_typeName":"joynr.OnChangeWithKeepAliveSubscriptionQos","alertAfterIntervalMs":0,"maxIntervalMs":${ info.qos.maxIntervalMs },"minIntervalMs":${info.qos.minIntervalMs},"expiryDateMs":${ info.qos.expiryDateMs },"publicationTtlMs":1000},"lastPublication":0,"_typeName":"joynr.SubscriptionInformation"}`; } /** * Called before each test. */ beforeEach(() => { proxyId = `proxy${nanoid()}`; providerId = `provider${nanoid()}`; testAttributeName = "testAttribute"; }); it("serialize single subscription shall work", () => { const info = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const subscriptions = { [info.subscriptionId]: info }; const serializedSubscriptions = SubscriptionUtil.serializeSubscriptions(subscriptions); const expectedString = `[${buildString(info)}]`; expect(JSON.parse(serializedSubscriptions)).toEqual(JSON.parse(expectedString)); }); it("serialize multiple subscription shall work", () => { const info1 = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const info2 = createSubscriptionInformation(proxyId, providerId, 300, 1000, true, 60); const info3 = createSubscriptionInformation(proxyId, providerId, 400, 1000, true, 70); const subscriptions = { [info1.subscriptionId]: info1, [info2.subscriptionId]: info2, [info3.subscriptionId]: info3 }; const serializedSubscriptions = SubscriptionUtil.serializeSubscriptions(subscriptions); const expectedString = `[${buildString(info1)},${buildString(info2)},${buildString(info3)}]`; expect(JSON.parse(serializedSubscriptions)).toEqual(JSON.parse(expectedString)); }); it("deserialize single subscription shall work", () => { const info = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const serializedSubscription = `[${buildString(info)}]`; const subscriptions = SubscriptionUtil.deserializeSubscriptions(serializedSubscription); expect(subscriptions[info.subscriptionId].subscriptionId).toBe(info.subscriptionId); expect(subscriptions[info.subscriptionId].subscribedToName).toBe(info.subscribedToName); expect(subscriptions[info.subscriptionId].proxyParticipantId).toBe(info.proxyParticipantId); expect(subscriptions[info.subscriptionId].providerParticipantId).toBe(info.providerParticipantId); expect(subscriptions[info.subscriptionId].qos.minIntervalMs).toBe(info.qos.minIntervalMs); expect(subscriptions[info.subscriptionId].qos.maxIntervalMs).toBe(info.qos.maxIntervalMs); }); it("createMulticastId", () => { expect(SubscriptionUtil.createMulticastId("a", "b")).toEqual("a/b"); expect(SubscriptionUtil.createMulticastId("a", "b", [])).toEqual("a/b"); expect(SubscriptionUtil.createMulticastId("a", "b", ["c"])).toEqual("a/b/c"); expect(SubscriptionUtil.createMulticastId("a", "b", ["c", "d"])).toEqual("a/b/c/d"); expect(SubscriptionUtil.createMulticastId("a", "b", ["c", "d", "e"])).toEqual("a/b/c/d/e"); expect(SubscriptionUtil.createMulticastId("a", "b", ["c", "d", "e", "f"])).toEqual("a/b/c/d/e/f"); }); it("deserialize multiple subscriptions shall work", () => { const info1 = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const info2 = createSubscriptionInformation(proxyId, providerId, 201, 1000, true, 77); const serializedSubscription = `[${buildString(info1)},${buildString(info2)}]`; const subscriptions = SubscriptionUtil.deserializeSubscriptions(serializedSubscription); expect(subscriptions[info1.subscriptionId].subscriptionId).toBe(info1.subscriptionId); expect(subscriptions[info1.subscriptionId].subscribedToName).toBe(info1.subscribedToName); expect(subscriptions[info1.subscriptionId].proxyParticipantId).toBe(info1.proxyParticipantId); expect(subscriptions[info1.subscriptionId].providerParticipantId).toBe(info1.providerParticipantId); expect(subscriptions[info1.subscriptionId].qos.minIntervalMs).toBe(info1.qos.minIntervalMs); expect(subscriptions[info1.subscriptionId].qos.maxIntervalMs).toBe(info1.qos.maxIntervalMs); expect(subscriptions[info2.subscriptionId].subscriptionId).toBe(info2.subscriptionId); expect(subscriptions[info2.subscriptionId].subscribedToName).toBe(info2.subscribedToName); expect(subscriptions[info2.subscriptionId].proxyParticipantId).toBe(info2.proxyParticipantId); expect(subscriptions[info2.subscriptionId].providerParticipantId).toBe(info2.providerParticipantId); expect(subscriptions[info2.subscriptionId].qos.minIntervalMs).toBe(info2.qos.minIntervalMs); expect(subscriptions[info2.subscriptionId].qos.maxIntervalMs).toBe(info2.qos.maxIntervalMs); let subscriptionId: any; for (subscriptionId in subscriptions) { if (subscriptions.hasOwnProperty(subscriptionId)) { expect(subscriptionId === info1.subscriptionId || subscriptionId === info2.subscriptionId).toBe(true); } } }); it("deserialize and deserialize single subscription shall work", () => { const origin = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const subscriptions = { [origin.subscriptionId]: origin }; const serializedSubscription = SubscriptionUtil.serializeSubscriptions(subscriptions); const newSubscriptions = SubscriptionUtil.deserializeSubscriptions(serializedSubscription); expect(newSubscriptions[origin.subscriptionId].subscriptionId).toBe(origin.subscriptionId); expect(newSubscriptions[origin.subscriptionId].subscribedToName).toBe(origin.subscribedToName); expect(newSubscriptions[origin.subscriptionId].proxyParticipantId).toBe(origin.proxyParticipantId); expect(newSubscriptions[origin.subscriptionId].providerParticipantId).toBe(origin.providerParticipantId); expect(newSubscriptions[origin.subscriptionId].qos.minIntervalMs).toBe(origin.qos.minIntervalMs); expect(newSubscriptions[origin.subscriptionId].qos.maxIntervalMs).toBe(origin.qos.maxIntervalMs); }); it("deserialize and deserialize multiple subscriptions shall work", () => { const origin1 = createSubscriptionInformation(proxyId, providerId, 200, 1000, true, 50); const origin2 = createSubscriptionInformation(proxyId, providerId, 180, 660, true, 70); const subscriptions = { [origin1.subscriptionId]: origin1, [origin2.subscriptionId]: origin2 }; const serializedSubscription = SubscriptionUtil.serializeSubscriptions(subscriptions); const newSubscriptions = SubscriptionUtil.deserializeSubscriptions(serializedSubscription); expect(newSubscriptions[origin1.subscriptionId].subscriptionId).toBe(origin1.subscriptionId); expect(newSubscriptions[origin1.subscriptionId].subscribedToName).toBe(origin1.subscribedToName); expect(newSubscriptions[origin1.subscriptionId].proxyParticipantId).toBe(origin1.proxyParticipantId); expect(newSubscriptions[origin1.subscriptionId].providerParticipantId).toBe(origin1.providerParticipantId); expect(newSubscriptions[origin1.subscriptionId].qos.minIntervalMs).toBe(origin1.qos.minIntervalMs); expect(newSubscriptions[origin1.subscriptionId].qos.maxIntervalMs).toBe(origin1.qos.maxIntervalMs); expect(newSubscriptions[origin2.subscriptionId].subscriptionId).toBe(origin2.subscriptionId); expect(newSubscriptions[origin2.subscriptionId].subscribedToName).toBe(origin2.subscribedToName); expect(newSubscriptions[origin2.subscriptionId].proxyParticipantId).toBe(origin2.proxyParticipantId); expect(newSubscriptions[origin2.subscriptionId].providerParticipantId).toBe(origin2.providerParticipantId); expect(newSubscriptions[origin2.subscriptionId].qos.minIntervalMs).toBe(origin2.qos.minIntervalMs); expect(newSubscriptions[origin2.subscriptionId].qos.maxIntervalMs).toBe(origin2.qos.maxIntervalMs); }); describe("validatePartitions", () => { it("does not throw with valid partitions", () => { expect(() => { SubscriptionUtil.validatePartitions(["a", "b", "0", "D", "Z"]); }).not.toThrow(); }); it("throws with invalid partitions", () => { expect(() => { SubscriptionUtil.validatePartitions([""]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["_"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["./$"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["\uD83D"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["\uDE33"]); }).toThrow(); }); it("supports the plus sign", () => { expect(() => { SubscriptionUtil.validatePartitions(["a", "b", "+", "c"]); }).not.toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["+"]); }).not.toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["a", "+"]); }).not.toThrow(); }); it("throws if plus sign is conjugated with characters in one partition", () => { expect(() => { SubscriptionUtil.validatePartitions(["+xy"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["x+y"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["xy+"]); }).toThrow(); }); it("throws if star is not the last partition", () => { expect(() => { SubscriptionUtil.validatePartitions(["*", "1"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["1", "*", "2"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["1", "2", "3", "*", "4", "5", "6"]); }).toThrow(); }); it("throws if star is conjugated with characters in one partition", () => { expect(() => { SubscriptionUtil.validatePartitions(["*xy"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["x*y"]); }).toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["xy*"]); }).toThrow(); }); it("supports combinations of plus sign and star", () => { expect(() => { SubscriptionUtil.validatePartitions(["+", "+", "*"]); }).not.toThrow(); }); it("does not throw if star is the last partition", () => { expect(() => { SubscriptionUtil.validatePartitions(["*"]); }).not.toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["1", "*"]); }).not.toThrow(); expect(() => { SubscriptionUtil.validatePartitions(["1", "2", "3", "4", "5", "6", "*"]); }).not.toThrow(); }); }); });
the_stack
import { Meteor } from 'meteor/meteor' import * as _ from 'underscore' import { PeripheralDevices, PeripheralDevice } from '../../lib/collections/PeripheralDevices' import { getCurrentTime, Time, unprotectString, getRandomId, assertNever } from '../../lib/lib' import { PeripheralDeviceAPI } from '../../lib/api/peripheralDevice' import { parseVersion, parseRange } from '../../lib/collections/CoreSystem' import { StatusResponse, CheckObj, ExternalStatus, CheckError, SystemInstanceId } from '../../lib/api/systemStatus' import { getRelevantSystemVersions } from '../coreSystem' import * as semver from 'semver' import { StudioId } from '../../lib/collections/Studios' import { OrganizationId } from '../../lib/collections/Organization' import { Settings } from '../../lib/Settings' import { StudioReadAccess } from '../security/studio' import { OrganizationReadAccess } from '../security/organization' import { resolveCredentials, Credentials } from '../security/lib/credentials' import { triggerWriteAccessBecauseNoCheckNecessary } from '../security/lib/securityVerify' import { SystemWriteAccess } from '../security/system' /** * Handling of system statuses */ /** Enum for the different status codes in the system */ export enum StatusCode { /** Status unknown */ UNKNOWN = 0, /** All good and green */ GOOD = 1, /** Everything is not OK, operation is not affected */ WARNING_MINOR = 2, /** Everything is not OK, operation might be affected */ WARNING_MAJOR = 3, /** Operation affected, possible to recover */ BAD = 4, /** Operation affected, not possible to recover without manual interference */ FATAL = 5, } export interface StatusObject { studioId?: StudioId statusCode: StatusCode messages?: Array<string> } export interface StatusObjectInternal { studioId?: StudioId statusCode: StatusCode /** Timestamp when statusCode was last changed */ timestamp: Time messages: Array<{ message: string /** Timestamp when message appeared first */ timestamp: Time }> } /** * Returns system status * @param studioId (Optional) If provided, limits the status to what's affecting the studio */ export function getSystemStatus(cred0: Credentials, studioId?: StudioId): StatusResponse { let checks: Array<CheckObj> = [] SystemWriteAccess.systemStatusRead(cred0) // Check systemStatuses: _.each(systemStatuses, (status: StatusObjectInternal, key: string) => { checks.push({ description: key, status: status2ExternalStatus(status.statusCode), updated: new Date(status.timestamp).toISOString(), _status: status.statusCode, errors: _.map( status.messages || [], (m): CheckError => { return { type: 'message', time: new Date(m.timestamp).toISOString(), message: m.message, } } ), }) }) let statusObj: StatusResponse = { name: 'Sofie Automation system', instanceId: instanceId, updated: new Date(getCurrentTime()).toISOString(), status: 'UNDEFINED', _status: StatusCode.UNKNOWN, documentation: 'https://github.com/nrkno/tv-automation-server-core', _internal: { // this _internal is set later statusCodeString: StatusCode[StatusCode.UNKNOWN], messages: [], versions: {}, }, checks: checks, } let devices: PeripheralDevice[] = [] if (studioId) { if (!StudioReadAccess.studioContent({ studioId: studioId }, cred0)) { throw new Meteor.Error(403, `Not allowed`) } devices = PeripheralDevices.find({ studioId: studioId }).fetch() } else { if (Settings.enableUserAccounts) { const cred = resolveCredentials(cred0) if (!cred.organization) throw new Meteor.Error(500, 'user has no organization') if (!OrganizationReadAccess.organizationContent({ organizationId: cred.organization._id }, cred)) { throw new Meteor.Error(403, `Not allowed`) } devices = PeripheralDevices.find({ organizationId: cred.organization._id }).fetch() } else { devices = PeripheralDevices.find({}).fetch() } } _.each(devices, (device: PeripheralDevice) => { let deviceStatus: StatusCode = device.status.statusCode let deviceStatusMessages: Array<string> = device.status.messages || [] let checks: Array<CheckObj> = [] if (deviceStatus === StatusCode.GOOD) { if (device.expectedVersions) { if (!device.versions) device.versions = {} let deviceVersions = device.versions _.each(device.expectedVersions, (expectedVersionStr, libraryName: string) => { let versionStr = deviceVersions[libraryName] let version = parseVersion(versionStr || '0.0.0') let expectedVersion = parseRange(expectedVersionStr) let statusCode = StatusCode.GOOD let messages: Array<string> = [] if (semver.satisfies(version, '0.0.0')) { // if the major version is 0.0.0, ignore it } else if (!versionStr) { statusCode = StatusCode.BAD messages.push(`${libraryName}: Expected version ${expectedVersionStr}, got undefined`) } else if (!semver.satisfies(version, expectedVersion)) { statusCode = StatusCode.BAD let message = `Version for ${libraryName}: "${versionStr}" does not satisy expected version "${expectedVersionStr}"` const version0 = semver.coerce(version) const expectedVersion0 = semver.coerce(expectedVersion) if (version0 && expectedVersion0 && version0.major !== expectedVersion0.major) { statusCode = StatusCode.BAD message = `${libraryName}: Expected version ${expectedVersionStr}, got ${versionStr} (major version differ)` } else if (version0 && expectedVersion0 && version0.minor < expectedVersion0.minor) { statusCode = StatusCode.WARNING_MAJOR message = `${libraryName}: Expected version ${expectedVersionStr}, got ${versionStr} (minor version differ)` } else if ( version0 && expectedVersion0 && version0.minor <= expectedVersion0.minor && version0.patch < expectedVersion0.patch ) { statusCode = StatusCode.WARNING_MINOR message = `${libraryName}: Expected version ${expectedVersionStr}, got ${versionStr} (patch version differ)` } messages.push(message) } checks.push({ description: `expectedVersion.${libraryName}`, status: status2ExternalStatus(statusCode), updated: new Date(device.lastSeen).toISOString(), _status: statusCode, errors: _.map( messages, (message: string): CheckError => { return { type: 'version-differ', time: new Date(device.lastSeen).toISOString(), message: message, } } ), }) }) } } let so: StatusResponse = { name: device.name, instanceId: device._id, status: 'UNDEFINED', updated: new Date(device.lastSeen).toISOString(), _status: deviceStatus, documentation: '', statusMessage: deviceStatusMessages.length ? deviceStatusMessages.join(', ') : undefined, _internal: { // statusCode: deviceStatus, statusCodeString: StatusCode[deviceStatus], messages: deviceStatusMessages, versions: device.versions || {}, }, checks: checks, } if (device.type === PeripheralDeviceAPI.DeviceType.MOS) { so.documentation = 'https://github.com/nrkno/tv-automation-mos-gateway' } else if (device.type === PeripheralDeviceAPI.DeviceType.SPREADSHEET) { so.documentation = 'https://github.com/SuperFlyTV/spreadsheet-gateway' } else if (device.type === PeripheralDeviceAPI.DeviceType.PLAYOUT) { so.documentation = 'https://github.com/nrkno/tv-automation-playout-gateway' } else if (device.type === PeripheralDeviceAPI.DeviceType.MEDIA_MANAGER) { so.documentation = 'https://github.com/nrkno/tv-automation-media-management' } else if (device.type === PeripheralDeviceAPI.DeviceType.INEWS) { so.documentation = 'https://github.com/olzzon/tv2-inews-ftp-gateway' } else if (device.type === PeripheralDeviceAPI.DeviceType.PACKAGE_MANAGER) { so.documentation = 'https://github.com/nrkno/tv-automation-package-manager' } else { assertNever(device.type) } if (!statusObj.components) statusObj.components = [] statusObj.components.push(so) }) let systemStatus: StatusCode = setStatus(statusObj) statusObj._internal = { // statusCode: systemStatus, statusCodeString: StatusCode[systemStatus], messages: collectMesages(statusObj), versions: getRelevantSystemVersions(), } statusObj.statusMessage = statusObj._internal.messages.join(', ') return statusObj } export function setSystemStatus(type: string, status: StatusObject) { let systemStatus: StatusObjectInternal = systemStatuses[type] if (!systemStatus) { systemStatus = { statusCode: StatusCode.UNKNOWN, timestamp: 0, messages: [], } systemStatuses[type] = systemStatus } if (systemStatus.statusCode !== status.statusCode) { systemStatus.statusCode = status.statusCode systemStatus.timestamp = getCurrentTime() } let messages: Array<{ message: string timestamp: Time }> = [] if (status.messages) { _.each(status.messages, (message) => { let m = _.find(systemStatus.messages, (m) => m.message === message) if (m) { messages.push(m) } else { messages.push({ message: message, timestamp: getCurrentTime(), }) } }) } systemStatus.messages = messages } export function removeSystemStatus(type: string) { delete systemStatuses[type] } /** Random id for this running instance of core */ const instanceId: SystemInstanceId = getRandomId() /** Map of surrent system statuses */ const systemStatuses: { [key: string]: StatusObjectInternal } = {} function setStatus(statusObj: StatusResponse): StatusCode { let s: StatusCode = statusObj._status if (statusObj.checks) { _.each(statusObj.checks, (check: CheckObj) => { if (check._status > s) s = check._status }) } if (statusObj.components) { _.each(statusObj.components, (component: StatusResponse) => { let s2: StatusCode = setStatus(component) if (s2 > s) s = s2 }) } statusObj.status = status2ExternalStatus(s) statusObj._status = s return s } function collectMesages(statusObj: StatusResponse): Array<string> { let allMessages: Array<string> = [] if (statusObj._internal) { _.each(statusObj._internal.messages, (msg) => { allMessages.push(msg) }) } if (statusObj.checks) { _.each(statusObj.checks, (check: CheckObj) => { if (check._status !== StatusCode.GOOD && check.errors) { _.each(check.errors, (errMsg) => { allMessages.push(`check ${check.description}: ${errMsg.message}`) }) } }) } if (statusObj.components) { _.each(statusObj.components, (component: StatusResponse) => { let messages = collectMesages(component) _.each(messages, (msg) => { allMessages.push(`${component.name}: ${msg}`) }) }) } return allMessages } export function status2ExternalStatus(statusCode: StatusCode): ExternalStatus { if (statusCode === StatusCode.GOOD) { return 'OK' } else if (statusCode === StatusCode.WARNING_MINOR || statusCode === StatusCode.WARNING_MAJOR) { return 'WARNING' } else if (statusCode === StatusCode.BAD || statusCode === StatusCode.FATAL) { return 'FAIL' } return 'UNDEFINED' }
the_stack
import { assert } from 'chai'; import { anyString, anything, instance, mock, verify, when } from 'ts-mockito'; import * as sinon from 'sinon'; import * as os from 'os'; import { QuickPickItem } from 'vscode'; import { ApplicationShell } from '../../../client/common/application/applicationShell'; import { ClipboardService } from '../../../client/common/application/clipboard'; import { CommandManager } from '../../../client/common/application/commandManager'; import { IClipboard, ICommandManager } from '../../../client/common/application/types'; import { ConfigurationService } from '../../../client/common/configuration/service'; import { IJupyterSettings } from '../../../client/common/types'; import { DataScience } from '../../../client/common/utils/localize'; import { MultiStepInput, MultiStepInputFactory } from '../../../client/common/utils/multiStepInput'; import { Settings } from '../../../client/datascience/constants'; import { JupyterServerSelector } from '../../../client/datascience/jupyter/serverSelector'; import { JupyterUriProviderRegistration } from '../../../client/datascience/jupyterUriProviderRegistration'; import { MockInputBox } from '../mockInputBox'; import { MockQuickPick } from '../mockQuickPick'; import { JupyterServerUriStorage } from '../../../client/datascience/jupyter/serverUriStorage'; import { MockMemento } from '../../mocks/mementos'; import { WorkspaceService } from '../../../client/common/application/workspace'; import { CryptoUtils } from '../../../client/common/crypto'; import { ApplicationEnvironment } from '../../../client/common/application/applicationEnvironment'; import { MockEncryptedStorage } from '../mockEncryptedStorage'; /* eslint-disable , @typescript-eslint/no-explicit-any */ suite('DataScience - Jupyter Server URI Selector', () => { let quickPick: MockQuickPick | undefined; let cmdManager: ICommandManager; let dsSettings: IJupyterSettings; let clipboard: IClipboard; let setting: string; function createDataScienceObject( quickPickSelection: string, inputSelection: string, hasFolders: boolean ): { selector: JupyterServerSelector; storage: JupyterServerUriStorage } { dsSettings = { jupyterServerType: Settings.JupyterServerLocalLaunch // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; clipboard = mock(ClipboardService); const configService = mock(ConfigurationService); const applicationShell = mock(ApplicationShell); const applicationEnv = mock(ApplicationEnvironment); const workspaceService = mock(WorkspaceService); const picker = mock(JupyterUriProviderRegistration); const crypto = mock(CryptoUtils); when(crypto.createHash(anyString(), 'string')).thenCall((a1, _a2) => a1); cmdManager = mock(CommandManager); quickPick = new MockQuickPick(quickPickSelection); const input = new MockInputBox(inputSelection); when(cmdManager.executeCommand(anything(), anything())).thenResolve(); when(applicationShell.createQuickPick()).thenReturn(quickPick!); when(applicationShell.createInputBox()).thenReturn(input); when(applicationEnv.machineId).thenReturn(os.hostname()); const multiStepFactory = new MultiStepInputFactory(instance(applicationShell)); // eslint-disable-next-line @typescript-eslint/no-explicit-any when(configService.getSettings(anything())).thenReturn(dsSettings as any); when(configService.updateSetting(anything(), anything(), anything(), anything())).thenCall((_s, v) => { setting = v; return Promise.resolve(); }); when(workspaceService.getWorkspaceFolderIdentifier(anything())).thenReturn('1'); when(workspaceService.hasWorkspaceFolders).thenReturn(hasFolders); const encryptedStorage = new MockEncryptedStorage(); const storage = new JupyterServerUriStorage( instance(configService), instance(workspaceService), instance(crypto), encryptedStorage, instance(applicationEnv), new MockMemento() ); const selector = new JupyterServerSelector( instance(clipboard), multiStepFactory, instance(cmdManager), instance(picker), storage ); return { selector, storage }; } teardown(() => sinon.restore()); test('Local pick server uri', async () => { const { selector, storage } = createDataScienceObject('$(zap) Default', '', true); await selector.selectJupyterURI(true); let value = await storage.getUri(); assert.equal(value, Settings.JupyterServerLocalLaunch, 'Default should pick local launch'); // Try a second time. await selector.selectJupyterURI(true); value = await storage.getUri(); assert.equal(value, Settings.JupyterServerLocalLaunch, 'Default should pick local launch'); // Verify active items assert.equal(quickPick?.items.length, 2, 'Wrong number of items in the quick pick'); }); test('Local pick server uri with no workspace', async () => { const { selector, storage } = createDataScienceObject('$(zap) Default', '', false); await selector.selectJupyterURI(true); let value = await storage.getUri(); assert.equal(value, Settings.JupyterServerLocalLaunch, 'Default should pick local launch'); // Try a second time. await selector.selectJupyterURI(true); value = await storage.getUri(); assert.equal(value, Settings.JupyterServerLocalLaunch, 'Default should pick local launch'); // Verify active items assert.equal(quickPick?.items.length, 2, 'Wrong number of items in the quick pick'); }); test('Quick pick MRU tests', async () => { const { selector, storage } = createDataScienceObject('$(zap) Default', '', true); await selector.selectJupyterURI(true); // Verify initial default items assert.equal(quickPick?.items.length, 2, 'Wrong number of items in the quick pick'); // Add in a new server const serverA1 = { uri: 'ServerA', time: 1, date: new Date(1) }; await storage.addToUriList(serverA1.uri, serverA1.time, serverA1.uri); await selector.selectJupyterURI(true); assert.equal(quickPick?.items.length, 3, 'Wrong number of items in the quick pick'); quickPickCheck(quickPick?.items[2], serverA1); // Add in a second server, the newer server should be higher in the list due to newer time const serverB1 = { uri: 'ServerB', time: 2, date: new Date(2) }; await storage.addToUriList(serverB1.uri, serverB1.time, serverB1.uri); await selector.selectJupyterURI(true); assert.equal(quickPick?.items.length, 4, 'Wrong number of items in the quick pick'); quickPickCheck(quickPick?.items[2], serverB1); quickPickCheck(quickPick?.items[3], serverA1); // Reconnect to server A with a new time, it should now be higher in the list const serverA3 = { uri: 'ServerA', time: 3, date: new Date(3) }; await storage.addToUriList(serverA3.uri, serverA3.time, serverA3.uri); await selector.selectJupyterURI(true); assert.equal(quickPick?.items.length, 4, 'Wrong number of items in the quick pick'); quickPickCheck(quickPick?.items[3], serverB1); quickPickCheck(quickPick?.items[2], serverA1); // Verify that we stick to our settings limit for (let i = 0; i < Settings.JupyterServerUriListMax + 10; i = i + 1) { await storage.addToUriList(i.toString(), i, i.toString()); } await selector.selectJupyterURI(true); // Need a plus 2 here for the two default items assert.equal( quickPick?.items.length, Settings.JupyterServerUriListMax + 2, 'Wrong number of items in the quick pick' ); }); function quickPickCheck(item: QuickPickItem | undefined, expected: { uri: string; time: Number; date: Date }) { assert.isOk(item, 'Quick pick item not defined'); if (item) { assert.equal(item.label, expected.uri, 'Wrong URI value in quick pick'); assert.equal( item.detail, DataScience.jupyterSelectURIMRUDetail().format(expected.date.toLocaleString()), 'Wrong detail value in quick pick' ); } } test('Remote server uri', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', true); await selector.selectJupyterURI(true); const value = await storage.getUri(); assert.equal(value, 'http://localhost:1111', 'Already running should end up with the user inputed value'); assert.equal(setting, 'remote'); }); test('Remote server uri no workspace', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', false); await selector.selectJupyterURI(true); const value = await storage.getUri(); assert.equal(value, 'http://localhost:1111', 'Already running should end up with the user inputed value'); assert.equal(setting, 'remote'); }); test('Remote server uri no local', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', true); await selector.selectJupyterURI(false); const value = await storage.getUri(); assert.equal(value, 'http://localhost:1111', 'Already running should end up with the user inputed value'); }); test('Remote server uri (reload VSCode if there is a change in settings)', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', true); await selector.selectJupyterURI(true); const value = await storage.getUri(); assert.equal(value, 'http://localhost:1111', 'Already running should end up with the user inputed value'); verify(cmdManager.executeCommand(anything(), anything())).once(); }); test('Remote server uri (do not reload VSCode if there is no change in settings)', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', true); await storage.setUri('http://localhost:1111'); await selector.selectJupyterURI(true); const value = await storage.getUri(); assert.equal(value, 'http://localhost:1111', 'Already running should end up with the user inputed value'); verify(cmdManager.executeCommand(anything(), anything())).never(); }); test('Invalid server uri', async () => { const { selector, storage } = createDataScienceObject('$(server) Existing', 'httx://localhost:1111', true); await selector.selectJupyterURI(true); const value = await storage.getUri(); assert.notEqual(value, 'httx://localhost:1111', 'Already running should validate'); assert.equal(value, 'local', 'Validation failed'); }); suite('Default Uri when selecting remote uri', () => { const defaultUri = 'https://hostname:8080/?token=849d61a414abafab97bc4aab1f3547755ddc232c2b8cb7fe'; async function testDefaultUri(expectedDefaultUri: string, clipboardValue?: string) { const showInputBox = sinon.spy(MultiStepInput.prototype, 'showInputBox'); const { selector } = createDataScienceObject('$(server) Existing', 'http://localhost:1111', true); when(clipboard.readText()).thenResolve(clipboardValue || ''); await selector.selectJupyterURI(true); assert.equal(showInputBox.firstCall.args[0].value, expectedDefaultUri); } test('Display default uri', async () => { await testDefaultUri(defaultUri); }); test('Display default uri if clipboard is empty', async () => { await testDefaultUri(defaultUri, ''); }); test('Display default uri if clipboard contains invalid uri, display default uri', async () => { await testDefaultUri(defaultUri, 'Hello World!'); }); test('Display default uri if clipboard contains invalid file uri, display default uri', async () => { await testDefaultUri(defaultUri, 'file://test.pdf'); }); test('Display default uri if clipboard contains a valid uri, display uri from clipboard', async () => { const validUri = 'https://wow:0909/?password=1234'; await testDefaultUri(validUri, validUri); }); }); });
the_stack
import { TreeGrid } from '../../src/treegrid/base/treegrid'; import { createGrid, destroy } from '../base/treegridutil.spec'; import { sampleData, projectData2, unorederedData, projectData, virtualData} from '../base/datasource.spec'; import { getObject } from '@syncfusion/ej2-grids'; import { EmitType } from '@syncfusion/ej2-base'; import { RowDD } from '../../src/treegrid/actions/rowdragdrop'; import { VirtualScroll } from '../../src/treegrid/actions/virtual-scroll'; import { ITreeData } from '../../src'; import { getMemoryProfile, inMB, profile } from '../common.spec'; /** * TreeGrid Indent and Outdent action spec */ TreeGrid.Inject(RowDD, VirtualScroll); describe('IndentOutdent action', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('EJ2-58872 - Indent/Outdent action check when persistSelection is enabled ', () => { let TreeGridObj: TreeGrid; let actionComplete: () => void; beforeAll((done: Function) => { TreeGridObj = createGrid( { dataSource: sampleData, childMapping: 'subtasks', treeColumnIndex: 1, height: 400, toolbar: ['Indent', 'Outdent'], selectionSettings: { enableToggle: true, mode: 'Row', type: 'Multiple', persistSelection: true, }, columns: [ { field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right', validationRules: { required: true, number: true }, width: 90, }, { field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, validationRules: { required: true }, }, { field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit', format: 'yMd', validationRules: { date: true }, }, { field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 100, editType: 'numericedit', validationRules: { number: true, min: 0 }, edit: { params: { format: 'n' } }, }, ] },done); }); it('Indent/Outdent icon updated check', (done: Function) => { actionComplete = (): void => { expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_indent').parentElement.classList.contains("e-hidden")).toBe(false); expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_outdent').parentElement.classList.contains("e-hidden")).toBe(true); done(); } TreeGridObj.actionComplete = actionComplete; TreeGridObj.selectRow(1); (<any>TreeGridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: TreeGridObj.grid.element.id + '_outdent' } }); TreeGridObj.rowDragAndDropModule.destroy(); }); afterAll(() => { destroy(TreeGridObj); }); }); describe('EJ2-59000 - Indent/Outdent action check with virtualization ', () => { let TreeGridObj: TreeGrid; let actionComplete: () => void; beforeAll((done: Function) => { TreeGridObj = createGrid( { toolbar: [ 'Indent', 'Outdent'], dataSource: virtualData.slice(0,100), parentIdMapping: 'ParentID', idMapping: 'TaskID', height: 200, enableVirtualization: true, columns: [ { field: 'TaskID', headerText: 'ID', isPrimaryKey: true, width: 140 }, { field: 'FIELD1', headerText: 'Player Name', width: 140 }, { field: 'FIELD2', headerText: 'Year', width: 120, textAlign: 'Right' }, { field: 'FIELD3', headerText: 'Stint', width: 120, textAlign: 'Right' }, { field: 'FIELD4', headerText: 'TMID', width: 120, textAlign: 'Right' }, { field: 'FIELD5', headerText: 'LGID', width: 120, textAlign: 'Right' }, { field: 'FIELD6', headerText: 'GP', width: 120, textAlign: 'Right' }, { field: 'FIELD7', headerText: 'GS', width: 120, textAlign: 'Right' }, { field: 'FIELD8', headerText: 'Minutes', width: 120, textAlign: 'Right' }, { field: 'FIELD9', headerText: 'Points', width: 120, textAlign: 'Right' }, ], treeColumnIndex: 1 },done); }); it('Indent/Outdent icon updated check', (done: Function) => { actionComplete = (args?: any): void => { expect(args.data[0].parentItem == undefined).toBe(true); done(); } TreeGridObj.actionComplete = actionComplete; TreeGridObj.selectRow(50); TreeGridObj.selectRow(51); (<any>TreeGridObj.grid.toolbarModule).toolbarClickHandler({ item: { id: TreeGridObj.grid.element.id + '_outdent' } }); setTimeout(done, 1000); TreeGridObj.rowDragAndDropModule.destroy(); }); afterAll(() => { destroy(TreeGridObj); }); }); describe('EJ2-59005 - Indent/Outdent action check with checkbox selection', () => { let TreeGridObj: TreeGrid; beforeAll((done: Function) => { TreeGridObj = createGrid( { dataSource: sampleData, childMapping: 'subtasks', treeColumnIndex: 1, height: 400, toolbar: ['Indent', 'Outdent'], columns: [ { type: 'checkbox', width: 50 }, { field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right', validationRules: { required: true, number: true}, width: 90 }, { field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, validationRules: {required: true} }, { field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit', format: 'yMd', validationRules: { date: true} }, { field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 100, editType: 'numericedit', validationRules: { number: true, min: 0}, edit: { params: { format: 'n'}} } ] },done); }); it('Indent/Outdent icon updated check', (done: Function) => { (<HTMLElement>TreeGridObj.getRows()[1].querySelector(".e-checkselect")).click(); (<HTMLElement>TreeGridObj.getRows()[2].querySelector(".e-checkselect")).click(); expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_indent').parentElement.classList.contains("e-hidden")).toBe(true); expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_outdent').parentElement.classList.contains("e-hidden")).toBe(true); (<HTMLElement>TreeGridObj.getRows()[2].querySelector(".e-checkselect")).click() expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_indent').parentElement.classList.contains("e-hidden")).toBe(true); expect(TreeGridObj.toolbarModule.getToolbar().querySelector("#" + TreeGridObj.element.id + '_gridcontrol_outdent').parentElement.classList.contains("e-hidden")).toBe(false); done(); }); afterAll(() => { destroy(TreeGridObj); }); }); describe('EJ2-58990 - Indent/Outdent action method check without parameter ', () => { let TreeGridObj: TreeGrid; let actionComplete: () => void; beforeAll((done: Function) => { TreeGridObj = createGrid( { dataSource: sampleData, childMapping: 'subtasks', treeColumnIndex: 1, height: 400, toolbar: ['Indent', 'Outdent'], selectionSettings: { enableToggle: true, mode: 'Row', type: 'Multiple', persistSelection: true, }, columns: [ { field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right', validationRules: { required: true, number: true }, width: 90, }, { field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, validationRules: { required: true }, }, { field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit', format: 'yMd', validationRules: { date: true }, }, { field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 100, editType: 'numericedit', validationRules: { number: true, min: 0 }, edit: { params: { format: 'n' } }, }, ] },done); }); it('Indent/Outdent icon updated check', (done: Function) => { actionComplete = (args?: any): void => { if (args.requestType == 'outdented') { expect(args.data[0].parentItem == undefined).toBe(true); } if (args.requestType == 'indented') { expect(args.data[0].parentItem.taskID == 3).toBe(true); } done(); } TreeGridObj.actionComplete = actionComplete; TreeGridObj.selectRow(1); TreeGridObj.outdent(); TreeGridObj.selectRow(2); TreeGridObj.indent(); }); afterAll(() => { destroy(TreeGridObj); }); }); describe('EJ2-58990 - Indent/Outdent action method check with parameter ', () => { let TreeGridObj: TreeGrid; let actionComplete: () => void; beforeAll((done: Function) => { TreeGridObj = createGrid( { dataSource: sampleData, childMapping: 'subtasks', treeColumnIndex: 1, height: 400, toolbar: ['Indent', 'Outdent'], selectionSettings: { enableToggle: true, mode: 'Row', type: 'Multiple', persistSelection: true, }, columns: [ { field: 'taskID', headerText: 'Task ID', isPrimaryKey: true, textAlign: 'Right', validationRules: { required: true, number: true }, width: 90, }, { field: 'taskName', headerText: 'Task Name', editType: 'stringedit', width: 220, validationRules: { required: true }, }, { field: 'startDate', headerText: 'Start Date', textAlign: 'Right', width: 130, editType: 'datepickeredit', format: 'yMd', validationRules: { date: true }, }, { field: 'duration', headerText: 'Duration', textAlign: 'Right', width: 100, editType: 'numericedit', validationRules: { number: true, min: 0 }, edit: { params: { format: 'n' } }, }, ] },done); }); it('Indent/Outdent icon updated check', (done: Function) => { actionComplete = (args?: any): void => { if (args.requestType == 'outdented') { expect(args.data[0].parentItem == undefined).toBe(true); } if (args.requestType == 'indented') { expect(args.data[0].parentItem != undefined).toBe(true); } done(); } TreeGridObj.actionComplete = actionComplete; TreeGridObj.outdent(TreeGridObj.getCurrentViewRecords()[1]); TreeGridObj.indent(TreeGridObj.getCurrentViewRecords()[2]); }); afterAll(() => { destroy(TreeGridObj); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { Component, ElementRef, EventEmitter, HostListener, Injector, OnDestroy, OnInit, Output, Renderer2, ViewChild } from '@angular/core'; import {AbstractComponent} from '@common/component/abstract.component'; import {UserService} from '../../../user/service/user.service'; import {User} from '@domain/user/user'; import {Role} from '@domain/user/role/role'; import {WorkspaceService} from '../../service/workspace.service'; import {Alert} from '@common/util/alert.util'; import * as _ from 'lodash'; import {Page} from '@domain/common/page'; import {GroupsService} from '../../../admin/user-management/service/groups.service'; import {Workspace} from '@domain/workspace/workspace'; import {RoleSet} from '@domain/user/role/roleSet'; import {PermissionService} from '../../../user/service/permission.service'; @Component({ selector: 'app-shared-member-manage', templateUrl: './shared-member-manage.component.html', }) export class SharedMemberManageComponent extends AbstractComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 현재 워크스페이스 private _workspace: Workspace; // 원본 워크스페이스 멤버 private _orgWsUsers: any[] = []; private _orgWsGroups: any[] = []; @ViewChild('inputSearch') private _inputSearch: ElementRef; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Output() public manageComplete = new EventEmitter(); // 팝업 닫기 public isShow: boolean = false; public users: User[] = []; // 유저 리스트 public groups: Role[] = []; // 그룹 리스트 public totalUsers: number = 0; // 전체 유저수 public totalGroups: number = 0; // 전체 그룹수 // 현재 (변경된) 워크스페이스 멤버 public workspaceUsers: any[] = []; public workspaceGroups: any[] = []; public isShowUserTab: boolean = true; // 사용자 탭 메뉴 표시여부 public isCheckAllUser: boolean = false; // 사용자 전체 체크 여부 public isCheckAllGroup: boolean = false; // 그룹 전체 체크 여부 // 페이지 번호 public allUserListPageNum: number = 0; public allGroupListPageNum: number = 0; public memberUserListPageNum: number = 0; public memberGroupListPageNum: number = 0; // 더보기 표시 여부 public showMoreAllUser: boolean = false; public showMoreAllGroup: boolean = false; public showMoreWsUser: boolean = false; public showMoreWsGroup: boolean = false; // 검색어 public searchText: string = ''; // 퍼미션 스키마 팝업 표시 여부 public isShowPermSchemaPopup: boolean = false; public roleSet: RoleSet; public defaultRole: Role; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Component |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(protected element: ElementRef, protected injector: Injector, protected renderer: Renderer2, private permissionService: PermissionService, private userService: UserService, private groupService: GroupsService, private workspaceService: WorkspaceService) { super(element, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { super.ngOnInit(); } // Destroy public ngOnDestroy() { super.ngOnDestroy(); this.renderer.removeStyle(document.body, 'overflow'); } /** * 화면 클릭 시 */ @HostListener('click', ['$event']) public clickListener(event: MouseEvent) { const $targetElm: any = $(event.target); if (!$targetElm.hasClass('ddp-ui-selected-option') && 0 === $targetElm.closest('.ddp-ui-selected-option').length) { this.$element.find('.ddp-ui-selected-option').removeClass('ddp-selected'); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 초기 실행 * @param {Workspace} workspace */ public init(workspace: Workspace) { // 초기 hidden 처리 this.renderer.setStyle(document.body, 'overflow', 'hidden'); // 초기화 this._reset(); this.isShow = true; this.safelyDetectChanges(); // 워크스페이스 정보 설정 this._workspace = workspace; const promise = []; this.loadingShow(); promise.push(this._getWorkspaceUsers(workspace.id)); promise.push(this._getUsers()); promise.push(this._getWorkspaceGroups(workspace.id)); promise.push(this._getGroups()); promise.push(new Promise((resolve, reject) => { this.permissionService.getRolesetDetail(workspace.roleSets[0].id).then((result: RoleSet) => { this.roleSet = result; this.defaultRole = result.roles.find(item => item.defaultRole); this.safelyDetectChanges(); resolve(null); }).catch(err => reject(err)); })); Promise.all(promise).then(() => { this.loadingHide(); this.safelyDetectChanges(); }).catch(() => { this.loadingHide(); this.safelyDetectChanges(); }); } // function - init /** * 현재 추가할 유저 이미지 로드 api * @param item * @returns {any} */ public getUserImage(item) { if (item.hasOwnProperty('imageUrl') && item.imageUrl) { return '/api/images/load/url?url=' + item.imageUrl + '/thumbnail'; } return '/assets/images/img_photo.png'; } // function - getUserImage /** * 공유 유저 | 그룹 수정 api */ public updateUser() { this.loadingShow(); const param = this._getAddMembers(); // 업데이트 할 멤버 데이터 조회 this.workspaceService.updateWorkspaceUser(this._workspace.id, param).then(() => { this.loadingHide(); Alert.success(this.translateService.instant('msg.space.alert.edit.member.success')); this.close(true); // 닫기 }).catch(() => { Alert.error(this.translateService.instant('msg.space.alert.edit.member.fail')); this.loadingHide(); }); } // function - UpdateUser /** * 전체 체크 여부 확인 */ public isCheckAll() { // 전체 체크 여부 확인 if (this.isShowUserTab) { this.isCheckAllUser = !this.users.some(item => !this.checkIsSharedTarget(item)); } else { this.isCheckAllGroup = !this.groups.some(item => !this.checkIsSharedTarget(item)); } } // function - isCheckAll /** * 전체 선택을 체크한다. */ public clickCheckAll() { if (this.isShowUserTab) { this.isCheckAllUser = !this.isCheckAllUser; if (this.isCheckAllUser) { this.users.forEach(user => { if (-1 === this.workspaceUsers.findIndex(item => user.username === item.member.username)) { this.workspaceUsers.push({ role: this.defaultRole.name, member: { type: 'user', id: user.id, username: user.username, fullName: user.fullName, email: user.email, imageUrl: user.imageUrl } }); } }); } else { this.workspaceUsers = []; } } else { this.isCheckAllGroup = !this.isCheckAllGroup; if (this.isCheckAllGroup) { this.groups.forEach(group => { if (-1 === this.workspaceGroups.findIndex(item => group.id === item.member.id)) { this.workspaceGroups.push({ role: this.defaultRole.name, member: {type: 'role', id: group.id, name: group.name} }); } }); } else { this.workspaceGroups = []; } } } // function - clickCheckAll /** * 공유 멤버(사용자/그룹) 추가/삭제 * @param selectedItem */ public setSharedTarget(selectedItem) { const list = this.isShowUserTab ? this.workspaceUsers : this.workspaceGroups; const memberIds = list.map((m) => m.member.username || m.member.id); const targetId = selectedItem.username || selectedItem.id; const selectedIdx = memberIds.indexOf(targetId); if (-1 === selectedIdx) { const target = this.isShowUserTab ? { role: this.defaultRole.name, member: { type: 'user', id: selectedItem.id, username: selectedItem.username, fullName: selectedItem.fullName, email: selectedItem.email, imageUrl: selectedItem.imageUrl } } : { role: this.defaultRole.name, member: { type: 'role', id: selectedItem.id, name: selectedItem.name } }; list.push(target); } else { list.splice(selectedIdx, 1); } // 전체 체크 확인 this.isCheckAll(); } // function - setSharedTarget /** * 멤버 리스트 체크상태 확인 * @param selectedItem * @returns {boolean} */ public checkIsSharedTarget(selectedItem): boolean { if (selectedItem) { const list = this.isShowUserTab ? this.workspaceUsers : this.workspaceGroups; const memberIds = list.map((m) => m.member.username || m.member.id); const targetId = selectedItem.username || selectedItem.id; const selectedIdx = memberIds.indexOf(targetId); return (selectedIdx > -1); } else { return false; } } // function - checkIsSharedTarget /** * 검색 조회 - 키보드 이벤트 * @param {KeyboardEvent} event */ public searchDataPressKey(event: KeyboardEvent) { (13 === event.keyCode) && (this.searchData()); } // function - searchDataPressKey /** * 검색 */ public searchData() { this.loadingShow(); // 검색어 설정 this.searchText = this._inputSearch.nativeElement.value; // 데이터 조회 if (this.isShowUserTab) { this._getUsers().then(() => this.loadingHide()) } else { this._getGroups().then(() => this.loadingHide()); } } // function - searchData /** * 검색어 리셋 */ public resetSearchText(isClear: boolean) { if (isClear) { this._inputSearch.nativeElement.value = ''; } else { // 검색어 설정 this._inputSearch.nativeElement.value = this.searchText; } } // function - resetSearchText /** * 전체 사용자 혹은 그룹의 다음 목록을 조회한다. */ public getMore() { this.loadingShow(); if (this.isShowUserTab) { this.allUserListPageNum++; this._getUsers(this.allUserListPageNum).then(() => { this.isCheckAll(); // 전체 체크 확인 this.loadingHide(); }); } else { this.allGroupListPageNum++; this._getGroups(this.allGroupListPageNum).then(() => { this.isCheckAll(); // 전체 체크 확인 this.loadingHide(); }); } } // function - getMore /** * 워크스페이스 사용자 혹은 그룹의 다음 목록을 조회한다. */ public getWsMemberMore() { this.loadingShow(); if (this.isShowUserTab) { this.memberUserListPageNum++; this._getWorkspaceUsers(this._workspace.id, this.memberUserListPageNum).then(() => { this.isCheckAll(); // 전체 체크 확인 this.loadingHide(); }); } else { this.memberGroupListPageNum++; this._getWorkspaceGroups(this._workspace.id, this.memberGroupListPageNum).then(() => { this.isCheckAll(); // 전체 체크 확인 this.loadingHide(); }); } } // function - getWsMemberMore /** * 닫기 * @param {boolean} completeFl */ public close(completeFl?: boolean) { // 팝업 닫기 this.isShow = false; this.manageComplete.emit(completeFl); this.renderer.removeStyle(document.body, 'overflow'); } // function - close /** * 권한 이름 조회 * @param name * @return {string} */ public getPredefinedName(name): string { if (['SYSTEM_ADMIN', 'SYSTEM_SUPERVISOR', 'SYSTEM_USER'].indexOf(name) > -1) { const roleName = name.replace(/^.*_/, '').toLowerCase(); return this.translateService.instant('msg.usr.role.system.' + roleName); } return name; } /** * 유저 탭 클릭 */ public clickUserTab() { this.isShowUserTab = true; this.isShowPermSchemaPopup = false; this.resetSearchText(true); this.searchData(); } // function - clickUserTab /** * 그룹 탭 클릭 */ public clickGroupTab() { this.isShowUserTab = false; this.isShowPermSchemaPopup = false; this.resetSearchText(true); this.searchData(); } // function - clickGroupTab /** * 롤 콤보 박스 클릭 이벤트 */ public clickRoleCombobox(userInfo) { userInfo['selected'] = !userInfo['selected']; this.workspaceUsers.forEach(item => { if (item.member.username !== userInfo.member.username) { item['selected'] = false; } }); } // function - clickRoleCombobox /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 추가 할 멤버 데이터 가공 * @returns {Array} * @private */ private _getAddMembers() { const params = []; const orgMembers: any[] = this._orgWsUsers.concat(this._orgWsGroups); const updateMembers: any[] = this.workspaceUsers.concat(this.workspaceGroups); // 현재 워크스페이스 멤버 const originMemberIds = orgMembers.map((item) => item.member.username || item.member.id); // 추가 및 업데이트 처리 updateMembers.forEach((updateMember) => { const memberInfo = { memberId: updateMember.member.username || updateMember.member.id, role: updateMember.role }; // 기존 목록에 있는 사용자라면 업데이트 const targetIdx: number = originMemberIds.indexOf(memberInfo.memberId); if (-1 < targetIdx) { const targetItem = orgMembers[targetIdx]; if (targetItem.role !== memberInfo.role) { memberInfo['op'] = 'replace'; params.push(memberInfo); } } else { // 기존 목록에 사용자 추가 memberInfo['op'] = 'add'; memberInfo['memberType'] = updateMember.member.type === 'user' ? 'USER' : 'GROUP'; params.push(memberInfo); } }); // 기존 목록에서 아이디 추출 const memberIds = updateMembers.map((m) => m.member.username || m.member.id); // 삭제 처리 orgMembers.forEach((obj) => { const delTargetId = obj.member.username || obj.member.id; if (memberIds.indexOf(delTargetId) === -1) { params.push({ op: 'remove', memberId: delTargetId }); } }); return params; } // function - _getAddMembers /** * 워크스페이스 사용자 목록 조회 * @param {string} workspaceId * @param {number} pageNum * @private */ private _getWorkspaceUsers(workspaceId: string, pageNum: number = 0) { return new Promise((resolve, reject) => { (0 === pageNum) && (this.workspaceUsers = []); const param: Page = new Page(); param.sort = 'memberName,asc'; param.page = pageNum; (0 === pageNum) && (this.allGroupListPageNum = 0); this.workspaceService.getWorkspaceUsers(workspaceId, param).then((data) => { // 데이터 있다면 if (data['_embedded']) { this.workspaceUsers = this.workspaceUsers.concat(data['_embedded']['members']); } this.showMoreWsUser = this._checkShowMore(data.page); this._orgWsUsers = _.cloneDeep(this.workspaceUsers); this.safelyDetectChanges(); resolve(null); }).catch(() => { Alert.error(this.translateService.instant('msg.space.alert.member.retrieve.fail')); reject(); }); }); } // function - _getWorkspaceUsers /** * 워크스페이스 그룹 목록 조회 * @param {string} workspaceId * @param {number} pageNum * @private */ private _getWorkspaceGroups(workspaceId: string, pageNum: number = 0) { return new Promise((resolve, reject) => { (0 === pageNum) && (this.workspaceGroups = []); const param: Page = new Page(); param.sort = 'memberName,asc'; param.page = pageNum; (0 === pageNum) && (this.memberGroupListPageNum = 0); this.workspaceService.getWorkspaceGroups(workspaceId, param).then((data) => { // 데이터 있다면 if (data['_embedded']) { this.workspaceGroups = this.workspaceGroups.concat(data['_embedded']['members']); } this.showMoreWsGroup = this._checkShowMore(data.page); this._orgWsGroups = _.cloneDeep(this.workspaceGroups); this.safelyDetectChanges(); resolve(null); }).catch(() => { Alert.error(this.translateService.instant('msg.space.alert.member.retrieve.fail')); reject(); }); }); } // function - _getWorkspaceGroups /** * 전체 유저 조회 Api * @param {number} pageNum * @private */ private _getUsers(pageNum: number = 0) { return new Promise((resolve, reject) => { const param: SearchParam = new SearchParam(); param.page = pageNum; param.sort = 'username,asc'; (0 === pageNum) && (this.allUserListPageNum = 0); // 검색어 this.searchText = this.searchText.trim(); if (this.searchText !== '') { param.nameContains = this.searchText; } // 유저 리스트 조회 (0 === pageNum) && (this.users = []); this.userService.getUserList(param, 'default').then((users) => { // 데이터 있을 시 if (users['_embedded']) { this.users = this.users.concat(users['_embedded']['users']); this.totalUsers = users.page.totalElements; } this.showMoreAllUser = this._checkShowMore(users.page); this.safelyDetectChanges(); resolve(null); }).catch(() => { Alert.error(this.translateService.instant('msg.space.alert.member.retrieve.fail')); reject(); }); }); } // function - _getUsers /** * 전체 그룹 조회 Api * @param {number} pageNum * @private */ private _getGroups(pageNum: number = 0) { return new Promise((resolve, reject) => { const param: SearchParam = new SearchParam(); param.page = pageNum; param.sort = 'name,asc'; (0 === pageNum) && (this.allGroupListPageNum = 0); // 검색어 this.searchText = this.searchText.trim(); if (this.searchText !== '') { param.nameContains = this.searchText; } // 그룹 리스트 조회 (0 === pageNum) && (this.groups = []); this.groupService.getGroupList(param, 'default').then((groups) => { // 데이터 있을 시 if (groups['_embedded']) { this.groups = this.groups.concat(groups['_embedded']['groups']); this.totalGroups = groups.page.totalElements; } this.showMoreAllGroup = this._checkShowMore(groups.page); this.safelyDetectChanges(); resolve(null); }).catch(() => { Alert.error(this.translateService.instant('msg.space.alert.group.retrieve.fail')); reject(); }); }); } // function - _getGroups /** * 전체 초기화 */ private _reset() { this.isShow = false; // 팝업 닫기 this.isShowUserTab = true; // 사용자 탭 메뉴 표시 this._workspace = null; // 워크스페이스 정보 this.users = []; // 유저 리스트 this.groups = []; // 그룹 리스트 this.searchText = ''; // 검색어 this.allUserListPageNum = 0; this.allGroupListPageNum = 0; this.memberUserListPageNum = 0; this.memberGroupListPageNum = 0; } // function - _reset /** * 더보기 버튼 표시 여부 확인 * @param pageResult * @private */ private _checkShowMore(pageResult): boolean { if (0 === pageResult.totalPages) { return false; } else { return pageResult.number < pageResult.totalPages - 1; } } // function - _checkShowMore } class SearchParam { public page: number = 0; public size: number = 30; public sort: string; public nameContains: string; }
the_stack
import { DocumentEditor } from '../../../src/document-editor/document-editor'; import { LayoutViewer, PageLayoutViewer, DocumentHelper } from '../../../src/index'; import { ListDialog } from '../../../src/document-editor/implementation/dialogs/list-dialog'; import { ListViewModel } from '../../../src/document-editor/implementation/dialogs/list-view-model'; import { createElement } from '@syncfusion/ej2-base'; import { TestHelper } from '../../test-helper.spec'; import { Selection } from '../../../src/index'; import { EditorHistory } from '../../../src/document-editor/implementation/editor-history/editor-history'; import { L10n } from '@syncfusion/ej2-base'; import { Editor } from '../../../src/index'; /** * List Dialog Spec */ function createDocument(editor: DocumentEditor) { editor.openBlank(); editor.editorModule.insertText('Adventure Works cycles'); } let arabic: any = { "sections": [ { "blocks": [ { "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 36, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1.149999976158142, "lineSpacingType": "Multiple", "textAlignment": "Left", "listFormat": { "listLevelNumber": 0, "listId": 7 } }, "inlines": [ { "text": "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.", "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" } } ] }, { "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 36, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1.149999976158142, "lineSpacingType": "Multiple", "textAlignment": "Left", "listFormat": { "listLevelNumber": 0, "listId": 7 } }, "inlines": [ { "text": "The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets.", "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" } } ] }, { "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 36, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1.149999976158142, "lineSpacingType": "Multiple", "textAlignment": "Left", "listFormat": { "listLevelNumber": 0, "listId": 7 } }, "inlines": [ { "text": "Whileits base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 12, "fontFamily": "Calibri", "fontColor": "#FF000000" } } ] } ], "headersFooters": {}, "sectionFormat": { "headerDistance": 36, "footerDistance": 36, "pageWidth": 612, "pageHeight": 792, "leftMargin": 72, "rightMargin": 72, "topMargin": 72, "bottomMargin": 72, "differentFirstPage": false, "differentOddAndEvenPages": false } } ], "characterFormat": { "bold": false, "italic": false, "strikethrough": "None", "baselineAlignment": "Normal", "fontSize": 10, "fontFamily": "Times New Roman", "fontColor": "#FF000000" }, "lists": [ { "listId": 7, "abstractListId": 7 } ], "abstractLists": [ { "abstractListId": 7, "levels": [ { "startAt": 1, "restartLevel": 0, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%1.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 36, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 1, "listLevelPattern": "UpRoman", "followCharacter": "Tab", "numberFormat": "%2.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 72, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 2, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%3.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 108, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 3, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%4.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 144, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 4, "listLevelPattern": "UpRoman", "followCharacter": "Tab", "numberFormat": "%5.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 180, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 5, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%6.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 216, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 6, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%7.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 252, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 7, "listLevelPattern": "UpRoman", "followCharacter": "Tab", "numberFormat": "%8.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 288, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } }, { "startAt": 1, "restartLevel": 8, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%9.", "characterFormat": { "bold": false, "italic": false, "fontSize": 8, "fontFamily": "Verdana", "fontColor": "#FF000000" }, "paragraphFormat": { "leftIndent": 324, "rightIndent": 0, "firstLineIndent": -18, "beforeSpacing": 0, "afterSpacing": 0, "lineSpacing": 1, "lineSpacingType": "Multiple", "textAlignment": "Left" } } ] } ] }; // describe('List dialog validation - 1', () => { // let editor: DocumentEditor; // let viewer: LayoutViewer; // let dialog: ListDialog; // beforeAll((): void => { // editor = undefined; // let ele: HTMLElement = createElement('div', { id: 'container' }); // document.body.appendChild(ele); // DocumentEditor.Inject(Editor, Selection, ListDialog, EditorHistory); // editor = new DocumentEditor({ isReadOnly: false,enableEditor: true, enableSelection: true, enableListDialog: true }); // editor.enableEditorHistory = true; // (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; // (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; // (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; // (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; // editor.appendTo('#container'); // dialog = new ListDialog(editor.documentHelper); // }); // afterAll((done): void => { // editor.destroy(); // dialog.destroy(); // dialog = undefined; // document.body.removeChild(document.getElementById('container')); // editor = undefined; // viewer = undefined; // setTimeout(function () { // done(); // }, 1000); // }); // // it('Dialog intial load testing', () => { // // viewer = editor.viewer as PageLayoutViewer; // // editor.open(JSON.stringify(arabic)); // // viewer = editor.viewer as PageLayoutViewer; // // viewer.selection.selectAll(); // // dialog.showListDialog(); // // let event: any = { target: { value: "UpRoman" } }; // // expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); // // (dialog as any).onApplyList(); // // editor.editorHistory.undo(); // // editor.editorHistory.redo(); // // }); // }); describe('List dialog validation-2', () => { let editor: DocumentEditor; let dialog: ListDialog; beforeAll((): void => { editor = undefined; let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); DocumentEditor.Inject(Editor, Selection, ListDialog); DocumentEditor.Inject(EditorHistory); editor = new DocumentEditor({ enableEditorHistory: true, enableEditor: true, enableSelection: true, isReadOnly: false, enableListDialog: true }); editor.enableEditorHistory = true; (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); dialog = editor.listDialogModule; }); afterAll((done): void => { editor.destroy(); document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 1000); }); it('followCharacter API validation', () => { console.log('followCharacter API validation'); dialog.showListDialog(); let number = (dialog as any).followCharacterConverter('None'); (dialog as any).followCharacterConverter('Space'); (dialog as any).followCharacterConverter('Tab'); expect(number).toBe(2); }); it('List Pattern API validation', () => { console.log('List Pattern API validation'); let number = (dialog as any).listPatternConverter('Arabic'); (dialog as any).listPatternConverter('LowRoman'); (dialog as any).listPatternConverter('UpRoman'); (dialog as any).listPatternConverter('LowLetter'); (dialog as any).listPatternConverter('UpLetter'); (dialog as any).listPatternConverter('Number'); (dialog as any).listPatternConverter('LeadingZero'); (dialog as any).listPatternConverter('Bullet'); (dialog as any).listPatternConverter('Ordinal'); (dialog as any).listPatternConverter('OrdinalText'); (dialog as any).listPatternConverter('Special'); (dialog as any).listPatternConverter('FarEast'); (dialog as any).listPatternConverter('None'); expect(number).toBe(0); }); it('Applylist API validation', () => { console.log('Applylist API validation'); let dialog: any = new ListDialog(editor.documentHelper); createDocument(editor); dialog.showListDialog(); dialog.documentHelper = undefined; expect(() => { (dialog as any).onApplyList(); }).toThrowError(); dialog.destroy(); }); }); describe('ListDialogViewModel class validation', () => { let editor: DocumentEditor; let dialog: ListDialog; let viewModel: ListViewModel beforeAll((): void => { editor = undefined; let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); DocumentEditor.Inject(Editor, Selection, ListDialog); DocumentEditor.Inject(EditorHistory); editor = new DocumentEditor({ enableEditorHistory: true, enableEditor: true, enableSelection: true, isReadOnly: false }); editor.enableEditorHistory = true; (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); dialog = new ListDialog(editor.documentHelper); viewModel = (dialog as any).viewModel; }); afterAll((done): void => { editor.destroy(); dialog.destroy(); document.body.removeChild(document.getElementById('container')); editor = undefined; dialog = undefined; viewModel = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 1000); }); it('viewmodel property validation', () => { console.log('viewmodel property validation'); dialog.showListDialog(); viewModel.listLevelPattern = 'Arabic'; expect(viewModel.listLevelPattern).not.toBe(undefined); }); it('viewmodel property validation', () => { console.log('viewmodel property validation'); dialog.showListDialog(); viewModel.followCharacter = 'Space'; expect(viewModel.followCharacter).not.toBe(undefined); }); it('Create List and addListLevel API validation', () => { console.log('Create List and addListLevel API validation'); dialog.showListDialog(); let dialogview: ListViewModel = new ListViewModel(); (dialogview as any).addListLevels(); }); }); describe('dialog event validation-1', () => { let editor: DocumentEditor; let dialog: ListDialog; beforeAll((): void => { editor = undefined; let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); DocumentEditor.Inject(Editor, Selection, ListDialog); DocumentEditor.Inject(EditorHistory); editor = new DocumentEditor({ enableEditorHistory: true, enableEditor: true, enableSelection: true, isReadOnly: false }); editor.enableEditorHistory = true; (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); dialog = new ListDialog(editor.documentHelper); }); afterAll((done): void => { editor.destroy(); dialog.destroy(); dialog = undefined; document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 500); }); it('NumberFormat event validation', (done) => { console.log('NumberFormat event validation'); editor.openBlank(); editor.editorModule.insertText('Syncfusion Software'); editor.editor.applyNumbering('%1.', 'Number'); dialog.showListDialog(); setTimeout(() => { let event: any = { target: { value: "%0." } }; (dialog as any).onNumberFormatChanged(event); expect((dialog as any).viewModel.listLevel.numberFormat).toBe('%0.'); (dialog as any).onCancelButtonClick(); done(); }); }); it('follow character event validation', () => { console.log('follow character event validation'); createDocument(editor); editor.editorModule.insertText('Syncfusion Software'); editor.editor.applyBullet('\uf0b7', 'Symbol'); let locale: L10n = new L10n('documenteditor', editor.defaultLocale); locale.setLocale(editor.locale); dialog.initListDialog(locale); let event: any = { target: { value: "Space" } }; (dialog as any).onFollowCharacterValueChanged(event); expect((dialog as any).viewModel.followCharacter).toBe('None'); }); it('follow character event validation', () => { console.log('follow character event validation'); let event: any = { target: { value: "Tab" } }; (dialog as any).onFollowCharacterValueChanged(event); expect((dialog as any).viewModel.followCharacter).toBe('None'); }); it('follow character event validation', () => { console.log('follow character event validation'); let event: any = { target: { value: "None" } }; (dialog as any).onFollowCharacterValueChanged(event); expect((dialog as any).viewModel.followCharacter).toBe('None'); }); }); describe('dialog event validation', () => { let editor: DocumentEditor; let dialog: ListDialog; beforeAll((): void => { editor = undefined; let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); DocumentEditor.Inject(Editor, Selection, ListDialog); DocumentEditor.Inject(EditorHistory); editor = new DocumentEditor({ enableEditorHistory: true, enableEditor: true, enableSelection: true, isReadOnly: false, enableListDialog: true }); editor.enableEditorHistory = true; (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); dialog = editor.listDialogModule; }); afterAll((done): void => { editor.destroy(); dialog.destroy(); dialog = undefined; document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 500); }); it('ListLevel event validation', () => { console.log('ListLevel event validation'); createDocument(editor); dialog.showListDialog(); let event: any = { value: 'Level 3', target: { selectedIndex: 2 } }; expect(() => { (dialog as any).onListLevelValueChanged(event); }).not.toThrowError(); (dialog as any).onApplyList(); }); // it('ListLevel event validation with index 0', () => { // console.log('ListLevel event validation with index 0'); // createDocument(editor); // dialog.showListDialog(); // let event: any = { value: 'Level 1', target: { selectedIndex: 0 } }; // expect(() => { (dialog as any).onListLevelValueChanged(event); }).not.toThrowError(); // (dialog as any).onApplyList(); // }); // it('ListLevel event validation with index 0', () => { // console.log('ListLevel event validation with index 0'); // editor.editorHistory.undo(); // expect(() => { editor.editorHistory.redo(); }).not.toThrowError(); // }); // it('Dialog property validation', (done) => { // console.log('Dialog property validation'); // createDocument(editor); // dialog.showListDialog(); // setTimeout(() => { // (dialog as any).viewModel = undefined; // expect(dialog.list).toBe(undefined); // expect(dialog.listLevel).toBe(undefined); // done(); // }); // }); }); describe('dialog event validation', () => { let editor: DocumentEditor; let dialog: ListDialog; let event: any; beforeAll((): void => { editor = undefined; let ele: HTMLElement = createElement('div', { id: 'container' }); document.body.appendChild(ele); DocumentEditor.Inject(Editor, Selection, EditorHistory, ListDialog); editor = new DocumentEditor({ enableEditorHistory: true, enableEditor: true, enableSelection: true, isReadOnly: false }); editor.enableEditorHistory = true; (editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas; (editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas; (editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas; (editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas; editor.appendTo('#container'); dialog = new ListDialog(editor.documentHelper); createDocument(editor); dialog.showListDialog(); }); afterAll((done): void => { editor.destroy(); dialog.destroy(); dialog = undefined; document.body.removeChild(document.getElementById('container')); editor = undefined; document.body.innerHTML = ''; setTimeout(function () { done(); }, 1000); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "UpRoman" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "LowRoman" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "UpLetter" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "LowLetter" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "Arabic" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation', () => { console.log('LevelPattern event validation'); event = { target: { value: "Bullet" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "Number" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "LeadingZero" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "Ordinal" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "OrdinalText" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "FarEast" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "Special" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('LevelPattern event validation-2', () => { console.log('LevelPattern event validation-2'); event = { target: { value: "None" } }; expect(() => { (dialog as any).onLevelPatternValueChanged(event); }).not.toThrowError(); }); it('module name validation', () => { console.log('module name validation'); let name: string = dialog.getModuleName(); expect(name).toBe('ListDialog') }); });
the_stack
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { CommonResponseService } from '../../../shared/services/common-response.service'; import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service'; import { AutorefreshService } from '../../services/autorefresh.service'; import { environment } from './../../../../environments/environment'; import {LoggerService} from '../../../shared/services/logger.service'; import {ErrorHandlingService} from '../../../shared/services/error-handling.service'; import {ToastObservableService} from '../../../post-login-app/common/services/toast-observable.service'; import {DownloadService} from '../../../shared/services/download.service'; import {RefactorFieldsService} from '../../../shared/services/refactor-fields.service'; @Component({ selector: 'app-installed-softwares', templateUrl: './installed-softwares.component.html', styleUrls: ['./installed-softwares.component.css'], providers: [CommonResponseService, AutorefreshService] }) export class InstalledSoftwaresComponent implements OnInit, OnDestroy { public somedata: any; public outerArr: any; public allColumns: any; selectedAssetGroup: string; public apiData: any; public applicationValue: any; public errorMessage: any; public dataComing = true; public showLoader = true; public tableHeaderData: any; private subscriptionToAssetGroup: Subscription; private downloadSubscription: Subscription; private dataSubscription: Subscription; public seekdata = false; durationParams: any; autoRefresh: boolean; totalRows = 0; bucketNumber = 0; paginatorSize = 10; dataTableData: any = []; tableDataLoaded = false; currentBucket = []; firstPaginator = 1; lastPaginator: number; currentPointer = 0; errorValue = 0; searchTxt = ''; showGenericMessage = false; firstTimeLoad = true; @Input() resourceId = ''; @Input() resourceType = 'ec2'; @Output() errorOccured = new EventEmitter<any>(); constructor( private commonResponseService: CommonResponseService, private assetGroupObservableService: AssetGroupObservableService, private downloadService: DownloadService, private autorefreshService: AutorefreshService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private toastObservableService: ToastObservableService, private refactorFieldsService: RefactorFieldsService ) { this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe( assetGroupName => { this.selectedAssetGroup = assetGroupName; this.updateComponent(); }); this.durationParams = this.autorefreshService.getDuration(); this.durationParams = parseInt(this.durationParams, 10); this.autoRefresh = this.autorefreshService.autoRefresh; } ngOnInit() { this.updateComponent(); } updateComponent() { /* All functions variables which are required to be set for component to be reloaded should go here */ try { if (this.resourceId !== '') { this.outerArr = []; this.searchTxt = ''; this.currentBucket = []; this.bucketNumber = 0; this.firstPaginator = 1; this.dataTableData = []; this.tableDataLoaded = false; this.currentPointer = 0; this.showLoader = true; this.dataComing = false; this.seekdata = false; this.errorValue = 0; this.showGenericMessage = false; this.getData(); } } catch (error) { this.logger.log('error', 'js error - ' + error); } } getData() { /* All functions to get data should go here */ this.getAllPatchingDetails(); } getAllPatchingDetails() { if (this.dataSubscription) { this.dataSubscription.unsubscribe(); } const payload = { 'ag': this.selectedAssetGroup, 'filter': {}, 'from': (this.bucketNumber) * this.paginatorSize, 'searchtext': this.searchTxt, 'size': this.paginatorSize }; const queryParam = { 'from': (this.bucketNumber) * this.paginatorSize, 'searchtext': this.searchTxt, 'size': this.paginatorSize }; this.errorValue = 0; const url = environment.installedSoftware.url; const newUrl = this.replaceUrl(url); const method = environment.installedSoftware.method; this.dataSubscription = this.commonResponseService.getData( newUrl, method, payload, queryParam).subscribe( response => { this.showGenericMessage = false; try { this.errorValue = 1; this.showLoader = false; this.seekdata = false; this.dataTableData = response.response; this.dataComing = true; this.dataComing = true; if (response.response.length === 0 && this.firstTimeLoad) { this.errorOccured.emit(); } this.firstTimeLoad = false; this.totalRows = response.total; this.firstPaginator = (this.bucketNumber * this.paginatorSize) + 1; this.lastPaginator = (this.bucketNumber * this.paginatorSize) + this.paginatorSize; this.currentPointer = this.bucketNumber; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } const updatedResponse = this.massageData(response.response); this.currentBucket[this.bucketNumber] = updatedResponse; this.processData(updatedResponse); } catch (e) { this.errorValue = 0; this.errorMessage = this.errorHandling.handleJavascriptError(e); this.getErrorValues(); this.errorOccured.emit(); } }, error => { this.showGenericMessage = true; this.errorMessage = error; this.getErrorValues(); this.errorOccured.emit(); }); } getErrorValues(): void { this.errorValue = -1; this.showLoader = false; this.dataComing = false; this.seekdata = true; } massageData(data) { /* * added by Trinanjan 14/02/2017 * the funciton replaces keys of the table header data to a readable format */ const refactoredService = this.refactorFieldsService; const newData = []; const formattedFilters = data.map(function(rowObj) { const KeysTobeChanged = Object.keys(rowObj); let newObj = {}; KeysTobeChanged.forEach(element => { const elementnew = refactoredService.getDisplayNameForAKey(element.toLocaleLowerCase()) || element; newObj = Object.assign(newObj, { [elementnew]: rowObj[element] }); }); newData.push(newObj); }); return newData; } processData(data) { let innerArr = {}; const totalVariablesObj = {}; let cellObj = {}; this.outerArr = []; const getData = data; const getCols = Object.keys(getData[0]); for (let row = 0 ; row < getData.length ; row++) { innerArr = {}; for (let col = 0; col < getCols.length; col++) { cellObj = { 'link': '', 'properties': { 'color': '' }, 'colName': getCols[col], 'hasPreImg': false, 'imgLink': '', 'text': getData[row][getCols[col]], 'valText': getData[row][getCols[col]] }; innerArr[getCols[col]] = cellObj; totalVariablesObj[getCols[col]] = ''; } this.outerArr.push(innerArr); } if (this.outerArr.length > getData.length) { const halfLength = this.outerArr.length / 2; this.outerArr = this.outerArr.splice(halfLength); } this.allColumns = Object.keys(totalVariablesObj); } replaceUrl(url) { let replacedUrl = url.replace('{resourceId}', this.resourceId.toString()); replacedUrl = replacedUrl.replace('{assetGroup}', this.selectedAssetGroup.toString()); replacedUrl = replacedUrl.replace('{resourceType}', this.resourceType.toString()); return replacedUrl; } prevPg() { this.currentPointer--; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1; this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize; } handlePopClick(rowText) { const fileType = 'csv'; try { let queryParams; queryParams = { 'fileFormat': 'csv', 'serviceId': 99, 'fileType': fileType }; const downloadRequest = { 'ag': this.selectedAssetGroup, 'filter': {}, 'from': 0, 'searchtext': this.searchTxt, 'size': this.totalRows }; this.downloadService.animateDownload(true); const downloadUrl = environment.download.url; const downloadMethod = environment.download.method; this.downloadService.requestForDownload(queryParams, downloadUrl, downloadMethod, downloadRequest , 'Installed Softwares', this.totalRows); } catch (error) { this.logger.log('error', error); this.downloadService.animateDownload(false); this.toastObservableService.postMessage('Download failed. Please try later'); this.downloadSubscription.unsubscribe(); } } nextPg() { if (this.currentPointer < this.bucketNumber) { this.currentPointer++; this.processData(this.currentBucket[this.currentPointer]); this.firstPaginator = (this.currentPointer * this.paginatorSize) + 1; this.lastPaginator = (this.currentPointer * this.paginatorSize) + this.paginatorSize; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } } else { this.bucketNumber++; this.getData(); } } searchCalled(search) { this.searchTxt = search; } callNewSearch() { this.bucketNumber = 0; this.currentBucket = []; this.getData(); } ngOnDestroy() { try { this.dataSubscription.unsubscribe(); } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.getErrorValues(); } } }
the_stack
import Char from 'typescript-char'; import { findNodeByOffset, getFirstAncestorOrSelf, getFirstAncestorOrSelfOfKind, getStringValueRange, getTokenAt, isDocString, } from '../analyzer/parseTreeUtils'; import { appendArray } from '../common/collectionUtils'; import { convertOffsetToPosition, convertTextRangeToRange } from '../common/positionUtils'; import { Range, TextRange } from '../common/textRange'; import { TextRangeCollection } from '../common/textRangeCollection'; import { ModuleNode, ParseNode, ParseNodeType, SuiteNode } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; import { defaultTabSize } from '../parser/tokenizer'; import { IndentToken, KeywordToken, KeywordType, StringToken, StringTokenFlags, Token, TokenType, } from '../parser/tokenizerTypes'; interface TokenInfo extends TextRange { range: Range; text: string; kind: 'comment' | 'string' | 'token'; firstTokenOnLine: boolean; multilineDocComment: boolean; } export function getIndentation(parseResults: ParseResults, offset: number, preferDedent?: boolean): number { // ex) // a = """ // | <= here const strIndent = _tryHandleStringLiterals(parseResults, offset); if (strIndent !== undefined) { return strIndent; } // ex) // a = 1 + \ // | <= here // or // a = (1 + // | <= here const exprIndent = _tryHandleMultilineConstructs(parseResults, offset); if (exprIndent !== undefined) { return exprIndent; } preferDedent = preferDedent ?? _shouldDedentAfterKeyword(parseResults.tokenizerOutput.tokens, offset); return Math.max(_getIndentation(parseResults, offset, preferDedent).indentation, 0); } export function reindentSpan( parseResults: ParseResults, span: TextRange, indentation: number, indentFirstToken = true ) { let indentDelta = 0; const texts: string[] = []; // Currently _convertTokenStreams converts text in the span as whitespace and non whitespace // and then this function puts those back to string with reidentation if needed. // // Another approach we can take is converting the text in 2 chunks that require reindentation and not // and process chunks that require reindentation line by line (like how it currently does for // multiline doc comments) and put chunks that don't require reindentation as it is. const tokenInfo = _convertTokenStreams(parseResults, span); let previousInfo = tokenInfo[0]; indentDelta = indentation - _getIndentationFromText(parseResults, previousInfo.range.start.line, previousInfo.range.start.character) .indentation; if (previousInfo.multilineDocComment) { appendArray(texts, _reindentLinesFromText(parseResults, previousInfo, indentDelta)); } else { if (indentFirstToken) { texts.push(_createIndentationString(parseResults, indentation)); } texts.push(previousInfo.text); } for (let i = 1; i < tokenInfo.length; i++) { const info = tokenInfo[i]; if (info.firstTokenOnLine) { texts.push( parseResults.tokenizerOutput.predominantEndOfLineSequence.repeat( info.range.start.line - previousInfo.range.end.line ) ); if (info.multilineDocComment) { appendArray(texts, _reindentLinesFromText(parseResults, info, indentDelta)); } else { // Put indentation for the first token on the line. texts.push( _createIndentationString( parseResults, Math.max( 0, _getIndentationFromText(parseResults, info.range.start.line, info.range.start.character) .indentation + indentDelta ) ) ); texts.push(info.text); } } else { // Put whitespace between 2 tokens on same line // token1[space]token2 texts.push(' '.repeat(info.range.start.character - previousInfo.range.end.character)); texts.push(info.text); } previousInfo = info; } return texts.join(''); } function _getIndentation( parseResults: ParseResults, offset: number, preferDedent: boolean ): { token?: Token; indentation: number } { const tokens = parseResults.tokenizerOutput.tokens; const startingToken = _findPreviousNonWhitespaceToken(tokens, offset); if (!startingToken) { return { indentation: 0, }; } const node = findNodeByOffset(parseResults.parseTree, TextRange.getEnd(startingToken)); if (!node) { return { indentation: 0, }; } const suite = getFirstAncestorOrSelfOfKind(node, ParseNodeType.Suite); if (!suite) { return _getIndentationForNode(parseResults, parseResults.parseTree, node); } const suiteSpan = convertTextRangeToRange(suite, parseResults.tokenizerOutput.lines); if (preferDedent || suiteSpan.start.line === suiteSpan.end.line) { // Go one more level up. const outerContainer = getFirstAncestorOrSelf( suite, (n) => n !== suite && n.nodeType === ParseNodeType.Suite ) as SuiteNode | undefined; return _getIndentationForNode(parseResults, outerContainer ?? parseResults.parseTree, suite); } return _getIndentationForNode(parseResults, suite, node); } function _getIndentationForNode( parseResults: ParseResults, container: ModuleNode | SuiteNode, current: ParseNode ): { token?: Token; indentation: number } { if (container.nodeType === ParseNodeType.Module) { // It is at the module level return { token: _getFirstTokenOFStatement(parseResults, container, current), indentation: 0, }; } if (_containsNoIndentBeforeFirstStatement(parseResults, container)) { const tabSize = _getTabSize(parseResults); const outerContainer = getFirstAncestorOrSelf( container, (n) => n !== container && n.nodeType === ParseNodeType.Suite ) as SuiteNode | undefined; const result = _getIndentationForNode(parseResults, outerContainer ?? parseResults.parseTree, container); return { token: result.token, indentation: result.indentation + tabSize, }; } else { const tokens = parseResults.tokenizerOutput.tokens; return { token: _getFirstTokenOFStatement(parseResults, container, current), indentation: _getIndentationFromIndentToken(tokens, tokens.getItemAtPosition(container.start)), }; } } function _containsNoIndentBeforeFirstStatement(parseResults: ParseResults, suite: SuiteNode): boolean { if (suite.statements.filter((s) => s.length > 0).length === 0) { // There is no statement in the suite. // ex) // def foo(): // | <= here return true; } // If suite contains no indent before first statement, then consider user is in the middle of writing block // and parser is in broken state. // ex) // def foo(): // while True: // | <= here // def bar(): // pass // // parser will think "def bar" belongs to "while True" with invalid indentation. const tokens = parseResults.tokenizerOutput.tokens; const start = tokens.getItemAtPosition(suite.start); const end = tokens.getItemAtPosition(suite.statements[0].start); for (let i = start; i <= end; i++) { const token = _getTokenAtIndex(tokens, i); if (token?.type === TokenType.Indent) { return false; } } return true; } function _getFirstTokenOFStatement( parseResults: ParseResults, container: ModuleNode | SuiteNode, span: TextRange ): Token { const tokens = parseResults.tokenizerOutput.tokens; for (const statement of container.statements) { if (!TextRange.containsRange(statement, span)) { continue; } return getTokenAt(tokens, statement.start)!; } return getTokenAt(tokens, container.start)!; } function _getIndentationFromIndentToken(tokens: TextRangeCollection<Token>, index: number) { for (let i = index; i < tokens.count; i++) { const token = _getTokenAtIndex(tokens, i); if (token?.type === TokenType.Indent) { return (token as IndentToken).indentAmount; } } // At the module level. return 0; } function _tryHandleMultilineConstructs(parseResults: ParseResults, offset: number): number | undefined { const tokens = parseResults.tokenizerOutput.tokens; // Make sure we use next token to get line delta. // This is just to handle how tokenizer associates new lines to which token. // ex) a = 1 + \ // | <= here // [b] = 2 const index = _findNextTokenIndex(tokens, offset); if (index < 0) { return undefined; } const lines = parseResults.tokenizerOutput.lines; const tabSize = _getTabSize(parseResults); for (let i = index; i > 0; i--) { const token = _getTokenAtIndex(tokens, i)!; if (TextRange.getEnd(token) < offset) { return undefined; } const previousToken = _getTokenAtIndex(tokens, i - 1)!; const tokenSpan = token ? convertTextRangeToRange(token, lines) : undefined; const previousTokenSpan = previousToken ? convertTextRangeToRange(previousToken, lines) : undefined; if ( tokenSpan && previousTokenSpan && previousTokenSpan.end.line < tokenSpan.start.line && previousToken!.type !== TokenType.NewLine ) { const indentationResult = _getIndentation(parseResults, previousToken!.start, /* preferDedent */ false); const currentPosition = convertOffsetToPosition(offset, lines); // Handle multiline constructs (explicit or implicit) // ex) def foo \ // | <= here // or // i = \ // \ // | <= here // or // a = ( // | <= here const lineDelta = currentPosition.line - (indentationResult.token ? convertOffsetToPosition(indentationResult.token.start, lines).line : previousTokenSpan.start.line); const indentation = _getFirstNonBlankLineIndentationFromText( parseResults, currentPosition.line, previousTokenSpan.start.line ); return indentation + (lineDelta === 1 ? tabSize : 0); } } return undefined; } function _tryHandleStringLiterals(parseResults: ParseResults, offset: number): number | undefined { const tokens = parseResults.tokenizerOutput.tokens; const index = tokens.getItemAtPosition(offset); if (index < 0) { return undefined; } const token = _findStringToken(tokens, index); if (!token || token.type !== TokenType.String) { return undefined; } const stringToken = token as StringToken; if (!(stringToken.flags & StringTokenFlags.Triplicate)) { // We only care """ string literal return undefined; } if ( !(stringToken.flags & StringTokenFlags.Unterminated) && !TextRange.contains(getStringValueRange(stringToken), offset) ) { // ex) We only support these 2 cases. // """ // | <= here // or // """ // | <= here // """ return undefined; } const lines = parseResults.tokenizerOutput.lines; const begin = convertOffsetToPosition(token.start, lines); const current = convertOffsetToPosition(offset, lines); return _getFirstNonBlankLineIndentationFromText(parseResults, current.line, begin.line); } function _getFirstNonBlankLineIndentationFromText(parseResults: ParseResults, currentLine: number, endingLine: number) { endingLine = Math.max(endingLine, 0); for (let i = currentLine; i >= endingLine; i--) { const result = _getIndentationFromText(parseResults, i); if (!_isBlankLine(parseResults, i, result.charOffset)) { // Not blank line. // ex) [indentation]i = 1 return result.indentation; } } return _getIndentationFromText(parseResults, endingLine).indentation; } function _findStringToken(tokens: TextRangeCollection<Token>, index: number): Token | undefined { const token = _findPreviousNonWhitespaceTokenFromIndex(tokens, index); if (!token) { return undefined; } return token.type === TokenType.String ? token : undefined; } function _findPreviousNonWhitespaceToken(tokens: TextRangeCollection<Token>, offset: number): Token | undefined { const index = tokens.getItemAtPosition(offset); if (index < 0) { return undefined; } return _findPreviousNonWhitespaceTokenFromIndex(tokens, index); } function _findPreviousNonWhitespaceTokenFromIndex( tokens: TextRangeCollection<Token>, index: number ): Token | undefined { for (let i = index; i >= 0; i--) { const token = _getTokenAtIndex(tokens, i); if (!token) { break; } if (_isWhitespaceToken(token.type)) { continue; } return token; } return undefined; } function _findNextTokenIndex(tokens: TextRangeCollection<Token>, offset: number): number { const index = tokens.getItemAtPosition(offset); if (index < 0) { return index; } for (let i = index + 1; i < tokens.count; i++) { const token = _getTokenAtIndex(tokens, i); if (token?.type === TokenType.Dedent || token?.type === TokenType.NewLine) { continue; } return i; } return tokens.count - 1; } function _getTokenAtIndex(tokens: TextRangeCollection<Token>, index: number) { if (index < 0) { return undefined; } return tokens.getItemAt(index); } function _shouldDedentAfterKeyword(tokens: TextRangeCollection<Token>, offset: number) { // Keeping the PTVS smart indenter behavior. // For now, we won't include all small statements that can put at single line. // See parser.ts to see all small statements or see python grammar. // ex) def foo(): pass const index = tokens.getItemAtPosition(offset); if (index < 0) { return false; } for (let i = index; i >= 0; i--) { const token = _getTokenAtIndex(tokens, i); if (!token) { return false; } switch (token.type) { case TokenType.Dedent: case TokenType.NewLine: case TokenType.EndOfStream: continue; case TokenType.Keyword: { const previousToken = _getTokenAtIndex(tokens, i - 1); if (previousToken?.type === TokenType.Colon) { // Not for single line construct. // ex) def foo(): pass return false; } const keyword = token as KeywordToken; return ( keyword.keywordType === KeywordType.Pass || keyword.keywordType === KeywordType.Return || keyword.keywordType === KeywordType.Break || keyword.keywordType === KeywordType.Continue || keyword.keywordType === KeywordType.Raise ); } default: return false; } } return false; } function _isBlankLine(parseResults: ParseResults, line: number, charOffset: number) { const endingLength = _getLineEndingLength(parseResults, line); const lineSpan = parseResults.tokenizerOutput.lines.getItemAt(line); return charOffset === lineSpan.length - endingLength; } function _getLineEndingLength(parseResults: ParseResults, line: number) { let length = 0; const range = parseResults.tokenizerOutput.lines.getItemAt(line); for (let i = range.length - 1; i >= 0; i--) { const charCode = parseResults.text.charCodeAt(range.start + i); switch (charCode) { case Char.FormFeed: case Char.Hash: case Char.LineFeed: case Char.CarriageReturn: length++; break; default: return length; } } return length; } function _getIndentationFromText( parseResults: ParseResults, line: number, uptoLineOffset?: number ): { indentation: number; charOffset: number } { let indentation = 0; let charOffset = 0; const tabSize = _getTabSize(parseResults); const range = parseResults.tokenizerOutput.lines.getItemAt(line); for (let i = 0; i < range.length; i++) { const charCode = parseResults.text.charCodeAt(range.start + i); switch (charCode) { case Char.Space: charOffset++; indentation++; break; case Char.Tab: charOffset++; indentation += tabSize; break; default: if (!uptoLineOffset || uptoLineOffset === i) { return { charOffset, indentation, }; } // calculate indentation upto line offset given. charOffset++; indentation++; } } return { charOffset, indentation, }; } function _convertTokenStreams(parseResults: ParseResults, span: TextRange) { // Existing token stream contains text and whitespace mixed, making it difficult // to process for re-indentation. This will convert those to strictly text and whitespace. const tokens = parseResults.tokenizerOutput.tokens; let startIndex = Math.max(tokens.getItemAtPosition(span.start), 0); const startToken = _getTokenAtIndex(tokens, startIndex)!; if (TextRange.getEnd(startToken) < span.start) { // ex) firstToken | <= span start. startIndex++; } let endIndex = Math.min(tokens.getItemAtPosition(TextRange.getEnd(span)), tokens.length - 1); const endToken = _getTokenAtIndex(tokens, endIndex)!; if (TextRange.getEnd(span) < endToken.start) { // ex) |< = span end [endToken] endIndex--; } const tokenInfoArray: TokenInfo[] = []; const lines = parseResults.tokenizerOutput.lines; for (let i = startIndex; i <= endIndex; i++) { const token = _getTokenAtIndex(tokens, i)!; if (token.comments) { for (const comment of token.comments) { tokenInfoArray.push({ start: comment.start, length: comment.length, range: convertTextRangeToRange(comment, lines), text: comment.value, kind: 'comment', firstTokenOnLine: false, multilineDocComment: false, }); } } if (_isWhitespaceToken(token.type) || token.length === 0) { continue; } tokenInfoArray.push({ start: token.start, length: token.length, range: convertTextRangeToRange(token, lines), text: parseResults.text.substr(token.start, token.length), kind: token.type === TokenType.String ? 'string' : 'token', firstTokenOnLine: false, multilineDocComment: false, }); } if (tokenInfoArray.length === 0) { return tokenInfoArray; } tokenInfoArray.sort((a, b) => a.start - b.start); // Handle text in whitespace that is not part of token stream. let previousInfo = tokenInfoArray[0]; const additionalTokens: TokenInfo[] = []; for (let i = 1; i < tokenInfoArray.length; i++) { const info = tokenInfoArray[i]; // Another approach is just blindly go through the range looking for // non whitespace char rather than looking for specific cases like below. if (previousInfo.kind !== 'comment') { for ( let whitespaceLine = previousInfo.range.end.line; whitespaceLine < info.range.start.line; whitespaceLine++ ) { const lineTextRange = lines.getItemAt(whitespaceLine); const lastCharOffset = lineTextRange.length - _getLineEndingLength(parseResults, whitespaceLine) - 1; if (lastCharOffset >= 0) { // ex) i = 1 \ <= explicit multiline construct // + // 2 const start = lineTextRange.start + lastCharOffset; _addTokenInfoIfMatch(parseResults, start, start + 1, Char.Backslash, additionalTokens); } } } if (info.kind === 'comment') { const start = previousInfo.range.end.line === info.range.start.line ? TextRange.getEnd(previousInfo) : lines.getItemAt(info.range.start.line).start; // ex) token [#] comment _addTokenInfoIfMatch(parseResults, start, info.start, Char.Hash, additionalTokens); } previousInfo = info; } appendArray(tokenInfoArray, additionalTokens); tokenInfoArray.sort((a, b) => a.start - b.start); // Update firstTokenOnLine and multilineDocComment previousInfo = tokenInfoArray[0]; if (startIndex === 0) { // It is the first token in the file. previousInfo.firstTokenOnLine = true; } else { const previousToken = _findPreviousNonWhitespaceTokenFromIndex(tokens, startIndex - 1)!; const previousEnd = convertOffsetToPosition(TextRange.getEnd(previousToken), lines); previousInfo.firstTokenOnLine = previousEnd.line !== previousInfo.range.start.line; } previousInfo.multilineDocComment = _isMultilineDocComment(parseResults, previousInfo); for (let i = 1; i < tokenInfoArray.length; i++) { const info = tokenInfoArray[i]; info.firstTokenOnLine = previousInfo.range.end.line !== info.range.start.line; info.multilineDocComment = _isMultilineDocComment(parseResults, info); previousInfo = info; } return tokenInfoArray; } function _addTokenInfoIfMatch( parseResults: ParseResults, start: number, end: number, charCode: number, tokens: TokenInfo[] ) { for (let i = start; i < end; i++) { if (parseResults.text.charCodeAt(i) === charCode) { tokens.push({ start: i, length: 1, range: convertTextRangeToRange(TextRange.create(i, 1), parseResults.tokenizerOutput.lines), text: String.fromCharCode(charCode), kind: 'token', firstTokenOnLine: false, multilineDocComment: false, }); } } } function _isWhitespaceToken(type: TokenType): boolean { switch (type) { case TokenType.Dedent: case TokenType.NewLine: case TokenType.Indent: case TokenType.EndOfStream: return true; default: return false; } } function _isMultilineDocComment(parseResults: ParseResults, info: TokenInfo) { if (info.kind !== 'string' || !info.firstTokenOnLine || info.range.start.line === info.range.end.line) { return false; } const node = findNodeByOffset(parseResults.parseTree, info.start); if ( node?.nodeType !== ParseNodeType.String || node.parent?.nodeType !== ParseNodeType.StringList || node.parent.parent?.nodeType !== ParseNodeType.StatementList ) { return false; } return isDocString(node.parent.parent); } function _reindentLinesFromText(parseResults: ParseResults, info: TokenInfo, indentDelta: number) { const texts: string[] = []; for (let i = info.range.start.line; i <= info.range.end.line; i++) { texts.push(_reindentLineFromText(parseResults, i, indentDelta, i === info.range.end.line ? info : undefined)); } return texts; } function _reindentLineFromText( parseResults: ParseResults, line: number, indentDelta: number, range?: TextRange ): string { const result = _getIndentationFromText(parseResults, line); if (_isBlankLine(parseResults, line, result.charOffset)) { return ''; } let lineRange = parseResults.tokenizerOutput.lines.getItemAt(line); if (range) { lineRange = TextRange.fromBounds( lineRange.start, Math.min(TextRange.getEnd(range), TextRange.getEnd(lineRange)) ); } const text = parseResults.text.substr(lineRange.start + result.charOffset, lineRange.length - result.charOffset); return _createIndentationString(parseResults, Math.max(result.indentation + indentDelta, 0)) + text; } function _getTabSize(parseResults: ParseResults) { const tab = parseResults.tokenizerOutput.predominantTabSequence; const tabLength = tab.length; if (tabLength === 1 && tab.charCodeAt(0) === Char.Tab) { // Tokenizer will use 8 for Char.Tab and put that info in indentToken's indent size. return defaultTabSize; } return tabLength; } function _createIndentationString(parseResults: ParseResults, indentation: number) { const tab = parseResults.tokenizerOutput.predominantTabSequence; const tabLength = tab.length; if (tabLength === 1 && tab.charCodeAt(0) === Char.Tab) { const spaceCount = indentation % defaultTabSize; const tabCount = (indentation - spaceCount) / defaultTabSize; return '\t'.repeat(tabCount) + ' '.repeat(spaceCount); } return ' '.repeat(indentation); }
the_stack
import { HttpClient, HttpInterceptor } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Query, PostsRes } from 'models/models'; import { STEEM_API, STEEMIA_POSTS, STEEMIA_USERS, STEEMIA_TAGS, STEEMIA_SEARCH } from '../../constants/constants'; import { UtilProvider } from '../util/util'; import { SteemConnectProvider } from '../steemconnect/steemconnect'; import { Observable } from 'rxjs/Observable'; import "rxjs/add/operator/debounceTime"; import 'rxjs/add/operator/switchMap'; import 'rxjs/add/operator/share'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/retry'; import 'rxjs/operator/shareReplay'; /** * * Class with Steemia API methods * * @author Jayser Mendez * @version 0.0.1 * */ @Injectable() export class SteemiaProvider { private username: string = ''; constructor(public http: HttpClient, public util: UtilProvider, private steemConnect: SteemConnectProvider) { this.steemConnect.status.subscribe(res => { if (res.status === true) { this.username = res.userObject.user; } }); } /** * Method to dispatch the debounced search * @method dispatch_search: Method to dispatch the search * @param {Observable<string>} term */ public dispatch_search(term: Observable<string>, page: number) { return term.debounceTime(500) .switchMap((value: string) => this.get_search(value, page)); } /** * Method to prepare the search operation * @method get_search: Prepare the http call for the search * @param {String} term: String with the search term */ private get_search(value: string, page: number) { let que: Query; let result: any; // If the search is for an user if (value[0] === '@') { value = value.substr(1); if (this.isEmpty(value) === true) { return Observable.of({ error: 'value is empty' }); } que = { search: value } // If the user is logged in, include it into the query if (this.isEmpty(this.username) === false) { que.username = this.username; } result = this.http.get(STEEMIA_SEARCH + 'users?' + this.util.encodeQueryData(que)).retry(3); } // If the search is for a tag else if (value[0] === '#') { value = value.substr(1); if (this.isEmpty(value) === true) { return Observable.of({ error: 'value is empty' }); } que = { search: value, page: page } // If the user is logged in, include it into the query if (this.isEmpty(this.username) === false) { que.username = this.username; } result = this.http.get(STEEMIA_SEARCH + 'tags?' + this.util.encodeQueryData(que)).retry(3) } else if (this.isEmpty(value) === true) { return Observable.of({ error: 'value is empty' }) } // Otherwise, it is a tag search else { value = value.split(' ')[0]; value = value.replace(/[^0-9a-z]/gi, ''); que = { search: value, page: page }; // If the user is logged in, include it into the query if (this.isEmpty(this.username) === false) { que.username = this.username; } result = this.http.get(STEEMIA_SEARCH + 'posts?' + this.util.encodeQueryData(que)).retry(3) .share() } // Return the prepared http call return result; } /** * Helper method to determine whether a string is empty * @param value: String to check * @returns a boolean statement determining whether it is empty or not */ private isEmpty(value): boolean { return value === '' || value === ' ' || value === null || value === undefined } /** * Public method to dispatch the data to the corresponding page * * @method dispatch_feed * @param {Query} query: Object with data for query */ public dispatch_feed(query: Query): Promise<any> { return this.http.get(STEEMIA_POSTS + 'feed?' + this.util.encodeQueryData(query)).retry(3) .share().toPromise(); } /** * Method to retrieve post in any category or in general. Also, * can be retrieved by hot, new, or top. * * @method get_posts * @param {String} type: hot, new, or top * @param {Query} query: Object with data for query * @param {String} category */ public get_posts(type: string, query: Query, category?: string) { return this.http.get(STEEMIA_POSTS + type + '?' + this.util.encodeQueryData(query)).retry(3) .share(); } /** * Public method to dispatch the data to the corresponding page * * @method dispatch_posts * @param {Query} query: Object with data for query */ public dispatch_posts(query: Query): Promise<any> { return this.get_posts(query.type, query).toPromise(); } /** * Public method to dispatch profile posts * * @method dispatch_profile_posts * @param {Query} query: Object with data for query */ public dispatch_profile_posts(query: Query): Promise<any> { return this.http.get(STEEMIA_POSTS + 'blog?' + this.util.encodeQueryData(query)).retry(3) .share().toPromise() } /** * Public method to dispatch profile info data * * @method dispatch_profile_info * @param {Query} query: Object with data for query */ public dispatch_profile_info(query: Query): Promise<any> { return this.http.get(STEEMIA_USERS + 'info?' + this.util.encodeQueryData(query)).retry(3).toPromise(); } /** * Public method to dispatch comments data * * @method dispatch_comments * @param {Query} query: Object with data for query */ public dispatch_comments(query: Query) { return this.http.get(STEEMIA_POSTS + 'comments?' + this.util.encodeQueryData(query)).retry(3).toPromise(); } /** * Public method to dispatch menu profile data * * @method dispatch_menu_profile * @param {string} account: Username of the user */ public dispatch_menu_profile(username: string): Promise<any> { return this.http.get(STEEMIA_USERS + 'info?user=' + username).retry(3).share().toPromise(); } /** * Public method to dispatch votes data * * @method dispatch_votes * @param {Query} query: Object with data for query */ public dispatch_votes(query: Query): Promise<any> { query.permlink = query.permlink.split('/')[3]; return this.http.get(STEEMIA_POSTS + 'votes?' + this.util.encodeQueryData(query)).retry(3) .share().toPromise(); } /** * Public method to dispatch account data * * @method dispatch_account * @param {string} account: Username of the user */ public dispatch_account(account): Promise<any> { return this.http.get(STEEM_API + 'get_accounts?names[]=%5B%22' + account + '%22%5D') .share().toPromise(); } /** * Public method to dispatch account activity data * * @method dispatch_account * @param {string} account: Username of the user */ public dispatch_activity(query): Promise<any> { return this.http.get(STEEM_API + 'get_account_history?' + this.util.encodeQueryData(query)).retry(3).share().toPromise(); } /** * Public method to dispatch post single data * * @method dispatch_post_single * @param {Query} query: Object with data for query */ public dispatch_post_single(query: Query): Promise<any> { query.permlink = query.permlink.split('/')[3]; query.username = this.username; return this.http.get(STEEMIA_POSTS + 'info?' + this.util.encodeQueryData(query)).retry(3).share().toPromise(); } /** * Public method to dispatch post single data * * @method dispatch_post_single * @param {Query} query: Object with data for query */ public dispatch_post_single_notifications(query: Query): Promise<any> { query.username = this.username; return this.http.get(STEEMIA_POSTS + 'info?' + this.util.encodeQueryData(query)).retry(3).share().toPromise(); } /** * Method to dispatch comment single data * * @method dispatch_comment_single * @param {String} author: Author of the comment * @param {String} permlink: Permlink of the comment */ public dispatch_comment_single(author: string, permlink: string): Promise<any> { let url = permlink.split('/')[4]; // Split the url in order to get the desired permlink return this.http.get(STEEM_API + 'get_content?' + this.util.encodeQueryData({ author: author, permlink: url })) .retry(3).share().toPromise(); } /** * Method to dispatch followers of an user * @param {String} username: Username to get followers for * @param {Number} limit: How many will be loaded * @param {String} start_following: From where it should start querying */ public dispatch_followers(username: string, limit: number, start_follower?: string): Promise<any> { // If not pagination is indicated, start from 0 (A.K.A empty string) if (!start_follower) { start_follower = ''; } return this.http.get(STEEMIA_USERS + 'followers?' + this.util.encodeQueryData({ username: username, limit: limit, start: start_follower })) .retry(3).toPromise(); } /** * Method to dispatch following of an user * @param {String} username: Username to get following for * @param {Number} limit: How many will be loaded * @param {String} start_following: From where it should start querying */ public dispatch_following(username: string, limit: number, start_following?: string): Promise<any> { // If not pagination is indicated, start from 0 (A.K.A empty string) if (!start_following) { start_following = ''; } return this.http.get(STEEMIA_USERS + 'following?' + this.util.encodeQueryData({ username: username, limit: limit, start: start_following })) .retry(3).toPromise(); } /** * Method to dispatch user stats data * @param {String} username: Username to get stats for */ public dispatch_stats(username: string): Promise<any> { return this.http.get(STEEMIA_USERS + 'stats?' + this.util.encodeQueryData({ user: username })).retry(3).toPromise(); } /** * Method to see if a user is following you or vice versa. * @param {String} username: Your username or other user username * @param {String} target: Username to compare against */ public is_following(username: string, target: string): Promise<any> { return this.http.get(STEEMIA_USERS + 'is_following?' + this.util.encodeQueryData({ username: username, user: target })).retry(3).toPromise(); } /** * Method to get voting power * @param {String} username: Username to get voting power */ public get_voting_power(username: string): Promise<any> { return this.http.get(STEEMIA_USERS + 'voting_power?username=' + username).retry(3).toPromise(); } /** * Method to get comments as tree nodes * @param {String} author: Author of the post * @param {String} permlink: Permlink of the post * @param {String} username: Current user logged in */ public get_comments_tree(author: string, permlink: string, username: string): Promise<any> { return this.http.get(STEEMIA_POSTS + 'comments-new?author=' + author + '&permlink=' + permlink + '&username=' + username).retry(3).toPromise(); } /** * Method to dipatch all tags (up to 1000) */ public dispatch_tags(): Promise<any> { return this.http.get(STEEMIA_TAGS + '/all').retry(3).toPromise(); } }
the_stack
import {Injectable, OnDestroy, OnInit} from '@angular/core'; import {ArchivaRequestService} from "@app/services/archiva-request.service"; import {UserInfo} from '@app/model/user-info'; import {HttpErrorResponse, HttpResponse} from "@angular/common/http"; import {ErrorResult} from "@app/model/error-result"; import {Observable, throwError} from "rxjs"; import {Permission} from '@app/model/permission'; import {PagedResult} from "@app/model/paged-result"; import {User} from '@app/model/user'; import {catchError, map} from "rxjs/operators"; import {RoleTree} from "@app/model/role-tree"; @Injectable({ providedIn: 'root' }) export class UserService implements OnInit, OnDestroy { userInfo: UserInfo; permissions: Permission[]; guestPermissions: Permission[]; authenticated: boolean; uiPermissionsDefault = { 'menu': { 'repo': { 'section': true, 'browse': true, 'search': true, 'upload': false }, 'security':{ 'section': false, 'roles': false, 'users': false, 'config': false }, 'admin': { 'section': false, 'config': false, 'status': false, 'reports': false }, } }; uiPermissions; constructor(private rest: ArchivaRequestService) { this.userInfo = new UserInfo(); this.uiPermissions = {}; this.deepCopy(this.uiPermissionsDefault, this.uiPermissions); } ngOnDestroy(): void { this.resetUser(); } ngOnInit(): void { this.userInfo.user_id = "guest"; this.loadPersistedUserInfo(); this.authenticated = false; this.deepCopy(this.uiPermissionsDefault, this.uiPermissions); if (this.guestPermissions == null) { let observer = { next: (permList: Permission[]) => { this.guestPermissions = permList; if (!this.authenticated) { this.permissions = this.guestPermissions; this.parsePermissions(this.permissions); } }, error: err => { console.log("Could not retrieve permissions " + err); } } this.retrievePermissionInfo("guest").subscribe(observer); } } /** * Retrieves the user information from the REST service for the current logged in user. * This works only, if a valid access token is present. * It returns a observable that can be subscribed to catch the user information. */ public retrieveUserInfo(): Observable<UserInfo> { return new Observable<UserInfo>((resultObserver) => { let accessToken = localStorage.getItem("access_token"); if (accessToken != null) { let infoObserver = this.rest.executeRestCall<UserInfo>("get", "redback", "users/me", null); let userInfoObserver = { next: (x: UserInfo) => { this.userInfo = x; if (this.userInfo.language == null) { this.loadPersistedUserInfo(); } this.persistUserInfo(); this.authenticated = true; resultObserver.next(this.userInfo); }, error: (err: HttpErrorResponse) => { console.log("Error " + (JSON.stringify(err))); let result = err.error as ErrorResult if (result != null && result.error_messages != null) { for (let msg of result.error_messages) { console.error('Observer got an error: ' + msg.error_key) } } else if (err.message != null) { console.error("Bad response from user info call: " + err.message); } this.authenticated = false; resultObserver.error(); }, complete: () => { resultObserver.complete(); } }; infoObserver.subscribe(userInfoObserver); } }); } /** * Retrieves the permission list from the REST service */ public retrievePermissionInfo(userNameParam?:string): Observable<Permission[]> { let userName; if (userNameParam==null||userNameParam=='') { userName = this.authenticated ? "me" : "guest"; } else { userName = userNameParam; } return this.rest.executeRestCall<Permission[]>("get", "redback", "users/" + userName + "/permissions", null).pipe( catchError((err:HttpErrorResponse)=> { console.log("Error " + (JSON.stringify(err))); let result = err.error as ErrorResult if (result.error_messages != null) { for (let msg of result.error_messages) { console.debug('Observer got an error: ' + msg.error_key) } } this.resetPermissions(); return []; }), map((perm:Permission[])=>{ this.permissions = perm; this.parsePermissions(perm); return perm; }) ); } resetPermissions() { this.deepCopy(this.uiPermissionsDefault, this.uiPermissions); } parsePermissions(permissions: Permission[]) { this.resetPermissions(); for (let perm of permissions) { // console.debug("Checking permission for op: " + perm.operation.name); switch (perm.operation.name) { case "archiva-manage-configuration": { if (perm.resource.identifier == '*') { this.uiPermissions.menu.admin.section = true; this.uiPermissions.menu.admin.config = true; this.uiPermissions.menu.admin.reports = true; this.uiPermissions.menu.admin.status = true; this.uiPermissions.menu.security.section = true; this.uiPermissions.menu.security.config = true; } } case "archiva-manage-users": { if (perm.resource.identifier == '*') { this.uiPermissions.menu.security.section = true; this.uiPermissions.menu.security.users = true; this.uiPermissions.menu.security.roles = true; } } case "redback-configuration-edit": { if (perm.resource.identifier == '*') { this.uiPermissions.menu.security.section = true; this.uiPermissions.menu.security.config = true; } } case "archiva-upload-file": { this.uiPermissions.menu.repo.upload = true; } } } } private deepCopy(src: Object, dst: Object) { Object.keys(src).forEach((key, idx) => { let srcEl = src[key]; if (typeof (srcEl) == 'object') { let dstEl; if (!dst.hasOwnProperty(key)) { dst[key] = {} } dstEl = dst[key]; this.deepCopy(srcEl, dstEl); } else { // console.debug("setting " + key + " = " + srcEl); dst[key] = srcEl; } }); } /** * Stores user information persistent. Not the complete UserInfo object, only properties, that * are needed. */ public persistUserInfo() { if (this.userInfo != null && this.userInfo.user_id != null && this.userInfo.user_id != "") { let prefix = "user." + this.userInfo.user_id; localStorage.setItem(prefix + ".user_id", this.userInfo.user_id); localStorage.setItem(prefix + ".id", this.userInfo.id); if (this.userInfo.language != null && this.userInfo.language != "") { localStorage.setItem(prefix + ".language", this.userInfo.language); } } } /** * Loads the persisted user info from the local storage */ public loadPersistedUserInfo() { if (this.userInfo.user_id != null && this.userInfo.user_id != "") { let prefix = "user." + this.userInfo.user_id; this.userInfo.language = localStorage.getItem(prefix + ".language"); } } /** * Resets the user info to default values. */ resetUser() { this.userInfo = new UserInfo(); this.userInfo.user_id = "guest"; this.resetPermissions(); this.authenticated = false; } public query(searchTerm: string, offset: number = 0, limit: number = 10, orderBy: string[] = ['user_id'], order: string = 'asc'): Observable<PagedResult<UserInfo>> { console.log("getUserList " + searchTerm + "," + offset + "," + limit + "," + orderBy + "," + order); if (searchTerm == null) { searchTerm = "" } if (orderBy == null || orderBy.length == 0) { orderBy = ['user_id']; } return this.rest.executeRestCall<PagedResult<UserInfo>>("get", "redback", "users", { 'q': searchTerm, 'offset': offset, 'limit': limit, 'orderBy': orderBy, 'order': order }); } public addUser(user: User): Observable<UserInfo> { return this.rest.executeResponseCall<UserInfo>("post", "redback", "users", user).pipe( catchError((error: HttpErrorResponse) => { return throwError(this.rest.getTranslatedErrorResult(error)); }), map((httpResponse: HttpResponse<UserInfo>) => { if (httpResponse.status==201) { let user = httpResponse.body; user.location = httpResponse.headers.get('Location'); return user; } else { throwError(new HttpErrorResponse({headers:httpResponse.headers,status:httpResponse.status,statusText:"Bad response code"})) } })); } public getUser(userid: string): Observable<UserInfo> { return this.rest.executeRestCall<UserInfo>("get", "redback", "users/" + userid, null).pipe( catchError((error: HttpErrorResponse) => { return throwError(this.rest.getTranslatedErrorResult(error)); })); } public updateUser(user:User): Observable<UserInfo> { return this.rest.executeRestCall<UserInfo>("put", "redback", "users/" + user.user_id, user).pipe( catchError((error: HttpErrorResponse) => { return throwError(this.rest.getTranslatedErrorResult(error)); })); } public deleteUser(user_id:string): Observable<boolean> { return this.rest.executeResponseCall<boolean>("delete", "redback", "users/" + user_id, null).pipe( catchError((error: HttpErrorResponse) => { return throwError(this.rest.getTranslatedErrorResult(error)); }), map((response) => { return response.status == 200; })); } public userExists(userid:string): Observable<boolean> { console.log("Checking user " + userid); return this.rest.executeResponseCall<string>("head", "redback", "users/" + userid, null).pipe( catchError((error: HttpErrorResponse) => { if (error.status==404) { console.log("Status 404") return [false]; } else { return throwError(this.rest.getTranslatedErrorResult(error)); } }), map((httpResponse: HttpResponse<string>) => httpResponse.status == 200)); } public userRoleTree(userid:string): Observable<RoleTree> { return this.rest.executeResponseCall<RoleTree>("get", "redback","users/"+userid+"/roletree", null).pipe( catchError((error: HttpErrorResponse)=>{ if (error.status==404) { console.error("User not found: " + userid); return []; } else { return throwError(this.rest.getTranslatedErrorResult(error)); } }) ).pipe(map((httpResponse:HttpResponse<RoleTree>)=>httpResponse.body)) } public changeOwnPassword(current_password:string, password:string, confirm_password:string) { let data = { "user_id":this.userInfo.user_id, "current_password":current_password, "new_password":password, "new_password_confirmation":confirm_password } return this.rest.executeRestCall<any>("post", "redback", "users/me/password/update", data).pipe( catchError((error: HttpErrorResponse)=>{ return throwError(this.rest.getTranslatedErrorResult(error)); }) ); } }
the_stack
import dotProp from 'dot-prop'; import { eachPair } from './iterators'; /** * Makes sure the error once printed using console.log contains the actual class name. * * @example * ``` * class MyApiError extends CustomerError {} * * throw MyApiError() // prints MyApiError instead of simply "Error". * ``` * * @public */ export class CustomError extends Error { public name: string; public stack?: string; constructor(public message: string = '') { super(message); this.name = this.constructor.name; } } /** * @public */ export interface ClassType<T = any> { new(...args: any[]): T; } /** * @public */ export type AbstractClassType<T = any> = abstract new (...args: any[]) => T; export type ExtractClassType<T> = T extends ClassType<infer K> ? K : never; declare const __forward: unique symbol; /** * This type maintains the actual type, but erases the decoratorMetadata, which is requires in a circular reference for ECMAScript modules. * Basically fixes like "ReferenceError: Cannot access 'MyClass' before initialization" */ export type Forward<T> = T & { [__forward]?: true }; /** * Returns the class name either of the class definition or of the class of an instance. * * Note when code is minimized/uglified this output will change. You should disable in your compile the * className modification. * * @example * ```typescript * class User {} * * expect(getClassName(User)).toBe('User'); * expect(getClassName(new User())).toBe('User'); * ``` * * @public */ export function getClassName<T>(classTypeOrInstance: ClassType<T> | Object): string { if (!classTypeOrInstance) return 'undefined'; const proto = (classTypeOrInstance as any)['prototype'] ? (classTypeOrInstance as any)['prototype'] : classTypeOrInstance; return proto.constructor.name; } /** * Same as getClassName but appends the propertyName. * @public */ export function getClassPropertyName<T>(classType: ClassType<T> | Object, propertyName: string): string { const name = getClassName(classType); return `${name}.${propertyName}`; } /** * @public */ export function applyDefaults<T>(classType: ClassType<T>, target: { [k: string]: any }): T { const classInstance = new classType(); for (const [i, v] of eachPair(target)) { (classInstance as any)[i] = v; } return classInstance; } /** * Tries to identify the object by normalised result of Object.toString(obj). */ export function typeOf(obj: any) { return ((({}).toString.call(obj).match(/\s([a-zA-Z]+)/) || [])[1] || '').toLowerCase(); } /** * Returns true if the given obj is a plain object, and no class instance. * * isPlainObject(\{\}) === true * isPlainObject(new ClassXY) === false * * @public */ export function isPlainObject(obj: any): obj is object { return Boolean(obj && typeof obj === 'object' && obj.constructor instanceof obj.constructor); } /** * Returns the ClassType for a given instance. */ export function getClassTypeFromInstance<T>(target: T): ClassType<T> { if (!isClassInstance(target)) { throw new Error(`Value is not a class instance. Got ${stringifyValueWithType(target)}`); } return (target as any)['constructor'] as ClassType<T>; } /** * Returns true when target is a class instance. */ export function isClassInstance(target: any): boolean { return target !== undefined && target !== null && target['constructor'] && Object.getPrototypeOf(target) === (target as any)['constructor'].prototype && !isPlainObject(target) && isObject(target); } /** * Returns a human readable string representation from the given value. */ export function stringifyValueWithType(value: any): string { if ('string' === typeof value) return `String(${value})`; if ('number' === typeof value) return `Number(${value})`; if ('boolean' === typeof value) return `Boolean(${value})`; if ('function' === typeof value) return `Function ${value.name}`; if (isPlainObject(value)) return `Object ${prettyPrintObject(value)}`; if (isObject(value)) return `${getClassName(getClassTypeFromInstance(value))} ${prettyPrintObject(value)}`; if (null === value) return `null`; return 'undefined'; } /** * Changes the class of a given instance and returns the new object. * * @example * ```typescript * * class Model1 { * id: number = 0; * } * * class Model2 { * id: number = 0; * } * * const model1 = new Model1(); * const model2 = changeClass(model1, Model2); * model2 instanceof Model2; //true * ``` */ export function changeClass<T>(value: object, newClass: ClassType<T>): T { return Object.assign(Object.create(newClass.prototype), value); } export function prettyPrintObject(object: object): string { let res: string[] = []; for (const i in object) { res.push(i + ': ' + stringifyValueWithType((object as any)[i])); } return '{' + res.join(',') + '}'; } /** * Returns true if given obj is a function. * * @public */ export function isFunction(obj: any): obj is Function { if ('function' === typeof obj) { return !obj.toString().startsWith('class '); } return false; } const AsyncFunction = (async () => { }).constructor; /** * Returns true if given obj is a async function. * * @public */ export function isAsyncFunction(obj: any): obj is (...args: any[]) => Promise<any> { return obj instanceof AsyncFunction; } /** * Returns true if given obj is a promise like object. * * Note: There's not way to check if it's actually a Promise using instanceof since * there are a lot of different implementations around. * * @public */ export function isPromise<T>(obj: any | Promise<T>): obj is Promise<T> { return obj !== null && typeof obj === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function' && typeof obj.finally === 'function'; } /** * Returns true if given obj is a ES6 class (ES5 fake classes are not supported). * * @public */ export function isClass(obj: any): obj is ClassType { if ('function' === typeof obj) { return obj.toString().startsWith('class ') || obj.toString().startsWith('class{'); } return false; } /** * Returns true for real objects: object literals ({}) or class instances (new MyClass). * * @public */ export function isObject(obj: any): obj is { [key: string]: any } { if (obj === null) { return false; } return (typeof obj === 'object' && !isArray(obj)); } /** * @public */ export function isArray(obj: any): obj is any[] { return !!(obj && 'number' === typeof obj.length && 'function' === typeof obj.reduce); } /** * @public */ export function isNull(obj: any): obj is null { return null === obj; } /** * @public */ export function isUndefined(obj: any): obj is undefined { return undefined === obj; } /** * Checks if obj is not null and not undefined. * * @public */ export function isSet(obj: any): boolean { return !isNull(obj) && !isUndefined(obj); } /** * @public */ export function isNumber(obj: any): obj is number { return 'number' === typeOf(obj); } /** * @public */ export function isString(obj: any): obj is string { return 'string' === typeOf(obj); } /** * @public */ export function indexOf<T>(array: T[], item: T): number { if (!array) { return -1; } return array.indexOf(item); } /** * @public */ export async function sleep(seconds: number): Promise<void> { return new Promise<void>(resolve => setTimeout(resolve, seconds * 1000)); } /** * Creates a shallow copy of given array. * * @public */ export function copy<T>(v: T[]): T[] { if (isArray(v)) { return v.slice(0); } return v; } /** * Checks whether given array or object is empty (no keys). If given object is falsy, returns false. * * @public */ export function empty<T>(value?: T[] | object | {}): boolean { if (!value) return true; if (isArray(value)) { return value.length === 0; } else { for (const i in value) if (value.hasOwnProperty(i)) return false; return true; } } /** * Returns the size of given array or object. * * @public */ export function size<T>(array: T[] | { [key: string]: T }): number { if (!array) { return 0; } if (isArray(array)) { return array.length; } else { return getObjectKeysSize(array); } } /** * Returns the first key of a given object. * * @public */ export function firstKey(v: { [key: string]: any } | object): string | undefined { return Object.keys(v)[0]; } /** * Returns the last key of a given object. * * @public */ export function lastKey(v: { [key: string]: any } | object): string | undefined { const keys = Object.keys(v); if (keys.length) { return; } return keys[keys.length - 1]; } /** * Returns the first value of given array or object. * * @public */ export function first<T>(v: { [key: string]: T } | T[]): T | undefined { if (isArray(v)) { return v[0]; } const key = firstKey(v); if (key) { return v[key]; } return; } /** * Returns the last value of given array or object. * * @public */ export function last<T>(v: { [key: string]: T } | T[]): T | undefined { if (isArray(v)) { if (v.length > 0) { return v[v.length - 1]; } return; } const key = firstKey(v); if (key) { return v[key]; } return; } /** * Returns the average of a number array. * * @public */ export function average(array: number[]): number { let sum = 0; for (const n of array) { sum += n; } return sum / array.length; } /** * @public */ export function prependObjectKeys(o: { [k: string]: any }, prependText: string): { [k: string]: any } { const converted: { [k: string]: any } = {}; for (const i in o) { if (!o.hasOwnProperty(i)) continue; converted[prependText + i] = o[i]; } return converted; } /** * @public */ export function appendObject(origin: { [k: string]: any }, extend: { [k: string]: any }, prependKeyName: string = '') { const no = prependObjectKeys(extend, prependKeyName); for (const [i, v] of eachPair(no)) { origin[i] = v; } } /** * A better alternative to "new Promise()" that supports error handling and maintains the stack trace for Error.stack. * * When you use `new Promise()` you need to wrap your code inside a try-catch to call `reject` on error. * asyncOperation() does this automatically. * * When you use `new Promise()` you will lose the stack trace when `reject(new Error())` is called. * asyncOperation() makes sure the error stack trace is the correct one. * * @example * ```typescript * await asyncOperation(async (resolve, reject) => { * await doSomething(); //if this fails, reject() will automatically be called * stream.on('data', (data) => { * resolve(data); //at some point you MUST call resolve(data) * }); * }); * ``` * * @public */ export async function asyncOperation<T>(executor: (resolve: (value: T) => void, reject: (error: any) => void) => void | Promise<void>): Promise<T> { try { return await new Promise<T>(async (resolve, reject) => { try { await executor(resolve, reject); } catch (e) { reject(e); } }); } catch (error) { mergeStack(error, createStack()); throw error; } } /** * @public */ export function mergePromiseStack<T>(promise: Promise<T>, stack?: string): Promise<T> { stack = stack || createStack(); promise.then(() => { }, (error) => { mergeStack(error, stack || ''); }); return promise; } /** * @beta */ export function createStack(removeCallee: boolean = true): string { if (Error.stackTraceLimit === 10) Error.stackTraceLimit = 100; let stack = new Error().stack || ''; /* at createStack (/file/path) at promiseToObservable (/file/path) at userLandCode1 (/file/path) at userLandCode2 (/file/path) */ //remove "at createStack" stack = stack.slice(stack.indexOf(' at ') + 6); stack = stack.slice(stack.indexOf(' at ') - 1); if (removeCallee) { //remove callee stack = stack.slice(stack.indexOf(' at ') + 6); stack = stack.slice(stack.indexOf(' at ') - 1); } return stack; } /** * @beta */ export function mergeStack(error: Error, stack: string) { if (error instanceof Error && error.stack) { error.stack += '\n' + stack; } } export function collectForMicrotask<T>(callback: (args: T[]) => void): (arg: T) => void { let items: T[] = []; let taskScheduled = false; return (arg: T) => { items.push(arg); if (!taskScheduled) { taskScheduled = true; queueMicrotask(() => { taskScheduled = false; callback(items); items.length = 0; }); } }; } /** * Returns the current time as seconds. * * @public */ export function time(): number { return Date.now() / 1000; } /** * @public */ export function getPathValue(bag: { [field: string]: any }, parameterPath: string, defaultValue?: any): any { if (isSet(bag[parameterPath])) { return bag[parameterPath]; } const result = dotProp.get(bag, parameterPath); return isSet(result) ? result : defaultValue; } /** * @public */ export function setPathValue(bag: object, parameterPath: string, value: any) { dotProp.set(bag, parameterPath, value); } /** * @public */ export function deletePathValue(bag: object, parameterPath: string) { dotProp.delete(bag, parameterPath); } /** * Returns the human readable byte representation. * * @public */ export function humanBytes(bytes: number, si: boolean = false): string { const thresh = si ? 1000 : 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } const units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; let u = -1; do { bytes /= thresh; ++u; } while (Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(2) + ' ' + units[u]; } /** * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length. */ export function getObjectKeysSize(obj: object): number { let size = 0; for (let i in obj) if (obj.hasOwnProperty(i)) size++; return size; } export function isConstructable(fn: any): boolean { try { new new Proxy(fn, { construct: () => ({}) }); return true; } catch (err) { return false; } }; export function isPrototypeOfBase(prototype: ClassType | undefined, base: ClassType): boolean { if (!prototype) return false; if (prototype === base) return true; let currentProto = Object.getPrototypeOf(prototype); while (currentProto && currentProto !== Object.prototype) { if (currentProto === base) return true; currentProto = Object.getPrototypeOf(currentProto); } return false; } declare var v8debug: any; export function inDebugMode() { return typeof v8debug === 'object' || /--debug|--inspect/.test(process.execArgv.join(' ')); } /** * Create a new class with the given name. * This is currently the only know way to make it workable in browsers too. */ export function createDynamicClass(name: string, base?: ClassType): ClassType { if (base) { let baseName = getClassName(base); if (baseName === name) baseName += 'Base'; return new Function(baseName, `return class ${name} extends ${baseName} {}`)(base); } return new Function(`return class ${name} {}`)(); }
the_stack
import { FastifyInstance } from 'fastify'; import StatusCodes from 'http-status-codes'; import { Pool } from 'pg'; import { constructionParseOperations, CONSTRUCTION_INVALID_TRANSACTION, CONSTRUCTION_PAYLOADS_REQUEST, CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_OUTPUT, CONSTRUCTION_PAYLOADS_REQUEST_WITH_MA, CONSTRUCTION_PAYLOADS_REQUEST_WITH_MULTIPLE_MA, CONSTRUCTION_PAYLOADS_REQUEST_WITH_SEVERAL_MA, CONSTRUCTION_PAYLOADS_REQUEST_WITM_MA_WITHOUT_NAME, CONSTRUCTION_PAYLOADS_STAKE_DELEGATION_RESPONSE, CONSTRUCTION_PAYLOADS_STAKE_DEREGISTRATION_RESPONSE, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_AND_DELEGATION_RESPONSE, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_AND_WITHDRAWAL_RESPONSE, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_RESPONSE, CONSTRUCTION_PAYLOADS_WITHDRAWAL_RESPONSE, CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_AND_PLEDGE, CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_CERT, CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_MULTIPLE_RELAY, CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_NO_METADATA, CONSTRUCTION_PAYLOADS_WITH_STAKE_DELEGATION, CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_DEREGISTRATION, CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION, CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION_AND_WITHDRAWAL, CONSTRUCTION_PAYLOADS_WITH_STAKE_REGISTRATION_AND_DELEGATION, CONSTRUCTION_PAYLOADS_WITH_WITHDRAWAL, CONSTRUCTION_SIGNED_TRANSACTION_WITH_EXTRA_DATA, CONSTRUCTION_SIGNED_TX_WITH_BYRON_ADDRESS_AND_EXTRA_DATA, CONSTRUCTION_SIGNED_TRANSACTION_WITH_MA, CONSTRUCTION_SIGNED_TRANSACTION_WITH_MULTIPLE_MA, CONSTRUCTION_SIGNED_TRANSACTION_WITH_SEVERAL_MA, CONSTRUCTION_SIGNED_TX_WITH_MA_WITHOUT_NAME, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_AND_PLEDGE, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_CERT, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_MULTIPLE_RELAYS, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_NO_METADATA, CONSTRUCTION_SIGNED_TX_WITH_POOL_RETIREMENT, CONSTRUCTION_SIGNED_TX_WITH_REGISTRATION_AND_EXTRA_DATA, CONSTRUCTION_SIGNED_TX_WITH_REGISTRATION_AND_WITHDRWAWAL_AND_EXTRA_DATA, CONSTRUCTION_UNSIGNED_TRANSACTION_WITH_EXTRA_DATA, CONSTRUCTION_SIGNED_TX_INPUT_WITH_BYRON_ADDRESS_AND_EXTRA_DATA, CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_INPUT, CONSTRUCTION_PAYLOADS_WITH_POOL_RETIREMENT, CONSTRUCTION_SIGNED_TX_WITH_VOTE_REGISTRATION, CONSTRUCTION_PAYLOADS_WITH_VOTE_REGISTRATION, CONSTRUCTION_PAYLOADS_WITH_VOTE_REGISTRATION_RESPONSE } from '../fixture-data'; import { setupOfflineDatabase, setupServer } from '../utils/test-utils'; const CONSTRUCTION_PARSE_ENDPOINT = '/construction/parse'; const generateParsePayload = (blockchain: string, network: string, signed: boolean, transaction: string) => ({ network_identifier: { blockchain, network }, signed, transaction }); describe(CONSTRUCTION_PARSE_ENDPOINT, () => { let database: Pool; let server: FastifyInstance; beforeAll(async () => { database = setupOfflineDatabase(); server = setupServer(database); }); afterAll(async () => { await database.end(); }); test('Should return 1 input, 2 outputs and signers if a valid signed transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TRANSACTION_WITH_EXTRA_DATA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual(constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST)); expect(response.json().account_identifier_signers).toEqual([ { address: CONSTRUCTION_PAYLOADS_REQUEST.operations[0].account?.address } ]); }); test('Should return 1 input with byron address and signers if a valid signed transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_INPUT_WITH_BYRON_ADDRESS_AND_EXTRA_DATA ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_INPUT) ); expect(response.json().account_identifier_signers).toEqual([ { address: CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_INPUT.operations[0].account?.address } ]); }); test('Should return valid data if a valid signed transaction with a Byron address is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_BYRON_ADDRESS_AND_EXTRA_DATA ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_OUTPUT) ); expect([response.json().account_identifier_signers[0].address]).toEqual([ CONSTRUCTION_PAYLOADS_REQUEST_WITH_BYRON_OUTPUT.operations[0].account?.address ]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key registration and signers with payment and stake addresses', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_REGISTRATION_AND_EXTRA_DATA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION) ); expect( response.json().account_identifier_signers.map((account_signer: { address: any }) => account_signer.address) ).toEqual([ CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION.operations[0].account?.address, 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' ]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key registration, 1 withdrawal and signers addresses should be unique ', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_REGISTRATION_AND_WITHDRWAWAL_AND_EXTRA_DATA ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION_AND_WITHDRAWAL) ); expect( response.json().account_identifier_signers.map((account_signer: { address: any }) => account_signer.address) ).toEqual([ CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION_AND_WITHDRAWAL.operations[0].account?.address, 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' ]); }); test('Should return 1 input, 2 outputs and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_UNSIGNED_TRANSACTION_WITH_EXTRA_DATA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual(constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST)); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key registration and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_RESPONSE) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION) ); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key deregistration and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_STAKE_DEREGISTRATION_RESPONSE) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_DEREGISTRATION) ); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake delegation and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_STAKE_DELEGATION_RESPONSE) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_DELEGATION) ); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key registration, 1 stake delegation and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_AND_DELEGATION_RESPONSE ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_REGISTRATION_AND_DELEGATION) ); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 withdrawal and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_WITHDRAWAL_RESPONSE) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual(constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_WITHDRAWAL)); expect(response.json().account_identifier_signers).toEqual([]); }); // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 stake key registration, 1 withdrawal and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_STAKE_REGISTRATION_AND_WITHDRAWAL_RESPONSE ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_STAKE_KEY_REGISTRATION_AND_WITHDRAWAL) ); expect(response.json().account_identifier_signers).toEqual([]); }); test('Should throw an error when invalid signed transaction bytes are provided', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_INVALID_TRANSACTION) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4011, message: 'Cant create signed transaction from transaction bytes', retriable: false }); }); test('Should throw an error when invalid unsigned transaction bytes are provided', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_INVALID_TRANSACTION) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4012, message: 'Cant create unsigned transaction from transaction bytes', retriable: false }); }); test('Should throw an error when valid unsigned transaction bytes but signed flag is true are provided', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_UNSIGNED_TRANSACTION_WITH_EXTRA_DATA) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4011, message: 'Cant create signed transaction from transaction bytes', retriable: false }); }); test('Should throw an error when valid signed transaction bytes but signed flag is false are provided', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', false, CONSTRUCTION_SIGNED_TRANSACTION_WITH_EXTRA_DATA) }); expect(response.statusCode).toEqual(StatusCodes.INTERNAL_SERVER_ERROR); expect(response.json()).toEqual({ code: 4012, message: 'Cant create unsigned transaction from transaction bytes', retriable: false }); }); test('Should return 1 input and 2 ouput, first input and ouput with MultiAssets', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TRANSACTION_WITH_MA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual(constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITH_MA)); }); test('Should correctly parse operations with two MultiAssets', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TRANSACTION_WITH_MULTIPLE_MA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITH_MULTIPLE_MA) ); }); test('Should correctly parse operations with several MultiAssets ', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TRANSACTION_WITH_SEVERAL_MA) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITH_SEVERAL_MA) ); }); test('Should correctly parse operations with MultiAssets without name ', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_MA_WITHOUT_NAME) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_REQUEST_WITM_MA_WITHOUT_NAME) ); }); describe('Pool registration requests', () => { test('Should correctly parse operations with pool registrations with pledge ', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_AND_PLEDGE ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_AND_PLEDGE) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' }, { address: '1b268f4cba3faa7e36d8a0cc4adca2096fb856119412ee7330f692b5' }, { address: 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' }, { address: 'stake1uxly0q2cnpxrjrqm9vpnr9dwkr0j945gulhhgs3dx33l47sweg9er' } ]); }); test('Should correctly parse operations with pool registrations with multiple relays', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_MULTIPLE_RELAYS ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_MULTIPLE_RELAY) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' }, { address: '1b268f4cba3faa7e36d8a0cc4adca2096fb856119412ee7330f692b5' }, { address: 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' }, { address: 'stake1uxly0q2cnpxrjrqm9vpnr9dwkr0j945gulhhgs3dx33l47sweg9er' } ]); }); test('Should correctly parse operations with pool registrations with no pool metadata', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_NO_METADATA ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_NO_METADATA) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' }, { address: '1b268f4cba3faa7e36d8a0cc4adca2096fb856119412ee7330f692b5' }, { address: 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' }, { address: 'stake1uxly0q2cnpxrjrqm9vpnr9dwkr0j945gulhhgs3dx33l47sweg9er' } ]); }); test('Should correctly parse operations with pool registrations with cert', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_POOL_REGISTRATION_WITH_CERT ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_POOL_REGISTRATION_WITH_CERT) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' }, { address: 'stake1u9af5n26dtr6nkrs9qv05049x0jkcncau9k6vyd8xrhr7qq8tez5p' }, { address: '1b268f4cba3faa7e36d8a0cc4adca2096fb856119412ee7330f692b5' }, { address: 'stake1uxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7caek7a5' } ]); }); }); describe('Pool retirement requests', () => { // eslint-disable-next-line max-len test('Should return 1 input, 2 outputs, 1 pool retirement and empty signers if a valid unsigned transaction is set', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_POOL_RETIREMENT) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_POOL_RETIREMENT) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' }, { address: '153806dbcd134ddee69a8c5204e38ac80448f62342f8c23cfe4b7edf' } ]); }); }); describe('Vote Registration', () => { test('Should correctly parse operations with vote registration data for signed transactions', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload('cardano', 'mainnet', true, CONSTRUCTION_SIGNED_TX_WITH_VOTE_REGISTRATION) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_VOTE_REGISTRATION) ); expect(response.json().account_identifier_signers).toEqual([ { address: 'addr1vxa5pudxg77g3sdaddecmw8tvc6hmynywn49lltt4fmvn7cpnkcpx' } ]); }); test('Should correctly parse operations with vote registration data for unsigned transactions', async () => { const response = await server.inject({ method: 'post', url: CONSTRUCTION_PARSE_ENDPOINT, payload: generateParsePayload( 'cardano', 'mainnet', false, CONSTRUCTION_PAYLOADS_WITH_VOTE_REGISTRATION_RESPONSE ) }); expect(response.statusCode).toEqual(StatusCodes.OK); expect(response.json().operations).toEqual( constructionParseOperations(CONSTRUCTION_PAYLOADS_WITH_VOTE_REGISTRATION) ); expect(response.json().account_identifier_signers).toEqual([]); }); }); });
the_stack
import { Buffer } from "buffer/" import BN from "bn.js" import BinTools from "../../utils/bintools" import { EVMConstants } from "./constants" import { EVMOutput } from "./outputs" import { TransferableInput } from "./inputs" import { EVMBaseTx } from "./basetx" import { SelectCredentialClass } from "./credentials" import { Signature, SigIdx, Credential } from "../../common/credentials" import { StandardAmountInput } from "../../common/input" import { KeyChain, KeyPair } from "./keychain" import { DefaultNetworkID, Defaults } from "../../utils/constants" import { Serialization, SerializedEncoding } from "../../utils/serialization" import { ChainIdError, TransferableInputError, EVMOutputError, EVMFeeError } from "../../utils/errors" /** * @ignore */ const bintools: BinTools = BinTools.getInstance() const serializer: Serialization = Serialization.getInstance() /** * Class representing an unsigned Import transaction. */ export class ImportTx extends EVMBaseTx { protected _typeName = "ImportTx" protected _typeID = EVMConstants.IMPORTTX serialize(encoding: SerializedEncoding = "hex"): object { let fields: object = super.serialize(encoding) return { ...fields, sourceChain: serializer.encoder( this.sourceChain, encoding, "Buffer", "cb58" ), importIns: this.importIns.map((i) => i.serialize(encoding)) } } deserialize(fields: object, encoding: SerializedEncoding = "hex") { super.deserialize(fields, encoding) this.sourceChain = serializer.decoder( fields["sourceChain"], encoding, "cb58", "Buffer", 32 ) this.importIns = fields["importIns"].map((i: object) => { let ii: TransferableInput = new TransferableInput() ii.deserialize(i, encoding) return ii }) this.numIns = Buffer.alloc(4) this.numIns.writeUInt32BE(this.importIns.length, 0) } protected sourceChain: Buffer = Buffer.alloc(32) protected numIns: Buffer = Buffer.alloc(4) protected importIns: TransferableInput[] = [] protected numOuts: Buffer = Buffer.alloc(4) protected outs: EVMOutput[] = [] /** * Returns the id of the [[ImportTx]] */ getTxType = (): number => { return this._typeID } /** * Returns a {@link https://github.com/feross/buffer|Buffer} for the source chainid. */ getSourceChain = (): Buffer => { return this.sourceChain } /** * Takes a {@link https://github.com/feross/buffer|Buffer} containing an [[ImportTx]], parses it, * populates the class, and returns the length of the [[ImportTx]] in bytes. * * @param bytes A {@link https://github.com/feross/buffer|Buffer} containing a raw [[ImportTx]] * @param offset A number representing the byte offset. Defaults to 0. * * @returns The length of the raw [[ImportTx]] * * @remarks assume not-checksummed */ fromBuffer(bytes: Buffer, offset: number = 0): number { offset = super.fromBuffer(bytes, offset) this.sourceChain = bintools.copyFrom(bytes, offset, offset + 32) offset += 32 this.numIns = bintools.copyFrom(bytes, offset, offset + 4) offset += 4 const numIns: number = this.numIns.readUInt32BE(0) for (let i: number = 0; i < numIns; i++) { const anIn: TransferableInput = new TransferableInput() offset = anIn.fromBuffer(bytes, offset) this.importIns.push(anIn) } this.numOuts = bintools.copyFrom(bytes, offset, offset + 4) offset += 4 const numOuts: number = this.numOuts.readUInt32BE(0) for (let i: number = 0; i < numOuts; i++) { const anOut: EVMOutput = new EVMOutput() offset = anOut.fromBuffer(bytes, offset) this.outs.push(anOut) } return offset } /** * Returns a {@link https://github.com/feross/buffer|Buffer} representation of the [[ImportTx]]. */ toBuffer(): Buffer { if (typeof this.sourceChain === "undefined") { throw new ChainIdError( "ImportTx.toBuffer -- this.sourceChain is undefined" ) } this.numIns.writeUInt32BE(this.importIns.length, 0) this.numOuts.writeUInt32BE(this.outs.length, 0) let barr: Buffer[] = [super.toBuffer(), this.sourceChain, this.numIns] let bsize: number = super.toBuffer().length + this.sourceChain.length + this.numIns.length this.importIns = this.importIns.sort(TransferableInput.comparator()) this.importIns.forEach((importIn: TransferableInput) => { bsize += importIn.toBuffer().length barr.push(importIn.toBuffer()) }) bsize += this.numOuts.length barr.push(this.numOuts) this.outs.forEach((out: EVMOutput) => { bsize += out.toBuffer().length barr.push(out.toBuffer()) }) return Buffer.concat(barr, bsize) } /** * Returns an array of [[TransferableInput]]s in this transaction. */ getImportInputs(): TransferableInput[] { return this.importIns } /** * Returns an array of [[EVMOutput]]s in this transaction. */ getOuts(): EVMOutput[] { return this.outs } clone(): this { let newImportTx: ImportTx = new ImportTx() newImportTx.fromBuffer(this.toBuffer()) return newImportTx as this } create(...args: any[]): this { return new ImportTx(...args) as this } /** * Takes the bytes of an [[UnsignedTx]] and returns an array of [[Credential]]s * * @param msg A Buffer for the [[UnsignedTx]] * @param kc An [[KeyChain]] used in signing * * @returns An array of [[Credential]]s */ sign(msg: Buffer, kc: KeyChain): Credential[] { const sigs: Credential[] = super.sign(msg, kc) this.importIns.forEach((importIn: TransferableInput) => { const cred: Credential = SelectCredentialClass( importIn.getInput().getCredentialID() ) const sigidxs: SigIdx[] = importIn.getInput().getSigIdxs() sigidxs.forEach((sigidx: SigIdx) => { const keypair: KeyPair = kc.getKey(sigidx.getSource()) const signval: Buffer = keypair.sign(msg) const sig: Signature = new Signature() sig.fromBuffer(signval) cred.addSignature(sig) }) sigs.push(cred) }) return sigs } /** * Class representing an unsigned Import transaction. * * @param networkID Optional networkID, [[DefaultNetworkID]] * @param blockchainID Optional blockchainID, default Buffer.alloc(32, 16) * @param sourceChainID Optional chainID for the source inputs to import. Default platform chainid. * @param importIns Array of [[TransferableInput]]s used in the transaction * @param outs Optional array of the [[EVMOutput]]s */ constructor( networkID: number = DefaultNetworkID, blockchainID: Buffer = Buffer.alloc(32, 16), sourceChainID: Buffer = Buffer.alloc(32, 16), importIns: TransferableInput[] = undefined, outs: EVMOutput[] = undefined ) { super(networkID, blockchainID) this.sourceChain = sourceChainID let inputsPassed: boolean = false let outputsPassed: boolean = false if ( typeof importIns !== "undefined" && Array.isArray(importIns) && importIns.length > 0 ) { importIns.forEach((importIn: TransferableInput) => { if (!(importIn instanceof TransferableInput)) { throw new TransferableInputError( "Error - ImportTx.constructor: invalid TransferableInput in array parameter 'importIns'" ) } }) inputsPassed = true this.importIns = importIns } if (typeof outs !== "undefined" && Array.isArray(outs) && outs.length > 0) { outs.forEach((out: EVMOutput) => { if (!(out instanceof EVMOutput)) { throw new EVMOutputError( "Error - ImportTx.constructor: invalid EVMOutput in array parameter 'outs'" ) } }) if (outs.length > 1) { outs = outs.sort(EVMOutput.comparator()) } outputsPassed = true this.outs = outs } if (inputsPassed && outputsPassed) { this.validateOuts() } } private validateOuts(): void { // This Map enforces uniqueness of pair(address, assetId) for each EVMOutput. // For each imported assetID, each ETH-style C-Chain address can // have exactly 1 EVMOutput. // Map(2) { // '0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC' => [ // 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', // 'F4MyJcUvq3Rxbqgd4Zs8sUpvwLHApyrp4yxJXe2bAV86Vvp38' // ], // '0xecC3B2968B277b837a81A7181e0b94EB1Ca54EdE' => [ // 'FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z', // '2Df96yHyhNc3vooieNNhyKwrjEfTsV2ReMo5FKjMpr8vwN4Jqy', // 'SfSXBzDb9GZ9R2uH61qZKe8nxQHW9KERW9Kq9WRe4vHJZRN3e' // ] // } const seenAssetSends: Map<string, string[]> = new Map() this.outs.forEach((evmOutput: EVMOutput): void => { const address: string = evmOutput.getAddressString() const assetId: string = bintools.cb58Encode(evmOutput.getAssetID()) if (seenAssetSends.has(address)) { const assetsSentToAddress: string[] = seenAssetSends.get(address) if (assetsSentToAddress.includes(assetId)) { const errorMessage: string = `Error - ImportTx: duplicate (address, assetId) pair found in outputs: (0x${address}, ${assetId})` throw new EVMOutputError(errorMessage) } assetsSentToAddress.push(assetId) } else { seenAssetSends.set(address, [assetId]) } }) // make sure this transaction pays the required avax fee const selectedNetwork: number = this.getNetworkID() const requiredFee: BN = Defaults.network[`${selectedNetwork}`].C.txFee const feeDiff: BN = new BN(0) const avaxAssetID: string = Defaults.network[`${selectedNetwork}`].X.avaxAssetID // sum incoming AVAX this.importIns.forEach((input: TransferableInput): void => { // only check StandardAmountInputs if ( input.getInput() instanceof StandardAmountInput && avaxAssetID === bintools.cb58Encode(input.getAssetID()) ) { const ui = input.getInput() as unknown const i = ui as StandardAmountInput feeDiff.iadd(i.getAmount()) } }) // subtract all outgoing AVAX this.outs.forEach((evmOutput: EVMOutput): void => { if (avaxAssetID === bintools.cb58Encode(evmOutput.getAssetID())) { feeDiff.isub(evmOutput.getAmount()) } }) if (feeDiff.lt(requiredFee)) { const errorMessage: string = `Error - ${requiredFee} AVAX required for fee and only ${feeDiff} AVAX provided` throw new EVMFeeError(errorMessage) } } }
the_stack
import { Spreadsheet } from '../base/index'; import { keyDown, cellNavigate, renameSheet, filterCellKeyDown, getUpdateUsingRaf, isLockedCells } from '../common/index'; import { SheetModel, getCellIndexes, getRangeAddress, getRowHeight, getColumnWidth, CellModel, getCell, isHiddenCol } from '../../workbook/index'; import { getRangeIndexes, getSwapRange, isHiddenRow, isColumnSelected, isRowSelected, skipHiddenIdx } from '../../workbook/index'; import { closest, isNullOrUndefined } from '@syncfusion/ej2-base'; /** * Represents keyboard navigation support for Spreadsheet. */ export class KeyboardNavigation { private parent: Spreadsheet; /** * Constructor for the Spreadsheet Keyboard Navigation module. * * @private * @param {Spreadsheet} parent - Specify the spreadsheet */ constructor(parent: Spreadsheet) { this.parent = parent; this.addEventListener(); /* code snippet */ } private addEventListener(): void { this.parent.on(keyDown, this.keyDownHandler, this); /* code snippet */ } private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(keyDown, this.keyDownHandler); } /* code snippet */ } private keyDownHandler(e: KeyboardEvent): void { if (!this.parent.isEdit && (document.activeElement.classList.contains('e-spreadsheet') || closest(document.activeElement, '.e-sheet')) && !closest(e.target as Element, '.e-name-box') && !(document.activeElement.classList.contains('e-ddl') && document.activeElement.classList.contains('e-input-focus'))) { let isNavigate: boolean; let scrollIdxes: number[]; const isRtl: boolean = this.parent.enableRtl; const sheet: SheetModel = this.parent.getActiveSheet(); const actIdxes: number[] = getCellIndexes(sheet.activeCell); if ([9, 37, 38, 39, 40, 33, 34].indexOf(e.keyCode) > -1) { e.preventDefault(); } const filterArgs: { [key: string]: KeyboardEvent | boolean } = { e: e, isFilterCell: false }; if (e.shiftKey) {// shift selection this.shiftSelection(e); } else if (e.altKey && e.keyCode === 40) { this.parent.notify(filterCellKeyDown, filterArgs); } if ((!e.shiftKey && ((!isRtl && e.keyCode === 37) || (isRtl && e.keyCode === 39))) || (e.shiftKey && e.keyCode === 9)) { //left key if (actIdxes[1] > 0 || sheet.isProtected) { if (sheet.isProtected && !sheet.protectSettings.selectUnLockedCells || !sheet.isProtected) { actIdxes[1] -= 1; } else { const idx: number[] = this.getNextUnlockedCell(e.keyCode, actIdxes); actIdxes[1] = idx[1]; actIdxes[0] = idx[0]; } isNavigate = true; } else { const content: Element = this.parent.getMainContent(); if (actIdxes[1] === 0 && content.scrollLeft && !isRtl) { content.scrollLeft = 0; } } } else if (e.shiftKey && e.keyCode === 13) { // Up key if (!this.parent.element.querySelector('.e-find-toolbar')) { if (actIdxes[0] > 0 || sheet.isProtected) { if (sheet.isProtected && !sheet.protectSettings.selectUnLockedCells || !sheet.isProtected) { actIdxes[0] -= 1; } else { const idx: number[] = this.getNextUnlockedCell(e.keyCode, actIdxes); actIdxes[1] = idx[1]; actIdxes[0] = idx[0]; } isNavigate = true; } else { const content: Element = this.parent.getMainContent().parentElement; if (actIdxes[0] === 0 && content.scrollTop) { content.scrollTop = 0; } } } } else if (!filterArgs.isFilterCell && !e.shiftKey && e.keyCode === 38) { // Up key if (sheet.isProtected || actIdxes[0] > 0) { if (sheet.isProtected && !sheet.protectSettings.selectUnLockedCells || !sheet.isProtected) { actIdxes[0] -= 1; } else { const cellIdx: number[] = this.getNextUnlockedCell(e.keyCode, actIdxes); actIdxes[1] = cellIdx[1]; actIdxes[0] = cellIdx[0]; } isNavigate = true; } else { const contentEle: Element = this.parent.getMainContent().parentElement; if (actIdxes[0] === 0 && contentEle.scrollTop) { contentEle.scrollTop = 0; } } } else if ((!e.shiftKey && ((!isRtl && e.keyCode === 39) || (isRtl && e.keyCode === 37))) || e.keyCode === 9) { // Right key const cell: CellModel = getCell(actIdxes[0], actIdxes[1], sheet); if (cell && cell.colSpan > 1) { actIdxes[1] += (cell.colSpan - 1); } if (actIdxes[1] < sheet.colCount - 1) { if (sheet.isProtected && !sheet.protectSettings.selectUnLockedCells || !sheet.isProtected) { actIdxes[1] += 1; } else { const idx: number[] = this.getNextUnlockedCell(e.keyCode, actIdxes); actIdxes[1] = idx[1]; actIdxes[0] = idx[0]; } isNavigate = true; } } else if ((!filterArgs.isFilterCell && !e.shiftKey && e.keyCode === 40) || e.keyCode === 13) { // Down Key const cell: CellModel = getCell(actIdxes[0], actIdxes[1], sheet); if (cell && cell.rowSpan > 1) { actIdxes[0] += (cell.rowSpan - 1); } if (actIdxes[0] < sheet.rowCount - 1) { if (sheet.isProtected && !sheet.protectSettings.selectUnLockedCells || !sheet.isProtected) { actIdxes[0] += 1; } else { const idx: number[] = this.getNextUnlockedCell(e.keyCode, actIdxes); actIdxes[1] = idx[1]; actIdxes[0] = idx[0]; } isNavigate = true; } } /* else if (e.keyCode === 36) { actIdxes[1] = 0; if (e.ctrlKey) { actIdxes[0] = 0; } isNavigate = true; e.preventDefault(); } else if (e.keyCode === 35 && e.ctrlKey) { actIdxes = [sheet.usedRange.rowIndex, sheet.usedRange.colIndex]; scrollIdxes = [sheet.usedRange.rowIndex - this.parent.viewport.rowCount, sheet.usedRange.colIndex - this.parent.viewport.colCount]; isNavigate = true; e.preventDefault(); } */ else if (!e.shiftKey && (e.keyCode === 34 || e.keyCode === 33) && (!this.parent.scrollModule || this.parent.scrollModule.isKeyScroll)) { // Page Up and Page Down const mainPanel: Element = this.parent.element.querySelector('.e-main-panel'); let diff: number = 0; if (e.keyCode === 34) { // Page Down diff = mainPanel.getBoundingClientRect().height + mainPanel.scrollTop; } else { // Page Up diff = mainPanel.scrollTop - mainPanel.getBoundingClientRect().height; if (diff < 0) { return; } } const aRowIdx: number = getCellIndexes(this.parent.getActiveSheet().activeCell)[0]; let topRow: number = getCellIndexes(this.parent.getActiveSheet().paneTopLeftCell)[0]; const selectDiff: number = aRowIdx - topRow; if (this.parent.scrollModule) { this.parent.scrollModule.isKeyScroll = false; } mainPanel.scrollTop = diff; getUpdateUsingRaf((): void => { topRow = getCellIndexes(this.parent.getActiveSheet().paneTopLeftCell)[0]; this.parent.notify(cellNavigate, { range: [topRow + selectDiff, actIdxes[1]], preventAnimation: true }); }); } if (isNavigate && (!this.parent.scrollModule || this.parent.scrollModule.isKeyScroll)) { if (e.keyCode === 40 || e.keyCode === 38 || e.keyCode === 13) { while (isHiddenRow(sheet, actIdxes[0])) { if (e.keyCode === 40 || (!e.shiftKey && e.keyCode === 13)) { actIdxes[0] = actIdxes[0] + 1; } if (e.keyCode === 38 || (e.shiftKey && e.keyCode === 13)) { actIdxes[0] = actIdxes[0] - 1; if (actIdxes[0] < 0) { return; } } } } if (e.keyCode === 37 || e.keyCode === 39 || e.keyCode === 9) { while (isHiddenCol(sheet, actIdxes[1])) { if (e.keyCode === 39 || (!e.shiftKey && e.keyCode === 9)) { actIdxes[1] = actIdxes[1] + 1; } if (e.keyCode === 37 || (e.shiftKey && e.keyCode === 9)) { actIdxes[1] = actIdxes[1] - 1; if (actIdxes[1] < 0) { return; } } } } this.scrollNavigation(scrollIdxes || actIdxes, scrollIdxes ? true : false); const range: string = getRangeAddress(actIdxes); const navigateFn: Function = (preventAnimation?: boolean) => { if (range === sheet.selectedRange) { return; } this.parent.setSheetPropertyOnMute(sheet, 'activeCell', range); this.parent.notify(cellNavigate, { range: actIdxes, preventAnimation: preventAnimation }); }; if (this.parent.scrollModule && this.parent.scrollModule.isKeyScroll) { if (range === sheet.selectedRange) { return; } getUpdateUsingRaf(navigateFn.bind(this, true)); } else { navigateFn(); } } } else if (e.altKey && e.keyCode === 38 && this.parent.element.lastElementChild.classList.contains('e-filter-popup')) { this.parent.notify(filterCellKeyDown, { closePopup: true }); } if ((e.target as Element).classList.contains('e-sheet-rename')) { if (e.keyCode === 32) { e.stopPropagation(); } else if (e.keyCode === 13 || e.keyCode === 27) { this.parent.notify(renameSheet, e); } } } private getNextUnlockedCell(keycode: number, actCellIdx: number[]): number[] { const sheet: SheetModel = this.parent.getActiveSheet(); let index: number[]; if (keycode === 39) { let colIdx: number = actCellIdx[1] + 1; let rowIdx: number = actCellIdx[0]; if (actCellIdx[1] === sheet.usedRange.colIndex) { colIdx = 0; rowIdx = rowIdx + 1; if (actCellIdx[0] === sheet.usedRange.rowIndex) { rowIdx = 0; } } if (actCellIdx[1] === sheet.usedRange.colIndex && actCellIdx[0] === sheet.usedRange.rowIndex) { rowIdx = colIdx = 0; } for (let i: number = rowIdx; i <= sheet.usedRange.rowIndex + 1; i++ ) { if (i > sheet.usedRange.rowIndex) { i = 0; } for (let j: number = colIdx; j <= sheet.usedRange.colIndex; j++) { if (!isLockedCells(this.parent, [i, j, i, j])) { index = [i, j]; return index; } colIdx = j; } rowIdx = i; if (colIdx === sheet.usedRange.colIndex) { colIdx = 0; if (rowIdx === sheet.usedRange.rowIndex) { rowIdx = 0; } else { rowIdx++; } } } } if (keycode === 37) { //Right Key let colIdx: number = actCellIdx[1] - 1; let rowIdx: number = actCellIdx[0]; if (actCellIdx[1] === 0) { colIdx = sheet.usedRange.colIndex; rowIdx = rowIdx - 1; if (actCellIdx[0] === 0) { rowIdx = sheet.usedRange.rowIndex; } } for (let i: number = rowIdx; i >= -1; i-- ) { if (i < 0){ i = sheet.usedRange.rowIndex; } for (let j: number = colIdx; j >= 0; j-- ) { if (!isLockedCells(this.parent, [i, j, i, j])) { index = [i, j]; return index; } colIdx = j; } rowIdx = i; if (colIdx === 0) { colIdx = sheet.usedRange.colIndex; if (rowIdx === 0) { rowIdx = sheet.usedRange.rowIndex; } else { rowIdx--; } } } } if (keycode === 40) { // Down Key let colIdx: number = actCellIdx[1]; let rowIdx: number = actCellIdx[0] + 1; if (actCellIdx[0] === sheet.usedRange.rowIndex) { colIdx = colIdx + 1; rowIdx = 0; if (actCellIdx[1] === sheet.usedRange.colIndex) { rowIdx = 0; } } if (actCellIdx[1] === sheet.usedRange.colIndex && actCellIdx[0] === sheet.usedRange.rowIndex) { rowIdx = colIdx = 0; } for (let i: number = colIdx; i <= sheet.usedRange.colIndex + 1; i++ ) { if (i > sheet.usedRange.colIndex) { i = 0; } for (let j: number = rowIdx; j<= sheet.usedRange.rowIndex; j++) { if (!isLockedCells(this.parent, [j, i, j, i])) { index = [j, i]; return index; } rowIdx = j; } colIdx = i; if (rowIdx === sheet.usedRange.rowIndex) { colIdx++; if (colIdx === sheet.usedRange.colIndex) { rowIdx = 0; } else { rowIdx = 0; } } } } if (keycode === 38) { // Up Key let colIdx: number = actCellIdx[1]; let rowIdx: number = actCellIdx[0] - 1; if (actCellIdx[0] === 0) { colIdx = colIdx - 1; rowIdx = sheet.usedRange.rowIndex; if (actCellIdx[1] === 0) { colIdx = sheet.usedRange.colIndex; } } for (let i: number = colIdx; i >= -1; i-- ) { if (i < 0) { i = sheet.usedRange.colIndex; } for (let j: number = rowIdx; j>= 0; j--) { if (!isLockedCells(this.parent, [j, i, j, i])) { index = [j, i]; return index; } rowIdx = j; } colIdx = i; if (rowIdx === 0) { rowIdx = sheet.usedRange.rowIndex; if (colIdx === 0) { colIdx = sheet.usedRange.colIndex; } else { colIdx--; } } } } return index; } private shiftSelection(e: KeyboardEvent): void { const sheet: SheetModel = this.parent.getActiveSheet(); const selectedRange: number[] = getRangeIndexes(sheet.selectedRange); const swapRange: number[] = getSwapRange(selectedRange); let noHidden: boolean = true; if (e.keyCode === 38) { // shift + up arrow for (let i: number = swapRange[1]; i <= swapRange[3]; i++) { const cell: CellModel = getCell(selectedRange[2], i, this.parent.getActiveSheet()); if (!isNullOrUndefined(cell) && cell.rowSpan && cell.rowSpan < 0) { selectedRange[2] = selectedRange[2] - (Math.abs(cell.rowSpan) + 1); noHidden = false; break; } } if (noHidden) { selectedRange[2] = selectedRange[2] - 1; } if (selectedRange[2] < 0) { selectedRange[2] = 0; } } if (e.keyCode === 40) { // shift + down arrow for (let i: number = swapRange[1]; i <= swapRange[3]; i++) { const cell: CellModel = getCell(selectedRange[2], i, this.parent.getActiveSheet()); if (!isNullOrUndefined(cell) && cell.rowSpan && cell.rowSpan > 0) { selectedRange[2] = selectedRange[2] + Math.abs(cell.rowSpan); noHidden = false; break; } } if (noHidden) { selectedRange[2] = selectedRange[2] + 1; } if (sheet.rowCount <= selectedRange[2]) { selectedRange[2] = sheet.rowCount - 1; } } if (e.keyCode === 39) { // shift + right arrow for (let i: number = swapRange[0]; i <= swapRange[2]; i++) { const cell: CellModel = getCell(i, selectedRange[3], this.parent.getActiveSheet()); if (!isNullOrUndefined(cell) && cell.colSpan && cell.colSpan > 0) { selectedRange[3] = selectedRange[3] + Math.abs(cell.colSpan); noHidden = false; break; } } if (noHidden) { selectedRange[3] = selectedRange[3] + 1; } if (sheet.colCount <= selectedRange[3]) { selectedRange[3] = sheet.colCount - 1; } } if (e.keyCode === 37) { // shift + left arrow for (let i: number = swapRange[0]; i <= swapRange[2]; i++) { const cell: CellModel = getCell(i, selectedRange[3], this.parent.getActiveSheet()); if (!isNullOrUndefined(cell) && cell.colSpan && cell.colSpan < 0) { selectedRange[3] = selectedRange[3] - (Math.abs(cell.colSpan) + 1); noHidden = false; break; } } if (noHidden) { selectedRange[3] = selectedRange[3] - 1; } if (selectedRange[3] < 0) { selectedRange[3] = 0; } } if (e.shiftKey && e.ctrlKey && !this.parent.scrollSettings.enableVirtualization) { // ctrl + shift selection const usedRange: number[] = [sheet.usedRange.rowIndex, sheet.usedRange.colIndex]; if (e.keyCode === 37) { if (selectedRange[3] <= usedRange[1]) { selectedRange[3] = 0; } else { selectedRange[3] = usedRange[1]; } } if (e.keyCode === 38) { if (selectedRange[2] <= usedRange[0]) { selectedRange[2] = 0; } else { selectedRange[2] = usedRange[0]; } } if (e.keyCode === 39) { if (selectedRange[3] <= usedRange[1]) { selectedRange[3] = usedRange[1]; } else { selectedRange[3] = this.parent.getActiveSheet().colCount; } } if (e.keyCode === 40) { if (selectedRange[2] <= usedRange[0]) { selectedRange[2] = usedRange[0]; } else { selectedRange[2] = this.parent.getActiveSheet().rowCount; } } } if (e.keyCode === 37 || e.keyCode === 39 || e.keyCode === 38 || e.keyCode === 40) { const activeIdxes: number[] = getCellIndexes(sheet.activeCell); while (isHiddenRow(this.parent.getActiveSheet(), selectedRange[2])) { if (e.keyCode === 40) { selectedRange[2] = selectedRange[2] + 1; } if (e.keyCode === 38) { selectedRange[2] = selectedRange[2] - 1; } } this.parent.selectRange(getRangeAddress(selectedRange)); this.scrollNavigation([isColumnSelected(sheet, selectedRange) ? activeIdxes[0] : selectedRange[2], isRowSelected(sheet, selectedRange) ? activeIdxes[1] : selectedRange[3]], false); } } private scrollNavigation(actIdxes: number[], isScroll: boolean): void { if (!this.parent.allowScrolling) { return; } const x: number = this.parent.enableRtl ? -1 : 1; const cont: Element = this.parent.getMainContent().parentElement; const hCont: Element = this.parent.getScrollElement(); const sheet: SheetModel = this.parent.getActiveSheet(); const selectedRange: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange)); const topLeftIdxes: number[] = getCellIndexes(sheet.topLeftCell); const frozenRow: number = this.parent.frozenRowCount(sheet); const frozenCol: number = this.parent.frozenColCount(sheet); const paneTopLeftIdxes: number[] = getCellIndexes(sheet.paneTopLeftCell); const topIdx: number = skipHiddenIdx(sheet, actIdxes[0] < frozenRow ? topLeftIdxes[0] : paneTopLeftIdxes[0], true); const leftIdx: number = actIdxes[1] < frozenCol ? topLeftIdxes[1] : paneTopLeftIdxes[1]; const offsetTopSize: number = this.parent.scrollModule.offset.top.size; if (cont.scrollTop) { if (frozenRow && actIdxes[0] !== selectedRange[2]) { if (actIdxes[0] === frozenRow) { cont.scrollTop = 0; return; } if (actIdxes[0] === frozenRow - 1) { cont.scrollTop = 0; } } else if (actIdxes[0] === skipHiddenIdx(sheet, 0, true)) { cont.scrollTop = 0; return; } } if (hCont && hCont.scrollLeft) { if (frozenCol && actIdxes[1] !== selectedRange[3]) { if (actIdxes[1] === frozenCol) { hCont.scrollLeft = 0; return; } if (actIdxes[1] === frozenCol - 1) { hCont.scrollLeft = 0; } } else if (actIdxes[1] === skipHiddenIdx(sheet, 0, true, 'columns')) { hCont.scrollLeft = 0; return; } } if (this.getBottomIdx(topIdx) <= actIdxes[0] || isScroll) { cont.scrollTop = offsetTopSize + getRowHeight(sheet, skipHiddenIdx(sheet, paneTopLeftIdxes[0], true), true); this.parent.scrollModule.isKeyScroll = false; } else if (topIdx > actIdxes[0]) { cont.scrollTop = offsetTopSize - Math.ceil(getRowHeight(sheet, actIdxes[0], true)); this.parent.scrollModule.isKeyScroll = false; } const scrollLeftIdx: number = this.getRightIdx(leftIdx); if ((scrollLeftIdx <= actIdxes[1] || isScroll) && hCont) { hCont.scrollLeft += getColumnWidth(sheet, scrollLeftIdx, null, true) * x; this.parent.scrollModule.isKeyScroll = false; } else if (leftIdx > actIdxes[1] && hCont) { hCont.scrollLeft -= getColumnWidth(sheet, actIdxes[1], null, true) * x; this.parent.scrollModule.isKeyScroll = false; } } private getBottomIdx(top: number): number { let hgt: number = 0; const sheet: SheetModel = this.parent.getActiveSheet(); const viewPortHeight: number = (sheet.frozenRows ? this.parent.viewport.height - this.parent.sheetModule.getColHeaderHeight( sheet, true) : this.parent.viewport.height) - 17 || 20; for (let i: number = top; ; i++) { hgt += getRowHeight(sheet, i, true); if (hgt >= viewPortHeight) { return i; } } } private getRightIdx(left: number): number { let width: number = 0; const sheet: SheetModel = this.parent.getActiveSheet(); const contWidth: number = (this.parent.getMainContent() as HTMLElement).parentElement.offsetWidth - this.parent.sheetModule.getRowHeaderWidth(sheet) - this.parent.sheetModule.getScrollSize(); for (let i: number = left; ; i++) { width += getColumnWidth(sheet, i, null, true); if (width >= contWidth) { return i; } } } /** * For internal use only - Get the module name. * * @private * @returns {string} - Get the module name. */ protected getModuleName(): string { return 'keyboardNavigation'; } public destroy(): void { this.removeEventListener(); this.parent = null; } }
the_stack
///<reference types="node"/> import * as assert from "assert"; import "mocha"; import {contains, repeat} from "../../../dist/commonjs/System/Collections/Array/Utility"; import * as Procedure from "../../../dist/commonjs/System/Collections/Array/Procedure"; import { Enumerable, InfiniteLinqEnumerable, LinqEnumerable } from "../../../dist/commonjs/System.Linq/Linq"; import Functions from "../../../dist/commonjs/System/Functions"; import {EmptyEnumerator} from "../../../dist/commonjs/System/Collections/Enumeration/EmptyEnumerator"; import {List} from "../../../dist/commonjs/System/Collections/List"; interface TestItem { a:number; b:number; c:string; children?:TestItem[]; } const source:TestItem[] = [ { a: 1, b: 2, c: "a", children: [ { a: 1, b: 2, c: "a", children: [ { a: 1, b: 2, c: "a", children: [] }, { a: 1, b: 1, c: "b", }, { a: 1, b: 3, c: "c" } ] }, { a: 1, b: 1, c: "b", }, { a: 1, b: 3, c: "c" } ] }, { a: 1, b: 1, c: "b", }, { a: 1, b: 3, c: "c" }, { a: 2, b: 2, c: "d" }, { a: 2, b: 1, c: "e" }, { a: 2, b: 3, c: "f" } ]; Object.freeze(source); // Compile test: //noinspection JSUnusedLocalSymbols function compileTest():LinqEnumerable<TestItem> { const list = new List(source); return list.linq.orderBy(v => v.a) .takeWhile((g, i) => i<5); } const sourceMany = Enumerable<string>(Object.freeze([ "a,b,c,d,e", <any>null, "f,g,h,i,j", "k,l,m,n,o", "p,q,r,s,t", "u,v,w,x,y", ])); const sourceManyFlat = "abcdefghijklmnopqrstuvwxy"; const sourceArrayEnumerable = Enumerable(source), sourceEnumerable = new LinqEnumerable(() => sourceArrayEnumerable.getEnumerator()); describe(".force()", () => { it("should not throw", () => { assert.doesNotThrow(() => { sourceEnumerable.force() }); }); }); describe(".count()", () => { it("should match count to length", () => { assert.equal(sourceArrayEnumerable.count(), source.length); assert.equal(sourceEnumerable.count(), source.length); assert.equal(Enumerable([]).count(), 0); assert.equal(Enumerable.empty().count(), 0); assert.equal(sourceArrayEnumerable.count(e => e.a===1), 3); }); }); describe(".source", () => { it("should equal the original", () => { assert.equal(source, (<any>(sourceArrayEnumerable)).source); }); }); describe(".memoize()", () => { it("should cache the values as it goes for reuse later", () => { const source = sourceEnumerable; let A = source.memoize(); source.memoize().dispose(); // Covers else condition. let sum = A.sum(o => o.a); assert.equal(sum, source.sum(o => o.a), "Values must be equal after memoize pass 1."); sum = A.sum(o => o.b); assert.equal(sum, source.sum(o => o.b), "Values must be equal after memoize pass 2."); A.dispose(); // Disposing this memoized source should not affect other tests. assert.throws(() => { // Should throw after disposal. A.force(); }); A = sourceArrayEnumerable.memoize(); A.dispose(); assert.throws(() => { // Should throw after disposal. A.force(); }); }); }); describe(".choose(predicate)", () => { it("should filter out null and undefined values.", () => { const other = <TestItem[]>[<any>null, <any>void(0)]; assert.equal(sourceArrayEnumerable .concat(other) .choose() .select(s => s.a) .where(s => s===1) .count(), 3); assert.equal(sourceArrayEnumerable .concat(other) .choose((e:TestItem, i:number) => { return <TestItem>(i%2 ? e : null); }) .count(), 3); sourceArrayEnumerable .concat(other) .choose() .dispose(); }); }); describe(".where(predicate).memoize()", () => { it("should cache the values as it goes for reuse later", () => { const source = sourceArrayEnumerable.where(i => i.a==1); let sum:number, A = source; sum = A.sum(o => o.a); assert.equal(sum, source.sum(o => o.a), "Values must be equal after where pass 1."); sum = A.sum(o => o.b); assert.equal(sum, source.sum(o => o.b), "Values must be equal after where pass 2."); A = source.memoize(); sum = A.sum(o => o.a); assert.equal(sum, source.sum(o => o.a), "Values must be equal after memoize pass 1."); sum = A.sum(o => o.b); assert.equal(sum, source.sum(o => o.b), "Values must be equal after memoize pass 2."); source.dispose(); }); }); describe(".orderBy(selector)", () => { it("should order ascending based upon the selector", () => { const source = sourceArrayEnumerable.reverse(); assert.equal(source.first().c, "f"); }); }); describe(".orderBy(selector)", () => { it("should order ascending based upon the selector", () => { const source = sourceArrayEnumerable.reverse(); const A = source.orderBy(o => o.a).toArray(); for(let i = 0; i<3; i++) { assert.equal(A[i].a, 1, "First three 'a' values should be 1 when ordered by 'a'."); } for(let i = 3; i<6; i++) { assert.equal(A[i].a, 2, "Last three 'a' values should be 2 when ordered by 'a'."); } const B = source.orderBy(o => o.b).toArray(); for(let i = 0; i<2; i++) { assert.equal(B[i].b, 1, "First two 'b' values should be 1 when ordered by 'b'."); } for(let i = 2; i<4; i++) { assert.equal(B[i].b, 2, "Second two 'b' values should be 2 when ordered by 'b'."); } for(let i = 4; i<6; i++) { assert.equal(B[i].b, 3, "Last two 'b' values should be 3 when ordered by 'b'."); } }); }); describe(".orderByDescending(selector)", () => { it("should order descending based upon the selector", () => { const source = sourceArrayEnumerable.reverse(); const A = source.orderByDescending((o:TestItem) => o.a).toArray(); for(let i = 0; i<3; i++) { assert.equal(A[i].a, 2, "First three 'a' values should be 2 when ordered by 'a'."); } for(let i = 3; i<6; i++) { assert.equal(A[i].a, 1, "Last three 'a' values should be 1 when ordered by 'a'."); } const B = source.orderByDescending((o:TestItem) => o.b).toArray(); for(let i = 0; i<2; i++) { assert.equal(B[i].b, 3, "First two 'b' values should be 3 when ordered by 'b'."); } for(let i = 2; i<4; i++) { assert.equal(B[i].b, 2, "Second two 'b' values should be 2 when ordered by 'b'."); } for(let i = 4; i<6; i++) { assert.equal(B[i].b, 1, "Last two 'b' values should be 1 when ordered by 'b'."); } }); }); describe(".orderBy(selector).thenBy(selector)", () => { it("should order by one then the other", () => { const B = sourceArrayEnumerable .orderBy(o => o.b) .thenBy(o => o.c) .toArray(); for(let i = 0; i<2; i++) { assert.equal(B[i].b, 1, "First two 'b' values should be 1 when ordered by 'b'."); } for(let i = 2; i<4; i++) { assert.equal(B[i].b, 2, "Second two 'b' values should be 2 when ordered by 'b'."); } for(let i = 4; i<6; i++) { assert.equal(B[i].b, 3, "Last two 'b' values should be 3 when ordered by 'b'."); } assert.equal(B[0].c, "b"); assert.equal(B[1].c, "e"); assert.equal(B[2].c, "a"); assert.equal(B[3].c, "d"); assert.equal(B[4].c, "c"); assert.equal(B[5].c, "f"); }); }); describe(".select(b)", () => { const b = sourceArrayEnumerable.select(e => e.b); describe(".distinct()", () => { const d = b.distinct(); describe(".orderBy()", () => { it("should be 1,2,3", () => { const s = d.orderBy(); assert.equal(s.count(), 3); assert.equal(s.sum(), 6); assert.equal(s.elementAt(0), 1); assert.equal(s.elementAt(1), 2); assert.equal(s.elementAt(2), 3); }); }); describe(".orderByDescending()", () => { it("should be 1,2,3", () => { const s = d.orderByDescending(); assert.equal(s.count(), 3); assert.equal(s.sum(), 6); assert.equal(s.elementAt(0), 3); assert.equal(s.elementAt(1), 2); assert.equal(s.elementAt(2), 1); }); }); }); describe(".distinctUntilChanged()", () => { it("should be as expected", () => { assert.equal(b.distinctUntilChanged().toJoinedString(), "213213"); assert.equal(b.distinctUntilChanged(v => Math.max(v, 2)).toJoinedString(), "2323"); assert.equal(b.distinctUntilChanged(v => Math.min(v, 2)).toJoinedString(), "21313"); assert.equal(b.orderBy().distinctUntilChanged().toJoinedString(), "123"); }); }); }); describe(".groupBy(selector)", () => { it("should group by key provided by the selector", () => { const A_distinct = sourceArrayEnumerable .select(o => o.a).distinct(); const A = sourceArrayEnumerable .groupBy(o => o.a); assert.equal(A_distinct.count(), A.count(), "Number of groups should match distinct values."); const B = sourceArrayEnumerable .groupBy(o => o.b); const C = sourceArrayEnumerable .groupBy(o => o.b, <any>null, <any>Functions.Identity); const D = sourceArrayEnumerable .groupBy(o => o.b, Functions.Identity, <any>Functions.Identity); assert.ok(B.first().sequenceEqual(C.first())); assert.ok(C.first().sequenceEqual(D.first())); const B_distinct = sourceArrayEnumerable .select(o => o.b).distinct(); assert.equal(B_distinct.count(), B.count(), "Number of groups should match distinct values."); const COMPANY_A = "Microsoft", COMPANY_B = "Hell Corp."; const objArray = [ {Name: "John", Id: 0, Salary: 1300.00, Company: COMPANY_A}, {Name: "Peter", Id: 1, Salary: 4800.50, Company: COMPANY_A}, {Name: "Sandra", Id: 2, Salary: 999.99, Company: COMPANY_A}, {Name: "Me", Id: 3, Salary: 1000000000.00, Company: COMPANY_B} ]; const groups = Enumerable(objArray).groupBy(x => x.Company); const companies = groups.select(x => x.key).toArray(); assert.equal(companies.length, 2, "2 groups expected."); assert.ok(contains(companies, COMPANY_A), "Expect " + COMPANY_A); assert.ok(contains(companies, COMPANY_B), "Expect " + COMPANY_B); const group_A = groups.where(g => g.key==COMPANY_A).single(); const group_B = groups.where(g => g.key==COMPANY_B).single(); assert.equal(group_A.count(), 3, "Expected count of 3."); assert.equal(group_A.sum(x => x.Salary), 7100.49, "Expected sum to be correct."); assert.equal(group_B.count(), 1, "Expected count of 1."); assert.equal(group_B.sum(x => x.Salary), 1000000000.00, "Expected sum to be correct."); }); }); describe(".take(count)", () => { it("count should match number taken", () => { const e = sourceArrayEnumerable.take(2); assert.equal(e.count(), 2); }); }); describe(".takeWhile(predicate)", () => { it("should take while predicate returns true", () => { const e = sourceArrayEnumerable.takeWhile(v => v.a==1); assert.equal(e.count(), 3, "count should match number taken"); }); }); describe(".takeUntil(predicate,includeUntil)", () => { it("should take until predicate returns true", () => { const e = sourceArrayEnumerable.takeUntil(v => v.a==2); assert.equal(e.count(), 3, "count should match number taken"); }); it("should take until predicate returns true and include value matched", () => { const e = sourceArrayEnumerable.takeUntil(v => v.a==2, true); assert.equal(e.count(), 4, "count should match number taken"); assert.equal(e.last().c, "d"); }); }); describe(".takeExceptLast(count)", () => { it("should take the first ones minus the last", () => { const test = (s:LinqEnumerable<TestItem>) => { let e = s.takeExceptLast(2); assert.equal(e.count(), 4); assert.equal(e.count(), 4, "count should match number taken"); assert.equal(e.last().c, "d"); e = s.takeExceptLast(); assert.equal(e.count(), 5); assert.equal(e.count(), 5, "count should match number taken"); assert.equal(e.last().c, "e"); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); }); // Inverse of takeExceptLast describe(".skipToLast(count)", () => { it("should take the last items based on the count", () => { const test = (s:LinqEnumerable<TestItem>) => { let e = s.skipToLast(2); assert.equal(e.count(), 2, "count should match number taken"); assert.equal(e.first().c, "e"); assert.equal(e.last().c, "f"); e = s.skipToLast(0); assert.equal(e.count(), 0); e = s.skipToLast(Infinity); assert.equal(e.count(), 6); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); }); describe(".skip(count)", () => { it("count should match total less skipped", () => { const test = (s:LinqEnumerable<TestItem>) => { const e = s.skip(2); assert.equal(e.count(), 4); assert.equal(e.first().c, "c"); assert.equal(e.last().c, "f"); }; test(sourceArrayEnumerable); test(sourceEnumerable); assert.equal(sourceArrayEnumerable.skip(0), sourceArrayEnumerable) }); }); describe(".skipWhile(predicate)", () => { it("should skip while predicate returns true", () => { const e = sourceArrayEnumerable.skipWhile(v => v.a==1); assert.equal(e.count(), 3, "count should match number taken"); assert.equal(e.first().c, "d"); assert.equal(e.last().c, "f"); }); }); describe(".select(selector)", () => { it("should use appropriate selection mechanism", () => { const test = (s:LinqEnumerable<TestItem>) => { const e = s.select(e => e.c); assert.equal(e.count(), 6); assert.equal(e.first(), "a"); assert.equal(e.last(), "f"); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); it("should use appropriate selection mechanism", () => { const test = (s:LinqEnumerable<TestItem>) => { const e = s.select((e, i) => i); assert.equal(e.count(), 6); assert.equal(e.first(), 0); assert.equal(e.last(), 5); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); }); describe(".shuffle()", () => { it("should randomize the enumerable", () => { const e = sourceArrayEnumerable.shuffle(); assert.equal(e.count(v => v.a==1), 3); e.dispose(); assert.throws(() => e.count()); }); }); describe(".every(predicate)", () => { it("should determine if every element matches the criteria", () => { const test = (s:LinqEnumerable<TestItem>) => { assert.ok(!s.every(v => v.a==1)); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); }); describe(".any(predicate)", () => { it("should determine if every element matches the criteria", () => { const test = (s:LinqEnumerable<TestItem>) => { assert.ok(s.some(v => v.a==1)); assert.ok(!s.isEmpty()); }; test(sourceArrayEnumerable); test(sourceEnumerable); }); }); describe(".empty()", () => { const source = Enumerable.empty(); describe(".singleOrDefault()", () => { it("should be defaulted", () => { assert.equal(source.singleOrDefault(), null); assert.equal(source.singleOrDefault(-1), -1); }); }); describe(".single()", () => { it("should throw", () => { assert.throws(() => { source.single(); }); }); }); describe(".first()", () => { it("should throw", () => { assert.throws(() => { source.first(); }); }); }); describe(".firstOrDefault()", () => { it("should be defaulted", () => { assert.equal(source.firstOrDefault(), null); }); }); describe(".last()", () => { it("should throw", () => { assert.throws(() => { source.last(); }); }); }); describe(".lastOrDefault()", () => { it("should be defaulted", () => { assert.equal(source.lastOrDefault(), null); const d = 1; assert.equal(source.lastOrDefault(d), d); }); }); }); describe(".last()", () => { it("should match last", () => { assert.equal(sourceArrayEnumerable.last().c, "f"); }); it("should throw", () => { assert.throws(() => Enumerable([]).last()); }); }); describe(".lastOrDefault()", () => { it("should match last", () => { assert.equal(sourceArrayEnumerable.lastOrDefault()!.c, "f"); }); it("should be defaulted", () => { assert.equal(Enumerable<string>([]).lastOrDefault("f"), "f"); }); }); describe(".from(x)", () => { it("should throw if not enumerable", () => { assert.throws(() => Enumerable(<any>1)); }); }); describe(".fromAny(x,default)", () => { it("should return the default if not enumerable", () => { assert.equal(Enumerable.fromAny(1), null); }); }); describe(".fromAny(x,default)", () => { it("should return an enumerable from an enumerable", () => { assert.ok(Enumerable.fromAny(sourceArrayEnumerable) instanceof InfiniteLinqEnumerable); }); it("should return an enumerable from an array", () => { assert.ok(Enumerable.fromAny(source) instanceof InfiniteLinqEnumerable); }); it("should return an enumerable from an IEnumerable", () => { const e = Enumerable.fromAny({getEnumerator: () => { return EmptyEnumerator; }}); e!.getEnumerator(); assert.ok(e instanceof InfiniteLinqEnumerable); }); }); describe(".from([1])", () => { let source = new LinqEnumerable(() => Enumerable([1]).getEnumerator()); describe(".singleOrDefault()", () => { it("should return single value", () => { assert.equal(source.single(), 1); }); }); describe(".singleOrDefault()", () => { it("should return single value", () => { assert.equal(source.singleOrDefault(), 1); }); }); describe(".elementAt(x)", () => { it("should throw if no more", () => { assert.throws(() => source.elementAt(2)); }); }); describe(".elementAtOrDefault (x)", () => { it("should be defaulted", () => { assert.equal(source.elementAtOrDefault(2, -1), -1); assert.equal(source.elementAtOrDefault(2), null); }); it("should throw", () => { assert.throws(() => {source.elementAtOrDefault(NaN)}); assert.throws(() => {source.elementAtOrDefault(-1)}); assert.throws(() => {source.elementAtOrDefault(Infinity)}); }); }); }); describe(".elementAt(x)", () => { it("should return the indexed element", () => { assert.equal(sourceEnumerable.elementAt(2), source[2]); assert.equal(sourceArrayEnumerable.elementAt(2), source[2]); }); it("should throw", () => { assert.throws(() => sourceArrayEnumerable.elementAt(-1)); }); }); describe(".elementAtOrDefault (x)", () => { it("should return the indexed element", () => { assert.equal(sourceEnumerable.elementAtOrDefault(2), source[2]); assert.equal(sourceArrayEnumerable.elementAtOrDefault(2), source[2]); const d = {}; assert.equal(sourceArrayEnumerable.elementAtOrDefault(10, <any>d), d); }); it("should throw", () => { assert.throws(() => sourceArrayEnumerable.elementAtOrDefault(-1)); }); }); describe(".min()", () => { it("should return the minimum of the selected", () => { assert.equal(sourceArrayEnumerable.select(e => e.b).min(), 1); assert.equal(sourceArrayEnumerable.select(e => e.c).min(), "a"); }); }); describe(".max()", () => { it("should return the maximum of the selected", () => { assert.equal(sourceArrayEnumerable.select(e => e.b).max(), 3); assert.equal(sourceArrayEnumerable.select(e => e.c).max(), "f"); }); }); describe(".minBy(selector)", () => { it("should return the minimum of the selected", () => { assert.equal(sourceArrayEnumerable.minBy(e => e.b)!.b, 1); assert.equal(sourceArrayEnumerable.minBy(e => e.c)!.c, "a"); assert.equal(sourceArrayEnumerable.select(e => e.b).minBy(), 1); assert.equal(sourceArrayEnumerable.select(e => e.c).minBy(), "a"); }); }); describe(".maxBy(selector)", () => { it("should return the maximum of the selected", () => { assert.equal(sourceArrayEnumerable.maxBy(e => e.b)!.b, 3); assert.equal(sourceArrayEnumerable.maxBy(e => e.c)!.c, "f"); assert.equal(sourceArrayEnumerable.select(e => e.b).maxBy(), 3); assert.equal(sourceArrayEnumerable.select(e => e.c).maxBy(), "f"); }); }); describe(".concat(...)", () => { it("should remain the same", () => { assert.equal(sourceArrayEnumerable.merge(<any>null).count(), 6); assert.equal(sourceArrayEnumerable.merge([]).count(), 6); }); it("should combine two into one", () => { assert.equal(sourceArrayEnumerable.concat(sourceArrayEnumerable).count(), 12); }); }); describe(".selectMany(...)", () => { it("should select the sub values", () => { function test(values:LinqEnumerable<string>) { assert.equal(values.count(), 25); assert.equal(values.toJoinedString(), sourceManyFlat); } const split:(s:string)=>string[] = s => s ? s.split(",") : []; const sm:(s:string, e:string)=>string = (c, e) => e; const a = sourceMany.selectMany(split); test(a); const b = sourceMany.selectMany(split, sm); test(b); assert.equal(Enumerable(<string[]>[]).selectMany(split).count(), 0); const iSource = Enumerable.toInfinity().selectMany(s => repeat("" + s, s)); assert.equal(iSource.take(10).toJoinedString(), "1223334444"); let s = sourceMany.select(s => s.length); s.dispose(); assert.throws(() => s.toArray()); }); }); describe(".traverseBreadthFirst()", () => { it("walk the tree in proper order", () => { const tree = sourceEnumerable .traverseBreadthFirst(e => e.children), c = tree.select(e => e.c); assert.equal(c.elementAt(2), "c"); assert.equal(c.elementAt(6), "a"); assert.equal(c.count(), 12); assert.equal(Enumerable.empty<TestItem>().traverseBreadthFirst( e => e.children, Functions.Identity).count(), 0); }); }); describe(".traverseDepthFirst()", () => { it("walk the tree in proper order", () => { const tree = sourceEnumerable .traverseDepthFirst(e => e.children), c = tree.select(e => e.c); assert.equal(c.elementAt(2), "a"); assert.equal(c.elementAt(6), "c"); assert.equal(c.count(), 12); assert.equal(Enumerable.empty<TestItem>().traverseDepthFirst( e => e.children, Functions.Identity).count(), 0); }); }); describe(".flatten()", () => { it("should convert deep enumerable to flat one", () => { assert.equal( sourceMany .choose() .select(s => s.split(',')) .concat([["z"]]) .flatten() .toJoinedString(), sourceManyFlat + "z"); }); }); describe(".ofType(type)", () => { const source = Enumerable(<any[]>[ 1, "a", true, [], [], 2, "b", [], false, function() {}, 3, "c", [], "d", "e", null, undefined ]); it("should select only the type requested", () => { assert.equal(source.ofType(Number).count(), 3); assert.equal(source.ofType(String).count(), 5); assert.equal(source.ofType(Boolean).count(), 2); assert.equal(source.ofType(Function).count(), 1); assert.equal(source.ofType(Array).count(), 4); }); }); describe(".buffer(size)", () => { it("should return arrays at the size provided", () => { const s2 = sourceEnumerable.buffer(2); assert.equal(s2.first().length, 2); assert.equal(s2.count(), 3); }); it("should throw for invalid sizes", () => { assert.throws(() => sourceEnumerable.buffer(-1)); assert.throws(() => sourceEnumerable.buffer(Infinity)); }); }); describe(".share()", () => { it("should share an enumerator", () => { const s = sourceEnumerable.select(e => e.c).share(); const e1 = s.getEnumerator(); const e2 = s.getEnumerator(); e1.moveNext(); assert.equal(e1.current, "a"); assert.equal(e2.current, "a"); e2.moveNext(); assert.equal(e1.current, "b"); assert.equal(e2.current, "b"); }); }); const mathTree = sourceEnumerable.traverseDepthFirst(e => e.children).throwWhenEmpty(), // Add throwWhenEmpty to validate safe case. mathTreeArray = mathTree.select(e => e.b).toArray(); describe(".throwWhenEmpty()", () => { assert.throws(() => { const e = Enumerable.empty<number>().throwWhenEmpty(); //noinspection JSUnusedLocalSymbols let c:number = e.max(); // Add this for a compile check. }); }); describe(".sum()", () => { it("should render the sum value", () => { const v = Procedure.sum(mathTreeArray); assert.equal(Enumerable.empty().sum(), 0); assert.equal(mathTree.select(e => e.b).sum(), v); assert.equal(mathTree.select(e => e.b).concat([Infinity, -Infinity]).sum(), v); assert.equal(mathTree.select(e => e.b).concat([ Infinity, Infinity, -Infinity ]).sum(), Infinity); assert.equal(mathTree.select(e => e.b).concat([ Infinity, -Infinity, -Infinity ]).sum(), -Infinity); assert.ok(isNaN(mathTree.select(e => e.b).concat([NaN]).sum())); assert.equal(mathTree.sum(e => e.b), v); }); }); describe(".product()", () => { it("should render the product value", () => { const v = Procedure.product(mathTreeArray); assert.equal(mathTree.select(e => e.b).product(), v); assert.ok(isNaN(mathTree.select(e => e.b).concat([NaN]).product())); assert.equal(mathTree.select(e => e.b).concat([0]).product(), 0); assert.equal(mathTree.product(e => e.b), v); }); }); describe(".quotient()", () => { it("should render the quotient value", () => { const v = Procedure.quotient(mathTreeArray); assert.equal(mathTree.select(e => e.b).quotient(), v); assert.ok(isNaN(mathTree.select(e => e.b).concat([NaN]).quotient())); assert.ok(isNaN(mathTree.select(e => e.b).take(1).quotient())); assert.equal(mathTree.quotient(e => e.b), v); }); }); describe(".average()", () => { it("should render the average value", () => { //noinspection JSUnusedLocalSymbols let tree = sourceEnumerable .traverseDepthFirst(e => e.children); const v = Procedure.average(mathTreeArray); assert.equal(mathTree.select(e => e.b).average(), v); assert.ok(isNaN(mathTree.select(e => e.b).concat([NaN]).average())); assert.equal(mathTree.average(e => e.b), v); }); }); describe(".weave(enumerables)", () => { it("should weave in order when only 1", () => { const s = Object.freeze([1, 2, 3, 4, 5, 6, 7]); const r = Enumerable.weave([s]); assert.equal(r.count(), 7); assert.equal(r.toJoinedString(), "1234567"); }); const source = Object.freeze([ ["a", "d"], ["b", "e", "g", "i"], ["c", "f", "h"] ]); it("should weave in order", () => { let w = Enumerable.weave(source); assert.equal(w.count(), 9); assert.equal(w.toJoinedString(), "abcdefghi"); }); it("should weave enumerable in order", () => { let w = Enumerable.weave(Enumerable.from(source)); assert.equal(w.count(), 9); assert.equal(w.toJoinedString(), "abcdefghi"); }); it("should throw", () => { assert.throws(() => Enumerable.weave(<any>null)); }); }); describe(".takeExceptLast(n)", () => { it("should stop return results when n away from end of source.", () => { const r = Enumerable([1, 2, 3, 4, 5, 6]) .skip(1) .takeExceptLast(2) .toArray(); assert.equal(r[0], 2); assert.equal(r[1], 3); assert.equal(r[2], 4); }) }); describe("Supported Enumerables", () => { const source = [1, 2, 3, 4, 5, 6]; it("Array", () => { assert.doesNotThrow(()=>{ let i: LinqEnumerable<number> = Enumerable.from(source); }); }); it("List", () => { assert.doesNotThrow(()=>{ let i: LinqEnumerable<number> = Enumerable.from(new List<number>()); }); }); it("Lambda", () => { assert.doesNotThrow(()=>{ let i: InfiniteLinqEnumerable<number> = Enumerable.from(()=>1); }); }); });
the_stack
import * as React from 'react'; import { Spin, Tabs, Descriptions, Divider } from 'antd'; import { ILogCollectTaskDetail, IKeyValue, IDirectoryLogCollectPath } from '../../interface/collect'; import { timeFormat } from '../../constants/time'; import { collectModeMap, oldDataFilterMap, hostRangeMap, logSliceRuleMap, suffixMatchMap, logFilter, logFilterType, limitType } from '../../constants/common'; import { renderTooltip } from '../../component/CustomComponent'; import { setLimitUnit } from '../../lib/utils'; import moment from 'moment'; import './index.less'; const { TabPane } = Tabs; const { Item } = Descriptions; interface IAcquisitionConfiguration { loading: boolean; detail: ILogCollectTaskDetail; } export class AcquisitionConfiguration extends React.Component<IAcquisitionConfiguration> { public renderCollectObj = (detail: ILogCollectTaskDetail) => { const labelStyle: any = { fontWeight: 'bold', } const cataFile = !!detail?.directoryLogCollectPathList?.length; const cataLog = [] as IDirectoryLogCollectPath[]; const log = cataFile ? cataLog : detail?.fileLogCollectPathList as any; const collectDelay = (detail?.collectDelayThresholdMs || 0) / 60 / 1000; return (<div className='agentConfigInfo'> <Descriptions column={2} title={<h3 style={{ fontSize: '14px', padding: '10px 0', borderBottom: '1px solid #dbe0e4' }}>采集对象配置</h3>}> <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>采集任务名</span>}>{renderTooltip(detail?.logCollectTaskName || '-')}</Item> <Item label={<span style={labelStyle}>采集应用</span>}>{renderTooltip(detail?.services[0]?.servicename || '-')}</Item> </Descriptions> <div className="descriptionsBox"> <h3 style={{ padding: '30px 0 10px', fontSize: '14px', borderBottom: '1px solid #dbe0e4' }}>采集日志配置</h3> <div className='collectLogConfig'> {log?.map((ele: any, index: number) => { return <Descriptions key={index} column={2}> {/* {index > 0 && <Divider />} */} <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>日志路径</span>}>{renderTooltip(ele?.path || '-', 60)}</Item> <Item label={<span style={labelStyle}>采集文件后缀匹配样式</span>}>{detail?.fileNameSuffixMatchRule?.suffixMatchRegular || '-'}</Item> <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>日志切片规则</span>}>{`左起第${detail?.logContentSliceRule?.sliceTimestampPrefixStringIndex || 0}个匹配 ${detail?.logContentSliceRule?.sliceTimestampPrefixString || ''} ${detail?.logContentSliceRule?.sliceTimestampFormat || ''}`}</Item> </Descriptions> })} </div> </div> <Descriptions column={2} title={<h3 style={{ fontSize: '14px', padding: '10px 0', borderBottom: '1px solid #dbe0e4' }}>接收端配置与监控</h3>}> <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>Kafka集群</span>}>{renderTooltip(detail?.receiver?.kafkaClusterName || '-', 60) || '-'}</Item> <Item label={<span style={labelStyle}>生产端属性</span>}>{detail.kafkaProducerConfiguration || '-'}</Item> <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>Topic</span>}>{renderTooltip(detail?.sendTopic || '-', 60)}</Item> <Item label={<span style={labelStyle}>采集延迟监控</span>}>{collectDelay ? `该任务下Agent客户端延迟超过 ${collectDelay} 分钟,则视为异常` : '关闭'}</Item> <Item className='agentConfigInfoLeft' label={<span style={labelStyle}>任务保障等级</span>}>{limitType[detail?.limitPriority] || "-"}</Item> <Item label={<span style={labelStyle}>配置信息</span>}><pre>{detail?.advancedConfigurationJsonString || '-'}</pre></Item> </Descriptions> {/* <Descriptions className='mt-10'> <Item label="采集任务名">{renderTooltip(detail?.logCollectTaskName)}</Item> <Item label="采集应用">{renderTooltip(detail?.services[0]?.servicename)}</Item> <Item label="采集模式">{collectModeMap[detail?.logCollectTaskType]}</Item> {detail?.logCollectTaskType === 0 && <Item label="历史数据过滤">{oldDataFilterMap[detail?.oldDataFilterType]}</Item>} {(detail?.logCollectTaskType === 0 && detail?.oldDataFilterType !== 0) || detail?.logCollectTaskType !== 0 ? <Item label="采集开始时间">{moment(detail?.collectStartBusinessTime).format(timeFormat)}</Item> : ''} {detail?.logCollectTaskType !== 0 && <Item label="采集结束时间">{moment(detail?.collectEndBusinessTime).format(timeFormat)}</Item>} <Item label="主机范围">{hostRangeMap[detail?.hostFilterRuleVO?.needHostFilterRule]}</Item> {detail?.hostFilterRuleVO?.needHostFilterRule === 1 && <> {detail?.hostFilterRuleVO?.filterSQL ? <> <Item label="主机白名单">SQL匹配</Item> <Item label="SQL匹配">{detail?.hostFilterRuleVO?.filterSQL}</Item> </> : <> <Item label="主机白名单">主机名</Item> <Item label="主机名">{detail?.hostFilterRuleVO?.hostNames}</Item> </>} </>} </Descriptions> */} {/* <Descriptions column={1}> <Item label="采集任务描述">{detail?.logCollectTaskRemark}</Item> </Descriptions> */} </div>) } public renderCollectLog = (detail: ILogCollectTaskDetail) => { const cataFile = !!detail?.directoryLogCollectPathList?.length; const cataLog = [] as IDirectoryLogCollectPath[]; cataLog?.push(detail?.directoryLogCollectPathList[0]); const log = cataFile ? cataLog : detail?.fileLogCollectPathList as any; const paths = detail?.directoryLogCollectPathList?.map(ele => ele.path); return (<> {log?.map((ele: any, index: number) => { const whites = ele?.filterRuleChain?.filter((ele: IKeyValue) => ele?.key === 0)?.map((ele: IKeyValue) => ele?.value) || []; const blacks = ele?.filterRuleChain?.filter((ele: IKeyValue) => ele?.key === 1)?.map((ele: IKeyValue) => ele?.value) || []; const unitText = setLimitUnit(ele?.maxBytesPerLogEvent, 2)?.flowunit === 1024 ? 'KB' : 'MB'; return (<div key={index} className='mt-10'> {index > 0 && <Divider />} <Descriptions column={2}> {/* <Item label="采集日志类型">{cataFile ? '目录型' : '文件型'}</Item> */} {/* <Item label="编码格式">{ele?.charset}</Item> */} <Item label="日志内容过滤">{logFilter[detail?.logContentFilterRuleVO?.needLogContentFilter]}</Item> {detail?.logContentFilterRuleVO?.needLogContentFilter === 1 && <> <Item label="过滤类型">{logFilterType[detail?.logContentFilterRuleVO?.logContentFilterType]}</Item> <Item label="过滤规则">{detail?.logContentFilterRuleVO?.logContentFilterExpression}</Item> </>} {!cataFile && <Item label="日志路径">{renderTooltip(ele?.path, 60)}</Item>} {cataFile ? <> <Item label="采集深度">{ele?.directoryCollectDepth}</Item> <Item label="采集文件白名单">{renderTooltip(whites[0], 60)}</Item> <Item label="采集文件黑名单">{renderTooltip(blacks[0], 60)}</Item> </> : <> {/* <Item label="文件名后缀分隔字符">{ele?.fileNameSuffixMatchRuleVO?.suffixSeparationCharacter}</Item> */} {/* <Item label="采集文件后缀匹配">{suffixMatchMap[ele?.fileNameSuffixMatchRuleVO?.suffixMatchType]}</Item> */} {ele?.fileNameSuffixMatchRuleVO?.suffixMatchType === 0 ? <Item label="固定格式匹配">{ele?.fileNameSuffixMatchRuleVO?.suffixLength}</Item> : <Item label="采集文件后缀匹配样式">{detail?.fileNameSuffixMatchRule?.suffixMatchRegular}</Item>} </>} <Item label="单机日志大小上限">{setLimitUnit(ele?.maxBytesPerLogEvent, 2)?.maxBytesPerLogEvent}{unitText}</Item> {/* <Item label="日志切片规则">{logSliceRuleMap[ele?.logSliceRuleVO?.sliceType]}</Item> */} {detail?.logContentSliceRule?.sliceType !== 0 ? <> <Item label="日志切片规则">{`左起第${detail?.logContentSliceRule?.sliceTimestampPrefixStringIndex}个匹配 ${detail?.logContentSliceRule?.sliceTimestampPrefixString} ${detail?.logContentSliceRule?.sliceTimestampFormat}`}</Item> {/* <Item label="左起第几个匹配">{detail?.logContentSliceRule?.sliceTimestampPrefixStringIndex}</Item> {detail?.logContentSliceRule?.sliceTimestampPrefixString && <Item label="切片时间戳前缀字符串">{detail?.logContentSliceRule?.sliceTimestampPrefixString}</Item>} <Item label="时间戳格式">{detail?.logContentSliceRule?.sliceTimestampFormat}</Item> */} </> : <Item label="切片正则">{ele?.logContentSliceRule?.sliceRegular}</Item>} </Descriptions> {cataFile && <Descriptions column={1}> <Item label="目录路径">{paths?.join(',')}</Item> </Descriptions>} </div>) })} </>); } public renderClientMonitor = (detail: ILogCollectTaskDetail) => { const judge = !!detail?.directoryLogCollectPathList?.length; const fdOffset = judge ? detail?.directoryLogCollectPathList[0]?.fdOffsetExpirationTimeMs : detail?.fileLogCollectPathList[0]?.fdOffsetExpirationTimeMs; const collectDelay = (detail?.fileLogCollectPathList[0]?.collectDelayThresholdMs || 0) / 60 / 1000; return (<> <Descriptions column={1} className='mt-10'> {/* <Item label="客户端offset(采集位点记录)清理">超过 {fdOffset} 天无数据写入,则在Agent客户端删除该文件的offset</Item> */} {!judge && <Item label="采集延迟监控">该任务下Agent客户端延迟超过 {collectDelay} 分钟,则视为异常 注:仅支持对按业务时间顺序进行输出的日志进行延迟监控</Item>} {/* {detail?.logCollectTaskType === 0 && <Item label="采集完成时间限制">该任务超过 {detail?.logCollectTaskExecuteTimeoutMs} 分钟未完成,则视为异常</Item>} */} <Item label="任务保障等级">{limitType[detail?.limitPriority]}</Item> </Descriptions> </>) } public renderReceiveEnd = (detail: ILogCollectTaskDetail) => { const collectDelay = (detail?.collectDelayThresholdMs || 0) / 60 / 1000; return (<> <Descriptions column={1} className='mt-10'> <Item label="Kafka集群">{renderTooltip(detail?.receiver?.kafkaClusterName, 60)}</Item> { detail.kafkaProducerConfiguration && <Item label="生产端属性">{detail.kafkaProducerConfiguration}</Item> } <Item label="Topic">{renderTooltip(detail?.sendTopic, 60)}</Item> <Item label="采集延迟监控">该任务下Agent客户端延迟超过 {collectDelay} 分钟,则视为异常 注:仅支持对按业务时间顺序进行输出的日志进行延迟监控</Item> <Item label="任务保障等级">{limitType[detail?.limitPriority]}</Item> </Descriptions> </>) } public renderAdvancedConfig = (detail: ILogCollectTaskDetail) => { return (<> <Descriptions className='mt-10'> <Item label="高级配置信息">{detail?.advancedConfigurationJsonString}</Item> </Descriptions> </>) } public render() { const { detail, loading } = this.props; return ( <Spin spinning={loading}>{Object.keys(detail).length !== 0 && this.renderCollectObj(detail) } {/* <Tabs type='card' defaultActiveKey="object"> <TabPane tab="采集对象配置" key="object"> </TabPane> <TabPane tab="采集日志配置" key="journal"> {this.renderCollectLog(detail)} </TabPane> <TabPane tab="客户端清理与自监控" key="client"> {this.renderClientMonitor(detail)} </TabPane> <TabPane tab="接收端配置与监控" key="receive"> {this.renderReceiveEnd(detail)} </TabPane> <TabPane tab="高级配置" key="senior"> {this.renderAdvancedConfig(detail)} </TabPane> </Tabs> */}</Spin> ); } }
the_stack
import { Entity } from '../../types' import type { When, Options } from '../types' import { Easing } from '../stepper/easing' import { Morpher } from '../morpher/morpher' import { Stepper } from '../stepper/stepper' import { Timeline } from '../scheduler/timeline' import { Controller } from '../stepper/controller' import { History, Executors, PrepareMethod, RunMethod, RetargetMethod, } from './types' import { Util } from './util' export class Animator< TAnimator, TOwner extends Animator.Owner = Animator.Owner, > { public readonly id: number public readonly declarative: boolean public done = false protected enabled = true protected reseted = true protected persisted: number | boolean protected owner: TOwner protected stepper: Stepper protected timeline: Timeline | null = null protected duration: number protected times = 1 protected wait = 0 protected swing = false protected reversal = false protected currentTime = 0 protected previousStepTime = 0 protected previousStepPosition: number protected readonly history: History<TAnimator> = {} protected readonly executors: Executors<TAnimator> = [] protected readonly callbacks: { [Key in Animator.EventNames]: any[] } = { start: [], step: [], finished: [], } constructor() constructor(duration: number) constructor(stepper: Stepper) constructor(options: number | Stepper = Util.defaults.duration) { this.id = Util.generateId() const opts = typeof options === 'function' ? new Controller(options) : options this.stepper = opts instanceof Controller ? opts : new Easing() this.declarative = opts instanceof Controller this.persisted = this.declarative ? true : 0 this.duration = typeof opts === 'number' ? opts : 0 } active(): boolean active(enabled: boolean): this active(enabled?: boolean) { if (enabled == null) { return this.enabled } this.enabled = enabled return this } ease(): Stepper ease(stepper: Stepper): this ease(stepper?: Stepper) { if (stepper == null) { return this.stepper } this.stepper = stepper return this } persist(): number /** * Make this runner persist on the timeline forever (true) or for a specific * time. Usually a runner is deleted after execution to clean up memory. */ persist(dt: number): this persist(forever: boolean): this persist(dtOrForever?: number | boolean) { if (dtOrForever == null) { return this.persisted } this.persisted = dtOrForever return this } master(): TOwner master(owner: TOwner): this master(owner?: TOwner) { if (owner == null) { return this.owner } this.owner = owner return this } scheduler(): Timeline scheduler(timeline: Timeline | null): this scheduler(timeline?: Timeline | null) { if (typeof timeline === 'undefined') { return this.timeline } this.timeline = timeline return this } /** * Set the runner back to zero time and all animations with it */ reset() { if (this.reseted) { return this } this.time(0) this.reseted = true return this } /** * Returns the duration the runner will run */ quantity() { return this.times * (this.wait + this.duration) - this.wait } schedule(delay: number, when: When): this schedule(timeline: Timeline, delay: number, when: When): this schedule(timeline: Timeline | number, delay: When | number, when?: When) { if (typeof timeline === 'number') { when = delay as When // eslint-disable-line delay = timeline // eslint-disable-line timeline = this.timeline! // eslint-disable-line } if (timeline == null) { throw Error('Runner cannot be scheduled without timeline') } const scheduler = timeline as Timeline scheduler.schedule(this, delay as number, when) return this } unschedule() { const timeline = this.timeline if (timeline) { timeline.unschedule(this) } return this } loop(times?: number | true, swing?: boolean, wait?: number): this loop(options: { times?: number | true; swing?: boolean; wait?: number }): this loop( times?: | { times?: number | true; swing?: boolean; wait?: number } | number | true, swing?: boolean, wait?: number, ) { const o = typeof times === 'object' ? times : { times, swing, wait } this.times = o.times == null || o.times === true ? Infinity : o.times this.swing = o.swing || false this.wait = o.wait || 0 return this } reverse(reverse?: boolean) { this.reversal = reverse == null ? !this.reversal : reverse return this } time(): number time(time: number): this time(time?: number) { if (time == null) { return this.currentTime } const delta = time - this.currentTime this.step(delta) return this } /** * Steps the runner to its finished state. */ finish() { return this.step(Infinity) } /** * Returns the current position of the runner including the wait times * (between 0 and 1). */ progress(): number /** * Sets the current position of the runner including the wait times * (between 0 and 1). */ progress(p: number): this progress(p?: number) { if (p == null) { return Math.min(1, this.currentTime / this.quantity()) } return this.time(p * this.quantity()) } /** * Get the current iteration of the runner. */ loops(): number /** * Jump to a specific iteration of the runner. * e.g. 3.5 for 4th loop half way through */ loops(p: number): this loops(p?: number) { const duration = this.duration + this.wait if (p == null) { const finishedCount = Math.floor(this.currentTime / duration) const delta = this.currentTime - finishedCount * duration const position = delta / this.duration return Math.min(finishedCount + position, this.times) } const whole = Math.floor(p) const partial = p % 1 const total = duration * whole + this.duration * partial return this.time(total) } /** * Returns the current position of the runner ignoring the wait times * (between 0 and 1). */ position(): number /** * Sets the current position of the runner ignoring the wait times * (between 0 and 1). */ position(p: number): this position(p?: number) { const current = this.currentTime const w = this.wait const t = this.times const s = this.swing const r = this.reversal const d = this.duration if (p == null) { /* This function converts a time to a position in the range [0, 1] The full explanation can be found in this desmos demonstration https://www.desmos.com/calculator/u4fbavgche The logic is slightly simplified here because we can use booleans */ // Figure out the value without thinking about the start or end time const f = (x: number) => { const swinging = (s ? 1 : 0) * Math.floor((x % (2 * (w + d))) / (w + d)) const backwards = +((swinging && !r) || (!swinging && r)) const uncliped = ((backwards ? -1 : 1) * (x % (w + d))) / d + backwards const clipped = Math.max(Math.min(uncliped, 1), 0) return clipped } // Figure out the value by incorporating the start time const endTime = t * (w + d) - w const position = current <= 0 ? Math.round(f(1e-5)) : current < endTime ? f(current) : Math.round(f(endTime - 1e-5)) return position } const finishedCount = Math.floor(this.loops()) const swingForward = s && finishedCount % 2 === 0 const forwards = (swingForward && !r) || (r && swingForward) const position = finishedCount + (forwards ? p : 1 - p) return this.loops(position) } animate(options: Options): this animate(duration?: number, delay?: number, when?: When): this animate(duration?: Options | number, delay?: number, when?: When) { const options = Util.sanitise(duration, delay, when) const Ctor = this.constructor as new (duration: number) => Animator< TAnimator, TOwner > const animator = new Ctor(options.duration) if (this.timeline) { animator.scheduler(this.timeline) } if (this.owner) { animator.master(this.owner) } return animator.loop(options).schedule(options.delay, options.when) } delay(delay: number) { return this.animate(0, delay) } /** * Step the runner by a certain time. */ step(delta = 16) { if (!this.active()) { return this } this.currentTime += delta // Figure out if we need to run the stepper in this frame const position = this.position() const running = this.previousStepPosition !== position && this.currentTime >= 0 this.previousStepPosition = position const quantity = this.quantity() const justStarted = this.previousStepTime <= 0 && this.currentTime > 0 const justFinished = this.previousStepTime < quantity && this.currentTime >= quantity this.previousStepTime = this.currentTime const callback = (cache: any[]) => { for (let i = 0, l = cache.length; i < l; i += 1) { const handler = cache[i] as Animator.EventHandler<TAnimator> const context = cache[i + 1] if (handler) { const result = handler.call(context, this) if (result === false) { return false } } } } if (justStarted) { if (callback(this.callbacks.start) === false) { return this } } this.reseted = false // Work out if the runner is finished set the done flag here so animations // know, that they are running in the last step (this is good for // transformations which can be merged) const declared = this.declarative this.done = !declared && !justFinished && this.currentTime >= quantity let converged = false if (running || declared) { this.prepare(running) converged = this.run(declared ? delta : position) if (callback(this.callbacks.step) === false) { return this } } // correct the done flag here // declaritive animations itself know when they converged this.done = this.done || (converged && declared) if (justFinished) { if (callback(this.callbacks.finished) === false) { return this } } return this } on( event: Animator.EventNames, callback: Animator.EventHandler<TAnimator>, context?: Entity, ) { const cache = this.callbacks[event] cache.push(callback, context) return this } off( event: Animator.EventNames, callback?: Animator.EventHandler<TAnimator>, context?: Entity, ) { const cache = this.callbacks[event] if (callback == null && context == null) { this.callbacks[event] = [] } else { for (let i = cache.length - 1; i >= 0; i -= 2) { if ( (callback == null || cache[i - 1] === callback) && (context == null || cache[i] === context) ) { cache.splice(i - 1, 2) } } } return this } protected queue<TTarget, TExtra = any>( prepare?: PrepareMethod<TAnimator> | null, run?: RunMethod<TAnimator> | null, retarget?: RetargetMethod<TAnimator, TTarget, TExtra> | null, isTransform?: boolean, ) { this.executors.push({ isTransform, retarget, prepare: prepare || (() => undefined), run: run || (() => undefined), ready: false, finished: false, }) if (this.timeline) { this.timeline.peek() } return this } protected prepare(running: boolean) { if (running || this.declarative) { for (let i = 0, l = this.executors.length; i < l; i += 1) { const exe = this.executors[i] const needInit = this.declarative || (!exe.ready && running) if (needInit && !exe.finished) { exe.prepare.call(this, this) exe.ready = true } } } } protected run(positionOrDelta: number) { let allfinished = true for (let i = 0, l = this.executors.length; i < l; i += 1) { const exe = this.executors[i] const converged = exe.run.call(this, this, positionOrDelta) exe.finished = exe.finished || converged === true allfinished = allfinished && exe.finished } return allfinished } protected remember(method: string, morpher: Morpher<any, any, any>) { // Save the morpher to the morpher list so that we can retarget it later this.history[method] = { morpher, executor: this.executors[this.executors.length - 1], } // We have to resume the timeline in case a controller // is already done without beeing ever run // This can happen when e.g. this is done: // anim = el.animate(new SVG.Spring) // and later // anim.move(...) if (this.declarative) { if (this.timeline) { this.timeline.play() } } } protected retarget<TTarget, TExtra>( method: string, target: TTarget, extra?: TExtra, ) { if (this.history[method]) { const { morpher, executor } = this.history[method] // If the previous executor wasn't even prepared, drop it. if (!executor.ready) { const index = this.executors.indexOf(executor) this.executors.splice(index, 1) return false } if (executor.retarget) { // For the case of transformations, we use the special // retarget function which has access to the outer scope executor.retarget.call(this, this, target, extra) } else { morpher.to(target) } executor.finished = false if (this.timeline) { this.timeline.play() } return true } return false } } export namespace Animator { export type Owner = Record<string, any> export type EventNames = 'start' | 'step' | 'finished' export type EventHandler<T> = (animator: T) => any }
the_stack
import {Plugin, Series} from 'uplot'; import {CursorOptions} from '../cursor/cursor'; import placement from './placement'; import Yagr from '../../index'; import {DataSeries, ProcessingInterpolation, YagrPlugin} from '../../types'; import {TOOLTIP_Y_OFFSET, TOOLTIP_X_OFFSET, TOOLTIP_DEFAULT_MAX_LINES, DEFAULT_Y_SCALE} from '../../defaults'; import {findInRange, findDataIdx, findSticky} from '../../utils/common'; import {TooltipOptions, TooltipRow, TrackingOptions, ValueFormatter, TooltipSection, TooltipHandler} from './types'; import {renderTooltip} from './render'; import {getOptionValue} from './utils'; export interface TooltipState { /** Is tooltip pinned */ pinned: boolean; /** X-Coord of click to track selections and differ them from single click */ clickStartedX: null | number; /** Is tooltip visible */ visible: boolean; /** Is tooltip mounted */ mounted: boolean; /** Current focused series */ focusedSeries: null | string; } export type TooltipAction = 'init' | 'mount' | 'render' | 'show' | 'hide' | 'pin' | 'unpin' | 'destroy'; // eslint-disable-next-line complexity const findValue = ( cursor: CursorOptions, data: DataSeries, serie: Series, idx: number, interpolation?: ProcessingInterpolation, ) => { const source = Array.isArray(serie.$c) ? serie.$c : data; let value = source[idx]; if (interpolation && value === interpolation.value) { const snapTo = interpolation.snapToValues ?? 'closest'; const nonNullIdx = findDataIdx(source, serie, idx, snapTo, interpolation.value); value = source[nonNullIdx]; } else if (value === null) { const cursorSnapToValues = cursor.snapToValues ?? 'closest'; const snapTo = serie.snapToValues ?? cursorSnapToValues; const nonNullIdx = findDataIdx(source, serie, idx, snapTo, null); value = source[nonNullIdx]; } return value; }; const DEFAULT_TOOLTIP_OPTIONS = { maxLines: TOOLTIP_DEFAULT_MAX_LINES, highlight: true, sum: false, render: renderTooltip, pinable: true, sort: undefined, showIndicies: false, hideNoData: false, className: 'yagr-tooltip_default', xOffset: TOOLTIP_X_OFFSET, yOffset: TOOLTIP_Y_OFFSET, }; export type TooltipPlugin = YagrPlugin< { state: TooltipState; pin(pinState: boolean, position?: {x: number; y: number}): void; show(): void; hide(): void; updateOptions: (o: Partial<TooltipOptions>) => void; on: (event: TooltipAction, handler: TooltipHandler) => void; off: (event: TooltipAction, handler: TooltipHandler) => void; display: (props: {left: number; top: number; idx: number}) => void; }, [Partial<TooltipOptions>] >; /* * Tooltip plugin constructor. * Every charts has it's own tooltip plugin instance */ function YagrTooltipPlugin(yagr: Yagr, options: Partial<TooltipOptions> = {}): ReturnType<TooltipPlugin> { const pSettings = yagr.config.processing || {}; const handlers: Record<TooltipAction, TooltipHandler[]> = { init: [], mount: [], show: [], pin: [], unpin: [], hide: [], render: [], destroy: [], }; /* Tooltip renderer, allows to deffer rendering to avoid jerky renderings when tooltip pinned */ let renderTooltipCloses = () => {}; const defaultTooltipValueFormatter = (n: string | number | null, precision?: number) => { if (typeof n === 'string') { if (pSettings.nullValues && pSettings.nullValues.hasOwnProperty(n)) { return pSettings.nullValues[n] as string; } return '-'; } if (typeof n === 'number') { return n.toFixed( // eslint-disable-next-line no-nested-ternary typeof precision === 'number' ? precision : typeof options.precision === 'number' ? options.precision : 2, ); } return '-'; }; const opts: TooltipOptions = { ...DEFAULT_TOOLTIP_OPTIONS, tracking: yagr.config.chart.series?.type === 'area' ? 'area' : 'sticky', value: defaultTooltipValueFormatter, ...options, }; let over: HTMLDivElement; let bLeft: number; let bTop: number; let bound: HTMLElement; const tOverlay = document.createElement('div'); tOverlay.id = `${yagr.id}_tooltip`; tOverlay.className = `yagr-tooltip ${opts.className || ''}`; tOverlay.style.display = 'none'; const state: TooltipState = { mounted: true, pinned: false, visible: false, clickStartedX: null, focusedSeries: null, }; const emit = (action: TooltipAction) => { handlers[action].forEach((handler) => { handler(tOverlay, { state, actions: { pin, show, hide, }, yagr, }); }); }; emit('init'); document.body.appendChild(tOverlay); state.mounted = true; emit('mount'); function show() { const shouldEmit = !state.visible; state.visible = true; tOverlay.style.display = 'block'; shouldEmit && emit('show'); } function hide() { const shouldEmit = state.visible; state.visible = false; tOverlay.style.display = 'none'; emit('hide'); shouldEmit && emit('show'); } const checkFocus = (event: MouseEvent) => { const target = event.target as HTMLElement | null; let serieIdx: string | undefined; if (target && tOverlay.contains(target) && target.classList.contains('yagr-tooltip__item')) { serieIdx = target.dataset['series']; } const serie = serieIdx ? yagr.uplot.series[Number(serieIdx)] : null; if (serieIdx && serie) { state.focusedSeries = serieIdx; yagr.setFocus(serie.id, true); } else if (state.focusedSeries) { state.focusedSeries = null; yagr.setFocus(null, true); } }; const onMouseDown = (event: MouseEvent) => { state.clickStartedX = event.clientX; }; const detectClickOutside = (event: MouseEvent) => { const target = event.target; if (target instanceof Element) { const isClickInsideTooltip = target && tOverlay.contains(target); const isClickOnUplotOver = target && over.contains(target); if (!isClickInsideTooltip && !isClickOnUplotOver) { pin(false); hide(); } } }; function pin(pinState: boolean, position?: {x: number; y: number}) { if (position) { placement( tOverlay, { left: position.x + bLeft, top: bTop + position.y - (opts.yOffset || 0), }, 'right', { bound, xOffset: opts.xOffset, yOffset: opts.yOffset, }, ); } const list = tOverlay.querySelector('._tooltip-list') as HTMLElement; state.pinned = pinState; yagr.plugins.cursor?.pin(pinState); if (pinState) { if (!state.visible) { show(); } tOverlay.classList.add('yagr-tooltip_pinned'); if (list) { list.style.height = list?.clientHeight + 'px'; } if (opts.render === renderTooltip) { document.addEventListener('mousemove', checkFocus); document.addEventListener('mousedown', detectClickOutside); } } else { tOverlay.classList.remove('yagr-tooltip_pinned'); if (opts.render === renderTooltip) { document.removeEventListener('mousemove', checkFocus); document.removeEventListener('mousedown', detectClickOutside); } } emit(pinState ? 'pin' : 'unpin'); } const onMouseUp = (event: MouseEvent) => { if (opts.pinable && state.clickStartedX && state.clickStartedX === event.clientX) { pin(!state.pinned); show(); renderTooltipCloses(); } }; const onMouseEnter = () => { show(); }; const onMouseLeave = () => { if (!state.pinned) { hide(); } }; const interpolation = pSettings.interpolation; const stripValue = interpolation ? interpolation.value : undefined; function calcTooltip(props: {left: number; top: number; idx: number}) { const u = yagr.uplot; const {left, top, idx} = props; if (opts.show && typeof opts.show === 'function' && opts.show(yagr) === false) { hide(); return; } if ((left < 0 || top < 0) && !state.pinned) { hide(); } const {data} = u; if (data === null || idx === null || idx === undefined || top === undefined) { return; } const x = data[0][idx]; const sum: Record<string, number> = {}; const sections: Record<string, TooltipSection> = {}; const rowsBySections: Record<string, number[]> = {}; let i = 1; while (i < u.series.length) { const serie = u.series[i]; if (!serie.show) { i += 1; continue; } const scale = serie.scale || DEFAULT_Y_SCALE; rowsBySections[scale] = rowsBySections[scale] || []; rowsBySections[scale].push(i); i += 1; } const rowEntries = Object.entries(rowsBySections); rowEntries.forEach(([scale, serieIndicies]) => { sections[scale] = sections[scale] || { rows: [], }; const section = sections[scale]; const cursorValue = Number(u.posToVal(top, scale).toFixed(2)); const valueRender = getOptionValue<ValueFormatter>(opts.value, scale); for (const seriesIdx of serieIndicies) { const seriesData = u.data[seriesIdx] as DataSeries; const serie = u.series[seriesIdx]; let value = findValue(yagr.config.cursor, seriesData, serie, idx, interpolation); let dValue = value; if (typeof value === 'string') { dValue = value; value = null; } if (getOptionValue(opts.sum, scale)) { sum[scale] = sum[scale] || 0; sum[scale] += value || 0; } const realY = seriesData[idx]; const yValue = serie.$c && serie.$c[idx] === stripValue ? value : realY; if ((value === null && opts.hideNoData) || serie.showInTooltip === false) { continue; } const seriesPrecision = serie.precision ?? getOptionValue(opts.precision, scale); const displayValue = serie.formatter ? serie.formatter(dValue, serie) : valueRender(dValue, seriesPrecision); const rowData: TooltipRow = { name: serie.name, originalValue: value, value: displayValue, y: yValue, displayY: realY, color: serie.color, seriesIdx, rowIdx: section.rows.length ? section.rows[section.rows.length - 1].rowIdx + 1 : 0, }; if (serie.normalizedData) { rowData.transformed = serie.normalizedData[idx]; } if (serie._transformed) { rowData.transformed = seriesData[idx]; } section.rows.push(rowData); } if (getOptionValue(opts.highlight, scale) && section.rows.length) { const tracking = getOptionValue<TrackingOptions>(opts.tracking, scale); let activeIndex: number | null = 0; if (tracking === 'area') { activeIndex = findInRange( section, cursorValue, getOptionValue<boolean | undefined>(opts.stickToRanges, scale), ); } else if (tracking === 'sticky') { activeIndex = findSticky(section, cursorValue); } else if (typeof tracking === 'function') { activeIndex = tracking(section, cursorValue); } if (activeIndex !== null) { section.rows[activeIndex].active = true; } } const sort = getOptionValue(opts.sort, scale); if (sort) { section.rows.sort(sort); } }); const hasOneRow = Object.values(sections).some(({rows}) => rows.length > 0); if (hasOneRow) { onMouseEnter(); } else { onMouseLeave(); return; } const bbox = over.getBoundingClientRect(); bLeft = bbox.left; bTop = bbox.top; const anchor = { left: left + bLeft, top: bTop + top - (opts.yOffset || 0), }; renderTooltipCloses = () => { tOverlay.innerHTML = opts.render({ scales: Object.entries(sections).map(([scale, sec]) => { return { scale, rows: sec.rows, sum: sum[scale], }; }), options: opts, x, pinned: state.pinned, yagr, }); placement(tOverlay, anchor, 'right', { bound, xOffset: opts.xOffset, yOffset: opts.yOffset, }); emit('render'); }; if (state.pinned) { return; } renderTooltipCloses(); } const uPlotPlugin: Plugin = { hooks: { init: (u) => { over = u.root.querySelector('.u-over') as HTMLDivElement; over.addEventListener('mousedown', onMouseDown); over.addEventListener('mouseup', onMouseUp); over.addEventListener('mouseenter', onMouseEnter); over.addEventListener('mouseleave', onMouseLeave); }, setData: (u) => { if (!u.data.every(Array.isArray)) { throw new Error('Tooltip plugin applied to unconvient datalines: expected number[][]'); } }, setSize: () => { const bbox = over.getBoundingClientRect(); bLeft = bbox.left; bTop = bbox.top; bound = opts.boundClassName ? document.querySelector(opts.boundClassName) || document.body : document.body; }, setCursor: (u) => { calcTooltip(u.cursor as Parameters<typeof calcTooltip>[0]); }, destroy: () => { /** Free overlay listeners */ over.removeEventListener('mousedown', onMouseDown); over.removeEventListener('mouseup', onMouseUp); over.removeEventListener('mouseenter', onMouseEnter); over.removeEventListener('mouseleave', onMouseLeave); /** Removing tooltip on destroy */ tOverlay.remove(); state.mounted = false; emit('destroy'); }, }, }; function updateOptions(newOptions: Partial<TooltipOptions>) { Object.assign(opts, newOptions); tOverlay.className = `yagr-tooltip ${opts.className || ''}`; } function on(event: TooltipAction, handler: TooltipHandler) { handlers[event].push(handler); } function off(event: TooltipAction, handler: TooltipHandler) { handlers[event] = handlers[event].filter((h) => h !== handler); } return { state, pin, show, hide, uplot: uPlotPlugin, display: calcTooltip, updateOptions, on, off, }; } export default YagrTooltipPlugin;
the_stack
import { Component, Input, ElementRef, OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy, KeyValueDiffers, ViewChild, NgZone, Output, EventEmitter } from '@angular/core'; import { FusionChartsService } from './fusioncharts.service'; import { FusionChartsConstructor } from './fusioncharts.constructor'; import FusionChartsEvent from '../interfaces/FusionChartsEvent'; import FusionChartInstance from '../interfaces/FusionChartInstance'; import EventsList from '../events/events'; @Component({ selector: 'fusioncharts', template: ` <div attr.id="container-{{ containerId }}" style="width:100%;height:100%"> {{ placeholder }} </div> `, providers: [FusionChartsService] }) class FusionChartsComponent implements OnInit, OnChanges, DoCheck, AfterViewInit, OnDestroy { chartObj: any; @Input() placeholder: string; @Input() dataSource: any; @Input() type: string; @Input() id: string; @Input() width: string; @Input() height: string; @Input() renderAt: string; @Input() dataFormat: string; @Input() events: string; @Input() link: string; @Input() showDataLoadingMessage: boolean; @Input() showChartLoadingMessage: boolean; @Input() baseChartMessageFont: string; @Input() baseChartMessageFontSize: string; @Input() baseChartMessageColor: string; @Input() dataLoadStartMessage: string; @Input() dataLoadErrorMessage: string; @Input() dataInvalidMessage: string; @Input() dataEmptyMessage: string; @Input() typeNotSupportedMessage: string; @Input() loadMessage: string; @Input() renderErrorMessage: string; @Input() containerBackgroundColor: string; @Input() containerBackgroundOpacity: string; @Input() containerClassName: string; @Input() baseChartMessageImageHAlign: string; @Input() baseChartMessageImageVAlign: string; @Input() baseChartMessageImageAlpha: number; @Input() baseChartMessageImageScale: number; @Input() typeNotSupportedMessageImageHAlign: string; @Input() typeNotSupportedMessageImageVAlign: string; @Input() typeNotSupportedMessageImageAlpha: number; @Input() typeNotSupportedMessageImageScale: number; @Input() dataLoadErrorMessageImageHAlign: string; @Input() dataLoadErrorMessageImageVAlign: string; @Input() dataLoadErrorMessageImageAlpha: number; @Input() dataLoadErrorMessageImageScale: number; @Input() dataLoadStartMessageImageHAlign: string; @Input() dataLoadStartMessageImageVAlign: string; @Input() dataLoadStartMessageImageAlpha: number; @Input() dataLoadStartMessageImageScale: number; @Input() dataInvalidMessageImageHAlign: string; @Input() dataInvalidMessageImageVAlign: string; @Input() dataInvalidMessageImageAlpha: number; @Input() dataInvalidMessageImageScale: number; @Input() dataEmptyMessageImageHAlign: string; @Input() dataEmptyMessageImageVAlign: string; @Input() dataEmptyMessageImageAlpha: number; @Input() dataEmptyMessageImageScale: number; @Input() renderErrorMessageImageHAlign: string; @Input() renderErrorMessageImageVAlign: string; @Input() renderErrorMessageImageAlpha: number; @Input() renderErrorMessageImageScale: number; @Input() loadMessageImageHAlign: string; @Input() loadMessageImageVAlign: string; @Input() loadMessageImageAlpha: number; @Input() loadMessageImageScale: number; @Input() chartConfig: string; /** * All Events List */ private eventList: Array<string> = EventsList; /** * All events emitter */ @Output() beforeLinkedItemOpen = new EventEmitter<FusionChartsEvent>(); @Output() linkedItemOpened = new EventEmitter<FusionChartsEvent>(); @Output() beforeLinkedItemClose = new EventEmitter<FusionChartsEvent>(); @Output() linkedItemClosed = new EventEmitter<FusionChartsEvent>(); @Output() printReadyStateChange = new EventEmitter<FusionChartsEvent>(); @Output() dataLoadRequestCompleted = new EventEmitter<FusionChartsEvent>(); @Output() dataLoadError = new EventEmitter<FusionChartsEvent>(); @Output() dataLoadCancelled = new EventEmitter<FusionChartsEvent>(); @Output() dataLoadRequestCancelled = new EventEmitter<FusionChartsEvent>(); @Output() dataUpdated = new EventEmitter<FusionChartsEvent>(); @Output() dataUpdateCancelled = new EventEmitter<FusionChartsEvent>(); @Output() dataLoadRequested = new EventEmitter<FusionChartsEvent>(); @Output() beforeDataUpdate = new EventEmitter<FusionChartsEvent>(); @Output() realTimeUpdateComplete = new EventEmitter<FusionChartsEvent>(); @Output() chartCleared = new EventEmitter<FusionChartsEvent>(); @Output() slicingEnd = new EventEmitter<FusionChartsEvent>(); @Output() slicingStart = new EventEmitter<FusionChartsEvent>(); @Output() entityRollOut = new EventEmitter<FusionChartsEvent>(); @Output() entityRollOver = new EventEmitter<FusionChartsEvent>(); @Output() entityClick = new EventEmitter<FusionChartsEvent>(); @Output() connectorRollOver = new EventEmitter<FusionChartsEvent>(); @Output() connectorRollOut = new EventEmitter<FusionChartsEvent>(); @Output() connectorClick = new EventEmitter<FusionChartsEvent>(); @Output() markerRollOver = new EventEmitter<FusionChartsEvent>(); @Output() markerRollOut = new EventEmitter<FusionChartsEvent>(); @Output() markerClick = new EventEmitter<FusionChartsEvent>(); @Output() pageNavigated = new EventEmitter<FusionChartsEvent>(); @Output() rotationEnd = new EventEmitter<FusionChartsEvent>(); @Output() rotationStart = new EventEmitter<FusionChartsEvent>(); @Output() centerLabelRollover = new EventEmitter<FusionChartsEvent>(); @Output() centerLabelRollout = new EventEmitter<FusionChartsEvent>(); @Output() centerLabelClick = new EventEmitter<FusionChartsEvent>(); @Output() centerLabelChanged = new EventEmitter<FusionChartsEvent>(); @Output() chartClick = new EventEmitter<FusionChartsEvent>(); @Output() chartMouseMove = new EventEmitter<FusionChartsEvent>(); @Output() chartRollOver = new EventEmitter<FusionChartsEvent>(); @Output() chartRollOut = new EventEmitter<FusionChartsEvent>(); @Output() backgroundLoaded = new EventEmitter<FusionChartsEvent>(); @Output() backgroundLoadError = new EventEmitter<FusionChartsEvent>(); @Output() legendItemClicked = new EventEmitter<FusionChartsEvent>(); @Output() legendItemRollover = new EventEmitter<FusionChartsEvent>(); @Output() legendItemRollout = new EventEmitter<FusionChartsEvent>(); @Output() logoRollover = new EventEmitter<FusionChartsEvent>(); @Output() logoRollout = new EventEmitter<FusionChartsEvent>(); @Output() logoClick = new EventEmitter<FusionChartsEvent>(); @Output() logoLoaded = new EventEmitter<FusionChartsEvent>(); @Output() logoLoadError = new EventEmitter<FusionChartsEvent>(); @Output() beforeExport = new EventEmitter<FusionChartsEvent>(); @Output() exported = new EventEmitter<FusionChartsEvent>(); @Output() exportCancelled = new EventEmitter<FusionChartsEvent>(); @Output() beforePrint = new EventEmitter<FusionChartsEvent>(); @Output() printComplete = new EventEmitter<FusionChartsEvent>(); @Output() printCancelled = new EventEmitter<FusionChartsEvent>(); @Output() dataLabelClick = new EventEmitter<FusionChartsEvent>(); @Output() dataLabelRollOver = new EventEmitter<FusionChartsEvent>(); @Output() dataLabelRollOut = new EventEmitter<FusionChartsEvent>(); @Output() scrollStart = new EventEmitter<FusionChartsEvent>(); @Output() scrollEnd = new EventEmitter<FusionChartsEvent>(); @Output() onScroll = new EventEmitter<FusionChartsEvent>(); @Output() zoomReset = new EventEmitter<FusionChartsEvent>(); @Output() zoomedOut = new EventEmitter<FusionChartsEvent>(); @Output() zoomedIn = new EventEmitter<FusionChartsEvent>(); @Output() zoomed = new EventEmitter<FusionChartsEvent>(); @Output() zoomModeChanged = new EventEmitter<FusionChartsEvent>(); @Output() pinned = new EventEmitter<FusionChartsEvent>(); @Output() dataRestored = new EventEmitter<FusionChartsEvent>(); @Output() beforeDataSubmit = new EventEmitter<FusionChartsEvent>(); @Output() dataSubmitError = new EventEmitter<FusionChartsEvent>(); @Output() dataSubmitted = new EventEmitter<FusionChartsEvent>(); @Output() dataSubmitCancelled = new EventEmitter<FusionChartsEvent>(); @Output() chartUpdated = new EventEmitter<FusionChartsEvent>(); @Output() nodeAdded = new EventEmitter<FusionChartsEvent>(); @Output() nodeUpdated = new EventEmitter<FusionChartsEvent>(); @Output() nodeDeleted = new EventEmitter<FusionChartsEvent>(); @Output() connectorAdded = new EventEmitter<FusionChartsEvent>(); @Output() connectorUpdated = new EventEmitter<FusionChartsEvent>(); @Output() connectorDeleted = new EventEmitter<FusionChartsEvent>(); @Output() labelAdded = new EventEmitter<FusionChartsEvent>(); @Output() labelDeleted = new EventEmitter<FusionChartsEvent>(); @Output() selectionRemoved = new EventEmitter<FusionChartsEvent>(); @Output() selectionStart = new EventEmitter<FusionChartsEvent>(); @Output() selectionEnd = new EventEmitter<FusionChartsEvent>(); @Output() labelClick = new EventEmitter<FusionChartsEvent>(); @Output() labelRollOver = new EventEmitter<FusionChartsEvent>(); @Output() labelRollOut = new EventEmitter<FusionChartsEvent>(); @Output() labelDragStart = new EventEmitter<FusionChartsEvent>(); @Output() labelDragEnd = new EventEmitter<FusionChartsEvent>(); @Output() dataplotDragStart = new EventEmitter<FusionChartsEvent>(); @Output() dataplotDragEnd = new EventEmitter<FusionChartsEvent>(); @Output() processClick = new EventEmitter<FusionChartsEvent>(); @Output() processRollOver = new EventEmitter<FusionChartsEvent>(); @Output() processRollOut = new EventEmitter<FusionChartsEvent>(); @Output() categoryClick = new EventEmitter<FusionChartsEvent>(); @Output() categoryRollOver = new EventEmitter<FusionChartsEvent>(); @Output() categoryRollOut = new EventEmitter<FusionChartsEvent>(); @Output() milestoneClick = new EventEmitter<FusionChartsEvent>(); @Output() milestoneRollOver = new EventEmitter<FusionChartsEvent>(); @Output() milestoneRollOut = new EventEmitter<FusionChartsEvent>(); @Output() chartTypeChanged = new EventEmitter<FusionChartsEvent>(); @Output() overlayButtonClick = new EventEmitter<FusionChartsEvent>(); @Output() loaded = new EventEmitter<FusionChartsEvent>(); @Output() rendered = new EventEmitter<FusionChartsEvent>(); @Output() drawComplete = new EventEmitter<FusionChartsEvent>(); @Output() renderComplete = new EventEmitter<FusionChartsEvent>(); @Output() dataInvalid = new EventEmitter<FusionChartsEvent>(); @Output() dataXMLInvalid = new EventEmitter<FusionChartsEvent>(); @Output() dataLoaded = new EventEmitter<FusionChartsEvent>(); @Output() noDataToDisplay = new EventEmitter<FusionChartsEvent>(); @Output() legendPointerDragStart = new EventEmitter<FusionChartsEvent>(); @Output() legendPointerDragStop = new EventEmitter<FusionChartsEvent>(); @Output() legendRangeUpdated = new EventEmitter<FusionChartsEvent>(); @Output() alertComplete = new EventEmitter<FusionChartsEvent>(); @Output() realTimeUpdateError = new EventEmitter<FusionChartsEvent>(); @Output() dataplotRollOver = new EventEmitter<FusionChartsEvent>(); @Output() dataplotRollOut = new EventEmitter<FusionChartsEvent>(); @Output() dataplotClick = new EventEmitter<FusionChartsEvent>(); @Output() linkClicked = new EventEmitter<FusionChartsEvent>(); @Output() beforeRender = new EventEmitter<FusionChartsEvent>(); @Output() renderCancelled = new EventEmitter<FusionChartsEvent>(); @Output() beforeResize = new EventEmitter<FusionChartsEvent>(); @Output() resized = new EventEmitter<FusionChartsEvent>(); @Output() resizeCancelled = new EventEmitter<FusionChartsEvent>(); @Output() beforeDispose = new EventEmitter<FusionChartsEvent>(); @Output() disposed = new EventEmitter<FusionChartsEvent>(); @Output() disposeCancelled = new EventEmitter<FusionChartsEvent>(); @Output() linkedChartInvoked = new EventEmitter<FusionChartsEvent>(); @Output() beforeDrillDown = new EventEmitter<FusionChartsEvent>(); @Output() drillDown = new EventEmitter<FusionChartsEvent>(); @Output() beforeDrillUp = new EventEmitter<FusionChartsEvent>(); @Output() drillUp = new EventEmitter<FusionChartsEvent>(); @Output() drillDownCancelled = new EventEmitter<FusionChartsEvent>(); @Output() drillUpCancelled = new EventEmitter<FusionChartsEvent>(); @Output() initialized = new EventEmitter<FusionChartInstance>(); containerId: string; private configObj: any; private oldDataSource: any = this.dataSource; private oldDataTable: any; private constructerParams = { type: true, id: true, width: true, height: true, renderAt: true, dataFormat: true, dataSource: true, events: true, link: true, showDataLoadingMessage: true, showChartLoadingMessage: true, baseChartMessageFont: true, baseChartMessageFontSize: true, baseChartMessageColor: true, dataLoadStartMessage: true, dataLoadErrorMessage: true, dataInvalidMessage: true, dataEmptyMessage: true, typeNotSupportedMessage: true, loadMessage: true, renderErrorMessage: true, containerBackgroundColor: true, containerBackgroundOpacity: true, containerClassName: true, baseChartMessageImageHAlign: true, baseChartMessageImageVAlign: true, baseChartMessageImageAlpha: true, baseChartMessageImageScale: true, typeNotSupportedMessageImageHAlign: true, typeNotSupportedMessageImageVAlign: true, typeNotSupportedMessageImageAlpha: true, typeNotSupportedMessageImageScale: true, dataLoadErrorMessageImageHAlign: true, dataLoadErrorMessageImageVAlign: true, dataLoadErrorMessageImageAlpha: true, dataLoadErrorMessageImageScale: true, dataLoadStartMessageImageHAlign: true, dataLoadStartMessageImageVAlign: true, dataLoadStartMessageImageAlpha: true, dataLoadStartMessageImageScale: true, dataInvalidMessageImageHAlign: true, dataInvalidMessageImageVAlign: true, dataInvalidMessageImageAlpha: true, dataInvalidMessageImageScale: true, dataEmptyMessageImageHAlign: true, dataEmptyMessageImageVAlign: true, dataEmptyMessageImageAlpha: true, dataEmptyMessageImageScale: true, renderErrorMessageImageHAlign: true, renderErrorMessageImageVAlign: true, renderErrorMessageImageAlpha: true, renderErrorMessageImageScale: true, loadMessageImageHAlign: true, loadMessageImageVAlign: true, loadMessageImageAlpha: true, loadMessageImageScale: true, chartConfig: true }; element: ElementRef; fusionchartsService: FusionChartsService; constructor( element: ElementRef, fusionchartsService: FusionChartsService, private differs: KeyValueDiffers, private zone: NgZone ) { this.element = element; this.fusionchartsService = fusionchartsService; this.containerId = fusionchartsService.getNextItemCount(); } // @ViewChild('samplediv') chartContainer: ElementRef; checkIfDataTableExists(dataSource) { if (dataSource && dataSource.data && dataSource.data._dataStore) { return true; } return false; } cloneDataSource(obj) { let type = typeof obj; if ( type === 'string' || type === 'number' || type === 'function' || type === 'boolean' ) { return obj; } if (obj === null || obj === undefined) { return obj; } if (Array.isArray(obj)) { let arr: any[] = []; for (let i = 0; i < obj.length; i++) { arr.push(this.cloneDataSource(obj[i])); } return arr; } if (typeof obj === 'object') { let clonedObj = {}; for (let prop in obj) { // Edge case handling for DataTable if (prop === 'data') { if (obj[prop]._dataStore) { clonedObj[prop] = `-`; } else { clonedObj[prop] = this.cloneDataSource(obj[prop]); } continue; } clonedObj[prop] = this.cloneDataSource(obj[prop]); } return clonedObj; } } ngOnInit() { if (this.checkIfDataTableExists(this.dataSource)) { this.oldDataSource = JSON.stringify( this.cloneDataSource(this.dataSource) ); } else { this.oldDataSource = JSON.stringify(this.dataSource); } this.placeholder = this.placeholder || 'FusionCharts will render here'; } ngOnChanges(changes: any) { for (const i of Object.keys(changes)) { const key = i.charAt(0).toUpperCase() + i.slice(1), THIS = this, fnName = `update${key}`; if (THIS[fnName]) { THIS[fnName](); } } } ngDoCheck() { let data; if (this.checkIfDataTableExists(this.dataSource)) { data = JSON.stringify(this.cloneDataSource(this.dataSource)); } else { data = JSON.stringify(this.dataSource); } if ( this.oldDataSource !== data || this.oldDataTable !== this.dataSource.data ) { this.oldDataTable = this.dataSource && this.dataSource.data; this.oldDataSource = data; this.updateChartData(); } } updateChartData() { const dataFormat = this.configObj && this.configObj.dataFormat ? this.configObj.dataFormat : 'json', data = this.dataSource; if (this.chartObj) { this.chartObj.setChartData(data, dataFormat); } } updateWidth() { if (this.chartObj) { this.chartObj.resizeTo({ w: this.width }); } } updateHeight() { if (this.chartObj) { this.chartObj.resizeTo({ h: this.height }); } } updateType() { if (this.chartObj) { this.chartObj.chartType(this.type); } } generateEventsCallback(eventList: Array<string>) { let events = {}; eventList.forEach(eventName => { events[eventName] = (eventObj: any, dataObj: any) => { let fEventObj: FusionChartsEvent = { eventObj: {}, dataObj: {} }; if (eventObj) fEventObj.eventObj = eventObj; if (dataObj) fEventObj.dataObj = dataObj; this[eventName].emit(fEventObj); }; }); return events; } ngAfterViewInit() { const _this = this, params = _this.constructerParams, configObj = _this.configObj || (_this.configObj = {}); let _chartConfig: any = _this.chartConfig || {}; if (typeof _chartConfig === 'string') { _chartConfig = JSON.parse(_chartConfig); } for (const i of Object.keys(params)) { const value = _this[i] || _chartConfig[i]; if (value) { configObj[i] = value; } } if (configObj['type']) { let events = _this.generateEventsCallback(_this.eventList); if (!configObj['events']) { configObj['events'] = events; } else { configObj['events'] = Object.assign(events, configObj['events']); } // configObj['renderAt'] = 'container-' + _this.chartObj.id; // _this.containerId = _this.chartObj.id; this.zone.runOutsideAngular(() => { setTimeout(() => { _this.chartObj = FusionChartsConstructor( _this.fusionchartsService, configObj ); this.initialized.emit({ chart: _this.chartObj }); _this.chartObj.render( _this.element.nativeElement.querySelector('div') ); }, 1); }); } } ngOnDestroy() { this.chartObj && this.chartObj.dispose(); } } export { FusionChartsComponent };
the_stack
import * as _ from 'lodash-es'; import * as React from 'react'; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore: FIXME missing exports due to out-of-sync @types/react-redux version import { useDispatch } from 'react-redux'; import { match as RMatch } from 'react-router-dom'; import { Table as PfTable, TableHeader, TableBody, TableGridBreakpoint, SortByDirection, OnSelect, TableProps as PfTableProps, } from '@patternfly/react-table'; import { CellMeasurerCache, CellMeasurer } from 'react-virtualized'; import { AutoSizer, VirtualTableBody, WindowScroller, } from '@patternfly/react-virtualized-extension'; import { Scroll } from '@patternfly/react-virtualized-extension/dist/js/components/Virtualized/types'; import { getNodeRoles, getMachinePhase, getMachineSetInstanceType, nodeMemory, nodeCPU, nodeFS, nodePods, nodeMachine, nodeInstanceType, nodeZone, pvcUsed, snapshotSize, snapshotSource, ALL_NAMESPACES_KEY, getName, useDeepCompareMemoize, } from '@console/shared'; import { PackageManifestKind } from '@console/operator-lifecycle-manager/src/types'; import { defaultChannelFor } from '@console/operator-lifecycle-manager/src/components'; import { RowFilter as RowFilterExt } from '@console/dynamic-plugin-sdk'; import { RowFilter } from '../filter-toolbar'; import * as UIActions from '../../actions/ui'; import { alertingRuleSource, alertingRuleStateOrder, alertSeverityOrder, alertSource, alertStateOrder, silenceFiringAlertsOrder, silenceStateOrder, } from '../monitoring/utils'; import { ingressValidHosts } from '../ingress'; import { convertToBaseValue, EmptyBox, StatusBox, WithScrollContainer } from '../utils'; import { CustomResourceDefinitionKind, getClusterOperatorStatus, getClusterOperatorVersion, getJobTypeAndCompletions, getLatestVersionForCRD, getTemplateInstanceStatus, K8sResourceKind, K8sResourceKindReference, NodeKind, planExternalName, PodKind, podPhase, podReadiness, podRestarts, serviceCatalogStatus, serviceClassDisplayName, MachineKind, VolumeSnapshotKind, } from '../../module/k8s'; import { useTableData } from './table-data-hook'; const sorts = { alertingRuleSource, alertingRuleStateOrder, alertSeverityOrder, alertSource, alertStateOrder, crdLatestVersion: (crd: CustomResourceDefinitionKind): string => getLatestVersionForCRD(crd), daemonsetNumScheduled: (daemonset) => _.toInteger(_.get(daemonset, 'status.currentNumberScheduled')), dataSize: (resource) => _.size(_.get(resource, 'data')) + _.size(_.get(resource, 'binaryData')), ingressValidHosts, serviceCatalogStatus, instanceType: (obj): string => getMachineSetInstanceType(obj), jobCompletionsSucceeded: (job) => job?.status?.succeeded || 0, jobType: (job) => getJobTypeAndCompletions(job).type, nodeReadiness: (node: NodeKind) => { let readiness = _.get(node, 'status.conditions'); readiness = _.find(readiness, { type: 'Ready' }); return _.get(readiness, 'status'); }, numReplicas: (resource) => _.toInteger(_.get(resource, 'status.replicas')), planExternalName, namespaceCPU: (ns: K8sResourceKind): number => UIActions.getNamespaceMetric(ns, 'cpu'), namespaceMemory: (ns: K8sResourceKind): number => UIActions.getNamespaceMetric(ns, 'memory'), podCPU: (pod: PodKind): number => UIActions.getPodMetric(pod, 'cpu'), podMemory: (pod: PodKind): number => UIActions.getPodMetric(pod, 'memory'), podPhase, podReadiness: (pod: PodKind): number => podReadiness(pod).readyCount, podRestarts, pvStorage: (pv) => _.toInteger(convertToBaseValue(pv?.spec?.capacity?.storage)), pvcStorage: (pvc) => _.toInteger(convertToBaseValue(pvc?.status?.capacity?.storage)), serviceClassDisplayName, silenceFiringAlertsOrder, silenceStateOrder, string: (val) => JSON.stringify(val), number: (val) => _.toNumber(val), getClusterOperatorStatus, getClusterOperatorVersion, getTemplateInstanceStatus, nodeRoles: (node: NodeKind): string => { const roles = getNodeRoles(node); return roles.sort().join(', '); }, nodeMemory: (node: NodeKind): number => nodeMemory(node), nodeCPU: (node: NodeKind): number => nodeCPU(node), nodeFS: (node: NodeKind): number => nodeFS(node), nodeMachine: (node: NodeKind): string => nodeMachine(node), nodeInstanceType: (node: NodeKind): string => nodeInstanceType(node), nodeZone: (node: NodeKind): string => nodeZone(node), machinePhase: (machine: MachineKind): string => getMachinePhase(machine), nodePods: (node: NodeKind): number => nodePods(node), pvcUsed: (pvc: K8sResourceKind): number => pvcUsed(pvc), volumeSnapshotSize: (snapshot: VolumeSnapshotKind): number => snapshotSize(snapshot), volumeSnapshotSource: (snapshot: VolumeSnapshotKind): string => snapshotSource(snapshot), snapshotLastRestore: (snapshot: K8sResourceKind, { restores }) => restores[getName(snapshot)]?.status?.restoreTime, sortPackageManifestByDefaultChannelName: (packageManifest: PackageManifestKind): string => { const channel = defaultChannelFor(packageManifest); return channel?.currentCSVDesc?.displayName; }, }; // Common table row/columns helper SFCs for implementing accessible data grid export const TableRow: React.FC<TableRowProps> = ({ id, index, trKey, style, className, ...props }) => { return ( <tr {...props} data-id={id} data-index={index} data-test-rows="resource-row" data-key={trKey} style={style} className={className} role="row" /> ); }; TableRow.displayName = 'TableRow'; export type TableRowProps = { id: React.ReactText; index: number; title?: string; trKey: string; style: object; className?: string; }; const BREAKPOINT_SM = 576; const BREAKPOINT_MD = 768; const BREAKPOINT_LG = 992; const BREAKPOINT_XL = 1200; const BREAKPOINT_XXL = 1400; const MAX_COL_XS = 2; const MAX_COL_SM = 4; const MAX_COL_MD = 4; const MAX_COL_LG = 6; const MAX_COL_XL = 8; const isColumnVisible = ( widthInPixels: number, columnID: string, columns: Set<string> = new Set(), showNamespaceOverride, ) => { const showNamespace = columnID !== 'namespace' || UIActions.getActiveNamespace() === ALL_NAMESPACES_KEY || showNamespaceOverride; if (_.isEmpty(columns) && showNamespace) { return true; } if (!columns.has(columnID) || !showNamespace) { return false; } const columnIndex = [...columns].indexOf(columnID); if (widthInPixels < BREAKPOINT_SM) { return columnIndex < MAX_COL_XS; } if (widthInPixels < BREAKPOINT_MD) { return columnIndex < MAX_COL_SM; } if (widthInPixels < BREAKPOINT_LG) { return columnIndex < MAX_COL_MD; } if (widthInPixels < BREAKPOINT_XL) { return columnIndex < MAX_COL_LG; } if (widthInPixels < BREAKPOINT_XXL) { return columnIndex < MAX_COL_XL; } return true; }; export const TableData: React.FC<TableDataProps> = ({ className, columnID, columns, showNamespaceOverride, ...props }) => { return isColumnVisible(window.innerWidth, columnID, columns, showNamespaceOverride) ? ( <td {...props} className={className} role="gridcell" /> ) : null; }; TableData.displayName = 'TableData'; export type TableDataProps = { className?: string; columnID?: string; columns?: Set<string>; id?: string; showNamespaceOverride?: boolean; }; const TableWrapper: React.FC<TableWrapperProps> = ({ virtualize, ariaLabel, ariaRowCount, ...props }) => { return virtualize ? ( <div {...props} role="grid" aria-label={ariaLabel} aria-rowcount={ariaRowCount} /> ) : ( <React.Fragment {...props} /> ); }; export type TableWrapperProps = { virtualize: boolean; ariaLabel: string; ariaRowCount: number; }; const RowMemo = React.memo<RowFunctionArgs & { Row: React.FC<RowFunctionArgs> }>( ({ Row, ...props }) => <Row {...props} />, ); const VirtualBody: React.FC<VirtualBodyProps> = (props) => { const { customData, Row, height, isScrolling, onChildScroll, data, columns, scrollTop, width, getRowProps, } = props; const cellMeasurementCache = new CellMeasurerCache({ fixedWidth: true, minHeight: 44, keyMapper: (rowIndex) => _.get(props.data[rowIndex], 'metadata.uid', rowIndex), }); const rowRenderer = ({ index, isVisible, key, style, parent }) => { const rowArgs = { obj: data[index], columns, customData, }; // do not render non visible elements (this excludes overscan) if (!isVisible) { return null; } const rowProps = getRowProps?.(rowArgs.obj); const rowId = rowProps?.id ?? key; return ( <CellMeasurer cache={cellMeasurementCache} columnIndex={0} key={key} parent={parent} rowIndex={index} > <TableRow {...rowProps} id={rowId} index={index} trKey={key} style={style}> <RowMemo Row={Row} {...rowArgs} /> </TableRow> </CellMeasurer> ); }; return ( <VirtualTableBody autoHeight className="pf-c-table pf-m-compact pf-m-border-rows pf-c-virtualized pf-c-window-scroller" deferredMeasurementCache={cellMeasurementCache} rowHeight={cellMeasurementCache.rowHeight} height={height || 0} isScrolling={isScrolling} onScroll={onChildScroll} overscanRowCount={10} columns={columns} rows={data} rowCount={data.length} rowRenderer={rowRenderer} scrollTop={scrollTop} width={width} /> ); }; export type RowFunctionArgs<T = any, C = any> = { obj: T; columns: any[]; customData?: C; }; export type VirtualBodyProps<D = any, C = any> = { customData?: C; Row: React.FC<RowFunctionArgs>; height: number; isScrolling: boolean; onChildScroll: (params: Scroll) => void; data: D[]; columns: any[]; scrollTop: number; width: number; expand: boolean; getRowProps?: (obj: D) => Partial<Pick<TableRowProps, 'id' | 'className' | 'title'>>; }; type HeaderFunc = (componentProps: ComponentProps) => any[]; const getActiveColumns = ( windowWidth: number, Header: HeaderFunc, componentProps: ComponentProps, activeColumns: Set<string>, columnManagementID: string, showNamespaceOverride: boolean, ) => { let columns = Header(componentProps); if (_.isEmpty(activeColumns)) { activeColumns = new Set( columns.map((col) => { if (col.id && !col.additional) { return col.id; } }), ); } if (columnManagementID) { columns = columns?.filter( (col) => isColumnVisible(windowWidth, col.id, activeColumns, showNamespaceOverride) || col.title === '', ); } else { columns = columns?.filter((col) => activeColumns.has(col.id) || col.title === ''); } const showNamespace = UIActions.getActiveNamespace() === ALL_NAMESPACES_KEY || showNamespaceOverride; if (!showNamespace) { columns = columns.filter((column) => column.id !== 'namespace'); } return columns; }; const getComponentProps = ( data: any[], filters: Filter[], selected: boolean, match: RMatch<any>, kindObj: K8sResourceKindReference, ): ComponentProps => ({ data, filters, selected, match, kindObj, }); export const Table: React.FC<TableProps> = ({ onSelect, filters: initFilters, selected, match, kindObj, Header: initHeader, activeColumns, columnManagementID, showNamespaceOverride, scrollElement, Rows, Row, expand, label, mock, selectedResourcesForKind, 'aria-label': ariaLabel, virtualize = true, customData, gridBreakPoint = TableGridBreakpoint.none, loaded, loadError, NoDataEmptyMsg, EmptyMsg, defaultSortOrder, customSorts, data: propData, defaultSortFunc, reduxID, reduxIDs, staticFilters, rowFilters, isPinned, defaultSortField, getRowProps, }) => { const filters = useDeepCompareMemoize(initFilters); const Header = useDeepCompareMemoize(initHeader); const { currentSortField, currentSortFunc, currentSortOrder, data, listId } = useTableData({ reduxID, reduxIDs, defaultSortFunc, defaultSortField, defaultSortOrder, staticFilters, filters, rowFilters: rowFilters as RowFilterExt[], propData, loaded, isPinned, customData, customSorts, sorts, }); const dispatch = useDispatch(); const [windowWidth, setWindowWidth] = React.useState(window.innerWidth); const [sortBy, setSortBy] = React.useState({}); const [columns, componentProps] = React.useMemo(() => { const cProps = getComponentProps(data, filters, selected, match, kindObj); return [ getActiveColumns( windowWidth, Header, cProps, activeColumns, columnManagementID, showNamespaceOverride, ), cProps, ]; }, [ windowWidth, Header, data, filters, selected, match, kindObj, activeColumns, columnManagementID, showNamespaceOverride, ]); const columnShift = onSelect ? 1 : 0; //shift indexes by 1 if select provided React.useEffect(() => { if (!sortBy) { let newSortBy = {}; if (currentSortField && currentSortOrder) { const columnIndex = _.findIndex(columns, { sortField: currentSortField }); if (columnIndex > -1) { newSortBy = { index: columnIndex + columnShift, direction: currentSortOrder }; } } else if (currentSortFunc && currentSortOrder) { const columnIndex = _.findIndex(columns, { sortFunc: currentSortFunc }); if (columnIndex > -1) { newSortBy = { index: columnIndex + columnShift, direction: currentSortOrder }; } } setSortBy(newSortBy); } }, [columnShift, columns, currentSortField, currentSortFunc, currentSortOrder, sortBy]); const applySort = React.useCallback( (sortField, sortFunc, direction, columnTitle) => { dispatch( UIActions.sortList(listId, sortField, sortFunc || currentSortFunc, direction, columnTitle), ); }, [currentSortFunc, dispatch, listId], ); const onSort = React.useCallback( (event, index, direction) => { event.preventDefault(); const sortColumn = columns[index - columnShift]; applySort(sortColumn.sortField, sortColumn.sortFunc, direction, sortColumn.title); setSortBy({ index, direction, }); }, [applySort, columnShift, columns], ); React.useEffect(() => { const handleResize = _.debounce(() => setWindowWidth(window.innerWidth), 100); const sp = new URLSearchParams(window.location.search); const columnIndex = _.findIndex(columns, { title: sp.get('sortBy') }); if (columnIndex > -1) { const sortOrder = sp.get('orderBy') || SortByDirection.asc; const column = columns[columnIndex]; applySort(column.sortField, column.sortFunc, sortOrder, column.title); setSortBy({ index: columnIndex + columnShift, direction: sortOrder, }); } // re-render after resize window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const ariaRowCount = data && data.length; const scrollNode = typeof scrollElement === 'function' ? scrollElement() : scrollElement; const renderVirtualizedTable = (scrollContainer) => ( <WindowScroller scrollElement={scrollContainer}> {({ height, isScrolling, registerChild, onChildScroll, scrollTop }) => ( <AutoSizer disableHeight> {({ width }) => ( <div ref={registerChild}> <VirtualBody Row={Row} customData={customData} height={height} isScrolling={isScrolling} onChildScroll={onChildScroll} data={data} columns={columns} scrollTop={scrollTop} width={width} expand={expand} getRowProps={getRowProps} /> </div> )} </AutoSizer> )} </WindowScroller> ); const children = mock ? ( <EmptyBox label={label} /> ) : ( <TableWrapper virtualize={virtualize} ariaLabel={ariaLabel} ariaRowCount={ariaRowCount}> <PfTable cells={columns} rows={ virtualize ? [] : Rows({ componentProps, selectedResourcesForKind, customData, }) } gridBreakPoint={gridBreakPoint} onSort={onSort} onSelect={onSelect} sortBy={sortBy} className="pf-m-compact pf-m-border-rows" role={virtualize ? 'presentation' : 'grid'} aria-label={virtualize ? null : ariaLabel} > <TableHeader role="rowgroup" /> {!virtualize && <TableBody />} </PfTable> {virtualize && (scrollNode ? ( renderVirtualizedTable(scrollNode) ) : ( <WithScrollContainer>{renderVirtualizedTable}</WithScrollContainer> ))} </TableWrapper> ); return ( <div className="co-m-table-grid co-m-table-grid--bordered"> {mock ? ( children ) : ( <StatusBox skeleton={<div className="loading-skeleton--table" />} data={data} loaded={loaded} loadError={loadError} unfilteredData={propData} label={label} NoDataEmptyMsg={NoDataEmptyMsg} EmptyMsg={EmptyMsg} > {children} </StatusBox> )} </div> ); }; export type Filter = { key: string; value: string }; type RowsArgs<C = any> = { componentProps: ComponentProps; selectedResourcesForKind: string[]; customData: C; }; export type TableProps<D = any, C = any> = Partial<ComponentProps<D>> & { customData?: C; customSorts?: { [key: string]: (obj: D) => number | string }; defaultSortFunc?: string; defaultSortField?: string; defaultSortOrder?: SortByDirection; showNamespaceOverride?: boolean; Header: HeaderFunc; loadError?: string | Object; Row?: React.FC<RowFunctionArgs<D, C>>; Rows?: (args: RowsArgs<C>) => PfTableProps['rows']; 'aria-label': string; onSelect?: OnSelect; virtualize?: boolean; NoDataEmptyMsg?: React.ComponentType<{}>; EmptyMsg?: React.ComponentType<{}>; loaded?: boolean; reduxID?: string; reduxIDs?: string[]; rowFilters?: RowFilter[]; label?: string; columnManagementID?: string; isPinned?: (val: D) => boolean; staticFilters?: Filter[]; activeColumns?: Set<string>; gridBreakPoint?: TableGridBreakpoint; selectedResourcesForKind?: string[]; mock?: boolean; expand?: boolean; scrollElement?: HTMLElement | (() => HTMLElement); getRowProps?: VirtualBodyProps<D>['getRowProps']; }; export type ComponentProps<D = any> = { data: D[]; filters: Filter[]; selected: boolean; match: RMatch<any>; kindObj: K8sResourceKindReference; };
the_stack
import { escape, find, findIndex } from '@microsoft/sp-lodash-subset'; import { Logger, LogLevel } from "@pnp/logging"; import { sp, SPHttpClient } from "@pnp/sp"; import { Folders, IFolder, IFolderInfo, IFolders } from "@pnp/sp/folders"; import { IFiles, IItem, IListInfo, ISiteUser } from "@pnp/sp/presets/all"; import { IRoleDefinitionInfo } from '@pnp/sp/security'; import { ISiteGroup, ISiteGroupInfo } from '@pnp/sp/site-groups'; import { ISiteUsers, SiteUser } from '@pnp/sp/site-users'; import { IViewInfo } from '@pnp/sp/views'; import { format } from "date-fns"; import { ActionButton, Button, PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { CommandBarButton } from 'office-ui-fabric-react/lib/Button'; import { CommandBar, ICommandBarItemProps } from 'office-ui-fabric-react/lib/CommandBar'; import { DatePicker } from 'office-ui-fabric-react/lib/DatePicker'; import { DetailsList, DetailsListLayoutMode, IColumn } from 'office-ui-fabric-react/lib/DetailsList'; import { Icon, IIconProps, IIconStyleProps } from 'office-ui-fabric-react/lib/Icon'; import { IconNames } from 'office-ui-fabric-react/lib/Icons'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { autobind, IObjectWithKey, Selection, SelectionMode } from 'office-ui-fabric-react/lib/Utilities'; import * as React from 'react'; import { CSVLink } from "react-csv"; import { roleDefinitionForLibraryMembersGroupOnLibrary } from 'RequestMaintenanceWebPartStrings'; import { IActivity } from '../../../models/IActivity'; import { IDrive } from '../../../models/IDrive'; import { IRFx } from '../../../models/IRFx'; import { IRFxFolder } from '../../../models/IRFxFolder'; import RFXUtilities from '../../../utilities/RFXUtilities'; import { IRequestMaintenanceProps } from './IRequestMaintenanceProps'; import { IRequestMaintenanceState } from './IRequestMaintenanceState'; import styles from './RequestMaintenance.module.scss'; import "@pnp/sp/files"; import "@pnp/sp/folders"; import "@pnp/sp/folders/item"; import "@pnp/sp/folders/list"; import "@pnp/sp/items"; import "@pnp/sp/lists/web"; import "@pnp/sp/lists/web"; import "@pnp/sp/security/list"; import "@pnp/sp/security/web"; import "@pnp/sp/site-groups"; import "@pnp/sp/site-users/web"; import "@pnp/sp/sites"; import "@pnp/sp/views"; import "@pnp/sp/webs"; export default class RequestMaintenance extends React.Component<IRequestMaintenanceProps, IRequestMaintenanceState> { private _drives: Array<IDrive>; private mainSelection: Selection; constructor(props: any) { super(props); this.state = { rfxs: [], siteGroups: [], currentUserId: null, currentUserEMail: null, currentUserLoginName: null, showAddNewLibrary: false, newRfxId: null, newRfxDescription: null, newRFxClosingDate: null, newRFxLibraryMembersGroupName: null, newRFxLibraryVisitorsGroupName: null, newRFxLibraryOwnersGroupName: null, newFolderMembersGroupName: null, newFolderVisitorsGroupName: null, isUpdating: false, invalidCharacters: false, newFolderName: null, rfxFolders: [], selectedRfx: null, showAddNewFolder: false, showFolders: false, showActivity: false, activities: [], mainSelectedItemsCount: 0 }; this.mainSelection = new Selection({ onSelectionChanged: this.onMainSelectionChanged, selectionMode: SelectionMode.multiple }); } private onMainSelectionChanged = () => { const newSelectedItems = this.mainSelection.getSelection(); this.setState((current) => ({ ...current, mainSelectedItemsCount: newSelectedItems.length })); } public componentDidMount() { this.fetchRFxs(); this.fetchSiteGroups(); this.fetchCurrentUser().then(() => { Logger.write(`User ${this.state.currentUserEMail} has started the app`, LogLevel.Warning); }); } private async fetchCurrentUser() { let user = await sp.web.currentUser.get(); this.setState((current) => ({ ...current, currentUserId: user.Id, currentUserEMail: user.Email, currentUserLoginName: user.LoginName, }) ); } /** * Fetches the list of secured libraries (store in a sharepoint list) and updates them in the docLibs State varieble * * @private * @memberof DocLibSecurity */ private fetchRFxs() { sp.web.lists.getByTitle(this.props.rfxListTitle).items.orderBy("Title") .expand("rfxContractSpecialist") .select("Id,Title,rfxDescription,rfxClosingDate,rfxLibraryMembersGroupId,rfxLibraryVisitorsGroupId,rfxOwnersGroupId,rfxContractSpecialistId,rfxContractSpecialist/EMail") .getAll().then((items) => { this.setState((current) => ({ ...current, rfxs: items.map((item) => { return { title: item.Title, id: item.ID, closingDate: new Date(item["rfxClosingDate"]), contractSpecialistId: item["rfxContractSpecialistId"], contractSpecialist: item["rfxContractSpecialist"], libraryMembersGroupId: item["rfxLibraryMembersGroupId"], libraryVisitorsGroupId: item["rfxLibraryVisitorsGroupId"], libraryOwnersGroupId: item["rfxOwnersGroupId"], description: item["rfxDescription"] }; }) }) ); }); } private fetchSiteGroups() { sp.web.siteGroups.get().then((items) => { this.setState((current) => ({ ...current, siteGroups: items }) ); }); } /** * Determinse if a SiteGroup with the given name exists * * @private * @param {string} groupName The name of the SiteGroup we want to check * @returns {Promise<boolean>} True if SiteGroup exists , otherwise false * @memberof DocLibSecurity */ private doesRFxExist(RFXId: string): boolean { if (findIndex(this.state.rfxs, (r) => { return r.title === RFXId; }) === -1) { return false; } else { return true; } } private getSiteGroupName(siteGroupId: number): string { let sg: ISiteGroupInfo = find(this.state.siteGroups as Array<ISiteGroupInfo>, (sgx) => { return sgx.Id === siteGroupId; }); if (sg) { return sg.Title; } else { return (`*${siteGroupId}*`); } } /** * Validates the data to add a new library and adds it if valid * * @private * @returns * @memberof DocLibSecurity */ private async validateAndAddLibrary() { this.setState((current) => ({ ...current, isUpdating: true })); if (!this.state.newRfxId || this.state.newRfxId.length === 0) { alert("Library/RFx Name is required"); this.setState((current) => ({ ...current, isUpdating: false })); return; } if (!this.state.newRFxClosingDate) { this.setState((current) => ({ ...current, isUpdating: false })); alert("Closing Date is required"); return; } //Do validation if (this.doesRFxExist(this.state.newRfxId)) { alert("An entry with this name already exists in the List of Libraries"); this.setState((current) => ({ ...current, isUpdating: false })); return; } if (await sp.web.lists.getByTitle(this.state.newRfxId).get() .then((list) => { return true; }) .catch((e) => { return false; }) ) { alert("A list with this name already exists"); this.setState((current) => ({ ...current, isUpdating: false })); return; } const membersGroupExists = await RFXUtilities.doesGroupExist(this.state.newRFxLibraryMembersGroupName); if (membersGroupExists) { alert(`A group named ${this.state.newRFxLibraryMembersGroupName} already exists`); this.setState((current) => ({ ...current, isUpdating: false })); return; } const visitorsGroupExists = await RFXUtilities.doesGroupExist(this.state.newRFxLibraryVisitorsGroupName); if (visitorsGroupExists) { alert(`A group named ${this.state.newRFxLibraryVisitorsGroupName} already exists`); this.setState((current) => ({ ...current, isUpdating: false })); return; } const libraryOwnerGroupExists = await RFXUtilities.doesGroupExist(this.state.newRFxLibraryOwnersGroupName); if (libraryOwnerGroupExists) { alert(`A group named ${this.state.newRFxLibraryOwnersGroupName} already exists`); this.setState((current) => ({ ...current, isUpdating: false })); return; } // Add the new library let listInfo: IListInfo = await sp.web.lists.add(this.state.newRfxId, "", 101, false, { OnQuickLaunch: true }) .catch((e) => { const message = `there was an error adding the library ${this.state.newRfxId}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!listInfo) return; //create the ownersGroup const libraryOwnersGroup: ISiteGroupInfo = await sp.web.siteGroups.add({ "Title": this.state.newRFxLibraryOwnersGroupName }) .then((g) => { return g.group(); }) .catch((e) => { const message = `there was an error adding the group ${this.state.newRFxLibraryOwnersGroupName}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (libraryOwnersGroup === null) return; // add the current user to the library owners group const owner: ISiteUser = await sp.web.siteGroups.getById(libraryOwnersGroup.Id).users.add(this.state.currentUserLoginName) .then((u) => { console.log(`added user ${this.state.currentUserLoginName} to group ${libraryOwnersGroup.Title}`); return u(); }) .catch((e) => { const message = `error adding user ${this.state.currentUserLoginName} to group ${libraryOwnersGroup.Title}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!owner) return; // add the siteowners to the library owners group const siteownwers: ISiteUsers = await sp.web.siteGroups.getById(this.props.siteOwnersGroup.Id).users.get() .then((so) => { console.log(`fetched ${so.length} people from site owners group`); return so; }) .catch((e) => { const message = `error fetching siteowners group with id ${this.props.siteOwnersGroup.Id}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!siteownwers) return; let errorAddingOwnwers = false; for (let i = 0; i < siteownwers.length; i++) { await sp.web.siteGroups.getById(libraryOwnersGroup.Id).users.add(siteownwers[i]["LoginName"]) .then((e) => { console.log(`added user ${this.state.currentUserLoginName} to group ${libraryOwnersGroup.Title}`); }) .catch((e) => { errorAddingOwnwers = true; const message = `error adding user ${this.state.currentUserLoginName} to group ${libraryOwnersGroup.Title}`; this.logError(message, e); }); } if (errorAddingOwnwers) { this.setState((current) => ({ ...current, isUpdating: false })); return null; } // break role inheritance on the new library if (! await sp.web.lists.getByTitle(this.state.newRfxId).breakRoleInheritance(false) .then(() => { return true; }) .catch((e) => { let message = `there was an error breaking inheritance on the library ${this.state.newRfxId}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // give the library Onwers group Full Control access to the library if (! await RFXUtilities.grantGroupAccessToLibrary(this.state.newRfxId, libraryOwnersGroup.Id, "Full Control", this.props.roleDefinitions) .then(() => { return true; }) .catch((e) => { const message = `there was an error granting group ${libraryOwnersGroup.Title} Full Control access to the library`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // Add the library members group const libraryMembersGroup: ISiteGroupInfo = await sp.web.siteGroups.add({ "Title": this.state.newRFxLibraryMembersGroupName }) .then((g) => { return g.group(); }) .catch((e) => { const message = `there was an error adding the group ${this.state.newRFxLibraryMembersGroupName}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!libraryMembersGroup) return; // set the owners of the new group if (! RFXUtilities.setGroupOwner(libraryMembersGroup.Id, libraryOwnersGroup.Id) .then((g) => { return true; }) .catch((e) => { const message = `there was an error setting the owner of group ${libraryMembersGroup.Id} to group ${libraryOwnersGroup.Id}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // give the library members group the specified access to the new library if (! await RFXUtilities.grantGroupAccessToLibrary(this.state.newRfxId, libraryMembersGroup.Id, this.props.roleDefinitionForLibraryMembersGroupOnLibrary, this.props.roleDefinitions) .then((g) => { return true; }) .catch((e) => { const message = `there was an error granting the group ${libraryMembersGroup.Title} access to the library ${this.state.newRfxId}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // give the library mambers group the specified access to the new Site if (! await RFXUtilities.grantGroupIdAccessToSite(libraryMembersGroup.Id, this.props.roleDefinitionForLibraryMembersGroupOnSite, this.props.roleDefinitions) .then((g) => { return true; }) .catch((e) => { const message = `there was an error granting access to the site to the ${this.state.newRFxLibraryMembersGroupName} group`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // Add the library visitors group const libraryVisitorsGroup: ISiteGroupInfo = await sp.web.siteGroups.add({ "Title": this.state.newRFxLibraryVisitorsGroupName }) .then((g) => { return g.group(); }) .catch((e) => { const message = `there was an error adding the group ${this.state.newRFxLibraryVisitorsGroupName}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!libraryVisitorsGroup) return; if (! await RFXUtilities.setGroupOwner(libraryVisitorsGroup.Id, libraryOwnersGroup.Id) .then((g) => { return true; }) .catch((e) => { const message = `there was an error setting the owner of group ${libraryVisitorsGroup.Id} to group ${libraryOwnersGroup.Id}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // give the library visitors group the specified access to the new library if (! await RFXUtilities.grantGroupAccessToLibrary(this.state.newRfxId, libraryVisitorsGroup.Id, this.props.roleDefinitionForLibraryVisitorsGroupOnLibrary, this.props.roleDefinitions) .then((g) => { return true; }) .catch((e) => { const message = `there was an error granting the group ${libraryVisitorsGroup.Title} access to the library`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // give the library visitors group the specified access to the new Site if (! await RFXUtilities.grantGroupIdAccessToSite(libraryVisitorsGroup.Id, this.props.roleDefinitionForLibraryVisitorsGroupOnSite, this.props.roleDefinitions) .then(() => { return true; }) .catch((e) => { const message = `there was an error granting access to the site to the ${this.state.newRFxLibraryMembersGroupName} group`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // // give the default Members group contribute access to the library // await this.grantGroupAccessToLibrary(this.state.newDocLibTitle, this.props.membersGroup.Id, "Contribute") // .catch((e) => { // alert(`there was an error granting group ${this.props.membersGroup.Title} Contribute access to the library`); // this.setState((current) => ({ ...current, isUpdating: false })); // return; // }); // give the default Visitors group contribute access to the library // await this.grantGroupAccessToLibrary(this.state.newDocLibTitle, this.props.visitorsGroup.Id, "Read") // .catch((e) => { // alert(`there was an error granting group ${this.props.visitorsGroup.Title} Read access to the library`); // this.setState((current) => ({ ...current, isUpdating: false })); // return; // }); // give the default Onwers group Full Control access to the library if (! await RFXUtilities.grantGroupAccessToLibrary(this.state.newRfxId, this.props.siteOwnersGroup.Id, "Full Control", this.props.roleDefinitions) .then(() => { return true; }) .catch((e) => { const message = `there was an error granting group ${this.props.siteOwnersGroup.Title} Full Control access to the library`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // 27OCT2020 // remove the users direct permission if (! await RFXUtilities.removeAccessToLibrary(this.state.newRfxId, this.state.currentUserId, "Full Control", this.props.roleDefinitions) .then(() => { return true; }) .catch((e) => { const message = `there was an error removing the current users direct "Full Control" Full Control access to the library`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // add an entry to the Secured Libraries list to track this entry if (! await sp.web.lists.getByTitle(this.props.rfxListTitle).items.add({ Title: this.state.newRfxId, rfxClosingDate: this.state.newRFxClosingDate, rfxContractSpecialistId: this.state.currentUserId, rfxDescription: this.state.newRfxDescription, rfxLibraryVisitorsGroupId: libraryVisitorsGroup.Id, rfxLibraryMembersGroupId: libraryMembersGroup.Id, rfxOwnersGroupId: libraryOwnersGroup.Id }) .then(() => { return true; }) .catch((e) => { const message = "there was an updating the list of libraries"; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } this.fetchRFxs(); this.fetchSiteGroups(); this.fetchCurrentUser(); this.setState((current) => ({ ...current, showAddNewLibrary: false, isUpdating: false, newRfxId: null, newRfxDescription: null, newRFxClosingDate: null, newRFxContractSpecialist: null, newRFxInternalMembersGroupName: null, newRFxExternalMembersGroupName: null, newRFxOwnersGroupName: null })); } private logError(message: string, e: any) { Logger.write(`${this.state.currentUserEMail}--${message}`, LogLevel.Error); Logger.writeJSON(e, LogLevel.Error); alert(e); } private async doesFolderExist(libraryName: string, folderName: string): Promise<boolean> { const exists = await sp.web.lists.getByTitle(libraryName).rootFolder .folders.getByName(folderName).get() .then((e) => { return true; }) .catch((e) => { return false; }); if (exists) { return true; } else { return false; } } private async validateAndAddFolder() { this.setState((current) => ({ ...current, isUpdating: true })); if (!this.state.newFolderName || this.state.newFolderName.length === 0) { alert("Folder Name is required"); this.setState((current) => ({ ...current, isUpdating: false })); return; } //does folder exist in library if (await this.doesFolderExist(this.state.selectedRfx.title, this.state.newFolderName)) { alert(`An folder named ${this.state.newFolderName} already exists in library ${this.state.selectedRfx.title}`); this.setState((current) => ({ ...current, isUpdating: false })); return; } //does folder exist in list of folders if (findIndex(this.state.rfxFolders, (f) => { return f.title === this.state.newFolderName; }) !== -1) { alert(`An entry named ${this.state.newFolderName} already exists in the list of folders for ${this.state.selectedRfx.title}`); this.setState((current) => ({ ...current, isUpdating: false })); return; } const membersGroupExists = await RFXUtilities.doesGroupExist(this.state.newFolderMembersGroupName); if (membersGroupExists) { alert(`A group named ${this.state.newFolderMembersGroupName} already exists`); this.setState((current) => ({ ...current, isUpdating: false })); return; } const visitorsGroupExists = await RFXUtilities.doesGroupExist(this.state.newFolderVisitorsGroupName); if (visitorsGroupExists) { alert(`A group named ${this.state.newFolderVisitorsGroupName} already exists`); this.setState((current) => ({ ...current, isUpdating: false })); return; } // good to go, start doing updates // Add the new folder let folder: IFolder = await sp.web.lists.getByTitle(this.state.selectedRfx.title).rootFolder .folders.add(this.state.newFolderName) .then((f) => { return f.folder(); }) .catch((e) => { const message = `there was an error adding folder ${this.state.newFolderName} to the library ${this.state.selectedRfx.title}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!folder) return; //create the folder Members group const folderMembersGroup: ISiteGroupInfo = await sp.web.siteGroups.add({ "Title": this.state.newFolderMembersGroupName }) .then((g) => { return g.group(); }) .catch((e) => { const message = `there was an error adding the group ${this.state.newFolderMembersGroupName}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!folderMembersGroup) return; //create the folder Visitors group const folderVisitorsGroup: ISiteGroupInfo = await sp.web.siteGroups.add({ "Title": this.state.newFolderVisitorsGroupName }) .then((g) => { return g.group(); }) .catch((e) => { const message = `there was an error adding the group ${this.state.newFolderVisitorsGroupName}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!folderVisitorsGroup) return; // set the owners of the new groups if (! await RFXUtilities.setGroupOwner(folderMembersGroup.Id, this.state.selectedRfx.libraryOwnersGroupId) .then(() => { return true; }) .catch((e) => { const message = `there was an error setting the owner of group ${folderMembersGroup.Id} to group ${this.state.selectedRfx.libraryOwnersGroupId}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } if (! await RFXUtilities.setGroupOwner(folderVisitorsGroup.Id, this.state.selectedRfx.libraryOwnersGroupId) .then(() => { return true; }) .catch((e) => { const message = `there was an error setting the owner of group ${folderVisitorsGroup.Id} to group ${this.state.selectedRfx.libraryOwnersGroupId}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return false; }) ) { return; } // break role inheritance on the new folder const item: IItem = await sp.web.lists.getByTitle(this.state.selectedRfx.title).rootFolder .folders.getByName(this.state.newFolderName).getItem() .catch((e) => { debugger; const message = `there was an error the item for folder ${this.state.newFolderName} in library ${this.state.selectedRfx.title}`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return null; }); if (!item) return; await item.breakRoleInheritance(false); // give the default Onwers group Full Control access to the folder const fcRoleDefId = await RFXUtilities.getRoledefId("Full Control", this.props.roleDefinitions); await item.roleAssignments.add(this.props.siteOwnersGroup.Id, fcRoleDefId) .then((e) => { console.log(`granted owners full access to the folder`); }) .catch((e) => { const message = `error granting owners full access to the folder`; this.logError(message, e); }); // give the folder members Group access to the folder const folderMembersRoleDefId = await RFXUtilities.getRoledefId(this.props.roleDefinitionForFolderMembersOnFolder, this.props.roleDefinitions); await item.roleAssignments.add(folderMembersGroup.Id, folderMembersRoleDefId) .then((e) => { console.log(`granted folder members access to folder`); }) .catch((e) => { const message = `error granting folder members access to folder`; this.logError(message, e); }); // give the folder visitors Group access to the folder const folderVisitorsRoleDefId = await RFXUtilities.getRoledefId(this.props.roleDefinitionForFolderVisitorsOnFolder, this.props.roleDefinitions); await item.roleAssignments.add(folderVisitorsGroup.Id, folderVisitorsRoleDefId) .then((e) => { console.log(`granted folder visitors access to folder`); }) .catch((e) => { const message = `error granting folder visitors (group id ${folderVisitorsGroup.Id}) access to folder (Role definition id ${folderVisitorsRoleDefId})`; this.logError(message, e); }); // give the folderMembersGroup access to the library await RFXUtilities.grantGroupAccessToLibrary(this.state.selectedRfx.title, folderMembersGroup.Id, this.props.roleDefinitionForFolderMembersOnLibrary, this.props.roleDefinitions) .catch((e) => { const message = `error granting folder members (group id ${folderMembersGroup.Id}) access to the library ${this.state.selectedRfx.title} (roledef:${this.props.roleDefinitionForFolderMembersOnLibrary})`; this.logError(message, e); }); // give the folderVisitorsGroup access to the library await RFXUtilities.grantGroupAccessToLibrary(this.state.selectedRfx.title, folderVisitorsGroup.Id, this.props.roleDefinitionForFolderVisitorsOnLibrary, this.props.roleDefinitions) .catch((e) => { const message = `error granting folder vistors (group id ${folderVisitorsGroup.Id}) access to the library ${this.state.selectedRfx.title} (roledef:${this.props.roleDefinitionForFolderVisitorsOnLibrary})`; this.logError(message, e); }); // give the folderMembers Group access to the site await RFXUtilities.grantGroupIdAccessToSite(folderMembersGroup.Id, this.props.roleDefinitionForFolderMembersOnSite, this.props.roleDefinitions) .catch((e) => { const message = `there was an error granting access to the site to the ${this.state.newFolderMembersGroupName} group`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return; }); // give the folderVisitors Group access to the site await RFXUtilities.grantGroupIdAccessToSite(folderVisitorsGroup.Id, this.props.roleDefinitionForFolderVisitorsOnSite, this.props.roleDefinitions) .catch((e) => { const message = `there was an error granting access to the site to the ${this.state.newFolderVisitorsGroupName} group`; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return; }); // give the folder members access to the folder await item.roleAssignments.add(folderMembersGroup.Id, folderMembersRoleDefId) .then((e) => { console.log(`granted folder members access to folder`); }) .catch((e) => { const message = `error granting folder members group access to folder (role def is ${folderMembersRoleDefId}, group id is ${folderMembersGroup.Id})`; this.logError(message, e); }); // give the folder Visitors access to the folder await item.roleAssignments.add(folderVisitorsGroup.Id, folderVisitorsRoleDefId) .then((e) => { console.log(`granted folder visitors access to folder`); }) .catch((e) => { const message = `error granting folder vistors group access to folder (role def is ${folderVisitorsRoleDefId}, group id is ${folderVisitorsGroup.Id})`; this.logError(message, e); }); // give the library members group access to the folder const libraryMembersRoleDefId = await RFXUtilities.getRoledefId(this.props.roleDefinitionForLibraryMembersGroupOnFolder, this.props.roleDefinitions); await item.roleAssignments.add(this.state.selectedRfx.libraryMembersGroupId, libraryMembersRoleDefId) .then((e) => { console.log(`granted library members access to folder`); }) .catch((e) => { const message = `error granting library members access to folder`; this.logError(message, e); }); // give the library Vistors group access to the folder const libraryVisitorsRoleDefId = await RFXUtilities.getRoledefId(this.props.roleDefinitionForLibraryVisitorsGroupOnFolder, this.props.roleDefinitions); await item.roleAssignments.add(this.state.selectedRfx.libraryVisitorsGroupId, libraryVisitorsRoleDefId) .then((e) => { console.log(`granted library visitors access to folder`); }) .catch((e) => { const message = `error granting library visitors access to folder`; this.logError(message, e); }); // 27OCT2020 // remove the users direct permission await item.roleAssignments.remove(this.state.currentUserId, fcRoleDefId) .then((e) => { console.log(`removed the current users Full Control access to the folder`); }) .catch((e) => { const message = `error removing the current users Full Control access to the folder`; this.logError(message, e); }); // add an entry to the folders list to track this entry await sp.web.lists.getByTitle(this.props.rfxFoldersListTitle).items.add({ Title: this.state.newFolderName, rfxFolderMembersGroupId: folderMembersGroup.Id, rfxFolderVisitorsGroupId: folderVisitorsGroup.Id, RFxId: this.state.selectedRfx.id, }) .catch((e) => { const message = "there was an error updating the list of folders"; this.logError(message, e); this.setState((current) => ({ ...current, isUpdating: false })); return; }); this.fetchRFxFolders(this.state.selectedRfx) .then((folders) => { this.setState((current) => ({ ...current, rfxFolders: folders })); }) .catch((e) => { const message = `there was an fetching folders for library ${this.state.selectedRfx.title}`; this.logError(message, e); }); this.fetchSiteGroups(); this.setState((current) => ({ ...current, showAddNewFolder: false, isUpdating: false, newFolderName: null, newFolderSecurityGroupName: null })); } public async archiveLibrary(rfx: IRFx): Promise<boolean> { let duplicatefolder = await sp.web.lists.getByTitle(this.props.archiveLibraryTitle).rootFolder.folders.getByName(rfx.title).get() .then(() => { return Promise.resolve(true); }) .catch((e) => { return Promise.resolve(false); }); if (duplicatefolder) { alert(`A folder named ${rfx.title} already exists in the ${this.props.archiveLibraryTitle} library. You must either delete or rename that folder before you archive this library.`); return Promise.resolve(false); } let folderadded = await sp.web.folders.add(`${this.props.webServerRelativeUrl}/${this.props.archiveLibraryTitle}/${rfx.title}`) .then(() => { return Promise.resolve(true); }) .catch((e) => { this.logError(`There was an error adding a folder at ${this.props.webServerRelativeUrl}/${this.props.archiveLibraryTitle}/${rfx.title}`, e); return Promise.resolve(false); }); if (!folderadded) { return Promise.resolve(false); } let foldersCopied: Promise<boolean>[] = []; await sp.web.lists.getByTitle(rfx.title).rootFolder.folders.get() .then(async (folders) => { for (let folder of folders) { if (folder.Name !== 'Forms') { debugger; foldersCopied.push(sp.web.getFolderByServerRelativePath(folder.ServerRelativeUrl).copyByPath(`${this.props.webServerRelativeUrl}/${this.props.archiveLibraryTitle}/${rfx.title}/${folder.Name}`, true) // note that copybypath does not thow an error if you pass it a bad source path (i.e. one that does not exist) .then((result) => { return true; }) .catch((e) => { this.logError(`An error occurred copying folder ${folder.ServerRelativeUrl}. Archive has been canceled.`, e); return false; })); } } }); let allfolderscopied: boolean = await Promise.all(foldersCopied) .then(() => { return Promise.resolve(true); }) .catch(() => { return Promise.resolve(false); }); if (!allfolderscopied) { return Promise.resolve(false); } let filesCopied: Promise<boolean>[] = []; debugger; await sp.web.lists.getByTitle(rfx.title).rootFolder.files.get() .then(async (files) => { console.log(files); for (let file of files) { filesCopied.push(sp.web.getFileByServerRelativeUrl(file.ServerRelativeUrl).copyByPath(`${this.props.webServerRelativeUrl}/${this.props.archiveLibraryTitle}/${rfx.title}/${file.Name}`, true) .then(() => { return Promise.resolve(true); }) .catch((e) => { this.logError(`An error occurred copying file ${file.ServerRelativeUrl}. Archive has been canceled.`, e); return Promise.resolve(false); }) ); } }); debugger; let allfilescopied: boolean = await Promise.all(filesCopied) .then(() => { return Promise.resolve(true); }) .catch(() => { return Promise.resolve(false); }); if (!allfilescopied) { return Promise.resolve(false); } debugger; return Promise.resolve(true); } public async deleteLibrary(rfx: IRFx) { let errorDeletingLibrary = false; let folders = await this.fetchRFxFolders(rfx) .then((x) => { console.log(`fetched ${this.state.rfxFolders.length} folders for the library`); return x; }) .catch((e) => { const message = `there was an error removing the library`; this.logError(message, e); errorDeletingLibrary = true; return []; }); if (errorDeletingLibrary) return; for (const folder of folders) { await this.deleteFolder(folder) .catch((e) => { const message = `there was an error removing the folder ${folder}`; this.logError(message, e); errorDeletingLibrary = true; }); } if (errorDeletingLibrary) return; await sp.web.lists.getByTitle(rfx.title).recycle() .then((x) => { console.log(`deleted the library`); }) .catch((e) => { const message = 'there was an error removing the library'; this.logError(message, e); errorDeletingLibrary = true; return; }); if (errorDeletingLibrary) return; // delete visitors group await sp.web.siteGroups.getById(rfx.libraryVisitorsGroupId).get() .then(async (grp) => { await sp.web.siteGroups.removeById(rfx.libraryVisitorsGroupId) .then((x) => { console.log(`deleted the externall secrity group`); }) .catch((e) => { const message = `there was an error removing the external group ${rfx.libraryVisitorsGroupId}`; this.logError(message, e); errorDeletingLibrary = true; return; }); }) .catch((e) => { const message = `the external users groups with an ID of ${rfx.libraryVisitorsGroupId} does not exist`; this.logError(message, e); errorDeletingLibrary = true; return; }); if (errorDeletingLibrary) return; //delete members group await sp.web.siteGroups.getById(rfx.libraryMembersGroupId).get() .then(async (grp) => { await sp.web.siteGroups.removeById(rfx.libraryMembersGroupId) .then((x) => { console.log(`deleted the internal secrity group`); }) .catch((e) => { const message = `there was an error removing the internal group ${rfx.libraryMembersGroupId}`; this.logError(message, e); errorDeletingLibrary = true; return; }); }) .catch((e) => { const message = `the internal users groups with an ID of ${rfx.libraryMembersGroupId} does not exist`; this.logError(message, e); errorDeletingLibrary = true; return; }); if (errorDeletingLibrary) return; // delete the owners groups await sp.web.siteGroups.getById(rfx.libraryOwnersGroupId).get() .then(async (grp) => { await sp.web.siteGroups.removeById(rfx.libraryOwnersGroupId) .then((x) => { console.log(`deleted the owners secrity group`); }) .catch((e) => { const message = `there was an error removing the owner group ${rfx.libraryOwnersGroupId}`; this.logError(message, e); errorDeletingLibrary = true; return; }); }) .catch((e) => { const message = `the owners group with an ID of ${rfx.libraryOwnersGroupId} does not exist`; this.logError(message, e); errorDeletingLibrary = true; return; }); if (errorDeletingLibrary) return; await sp.web.lists.getByTitle(this.props.rfxListTitle).items.getById(rfx.id).recycle() .then((x) => { console.log(`deleted item ${rfx.id} from list ${this.props.rfxListTitle}`); }) .catch((e) => { const message = `there was an error removing row ${rfx.id} from the list ${this.props.rfxListTitle}`; this.logError(message, e); errorDeletingLibrary = true; return; }); if (errorDeletingLibrary) return; this.fetchRFxs(); } public async deleteFolder(folder: IRFxFolder): Promise<any> { let errorDeletingFolder = false; const rfx = await sp.web.lists.getByTitle(this.props.rfxListTitle) .items.getById(folder.rfxId).get() .then((item) => { console.log(`fetched row ${folder.rfxId} from the List of Libraries `); return item; }) .catch((e) => { const message = `there was an error fetching row ${folder.rfxId} from the List of Libraries `; this.logError(message, e); return null; }); if (!rfx) { return Promise.reject(`there was an error fetching row ${folder.rfxId} from the List of Libraries for folder ${folder.title} `); } await sp.web.lists.getByTitle(rfx["Title"]).rootFolder .folders.getByName(folder.title).recycle() .then((x) => { console.log(`deleted the folder ${folder.title}`); }) .catch((e) => { debugger; const message = `there was an error removing the folder ${folder.title}`; this.logError(message, e); //errorDeletingFolder = true; let's not stop the process, continue on to remove the groups }); if (errorDeletingFolder) return Promise.reject(`there was an error removing the folder ${folder.title}`); // delete Members group await sp.web.siteGroups.getById(folder.folderMembersGroupId).get() .then(async (grp) => { await sp.web.siteGroups.removeById(folder.folderMembersGroupId) .then((x) => { console.log(`deleted the Members secrity group`); }) .catch((e) => { const message = `there was an error removing the members group ${folder.folderMembersGroupId}`; this.logError(message, e); }); }) .catch((e) => { const message = `the members group with an ID of ${folder.folderMembersGroupId} does not exist`; this.logError(message, e); errorDeletingFolder = true; }); if (errorDeletingFolder) return Promise.reject(`the external users groups with an ID of ${folder.folderMembersGroupId} does not exist`); // delete Visitors group await sp.web.siteGroups.getById(folder.folderVisitorsGroupId).get() .then(async (grp) => { await sp.web.siteGroups.removeById(folder.folderVisitorsGroupId) .then((x) => { console.log(`deleted the Visitors security group`); }) .catch((e) => { const message = `there was an error removing the visitors group ${folder.folderVisitorsGroupId}`; this.logError(message, e); }); }) .catch((e) => { const message = `the visitors group with an ID of ${folder.folderVisitorsGroupId} does not exist`; this.logError(message, e); errorDeletingFolder = true; }); if (errorDeletingFolder) return Promise.reject(`the visitors group with an ID of ${folder.folderVisitorsGroupId} does not exist`); await sp.web.lists.getByTitle(this.props.rfxFoldersListTitle).items.getById(folder.id).recycle() .then((x) => { console.log(`deleted item ${folder.id} from list ${this.props.rfxFoldersListTitle}`); }) .catch((e) => { const message = `there was an error removing row ${folder.id} from the list ${this.props.rfxFoldersListTitle}`; this.logError(message, e); errorDeletingFolder = true; }); if (errorDeletingFolder) return Promise.reject(`there was an error removing row ${folder.id} from the list ${this.props.rfxFoldersListTitle}`); return Promise.resolve(); } private fetchRFxFolders(rfx: IRFx): Promise<Array<IRFxFolder>> { return sp.web.lists.getByTitle(this.props.rfxFoldersListTitle).items.filter(`RFxId eq ${rfx.id} `) .orderBy("Title") .getAll() .then((items) => { console.log(`fetched folders for rfx # ${rfx.id}`); return items.map((item) => { return { title: item.Title, id: item.Id, //the id of the listitem that holds the folder folderMembersGroupId: item.rfxFolderMembersGroupId, folderVisitorsGroupId: item.rfxFolderVisitorsGroupId, rfxId: item.RFxId, }; }); }); } public async showFolders(rfx: IRFx) { this.fetchRFxFolders(rfx) .then((folders) => { this.setState((current) => ({ ...current, rfxFolders: folders, showFolders: true, selectedRfx: rfx })); }) .catch((e) => { const message = `there was an fetching folders for library ${rfx.title}`; this.logError(message, e); }); } public async fetchRFxDrives(): Promise<Array<IDrive> | null> { let drives: Array<IDrive> = []; const client = new SPHttpClient(); return client.get(`${document.location.origin}${this.props.webServerRelativeUrl}/_api/v2.0/drives`, { headers: { } }/* as FetchOptions, but this is not required */) .then(res => { // (res: Response) Fetch's Response return res.json().then((js) => { for (let v of js.value) { drives.push({ description: v.description, id: v.id, name: v.name, webUrl: v.webUrl, driveType: v.driveType, }); } return drives; }); }) .catch((e) => { const message = `error fetching drives `; this.logError(message, e); return null; }); } public async fetchActivityDetails(driveId: string): Promise<Array<IActivity> | null> { let activities: Array<IActivity> = []; const client = new SPHttpClient(); return client.get(`${document.location.origin}${this.props.webServerRelativeUrl}/_api/v2.0/drives/${driveId}/root/activities?%24expand=driveItem(%24select%3Did%2Cname%2CwebUrl%2CparentReference%2Cfile%2Cfolder)&%24top=5000`, { headers: { } }/* as FetchOptions, but this is not required */) .then(res => { // (res: Response) Fetch's Response return res.json().then((js) => { for (let v of js.value) { activities.push({ userEmail: v.actor.user.email, userDisplayName: v.actor.user.displayName, driveItemType: v.driveItem ? v.driveItem['@odata.type'] : "", driveItemName: v.driveItem ? v.driveItem.name : "", driveItemParentReference: v.driveItem ? v.driveItem.parentReference.path : "", activityRecordedTime: new Date(v.times.recordedTime), action: Object.getOwnPropertyNames(v.action)[0] }); } return activities; }); }) .catch((e) => { const message = `error fetching activities `; this.logError(message, e); return null; }); } public async fetchRFxActivity(rfx: IRFx): Promise<Array<IActivity>> { if (!this._drives) { await this.fetchRFxDrives().then((d) => { this._drives = d; }). catch((e) => { alert(`there was an error fetching drives`); }); } if (!this._drives) return; const drive: IDrive = find(this._drives, d => { return d.name === rfx.title; }); const a = await this.fetchActivityDetails(drive.id) .then((ad) => { return ad; }). catch((e) => { alert(`there was an error fetching ACTIVITIES`); return null; }); return a; } public async showActivity(rfx: IRFx) { this.fetchRFxActivity(rfx) .then((a) => { this.setState((current) => ({ ...current, showActivity: true, activities: a, selectedRfx: rfx })); }) .catch((e) => { const message = `there was an fetching activities`; this.logError(message, e); }); } public async ArchiveAndDelete(rfx: IRFx) { this.setState((current) => ({ ...current, isUpdating: true })); let archiveSuccessful = await this.archiveLibrary(rfx); if (archiveSuccessful) { await this.deleteLibrary(rfx); } this.setState((current) => ({ ...current, isUpdating: false })); } public render(): React.ReactElement<IRequestMaintenanceProps> { const farCommandBarItems: Array<ICommandBarItemProps> = [ { key: "Delete", text: 'Delete Library', disabled: (this.state.mainSelectedItemsCount != 1), onClick: () => { if (!this.state.isUpdating) { const items = this.mainSelection.getSelection(); if (window.confirm(`Are you sure you want to delete library ${items[0]['title']} instead of archiving it?`)) { this.setState((current) => ({ ...current, isUpdating: true })); this.deleteLibrary(items[0] as IRFx); this.setState((current) => ({ ...current, isUpdating: false })); } } else { } }, iconProps: { iconName: 'Delete', } }, ]; const mainCommandBarItems: Array<ICommandBarItemProps> = []; mainCommandBarItems.push( { key: "add", text: 'Add a new Library', onClick: () => { this.setState((current) => ({ ...current, showAddNewLibrary: true, newDocLibGroupName: "", newDocLibTitle: "" })); }, iconProps: { iconName: 'Add' } }); if (this.props.enablePrivateFolders) { mainCommandBarItems.push( { key: "folders", text: 'Manage Folders', disabled: (this.state.mainSelectedItemsCount != 1), onClick: () => { if (!this.state.isUpdating) { const items = this.mainSelection.getSelection(); this.showFolders(items[0] as IRFx); } }, iconProps: { iconName: 'FolderList', } }); } if (this.props.archiveLibraryTitle) { mainCommandBarItems.push( { key: "Archive", text: 'Archive Library', disabled: (this.state.mainSelectedItemsCount != 1), onClick: () => { if (!this.state.isUpdating) { const items = this.mainSelection.getSelection(); if (window.confirm(`Are you sure you want to archive library ${items[0]['title']}`)) { this.ArchiveAndDelete(items[0] as IRFx); } } }, iconProps: { iconName: 'Archive', } }); } mainCommandBarItems.push( { key: "Activity", text: 'Recent Activity', disabled: (this.state.mainSelectedItemsCount != 1), onClick: () => { if (!this.state.isUpdating) { const items = this.mainSelection.getSelection(); this.showActivity(items[0] as IRFx); } }, iconProps: { iconName: 'Info', } }); return ( <div className={styles.requestMaintenance}> {/* ADD NEW LIBRARY PANEL */} {this.state.showAddNewLibrary && <Panel isOpen={this.state.showAddNewLibrary} onDismiss={(e) => { this.setState((current) => ({ ...current, showAddNewLibrary: false })); }} type={PanelType.medium} headerText={`Add a new Library`} > <TextField required label="Library Name" placeholder="enter library name" value={this.state.newRfxId} onChange={(e, value) => { this.setState((current) => ({ ...current, newRfxId: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, ''), newRFxOwnersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Owners", newRFxLibraryMembersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Members", newRFxLibraryVisitorsGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Visitors", newRFxLibraryOwnersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Owners", })); }} /> <DatePicker isRequired={true} label="Closing Date" placeholder="enter closing Date" value={this.state.newRFxClosingDate} onSelectDate={(date: Date) => { this.setState((current) => ({ ...current, newRFxClosingDate: date })); }} /> <TextField multiline rows={3} label="Description" placeholder="enter RFx Description" value={this.state.newRfxDescription} onChange={(e, value) => { this.setState((current) => ({ ...current, newRfxDescription: value })); }} /> <TextField required label="Contract Specialist" value={this.state.currentUserEMail} disabled={true} /> <TextField label="Owners Group Name" disabled={!this.props.allowGroupNameChanges} placeholder="enter group name" value={this.state.newRFxLibraryOwnersGroupName} onChange={(e, value) => { this.setState((current) => ({ ...current, newRFxLibraryOwnersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') })); }} /> <TextField label="Members Group Name" disabled={!this.props.allowGroupNameChanges} placeholder="enter group name" value={this.state.newRFxLibraryMembersGroupName} onChange={(e, value) => { this.setState((current) => ({ ...current, newRFxLibraryMembersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') })); }} /> <TextField label="Visitors Group Name" disabled={!this.props.allowGroupNameChanges} placeholder="enter group name" value={this.state.newRFxLibraryVisitorsGroupName} onChange={(e, value) => { this.setState((current) => ({ ...current, newRFxLibraryVisitorsGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') })); }} /> <br /> <PrimaryButton disabled={this.state.isUpdating || this.state.invalidCharacters} onClick={(e) => { this.validateAndAddLibrary(); }}>Add Library</PrimaryButton> </Panel> } {/* ADD NEW FOLDER PANEL */} {this.state.showAddNewFolder && <Panel isOpen={this.state.showAddNewFolder} onDismiss={(e) => { this.setState((current) => ({ ...current, showAddNewFolder: false })); }} type={PanelType.medium} headerText={`Add a Folder to Library ${this.state.selectedRfx.title}`} > <TextField required label="Folder Name" placeholder="enter folder name" value={this.state.newFolderName} onChange={(e, value) => { this.setState((current) => ({ ...current, newFolderName: value.replace(/[\x5B&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, ''), newFolderMembersGroupName: this.state.selectedRfx.title + " - " + value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Members", newFolderVisitorsGroupName: this.state.selectedRfx.title + " - " + value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') + " Visitors", })); }} /> <TextField disabled={!this.props.allowGroupNameChanges} label="Members Group" placeholder="enter security group name" value={this.state.newFolderMembersGroupName} onChange={(e, value) => { this.setState((current) => ({ ...current, newFolderMembersGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') })); }} /> <TextField disabled={!this.props.allowGroupNameChanges} label="Visitors Group" placeholder="enter security group name" value={this.state.newFolderVisitorsGroupName} onChange={(e, value) => { this.setState((current) => ({ ...current, newFolderVisitorsGroupName: value.replace(/[&\/\\#,+()$~% "`:;*?<>{}|^!@$']/g, '') })); }} /> <br /> <PrimaryButton disabled={this.state.isUpdating || this.state.invalidCharacters} onClick={(e) => { this.validateAndAddFolder(); }}>Add Folder</PrimaryButton> </Panel> } {/* Show FOLDERs PANEL */} {(this.state.showFolders && !this.state.showAddNewFolder) && <Panel isOpen={(this.state.showFolders && !this.state.showAddNewFolder)} type={PanelType.medium} onDismiss={(e) => { this.setState((current) => ({ ...current, showFolders: false })); }} headerText={`Folders for Rfx ${this.state.selectedRfx.title}`} > <DetailsList items={this.state.rfxFolders} columns={[ { key: 'rfx', name: 'Folder Name', fieldName: 'title', minWidth: 75, maxWidth: 200, isResizable: true, onRender: (item: IRFxFolder) => ( <Link onClick={() => { RFXUtilities.linkToFolder(item, this.props.rfxListTitle); }}>{item.title}</Link> ) }, { key: 'column5', name: 'Members Group', fieldName: 'folderMembersGroupId', minWidth: 100, maxWidth: 200, isResizable: true, onRender: (item: IRFxFolder) => ( <Link onClick={() => { RFXUtilities.linkToGroupById(item.folderMembersGroupId, this.props.webServerRelativeUrl); }}>{this.getSiteGroupName(item.folderMembersGroupId)}</Link> ) }, { key: 'column5', name: 'Visitors Group', fieldName: 'folderVisitorsGroupId', minWidth: 100, maxWidth: 200, isResizable: true, onRender: (item: IRFxFolder) => ( <Link onClick={() => { RFXUtilities.linkToGroupById(item.folderVisitorsGroupId, this.props.webServerRelativeUrl); }}>{this.getSiteGroupName(item.folderVisitorsGroupId)}</Link> ) }, { key: 'edit', name: ' ', fieldName: 'edit', minWidth: 50, maxWidth: 50, isResizable: false, onRender: (item: IRFxFolder) => ( <Icon iconName={IconNames.Delete} onClick={async () => { if (!this.state.isUpdating) { if (window.confirm(`Are you sure you want to delete folder ${item['title']} ?`)) { this.setState((current) => ({ ...current, isUpdating: true })); await this.deleteFolder(item); await this.fetchRFxFolders(this.state.selectedRfx) .then((folders) => { this.setState((current) => ({ ...current, rfxFolders: folders })); }) .catch((e) => { const message = `there was an fetching folders for library ${item.title}`; this.logError(message, e); }); this.setState((current) => ({ ...current, isUpdating: false })); } } }} /> ) }, ]} > </DetailsList> <ActionButton disabled={this.state.isUpdating} iconProps={{ iconName: IconNames.Add }} onClick={(e) => { this.setState((current) => ({ ...current, showAddNewFolder: true, newFolderName: "", newFolderSecurityGroupName: "" })); } }>Add a new Folder</ActionButton> </Panel> } {/* Show Activities PANEL */} {(this.state.showActivity) && <Panel isOpen={(this.state.showActivity)} type={PanelType.large} onDismiss={(e) => { this.setState((current) => ({ ...current, showActivity: false })); }} headerText={`Activity for Rfx ${this.state.selectedRfx.title}`} > <CSVLink data={this.state.activities} filename={'Reactivitiesquests.csv'}> <CommandBarButton iconProps={{ iconName: 'ExcelLogoInverse' }} text='Export to Excel' /> </CSVLink> <DetailsList selectionMode={SelectionMode.none} items={this.state.activities} columns={[ { key: 'userEmail', name: 'User', fieldName: 'userEmail', minWidth: 175, maxWidth: 175, isResizable: true, }, { key: 'action', name: 'Action', fieldName: 'action', minWidth: 44, maxWidth: 44, isResizable: true, }, { key: 'driveItemName', name: 'Name', fieldName: 'driveItemName', minWidth: 200, maxWidth: 200, isResizable: true, }, { key: 'activityRecordedTime', name: 'Time', fieldName: 'activityRecordedTime', minWidth: 130, maxWidth: 130, isResizable: true, onRender: (item: IActivity) => ( format(item.activityRecordedTime, "yyyyMMMd@h:m:sa") ) }, { key: 'driveItemParentReference', name: 'Folder', fieldName: 'driveItemParentReference', minWidth: 200, maxWidth: 200, isResizable: true, onRender: (item: IActivity) => ( item.driveItemParentReference.substring(item.driveItemParentReference.indexOf("root:") + 6) ) }, ]} > </DetailsList> </Panel> } {/* MAIN DISPLAY */} {this.state.isUpdating && <MessageBar messageBarType={MessageBarType.blocked}>Updating...</MessageBar> } <CommandBar items={mainCommandBarItems} farItems={farCommandBarItems} className={styles.commandBar}></CommandBar> <DetailsList selectionMode={SelectionMode.single} selection={this.mainSelection} items={this.state.rfxs} columns={[ { key: 'rfx', name: 'RFX #', fieldName: 'title', minWidth: 100, maxWidth: 100, isResizable: true, onRender: (item: IRFx) => ( <Link onClick={() => { RFXUtilities.linkToLibrary(item.title); }}>{item.title}</Link> ) }, // { // key: 'contractSpecialist', name: 'Contract Specialist', fieldName: 'contractSpecialist.EMail', minWidth: 200, maxWidth: 200, isResizable: true, // onRender: (item: IRFx) => ( // item.contractSpecialist.EMail // ) // }, { key: 'closingDate', name: 'Closing Date', fieldName: 'closingDate', minWidth: 100, maxWidth: 100, isResizable: true, onRender: (item: IRFx) => ( item.closingDate.toDateString() ) }, { key: 'description', name: 'Description', fieldName: 'description', minWidth: 100, maxWidth: 400, isResizable: true, onRender: (item: IRFx) => ( <div dangerouslySetInnerHTML={{ __html: item.description }} /> ) }, { key: 'column4', name: 'Owners', fieldName: 'libraryOwnersGroupId', minWidth: 100, maxWidth: 400, isResizable: true, onRender: (item: IRFx) => ( <Link onClick={() => { RFXUtilities.linkToGroupById(item.libraryOwnersGroupId, this.props.webServerRelativeUrl); }}>{this.getSiteGroupName(item.libraryOwnersGroupId)}</Link> ) }, { key: 'column4', name: 'Members', fieldName: 'libraryMembersGroupId', minWidth: 100, maxWidth: 400, isResizable: true, onRender: (item: IRFx) => ( <Link onClick={() => { RFXUtilities.linkToGroupById(item.libraryMembersGroupId, this.props.webServerRelativeUrl); }}>{this.getSiteGroupName(item.libraryMembersGroupId)}</Link> ) }, { key: 'column4a', name: 'Visitors', fieldName: 'libraryVisitorsGroupId', minWidth: 100, maxWidth: 400, isResizable: true, onRender: (item: IRFx) => ( <Link onClick={() => { RFXUtilities.linkToGroupById(item.libraryVisitorsGroupId, this.props.webServerRelativeUrl); }}>{this.getSiteGroupName(item.libraryVisitorsGroupId)}</Link> ) }, ]} > </DetailsList> {/* <ActionButton disabled={this.state.isUpdating} iconProps={{ iconName: IconNames.Add }} onClick={(e) => { this.setState((current) => ({ ...current, showAddNewLibrary: true, newDocLibGroupName: "", newDocLibTitle: "" })); } }>Add a new RFx library</ActionButton> */} </div> ); } }
the_stack
import { CubismIdHandle } from '../id/cubismid'; import { CubismFramework } from '../live2dcubismframework'; import { CubismModel } from '../model/cubismmodel'; import { csmVector, iterator } from '../type/csmvector'; import { CubismJson, Value } from '../utils/cubismjson'; const Epsilon = 0.001; const DefaultFadeInSeconds = 0.5; // Pose.jsonのタグ const FadeIn = 'FadeInTime'; const Link = 'Link'; const Groups = 'Groups'; const Id = 'Id'; /** * パーツの不透明度の設定 * * パーツの不透明度の管理と設定を行う。 */ export class CubismPose { /** * インスタンスの作成 * @param pose3json pose3.jsonのデータ * @param size pose3.jsonのデータのサイズ[byte] * @return 作成されたインスタンス */ public static create(pose3json: ArrayBuffer, size: number): CubismPose { const ret: CubismPose = new CubismPose(); const json: CubismJson = CubismJson.create(pose3json, size); const root: Value = json.getRoot(); // フェード時間の指定 if (!root.getValueByString(FadeIn).isNull()) { ret._fadeTimeSeconds = root .getValueByString(FadeIn) .toFloat(DefaultFadeInSeconds); if (ret._fadeTimeSeconds <= 0.0) { ret._fadeTimeSeconds = DefaultFadeInSeconds; } } // パーツグループ const poseListInfo: Value = root.getValueByString(Groups); const poseCount: number = poseListInfo.getSize(); for (let poseIndex = 0; poseIndex < poseCount; ++poseIndex) { const idListInfo: Value = poseListInfo.getValueByIndex(poseIndex); const idCount: number = idListInfo.getSize(); let groupCount = 0; for (let groupIndex = 0; groupIndex < idCount; ++groupIndex) { const partInfo: Value = idListInfo.getValueByIndex(groupIndex); const partData: PartData = new PartData(); const parameterId: CubismIdHandle = CubismFramework.getIdManager().getId( partInfo.getValueByString(Id).getRawString() ); partData.partId = parameterId; // リンクするパーツの設定 if (!partInfo.getValueByString(Link).isNull()) { const linkListInfo: Value = partInfo.getValueByString(Link); const linkCount: number = linkListInfo.getSize(); for (let linkIndex = 0; linkIndex < linkCount; ++linkIndex) { const linkPart: PartData = new PartData(); const linkId: CubismIdHandle = CubismFramework.getIdManager().getId( linkListInfo.getValueByIndex(linkIndex).getString() ); linkPart.partId = linkId; partData.link.pushBack(linkPart); } } ret._partGroups.pushBack(partData.clone()); ++groupCount; } ret._partGroupCounts.pushBack(groupCount); } CubismJson.delete(json); return ret; } /** * インスタンスを破棄する * @param pose 対象のCubismPose */ public static delete(pose: CubismPose): void { if (pose != null) { pose = null; } } /** * モデルのパラメータの更新 * @param model 対象のモデル * @param deltaTimeSeconds デルタ時間[秒] */ public updateParameters(model: CubismModel, deltaTimeSeconds: number): void { // 前回のモデルと同じでない場合は初期化が必要 if (model != this._lastModel) { // パラメータインデックスの初期化 this.reset(model); } this._lastModel = model; // 設定から時間を変更すると、経過時間がマイナスになる事があるので、経過時間0として対応 if (deltaTimeSeconds < 0.0) { deltaTimeSeconds = 0.0; } let beginIndex = 0; for (let i = 0; i < this._partGroupCounts.getSize(); i++) { const partGroupCount: number = this._partGroupCounts.at(i); this.doFade(model, deltaTimeSeconds, beginIndex, partGroupCount); beginIndex += partGroupCount; } this.copyPartOpacities(model); } /** * 表示を初期化 * @param model 対象のモデル * @note 不透明度の初期値が0でないパラメータは、不透明度を1に設定する */ public reset(model: CubismModel): void { let beginIndex = 0; for (let i = 0; i < this._partGroupCounts.getSize(); ++i) { const groupCount: number = this._partGroupCounts.at(i); for (let j: number = beginIndex; j < beginIndex + groupCount; ++j) { this._partGroups.at(j).initialize(model); const partsIndex: number = this._partGroups.at(j).partIndex; const paramIndex: number = this._partGroups.at(j).parameterIndex; if (partsIndex < 0) { continue; } model.setPartOpacityByIndex(partsIndex, j == beginIndex ? 1.0 : 0.0); model.setParameterValueByIndex(paramIndex, j == beginIndex ? 1.0 : 0.0); for (let k = 0; k < this._partGroups.at(j).link.getSize(); ++k) { this._partGroups .at(j) .link.at(k) .initialize(model); } } beginIndex += groupCount; } } /** * パーツの不透明度をコピー * * @param model 対象のモデル */ public copyPartOpacities(model: CubismModel): void { for ( let groupIndex = 0; groupIndex < this._partGroups.getSize(); ++groupIndex ) { const partData: PartData = this._partGroups.at(groupIndex); if (partData.link.getSize() == 0) { continue; // 連動するパラメータはない } const partIndex: number = this._partGroups.at(groupIndex).partIndex; const opacity: number = model.getPartOpacityByIndex(partIndex); for ( let linkIndex = 0; linkIndex < partData.link.getSize(); ++linkIndex ) { const linkPart: PartData = partData.link.at(linkIndex); const linkPartIndex: number = linkPart.partIndex; if (linkPartIndex < 0) { continue; } model.setPartOpacityByIndex(linkPartIndex, opacity); } } } /** * パーツのフェード操作を行う。 * @param model 対象のモデル * @param deltaTimeSeconds デルタ時間[秒] * @param beginIndex フェード操作を行うパーツグループの先頭インデックス * @param partGroupCount フェード操作を行うパーツグループの個数 */ public doFade( model: CubismModel, deltaTimeSeconds: number, beginIndex: number, partGroupCount: number ): void { let visiblePartIndex = -1; let newOpacity = 1.0; const phi = 0.5; const backOpacityThreshold = 0.15; // 現在、表示状態になっているパーツを取得 for (let i: number = beginIndex; i < beginIndex + partGroupCount; ++i) { const partIndex: number = this._partGroups.at(i).partIndex; const paramIndex: number = this._partGroups.at(i).parameterIndex; if (model.getParameterValueByIndex(paramIndex) > Epsilon) { if (visiblePartIndex >= 0) { break; } visiblePartIndex = i; newOpacity = model.getPartOpacityByIndex(partIndex); // 新しい不透明度を計算 newOpacity += deltaTimeSeconds / this._fadeTimeSeconds; if (newOpacity > 1.0) { newOpacity = 1.0; } } } if (visiblePartIndex < 0) { visiblePartIndex = 0; newOpacity = 1.0; } // 表示パーツ、非表示パーツの不透明度を設定する for (let i: number = beginIndex; i < beginIndex + partGroupCount; ++i) { const partsIndex: number = this._partGroups.at(i).partIndex; // 表示パーツの設定 if (visiblePartIndex == i) { model.setPartOpacityByIndex(partsIndex, newOpacity); // 先に設定 } // 非表示パーツの設定 else { let opacity: number = model.getPartOpacityByIndex(partsIndex); let a1: number; // 計算によって求められる不透明度 if (newOpacity < phi) { a1 = (newOpacity * (phi - 1)) / phi + 1.0; // (0,1),(phi,phi)を通る直線式 } else { a1 = ((1 - newOpacity) * phi) / (1.0 - phi); // (1,0),(phi,phi)を通る直線式 } // 背景の見える割合を制限する場合 const backOpacity: number = (1.0 - a1) * (1.0 - newOpacity); if (backOpacity > backOpacityThreshold) { a1 = 1.0 - backOpacityThreshold / (1.0 - newOpacity); } if (opacity > a1) { opacity = a1; // 計算の不透明度よりも大きければ(濃ければ)不透明度を上げる } model.setPartOpacityByIndex(partsIndex, opacity); } } } /** * コンストラクタ */ public constructor() { this._fadeTimeSeconds = DefaultFadeInSeconds; this._lastModel = null; this._partGroups = new csmVector<PartData>(); this._partGroupCounts = new csmVector<number>(); } _partGroups: csmVector<PartData>; // パーツグループ _partGroupCounts: csmVector<number>; // それぞれのパーツグループの個数 _fadeTimeSeconds: number; // フェード時間[秒] _lastModel: CubismModel; // 前回操作したモデル } /** * パーツにまつわるデータを管理 */ export class PartData { /** * コンストラクタ */ constructor(v?: PartData) { this.parameterIndex = 0; this.partIndex = 0; this.link = new csmVector<PartData>(); if (v != undefined) { this.partId = v.partId; for ( const ite: iterator<PartData> = v.link.begin(); ite.notEqual(v.link.end()); ite.preIncrement() ) { this.link.pushBack(ite.ptr().clone()); } } } /** * =演算子のオーバーロード */ public assignment(v: PartData): PartData { this.partId = v.partId; for ( const ite: iterator<PartData> = v.link.begin(); ite.notEqual(v.link.end()); ite.preIncrement() ) { this.link.pushBack(ite.ptr().clone()); } return this; } /** * 初期化 * @param model 初期化に使用するモデル */ public initialize(model: CubismModel): void { this.parameterIndex = model.getParameterIndex(this.partId); this.partIndex = model.getPartIndex(this.partId); model.setParameterValueByIndex(this.parameterIndex, 1); } /** * オブジェクトのコピーを生成する */ public clone(): PartData { const clonePartData: PartData = new PartData(); clonePartData.partId = this.partId; clonePartData.parameterIndex = this.parameterIndex; clonePartData.partIndex = this.partIndex; clonePartData.link = new csmVector<PartData>(); for ( let ite: iterator<PartData> = this.link.begin(); ite.notEqual(this.link.end()); ite.increment() ) { clonePartData.link.pushBack(ite.ptr().clone()); } return clonePartData; } partId: CubismIdHandle; // パーツID parameterIndex: number; // パラメータのインデックス partIndex: number; // パーツのインデックス link: csmVector<PartData>; // 連動するパラメータ } // Namespace definition for compatibility. import * as $ from './cubismpose'; // eslint-disable-next-line @typescript-eslint/no-namespace export namespace Live2DCubismFramework { export const CubismPose = $.CubismPose; export type CubismPose = $.CubismPose; export const PartData = $.PartData; export type PartData = $.PartData; }
the_stack
export interface WorldSpawn { classname: 'worldspawn' wad: string[] mapversion: number skyname: string maxRange: number message: string sounds: number light: number waveHeight: number startDark: WorldSpawnStartDark newUnit: WorldSpawnNewUnit gameTitle: WorldSpawnGameTitle defaultTeam: WorldSpawnDefaultTeam } export enum WorldSpawnStartDark { No = 0, Yes = 1 // the level will start black with fade in } export enum WorldSpawnGameTitle { No = 0, Yes = 1 // "Half-Life" will be displayed after the map loads } export enum WorldSpawnNewUnit { No = 0, Yes = 1 // All previous global triggers will be removed } export enum WorldSpawnDefaultTeam { FewestPlayers = 0, FirstTeam = 1 } export interface AiScriptedSequence { classname: 'aiscripted_sequence' m_iszEntity: string m_iszPlay: string m_flRadius: number m_flRepeat: number m_fMoveTo: AiScriptedSequenceMoveTo m_iFinishSchedule: AiScriptedSequenceFinishSchedule spawnflags: AiScriptedSequenceSpawnflags } export enum AiScriptedSequenceMoveTo { No = 0, Walk = 1, Run = 2, Instantaneous = 4, No_TurnToFace = 5 } export enum AiScriptedSequenceFinishSchedule { DefaultAI = 0, Ambush = 1 } export enum AiScriptedSequenceSpawnflags { Repeatable = 4, LeaveCorpse = 8 } export interface AmbientGeneric { classname: 'ambient_generic' origin: number[] targetName: string message: string health: number preset: AmbientGenericPreset startVolume: number fadeIn: number fadeOut: number pitch: number pitchStart: number spinUp: number spinDown: number lfoType: number lfoRate: number lfoModPitch: number lfoModVolume: number cSpinUp: number spawnFlags: AmbientGenericSpawnFlags } export enum AmbientGenericPreset { None = 0, HugeMachine = 1, BigMachine = 2, Machine = 3, SlowFadeIn = 4, FadeIn = 5, QuickFadeIn = 6, SlowPulse = 7, Pulse = 8, QuickPulse = 9, SlowOscillator = 10, Oscillator = 11, QuickOscillator = 12, GrungePitch = 13, VeryLowPitch = 14, LowPitch = 15, HighPitch = 16, VeryHighPitch = 17, ScreamingPitch = 18, OscillateSpinUpDown = 19, PulseSpinUpDown = 20, RandomPitch = 21, RandomPitchFast = 22, IncrementalSpinup = 23, Alien = 24, Bizzare = 25, PlanetX = 26, Haunted = 27 } export enum AmbientGenericSpawnFlags { PlayEverywhere = 1, SmallRadius = 2, MediumRadius = 4, LargeRadius = 8, StartSilent = 16, NotToggled = 32 } export interface Ammo357 { classname: 'ammo_357' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface Ammo9mmAR { classname: 'ammo_9mmAR' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface Ammo9mmBox { classname: 'ammo_9mmbox' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface Ammo9mmClip { classname: 'ammo_9mmclip' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface AmmoARGrenades { classname: 'ammo_ARgrenades' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface AmmoBuckShot { classname: 'ammo_buckshot' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface AmmoCrossBox { classname: 'ammo_crossbow' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface AmmoGaussClip { classname: 'ammo_gaussclip' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface AmmoRPGClip { classname: 'ammo_rpgclip' origin: number[] angles: number[] target: string targetName: string delay: number killTarget: string spawnFlags: number } export interface ButtonTarget { classname: 'button_target' target: string master: string renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] zhltLightFlags: ZHLTLightFlags lightOrigin: string spawnFlags: ButtonTargetSpawnFlags } export enum ButtonTargetSpawnFlags { UseActivates = 1, StartOn = 2 } export interface Cycler { classname: 'cycler' origin: number[] angles: number[] targetName: string model: string sequence: string renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] } export interface CyclerSprite { classname: 'cycler_sprite' origin: number[] angles: number[] targetName: string model: string framerate: number renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] } export interface CyclerWeapon { classname: 'cycler_weapon' origin: number[] angles: number[] target: string targetName: string triggerTarget: string triggerCondition: CyclerWeaponTriggerCondition model: string sequence: string renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] } export enum CyclerWeaponTriggerCondition { NoTrigger = 0, SeePlayerMadAtPlayer = 1, TakeDamage = 2, HalfHealthRemaining = 3, Death = 4, HearWorld = 7, HearPlayer = 8, HearCombat = 9, SeePlayerUnconditional = 10, SeePlayerNotInCombat = 11 } export interface CyclerWreckage { classname: 'cycler_wreckage' origin: number[] angles: number[] targetName: string model: string framerate: number scale: number renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] } export interface EnvBeam { classname: 'env_beam', renderEffect: RenderEffect renderMode: RenderMode renderAmmount: number renderColor: number[] radius: number life: number boltWidth: number noiseAmplitude: number texture: string textureScroll: number frameRate: number frameStart: number strikeTime: number damage: number spawnFlags: EnvBeamSpawnFlags } export enum EnvBeamSpawnFlags { StartOn = 1, Toggle = 2, RandomStrike = 4, Ring = 8, StartSparks = 16, EndSparks = 32, DecalEnd = 64, FadeStart = 128, FadeEnd = 256 } export enum ZHLTLightFlags { Normal = 0, EmbeddedFix = 1, OpaqueBlockLight = 2, OpaqueEmbeddedFix = 3, OpaqueConcaveFix = 6 } export enum RenderEffect { Normal = 0, SlowPulse = 1, //* Additive or Texture mode only. FastPulse = 2, //* Additive or Texture mode only. SlowWidePulse = 3, //* Additive or Texture mode only. FastWidePulse = 4, //* Additive or Texture mode only. SlowFadeAway = 5, FastFadeAway = 6, SlowBecomeSolid = 7, FastBecomeSolid = 8, SlowStrobe = 9, FastStrobe = 10, FasterStrobe = 11, SlowFlicker = 12, FastFlicker = 13, //* Constant Glow only affects the Glow rendermode. With this setting, Glow mode behaves //* exactly like Additive mode - except that (as is usual for Glow mode) the sprite isn't //* obscured by intervening sprites or models. ConstantGlow = 14, DistortModels = 15, HologramDistort = 16 } export enum RenderMode { Normal = 0, Color = 1, Texture = 2, Glow = 3, Solid = 4, Additive = 5 } const parseNumberArray = (a: string) => a.split(' ').map(b => parseFloat(b)) const parsers: { worldspawn: (entityData: {[name: string]: any}) => WorldSpawn aiscripted_sequence: (entityData: {[name: string]: any}) => AiScriptedSequence ambient_generic: (entityData: {[name: string]: any}) => AmbientGeneric ammo_357: (entityData: {[name: string]: any}) => Ammo357 ammo_9mmAR: (entityData: {[name: string]: any}) => Ammo9mmAR ammo_9mmbox: (entityData: {[name: string]: any}) => Ammo9mmBox ammo_9mmclip: (entityData: {[name: string]: any}) => Ammo9mmClip ammo_ARgrenades: (entityData: {[name: string]: any}) => AmmoARGrenades ammo_buckshot: (entityData: {[name: string]: any}) => AmmoBuckShot ammo_crossbow: (entityData: {[name: string]: any}) => AmmoCrossBox ammo_gaussclip: (entityData: {[name: string]: any}) => AmmoGaussClip ammo_rpgclip: (entityData: {[name: string]: any}) => AmmoRPGClip button_target: (entityData: {[name: string]: any}) => ButtonTarget cycler: (entityData: {[name: string]: any}) => Cycler cycler_sprite: (entityData: {[name: string]: any}) => CyclerSprite cyclear_weapon: (entityData: {[name: string]: any}) => CyclerWeapon cyclear_wreckage: (entityData: {[name: string]: any}) => CyclerWreckage env_beam: (entityData: {[name: string]: any}) => EnvBeam } = { worldspawn: (e) => ({ classname: 'worldspawn', wad: e.wad .split(';') .filter((a: string) => a.length) .map((w: string) => w.replace(/\\/g, '/')), mapversion: parseInt(e.mapversion), skyname: e.skyname, maxRange: parseFloat(e.MaxRange) || 8192, message: e.message || '', sounds: parseInt(e.sounds) || 0, light: parseInt(e.light) || 0, waveHeight: parseFloat(e.WaveHeight) || 0, startDark: parseInt(e.startdark) || 0, newUnit: parseInt(e.newunit) || 0, defaultTeam: parseInt(e.defaultteam) || 0, gameTitle: parseInt(e.gametitle) || 0 }), aiscripted_sequence: (e) => ({ classname: 'aiscripted_sequence', spawnflags: parseInt(e.spawnflags), m_iszEntity: e.m_iszEntity, m_iszPlay: e.m_iszPlay || '', m_flRadius: parseInt(e.m_flRadius) || 512, m_flRepeat: parseInt(e.m_flRepeat) || 0, m_fMoveTo: parseInt(e.m_fMoveTo) || 0, m_iFinishSchedule: parseInt(e.m_iFinishSchedule) || 0, }), ambient_generic: (e) => ({ classname: 'ambient_generic', origin: parseNumberArray(e.origin), targetName: e.targetname, message: e.message, health: parseInt(e.health) || 10, preset: parseInt(e.preset) || 0, startVolume: parseInt(e.volstart) || 0, fadeIn: parseInt(e.fadein), fadeOut: parseInt(e.fadeout), pitch: parseInt(e.pitch), pitchStart: parseInt(e.pitchstart), spinUp: parseInt(e.spinup), spinDown: parseInt(e.spindown), lfoType: parseInt(e.lfotype), lfoRate: parseInt(e.lforate), lfoModPitch: parseInt(e.lfomodpitch), lfoModVolume: parseInt(e.lfomodvolume), cSpinUp: parseInt(e.cspinup), spawnFlags: parseInt(e.spawnflags) }), ammo_357: (e) => ({ classname: 'ammo_357', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_9mmAR: (e) => ({ classname: 'ammo_9mmAR', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_9mmbox: (e) => ({ classname: 'ammo_9mmbox', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_9mmclip: (e) => ({ classname: 'ammo_9mmclip', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_ARgrenades: (e) => ({ classname: 'ammo_ARgrenades', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_buckshot: (e) => ({ classname: 'ammo_buckshot', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_crossbow: (e) => ({ classname: 'ammo_crossbow', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_gaussclip: (e) => ({ classname: 'ammo_gaussclip', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), ammo_rpgclip: (e) => ({ classname: 'ammo_rpgclip', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname || '', delay: parseInt(e.delay) || 0, killTarget: e.killtarget || '', spawnFlags: e.spawnflags || 0 }), button_target: (e) => ({ classname: 'button_target', target: e.target, master: e.master, renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0'), zhltLightFlags: parseInt(e.zhlt_lightflags) || 0, lightOrigin: e.light_origin, spawnFlags: parseInt(e.spawnflags) || 1 }), cycler: (e) => ({ classname: 'cycler', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), targetName: e.targetname, model: e.model, sequence: e.sequence || '', renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0') }), cycler_sprite: (e) => ({ classname: 'cycler_sprite', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), targetName: e.targetname, model: e.model, framerate: parseInt(e.framerate || '10'), renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0') }), cyclear_weapon: (e) => ({ classname: 'cycler_weapon', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), target: e.target, targetName: e.targetname, triggerTarget: e.TriggerTarget || '', triggerCondition: parseInt(e.TriggerCondition) || 0, model: e.model, sequence: e.sequence, renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0') }), cyclear_wreckage: (e) => ({ classname: 'cycler_wreckage', origin: parseNumberArray(e.origin), angles: parseNumberArray(e.angles), targetName: e.targetname, model: e.model, framerate: parseInt(e.framerate) || 10, scale: parseFloat(e.scale) || 1.0, renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0') }), env_beam: (e) => ({ classname: 'env_beam', renderEffect: parseInt(e.renderfx) || 0, renderMode: parseInt(e.rendermode) || 0, renderAmmount: parseInt(e.renderamt) || 255, renderColor: parseNumberArray(e.rendercolor || '0 0 0'), radius: parseFloat(e.Radius) || 256, life: parseInt(e.life) || 1, boltWidth: parseInt(e.BoltWidth) || 20, noiseAmplitude: parseInt(e.NoiseAmplitude) || 0, texture: e.texture || 'sprites/laserbeam.spr', textureScroll: parseInt(e.TextureScroll) || 35, frameRate: parseInt(e.framerate) || 0, frameStart: parseInt(e.framestart) || 0, strikeTime: parseInt(e.StrikeTime) || 1, damage: parseInt(e.damage) || 1, spawnFlags: parseInt(e.spawnflags) }) } // env_beverage (Half-Life) // env_blood (Half-Life) // env_bubbles (Half-Life) // env_explosion (Half-Life) // env_fade (Half-Life) // env_funnel (Half-Life) // env_global (Half-Life) // env_glow (Half-Life) // env_laser (Half-Life) // env_message (Half-Life) // env_render (Half-Life) // env_shake (Half-Life) // env_shooter (Half-Life) // env_sound (Half-Life) // env_spark (Half-Life) // env_sprite (Half-Life) // func_breakable (Half-Life) // func_button (Half-Life) // func_conveyor (Half-Life) // func_door (Half-Life) // func_door_rotating (Half-Life) // func_friction (Half-Life) // func_guntarget (Half-Life) // func_healthcharge (Half-Life) // func_illusionary (Half-Life) // func_ladder (Half-Life) // func_minicompo (Half-Life) // func_monsterclip (Half-Life) // func_mortar_field (Half-Life) // func_pendulum (Half-Life) // func_plat (Half-Life) // func_platrot (Half-Life) // func_pushable (Half-Life) // func_recharge (Half-Life) // func_rot_button (Half-Life) // func_rotating (Half-Life) // func_tank (Half-Life) // func_tankcontrols (Half-Life) // func_tanklaser (Half-Life) // func_tankmortar (Half-Life) // func_tankrocket (Half-Life) // func_trackautochange (Half-Life) // func_trackchange (Half-Life) // func_tracktrain (Half-Life) // func_train (Half-Life) // func_traincontrols (Half-Life) // func_wall (Half-Life) // func_wall_toggle (Half-Life) // func_water (Half-Life) // game_counter (Half-Life) // game_counter_set (Half-Life) // game_end (Half-Life) // game_player_equip (Half-Life) // game_player_hurt (Half-Life) // game_player_team (Half-Life) // game_score (Half-Life) // game_team_master (Half-Life) // game_team_set (Half-Life) // game_text (Half-Life) // game_zone_player (Half-Life) // gibshooter (Half-Life) // info_bigmomma (Half-Life) // info_intermission (Half-Life) // info_landmark (Half-Life) // info_node (Half-Life) // info_node_air (Half-Life) // info_null (Half-Life) // info_player_coop (Half-Life) // info_player_deathmatch (Half-Life) // info_player_start (Half-Life) // info_target (Half-Life) // info_teleport_destination (Half-Life) // info_texlights (Half-Life) // infodecal (Half-Life) // item_airtank (Half-Life) // item_antidote (Half-Life) // item_battery (Half-Life) // item_healthkit (Half-Life) // item_longjump (Half-Life) // item_security (Half-Life) // item_sodacan (Half-Life) // item_suit (Half-Life) // light (Half-Life) // light_environment (Half-Life) // light_spot (Half-Life) // momentary_door (Half-Life) // momentary_rot_button (Half-Life) // monster_alien_controller (Half-Life) // monster_alien_grunt (Half-Life) // monster_alien_slave (Half-Life) // monster_apache (Half-Life) // monster_babycrab (Half-Life) // monster_barnacle (Half-Life) // monster_barney (Half-Life) // monster_barney_dead (Half-Life) // monster_bigmomma (Half-Life) // monster_bloater (Half-Life) // monster_bullchicken (Half-Life) // monster_cockroach (Half-Life) // monster_flyer_flock (Half-Life) // monster_furniture (Half-Life) // monster_gargantua (Half-Life) // monster_generic (Half-Life) // monster_gman (Half-Life) // monster_grunt_repel (Half-Life) // monster_handgrenade (Half-Life) // monster_headcrab (Half-Life) // monster_hevsuit_dead (Half-Life) // monster_hgrunt_dead (Half-Life) // monster_houndeye (Half-Life) // monster_human_assassin (Half-Life) // monster_human_grunt (Half-Life) // monster_ichthyosaur (Half-Life) // monster_leech (Half-Life) // monster_miniturret (Half-Life) // monster_nihilanth (Half-Life) // monster_osprey (Half-Life) // monster_rat (Half-Life) // monster_satchelcharge (Half-Life) // monster_scientist (Half-Life) // monster_scientist_dead (Half-Life) // monster_sentry (Half-Life) // monster_sitting_scientist (Half-Life) // monster_snark (Half-Life) // monster_tentacle (Half-Life) // monster_tripmine (Half-Life) // monster_turret (Half-Life) // monster_zombie (Half-Life) // monstermaker (Half-Life) // multi_manager (Half-Life) // multisource (Half-Life) // path_corner (Half-Life) // path_track (Half-Life) // player_loadsaved (Half-Life) // player_weaponstrip (Half-Life) // scripted_sentence (Half-Life) // scripted_sequence (Half-Life) // speaker (Half-Life) // target_cdaudio (Half-Life) // trigger_auto (Half-Life) // trigger_autosave (Half-Life) // trigger_camera (Half-Life) // trigger_cdaudio (Half-Life) // trigger_changelevel (Half-Life) // trigger_changetarget (Half-Life) // trigger_counter (Half-Life) // trigger_endsection (Half-Life) // trigger_gravity (Half-Life) // trigger_hurt (Half-Life) // trigger_monsterjump (Half-Life) // trigger_multiple (Half-Life) // trigger_once (Half-Life) // trigger_push (Half-Life) // trigger_relay (Half-Life) // trigger_teleport (Half-Life) // trigger_transition (Half-Life) // weapon_357 (Half-Life) // weapon_9mmAR (Half-Life) // weapon_9mmhandgun (Half-Life) // weapon_crossbow (Half-Life) // weapon_crowbar (Half-Life) // weapon_egon (Half-Life) // weapon_gauss (Half-Life) // weapon_handgrenade (Half-Life) // weapon_hornetgun (Half-Life) // weapon_rpg (Half-Life) // weapon_satchel (Half-Life) // weapon_shotgun (Half-Life) // weapon_snark (Half-Life) // weapon_tripmine (Half-Life) // weaponbox (Half-Life) // world_items (Half-Life) // worldspawn (Half-Life) // xen_hair (Half-Life) // xen_plantlight (Half-Life) // xen_spore_large (Half-Life) // xen_spore_medium (Half-Life) // xen_spore_small (Half-Life) // xen_tree (Half-Life) export interface FuncBreakable { classname: 'func_breakable' } export interface BadEntity { classname: '!' data: any } export interface UnknownEntity { classname: '?' originalClassname: string data: any } export type Entity = WorldSpawn | FuncBreakable | BadEntity | UnknownEntity export class BspEntityParser { static parse(entities: any[]): Entity[] { const arr: Entity[] = [] for (let i = 0; i < entities.length; ++i) { const e = entities[i] if (!e.classname) { arr.push({ classname: '!', data: e }) } if ((parsers as any)[e.classname]) { arr.push((parsers as any)[e.classname](e)) } else { arr.push({ classname: '?', originalClassname: e.classname, data: e }) } } return arr } }
the_stack
import React from 'react' import { createState } from '@hookstate/core' import { createXRUI } from '../../xrui/functions/createXRUI' import { useXRUIState } from '@xrengine/engine/src/xrui/functions/useXRUIState' import { NavigateNext, NavigateBefore } from '@mui/icons-material' import { InteractableComponentType } from '../components/InteractableComponent' export function createInteractiveModalView(data: InteractableComponentType) { return createXRUI( () => <InteractiveModalView callback={data.callback}></InteractiveModalView>, createInteractiveModalState(data) ) } function createInteractiveModalState(data: InteractableComponentType) { const totalMediaUrls: any[] = [] if (data.interactionImages) for (let url of data.interactionImages) { totalMediaUrls.push({ type: 'image', path: url }) } if (data.interactionVideos) for (let url of data.interactionVideos) { totalMediaUrls.push({ type: 'video', path: url }) } if (data.interactionModels) for (let url of data.interactionModels) { totalMediaUrls.push({ type: 'model', path: url }) } let entityIndex = 0 if (data.interactionUserData && data.interactionUserData.entity) { entityIndex = data.interactionUserData.entity } return createState({ title: data.interactionName, description: data.interactionDescription, images: data.interactionImages, videos: data.interactionVideos, urls: data.interactionUrls, models: data.interactionModels, themeIndex: data.interactionThemeIndex, mediaIndex: data.mediaIndex ? data.mediaIndex : 0, entityIndex, totalMediaUrls }) } type InteractiveDetailState = ReturnType<typeof createInteractiveModalState> const InteractiveModalView = (props) => { const detailState = useXRUIState() as InteractiveDetailState const nextClick = () => { let value = detailState.mediaIndex.value value++ if (value > detailState.totalMediaUrls.value.length) value = 0 detailState.mediaIndex.set(value) if (props && props.callback) { props.callback({ mediaIndex: value, mediaData: detailState.totalMediaUrls.value, entityIndex: detailState.entityIndex.value }) } } const beforeClick = () => { let value = detailState.mediaIndex.value value-- if (value < 0) value = detailState.totalMediaUrls.value.length - 1 detailState.mediaIndex.set(value) if (props && props.callback) { props.callback({ mediaIndex: value, mediaData: detailState.totalMediaUrls.value, entityIndex: detailState.entityIndex.value }) } } const linkClick = (urls) => { for (let url of urls) { window.open(url, '_blank')!.focus() } } const renderMedia = (width, height, position?) => { let value = detailState.mediaIndex.value let entityIndex = detailState.entityIndex.value if (value < 0) value = detailState.totalMediaUrls.value.length - 1 if (value >= detailState.totalMediaUrls.value.length) value = 0 const media = detailState.totalMediaUrls.value[value] if (!media) return const data = { type: media.type, path: media.path } let imageUrl = '' if (data.type == 'image') { imageUrl = media.path } if (!position) position = 'relative' return ( <div style={{ width: width, height: height, position }} > <img src={imageUrl} width="100%" height="100%" style={{ width: '100%', height: '100%', position: 'absolute', objectFit: 'cover', display: data.type == 'image' ? 'block' : 'none' }} ></img> <video id={`interactive-ui-video-${entityIndex}`} width="100%" height="100%" style={{ width: '100%', height: 'auto', maxHeight: '100%', position: 'absolute', display: data.type == 'video' ? 'block' : 'none' }} ></video> <div xr-layer="true" id={`interactive-ui-model-${entityIndex}`} style={{ width: '100%', height: '1200px', position: 'absolute', display: data.type == 'model' ? 'block' : 'none' }} ></div> </div> ) } if (detailState.themeIndex.value?.toString() == '1') { return ( <div style={{ fontSize: '120px', backgroundColor: '#000000dd', color: 'white', fontFamily: "'Roboto', sans-serif", border: '10px solid white', borderRadius: '50px', padding: '20px', margin: '60px', boxShadow: '#fff2 0 0 30px', width: '3200px', height: '2400px', textAlign: 'center' }} > <div style={{ fontSize: '150px', padding: '50px 0px', textAlign: 'center' }} > {detailState.title.value} </div> {renderMedia('100%', '1200px')} <div style={{ padding: '50px', height: '500px', overflow: 'hidden', textAlign: 'left', fontSize: '90px' }} > {detailState.description.value} {/* Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS.Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS. */} </div> {detailState.urls.value && detailState.urls.value.length ? ( <button xr-layer="true" style={{ width: '500px', height: '200px', fontSize: '90px', backgroundColor: '#000000dd', color: 'white' }} onClick={() => { linkClick(detailState.urls.value) }} > <a>Open Link</a> </button> ) : ( <></> )} <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '1050px', right: '150px' }} onClick={nextClick} > <NavigateNext /> </button> <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '1050px', left: '150px' }} onClick={beforeClick} > <style dangerouslySetInnerHTML={{ __html: ` button:hover { border: 10px solid red; } ` }} ></style> <NavigateBefore /> </button> </div> ) } else if (detailState.themeIndex.value?.toString() == '2') { return ( <div style={{ fontSize: '120px', backgroundColor: '#000000dd', color: 'white', fontFamily: "'Roboto', sans-serif", border: '10px solid white', borderRadius: '50px', padding: '20px', margin: '60px', boxShadow: '#fff2 0 0 30px', width: '4600px', height: '1600px', textAlign: 'center' }} > <div style={{ fontSize: '150px', padding: '50px 0px', textAlign: 'center' }} > {detailState.title.value} </div> <div style={{ display: 'flex' }} > {renderMedia('2300px', '1200px', 'fixed')} <div style={{ padding: '50px', height: '1200px', overflow: 'hidden', textAlign: 'left', fontSize: '90px', width: '2200px', position: 'absolute', right: '50px' }} > {detailState.description.value} {/* Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS.Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS. */} </div> </div> {detailState.urls.value && detailState.urls.value.length ? ( <button xr-layer="true" style={{ width: '500px', height: '200px', fontSize: '90px', backgroundColor: '#000000dd', color: 'white', position: 'absolute', bottom: '200px', right: '200px' }} onClick={() => { linkClick(detailState.urls.value) }} > <a>Open Link</a> </button> ) : ( <></> )} <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '850px', left: '2050px' }} onClick={nextClick} > <NavigateNext /> </button> <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '850px', left: '150px' }} onClick={beforeClick} > <NavigateBefore /> </button> <style dangerouslySetInnerHTML={{ __html: ` button:hover { border: 10px solid red; } ` }} ></style> </div> ) } else { return ( <div style={{ fontSize: '120px', backgroundColor: '#000000dd', color: 'white', fontFamily: "'Roboto', sans-serif", border: '10px solid white', borderRadius: '50px', padding: '20px', margin: '60px', boxShadow: '#fff2 0 0 30px', width: '2000px', height: '3200px', textAlign: 'center' }} > <div style={{ fontSize: '150px', padding: '50px 0px', textAlign: 'center' }} > {detailState.title.value} </div> {renderMedia('100%', '1200px')} <div style={{ padding: '50px', height: '1000px', overflow: 'hidden', textAlign: 'left', fontSize: '90px' }} > {detailState.description.value} {/* Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS.Extend your battlefield prowess with the ROG Strix Scope Deluxe gaming keyboard featuring an ergonomic wrist rest to keep you comfortable through those marathon gaming sessions. From ASUS. */} </div> {detailState.urls.value && detailState.urls.value.length ? ( <button xr-layer="true" style={{ width: '500px', height: '200px', fontSize: '90px', backgroundColor: '#000000dd', color: 'white' }} onClick={() => { linkClick(detailState.urls.value) }} > <a>Open Link</a> </button> ) : ( <></> )} <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '1050px', right: '150px' }} onClick={nextClick} > <NavigateNext /> </button> <button xr-layer="true" style={{ width: '250px', height: '250px', position: 'absolute', top: '1050px', left: '150px' }} onClick={beforeClick} > <NavigateBefore /> </button> <style dangerouslySetInnerHTML={{ __html: ` button:hover { border: 10px solid red; } ` }} ></style> </div> ) } }
the_stack
import type { Node, ResolvedPos } from 'prosemirror-model'; import { findNodeBy } from '@/wysiwyg/util'; export interface CellInfo { offset: number; nodeSize: number; extended?: boolean; } export interface SelectionInfo { startRowIdx: number; startColIdx: number; endRowIdx: number; endColIdx: number; } interface SpanMap { [key: number]: { count: number; startSpanIdx: number }; } export interface RowInfo { [key: number]: CellInfo; length: number; rowspanMap: SpanMap; colspanMap: SpanMap; } function getSortedNumPair(valueA: number, valueB: number) { return valueA > valueB ? [valueB, valueA] : [valueA, valueB]; } export class TableOffsetMap { private table: Node; private tableRows: Node[]; private tableStartPos: number; private rowInfo: RowInfo[]; constructor(table: Node, tableRows: Node[], tableStartPos: number, rowInfo: RowInfo[]) { this.table = table; this.tableRows = tableRows; this.tableStartPos = tableStartPos; this.rowInfo = rowInfo; } static create(cellPos: ResolvedPos): TableOffsetMap | null { const table = findNodeBy(cellPos, ({ type }: Node) => type.name === 'table'); if (table) { const { node, depth } = table; const rows: Node[] = []; const tablePos = cellPos.start(depth); const thead = node.child(0); const tbody = node.child(1); const theadCellInfo = createOffsetMap(thead, tablePos); const tbodyCellInfo = createOffsetMap(tbody, tablePos + thead.nodeSize); thead.forEach((row) => rows.push(row)); tbody.forEach((row) => rows.push(row)); const map = new TableOffsetMap(node, rows, tablePos, theadCellInfo.concat(tbodyCellInfo)); return map; } return null; } get totalRowCount() { return this.rowInfo.length; } get totalColumnCount() { return this.rowInfo[0].length; } get tableStartOffset() { return this.tableStartPos; } get tableEndOffset() { return this.tableStartPos + this.table.nodeSize - 1; } getCellInfo(rowIdx: number, colIdx: number) { return this.rowInfo[rowIdx][colIdx]; } posAt(rowIdx: number, colIdx: number): number { for (let i = 0, rowStart = this.tableStartPos; ; i += 1) { const rowEnd = rowStart + this.tableRows[i].nodeSize; if (i === rowIdx) { let index = colIdx; // Skip the cells from previous row(via rowspan) while (index < this.totalColumnCount && this.rowInfo[i][index].offset < rowStart) { index += 1; } return index === this.totalColumnCount ? rowEnd : this.rowInfo[i][index].offset; } rowStart = rowEnd; } } getNodeAndPos(rowIdx: number, colIdx: number) { const cellInfo = this.rowInfo[rowIdx][colIdx]; return { node: this.table.nodeAt(cellInfo.offset - 1)!, pos: cellInfo.offset }; } extendedRowspan(rowIdx: number, colIdx: number) { const rowspanInfo = this.rowInfo[rowIdx].rowspanMap[colIdx]; return !!rowspanInfo && rowspanInfo.startSpanIdx !== rowIdx; } extendedColspan(rowIdx: number, colIdx: number) { const colspanInfo = this.rowInfo[rowIdx].colspanMap[colIdx]; return !!colspanInfo && colspanInfo.startSpanIdx !== colIdx; } getRowspanCount(rowIdx: number, colIdx: number) { const rowspanInfo = this.rowInfo[rowIdx].rowspanMap[colIdx]; return rowspanInfo ? rowspanInfo.count : 0; } getColspanCount(rowIdx: number, colIdx: number) { const colspanInfo = this.rowInfo[rowIdx].colspanMap[colIdx]; return colspanInfo ? colspanInfo.count : 0; } decreaseColspanCount(rowIdx: number, colIdx: number) { const colspanInfo = this.rowInfo[rowIdx].colspanMap[colIdx]; const startColspanInfo = this.rowInfo[rowIdx].colspanMap[colspanInfo.startSpanIdx]; startColspanInfo.count -= 1; return startColspanInfo.count; } decreaseRowspanCount(rowIdx: number, colIdx: number) { const rowspanInfo = this.rowInfo[rowIdx].rowspanMap[colIdx]; const startRowspanInfo = this.rowInfo[rowspanInfo.startSpanIdx].rowspanMap[colIdx]; startRowspanInfo.count -= 1; return startRowspanInfo.count; } getColspanStartInfo(rowIdx: number, colIdx: number) { const { colspanMap } = this.rowInfo[rowIdx]; const colspanInfo = colspanMap[colIdx]; if (colspanInfo) { const { startSpanIdx } = colspanInfo; const cellInfo = this.rowInfo[rowIdx][startSpanIdx]; return { node: this.table.nodeAt(cellInfo.offset - 1)!, pos: cellInfo.offset, startSpanIdx, count: colspanMap[startSpanIdx].count, }; } return null; } getRowspanStartInfo(rowIdx: number, colIdx: number) { const { rowspanMap } = this.rowInfo[rowIdx]; const rowspanInfo = rowspanMap[colIdx]; if (rowspanInfo) { const { startSpanIdx } = rowspanInfo; const cellInfo = this.rowInfo[startSpanIdx][colIdx]; return { node: this.table.nodeAt(cellInfo.offset - 1)!, pos: cellInfo.offset, startSpanIdx, count: this.rowInfo[startSpanIdx].rowspanMap[colIdx].count, }; } return null; } getSpannedOffsets(selectionInfo: SelectionInfo): SelectionInfo { let { startRowIdx, startColIdx, endRowIdx, endColIdx } = selectionInfo; for (let rowIdx = endRowIdx; rowIdx >= startRowIdx; rowIdx -= 1) { if (this.rowInfo[rowIdx]) { const { rowspanMap, colspanMap } = this.rowInfo[rowIdx]; for (let colIdx = endColIdx; colIdx >= startColIdx; colIdx -= 1) { const rowspanInfo = rowspanMap[colIdx]; const colspanInfo = colspanMap[colIdx]; if (rowspanInfo) { startRowIdx = Math.min(startRowIdx, rowspanInfo.startSpanIdx); } if (colspanInfo) { startColIdx = Math.min(startColIdx, colspanInfo.startSpanIdx); } } } } for (let rowIdx = startRowIdx; rowIdx <= endRowIdx; rowIdx += 1) { if (this.rowInfo[rowIdx]) { const { rowspanMap, colspanMap } = this.rowInfo[rowIdx]; for (let colIdx = startColIdx; colIdx <= endColIdx; colIdx += 1) { const rowspanInfo = rowspanMap[colIdx]; const colspanInfo = colspanMap[colIdx]; if (rowspanInfo) { endRowIdx = Math.max(endRowIdx, rowIdx + rowspanInfo.count - 1); } if (colspanInfo) { endColIdx = Math.max(endColIdx, colIdx + colspanInfo.count - 1); } } } } return { startRowIdx, startColIdx, endRowIdx, endColIdx }; } getCellStartOffset(rowIdx: number, colIdx: number) { const { offset } = this.rowInfo[rowIdx][colIdx]; return this.extendedRowspan(rowIdx, colIdx) ? this.posAt(rowIdx, colIdx) : offset; } getCellEndOffset(rowIdx: number, colIdx: number) { const { offset, nodeSize } = this.rowInfo[rowIdx][colIdx]; return this.extendedRowspan(rowIdx, colIdx) ? this.posAt(rowIdx, colIdx) : offset + nodeSize; } getCellIndex(cellPos: ResolvedPos): [rowIdx: number, colIdx: number] { for (let rowIdx = 0; rowIdx < this.totalRowCount; rowIdx += 1) { const rowInfo = this.rowInfo[rowIdx]; for (let colIdx = 0; colIdx < this.totalColumnCount; colIdx += 1) { if (rowInfo[colIdx].offset + 1 > cellPos.pos) { return [rowIdx, colIdx]; } } } return [0, 0]; } getRectOffsets(startCellPos: ResolvedPos, endCellPos = startCellPos) { if (startCellPos.pos > endCellPos.pos) { [startCellPos, endCellPos] = [endCellPos, startCellPos]; } let [startRowIdx, startColIdx] = this.getCellIndex(startCellPos); let [endRowIdx, endColIdx] = this.getCellIndex(endCellPos); [startRowIdx, endRowIdx] = getSortedNumPair(startRowIdx, endRowIdx); [startColIdx, endColIdx] = getSortedNumPair(startColIdx, endColIdx); return this.getSpannedOffsets({ startRowIdx, startColIdx, endRowIdx, endColIdx }); } } function extendPrevRowspan(prevRowInfo: RowInfo, rowInfo: RowInfo) { const { rowspanMap, colspanMap } = rowInfo; const { rowspanMap: prevRowspanMap, colspanMap: prevColspanMap } = prevRowInfo; Object.keys(prevRowspanMap).forEach((key) => { const colIdx = Number(key); const prevRowspanInfo = prevRowspanMap[colIdx]; if (prevRowspanInfo?.count > 1) { const prevColspanInfo = prevColspanMap[colIdx]; const { count, startSpanIdx } = prevRowspanInfo; rowspanMap[colIdx] = { count: count - 1, startSpanIdx }; colspanMap[colIdx] = prevColspanInfo; rowInfo[colIdx] = { ...prevRowInfo[colIdx], extended: true }; rowInfo.length += 1; } }); } function extendPrevColspan( rowspan: number, colspan: number, rowIdx: number, colIdx: number, rowInfo: RowInfo ) { const { rowspanMap, colspanMap } = rowInfo; for (let i = 1; i < colspan; i += 1) { colspanMap[colIdx + i] = { count: colspan - i, startSpanIdx: colIdx }; if (rowspan > 1) { rowspanMap[colIdx + i] = { count: rowspan, startSpanIdx: rowIdx }; } rowInfo[colIdx + i] = { ...rowInfo[colIdx] }; rowInfo.length += 1; } } function createOffsetMap(headOrBody: Node, startOffset: number, startFromBody = false) { const cellInfoMatrix: RowInfo[] = []; const beInBody = headOrBody.type.name === 'tableBody'; headOrBody.forEach((row: Node, rowOffset: number, rowIdx: number) => { // get row index based on table(not table head or table body) const rowIdxInWholeTable = beInBody && !startFromBody ? rowIdx + 1 : rowIdx; const prevRowInfo = cellInfoMatrix[rowIdx - 1]; const rowInfo: RowInfo = { rowspanMap: {}, colspanMap: {}, length: 0 }; if (prevRowInfo) { extendPrevRowspan(prevRowInfo, rowInfo); } row.forEach(({ nodeSize, attrs }: Node, cellOffset: number) => { const colspan: number = attrs.colspan ?? 1; const rowspan: number = attrs.rowspan ?? 1; let colIdx = 0; while (rowInfo[colIdx]) { colIdx += 1; } rowInfo[colIdx] = { // 2 is the sum of the front and back positions of the tag offset: startOffset + rowOffset + cellOffset + 2, nodeSize, }; rowInfo.length += 1; if (rowspan > 1) { rowInfo.rowspanMap[colIdx] = { count: rowspan, startSpanIdx: rowIdxInWholeTable }; } if (colspan > 1) { rowInfo.colspanMap[colIdx] = { count: colspan, startSpanIdx: colIdx }; extendPrevColspan(rowspan, colspan, rowIdxInWholeTable, colIdx, rowInfo); } }); cellInfoMatrix.push(rowInfo); }); return cellInfoMatrix; }
the_stack
import * as vscode from 'vscode'; import { LanguageClientOptions, RevealOutputChannelOn } from 'vscode-languageclient'; import { LanguageClient } from 'vscode-languageclient/browser'; import { SupportedLanguages } from './supportedLanguages'; import TelemetryReporter from 'vscode-extension-telemetry'; export function activate(context: vscode.ExtensionContext) { const telemetry = new TelemetryReporter(context.extension.id, context.extension.packageJSON['version'], context.extension.packageJSON['aiKey']); const supportedLanguages = new SupportedLanguages(context); let serverHandles: Promise<vscode.Disposable>[] = []; startServer(); function startServer() { serverHandles.push( _startServer(context, supportedLanguages, telemetry) ); } async function stopServers() { const oldHandles = serverHandles.slice(0); serverHandles = []; const result = await Promise.allSettled(oldHandles); for (const item of result) { if (item.status === 'fulfilled') { item.value.dispose(); } } } context.subscriptions.push(supportedLanguages); context.subscriptions.push(supportedLanguages.onDidChange(() => { // restart server when supported languages change stopServers(); startServer(); })); // stop server on deactivate context.subscriptions.push(new vscode.Disposable(stopServers)); } async function _showStatusAndInfo(context: vscode.ExtensionContext, supportedLanguages: SupportedLanguages, showCommandHint: boolean): Promise<vscode.Disposable> { const disposables: vscode.Disposable[] = []; const _mementoKey = 'didShowMessage'; const didShowExplainer = context.globalState.get(_mementoKey, false); disposables.push(vscode.commands.registerCommand('anycode.resetDidShowMessage', () => context.globalState.update(_mementoKey, false))); // --- language status item const statusItem = vscode.languages.createLanguageStatusItem('info', supportedLanguages.getSupportedLanguagesAsSelector()); disposables.push(statusItem); statusItem.severity = vscode.LanguageStatusSeverity.Warning; statusItem.text = `Partial Mode`; if (showCommandHint) { statusItem.detail = 'Language support for this file is inaccurate. $(lightbulb-autofix) Did not index all files because search [indexing is disabled](command:remoteHub.enableIndexing).'; } else { statusItem.detail = 'Language support for this file is inaccurate.'; } statusItem.command = { title: 'Learn More', command: 'vscode.open', arguments: [ vscode.Uri.parse('https://aka.ms/vscode-anycode'), ] }; // --- notifications message on interaction if (!didShowExplainer) { async function showMessage() { await vscode.window.showInformationMessage('Language support is inaccurate in this context, results may be imprecise and incomplete.'); }; const provideFyi = async () => { registrations.dispose(); context.globalState.update(_mementoKey, true); context.globalState.setKeysForSync([_mementoKey]); showMessage(); return undefined; }; const selector = supportedLanguages.getSupportedLanguagesAsSelector(); const registrations = vscode.Disposable.from( // vscode.languages.registerCompletionItemProvider(selector, { provideCompletionItems: provideFyi }), // vscode.languages.registerDocumentSymbolProvider(selector, { provideDocumentSymbols: provideFyi }), vscode.languages.registerDefinitionProvider(selector, { provideDefinition: provideFyi }), vscode.languages.registerReferenceProvider(selector, { provideReferences: provideFyi }), // vscode.languages.registerWorkspaceSymbolProvider({ provideWorkspaceSymbols: provideFyi }), ); disposables.push(registrations); } return vscode.Disposable.from(...disposables); } async function _startServer(context: vscode.ExtensionContext, supportedLanguages: SupportedLanguages, telemetry: TelemetryReporter): Promise<vscode.Disposable> { const disposables: vscode.Disposable[] = []; function _sendFeatureTelementry(name: string, language: string) { /* __GDPR__ "feature" : { "name" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" }, "language" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ telemetry.sendTelemetryEvent('feature', { name, language }); } const databaseName = context.workspaceState.get('dbName', `anycode_${Math.random().toString(32).slice(2)}`); context.workspaceState.update('dbName', databaseName); const clientOptions: LanguageClientOptions = { outputChannelName: 'anycode', revealOutputChannelOn: RevealOutputChannelOn.Never, documentSelector: supportedLanguages.getSupportedLanguagesAsSelector(), synchronize: {}, initializationOptions: { treeSitterWasmUri: vscode.Uri.joinPath(context.extensionUri, './server/tree-sitter/tree-sitter.wasm').toString(), supportedLanguages: supportedLanguages.getSupportedLanguages(), databaseName }, middleware: { provideWorkspaceSymbols(query, token, next) { _sendFeatureTelementry('workspaceSymbols', ''); return next(query, token); }, provideDefinition(document, position, token, next) { _sendFeatureTelementry('definition', document.languageId); return next(document, position, token); }, provideReferences(document, position, options, token, next) { _sendFeatureTelementry('references', document.languageId); return next(document, position, options, token); }, provideDocumentHighlights(document, position, token, next) { _sendFeatureTelementry('documentHighlights', document.languageId); return next(document, position, token); }, provideCompletionItem(document, position, context, token, next) { _sendFeatureTelementry('completions', document.languageId); return next(document, position, context, token); } } }; const serverMain = vscode.Uri.joinPath(context.extensionUri, 'dist/anycode.server.js'); const worker = new Worker(serverMain.toString()); const client = new LanguageClient('anycode', 'anycode', clientOptions, worker); disposables.push(client.start()); disposables.push(new vscode.Disposable(() => worker.terminate())); await client.onReady(); // Build a glob-patterns for languages which have features enabled, like workspace symbol search, // and use this pattern for initial file discovery and file watching const findAndSearchSuffixes: string[][] = []; for (const [info, config] of supportedLanguages.getSupportedLanguages()) { if (config.workspaceSymbols || config.references || config.definitions) { findAndSearchSuffixes.push(info.suffixes); } } const langPattern = `**/*.{${findAndSearchSuffixes.join(',')}}`; const watcher = vscode.workspace.createFileSystemWatcher(langPattern); disposables.push(watcher); // file discover and watching. in addition to text documents we annouce and provide // all matching files // workaround for https://github.com/microsoft/vscode/issues/48674 const exclude = `{${[ ...Object.keys(vscode.workspace.getConfiguration('search', null).get('exclude') ?? {}), ...Object.keys(vscode.workspace.getConfiguration('files', null).get('exclude') ?? {}) ].join(',')}}`; let size: number = Math.max(0, vscode.workspace.getConfiguration('anycode').get<number>('symbolIndexSize', 500)); const init = Promise.resolve(vscode.workspace.findFiles(langPattern, exclude, /*unlimited to count the number of files*/).then(async all => { let hasWorkspaceContents = 0; if (all.length > 50) { // we have quite some files. let's check if we can read them without limits. // for remotehub this means try to fetch the repo-tar first if (await _canInitWithoutLimits()) { size = Number.MAX_SAFE_INTEGER; hasWorkspaceContents = 1; } } const uris = all.slice(0, size); console.info(`USING ${uris.length} of ${all.length} files for ${langPattern}`); const t1 = performance.now(); await client.sendRequest('queue/init', uris.map(String)); /* __GDPR__ "init" : { "numOfFiles" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "indexSize" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "hasWorkspaceContents" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true }, "duration" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true } } */ telemetry.sendTelemetryEvent('init', undefined, { numOfFiles: all.length, // number of files found indexSize: uris.length, // number of files loaded hasWorkspaceContents, // firehose access? duration: performance.now() - t1, }); // show status/maybe notifications disposables.push(await _showStatusAndInfo(context, supportedLanguages, !hasWorkspaceContents && _isRemoteHubWorkspace())); })); // stop on server-end const initCancel = new Promise(resolve => disposables.push(new vscode.Disposable(resolve))); vscode.window.withProgress({ location: vscode.ProgressLocation.Window, title: 'Building Index...' }, () => Promise.race([init, initCancel])); disposables.push(watcher.onDidCreate(uri => { client.sendNotification('queue/add', uri.toString()); })); disposables.push(watcher.onDidDelete(uri => { client.sendNotification('queue/remove', uri.toString()); client.sendNotification('file-cache/remove', uri.toString()); })); disposables.push(watcher.onDidChange(uri => { client.sendNotification('queue/add', uri.toString()); client.sendNotification('file-cache/remove', uri.toString()); })); // serve fileRead request client.onRequest('file/read', async raw => { const uri = vscode.Uri.parse(raw); if (uri.scheme === 'vscode-notebook-cell') { // we are dealing with a notebook try { const doc = await vscode.workspace.openTextDocument(uri); return new TextEncoder().encode(doc.getText()); } catch (err) { console.warn(err); return new Uint8Array(); } } if (vscode.workspace.fs.isWritableFileSystem(uri.scheme) === undefined) { // undefined means we don't know anything about these uris return new Uint8Array(); } let data: Uint8Array; try { const stat = await vscode.workspace.fs.stat(uri); if (stat.size > 1024 ** 2) { console.warn(`IGNORING "${uri.toString()}" because it is too large (${stat.size}bytes)`); data = new Uint8Array(); } else { data = await vscode.workspace.fs.readFile(uri); } return data; } catch (err) { // graceful console.warn(err); return new Uint8Array(); } }); // file persisted index const persistUri = context.storageUri && vscode.Uri.joinPath(context.storageUri, 'anycode.db'); client.onRequest('persisted/read', async () => { if (!persistUri) { return new Uint8Array(); } try { return await vscode.workspace.fs.readFile(persistUri); } catch { return new Uint8Array(); } }); client.onRequest('persisted/write', async (data) => { if (persistUri) { await vscode.workspace.fs.writeFile(persistUri, data); } }); return vscode.Disposable.from(...disposables); } function _isRemoteHubWorkspace() { if (!vscode.extensions.getExtension('GitHub.remoteHub') && !vscode.extensions.getExtension('GitHub.remoteHub-insiders')) { return false; } return vscode.workspace.workspaceFolders?.every(folder => folder.uri.scheme === 'vscode-vfs') ?? false; } async function _canInitWithoutLimits() { if (!vscode.workspace.workspaceFolders) { // no folder -> NO fetch return false; } type RemoteHubApiStub = { loadWorkspaceContents?(workspaceUri: vscode.Uri): Promise<boolean> }; const remoteFolders = vscode.workspace.workspaceFolders.filter(folder => folder.uri.scheme === 'vscode-vfs'); if (remoteFolders.length === 0) { // no remote folders -> fetch ALL return true; } const remoteHub = vscode.extensions.getExtension<RemoteHubApiStub>('GitHub.remoteHub') ?? vscode.extensions.getExtension<RemoteHubApiStub>('GitHub.remoteHub-insiders'); const remoteHubApi = await remoteHub?.activate(); if (typeof remoteHubApi?.loadWorkspaceContents !== 'function') { // no remotehub or bad version return false; } for (const folder of remoteFolders) { if (!await remoteHubApi.loadWorkspaceContents(folder.uri)) { // remote folder -> FAILED to load one return false; } } // remote folders, all good return true; }
the_stack
declare module 'vscode' { /** * Controls how the task channel is used between tasks */ export enum TaskPanelKind { /** * Shares a panel with other tasks. This is the default. */ Shared = 1, /** * Uses a dedicated panel for this tasks. The panel is not * shared with other tasks. */ Dedicated = 2, /** * Creates a new panel whenever this task is executed. */ New = 3, } /** * Controls the behaviour of the terminal's visibility. */ export enum TaskRevealKind { /** * Always brings the terminal to front if the task is executed. */ Always = 1, /** * Only brings the terminal to front if a problem is detected executing the task * (e.g. the task couldn't be started because). */ Silent = 2, /** * The terminal never comes to front when the task is executed. */ Never = 3, } /** * Controls how the task is presented in the UI. */ export interface TaskPresentationOptions { /** * Controls whether the task output is reveal in the user interface. * Defaults to `RevealKind.Always`. */ reveal?: TaskRevealKind; /** * Controls whether the command associated with the task is echoed * in the user interface. */ echo?: boolean; /** * Controls whether the panel showing the task output is taking focus. */ focus?: boolean; /** * Controls if the task panel is used for this task only (dedicated), * shared between tasks (shared) or if a new panel is created on * every task execution (new). Defaults to `TaskInstanceKind.Shared` */ panel?: TaskPanelKind; /** * Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message. */ showReuseMessage?: boolean; /** * Controls whether the terminal is cleared before executing the task. */ clear?: boolean; } /** * A grouping for tasks. The editor by default supports the * 'Clean', 'Build', 'RebuildAll' and 'Test' group. */ export class TaskGroup { /** * The clean task group; */ static Clean: TaskGroup; /** * The build task group; */ static Build: TaskGroup; /** * The rebuild all task group; */ static Rebuild: TaskGroup; /** * The test all task group; */ static Test: TaskGroup; /** * Whether the task that is part of this group is the default for the group. * This property cannot be set through API, and is controlled by a user's task configurations. */ readonly isDefault?: boolean; /** * The ID of the task group. Is one of TaskGroup.Clean.id, TaskGroup.Build.id, TaskGroup.Rebuild.id, or TaskGroup.Test.id. */ readonly id: string; private constructor(id: string, label: string); } /** * A structure that defines a task kind in the system. * The value must be JSON-stringifyable. */ export interface TaskDefinition { /** * The task definition describing the task provided by an extension. * Usually a task provider defines more properties to identify * a task. They need to be defined in the package.json of the * extension under the 'taskDefinitions' extension point. The npm * task definition for example looks like this * ```typescript * interface NpmTaskDefinition extends TaskDefinition { * script: string; * } * ``` * * Note that type identifier starting with a '$' are reserved for internal * usages and shouldn't be used by extensions. */ readonly type: string; /** * Additional attributes of a concrete task definition. */ [name: string]: any; } /** * Options for a process execution */ export interface ProcessExecutionOptions { /** * The current working directory of the executed program or shell. * If omitted the tools current workspace root is used. */ cwd?: string; /** * The additional environment of the executed program or shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env?: { [key: string]: string }; } /** * The execution of a task happens as an external process * without shell interaction. */ export class ProcessExecution { /** * Creates a process execution. * * @param process The process to start. * @param options Optional options for the started process. */ constructor(process: string, options?: ProcessExecutionOptions); /** * Creates a process execution. * * @param process The process to start. * @param args Arguments to be passed to the process. * @param options Optional options for the started process. */ constructor(process: string, args: string[], options?: ProcessExecutionOptions); /** * The process to be executed. */ process: string; /** * The arguments passed to the process. Defaults to an empty array. */ args: string[]; /** * The process options used when the process is executed. * Defaults to undefined. */ options?: ProcessExecutionOptions; } /** * The shell quoting options. */ export interface ShellQuotingOptions { /** * The character used to do character escaping. If a string is provided only spaces * are escaped. If a `{ escapeChar, charsToEscape }` literal is provide all characters * in `charsToEscape` are escaped using the `escapeChar`. */ escape?: string | { /** * The escape character. */ escapeChar: string; /** * The characters to escape. */ charsToEscape: string; }; /** * The character used for strong quoting. The string's length must be 1. */ strong?: string; /** * The character used for weak quoting. The string's length must be 1. */ weak?: string; } /** * Options for a shell execution */ export interface ShellExecutionOptions { /** * The shell executable. */ executable?: string; /** * The arguments to be passed to the shell executable used to run the task. Most shells * require special arguments to execute a command. For example `bash` requires the `-c` * argument to execute a command, `PowerShell` requires `-Command` and `cmd` requires both * `/d` and `/c`. */ shellArgs?: string[]; /** * The shell quotes supported by this shell. */ shellQuoting?: ShellQuotingOptions; /** * The current working directory of the executed shell. * If omitted the tools current workspace root is used. */ cwd?: string; /** * The additional environment of the executed shell. If omitted * the parent process' environment is used. If provided it is merged with * the parent process' environment. */ env?: { [key: string]: string }; } /** * Defines how an argument should be quoted if it contains * spaces or unsupported characters. */ export enum ShellQuoting { /** * Character escaping should be used. This for example * uses \ on bash and ` on PowerShell. */ Escape = 1, /** * Strong string quoting should be used. This for example * uses " for Windows cmd and ' for bash and PowerShell. * Strong quoting treats arguments as literal strings. * Under PowerShell echo 'The value is $(2 * 3)' will * print `The value is $(2 * 3)` */ Strong = 2, /** * Weak string quoting should be used. This for example * uses " for Windows cmd, bash and PowerShell. Weak quoting * still performs some kind of evaluation inside the quoted * string. Under PowerShell echo "The value is $(2 * 3)" * will print `The value is 6` */ Weak = 3, } /** * A string that will be quoted depending on the used shell. */ export interface ShellQuotedString { /** * The actual string value. */ value: string; /** * The quoting style to use. */ quoting: ShellQuoting; } export class ShellExecution { /** * Creates a shell execution with a full command line. * * @param commandLine The command line to execute. * @param options Optional options for the started the shell. */ constructor(commandLine: string, options?: ShellExecutionOptions); /** * Creates a shell execution with a command and arguments. For the real execution VS Code will * construct a command line from the command and the arguments. This is subject to interpretation * especially when it comes to quoting. If full control over the command line is needed please * use the constructor that creates a `ShellExecution` with the full command line. * * @param command The command to execute. * @param args The command arguments. * @param options Optional options for the started the shell. */ constructor(command: string | ShellQuotedString, args: (string | ShellQuotedString)[], options?: ShellExecutionOptions); /** * The shell command line. Is `undefined` if created with a command and arguments. */ commandLine: string; /** * The shell command. Is `undefined` if created with a full command line. */ command: string | ShellQuotedString; /** * The shell args. Is `undefined` if created with a full command line. */ args: (string | ShellQuotedString)[]; /** * The shell options used when the command line is executed in a shell. * Defaults to undefined. */ options?: ShellExecutionOptions; } /** * The scope of a task. */ export enum TaskScope { /** * The task is a global task */ Global = 1, /** * The task is a workspace task */ Workspace = 2, } /** * Run options for a task. */ export interface RunOptions { /** * Controls whether task variables are re-evaluated on rerun. */ reevaluateOnRerun?: boolean; } /** * A task to execute */ export class Task { /** * Creates a new task. * * @param definition The task definition as defined in the taskDefinitions extension point. * @param scope Specifies the task's scope. It is either a global or a workspace task or a task for a specific workspace folder. * @param name The task's name. Is presented in the user interface. * @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface. * @param execution The process or shell execution. * @param problemMatchers the names of problem matchers to use, like '$tsc' * or '$eslint'. Problem matchers can be contributed by an extension using * the `problemMatchers` extension point. */ constructor(taskDefinition: TaskDefinition, scope: WorkspaceFolder | TaskScope.Global | TaskScope.Workspace, name: string, source: string, execution?: ProcessExecution | ShellExecution | CustomExecution, problemMatchers?: string | string[]); /** * ~~Creates a new task.~~ * * @deprecated Use the new constructors that allow specifying a scope for the task. * * @param definition The task definition as defined in the taskDefinitions extension point. * @param name The task's name. Is presented in the user interface. * @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface. * @param execution The process or shell execution. * @param problemMatchers the names of problem matchers to use, like '$tsc' * or '$eslint'. Problem matchers can be contributed by an extension using * the `problemMatchers` extension point. */ constructor(taskDefinition: TaskDefinition, name: string, source: string, execution?: ProcessExecution | ShellExecution | CustomExecution, problemMatchers?: string | string[]); /** * ~~Creates a new task.~~ * * @deprecated Use the new constructors that allow specifying a scope for the task. * * @param definition The task definition as defined in the taskDefinitions extension point. * @param name The task's name. Is presented in the user interface. * @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface. * @param execution The process or shell execution. * @param problemMatchers the names of problem matchers to use, like '$tsc' * or '$eslint'. Problem matchers can be contributed by an extension using * the `problemMatchers` extension point. */ constructor(taskDefinition: TaskDefinition, name: string, source: string, execution?: ProcessExecution | ShellExecution, problemMatchers?: string | string[]); /** * The task's definition. */ definition: TaskDefinition; /** * The task's scope. */ readonly scope?: TaskScope.Global | TaskScope.Workspace | WorkspaceFolder; /** * The task's name */ name: string; /** * A human-readable string which is rendered less prominently on a separate line in places * where the task's name is displayed. Supports rendering of {@link ThemeIcon theme icons} * via the `$(<name>)`-syntax. */ detail?: string; /** * The task's execution engine */ execution?: ProcessExecution | ShellExecution | CustomExecution; /** * Whether the task is a background task or not. */ isBackground: boolean; /** * A human-readable string describing the source of this * shell task, e.g. 'gulp' or 'npm'. */ source: string; /** * The task group this tasks belongs to. See TaskGroup * for a predefined set of available groups. * Defaults to undefined meaning that the task doesn't * belong to any special group. */ group?: TaskGroup; /** * The presentation options. Defaults to an empty literal. */ presentationOptions: TaskPresentationOptions; /** * The problem matchers attached to the task. Defaults to an empty * array. */ problemMatchers: string[]; /** * Run options for the task */ runOptions: RunOptions; } /** * A task provider allows to add tasks to the task service. * A task provider is registered via #tasks.registerTaskProvider. */ export interface TaskProvider<T extends Task = Task> { /** * Provides tasks. * @param token A cancellation token. * @return an array of tasks */ provideTasks(token: CancellationToken): ProviderResult<T[]>; /** * Resolves a task that has no {@link Task.execution `execution`} set. Tasks are * often created from information found in the `tasks.json`-file. Such tasks miss * the information on how to execute them and a task provider must fill in * the missing information in the `resolveTask`-method. This method will not be * called for tasks returned from the above `provideTasks` method since those * tasks are always fully resolved. A valid default implementation for the * `resolveTask` method is to return `undefined`. * * Note that when filling in the properties of `task`, you _must_ be sure to * use the exact same `TaskDefinition` and not create a new one. Other properties * may be changed. * * @param task The task to resolve. * @param token A cancellation token. * @return The resolved task */ resolveTask(task: T, token: CancellationToken): ProviderResult<T>; } /** * An object representing an executed Task. It can be used * to terminate a task. * * This interface is not intended to be implemented. */ export interface TaskExecution { /** * The task that got started. */ task: Task; /** * Terminates the task execution. */ terminate(): void; } /** * An event signaling the start of a task execution. * * This interface is not intended to be implemented. */ interface TaskStartEvent { /** * The task item representing the task that got started. */ readonly execution: TaskExecution; } /** * An event signaling the end of an executed task. * * This interface is not intended to be implemented. */ interface TaskEndEvent { /** * The task item representing the task that finished. */ readonly execution: TaskExecution; } /** * An event signaling the start of a process execution * triggered through a task */ export interface TaskProcessStartEvent { /** * The task execution for which the process got started. */ readonly execution: TaskExecution; /** * The underlying process id. */ readonly processId: number; } /** * An event signaling the end of a process execution * triggered through a task */ export interface TaskProcessEndEvent { /** * The task execution for which the process got started. */ readonly execution: TaskExecution; /** * The process's exit code. */ readonly exitCode: number; } export interface TaskFilter { /** * The task version as used in the tasks.json file. * The string support the package.json semver notation. */ version?: string; /** * The task type to return; */ type?: string; } /** * Namespace for tasks functionality. */ export namespace tasks { /** * Register a task provider. * * @param type The task kind type this provider is registered for. * @param provider A task provider. * @return A [disposable](#Disposable) that unregisters this provider when being disposed. */ export function registerTaskProvider(type: string, provider: TaskProvider): Disposable; /** * Fetches all tasks available in the systems. This includes tasks * from `tasks.json` files as well as tasks from task providers * contributed through extensions. * * @param filter Optional filter to select tasks of a certain type or version. */ export function fetchTasks(filter?: TaskFilter): Thenable<Task[]>; /** * Executes a task that is managed by VS Code. The returned * task execution can be used to terminate the task. * * @param task the task to execute */ export function executeTask(task: Task): Thenable<TaskExecution>; /** * The currently active task executions or an empty array. */ export const taskExecutions: ReadonlyArray<TaskExecution>; /** * Fires when a task starts. */ export const onDidStartTask: Event<TaskStartEvent>; /** * Fires when a task ends. */ export const onDidEndTask: Event<TaskEndEvent>; /** * Fires when the underlying process has been started. * This event will not fire for tasks that don't * execute an underlying process. */ export const onDidStartTaskProcess: Event<TaskProcessStartEvent>; /** * Fires when the underlying process has ended. * This event will not fire for tasks that don't * execute an underlying process. */ export const onDidEndTaskProcess: Event<TaskProcessEndEvent>; } }
the_stack
import { EaseSegment, SimpleEase } from './ParticleUtils'; import { ValueList } from './PropertyNode'; import { IPointData } from '@pixi/math'; /** * Full Emitter configuration for initializing an Emitter instance. */ export interface EmitterConfigV3 { /** * Random number configuration for picking the lifetime for each particle.. */ lifetime: RandNumber; /** * Easing to be applied to all interpolated or stepped values across the particle lifetime. */ ease?: SimpleEase | EaseSegment[]; /** * How many particles to spawn at once, each time that it is determined that particles should be spawned. * If omitted, only one particle will spawn at a time. */ particlesPerWave?: number; /** * How often to spawn particles. This is a value in seconds, so a value of 0.5 would be twice a second. */ frequency: number; /** * Defines a chance to not spawn particles. Values lower than 1 mean particles may not be spawned each time. * If omitted, particles will always spawn. */ spawnChance?: number; /** * How long to run the Emitter before it stops spawning particles. If omitted, runs forever (or until told to stop * manually). */ emitterLifetime?: number; /** * Maximum number of particles that can be alive at any given time for this emitter. */ maxParticles?: number; /** * If newly spawned particles should be added to the back of the parent container (to make them less conspicuous * as they pop in). If omitted, particles will be added to the top of the container. */ addAtBack?: boolean; /** * Default position to spawn particles from inside the parent container. */ pos: { x: number; y: number }; /** * If the emitter should start out emitting particles. If omitted, it will be treated as `true` and will emit particles * immediately. */ emit?: boolean; /** * If the Emitter should hook into PixiJS's shared ticker. If this is false or emitted, you will be responsible for * connecting it to update ticks. */ autoUpdate?: boolean; /** * The list of behaviors to apply to this emitter. See the behaviors namespace for * a list of built in behaviors. Custom behaviors may be registered with {@link Emitter.registerBehavior}. */ behaviors: BehaviorEntry[]; } /** * See {@link EmitterConfigV3.behaviors} */ export interface BehaviorEntry { /** * The behavior type, as defined as the static `type` property of a behavior class. */ type: string; /** * Configuration data specific to that behavior. */ config: any; } /** * Configuration for how to pick a random number (inclusive). */ export interface RandNumber { /** * Maximum pickable value. */ max: number; /** * Minimum pickable value. */ min: number; } /** * Converts emitter configuration from pre-5.0.0 library values into the current version. * * Example usage: * ```javascript * const emitter = new Emitter(myContainer, upgradeConfig(myOldConfig, [myTexture, myOtherTexture])); * ``` * @param config The old emitter config to upgrade. * @param art The old art values as would have been passed into the Emitter constructor or `Emitter.init()` */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function upgradeConfig(config: EmitterConfigV2|EmitterConfigV1, art: any): EmitterConfigV3 { // just ensure we aren't given any V3 config data if ('behaviors' in config) { return config; } const out: EmitterConfigV3 = { lifetime: config.lifetime, ease: config.ease, particlesPerWave: config.particlesPerWave, frequency: config.frequency, spawnChance: config.spawnChance, emitterLifetime: config.emitterLifetime, maxParticles: config.maxParticles, addAtBack: config.addAtBack, pos: config.pos, emit: config.emit, autoUpdate: config.autoUpdate, behaviors: [], }; // set up the alpha if (config.alpha) { if ('start' in config.alpha) { if (config.alpha.start === config.alpha.end) { if (config.alpha.start !== 1) { out.behaviors.push({ type: 'alphaStatic', config: { alpha: config.alpha.start }, }); } } else { const list: ValueList<number> = { list: [ { time: 0, value: config.alpha.start }, { time: 1, value: config.alpha.end }, ], }; out.behaviors.push({ type: 'alpha', config: { alpha: list }, }); } } else if (config.alpha.list.length === 1) { if (config.alpha.list[0].value !== 1) { out.behaviors.push({ type: 'alphaStatic', config: { alpha: config.alpha.list[0].value }, }); } } else { out.behaviors.push({ type: 'alpha', config: { alpha: config.alpha }, }); } } // acceleration movement if (config.acceleration && (config.acceleration.x || config.acceleration.y)) { let minStart: number; let maxStart: number; if ('start' in config.speed) { minStart = config.speed.start * (config.speed.minimumSpeedMultiplier ?? 1); maxStart = config.speed.start; } else { minStart = config.speed.list[0].value * ((config as EmitterConfigV2).minimumSpeedMultiplier ?? 1); maxStart = config.speed.list[0].value; } out.behaviors.push({ type: 'moveAcceleration', config: { accel: config.acceleration, minStart, maxStart, rotate: !config.noRotation, maxSpeed: config.maxSpeed, }, }); } // path movement else if (config.extraData?.path) { let list: ValueList<number>; let mult: number; if ('start' in config.speed) { mult = config.speed.minimumSpeedMultiplier ?? 1; if (config.speed.start === config.speed.end) { list = { list: [{ time: 0, value: config.speed.start }], }; } else { list = { list: [ { time: 0, value: config.speed.start }, { time: 1, value: config.speed.end }, ], }; } } else { list = config.speed; mult = ((config as EmitterConfigV2).minimumSpeedMultiplier ?? 1); } out.behaviors.push({ type: 'movePath', config: { path: config.extraData.path, speed: list, minMult: mult, }, }); } // normal speed movement else { if (config.speed) { if ('start' in config.speed) { if (config.speed.start === config.speed.end) { out.behaviors.push({ type: 'moveSpeedStatic', config: { min: config.speed.start * (config.speed.minimumSpeedMultiplier ?? 1), max: config.speed.start, }, }); } else { const list: ValueList<number> = { list: [ { time: 0, value: config.speed.start }, { time: 1, value: config.speed.end }, ], }; out.behaviors.push({ type: 'moveSpeed', config: { speed: list, minMult: config.speed.minimumSpeedMultiplier }, }); } } else if (config.speed.list.length === 1) { out.behaviors.push({ type: 'moveSpeedStatic', config: { min: config.speed.list[0].value * ((config as EmitterConfigV2).minimumSpeedMultiplier ?? 1), max: config.speed.list[0].value, }, }); } else { out.behaviors.push({ type: 'moveSpeed', config: { speed: config.speed, minMult: ((config as EmitterConfigV2).minimumSpeedMultiplier ?? 1) }, }); } } } // scale if (config.scale) { if ('start' in config.scale) { const mult = config.scale.minimumScaleMultiplier ?? 1; if (config.scale.start === config.scale.end) { out.behaviors.push({ type: 'scaleStatic', config: { min: config.scale.start * mult, max: config.scale.start, }, }); } else { const list: ValueList<number> = { list: [ { time: 0, value: config.scale.start }, { time: 1, value: config.scale.end }, ], }; out.behaviors.push({ type: 'scale', config: { scale: list, minMult: mult }, }); } } else if (config.scale.list.length === 1) { const mult = (config as EmitterConfigV2).minimumScaleMultiplier ?? 1; const scale = config.scale.list[0].value; out.behaviors.push({ type: 'scaleStatic', config: { min: scale * mult, max: scale }, }); } else { out.behaviors.push({ type: 'scale', config: { scale: config.scale, minMult: (config as EmitterConfigV2).minimumScaleMultiplier ?? 1 }, }); } } // color if (config.color) { if ('start' in config.color) { if (config.color.start === config.color.end) { if (config.color.start !== 'ffffff') { out.behaviors.push({ type: 'colorStatic', config: { color: config.color.start }, }); } } else { const list: ValueList<string> = { list: [ { time: 0, value: config.color.start }, { time: 1, value: config.color.end }, ], }; out.behaviors.push({ type: 'color', config: { color: list }, }); } } else if (config.color.list.length === 1) { if (config.color.list[0].value !== 'ffffff') { out.behaviors.push({ type: 'colorStatic', config: { color: config.color.list[0].value }, }); } } else { out.behaviors.push({ type: 'color', config: { color: config.color }, }); } } // rotation if (config.rotationAcceleration || config.rotationSpeed?.min || config.rotationSpeed?.max) { out.behaviors.push({ type: 'rotation', config: { accel: config.rotationAcceleration || 0, minSpeed: config.rotationSpeed?.min || 0, maxSpeed: config.rotationSpeed?.max || 0, minStart: config.startRotation?.min || 0, maxStart: config.startRotation?.max || 0, }, }); } else if (config.startRotation?.min || config.startRotation?.max) { out.behaviors.push({ type: 'rotationStatic', config: { min: config.startRotation?.min || 0, max: config.startRotation?.max || 0, }, }); } if (config.noRotation) { out.behaviors.push({ type: 'noRotation', config: {}, }); } // blend mode if (config.blendMode && config.blendMode !== 'normal') { out.behaviors.push({ type: 'blendMode', config: { blendMode: config.blendMode, }, }); } // animated if (Array.isArray(art) && typeof art[0] !== 'string' && 'framerate' in art[0]) { for (let i = 0; i < art.length; ++i) { if (art[i].framerate === 'matchLife') { art[i].framerate = -1; } } out.behaviors.push({ type: 'animatedRandom', config: { anims: art, }, }); } else if (typeof art !== 'string' && 'framerate' in art) { if (art.framerate === 'matchLife') { art.framerate = -1; } out.behaviors.push({ type: 'animatedSingle', config: { anim: art, }, }); } // ordered art else if (config.orderedArt && Array.isArray(art)) { out.behaviors.push({ type: 'textureOrdered', config: { textures: art, }, }); } // random texture else if (Array.isArray(art)) { out.behaviors.push({ type: 'textureRandom', config: { textures: art, }, }); } // single texture else { out.behaviors.push({ type: 'textureSingle', config: { texture: art, }, }); } // spawn burst if (config.spawnType === 'burst') { out.behaviors.push({ type: 'spawnBurst', config: { start: config.angleStart || 0, spacing: config.particleSpacing, // older formats bursted from a single point distance: 0, }, }); } // spawn point else if (config.spawnType === 'point') { out.behaviors.push({ type: 'spawnPoint', config: {}, }); } // spawn shape else { let shape: any; if (config.spawnType === 'ring') { shape = { type: 'torus', data: { x: config.spawnCircle.x, y: config.spawnCircle.y, radius: config.spawnCircle.r, innerRadius: config.spawnCircle.minR, affectRotation: true, }, }; } else if (config.spawnType === 'circle') { shape = { type: 'torus', data: { x: config.spawnCircle.x, y: config.spawnCircle.y, radius: config.spawnCircle.r, innerRadius: 0, affectRotation: false, }, }; } else if (config.spawnType === 'rect') { shape = { type: 'rect', data: config.spawnRect, }; } else if (config.spawnType === 'polygonalChain') { shape = { type: 'polygonalChain', data: config.spawnPolygon, }; } if (shape) { out.behaviors.push({ type: 'spawnShape', config: shape, }); } } return out; } /** * The obsolete emitter configuration format from version 3.0.0 of the library. * This type information is kept to make it easy to upgrade, but otherwise * configuration should be made as {@link EmitterConfigV3}. */ export interface EmitterConfigV2 { alpha?: ValueList<number>; speed?: ValueList<number>; minimumSpeedMultiplier?: number; maxSpeed?: number; acceleration?: {x: number; y: number}; scale?: ValueList<number>; minimumScaleMultiplier?: number; color?: ValueList<string>; startRotation?: RandNumber; noRotation?: boolean; rotationSpeed?: RandNumber; rotationAcceleration?: number; lifetime: RandNumber; blendMode?: string; ease?: SimpleEase | EaseSegment[]; extraData?: any; particlesPerWave?: number; /** * Really "rect"|"circle"|"ring"|"burst"|"point"|"polygonalChain", but that * tends to be too strict for random object creation. */ spawnType?: string; spawnRect?: {x: number; y: number; w: number; h: number}; spawnCircle?: {x: number; y: number; r: number; minR?: number}; particleSpacing?: number; angleStart?: number; spawnPolygon?: IPointData[] | IPointData[][]; frequency: number; spawnChance?: number; emitterLifetime?: number; maxParticles?: number; addAtBack?: boolean; pos: {x: number; y: number}; emit?: boolean; autoUpdate?: boolean; orderedArt?: boolean; } export interface BasicTweenable<T> { start: T; end: T; } /** * The obsolete emitter configuration format of the initial library release. * This type information is kept to maintain compatibility with the older particle tool, but otherwise * configuration should be made as {@link EmitterConfigV3}. */ export interface EmitterConfigV1 { alpha?: BasicTweenable<number>; speed?: BasicTweenable<number> & {minimumSpeedMultiplier?: number}; maxSpeed?: number; acceleration?: {x: number; y: number}; scale?: BasicTweenable<number> & {minimumScaleMultiplier?: number}; color?: BasicTweenable<string>; startRotation?: RandNumber; noRotation?: boolean; rotationSpeed?: RandNumber; rotationAcceleration?: number; lifetime: RandNumber; blendMode?: string; ease?: SimpleEase | EaseSegment[]; extraData?: any; particlesPerWave?: number; /** * Really "rect"|"circle"|"ring"|"burst"|"point"|"polygonalChain", but that * tends to be too strict for random object creation. */ spawnType?: string; spawnRect?: {x: number; y: number; w: number; h: number}; spawnCircle?: {x: number; y: number; r: number; minR?: number}; particleSpacing?: number; angleStart?: number; spawnPolygon?: IPointData[] | IPointData[][]; frequency: number; spawnChance?: number; emitterLifetime?: number; maxParticles?: number; addAtBack?: boolean; pos: {x: number; y: number}; emit?: boolean; autoUpdate?: boolean; orderedArt?: boolean; }
the_stack
import moment from 'moment'; import { isTimeTableElementsMetaActual, isAllDayElementsMetaActual, sortAppointments, findOverlappedAppointments, calculateAppointmentOffsets, unwrapGroups, calculateRectByDateAndGroupIntervals, createAppointmentForest, calculateAppointmentLeftAndWidth, isPossibleChild, findMaxReduceValue, calculateAppointmentsMetaData, isOverlappingSubTreeRoot, findChildrenMaxEndDate, prepareToGroupIntoBlocks, groupAppointmentsIntoBlocks, findBlockIndexByAppointment, findIncludedBlocks, findChildBlocks, calculateIncludedBlockMaxRight, calculateBlocksTotalSize, calculateBlocksLeftLimit, updateBlocksProportions, updateBlocksLeft, adjustByBlocks, } from './helpers'; import { VERTICAL_GROUP_ORIENTATION, HORIZONTAL_GROUP_ORIENTATION } from '../../constants'; const matchFloat = expected => ({ $$typeof: Symbol.for('jest.asymmetricMatcher'), asymmetricMatch: actual => Math.abs(actual - expected) < 0.01, toAsymmetricMatcher: () => `~${expected}`, }); describe('Appointments helpers', () => { const appointmentsBase = [ { start: moment('2018-07-02 10:00'), end: moment('2018-07-02 11:00') }, { start: moment('2018-07-02 10:30'), end: moment('2018-07-02 12:00') }, { start: moment('2018-07-01 10:00'), end: moment('2018-07-01 13:00') }, { start: moment('2018-07-01 11:30'), end: moment('2018-07-01 12:00') }, { start: moment('2018-07-01 10:00'), end: moment('2018-07-01 11:00') }, { start: moment('2018-07-02 10:40'), end: moment('2018-07-02 13:00') }, { start: moment('2018-07-03 11:00'), end: moment('2018-07-03 15:00') }, { start: moment('2018-07-02 12:00'), end: moment('2018-07-02 15:00') }, { start: moment('2018-07-02 12:00'), end: moment('2018-07-03 09:30') }, { start: moment('2018-07-01 12:00'), end: moment('2018-07-02 00:00') }, { start: moment('2018-07-01 00:00'), end: moment('2018-07-03 00:00') }, { start: moment('2018-07-01 00:00'), end: moment('2018-07-02 00:00') }, { start: moment('2018-07-02 00:00'), end: moment('2018-07-03 00:00') }, { start: moment('2018-07-01 00:00'), end: moment('2018-07-02 00:00:01') }, ]; const sortedAppointmentsBase = [ appointmentsBase[2], appointmentsBase[4], appointmentsBase[3], appointmentsBase[0], appointmentsBase[1], appointmentsBase[5], appointmentsBase[6], ]; const overlappedAppointments = [ [{ ...appointmentsBase[2] }, { ...appointmentsBase[4] }, { ...appointmentsBase[3] }], [{ ...appointmentsBase[0] }, { ...appointmentsBase[1] }, { ...appointmentsBase[5] }], [{ ...appointmentsBase[6] }], ]; const INDIRECT_CHILD_LEFT_OFFSET = 0.05; const MAX_RIGHT = 1; describe('#isTimeTableElementsMetaActual', () => { const viewCellsData = [[ {}, {}, {}, ], [ {}, {}, {}, ]]; it('should return false if getCellRects doesn\'t exist', () => { expect(isTimeTableElementsMetaActual(viewCellsData, {})) .toBeFalsy(); }); it('should return false viewCellsData\'s and getCellRects are different', () => { const timeTableElementsMeta = { getCellRects: [{}, {}, {}, {}, {}, {}, {}, {}, {}], }; expect(isTimeTableElementsMetaActual(viewCellsData, timeTableElementsMeta)) .toBeFalsy(); }); it('should return true viewCellsData\' and getCellRects\' sizes are equal', () => { const timeTableElementsMeta = { getCellRects: [{}, {}, {}, {}, {}, {}], }; expect(isTimeTableElementsMetaActual(viewCellsData, timeTableElementsMeta)) .toBeTruthy(); }); }); describe('#isAllDayElementsMetaActual', () => { const viewCellsData = [[ 'test1', 'test2', 'test3', ]]; it('should return true if getCellRects exists and its length is equal to the first row', () => { const allDayElementsMeta = { getCellRects: [ 'test1', 'test2', 'test3', ], }; expect(isAllDayElementsMetaActual( viewCellsData, allDayElementsMeta, HORIZONTAL_GROUP_ORIENTATION, 1, )) .toBeTruthy(); }); it('should return false if getCellRects does not exist', () => { expect(isAllDayElementsMetaActual(viewCellsData, {}, HORIZONTAL_GROUP_ORIENTATION, 1)) .toBeFalsy(); }); it('should return false if getCellRects length is not equal to the first row', () => { const allDayElementsMeta = { getCellRects: [ 'test1', 'test2', ], }; expect(isAllDayElementsMetaActual( viewCellsData, allDayElementsMeta, HORIZONTAL_GROUP_ORIENTATION, 1, )) .toBeFalsy(); }); it('should work with verticalGrouping', () => { const allDayElementsMeta = { getCellRects: [ 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', ], }; let groupCount = 2; expect(isAllDayElementsMetaActual( viewCellsData, allDayElementsMeta, VERTICAL_GROUP_ORIENTATION, groupCount, )) .toBeTruthy(); groupCount = 3; expect(isAllDayElementsMetaActual( viewCellsData, allDayElementsMeta, VERTICAL_GROUP_ORIENTATION, groupCount, )) .toBeFalsy(); }); }); describe('#sortAppointments', () => { it('should sort appointments', () => { const appointments = [ { start: moment('2018-07-02 10:00'), end: moment('2018-07-02 11:00') }, { start: moment('2018-07-02 10:30'), end: moment('2018-07-02 12:00') }, { start: moment('2018-07-01 10:00'), end: moment('2018-07-01 13:00') }, { start: moment('2018-07-01 11:30'), end: moment('2018-07-01 12:00') }, { start: moment('2018-07-01 10:00'), end: moment('2018-07-01 11:00') }, { start: moment('2018-07-02 10:40'), end: moment('2018-07-02 13:00') }, { start: moment('2018-07-03 11:00'), end: moment('2018-07-03 15:00') }, ]; const sortedAppointments = [ appointments[2], appointments[4], appointments[3], appointments[0], appointments[1], appointments[5], appointments[6], ]; expect(sortAppointments(appointments)) .toEqual(sortedAppointments); }); it('should place all-day appointments before ordinary ones if they are on the same day', () => { const appointments = [ { start: moment('2018-07-02 09:30'), end: moment('2018-07-02 12:00') }, { start: moment('2018-07-01 10:00'), end: moment('2018-07-01 13:00') }, { start: moment('2018-07-02 10:00'), end: moment('2018-07-02 11:00'), allDay: true }, { start: moment('2018-07-02 10:00'), end: moment('2018-07-04 11:00'), allDay: true }, ]; const sortedAppointments = [ appointments[1], appointments[3], appointments[2], appointments[0], ]; expect(sortAppointments(appointments)) .toEqual(sortedAppointments); }); }); describe('#findOverlappedAppointments', () => { it('should detect overlapped appointments', () => { expect(findOverlappedAppointments(sortedAppointmentsBase)) .toEqual(overlappedAppointments); }); it('should detect overlapped appointments depend on', () => { const sortedAppointmentsForDay = [ appointmentsBase[0], appointmentsBase[7], ]; const overlappedAppointmentsForDay = [ [{ ...appointmentsBase[0] }, { ...appointmentsBase[7] }], ]; expect(findOverlappedAppointments(sortedAppointmentsForDay, true)) .toEqual(overlappedAppointmentsForDay); }); it('should detect if appointment ends at 12:00 AM', () => { const sortedAppointmentsForDay = [ appointmentsBase[9], appointmentsBase[0], ]; expect(findOverlappedAppointments(sortedAppointmentsForDay, true)) .toEqual([ [{ ...appointmentsBase[9] }], [{ ...appointmentsBase[0] }], ]); }); }); describe('#calculateAppointmentOffsets', () => { it('should calculate appointment offset and reduce coefficient', () => { expect(calculateAppointmentOffsets(overlappedAppointments)) .toEqual([ { items: [ { ...appointmentsBase[2], offset: 0 }, { ...appointmentsBase[4], offset: 1 }, { ...appointmentsBase[3], offset: 1 }, ], reduceValue: 2, }, { items: [ { ...appointmentsBase[0], offset: 0 }, { ...appointmentsBase[1], offset: 1 }, { ...appointmentsBase[5], offset: 2 }, ], reduceValue: 3, }, { items: [ { ...appointmentsBase[6], offset: 0 }, ], reduceValue: 1, }, ]); }); it('should consider if appointments start and end at the same time', () => { const groups = [ [{ ...appointmentsBase[1] }, { ...appointmentsBase[7] }], ]; expect(calculateAppointmentOffsets(groups)) .toEqual([ { items: [ { ...appointmentsBase[1], offset: 0 }, { ...appointmentsBase[7], offset: 0 }, ], reduceValue: 1, }, ]); }); it('should calculate appointment offset depend on day', () => { const groups = [ [{ ...appointmentsBase[8] }, { ...appointmentsBase[6] }], ]; expect(calculateAppointmentOffsets(groups, true)) .toEqual([ { items: [ { ...appointmentsBase[8], offset: 0 }, { ...appointmentsBase[6], offset: 1 }, ], reduceValue: 2, }, ]); }); it('should calculate appointment offset depend on midnight', () => { const groups = [ [{ ...appointmentsBase[10] }, { ...appointmentsBase[11] }, { ...appointmentsBase[12] }], ]; expect(calculateAppointmentOffsets(groups, true)) .toEqual([ { items: [ { ...appointmentsBase[10], offset: 0 }, { ...appointmentsBase[11], offset: 1 }, { ...appointmentsBase[12], offset: 1 }, ], reduceValue: 2, }, ]); }); it('should calculate appointment offset when appointment ends after midnight', () => { const groups = [ [{ ...appointmentsBase[10] }, { ...appointmentsBase[13] }, { ...appointmentsBase[12] }], ]; expect(calculateAppointmentOffsets(groups, true)) .toEqual([ { items: [ { ...appointmentsBase[10], offset: 0 }, { ...appointmentsBase[13], offset: 1 }, { ...appointmentsBase[12], offset: 2 }, ], reduceValue: 3, }, ]); }); it('shouldn\'t change appointments but should create new ones and change them instead', () => { const groups = [[{ ...appointmentsBase[0] }]]; const result = calculateAppointmentOffsets(groups, true); expect(result[0].items[0]) .not.toBe(groups[0][0]); }); }); describe('#unwrapGroups', () => { it('should calculate appointment offset and reduce coefficient', () => { const appointmentsGroups = [ { reduceValue: 1, items: [ { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), dataItem: { startDate: new Date('2017-07-20 08:00'), endDate: new Date('2017-07-20 08:30'), }, offset: 1, }, { start: moment('2017-07-20 08:30'), end: moment('2017-07-20 09:00'), dataItem: { startDate: new Date('2017-07-20 08:30'), endDate: new Date('2017-07-20 09:30'), }, offset: 2, }, ], }, { reduceValue: 2, items: [ { start: moment('2017-04-20 08:00'), end: moment('2017-04-22 08:30'), dataItem: { startDate: new Date('2017-04-20 07:00'), endDate: new Date('2017-04-22 08:30'), }, offset: 0, }, { start: moment('2017-05-25 08:00'), end: moment('2017-05-25 09:15'), dataItem: { startDate: new Date('2017-05-25 07:59'), endDate: new Date('2017-05-25 09:17'), }, offset: 1, }, ], }, ]; expect(unwrapGroups(appointmentsGroups)) .toEqual([ { ...appointmentsGroups[0].items[0], fromPrev: false, toNext: false, reduceValue: 1, }, { ...appointmentsGroups[0].items[1], fromPrev: false, toNext: true, reduceValue: 1, }, { ...appointmentsGroups[1].items[0], fromPrev: true, toNext: false, reduceValue: 2, }, { ...appointmentsGroups[1].items[1], fromPrev: false, toNext: true, reduceValue: 2, }, ]); }); }); describe('#calculateRectByDateAndGroupIntervals', () => { it('should work with horizontal', () => { const rectByDatesMock = jest.fn(); rectByDatesMock.mockImplementation(() => ({ top: 10, left: 0, height: 50, width: 99, parentWidth: 300, })); const type = { growDirection: 'horizontal' }; const rectByDatesMeta = {}; const intervals = [[ { start: moment('2018-09-12 10:00'), end: moment('2018-09-13 10:00'), dataItem: 'a' }, { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 15:00'), dataItem: 'b' }, ]]; const rects = calculateRectByDateAndGroupIntervals( type, intervals, rectByDatesMock, rectByDatesMeta, ); expect(rects) .toHaveLength(2); expect(rects[0]) .toMatchObject({ top: 35, height: 25, left: 0, width: 33, dataItem: 'b', type: 'horizontal', }); expect(rects[1]) .toMatchObject({ top: 10, height: 25, left: 0, width: 33, dataItem: 'a', type: 'horizontal', }); }); it('should work with old vertical', () => { const rectByDatesMock = jest.fn(); rectByDatesMock.mockImplementation(() => ({ top: 10, left: 0, height: 50, width: 99, parentWidth: 300, })); const type = { growDirection: 'vertical' }; const rectByDatesMeta = { cellDuration: 30, placeAppointmentsNextToEachOther: true }; const intervals = [[ { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:10'), dataItem: 'a' }, { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:30'), dataItem: 'b' }, { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:35'), dataItem: 'c' }, ]]; const rects = calculateRectByDateAndGroupIntervals( type, intervals, rectByDatesMock, rectByDatesMeta, ); expect(rects) .toHaveLength(3); expect(rects[0]) .toMatchObject({ top: 10, height: 50, left: 22, width: 11, dataItem: 'a', type: 'vertical', durationType: 'short', }); expect(rects[1]) .toMatchObject({ top: 10, height: 50, left: 11, width: 11, dataItem: 'b', type: 'vertical', durationType: 'middle', }); expect(rects[2]) .toMatchObject({ top: 10, height: 50, left: 0, width: 11, dataItem: 'c', type: 'vertical', durationType: 'long', }); }); it('should work with vertical', () => { const rectByDatesMock = jest.fn(); rectByDatesMock.mockImplementation(() => ({ top: 10, left: 0, height: 50, width: 99, parentWidth: 300, })); const type = { growDirection: 'vertical' }; const rectByDatesMeta = { cellDuration: 30 }; const intervals = [[ { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:10'), dataItem: 'a' }, { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:30'), dataItem: 'b' }, { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 10:35'), dataItem: 'c' }, ]]; const rects = calculateRectByDateAndGroupIntervals( type, intervals, rectByDatesMock, rectByDatesMeta, ); expect(rects) .toHaveLength(3); expect(rects[0]) .toMatchObject({ top: 10, height: 50, left: 0, width: matchFloat(18.33), dataItem: 'c', type: 'vertical', durationType: 'long', }); expect(rects[1]) .toMatchObject({ top: 10, height: 50, left: 11, width: matchFloat(18.33), dataItem: 'b', type: 'vertical', durationType: 'middle', }); expect(rects[2]) .toMatchObject({ top: 10, height: 50, left: matchFloat(22), width: matchFloat(11), dataItem: 'a', type: 'vertical', durationType: 'short', }); }); it('should work with separated by start date vertical', () => { const rectByDatesMock = jest.fn(); rectByDatesMock.mockImplementation(() => ({ top: 10, left: 0, height: 50, width: 99, parentWidth: 300, })); const type = { growDirection: 'vertical' }; const rectByDatesMeta = { cellDuration: 30 }; const intervals = [[ { start: moment('2018-09-12 10:00'), end: moment('2018-09-12 15:00'), dataItem: 'a' }, { start: moment('2018-09-12 11:00'), end: moment('2018-09-12 12:30'), dataItem: 'b' }, ]]; const rects = calculateRectByDateAndGroupIntervals( type, intervals, rectByDatesMock, rectByDatesMeta, ); expect(rects) .toHaveLength(2); expect(rects[0]) .toMatchObject({ top: 10, height: 50, left: 0, width: matchFloat(33), dataItem: 'a', type: 'vertical', durationType: 'long', }); expect(rects[1]) .toMatchObject({ top: 10, height: 50, left: matchFloat(1.65), width: matchFloat(31.35), dataItem: 'b', type: 'vertical', durationType: 'long', }); }); it('should group 2 all-day appointments if the first ends on the same day as the second starts, but earlier', () => { const rectByDatesMock = jest.fn(); rectByDatesMock.mockImplementation(() => ({ top: 10, left: 0, height: 50, width: 99, parentWidth: 300, })); const type = { growDirection: 'horizontal', multiline: false }; const rectByDatesMeta = {}; const intervals = [[ { start: moment('2018-09-12 10:00'), end: moment('2018-09-13 10:00'), dataItem: 'a' }, { start: moment('2018-09-13 11:00'), end: moment('2018-09-14 15:00'), dataItem: 'b' }, ]]; const rects = calculateRectByDateAndGroupIntervals( type, intervals, rectByDatesMock, rectByDatesMeta, ); expect(rects) .toHaveLength(2); expect(rects[0]) .toMatchObject({ top: 35, height: 25, left: 0, width: 33, dataItem: 'b', type: 'horizontal', }); expect(rects[1]) .toMatchObject({ top: 10, height: 25, left: 0, width: 33, dataItem: 'a', type: 'horizontal', }); }); }); describe('#createAppointmentForest', () => { const CELL_DURATION = 30; it('should create a single tree if items.length === 1', () => { const appointmentGroups = [{ reduceValue: 1, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), dataItem: {}, offset: 0, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, }]; expect(createAppointmentForest(appointmentGroups, CELL_DURATION)) .toEqual([{ items: expectedItems, reduceValue: 1, roots: [0], }]); }); it('should create a tree with a direct child (whose start is not later than parent\'s start plus cell duration)', () => { const appointmentGroups = [{ reduceValue: 2, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), dataItem: { id: 0 }, offset: 0, }, { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), dataItem: { id: 1 }, offset: 1, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [1], treeDepth: 1, hasDirectChild: true, isDirectChild: false, }, { data: appointmentGroups[0].items[1], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: true, parent: 0, }]; const result = createAppointmentForest(appointmentGroups, CELL_DURATION); expect(result[0].items) .toHaveLength(2); expect(result) .toEqual([{ items: expectedItems, reduceValue: 2, roots: [0], }]); }); it('should create a tree with an indirect child (whose start is later than parent\'s start plus cell duration)', () => { const appointmentGroups = [{ reduceValue: 2, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 09:00'), dataItem: { id: 0 }, offset: 0, }, { start: moment('2017-07-20 08:30'), end: moment('2017-07-20 09:00'), dataItem: { id: 1 }, offset: 1, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [1], treeDepth: 1, hasDirectChild: false, isDirectChild: false, }, { data: appointmentGroups[0].items[1], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, parent: 0, }]; const result = createAppointmentForest(appointmentGroups, CELL_DURATION); expect(result[0].items) .toHaveLength(2); expect(result) .toEqual([{ items: expectedItems, reduceValue: 2, roots: [0], }]); }); it('should create a forest with 2 roots', () => { const appointmentGroups = [{ reduceValue: 2, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 09:00'), dataItem: { id: 0 }, offset: 0, }, { start: moment('2017-07-20 08:30'), end: moment('2017-07-20 10:00'), dataItem: { id: 1 }, offset: 1, }, { start: moment('2017-07-20 09:00'), end: moment('2017-07-20 10:00'), dataItem: { id: 2 }, offset: 0, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [1], treeDepth: 1, hasDirectChild: false, isDirectChild: false, }, { data: appointmentGroups[0].items[1], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, parent: 0, }, { data: appointmentGroups[0].items[2], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, }]; const result = createAppointmentForest(appointmentGroups, CELL_DURATION); expect(result[0].items) .toHaveLength(3); expect(result) .toEqual([{ items: expectedItems, reduceValue: 2, roots: [0, 2], }]); }); it('should create a forest and correctly assign parents and children props ' + 'when there are appointments with smaller offset between a parent and its child', () => { // The last appointment's parent should be the appointment with id = 1 const appointmentGroups = [{ reduceValue: 3, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 09:00'), dataItem: { id: 0 }, offset: 0, }, { start: moment('2017-07-20 08:30'), end: moment('2017-07-20 12:00'), dataItem: { id: 1 }, offset: 1, }, { start: moment('2017-07-20 09:00'), end: moment('2017-07-20 10:00'), dataItem: { id: 2 }, offset: 0, }, { start: moment('2017-07-20 09:00'), end: moment('2017-07-20 10:00'), dataItem: { id: 3 }, offset: 2, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [1], treeDepth: 2, hasDirectChild: false, isDirectChild: false, }, { data: appointmentGroups[0].items[1], children: [3], treeDepth: 1, hasDirectChild: false, isDirectChild: false, parent: 0, }, { data: appointmentGroups[0].items[2], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, }, { data: appointmentGroups[0].items[3], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, parent: 1, }]; const result = createAppointmentForest(appointmentGroups, CELL_DURATION); expect(result[0].items) .toHaveLength(4); expect(result) .toEqual([{ items: expectedItems, reduceValue: 3, roots: [0, 2], }]); }); it('should work correctly when there are several children', () => { const appointmentGroups = [{ reduceValue: 2, items: [{ start: moment('2017-07-20 08:00'), end: moment('2017-07-20 12:00'), dataItem: { id: 0 }, offset: 0, }, { start: moment('2017-07-20 08:29'), end: moment('2017-07-20 09:00'), dataItem: { id: 1 }, offset: 1, }, { start: moment('2017-07-20 10:30'), end: moment('2017-07-20 11:00'), dataItem: { id: 2 }, offset: 1, }], }]; const expectedItems = [{ data: appointmentGroups[0].items[0], children: [1, 2], treeDepth: 1, hasDirectChild: true, isDirectChild: false, }, { data: appointmentGroups[0].items[1], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: true, parent: 0, }, { data: appointmentGroups[0].items[2], children: [], treeDepth: 0, hasDirectChild: false, isDirectChild: false, parent: 0, }]; const result = createAppointmentForest(appointmentGroups, CELL_DURATION); expect(result[0].items) .toHaveLength(3); expect(result) .toEqual([{ items: expectedItems, reduceValue: 2, roots: [0], }]); }); }); describe('#isPossibleChild', () => { const baseAppointments = [ { data: { start: moment('2018-07-02 10:00'), end: moment('2018-07-02 11:00'), offset: 0 } }, { data: { start: moment('2018-07-02 10:30'), end: moment('2018-07-02 12:00'), offset: 1 } }, { data: { start: moment('2018-07-01 10:30'), end: moment('2018-07-01 13:30'), offset: 2 } }, ]; it('should return true if this appointment or one of the following may be a child', () => { const { end: parentEnd, end: parentOFfset } = baseAppointments[0].data; expect(isPossibleChild(baseAppointments, 1, parentEnd, parentOFfset)) .toBe(true); expect(isPossibleChild(baseAppointments, 2, parentEnd, parentOFfset)) .toBe(true); }); it('should return false if the appointment with provided index does not exist', () => { const { end: parentEnd, end: parentOFfset } = baseAppointments[0].data; expect(isPossibleChild(baseAppointments, 3, parentEnd, parentOFfset)) .toBe(false); }); it('should return false if appointment\'s start is after parent\'s end', () => { const appointments = [ ...baseAppointments, { data: { start: moment('2018-07-02 13:00'), end: moment('2018-07-02 14:00'), offset: 3 } }, ]; const { end: parentEnd, end: parentOFfset } = appointments[1].data; expect(isPossibleChild(appointments, 3, parentEnd, parentOFfset)) .toBe(false); }); it('should return false if appointment\'s offset is equal to that of the parent', () => { const appointments = [ ...baseAppointments, { data: { start: moment('2018-07-02 11:00'), end: moment('2018-07-02 12:00'), offset: 0 } }, ]; const { end: parentEnd, end: parentOFfset } = appointments[0].data; expect(isPossibleChild(appointments, 3, parentEnd, parentOFfset)) .toBe(false); }); }); describe('#findMaxReduceValue', () => { it('should work', () => { const appointmentGroups = [ { reduceValue: 3 }, { reduceValue: 5 }, { reduceValue: 2 }, { reduceValue: 7 }, ]; expect(findMaxReduceValue(appointmentGroups)) .toBe(7); }); }); describe('#calculateAppointmentLeftAndWidth', () => { it('should work when there are no parent and no direct children', () => { const appointment = { hasDirectChild: false, parent: undefined, children: [], }; expect(calculateAppointmentLeftAndWidth( [], undefined, appointment, MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: 0, width: 1 }); }); it('should work when appointment has no parent but has a direct child', () => { const appointment = { hasDirectChild: true, parent: undefined, treeDepth: 1, children: [], }; expect(calculateAppointmentLeftAndWidth( [], undefined, appointment, MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: 0, width: matchFloat(0.5) }); }); it('should work when appointment is a direct child, has a parent and does not have direct children', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 0.5 }, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 0, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.5), width: matchFloat(0.5) }); }); it('should work when appointment is not a direct child, has a parent and does not have direct children', () => { const appointments = [{ hasDirectChild: false, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 1 }, }, { hasDirectChild: false, isDirectChild: false, treeDepth: 0, children: [], parent: 0, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.05), width: matchFloat(0.95) }); }); // tslint:disable-next-line: max-line-length it('should work when appointment is not a direct child, has a parent, which has a direct child', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 1 }, }, { hasDirectChild: false, isDirectChild: false, treeDepth: 0, children: [], parent: 0, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.05), width: matchFloat(0.95) }); }); // tslint:disable-next-line: max-line-length it('should work when appointment is a direct child, has a parent and has direct children', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 0.33 }, }, { hasDirectChild: true, isDirectChild: true, treeDepth: 1, children: [2], parent: 0, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.33), width: matchFloat(0.33) }); }); it('should work when appointment is not a direct child, has a parent and does not have direct children', () => { const appointments = [{ hasDirectChild: false, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 1 }, }, { hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [2], parent: 0, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.05), width: matchFloat(0.475) }); }); it('should work when appointment is not a direct child, does not have direct children and has a parent, which has a direct child', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 1 }, }, { hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [2], parent: 0, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.05), width: matchFloat(0.475) }); }); it('should take into account maxRight', () => { const appointment = { hasDirectChild: false, parent: undefined, children: [], }; expect(calculateAppointmentLeftAndWidth( [], undefined, appointment, 0.5, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: 0, width: 0.5 }); }); it('should take into account indirectChildLeft', () => { const appointments = [{ hasDirectChild: false, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 1 }, }, { hasDirectChild: false, isDirectChild: false, treeDepth: 0, children: [], parent: 0, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, 0.03, undefined, )) .toEqual({ left: matchFloat(0.03), width: matchFloat(0.97) }); }); it('should take into account defaultLeft', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 0.5 }, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 0, }]; const defaultLeft = 0.95; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, defaultLeft, )) .toEqual({ left: matchFloat(0.95), width: matchFloat(0.05) }); }); it('should ignore defaultLeft if it is less than calculated left', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 1, children: [1], data: { left: 0, width: 0.5 }, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 0, }]; const defaultLeft = 0.33; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, defaultLeft, )) .toEqual({ left: matchFloat(0.5), width: matchFloat(0.5) }); }); it('should work with block indexes', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 0.33 }, }, { hasDirectChild: true, isDirectChild: true, treeDepth: 1, children: [2], parent: 0, blockIndex: 1, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, blockIndex: 1, }]; expect(calculateAppointmentLeftAndWidth( appointments, undefined, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.33), width: matchFloat(0.33) }); }); it('should work with blocks', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 0.33 }, }, { hasDirectChild: true, isDirectChild: true, treeDepth: 1, children: [2], parent: 0, blockIndex: 1, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, blockIndex: 2, }]; const blocks = [ { includedInto: undefined }, { includedInto: undefined }, { includedInto: undefined }, ]; expect(calculateAppointmentLeftAndWidth( appointments, blocks, appointments[1], MAX_RIGHT, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.33), width: matchFloat(0.33) }); }); it('should work with blocks and custom maxRight', () => { const appointments = [{ hasDirectChild: true, isDirectChild: false, treeDepth: 2, children: [1], data: { left: 0, width: 0.33 }, }, { hasDirectChild: true, isDirectChild: true, treeDepth: 1, children: [2], parent: 0, blockIndex: 1, }, { hasDirectChild: false, isDirectChild: true, treeDepth: 0, children: [], parent: 1, blockIndex: 2, }]; const blocks = [ { includedInto: undefined }, { includedInto: undefined }, { includedInto: undefined }, ]; expect(calculateAppointmentLeftAndWidth( appointments, blocks, appointments[1], 0.9, INDIRECT_CHILD_LEFT_OFFSET, undefined, )) .toEqual({ left: matchFloat(0.33), width: matchFloat(0.57) }); }); }); describe('#calculateAppointmentsMetaData', () => { it('should work when there is only root', () => { const appointmentForest = [{ roots: [0], items: [{ data: {}, hasDirectChild: false, isDirectChild: false, children: [], treeDepth: 0, }], reduceValue: 1, }]; expect(calculateAppointmentsMetaData(appointmentForest, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ ...appointmentForest[0], items: [{ ...appointmentForest[0].items[0], data: { left: 0, width: 1 }, }], }]); }); it('should work with children', () => { const appointmentForest = [{ roots: [0], items: [{ data: {}, hasDirectChild: true, isDirectChild: false, children: [1, 2], treeDepth: 2, }, { data: {}, hasDirectChild: false, isDirectChild: true, children: [], treeDepth: 0, parent: 0, }, { data: {}, hasDirectChild: true, isDirectChild: false, children: [3], treeDepth: 1, parent: 0, }, { data: {}, hasDirectChild: false, isDirectChild: true, children: [], treeDepth: 0, parent: 2, }], reduceValue: 3, }]; expect(calculateAppointmentsMetaData(appointmentForest, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ ...appointmentForest[0], items: [{ ...appointmentForest[0].items[0], data: { left: 0, width: matchFloat(0.33) }, }, { ...appointmentForest[0].items[1], data: { left: matchFloat(0.33), width: matchFloat(0.67) }, }, { ...appointmentForest[0].items[2], data: { left: matchFloat(0.05), width: matchFloat(0.475) }, }, { ...appointmentForest[0].items[3], data: { left: matchFloat(0.525), width: matchFloat(0.475) }, }], }]); }); it('should work with several roots', () => { const appointmentForest = [{ roots: [0, 2], items: [{ data: {}, hasDirectChild: true, isDirectChild: false, children: [1], treeDepth: 1, }, { data: {}, hasDirectChild: false, isDirectChild: true, children: [], treeDepth: 0, parent: 0, }, { data: {}, hasDirectChild: false, isDirectChild: false, children: [], treeDepth: 0, }], reduceValue: 2, }]; expect(calculateAppointmentsMetaData(appointmentForest, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ ...appointmentForest[0], items: [{ ...appointmentForest[0].items[0], data: { left: 0, width: matchFloat(0.5) }, }, { ...appointmentForest[0].items[1], data: { left: matchFloat(0.5), width: matchFloat(0.5) }, }, { ...appointmentForest[0].items[2], data: { left: 0, width: 1 }, }], }]); }); it('should work if all roots have children', () => { const appointmentForest = [{ roots: [0, 2], items: [{ data: {}, hasDirectChild: true, isDirectChild: false, children: [1], treeDepth: 1, }, { data: {}, hasDirectChild: false, isDirectChild: true, children: [], treeDepth: 0, parent: 0, }, { data: {}, hasDirectChild: false, isDirectChild: false, children: [3], treeDepth: 1, }, { data: {}, hasDirectChild: false, isDirectChild: false, children: [], treeDepth: 0, parent: 2, }], reduceValue: 2, }]; expect(calculateAppointmentsMetaData(appointmentForest, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ ...appointmentForest[0], items: [{ ...appointmentForest[0].items[0], data: { left: 0, width: matchFloat(0.5) }, }, { ...appointmentForest[0].items[1], data: { left: matchFloat(0.5), width: matchFloat(0.5) }, }, { ...appointmentForest[0].items[2], data: { left: 0, width: 1 }, }, { ...appointmentForest[0].items[3], data: { left: matchFloat(0.05), width: matchFloat(0.95) }, }], }]); }); }); describe('#findChildrenMaxEndDate', () => { it('should return max end date from the chosen appointment and its children', () => { const appointments = [ { data: { end: moment('2020-05-06 16:00') }, children: [1] }, { data: { end: moment('2020-05-06 16:40') }, children: [2, 3, 4] }, { data: { end: moment('2020-05-06 16:20') }, children: [] }, { data: { end: moment('2020-05-06 16:50') }, children: [] }, { data: { end: moment('2020-05-06 16:30') }, children: [] }, ]; expect(findChildrenMaxEndDate(appointments, appointments[0])) .toEqual(moment('2020-05-06 16:50')); }); }); describe('#isOverlappingSubTreeRoot', () => { it('should return false if nextAppointment\'s offset is greater then current', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 6 } }; expect(isOverlappingSubTreeRoot(appointment, nextAppointment, undefined, undefined)) .toBe(false); }); it('should return false if nextAppointment is already an overlappingSubTreeRoot', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3 }, overlappingSubTreeRoot: true }; expect(isOverlappingSubTreeRoot(appointment, nextAppointment, undefined, undefined)) .toBe(false); }); it('should return false if nextAppointment\'s maxOffset is less than offset', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3 }, overlappingSubTreeRoot: false, maxOffset: 4 }; expect(isOverlappingSubTreeRoot(appointment, nextAppointment, undefined, undefined)) .toBe(false); }); it('should return false if nextAppointment\'s offset is greater than that of the previous subTreeRoot', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3 }, overlappingSubTreeRoot: false }; const previousSubTreeRoot = { data: { offset: 2 } }; expect(isOverlappingSubTreeRoot(appointment, nextAppointment, previousSubTreeRoot, undefined)) .toBe(false); }); it('should return false if nextAppointment\'s start is before than block end', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3, start: moment('2020-05-06 16:00') }, overlappingSubTreeRoot: false, }; const previousSubTreeRoot = { data: { offset: 4 } }; const blockEnd = moment('2020-05-06 18:00'); expect(isOverlappingSubTreeRoot(appointment, nextAppointment, previousSubTreeRoot, blockEnd)) .toBe(false); }); it('should return true if 1) there is no previous sub tree root, ' + '2) next offset is less than current offset, 3) next appointment is not overlapping subtree root and ' + '4) next appointment\'s maxOffset is undefined', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3, start: moment('2020-05-06 16:00') }, overlappingSubTreeRoot: false, }; const previousSubTreeRoot = undefined; const blockEnd = moment('2020-05-06 18:00'); expect(isOverlappingSubTreeRoot(appointment, nextAppointment, previousSubTreeRoot, blockEnd)) .toBe(true); }); it('should return true if 1) there is no previous sub tree root, ' + '2) next offset is less than current offset, 3) next appointment is not overlapping subtree root and ' + '4) next appointment\'s maxOffset is greater than or equal to current offset', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3, start: moment('2020-05-06 16:00') }, overlappingSubTreeRoot: false, maxOffset: 5, }; const previousSubTreeRoot = undefined; const blockEnd = moment('2020-05-06 18:00'); expect(isOverlappingSubTreeRoot(appointment, nextAppointment, previousSubTreeRoot, blockEnd)) .toBe(true); }); it('should return true if 1) previous subtree root\'s offset is greater than or equal to nextAppointment\'s offset, ' + '2) next offset is less than current offset, 3) next appointment is not overlapping subtree root, ' + '4) next appointment\'s maxOffset is greater than or equal to current offset and ' + '5) block end date is before next appointment\'s start', () => { const appointment = { data: { offset: 5 } }; const nextAppointment = { data: { offset: 3, start: moment('2020-05-06 19:00') }, overlappingSubTreeRoot: false, maxOffset: 5, }; const previousSubTreeRoot = { data: { offset: 4 } }; const blockEnd = moment('2020-05-06 18:00'); expect(isOverlappingSubTreeRoot(appointment, nextAppointment, previousSubTreeRoot, blockEnd)) .toBe(true); }); }); describe('#prepareToGroupIntoBlocks', () => { it('should not find overlapping subtree roots', () => { const appointmentForest = [{ reduceValue: 2, items: [{ data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), offset: 0, }, children: [1], }, { data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), offset: 1, }, children: [], parent: 0, }], }]; const expectedItems = [{ ...appointmentForest[0].items[0], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[1], overlappingSubTreeRoots: [], }]; expect(prepareToGroupIntoBlocks(appointmentForest)) .toEqual([{ ...appointmentForest[0], items: expectedItems, }]); }); it('should find one overlapping subtree roots', () => { const appointmentForest = [{ reduceValue: 2, items: [ { data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), offset: 0, }, children: [1], }, { data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 11:30'), offset: 1, }, children: [], parent: 0, }, // should be an overlapping subtree root because it overlaps the second appointment // and its offset is less than second appointment's offset { data: { start: moment('2017-07-20 09:00'), end: moment('2017-07-20 11:00'), offset: 0, }, children: [], }], }]; const expectedItems = [{ ...appointmentForest[0].items[0], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[1], overlappingSubTreeRoots: [2], }, { ...appointmentForest[0].items[2], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, maxOffset: 1, }]; expect(prepareToGroupIntoBlocks(appointmentForest)) .toEqual([{ ...appointmentForest[0], items: expectedItems, }]); }); it('should work when there are several overlapping subtree roots', () => { const appointmentForest = [{ reduceValue: 3, items: [ { data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 09:30'), offset: 0, }, children: [1], }, { data: { start: moment('2017-07-20 08:00'), end: moment('2017-07-20 08:30'), offset: 1, }, children: [2], parent: 0, }, { data: { start: moment('2017-07-20 08:15'), end: moment('2017-07-20 12:30'), offset: 2, }, children: [], parent: 1, }, // should be an overlapping subtree root because it overlaps the third appointment // and its offset is less than third appointment's offset { data: { start: moment('2017-07-20 09:00'), end: moment('2017-07-20 11:00'), offset: 1, }, children: [], parent: 0, }, // should be an overlapping subtree root because it overlaps the fourth appointment // and its offset is less than fourth appointment's offset { data: { start: moment('2017-07-20 10:00'), end: moment('2017-07-20 12:00'), offset: 0, }, children: [], }, ], }]; const expectedItems = [{ ...appointmentForest[0].items[0], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[1], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[2], overlappingSubTreeRoots: [3], }, { ...appointmentForest[0].items[3], overlappingSubTreeRoots: [4], overlappingSubTreeRoot: true, maxOffset: 2, }, { ...appointmentForest[0].items[4], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, maxOffset: 2, }]; expect(prepareToGroupIntoBlocks(appointmentForest)) .toEqual([{ ...appointmentForest[0], items: expectedItems, }]); }); it('should work with complex cases', () => { const appointmentForest = [{ reduceValue: 3, items: [ { data: { start: moment('2020-05-07 10:00'), end: moment('2020-05-07 13:30'), offset: 0, }, children: [1], }, { data: { start: moment('2020-05-07 10:30'), end: moment('2020-05-07 13:30'), offset: 1, }, children: [2], parent: 0, }, { data: { start: moment('2020-05-07 11:00'), end: moment('2020-05-07 13:30'), offset: 2, }, children: [3], parent: 1, }, { data: { start: moment('2020-05-07 13:00'), end: moment('2020-05-07 15:30'), offset: 3, }, children: [], parent: 2, }, // Should be an overlapping subtree root because it overlaps the appointment with index 3 // and its offset is less than the other one's { data: { start: moment('2020-05-07 14:00'), end: moment('2020-05-07 15:30'), offset: 0, }, children: [5, 7], }, { data: { start: moment('2020-05-07 14:30'), end: moment('2020-05-07 15:00'), offset: 1, }, children: [6], parent: 4, }, // Cannot be an overlapping subtree root because it will be a part of the block // wich root - the appointment with index 4 { data: { start: moment('2020-05-07 14:45'), end: moment('2020-05-07 15:15'), offset: 2, }, children: [], parent: 5, }, // Overlapping subtree root for the previous appointment because overlaps with it // and its offset is less than the previous one { data: { start: moment('2020-05-07 15:00'), end: moment('2020-05-07 15:30'), offset: 1, }, children: [], parent: 4, }, ], }]; const expectedItems = [{ ...appointmentForest[0].items[0], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[1], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[2], overlappingSubTreeRoots: [], }, { ...appointmentForest[0].items[3], overlappingSubTreeRoots: [4], }, { ...appointmentForest[0].items[4], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, maxOffset: 3, }, { ...appointmentForest[0].items[5], overlappingSubTreeRoots: [], maxOffset: 3, }, { ...appointmentForest[0].items[6], overlappingSubTreeRoots: [7], maxOffset: 3, }, { ...appointmentForest[0].items[7], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, maxOffset: 3, }]; expect(prepareToGroupIntoBlocks(appointmentForest)) .toEqual([{ ...appointmentForest[0], items: expectedItems, }]); }); }); describe('#groupAppointmentsIntoBlocks', () => { it('should create one block for simple cases that will contain all of the appointments', () => { const appointmentForests = [{ reduceValue: 2, items: [{ data: { start: moment('2020-05-07 08:00'), end: moment('2020-05-07 08:30'), offset: 0, }, children: [1], overlappingSubTreeRoots: [], }, { data: { start: moment('2020-05-07 08:00'), end: moment('2020-05-07 08:30'), offset: 1, }, children: [], parent: 0, overlappingSubTreeRoots: [], }], }]; const expectedAppointmentFoerst = { ...appointmentForests[0], items: [{ ...appointmentForests[0].items[0], blockIndex: 0, }, { ...appointmentForests[0].items[1], blockIndex: 0, }], }; const expectedBlocks = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 08:30'), endForChildren: moment('2020-05-07 08:30'), minOffset: 0, maxOffset: 1, size: 2, items: [0, 1], }]; expect(groupAppointmentsIntoBlocks(appointmentForests)) .toEqual([{ appointmentForest: expectedAppointmentFoerst, blocks: expectedBlocks, }]); }); it('should create three blocks - one external and two overlapping', () => { const appointmentForests = [{ reduceValue: 2, items: [{ data: { start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), offset: 0, }, children: [1], overlappingSubTreeRoots: [], treeDepth: 1, }, { data: { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:30'), offset: 1, }, children: [], parent: 0, overlappingSubTreeRoots: [2], treeDepth: 0, }, { data: { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 10:00'), offset: 0, }, children: [], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, treeDepth: 0, }], }]; const expectedAppointmentFoerst = { ...appointmentForests[0], items: [{ ...appointmentForests[0].items[0], blockIndex: 0, }, { ...appointmentForests[0].items[1], blockIndex: 1, }, { ...appointmentForests[0].items[2], blockIndex: 2, }], }; const expectedBlocks = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), endForChildren: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 1, size: 2, items: [0], }, { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:30'), endForChildren: moment('2020-05-07 09:30'), minOffset: 1, maxOffset: 1, size: 1, items: [1], }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 09:30'), endForChildren: moment('2020-05-07 10:00'), minOffset: 0, maxOffset: 0, size: 1, items: [2], }]; expect(groupAppointmentsIntoBlocks(appointmentForests)) .toEqual([{ appointmentForest: expectedAppointmentFoerst, blocks: expectedBlocks, }]); }); it('should work ocrrectly if block root has children', () => { const appointmentForests = [{ reduceValue: 3, items: [{ data: { start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), offset: 0, }, children: [1], overlappingSubTreeRoots: [], treeDepth: 2, }, { data: { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:30'), offset: 1, }, children: [], parent: 0, overlappingSubTreeRoots: [3], treeDepth: 1, }, { data: { start: moment('2020-05-07 08:45'), end: moment('2020-05-07 12:30'), offset: 2, }, children: [], parent: 0, overlappingSubTreeRoots: [], treeDepth: 0, }, { data: { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 10:00'), offset: 0, }, children: [], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, treeDepth: 0, }], }]; const expectedAppointmentFoerst = { ...appointmentForests[0], items: [{ ...appointmentForests[0].items[0], blockIndex: 0, }, { ...appointmentForests[0].items[1], blockIndex: 1, }, { ...appointmentForests[0].items[2], blockIndex: 1, }, { ...appointmentForests[0].items[3], blockIndex: 2, }], }; const expectedBlocks = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), endForChildren: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 2, size: 3, items: [0], }, { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:30'), endForChildren: moment('2020-05-07 09:30'), minOffset: 1, maxOffset: 2, size: 2, items: [1, 2], }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 09:30'), endForChildren: moment('2020-05-07 10:00'), minOffset: 0, maxOffset: 0, size: 1, items: [3], }]; expect(groupAppointmentsIntoBlocks(appointmentForests)) .toEqual([{ appointmentForest: expectedAppointmentFoerst, blocks: expectedBlocks, }]); }); it('should work when several blocks are inside another block', () => { const appointmentForests = [{ reduceValue: 4, items: [{ data: { start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), offset: 0, }, children: [1], overlappingSubTreeRoots: [], treeDepth: 3, }, { data: { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:00'), offset: 1, }, children: [2], parent: 0, overlappingSubTreeRoots: [], treeDepth: 2, }, { data: { start: moment('2020-05-07 08:30'), end: moment('2020-05-07 09:00'), offset: 1, }, children: [3], parent: 2, overlappingSubTreeRoots: [], treeDepth: 1, }, { data: { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 12:00'), offset: 3, }, children: [], parent: 2, overlappingSubTreeRoots: [4], treeDepth: 0, }, { data: { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 12:00'), offset: 0, }, children: [5, 7], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, treeDepth: 2, }, { data: { start: moment('2020-05-07 10:00'), end: moment('2020-05-07 10:30'), offset: 1, }, parent: 4, children: [6], overlappingSubTreeRoots: [], treeDepth: 1, }, { data: { start: moment('2020-05-07 10:15'), end: moment('2020-05-07 10:45'), offset: 2, }, parent: 5, children: [], overlappingSubTreeRoots: [7], treeDepth: 0, }, { data: { start: moment('2020-05-07 10:30'), end: moment('2020-05-07 11:00'), offset: 1, }, children: [], overlappingSubTreeRoots: [], overlappingSubTreeRoot: true, treeDepth: 0, }], }]; const expectedAppointmentFoerst = { ...appointmentForests[0], items: [{ ...appointmentForests[0].items[0], blockIndex: 0, }, { ...appointmentForests[0].items[1], blockIndex: 0, }, { ...appointmentForests[0].items[2], blockIndex: 0, }, { ...appointmentForests[0].items[3], blockIndex: 1, }, { ...appointmentForests[0].items[4], blockIndex: 2, }, { ...appointmentForests[0].items[5], blockIndex: 2, }, { ...appointmentForests[0].items[6], blockIndex: 3, }, { ...appointmentForests[0].items[7], blockIndex: 4, }], }; const expectedBlocks = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), endForChildren: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 3, size: 4, items: [0, 1, 2], }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 12:00'), endForChildren: moment('2020-05-07 12:00'), minOffset: 3, maxOffset: 3, size: 1, items: [3], }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 12:00'), endForChildren: moment('2020-05-07 12:00'), minOffset: 0, maxOffset: 2, size: 3, items: [4, 5], }, { start: moment('2020-05-07 10:15'), end: moment('2020-05-07 10:45'), endForChildren: moment('2020-05-07 10:45'), minOffset: 2, maxOffset: 2, size: 1, items: [6], }, { start: moment('2020-05-07 10:30'), end: moment('2020-05-07 10:45'), endForChildren: moment('2020-05-07 11:00'), minOffset: 1, maxOffset: 1, size: 1, items: [7], }]; expect(groupAppointmentsIntoBlocks(appointmentForests)) .toEqual([{ appointmentForest: expectedAppointmentFoerst, blocks: expectedBlocks, }]); }); }); describe('#findBlockIndexByAppointment', () => { it('should work', () => { const blocks = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 5, }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 12:00'), minOffset: 4, maxOffset: 5, }, { start: moment('2020-05-07 10:00'), end: moment('2020-05-07 12:00'), minOffset: 1, maxOffset: 4, }]; const appointments = [{ data: { offset: 0, start: moment('2020-05-07 08:00') }, }, { data: { offset: 4, start: moment('2020-05-07 09:00') }, }, { data: { offset: 5, start: moment('2020-05-07 10:00') }, }, { data: { offset: 2, start: moment('2020-05-07 11:00') }, }, { data: { offset: 3, start: moment('2020-05-07 13:00') }, }]; expect(findBlockIndexByAppointment(blocks, appointments[0])) .toBe(0); expect(findBlockIndexByAppointment(blocks, appointments[1])) .toBe(1); expect(findBlockIndexByAppointment(blocks, appointments[2])) .toBe(1); expect(findBlockIndexByAppointment(blocks, appointments[3])) .toBe(2); expect(findBlockIndexByAppointment(blocks, appointments[4])) .toBe(0); }); }); describe('#findIncludedBlocks', () => { const blocksBase = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 5, }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 10:00'), minOffset: 4, maxOffset: 5, }, { start: moment('2020-05-07 09:30'), end: moment('2020-05-07 12:00'), minOffset: 1, maxOffset: 4, }]; it('should not find included blocks in a simple case', () => { const data = [{ blocks: blocksBase, }]; const expectedBlocks = [{ ...blocksBase[0], includedBlocks: [], }, { ...blocksBase[1], includedBlocks: [], }, { ...blocksBase[2], includedBlocks: [], }]; expect(findIncludedBlocks(data)) .toEqual([{ blocks: expectedBlocks, }]); }); it('should find included blocks when one block is inside another', () => { const blocks = [ ...blocksBase, { start: moment('2020-05-07 10:00'), end: moment('2020-05-07 11:30'), minOffset: 4, maxOffset: 4, }, { start: moment('2020-05-07 10:30'), end: moment('2020-05-07 11:30'), minOffset: 1, maxOffset: 3, }, ]; const data = [{ blocks, }]; const expectedBlocks = [{ ...blocks[0], includedBlocks: [], }, { ...blocks[1], includedBlocks: [], }, { ...blocks[2], includedBlocks: [3, 4], }, { ...blocks[3], includedBlocks: [], includedInto: 2, }, { ...blocks[4], includedBlocks: [], includedInto: 2, }]; expect(findIncludedBlocks(data)) .toEqual([{ blocks: expectedBlocks, }]); }); }); describe('#findChildBlocks', () => { const blocksBase = [{ start: moment('2020-05-07 08:00'), end: moment('2020-05-07 09:00'), minOffset: 0, maxOffset: 5, includedBlocks: [], }, { start: moment('2020-05-07 09:00'), end: moment('2020-05-07 10:00'), endForChildren: moment('2020-05-07 10:00'), minOffset: 4, maxOffset: 5, includedBlocks: [], }, { start: moment('2020-05-07 09:30'), end: moment('2020-05-07 12:00'), endForChildren: moment('2020-05-07 12:00'), minOffset: 1, maxOffset: 3, includedBlocks: [3, 4], }, { start: moment('2020-05-07 10:00'), end: moment('2020-05-07 11:30'), endForChildren: moment('2020-05-07 11:30'), minOffset: 3, maxOffset: 3, ncludedBlocks: [], includedInto: 2, }, { start: moment('2020-05-07 10:30'), end: moment('2020-05-07 11:30'), endForChildren: moment('2020-05-07 11:30'), minOffset: 1, maxOffset: 2, ncludedBlocks: [], includedInto: 2, }]; it('should not find children in the simples case', () => { const data = [{ blocks: [blocksBase[0]], }]; const expectedBlocks = [{ ...blocksBase[0], children: [], }]; expect(findChildBlocks(data)) .toEqual([{ blocks: expectedBlocks, }]); }); it('should find one child without included blocks', () => { const data = [{ blocks: [ blocksBase[0], blocksBase[1], { ...blocksBase[2], includedBlocks: [], }, ], }]; const expectedBlocks = [{ ...blocksBase[0], children: [], }, { ...blocksBase[1], children: [2], }, { ...blocksBase[2], includedBlocks: [], parent: 1, children: [], }]; expect(findChildBlocks(data)) .toEqual([{ blocks: expectedBlocks, }]); }); it('should work with included', () => { const data = [{ blocks: blocksBase, }]; const expectedBlocks = [{ ...blocksBase[0], children: [], }, { ...blocksBase[1], children: [2], }, { ...blocksBase[2], parent: 1, children: [], }, { ...blocksBase[3], children: [4], }, { ...blocksBase[4], parent: 3, children: [], }]; expect(findChildBlocks(data)) .toEqual([{ blocks: expectedBlocks, }]); }); }); describe('#calculateIncludedBlockMaxRight', () => { it('should work', () => { const blocks = [{ right: 0.5, }, { right: 0.5, includedInto: 0, }, { includedInto: 1, right: 0.5, }]; expect(calculateIncludedBlockMaxRight(blocks, blocks[2])) .toBe(0.25); }); }); describe('#calculateBlocksTotalSize', () => { it('should work', () => { const blocks = [{ size: 3, children: [1, 2], }, { size: 3, children: [], }, { size: 2, children: [3], }, { size: 2, children: [], }]; expect(calculateBlocksTotalSize(blocks)) .toEqual([{ ...blocks[0], totalSize: 7, leftOffset: 4, }, { ...blocks[1], totalSize: 3, leftOffset: 0, }, { ...blocks[2], totalSize: 4, leftOffset: 2, }, { ...blocks[3], totalSize: 2, leftOffset: 0, }]); }); }); describe('#calculateBlocksLeftLimit', () => { const appointments = [ { data: { left: 0.6 } }, { data: { left: 0.2 } }, { data: { left: 0.3 } }, { data: { left: 0.1 } }, ]; it('should work', () => { const blocks = [{ size: 3, children: [1, 2], totalSize: 7, items: [0], }, { size: 3, children: [], totalSize: 3, items: [1], }, { size: 2, children: [3], totalSize: 4, items: [2], }, { size: 2, children: [], totalSize: 2, items: [3], }]; expect(calculateBlocksLeftLimit(blocks, appointments)) .toEqual([{ ...blocks[0], leftLimit: 0.1, }, { ...blocks[1], leftLimit: 0.2, }, { ...blocks[2], leftLimit: 0.1, }, { ...blocks[3], leftLimit: 0.1, }]); }); it('should work when block lefts are defined', () => { const blocks = [{ size: 3, children: [1, 2], totalSize: 7, items: [0], left: 0.5, }, { size: 3, children: [], totalSize: 3, items: [1], left: 0.05, }, { size: 2, children: [3], totalSize: 4, items: [2], left: 0.25, }, { size: 2, children: [], totalSize: 2, items: [3], left: 0, }]; expect(calculateBlocksLeftLimit(blocks, appointments)) .toEqual([{ ...blocks[0], leftLimit: 0, }, { ...blocks[1], leftLimit: 0.05, }, { ...blocks[2], leftLimit: 0, }, { ...blocks[3], leftLimit: 0, }]); }); }); describe('#updateBlocksProportions', () => { it('should work', () => { const blocks = [{ size: 3, children: [1, 2], totalSize: 7, leftOffset: 4, leftLimit: 0, }, { size: 3, children: [], totalSize: 3, leftOffset: 0, leftLimit: 0.1, parent: 0, }, { size: 2, children: [3], totalSize: 4, leftOffset: 2, leftLimit: 0, parent: 0, }, { size: 2, children: [], totalSize: 2, leftOffset: 0, leftLimit: 0, parent: 2, }]; expect(updateBlocksProportions(blocks)) .toEqual([{ ...blocks[0], left: matchFloat(4 / 7), right: 1, totalSize: 7, }, { ...blocks[1], left: matchFloat(0.1), right: matchFloat(4 / 7), totalSize: 7, }, { ...blocks[2], left: matchFloat(2 / 7), right: matchFloat(4 / 7), totalSize: 7, }, { ...blocks[3], left: 0, right: matchFloat(2 / 7), totalSize: 7, }]); }); }); describe('#updateBlocksLeft', () => { it('should work', () => { const blocks = [{ children: [], items: [0], left: 0, }, { children: [2], items: [1], left: 0.2, }, { children: [], items: [2], left: 0, parent: 1, }, { children: [], items: [3], left: 0.5, }]; const appointments = [ { blockIndex: 0 }, { blockIndex: 1 }, { blockIndex: 2 }, { blockIndex: 3, parent: 2 }, ]; expect(updateBlocksLeft(blocks, appointments)) .toEqual([{ ...blocks[0], }, { ...blocks[1], }, { ...blocks[2], }, { ...blocks[3], left: 0.2, }]); }); }); describe('#adjustByBlocks', () => { it('should work in case with one block', () => { const groupedIntoBlocks = [{ blocks: [{ children: [], items: [0, 1], size: 2, }], appointmentForest: { items: [{ data: { left: 0, width: 0.5 }, hasDirectChild: true, isDirectChild: false, children: [1], }, { data: { left: 0.5, width: 0.5 }, hasDirectChild: false, isDirectChild: true, children: [], parent: 0, }], }, }]; expect(adjustByBlocks(groupedIntoBlocks, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([groupedIntoBlocks[0].appointmentForest]); }); it('should work with several blocks', () => { const groupedIntoBlocks = [{ blocks: [{ children: [], items: [0, 1], size: 3, included: [], }, { children: [2], items: [2], size: 1, included: [], }, { children: [3], items: [3], size: 1, included: [], parent: 1, }, { children: [], items: [4], size: 1, included: [], parent: 2, }], appointmentForest: { items: [{ data: { left: 0, width: 1 }, hasDirectChild: false, isDirectChild: false, children: [1], blockIndex: 0, treeDepth: 2, }, { data: { left: 0.05, width: 0.95 }, hasDirectChild: false, isDirectChild: false, children: [2], parent: 0, blockIndex: 0, treeDepth: 1, }, { data: { left: 0.1, width: 0.9 }, hasDirectChild: false, isDirectChild: false, children: [], parent: 1, blockIndex: 1, treeDepth: 0, }, { data: { left: 0.05, width: 0.95 }, hasDirectChild: false, isDirectChild: false, children: [], parent: 0, blockIndex: 2, treeDepth: 0, }, { data: { left: 0, width: 1 }, hasDirectChild: false, isDirectChild: false, children: [], blockIndex: 3, treeDepth: 0, }], }, }]; expect(adjustByBlocks(groupedIntoBlocks, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ items: [{ ...groupedIntoBlocks[0].appointmentForest.items[0], }, { ...groupedIntoBlocks[0].appointmentForest.items[1], }, { ...groupedIntoBlocks[0].appointmentForest.items[2], data: { left: matchFloat(2 / 3), width: matchFloat(1 / 3) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[3], data: { left: matchFloat(1 / 3), width: matchFloat(1 / 3) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[4], data: { left: 0, width: matchFloat(1 / 3) }, }], }]); }); it('should work with included blocks', () => { const groupedIntoBlocks = [{ blocks: [{ children: [], items: [0, 1, 2], size: 4, included: [], }, { children: [2], items: [3], size: 1, included: [], }, { children: [], items: [4, 5], size: 3, included: [3, 4], parent: 1, }, { children: [4], items: [6], size: 1, included: [], includedInto: 2, }, { children: [], items: [7], size: 1, included: [], parent: 3, includedInto: 2, }], appointmentForest: { items: [{ data: { left: 0, width: 1 }, hasDirectChild: false, isDirectChild: false, children: [1], blockIndex: 0, treeDepth: 3, }, { data: { left: 0.05, width: 0.95 }, hasDirectChild: false, isDirectChild: false, children: [2], parent: 0, blockIndex: 0, treeDepth: 2, }, { data: { left: 0.1, width: 0.9 }, hasDirectChild: false, isDirectChild: false, children: [3], parent: 1, blockIndex: 0, treeDepth: 1, }, { data: { left: 0.15, width: 0.85 }, hasDirectChild: false, isDirectChild: false, children: [], parent: 2, blockIndex: 1, treeDepth: 0, }, { data: { left: 0, width: 1 }, hasDirectChild: false, isDirectChild: false, children: [5, 7], blockIndex: 2, treeDepth: 2, }, { data: { left: 0.05, width: 0.475 }, hasDirectChild: true, isDirectChild: false, children: [6], blockIndex: 2, treeDepth: 1, parent: 4, }, { data: { left: 0.525, width: 0.475 }, hasDirectChild: false, isDirectChild: true, children: [], blockIndex: 3, treeDepth: 0, parent: 5, }, { data: { left: 0.05, width: 0.95 }, hasDirectChild: false, isDirectChild: false, children: [], blockIndex: 4, treeDepth: 0, parent: 4, }], }, }]; expect(adjustByBlocks(groupedIntoBlocks, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ items: [{ ...groupedIntoBlocks[0].appointmentForest.items[0], }, { ...groupedIntoBlocks[0].appointmentForest.items[1], }, { ...groupedIntoBlocks[0].appointmentForest.items[2], }, { ...groupedIntoBlocks[0].appointmentForest.items[3], data: { left: matchFloat(0.75), width: matchFloat(0.25) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[4], data: { left: 0, width: matchFloat(0.75) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[5], data: { left: matchFloat(0.05), width: matchFloat(0.35) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[6], data: { left: matchFloat(0.4), width: matchFloat(0.35) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[7], data: { left: matchFloat(0.05), width: matchFloat(0.35) }, }], }]); }); it('should distribute blocks correctly', () => { const groupedIntoBlocks = [{ blocks: [{ children: [], items: [0, 1, 2], size: 3, included: [], }, { children: [2], items: [3], size: 1, included: [], }, { children: [], items: [4], size: 1, included: [], parent: 1, }], appointmentForest: { items: [{ data: { left: 0, width: 0.25 }, hasDirectChild: true, isDirectChild: false, children: [1], blockIndex: 0, treeDepth: 3, }, { data: { left: 0.25, width: 0.25 }, hasDirectChild: true, isDirectChild: true, children: [2], parent: 0, blockIndex: 0, treeDepth: 2, }, { data: { left: 0.5, width: 0.25 }, hasDirectChild: true, isDirectChild: true, children: [3], parent: 1, blockIndex: 1, treeDepth: 1, }, { data: { left: 0.75, width: 0.25 }, hasDirectChild: false, isDirectChild: true, children: [], parent: 2, blockIndex: 2, treeDepth: 0, }, { data: { left: 0, width: 1 }, hasDirectChild: false, isDirectChild: false, children: [], blockIndex: 3, treeDepth: 0, }], }, }]; expect(adjustByBlocks(groupedIntoBlocks, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ items: [{ ...groupedIntoBlocks[0].appointmentForest.items[0], }, { ...groupedIntoBlocks[0].appointmentForest.items[1], }, { ...groupedIntoBlocks[0].appointmentForest.items[2], }, { ...groupedIntoBlocks[0].appointmentForest.items[3], }, { ...groupedIntoBlocks[0].appointmentForest.items[4], data: { left: 0, width: matchFloat(0.75) }, }], }]); }); it('should update items in the first block (with index 0)', () => { const groupedIntoBlocks = [{ blocks: [{ children: [], items: [0, 4], size: 3, included: [], }, { children: [2], items: [1, 2], size: 2, included: [], }, { children: [], items: [3], size: 1, included: [], parent: 1, }], appointmentForest: { items: [{ data: { left: 0, width: 1 / 3 }, hasDirectChild: true, isDirectChild: false, children: [1], blockIndex: 0, treeDepth: 2, }, { data: { left: 1 / 3, width: 1 / 3 }, hasDirectChild: true, isDirectChild: true, children: [2], parent: 0, blockIndex: 1, treeDepth: 1, }, { data: { left: 2 / 3, width: 1 / 3 }, hasDirectChild: false, isDirectChild: true, children: [], parent: 1, blockIndex: 1, treeDepth: 0, }, { data: { left: 0, width: 0.5 }, hasDirectChild: true, isDirectChild: false, children: [4], blockIndex: 2, treeDepth: 1, }, { data: { left: 0.5, width: 0.5 }, hasDirectChild: false, isDirectChild: true, children: [], blockIndex: 0, treeDepth: 0, parent: 3, }], }, }]; expect(adjustByBlocks(groupedIntoBlocks, INDIRECT_CHILD_LEFT_OFFSET)) .toEqual([{ items: [{ ...groupedIntoBlocks[0].appointmentForest.items[0], }, { ...groupedIntoBlocks[0].appointmentForest.items[1], }, { ...groupedIntoBlocks[0].appointmentForest.items[2], }, { ...groupedIntoBlocks[0].appointmentForest.items[3], data: { left: 0, width: matchFloat(1 / 3) }, }, { ...groupedIntoBlocks[0].appointmentForest.items[4], data: { left: matchFloat(1 / 3), width: matchFloat(2 / 3) }, }], }]); }); }); });
the_stack
* @title: Draw2D * @description: * This sample demonstrates the capabilities of the Draw2D API. * You can drag the slider around to increase or decrease the amount of sprites rendered using the Draw2D API. * You can also select between different rendering options (draw mode, texture mode, sort mode and blend mode) * and see the impact on performance reflected on the frames per second counter at the bottom of the left pane. */ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/draw2d.js") }}*/ /*{{ javascript("jslib/textureeffects.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global RequestHandler: false */ /*global Draw2D: false */ /*global Draw2DSprite: false */ /*global HTMLControls: false */ TurbulenzEngine.onload = function onloadFn() { //========================================================================== // HTML Controls //========================================================================== var htmlControls; var objectCount = 500; var moveSprites = true; var rotateSprites = false; var cycleColorSprites = false; var drawMode = 'drawSprite'; var texMode = 'single'; var sortMode = 'deferred'; var blendMode = 'alpha'; var scaleMode = 'scale'; //========================================================================== // Turbulenz Initialization //========================================================================== var graphicsDevice = TurbulenzEngine.createGraphicsDevice({}); var mathDevice = TurbulenzEngine.createMathDevice({}); var requestHandler = RequestHandler.create({}); var loadedResources = 0; // Textures to load: var spriteTextureNames = ["textures/draw2DCircle.png", "textures/draw2DSquare.png", "textures/draw2DStar.png"]; // List to store Texture objects. var textures = {}; var numResources = spriteTextureNames.length; function mappingTableReceived(mappingTable) { function textureParams(src) { return { src : mappingTable.getURL(src), mipmaps : true, onload : function (texture) { if (texture) { textures[src] = texture; loadedResources += 1; } } }; } var i; for (i = 0; i < spriteTextureNames.length; i += 1) { graphicsDevice.createTexture(textureParams(spriteTextureNames[i])); } } var gameSession; function sessionCreated() { TurbulenzServices.createMappingTable( requestHandler, gameSession, mappingTableReceived ); } gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated); //========================================================================== // Draw2D initialization //========================================================================== var draw2D = Draw2D.create({ graphicsDevice : graphicsDevice }); // Viewport for Draw2D. var gameWidth = graphicsDevice.width; var gameHeight = graphicsDevice.height; var viewport = mathDevice.v4Build(0, 0, gameWidth, gameHeight); var configureParams = { scaleMode : undefined, viewportRectangle : viewport }; //========================================================================== // Sprite drawing. //========================================================================== // Draw2DSprite object collections. // Lazily constructed and cached. var sprites = []; var spriteSize = 32; function getTexture() { if (texMode === 'none') { return null; } else if (texMode === 'single') { return textures[spriteTextureNames[0]]; } else { var ind = Math.floor(Math.random() * spriteTextureNames.length); return textures[spriteTextureNames[ind]]; } } function invalidateSpriteTextures() { var i; var limit = sprites.length; for (i = 0; i < limit; i += 1) { var sprite = sprites[i]; var tex = getTexture(); sprite.body.setTexture(tex); sprite.halo.setTexture(tex); } } var prevObjectCount; function validateSprites() { var tex; while (sprites.length < objectCount) { // We don't do any scaling or shearing as standard draw mode // cannot support this. tex = getTexture(); var body = Draw2DSprite.create({ texture : tex, width : spriteSize, height : spriteSize, x : (Math.random() * (gameWidth - spriteSize) + (spriteSize * 0.5)), y : (Math.random() * (gameHeight - spriteSize) + (spriteSize * 0.5)), rotation : 0, color : mathDevice.v4Build(1, 1, 1, 1), textureRectangle : mathDevice.v4Build(0, 0, spriteSize, spriteSize) }); var halo = Draw2DSprite.create({ texture : tex, width : spriteSize, height : spriteSize, x : body.x, y : body.y, rotation : body.rotation, color : mathDevice.v4Build(1, 1, 1, 1), textureRectangle : mathDevice.v4Build(spriteSize, 0, spriteSize * 2, spriteSize) }); sprites.push({ body : body, halo : halo, colorModifier : mathDevice.v4Build( Math.random() / 100, Math.random() / 100, Math.random() / 100, Math.random() / 100), velocity : [Math.random() * 4 - 2, Math.random() * 4 - 2], angularVel : Math.random() / 10 - (1 / 20) }); } // Reset position/rotation/color of reused objects etc. var i; for (i = prevObjectCount; i < objectCount; i += 1) { var sprite = sprites[i]; tex = getTexture(); sprite.body.setTexture(tex); sprite.body.x = (Math.random() * (gameWidth - spriteSize) + (spriteSize * 0.5)); sprite.body.y = (Math.random() * (gameHeight - spriteSize) + (spriteSize * 0.5)); sprite.body.rotation = 0; sprite.body.setColor(mathDevice.v4Build(1, 1, 1, 1)); sprite.halo.setTexture(tex); sprite.halo.x = sprite.body.x; sprite.halo.y = sprite.body.y; sprite.halo.rotation = sprite.body.rotation; sprite.halo.setColor(mathDevice.v4Build(1, 1, 1, 1)); } prevObjectCount = objectCount; } // Object used when performing draw() calls. var drawObjectColor = mathDevice.v4BuildZero(); var drawObjectDest = mathDevice.v4BuildZero(); var drawObjectSrc = mathDevice.v4BuildZero(); var drawObject = { color : drawObjectColor, rotation : 0, destinationRectangle : drawObjectDest, sourceRectangle : drawObjectSrc, texture : null }; // Buffer used when performing drawRaw() calls. var rawBuffer; if (typeof Float32Array !== "undefined") { rawBuffer = new Float32Array(20000 * 16); } else { rawBuffer = []; } //========================================================================== // Main loop. //========================================================================== var fpsElement = document.getElementById("fps"); var gpuElement = document.getElementById("gpu"); var dataElement = document.getElementById("dataTransfers"); var batchElement = document.getElementById("batchCount"); var minElement = document.getElementById("minBatch"); var maxElement = document.getElementById("maxBatch"); var avgElement = document.getElementById("avgBatch"); var lastFPS = ""; var lastGPU = ""; var lastData = ""; var lastBatch = ""; var lastMin = ""; var lastMax = ""; var lastAvg = ""; var nextUpdate = 0; function displayPerformance() { var currentTime = TurbulenzEngine.time; if (currentTime > nextUpdate) { nextUpdate = (currentTime + 0.1); var data = draw2D.performanceData; var fpsText = (graphicsDevice.fps).toFixed(2) + " fps"; var gpuText = (data.gpuMemoryUsage / 1024).toFixed(2) + " KiB"; var dataText = (data.dataTransfers).toString(); var batchText = (data.batchCount).toString(); var minText = (data.batchCount === 0) ? "" : (data.minBatchSize + " sprites"); var maxText = (data.batchCount === 0) ? "" : (data.maxBatchSize + " sprites"); var avgText = (data.batchCount === 0) ? "" : (Math.round(data.avgBatchSize) + " sprites"); if (fpsText !== lastFPS) { lastFPS = fpsText; fpsElement.innerHTML = fpsText; } if (gpuText !== lastGPU) { lastGPU = gpuText; gpuElement.innerHTML = gpuText; } if (dataText !== lastData) { lastData = dataText; dataElement.innerHTML = dataText; } if (batchText !== lastBatch) { lastBatch = batchText; batchElement.innerHTML = batchText; } if (minText !== lastMin) { lastMin = minText; minElement.innerHTML = minText; } if (maxText !== lastMax) { lastMax = maxText; maxElement.innerHTML = maxText; } if (avgText !== lastAvg) { lastAvg = avgText; avgElement.innerHTML = avgText; } } } // array of blend modes for when 'cycle' option is chosen. var blendCycleModes = ['alpha', 'additive', 'opaque']; var curBlend; var colorTmp = mathDevice.v4Build(0, 0, 0, 0); function mainLoop() { if (!graphicsDevice.beginFrame()) { return; } draw2D.resetPerformanceData(); // reset any reused sprites, create any new sprites necessary // to reach current spriteCnt value. validateSprites(); if (scaleMode === 'none') { // with scale mode none, we resize the viewport so that // balls can expand into the new area, or become restricted // to the smaller screen area. gameWidth = graphicsDevice.width; gameHeight = graphicsDevice.height; viewport[2] = gameWidth; viewport[3] = gameHeight; } configureParams.scaleMode = scaleMode; draw2D.configure(configureParams); draw2D.setBackBuffer(); draw2D.clear(); curBlend = 0; draw2D.begin(blendMode === 'cycle' ? blendCycleModes[curBlend] : blendMode, sortMode); var halfSize = spriteSize * 0.5; var xMin = halfSize; var yMin = halfSize; var xMax = gameWidth - halfSize; var yMax = gameHeight - halfSize; var i; // Draw sprites! for (i = 0; i < objectCount; i += 1) { // cycling blend modes has no effect when using drawRaw // as we are buffering everything into one draw call. if (drawMode !== 'drawRaw' && blendMode === 'cycle' && ((i % 100) === 99)) { draw2D.end(); curBlend = (curBlend + 1) % blendCycleModes.length; draw2D.begin(blendCycleModes[curBlend], sortMode); } var sprite = sprites[i]; var body = sprite.body; var halo = sprite.halo; if (moveSprites) { body.x += sprite.velocity[0]; body.y += sprite.velocity[1]; if (body.x < xMin) { body.x = xMin; sprite.velocity[0] *= -1; } if (body.y < yMin) { body.y = yMin; sprite.velocity[1] *= -1; } if (body.x > xMax) { body.x = xMax; sprite.velocity[0] *= -1; } if (body.y > yMax) { body.y = yMax; sprite.velocity[1] *= -1; } halo.x = body.x; halo.y = body.y; } if (rotateSprites) { body.rotation += sprite.angularVel; halo.rotation = body.rotation; } if (cycleColorSprites) { body.getColor(colorTmp); var j; for (j = 0; j < 4; j += 1) { var c = colorTmp[j] + sprite.colorModifier[j]; if (c < 0) { c = 0; sprite.colorModifier[j] *= -1; } else if (c > 1) { c = 1; sprite.colorModifier[j] *= -1; } colorTmp[j] = c; } body.setColor(colorTmp); // Halo has same alpha, but white color. colorTmp[0] = colorTmp[1] = colorTmp[2] = 1; halo.setColor(colorTmp); } if (drawMode === 'drawSprite') { draw2D.drawSprite(halo); draw2D.drawSprite(body); } else if (drawMode === 'draw') { drawObject.texture = body.getTexture(); drawObject.rotation = body.rotation; drawObjectDest[0] = body.x - halfSize; drawObjectDest[1] = body.y - halfSize; drawObjectDest[2] = body.x + halfSize; drawObjectDest[3] = body.y + halfSize; halo.getTextureRectangle(drawObjectSrc); halo.getColor(drawObjectColor); draw2D.draw(drawObject); body.getTextureRectangle(drawObjectSrc); body.getColor(drawObjectColor); draw2D.draw(drawObject); } else { draw2D.bufferSprite(rawBuffer, halo, (i * 2)); draw2D.bufferSprite(rawBuffer, body, (i * 2) + 1); } } // drawRaw mode we can only use 1 texture. so Regardless we must force this. if (drawMode === 'drawRaw' && objectCount !== 0) { draw2D.drawRaw(sprites[0].body.getTexture(), rawBuffer, objectCount * 2); } draw2D.end(); graphicsDevice.endFrame(); if (fpsElement) { displayPerformance(); } } var intervalID; function loadingLoop() { if (loadedResources === numResources) { TurbulenzEngine.clearInterval(intervalID); intervalID = TurbulenzEngine.setInterval(mainLoop, 1000 / 60); } } intervalID = TurbulenzEngine.setInterval(loadingLoop, 100); //========================================================================== function loadHtmlControls() { htmlControls = HTMLControls.create(); htmlControls.addSliderControl({ id: "spriteSlider", value: (objectCount * 2), max: 20000, min: 2, step: 2, fn: function () { objectCount = Math.floor(this.value / 2); htmlControls.updateSlider("spriteSlider", objectCount * 2); } }); htmlControls.addCheckboxControl({ id: "moveBox", value: "moveSprites", isSelected: moveSprites, fn: function () { moveSprites = !moveSprites; return moveSprites; } }); htmlControls.addCheckboxControl({ id: "rotateBox", value: "rotateSprites", isSelected: rotateSprites, fn: function () { rotateSprites = !rotateSprites; return rotateSprites; } }); htmlControls.addCheckboxControl({ id: "colorBox", value: "cycleColorSprites", isSelected: cycleColorSprites, fn: function () { cycleColorSprites = !cycleColorSprites; return cycleColorSprites; } }); htmlControls.addRadioControl({ id: "draw0", groupName: "drawMode", radioIndex: 0, value: "drawSprite", fn: function () { drawMode = 'drawSprite'; }, isDefault : true }); htmlControls.addRadioControl({ id: "draw1", groupName: "drawMode", radioIndex: 1, value: "draw", fn: function () { drawMode = 'draw'; }, isDefault : false }); htmlControls.addRadioControl({ id: "draw2", groupName: "drawMode", radioIndex: 2, value: "drawRaw", fn: function () { drawMode = 'drawRaw'; }, isDefault : false }); htmlControls.addRadioControl({ id: "tex0", groupName: "texMode", radioIndex: 0, value: "none", fn: function () { texMode = 'none'; invalidateSpriteTextures(); }, isDefault : false }); htmlControls.addRadioControl({ id: "tex1", groupName: "texMode", radioIndex: 1, value: "single", fn: function () { texMode = 'single'; invalidateSpriteTextures(); }, isDefault : true }); htmlControls.addRadioControl({ id: "tex2", groupName: "texMode", radioIndex: 2, value: "many", fn: function () { texMode = 'many'; invalidateSpriteTextures(); }, isDefault : false }); htmlControls.addRadioControl({ id: "sort0", groupName: "sortMode", radioIndex: 0, value: "immediate", fn: function () { sortMode = 'immediate'; }, isDefault : false }); htmlControls.addRadioControl({ id: "sort1", groupName: "sortMode", radioIndex: 1, value: "deferred", fn: function () { sortMode = 'deferred'; }, isDefault : true }); htmlControls.addRadioControl({ id: "sort2", groupName: "sortMode", radioIndex: 2, value: "texture", fn: function () { sortMode = 'texture'; }, isDefault : false }); htmlControls.addRadioControl({ id: "blend0", groupName: "blendMode", radioIndex: 0, value: "opaque", fn: function () { blendMode = 'opaque'; }, isDefault : false }); htmlControls.addRadioControl({ id: "blend1", groupName: "blendMode", radioIndex: 1, value: "alpha", fn: function () { blendMode = 'alpha'; }, isDefault : true }); htmlControls.addRadioControl({ id: "blend2", groupName: "blendMode", radioIndex: 2, value: "additive", fn: function () { blendMode = 'additive'; }, isDefault : false }); htmlControls.addRadioControl({ id: "blend3", groupName: "blendMode", radioIndex: 3, value: "cycle", fn: function () { blendMode = 'cycle'; }, isDefault : false }); htmlControls.addRadioControl({ id: "scale0", groupName: "scaleMode", radioIndex: 0, value: "none", fn: function () { scaleMode = 'none'; }, isDefault : false }); htmlControls.addRadioControl({ id: "scale1", groupName: "scaleMode", radioIndex: 1, value: "scale", fn: function () { scaleMode = 'scale'; }, isDefault : true }); htmlControls.register(); } loadHtmlControls(); // Create a scene destroy callback to run when the window is closed TurbulenzEngine.onunload = function destroyScene() { if (intervalID) { TurbulenzEngine.clearInterval(intervalID); } if (gameSession) { gameSession.destroy(); gameSession = null; } }; };
the_stack
import { Property, Complex, ChildProperty, DateFormatOptions, isNullOrUndefined, Collection } from '@syncfusion/ej2-base'; import { DataUtil } from '@syncfusion/ej2-data'; import { Orientation } from '../utils/enum'; import { FontModel, TitleModel, AxisLabelBorderModel, MultiLevelLabelsModel, MultiLevelCategoriesModel } from '../model/base-model'; import { Font, Title, AxisLabelBorder, MultiLevelLabels, MultiLevelCategories, MultipleRow } from '../model/base'; import { Theme } from '../model/theme'; import { Rect, measureText, Size, rotateTextSize, increaseDateTimeInterval, formatValue, textTrim } from '../utils/helper'; import { MultiLevelPosition, textWrap } from '../utils/helper'; import { ValueType, IntervalType, LabelIntersectAction, LabelType } from '../utils/enum'; import { HeatMap } from '../heatmap'; export class Axis extends ChildProperty<Axis> { /** * Title of heat map axis * * @default '' */ @Complex<TitleModel>({ text: '', textStyle: Theme.axisTitleFont }, Title) public title: TitleModel; /** * If set to true, the axis will render at the opposite side of its default position. * * @default false */ @Property(false) public opposedPosition: boolean; /** * Options for label assignment. */ @Property(null) public labels: string[]; /** * Options for customizing the label text. */ @Complex<FontModel>(Theme.axisLabelFont, Font) public textStyle: FontModel; /** * The angle to rotate the axis label * * @default 0 */ @Property(0) public labelRotation: number; /** * It specifies whether the axis to be rendered in inversed manner or not. * * @default false */ @Property(false) public isInversed: boolean; /** * Specifies the type of data the axis is handling. * * Numeric: Renders a numeric axis. * * DateTime: Renders a dateTime axis. * * Category: Renders a category axis. * * @default Category * @aspType Syncfusion.EJ2.HeatMap.ValueType * @blazorType Syncfusion.EJ2.HeatMap.ValueType * @isEnumeration true */ @Property('Category') public valueType: ValueType; /** * Specifies the increment for an axis label. * * @default 1 */ @Property(1) public increment: number; /** * Defines the axis label display type for date time axis. * * None: Axis labels displayed based on the value type. * * Years: Define the axis labels display in every year. * * Months: Define the axis labels display in every month. * * Days: Define the axis labels display in every day. * * Hours: Define the axis labels display in every hour. * * @default 'None' */ @Property('None') public showLabelOn: LabelType; /** * Specifies the minimum range of an axis. * * @default null */ @Property(null) public minimum: Object; /** * Specifies the maximum range of an axis. * * @default null */ @Property(null) public maximum: Object; /** * Specifies the interval for an axis. * * @default null */ @Property(null) public interval: number; /** * Used to format the axis label that accepts any global string format like 'C', 'n1', 'P' etc. * It also accepts placeholder like '{value}°C' in which value represent the axis label, e.g, 20°C. * * @default '' */ @Property('') public labelFormat: string; /** * Specifies the types like `Years`, `Months`, `Days`, `Hours`, `Minutes` in date time axis.They are, * * Years: Defines the interval of the axis in years. * * Months: Defines the interval of the axis in months. * * Days: Defines the interval of the axis in days. * * Hours: Defines the interval of the axis in hours. * * Minutes: Defines the interval of the axis in minutes. * * @default 'Days' */ @Property('Days') public intervalType: IntervalType; /** * Specifies the actions like `Rotate45`, `None` and `Trim` when the axis labels intersect with each other.They are, * * None: Shows all the labels. * * Rotate45: Rotates the label to 45 degree when it intersects. * * Trim : Trim the label when label text width exceed the label width * * @default Trim */ @Property('Trim') public labelIntersectAction: LabelIntersectAction; /** * Enable Trim for heatmap yAxis * * @default false */ @Property(false) public enableTrim: boolean; /** * Specifies the maximum length of an axis label. * * @default 35. */ @Property(35) public maxLabelLength: number; /** * Border of the axis labels. */ @Complex<AxisLabelBorderModel>({ color: '#b5b5b5', width: 0, type: 'Rectangle' }, AxisLabelBorder) public border: AxisLabelBorderModel; /** * Specifies the multi level labels collection for the axis */ @Collection<MultiLevelLabels>([], MultiLevelLabels) public multiLevelLabels: MultiLevelLabelsModel[]; /** @private */ public orientation: Orientation; /** @private */ public multipleRow: MultipleRow [] = []; /** @private */ public rect: Rect = new Rect(undefined, undefined, 0, 0); /** @private */ public nearSizes: number[] = []; /** @private */ public farSizes: number[] = []; /** @private */ public maxLabelSize: Size = new Size(0, 0); /** @private */ public titleSize: Size = new Size(0, 0); /** @private */ public multilevel: number[] = []; /** @private */ public axisLabels: string[] = []; /** @private */ public tooltipLabels: string[] = []; /** @private */ public labelValue: (string | number | Date)[] = []; /** @private */ public axisLabelSize: number = 0; /** @private */ public axisLabelInterval: number = 0; /** @private */ public dateTimeAxisLabelInterval: number[] = []; /** @private */ public maxLength: number = 0; /** @private */ public min: number = 0; /** @private */ public max: number = 0; /** @private */ // eslint-disable-next-line @typescript-eslint/ban-types public format: Function; /** @private */ public angle: number; /** @private */ public isIntersect: boolean = false; /** @private */ public jsonCellLabel: string[] = []; public multiLevelSize: Size[] = []; /** @private */ public xAxisMultiLabelHeight: number[] = []; /** @private */ public yAxisMultiLabelHeight: number[] = []; /** @private */ public multiLevelPosition: MultiLevelPosition[] = []; /** * measure the axis title and label size * * @param axis * @param heatmap * @private */ public computeSize(axis: Axis, heatmap: HeatMap, rect: Rect): void { let size: Size = new Size(0, 0); const innerPadding: number = 10; this.titleSize = axis.getTitleSize(axis, innerPadding); this.maxLabelSize = axis.getMaxLabelSize(axis, heatmap); this.getMultilevelLabelsHeight(axis, rect, heatmap); for (let i: number = 0; i < this.multiLevelLabels.length; i++) { size = axis.multiLevelLabelSize(innerPadding, i); this.multiLevelSize.push(size); } } /** * calculating x, y position of multi level labels * * @private */ public multiPosition(axis: Axis, index: number): MultiLevelPosition { const innerPadding: number = axis.orientation === 'Horizontal' ? 10 : 20; const multiPosition: MultiLevelPosition = new MultiLevelPosition(0, 0); if (axis.orientation === 'Horizontal') { const level0: number = axis.maxLabelSize.height + innerPadding ; const level1: number = this.xAxisMultiLabelHeight[index - 1] ; multiPosition.x = (axis.isInversed ? axis.rect.x + axis.rect.width : axis.rect.x); multiPosition.y = index === 0 ? axis.rect.y + (axis.opposedPosition ? -level0 : level0) : axis.multiLevelPosition[index - 1].y + (axis.opposedPosition ? -level1 : level1 ); } else { const level0: number = axis.maxLabelSize.width + innerPadding; const level1: number = index !== 0 && (this.multiLevelSize[index - 1].width ); multiPosition.x = index === 0 ? axis.rect.x - (axis.opposedPosition ? -level0 : level0 ) : axis.multiLevelPosition[index - 1].x - (axis.opposedPosition ? - (level1 + innerPadding) : level1 + innerPadding); multiPosition.y = axis.isInversed ? axis.rect.y : axis.rect.y + axis.rect.height; } return multiPosition; } private multiLevelLabelSize(innerPadding: number, index: number): Size { const labelSize: Size = new Size(0, 0); const multiLevel: MultiLevelLabelsModel[] = this.multiLevelLabels; const categoryLabel: MultiLevelCategoriesModel[] = multiLevel[index].categories; for (let i: number = 0; i < categoryLabel.length; i++) { const size: Size = measureText(categoryLabel[i].text, multiLevel[index].textStyle); labelSize.width = (labelSize.width > size.width) ? labelSize.width : size.width; labelSize.height = (labelSize.height > size.height) ? labelSize.height : size.height; } const size: number = (this.orientation === 'Horizontal') ? this.xAxisMultiLabelHeight[index] : this.yAxisMultiLabelHeight[index]; if (this.opposedPosition) { this.farSizes.push(size ); } else { this.nearSizes.push(size ); } return labelSize; } private getMultilevelLabelsHeight(axis: Axis, rect: Rect, heatmap: HeatMap): void { let labelSize: Size; let gap: number; let height: number; const multiLevelLabelsHeight: number[] = []; let start: number | Date; let end: number | Date; let startPosition: number; let endPosition: number; const isVertical: boolean = axis.orientation === 'Vertical'; const padding: number = axis.orientation === 'Vertical' ? 20 : 10; this.multiLevelLabels.map((multiLevel: MultiLevelLabels, index: number) => { multiLevel.categories.map((categoryLabel: MultiLevelCategories) => { start = typeof categoryLabel.start === 'number' ? categoryLabel.start : Number(new Date(<string>categoryLabel.start)); end = typeof categoryLabel.end === 'number' ? categoryLabel.end : Number(new Date(<string>categoryLabel.end)); if (categoryLabel.text !== '' && categoryLabel.start !== null && categoryLabel.end !== null) { labelSize = measureText(categoryLabel.text, multiLevel.textStyle); height = isVertical ? labelSize.width : labelSize.height; startPosition = heatmap.heatMapAxis.calculateLeftPosition(axis, start, categoryLabel.start, rect); endPosition = heatmap.heatMapAxis.calculateWidth(axis, categoryLabel.end, end, rect); labelSize = measureText(categoryLabel.text, multiLevel.textStyle); gap = ((categoryLabel.maximumTextWidth === null) ? Math.abs(endPosition - startPosition) : categoryLabel.maximumTextWidth); if ((labelSize.width > gap - padding) && (multiLevel.overflow === 'Wrap') && !isVertical) { height = (height * (textWrap(categoryLabel.text, gap - padding, multiLevel.textStyle).length)); } multiLevelLabelsHeight[index] = !multiLevelLabelsHeight[index] ? height + padding : ((multiLevelLabelsHeight[index] < height) ? height + padding : multiLevelLabelsHeight[index]); } }); }); if (isVertical) { this.yAxisMultiLabelHeight = multiLevelLabelsHeight; } else { this.xAxisMultiLabelHeight = multiLevelLabelsHeight; } } private getTitleSize(axis: Axis, innerPadding: number): Size { let titleSize: Size = new Size(0, 0); if (this.title.text) { titleSize = measureText(this.title.text, this.title.textStyle); titleSize.height += innerPadding; } if (axis.opposedPosition) { this.farSizes.push(titleSize.height); } else { this.nearSizes.push(titleSize.height); } return titleSize; } private getMaxLabelSize(axis: Axis, heatmap: HeatMap): Size { const labelSize: Size = new Size(0, 0); const labels: string[] = this.axisLabels; const padding: number = (axis.border.width > 0 || axis.multiLevelLabels.length > 0) ? 10 : 0; let count: number = 1; const row: number = 1; const interval: number = (axis.valueType === 'DateTime' && axis.showLabelOn !== 'None') ? heatmap.initialClipRect.width / axis.axisLabelSize : heatmap.initialClipRect.width / axis.axisLabels.length; axis.angle = axis.labelRotation; axis.isIntersect = false; if (axis.orientation === 'Horizontal' && (axis.labelIntersectAction === 'Rotate45' || (axis.labelRotation % 180 === 0 && axis.labelIntersectAction === 'Trim' || axis.enableTrim)) || axis.labelIntersectAction === 'MultipleRows') { let startX: number = heatmap.initialClipRect.x + ((!axis.isInversed) ? 0 : heatmap.initialClipRect.width); let previousEnd: number; let previousStart: number; this.clearMultipleRow(); for (let i: number = 0, len: number = labels.length; i < len; i++) { const label: string = labels[i]; const elementSize: Size = measureText(label, axis.textStyle); const axisInterval: number = (axis.valueType === 'DateTime' && axis.showLabelOn !== 'None') ? axis.dateTimeAxisLabelInterval[i] * interval : interval; let startPoint: number = startX + (!axis.isInversed ? ((interval - elementSize.width) / 2) : -((interval + elementSize.width) / 2)); startPoint = startPoint < heatmap.initialClipRect.x ? heatmap.initialClipRect.x : startPoint; const endPoint: number = startPoint + elementSize.width; if (!axis.isInversed) { if (isNullOrUndefined(previousEnd)) { previousEnd = endPoint; } else if ((startPoint < previousEnd) && axis.labelIntersectAction !== 'MultipleRows') { if (axis.labelIntersectAction === 'Rotate45' && !axis.enableTrim) { axis.angle = 45; } else { axis.isIntersect = true; } break; } previousEnd = endPoint; } else { if (isNullOrUndefined(previousStart)) { previousStart = startPoint; } else if ((previousStart < endPoint && axis.labelIntersectAction !== 'MultipleRows')) { if (axis.labelIntersectAction === 'Rotate45' && !axis.enableTrim) { axis.angle = 45; } else { axis.isIntersect = true; } break; } previousStart = startPoint; } startX += axis.isInversed ? -axisInterval : axisInterval; if (axis.orientation === 'Horizontal' && axis.labelIntersectAction === 'MultipleRows' && axis.labelRotation === 0) { this.multipleRow.push(new MultipleRow (startPoint , endPoint, count, label, row)); } } if (axis.orientation === 'Horizontal' && axis.labelIntersectAction === 'MultipleRows' && axis.isInversed) { this.multipleRow = this.multipleRow.reverse(); } } for (let i: number = 0; i < labels.length; i++) { const multipleRow : MultipleRow [] = this.multipleRow; let label : string; if (axis.enableTrim) { label = textTrim(axis.maxLabelLength, labels[i], axis.textStyle); } else { label = labels[i]; } const size: Size = (axis.angle % 180 === 0) ? measureText(label, axis.textStyle) : rotateTextSize(axis.textStyle, labels[i], axis.angle); labelSize.width = (labelSize.width > size.width) ? labelSize.width : size.width; if (axis.labelIntersectAction === 'MultipleRows' && axis.orientation === 'Horizontal' && i > 0 && axis.labelRotation === 0) { if (multipleRow[i].end >= heatmap.initialClipRect.width && i < labels.length - 1) { multipleRow[i].row = multipleRow[i].row + 1; } for (let k: number = 1; k <= axis.multilevel.length; k++) { if (multipleRow[i].start < multipleRow[i - 1].end) { if (axis.multilevel[k] < multipleRow[i].start) { count = k; break; } else if (k === axis.multilevel.length - 1) { count = axis.multilevel.length; break; } } else if (size.width < interval) { for (let j: number = 1; j <= axis.multilevel.length; j++) { if (axis.multilevel[j] < multipleRow[i].start) { count = j; multipleRow[j].row = count; break; } } } } labelSize.height = (labelSize.height > ((size.height * count) + (((size.height * 0.5) / 2) * (count - 1)))) ? labelSize.height : ((size.height * count) + (((size.height * 0.5) / 2) * count)); this.multipleRow[i].index = count; axis.multilevel[count] = multipleRow[i].end; } else { if (axis.orientation === 'Horizontal' && axis.labelIntersectAction === 'MultipleRows' && i === 0 && axis.labelRotation === 0) { axis.multilevel[1] = multipleRow[i].end; } labelSize.height = (labelSize.height > size.height) ? labelSize.height : size.height; } } if (heatmap.cellSettings.border.width >= 20 && axis.orientation !== 'Horizontal') { labelSize.width = labelSize.width + (heatmap.cellSettings.border.width / 4); } if (axis.opposedPosition) { this.farSizes.push((axis.orientation === 'Horizontal') ? labelSize.height : labelSize.width + padding); } else { this.nearSizes.push((axis.orientation === 'Horizontal') ? labelSize.height : labelSize.width + padding); } return labelSize; } /** * Generate the axis lables for numeric axis * * @param heatmap * @private */ public calculateNumericAxisLabels(heatmap: HeatMap): void { //Axis Min let min: number = 0; let max: number = 0; const interval: number = this.interval ? this.interval : 1; let adaptorMin: Object; let adaptorMax: Object; if (heatmap.adaptorModule && heatmap.isCellData) { adaptorMin = this.orientation === 'Horizontal' ? heatmap.adaptorModule.adaptiveXMinMax.min : heatmap.adaptorModule.adaptiveYMinMax.min; adaptorMax = this.orientation === 'Horizontal' ? heatmap.adaptorModule.adaptiveXMinMax.max : heatmap.adaptorModule.adaptiveYMinMax.max; } min = !isNullOrUndefined(this.minimum) ? <number>this.minimum : ((adaptorMin) ? <number>adaptorMin : 0); max = !isNullOrUndefined(this.maximum) ? <number>this.maximum : ((adaptorMax) ? <number>adaptorMax : (this.maxLength * this.increment)); let temp: number; if (this.minimum && this.maximum && min > max) { temp = min; min = max; max = temp; } max = !isNullOrUndefined(this.maximum) ? max : (adaptorMax ? <number>adaptorMax : (max + min)); const format: string = this.labelFormat; const isCustom: boolean = format.match('{value}') !== null; this.format = heatmap.intl.getNumberFormat({ format: isCustom ? '' : format }); for (let i: number = min; i <= max; i = i + (interval * this.increment)) { const value: string = formatValue(isCustom, format, i, this.format); this.axisLabels.push(value); } this.min = 0; this.axisLabelSize = Math.floor(((max - min) / this.increment) + 1); this.max = this.axisLabelSize - 1; this.axisLabelInterval = interval; for (let i: number = min; i <= max; i = i + this.increment) { const value: string = formatValue(isCustom, format, i, this.format); this.tooltipLabels.push(value); this.labelValue.push(i); } this.labelValue = this.isInversed ? this.labelValue.reverse() : this.labelValue; } /** * Generate the axis lables for category axis * * @private */ public calculateCategoryAxisLabels(): void { let labels: string[] = this.labels ? this.labels : []; labels = (labels.length > 0) ? labels : this.jsonCellLabel; let min: number = !isNullOrUndefined(this.minimum) && !(this.minimum instanceof Date) ? <number>this.minimum : 0; let max: number = !isNullOrUndefined(this.maximum) && !(this.maximum instanceof Date) ? <number>this.maximum : this.maxLength; const interval: number = this.interval ? this.interval : 1; let temp: number; if (!isNullOrUndefined(this.minimum) && !isNullOrUndefined(this.maximum) && min > max) { temp = min; min = max; max = temp; } if (labels && labels.length > 0) { for (let i: number = min; i <= max; i = i + interval) { const value: string = labels[i] ? labels[i].toString() : i.toString(); this.axisLabels.push(value); } } else { for (let i: number = min; i <= max; i = i + interval) { this.axisLabels.push(i.toString()); } } for (let i: number = min; i <= max; i++) { this.tooltipLabels.push(labels[i] ? labels[i].toString() : i.toString()); this.labelValue.push(labels[i] ? labels[i].toString() : i.toString()); } this.min = min; this.max = max; this.axisLabelSize = max - min + 1; this.axisLabelInterval = interval; this.labelValue = this.isInversed ? this.labelValue.reverse() : this.labelValue; } /** * Generate the axis labels for date time axis. * * @param heatmap * @private */ public calculateDateTimeAxisLabel(heatmap: HeatMap): void { let interval: number = this.interval ? this.interval : 1; const option: DateFormatOptions = { skeleton: 'full', type: 'dateTime' }; // eslint-disable-next-line @typescript-eslint/ban-types const dateParser: Function = heatmap.intl.getDateParser(option); // eslint-disable-next-line @typescript-eslint/ban-types const dateFormatter: Function = heatmap.intl.getDateFormat(option); let min: number; let max: number; let adaptorMin: Object = null; let adaptorMax: Object = null; if (heatmap.adaptorModule && heatmap.isCellData) { adaptorMin = this.orientation === 'Horizontal' ? heatmap.adaptorModule.adaptiveXMinMax.min : heatmap.adaptorModule.adaptiveYMinMax.min; adaptorMax = this.orientation === 'Horizontal' ? heatmap.adaptorModule.adaptiveXMinMax.max : heatmap.adaptorModule.adaptiveYMinMax.max; } const minimum: object = this.minimum ? this.minimum : (adaptorMin ? adaptorMin : null); const maximum: object = this.maximum ? this.maximum : (adaptorMax ? adaptorMax : null); if (minimum === null && maximum === null) { min = 0; max = this.maxLength * this.increment; for (let i: number = min; i <= max; i = i + (interval * this.increment)) { this.axisLabels.push(i.toString()); this.tooltipLabels.push(i.toString()); this.labelValue.push(i.toString()); } this.min = 0; this.max = this.maxLength; this.axisLabelSize = (max - min) / this.increment + 1; this.axisLabelInterval = interval; } else { if (minimum !== null && maximum === null) { min = Date.parse(dateParser(dateFormatter(new Date( DataUtil.parse.parseJson({ val: minimum }).val )))); max = increaseDateTimeInterval(min, this.maxLength, this.intervalType, this.increment).getTime(); } else if (minimum === null && maximum !== null) { max = Date.parse(dateParser(dateFormatter(new Date( DataUtil.parse.parseJson({ val: maximum }).val )))); min = increaseDateTimeInterval(max, -this.maxLength, this.intervalType, this.increment).getTime(); } else { min = Date.parse(dateParser(dateFormatter(new Date( DataUtil.parse.parseJson({ val: minimum }).val )))); max = Date.parse(dateParser(dateFormatter(new Date( DataUtil.parse.parseJson({ val: maximum }).val )))); } this.format = heatmap.intl.getDateFormat({ format: this.labelFormat, skeleton: this.getSkeleton() }); let tempInterval: number = min; while (tempInterval <= max) { const value: string = this.format(new Date(tempInterval)); this.axisLabels.push(value); if (this.showLabelOn !== 'None') { interval = this.calculateLabelInterval(tempInterval); this.dateTimeAxisLabelInterval.push(interval); } tempInterval = increaseDateTimeInterval(tempInterval, interval, this.intervalType, this.increment).getTime(); } this.min = 0; this.axisLabelInterval = interval; this.axisLabelSize = this.getTotalLabelLength(min, max); // this.tooltipLabels.length; this.max = this.axisLabelSize - 1; tempInterval = min; while (tempInterval <= max) { const value: string = this.format(new Date(tempInterval)); this.tooltipLabels.push(value); this.labelValue.push(new Date(tempInterval)); tempInterval = increaseDateTimeInterval(tempInterval, 1, this.intervalType, this.increment).getTime(); } } this.labelValue = this.isInversed ? this.labelValue.reverse() : this.labelValue; } private calculateLabelInterval(interval: number): number { const year: number = new Date(interval).getFullYear(); const month: number = new Date(interval).getMonth() + 1; const day: number = new Date(interval).getDate(); let numberOfDays: number; let tempInterval: number; if (this.showLabelOn === 'Years' || this.showLabelOn === 'Months') { if (this.showLabelOn === 'Years' && this.intervalType === 'Months') { tempInterval = Math.ceil(12 / this.increment); } else { numberOfDays = this.showLabelOn === 'Years' ? year % 4 === 0 ? 366 : 365 : new Date(year, month, 0).getDate(); numberOfDays += 1 - day; tempInterval = this.intervalType === 'Days' ? Math.ceil(numberOfDays / this.increment) : this.intervalType === 'Hours' ? Math.ceil((numberOfDays * 24) / this.increment) : this.intervalType === 'Minutes' ? Math.ceil((numberOfDays * 24 * 60) / this.increment) : 1; } } else if (this.showLabelOn === 'Days') { tempInterval = this.intervalType === 'Hours' ? Math.ceil(24 / this.increment) : this.intervalType === 'Minutes' ? Math.ceil((24 * 60) / this.increment) : 1; } else if (this.showLabelOn === 'Hours') { const minutes: number = new Date(interval).getMinutes(); tempInterval = this.intervalType === 'Minutes' ? Math.ceil((60 - minutes) / this.increment) : 1; } else { tempInterval = 1; } return tempInterval; } /** * @private */ public getSkeleton(): string { let skeleton: string; if (this.intervalType === 'Years') { skeleton = 'yMMM'; } else if (this.intervalType === 'Months') { skeleton = 'MMMd'; } else if (this.intervalType === 'Days') { skeleton = 'yMd'; } else if (this.intervalType === 'Hours') { skeleton = 'EHm'; } else if (this.intervalType === 'Minutes') { skeleton = 'Hms'; } else { skeleton = 'Hms'; } return skeleton; } /** @private */ public getTotalLabelLength(min: number, max: number): number { let length: number = 0; const minimum: Date = new Date(min); const maximum: Date = new Date(max); let difference: number; let days: number; switch (this.intervalType) { case 'Years': // eslint-disable-next-line no-case-declarations const years: number = ((maximum.getFullYear() - minimum.getFullYear()) / this.increment) + 1; length = Math.floor(years); break; case 'Months': // eslint-disable-next-line no-case-declarations let months: number = (maximum.getFullYear() - minimum.getFullYear()) * 12; months -= minimum.getMonth(); months += maximum.getMonth(); length = months <= 0 ? 1 : Math.floor((months / this.increment) + 1); break; case 'Days': difference = Math.abs(minimum.getTime() - maximum.getTime()); days = Math.floor(difference / (1000 * 3600 * 24)); length = Math.floor((days / this.increment) + 1); break; case 'Hours': difference = Math.abs(minimum.getTime() - maximum.getTime()); // eslint-disable-next-line no-case-declarations const hours: number = Math.floor(difference / (1000 * 3600)); length = Math.floor(hours / this.increment) + 1; break; case 'Minutes': difference = Math.abs(minimum.getTime() - maximum.getTime()); // eslint-disable-next-line no-case-declarations const minutes: number = Math.floor(difference / (1000 * 60)); length = Math.floor(minutes / this.increment) + 1; break; } return length; } /** * Clear the axis label collection * * @private */ public clearAxisLabel(): void { this.axisLabels = []; this.tooltipLabels = []; this.dateTimeAxisLabelInterval = []; this.labelValue = []; } /** * Clear the axis label collection * * @private */ public clearMultipleRow(): void { this.multipleRow = []; this.multilevel = []; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { GenericResourceExpanded, ResourcesListByResourceGroupOptionalParams, ResourcesListOptionalParams, ResourcesMoveInfo, ResourcesMoveResourcesOptionalParams, ResourcesValidateMoveResourcesOptionalParams, ResourcesCheckExistenceOptionalParams, ResourcesCheckExistenceResponse, ResourcesDeleteOptionalParams, GenericResource, ResourcesCreateOrUpdateOptionalParams, ResourcesCreateOrUpdateResponse, ResourcesUpdateOptionalParams, ResourcesUpdateResponse, ResourcesGetOptionalParams, ResourcesGetResponse, ResourcesCheckExistenceByIdOptionalParams, ResourcesCheckExistenceByIdResponse, ResourcesDeleteByIdOptionalParams, ResourcesCreateOrUpdateByIdOptionalParams, ResourcesCreateOrUpdateByIdResponse, ResourcesUpdateByIdOptionalParams, ResourcesUpdateByIdResponse, ResourcesGetByIdOptionalParams, ResourcesGetByIdResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a Resources. */ export interface Resources { /** * Get all the resources for a resource group. * @param resourceGroupName The resource group with the resources to get. * @param options The options parameters. */ listByResourceGroup( resourceGroupName: string, options?: ResourcesListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<GenericResourceExpanded>; /** * Get all the resources in a subscription. * @param options The options parameters. */ list( options?: ResourcesListOptionalParams ): PagedAsyncIterableIterator<GenericResourceExpanded>; /** * The resources to be moved must be in the same source resource group in the source subscription being * used. The target resource group may be in a different subscription. When moving resources, both the * source group and the target group are locked for the duration of the operation. Write and delete * operations are blocked on the groups until the move completes. * @param sourceResourceGroupName The name of the resource group from the source subscription * containing the resources to be moved. * @param parameters Parameters for moving resources. * @param options The options parameters. */ beginMoveResources( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesMoveResourcesOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * The resources to be moved must be in the same source resource group in the source subscription being * used. The target resource group may be in a different subscription. When moving resources, both the * source group and the target group are locked for the duration of the operation. Write and delete * operations are blocked on the groups until the move completes. * @param sourceResourceGroupName The name of the resource group from the source subscription * containing the resources to be moved. * @param parameters Parameters for moving resources. * @param options The options parameters. */ beginMoveResourcesAndWait( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesMoveResourcesOptionalParams ): Promise<void>; /** * This operation checks whether the specified resources can be moved to the target. The resources to * be moved must be in the same source resource group in the source subscription being used. The target * resource group may be in a different subscription. If validation succeeds, it returns HTTP response * code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an * error message. Retrieve the URL in the Location header value to check the result of the long-running * operation. * @param sourceResourceGroupName The name of the resource group from the source subscription * containing the resources to be validated for move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ beginValidateMoveResources( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesValidateMoveResourcesOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * This operation checks whether the specified resources can be moved to the target. The resources to * be moved must be in the same source resource group in the source subscription being used. The target * resource group may be in a different subscription. If validation succeeds, it returns HTTP response * code 204 (no content). If validation fails, it returns HTTP response code 409 (Conflict) with an * error message. Retrieve the URL in the Location header value to check the result of the long-running * operation. * @param sourceResourceGroupName The name of the resource group from the source subscription * containing the resources to be validated for move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ beginValidateMoveResourcesAndWait( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesValidateMoveResourcesOptionalParams ): Promise<void>; /** * Checks whether a resource exists. * @param resourceGroupName The name of the resource group containing the resource to check. The name * is case insensitive. * @param resourceProviderNamespace The resource provider of the resource to check. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to check whether it exists. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ checkExistence( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesCheckExistenceOptionalParams ): Promise<ResourcesCheckExistenceResponse>; /** * Deletes a resource. * @param resourceGroupName The name of the resource group that contains the resource to delete. The * name is case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to delete. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ beginDelete( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes a resource. * @param resourceGroupName The name of the resource group that contains the resource to delete. The * name is case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to delete. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesDeleteOptionalParams ): Promise<void>; /** * Creates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to create. * @param resourceName The name of the resource to create. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for creating or updating the resource. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesCreateOrUpdateResponse>, ResourcesCreateOrUpdateResponse > >; /** * Creates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to create. * @param resourceName The name of the resource to create. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for creating or updating the resource. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateOptionalParams ): Promise<ResourcesCreateOrUpdateResponse>; /** * Updates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to update. * @param resourceName The name of the resource to update. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for updating the resource. * @param options The options parameters. */ beginUpdate( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesUpdateResponse>, ResourcesUpdateResponse > >; /** * Updates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to update. * @param resourceName The name of the resource to update. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for updating the resource. * @param options The options parameters. */ beginUpdateAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateOptionalParams ): Promise<ResourcesUpdateResponse>; /** * Gets a resource. * @param resourceGroupName The name of the resource group containing the resource to get. The name is * case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource. * @param resourceName The name of the resource to get. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ get( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesGetOptionalParams ): Promise<ResourcesGetResponse>; /** * Checks by ID whether a resource exists. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ checkExistenceById( resourceId: string, apiVersion: string, options?: ResourcesCheckExistenceByIdOptionalParams ): Promise<ResourcesCheckExistenceByIdResponse>; /** * Deletes a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ beginDeleteById( resourceId: string, apiVersion: string, options?: ResourcesDeleteByIdOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Deletes a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ beginDeleteByIdAndWait( resourceId: string, apiVersion: string, options?: ResourcesDeleteByIdOptionalParams ): Promise<void>; /** * Create a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Create or update resource parameters. * @param options The options parameters. */ beginCreateOrUpdateById( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateByIdOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesCreateOrUpdateByIdResponse>, ResourcesCreateOrUpdateByIdResponse > >; /** * Create a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Create or update resource parameters. * @param options The options parameters. */ beginCreateOrUpdateByIdAndWait( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateByIdOptionalParams ): Promise<ResourcesCreateOrUpdateByIdResponse>; /** * Updates a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Update resource parameters. * @param options The options parameters. */ beginUpdateById( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateByIdOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesUpdateByIdResponse>, ResourcesUpdateByIdResponse > >; /** * Updates a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Update resource parameters. * @param options The options parameters. */ beginUpdateByIdAndWait( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateByIdOptionalParams ): Promise<ResourcesUpdateByIdResponse>; /** * Gets a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ getById( resourceId: string, apiVersion: string, options?: ResourcesGetByIdOptionalParams ): Promise<ResourcesGetByIdResponse>; }
the_stack
import * as t from 'io-ts'; import { RTTI_id } from '../Scalar/RTTI_id'; import { RTTI_Meta, IMeta } from './RTTI_Meta'; import { RTTI_uri } from '../Scalar/RTTI_uri'; import { RTTI_Element, IElement } from './RTTI_Element'; import { RTTI_code } from '../Scalar/RTTI_code'; import { RTTI_Narrative, INarrative } from './RTTI_Narrative'; import { RTTI_ResourceList, IResourceList } from '../Union/RTTI_ResourceList'; import { RTTI_Extension, IExtension } from './RTTI_Extension'; import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier'; import { RTTI_canonical } from '../Scalar/RTTI_canonical'; import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept'; import { RTTI_Reference, IReference } from './RTTI_Reference'; import { RTTI_dateTime } from '../Scalar/RTTI_dateTime'; import { RTTI_Period, IPeriod } from './RTTI_Period'; import { RTTI_Age, IAge } from './RTTI_Age'; import { RTTI_Range, IRange } from './RTTI_Range'; import { RTTI_Annotation, IAnnotation } from './RTTI_Annotation'; import { RTTI_FamilyMemberHistory_Condition, IFamilyMemberHistory_Condition } from './RTTI_FamilyMemberHistory_Condition'; export enum FamilyMemberHistoryStatusKind { _partial = 'partial', _completed = 'completed', _enteredInError = 'entered-in-error', _healthUnknown = 'health-unknown' } import { createEnumType } from '../../EnumType'; import { IDomainResource } from './IDomainResource'; export interface IFamilyMemberHistory extends IDomainResource { /** * This is a FamilyMemberHistory resource */ resourceType: 'FamilyMemberHistory'; /** * The person who this history concerns. */ patient: IReference; /** * The type of relationship this person has to the patient (father, mother, brother etc.). */ relationship: ICodeableConcept; /** * The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. */ id?: string; /** * The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource. */ meta?: IMeta; /** * A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc. */ implicitRules?: string; /** * Extensions for implicitRules */ _implicitRules?: IElement; /** * The base language in which the resource is written. */ language?: string; /** * Extensions for language */ _language?: IElement; /** * A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety. */ text?: INarrative; /** * These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope. */ contained?: IResourceList[]; /** * May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. */ extension?: IExtension[]; /** * May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions. Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself). */ modifierExtension?: IExtension[]; /** * Business identifiers assigned to this family member history by the performer or other systems which remain constant as the resource is updated and propagates from server to server. */ identifier?: IIdentifier[]; /** * The URL pointing to a FHIR-defined protocol, guideline, orderset or other definition that is adhered to in whole or in part by this FamilyMemberHistory. */ instantiatesCanonical?: string[]; /** * The URL pointing to an externally maintained protocol, guideline, orderset or other definition that is adhered to in whole or in part by this FamilyMemberHistory. */ instantiatesUri?: string[]; /** * Extensions for instantiatesUri */ _instantiatesUri?: IElement[]; /** * A code specifying the status of the record of the family history of a specific family member. */ status?: FamilyMemberHistoryStatusKind; /** * Extensions for status */ _status?: IElement; /** * Describes why the family member's history is not available. */ dataAbsentReason?: ICodeableConcept; /** * The date (and possibly time) when the family member history was recorded or last updated. */ date?: string; /** * Extensions for date */ _date?: IElement; /** * This will either be a name or a description; e.g. "Aunt Susan", "my cousin with the red hair". */ name?: string; /** * Extensions for name */ _name?: IElement; /** * The birth sex of the family member. */ sex?: ICodeableConcept; /** * The actual or approximate date of birth of the relative. */ bornPeriod?: IPeriod; /** * The actual or approximate date of birth of the relative. */ bornDate?: string; /** * Extensions for bornDate */ _bornDate?: IElement; /** * The actual or approximate date of birth of the relative. */ bornString?: string; /** * Extensions for bornString */ _bornString?: IElement; /** * The age of the relative at the time the family member history is recorded. */ ageAge?: IAge; /** * The age of the relative at the time the family member history is recorded. */ ageRange?: IRange; /** * The age of the relative at the time the family member history is recorded. */ ageString?: string; /** * Extensions for ageString */ _ageString?: IElement; /** * If true, indicates that the age value specified is an estimated value. */ estimatedAge?: boolean; /** * Extensions for estimatedAge */ _estimatedAge?: IElement; /** * Deceased flag or the actual or approximate age of the relative at the time of death for the family member history record. */ deceasedBoolean?: boolean; /** * Extensions for deceasedBoolean */ _deceasedBoolean?: IElement; /** * Deceased flag or the actual or approximate age of the relative at the time of death for the family member history record. */ deceasedAge?: IAge; /** * Deceased flag or the actual or approximate age of the relative at the time of death for the family member history record. */ deceasedRange?: IRange; /** * Deceased flag or the actual or approximate age of the relative at the time of death for the family member history record. */ deceasedDate?: string; /** * Extensions for deceasedDate */ _deceasedDate?: IElement; /** * Deceased flag or the actual or approximate age of the relative at the time of death for the family member history record. */ deceasedString?: string; /** * Extensions for deceasedString */ _deceasedString?: IElement; /** * Describes why the family member history occurred in coded or textual form. */ reasonCode?: ICodeableConcept[]; /** * Indicates a Condition, Observation, AllergyIntolerance, or QuestionnaireResponse that justifies this family member history event. */ reasonReference?: IReference[]; /** * This property allows a non condition-specific note to the made about the related person. Ideally, the note would be in the condition property, but this is not always possible. */ note?: IAnnotation[]; /** * The significant Conditions (or condition) that the family member had. This is a repeating section to allow a system to represent more than one condition per resource, though there is nothing stopping multiple resources - one per condition. */ condition?: IFamilyMemberHistory_Condition[]; } export const RTTI_FamilyMemberHistory: t.Type< IFamilyMemberHistory > = t.recursion('IFamilyMemberHistory', () => t.intersection([ t.type({ resourceType: t.literal('FamilyMemberHistory'), patient: RTTI_Reference, relationship: RTTI_CodeableConcept }), t.partial({ id: RTTI_id, meta: RTTI_Meta, implicitRules: RTTI_uri, _implicitRules: RTTI_Element, language: RTTI_code, _language: RTTI_Element, text: RTTI_Narrative, contained: t.array(RTTI_ResourceList), extension: t.array(RTTI_Extension), modifierExtension: t.array(RTTI_Extension), identifier: t.array(RTTI_Identifier), instantiatesCanonical: t.array(RTTI_canonical), instantiatesUri: t.array(RTTI_uri), _instantiatesUri: t.array(RTTI_Element), status: createEnumType<FamilyMemberHistoryStatusKind>( FamilyMemberHistoryStatusKind, 'FamilyMemberHistoryStatusKind' ), _status: RTTI_Element, dataAbsentReason: RTTI_CodeableConcept, date: RTTI_dateTime, _date: RTTI_Element, name: t.string, _name: RTTI_Element, sex: RTTI_CodeableConcept, bornPeriod: RTTI_Period, bornDate: t.string, _bornDate: RTTI_Element, bornString: t.string, _bornString: RTTI_Element, ageAge: RTTI_Age, ageRange: RTTI_Range, ageString: t.string, _ageString: RTTI_Element, estimatedAge: t.boolean, _estimatedAge: RTTI_Element, deceasedBoolean: t.boolean, _deceasedBoolean: RTTI_Element, deceasedAge: RTTI_Age, deceasedRange: RTTI_Range, deceasedDate: t.string, _deceasedDate: RTTI_Element, deceasedString: t.string, _deceasedString: RTTI_Element, reasonCode: t.array(RTTI_CodeableConcept), reasonReference: t.array(RTTI_Reference), note: t.array(RTTI_Annotation), condition: t.array(RTTI_FamilyMemberHistory_Condition) }) ]) );
the_stack
import get from 'lodash/get'; import got, { Headers } from 'got'; import publicIp from 'public-ip'; import Logger from '@cumulus/logger'; import * as secretsManagerUtils from '@cumulus/aws-client/SecretsManager'; import { searchConcept } from './searchConcept'; import ingestConcept from './ingestConcept'; import deleteConcept from './deleteConcept'; import getConceptMetadata from './getConcept'; import { getIngestUrl, getTokenUrl } from './getUrl'; import { UmmMetadata, ummVersion, validateUMMG } from './UmmUtils'; const log = new Logger({ sender: 'cmr-client' }); const logDetails: { [key: string]: string } = { file: 'cmr-client/CMR.js', }; const IP_TIMEOUT_MS = 1 * 1000; const userIpAddress = (): Promise<string> => publicIp.v4({ timeout: IP_TIMEOUT_MS }) .catch(() => '127.0.0.1'); /** * Returns a valid a CMR token * * @param {string} cmrProvider - the CMR provider id * @param {string} clientId - the CMR clientId * @param {string} username - CMR username * @param {string} password - CMR password * @returns {Promise.<string>} the token * * @private */ async function updateToken( cmrProvider: string, clientId: string, username: string, password: string ): Promise<string> { const url = getTokenUrl(); // Update the saved ECHO token // for info on how to add collections to CMR: https://cmr.earthdata.nasa.gov/ingest/site/ingest_api_docs.html#validate-collection let response: { body: { token?: { id: string } } }; try { response = await got.post(url, { json: { token: { username: username, password: password, client_id: clientId, user_ip_address: await userIpAddress(), provider: cmrProvider, }, }, responseType: 'json', }); } catch (error) { if (get(error, 'response.body.errors')) { throw new Error(`CMR Error: ${error.response.body.errors[0]}`); } throw error; } if (!response.body.token) throw new Error('Authentication with CMR failed'); return response.body.token.id; } export interface CMRConstructorParams { clientId: string, password?: string, passwordSecretName?: string provider: string, token?: string, username: string, oauthProvider: string, } /** * A class to simplify requests to the CMR * * @typicalname cmrClient * * @example * const { CMR } = require('@cumulus/cmr-client'); * * const cmrClient = new CMR({ * provider: 'my-provider', * clientId: 'my-clientId', * username: 'my-username', * password: 'my-password' * }); * * or * * const cmrClient = new CMR({ * provider: 'my-provider', * clientId: 'my-clientId', * token: 'cmr_or_launchpad_token' * }); */ export class CMR { clientId: string; provider: string; username: string; oauthProvider: string; password?: string; passwordSecretName?: string; token?: string; /** * The constructor for the CMR class * * @param {Object} params * @param {string} params.provider - the CMR provider id * @param {string} params.clientId - the CMR clientId * @param {string} params.username - CMR username, not used if token is provided * @param {string} params.passwordSecretName - CMR password secret, not used if token is provided * @param {string} params.password - CMR password, not used if token or * passwordSecretName is provided * @param {string} params.token - CMR or Launchpad token, * if not provided, CMR username and password are used to get a cmr token * @param {string} params.oauthProvider - Oauth provider: earthdata or launchpad */ constructor(params: CMRConstructorParams) { this.clientId = params.clientId; this.provider = params.provider; this.username = params.username; this.password = params.password; this.passwordSecretName = params.passwordSecretName; this.token = params.token; this.oauthProvider = params.oauthProvider; } /** * Get the CMR password, from the AWS secret if set, else return the password * @returns {Promise.<string>} - the CMR password */ async getCmrPassword(): Promise<string> { if (this.passwordSecretName) { const value = await secretsManagerUtils.getSecretString( this.passwordSecretName ); if (!value) { throw new Error('Unable to retrieve CMR password'); } return value; } if (!this.password) { throw new Error('No CMR password set'); } return this.password; } /** * The method for getting the token * * @returns {Promise.<string>} the token */ async getToken(): Promise<string> { return this.token ? this.token : updateToken(this.provider, this.clientId, this.username, await this.getCmrPassword()); } /** * Return object containing CMR request headers for PUT / POST / DELETE * * @param {Object} params * @param {string} [params.token] - CMR request token * @param {string} [params.ummgVersion] - UMMG metadata version string or null if echo10 metadata * @param {string} [params.cmrRevisionId] - CMR Revision ID * @returns {Object} CMR headers object */ getWriteHeaders( params: { token?: string, ummgVersion?: string, cmrRevisionId?:string, } = {} ): Headers { const contentType = params.ummgVersion ? `application/vnd.nasa.cmr.umm+json;version=${params.ummgVersion}` : 'application/echo10+xml'; const headers: Headers = { 'Client-Id': this.clientId, 'Content-type': contentType, }; if (params.token) { if (this.oauthProvider === 'launchpad') headers.Authorization = params.token; else headers['Echo-Token'] = params.token; } if (params.ummgVersion) headers.Accept = 'application/json'; if (params.cmrRevisionId) headers['Cmr-Revision-Id'] = params.cmrRevisionId; return headers; } /** * Return object containing CMR request headers for GETs * * @param {Object} params * @param {string} [params.token] - CMR request token * @returns {Object} CMR headers object */ getReadHeaders(params: { token?: string } = {}): Headers { const headers: Headers = { 'Client-Id': this.clientId, }; if (params.token) { if (this.oauthProvider === 'launchpad') headers.Authorization = params.token; else headers['Echo-Token'] = params.token; } return headers; } /** * Adds a collection record to the CMR * * @param {string} xml - the collection XML document * @returns {Promise.<Object>} the CMR response */ async ingestCollection(xml: string): Promise<unknown> { const headers = this.getWriteHeaders({ token: await this.getToken() }); return await ingestConcept('collection', xml, 'Collection.DataSetId', this.provider, headers); } /** * Adds a granule record to the CMR * * @param {string} xml - the granule XML document * @param {string} cmrRevisionId - Optional CMR Revision ID * @returns {Promise.<Object>} the CMR response */ async ingestGranule(xml: string, cmrRevisionId?: string): Promise<unknown> { const headers = this.getWriteHeaders({ token: await this.getToken(), cmrRevisionId }); return await ingestConcept('granule', xml, 'Granule.GranuleUR', this.provider, headers); } /** * Adds/Updates UMMG json metadata in the CMR * * @param {Object} ummgMetadata - UMMG metadata object * @param {string} cmrRevisionId - Optional CMR Revision ID * @returns {Promise<Object>} to the CMR response object. */ async ingestUMMGranule(ummgMetadata: UmmMetadata, cmrRevisionId?: string): Promise<unknown> { const headers = this.getWriteHeaders({ token: await this.getToken(), ummgVersion: ummVersion(ummgMetadata), cmrRevisionId, }); const granuleId = ummgMetadata.GranuleUR || 'no GranuleId found on input metadata'; logDetails.granuleId = granuleId; let response: { body: { errors?: unknown } }; try { await validateUMMG(ummgMetadata, granuleId, this.provider); response = await got.put( `${getIngestUrl({ provider: this.provider })}granules/${granuleId}`, { json: ummgMetadata, responseType: 'json', headers, } ); if (response.body.errors) { throw new Error(`Failed to ingest, CMR Errors: ${response.body.errors}`); } } catch (error) { log.error(error, logDetails); throw error; } return response.body; } /** * Deletes a collection record from the CMR * * @param {string} datasetID - the collection unique id * @returns {Promise.<Object>} the CMR response */ async deleteCollection(datasetID: string): Promise<unknown> { const headers = this.getWriteHeaders({ token: await this.getToken() }); return await deleteConcept('collections', datasetID, this.provider, headers); } /** * Deletes a granule record from the CMR * * @param {string} granuleUR - the granule unique id * @returns {Promise.<Object>} the CMR response */ async deleteGranule(granuleUR: string): Promise<unknown> { const headers = this.getWriteHeaders({ token: await this.getToken() }); return await deleteConcept('granules', granuleUR, this.provider, headers); } async searchConcept( type: string, searchParams: URLSearchParams, format = 'json', recursive = true ): Promise<unknown[]> { const headers = this.getReadHeaders({ token: await this.getToken() }); return await searchConcept({ type, searchParams, previousResults: [], headers, format, recursive, }); } /** * Search in collections * * @param {string} params - the search parameters * @param {string} [format=json] - format of the response * @returns {Promise.<Object>} the CMR response */ async searchCollections( params: { [key: string]: string }, format = 'json' ): Promise<unknown[]> { const searchParams = new URLSearchParams({ provider_short_name: this.provider, ...params, }); return await this.searchConcept( 'collections', searchParams, format ); } /** * Search in granules * * @param {string} params - the search parameters * @param {string} [format='json'] - format of the response * @returns {Promise.<Object>} the CMR response */ async searchGranules( params: { [key: string]: string }, format = 'json' ): Promise<unknown[]> { const searchParams = new URLSearchParams({ provider_short_name: this.provider, ...params, }); return await this.searchConcept( 'granules', searchParams, format ); } /** * Get the granule metadata from CMR using the cmrLink * * @param {string} cmrLink - URL to concept * @returns {Object} - metadata as a JS object, null if not found */ async getGranuleMetadata(cmrLink: string): Promise<unknown> { const headers = this.getReadHeaders({ token: await this.getToken() }); return await getConceptMetadata(cmrLink, headers); } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [kinesisvideo](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonkinesisvideostreams.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Kinesisvideo extends PolicyStatement { public servicePrefix = 'kinesisvideo'; /** * Statement provider for service [kinesisvideo](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonkinesisvideostreams.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); } /** * Grants permission to connect as a master to the signaling channel specified by the endpoint * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ConnectAsMaster.html */ public toConnectAsMaster() { return this.to('ConnectAsMaster'); } /** * Grants permission to connect as a viewer to the signaling channel specified by the endpoint * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ConnectAsViewer.html */ public toConnectAsViewer() { return this.to('ConnectAsViewer'); } /** * Grants permission to create a signaling channel * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_CreateSignalingChannel.html */ public toCreateSignalingChannel() { return this.to('CreateSignalingChannel'); } /** * Grants permission to create a Kinesis video stream * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_CreateStream.html */ public toCreateStream() { return this.to('CreateStream'); } /** * Grants permission to delete an existing signaling channel * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_DeleteSignalingChannel.html */ public toDeleteSignalingChannel() { return this.to('DeleteSignalingChannel'); } /** * Grants permission to delete an existing Kinesis video stream * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_DeleteStream.html */ public toDeleteStream() { return this.to('DeleteStream'); } /** * Grants permission to describe the specified signaling channel * * Access Level: List * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_DescribeSignalingChannel.html */ public toDescribeSignalingChannel() { return this.to('DescribeSignalingChannel'); } /** * Grants permission to describe the specified Kinesis video stream * * Access Level: List * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_DescribeStream.html */ public toDescribeStream() { return this.to('DescribeStream'); } /** * Grants permission to get a media clip from a video stream * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetClip.html */ public toGetClip() { return this.to('GetClip'); } /** * Grants permission to create a URL for MPEG-DASH video streaming * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetDASHStreamingSessionURL.html */ public toGetDASHStreamingSessionURL() { return this.to('GetDASHStreamingSessionURL'); } /** * Grants permission to get an endpoint for a specified stream for either reading or writing media data to Kinesis Video Streams * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetDataEndpoint.html */ public toGetDataEndpoint() { return this.to('GetDataEndpoint'); } /** * Grants permission to create a URL for HLS video streaming * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetHLSStreamingSessionURL.html */ public toGetHLSStreamingSessionURL() { return this.to('GetHLSStreamingSessionURL'); } /** * Grants permission to get the ICE server configuration * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetIceServerConfig.html */ public toGetIceServerConfig() { return this.to('GetIceServerConfig'); } /** * Grants permission to return media content of a Kinesis video stream * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetMedia.html */ public toGetMedia() { return this.to('GetMedia'); } /** * Grants permission to read and return media data only from persisted storage * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetMediaForFragmentList.html */ public toGetMediaForFragmentList() { return this.to('GetMediaForFragmentList'); } /** * Grants permission to get endpoints for a specified combination of protocol and role for a signaling channel * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_GetSignalingChannelEndpoint.html */ public toGetSignalingChannelEndpoint() { return this.to('GetSignalingChannelEndpoint'); } /** * Grants permission to list the fragments from archival storage based on the pagination token or selector type with range specified * * Access Level: List * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ListFragments.html */ public toListFragments() { return this.to('ListFragments'); } /** * Grants permission to list your signaling channels * * Access Level: List * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ListSignalingChannels.html */ public toListSignalingChannels() { return this.to('ListSignalingChannels'); } /** * Grants permission to list your Kinesis video streams * * Access Level: List * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ListStreams.html */ public toListStreams() { return this.to('ListStreams'); } /** * Grants permission to fetch the tags associated with your resource * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to fetch the tags associated with Kinesis video stream * * Access Level: Read * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_ListTagsForStream.html */ public toListTagsForStream() { return this.to('ListTagsForStream'); } /** * Grants permission to send media data to a Kinesis video stream * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_PutMedia.html */ public toPutMedia() { return this.to('PutMedia'); } /** * Grants permission to send the Alexa SDP offer to the master * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_SendAlexaOfferToMaster.html */ public toSendAlexaOfferToMaster() { return this.to('SendAlexaOfferToMaster'); } /** * Grants permission to attach set of tags to your resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to attach set of tags to your Kinesis video streams * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_TagStream.html */ public toTagStream() { return this.to('TagStream'); } /** * Grants permission to remove one or more tags from your resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to remove one or more tags from your Kinesis video streams * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_UntagStream.html */ public toUntagStream() { return this.to('UntagStream'); } /** * Grants permission to update the data retention period of your Kinesis video stream * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_UpdateDataRetention.html */ public toUpdateDataRetention() { return this.to('UpdateDataRetention'); } /** * Grants permission to update an existing signaling channel * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_UpdateSignalingChannel.html */ public toUpdateSignalingChannel() { return this.to('UpdateSignalingChannel'); } /** * Grants permission to update an existing Kinesis video stream * * Access Level: Write * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_UpdateStream.html */ public toUpdateStream() { return this.to('UpdateStream'); } protected accessLevelList: AccessLevelList = { "Write": [ "ConnectAsMaster", "ConnectAsViewer", "CreateSignalingChannel", "CreateStream", "DeleteSignalingChannel", "DeleteStream", "PutMedia", "SendAlexaOfferToMaster", "UpdateDataRetention", "UpdateSignalingChannel", "UpdateStream" ], "List": [ "DescribeSignalingChannel", "DescribeStream", "ListFragments", "ListSignalingChannels", "ListStreams" ], "Read": [ "GetClip", "GetDASHStreamingSessionURL", "GetDataEndpoint", "GetHLSStreamingSessionURL", "GetIceServerConfig", "GetMedia", "GetMediaForFragmentList", "GetSignalingChannelEndpoint", "ListTagsForResource", "ListTagsForStream" ], "Tagging": [ "TagResource", "TagStream", "UntagResource", "UntagStream" ] }; /** * Adds a resource of type stream to the statement * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/how-it-works.html * * @param streamName - Identifier for the streamName. * @param creationTime - Identifier for the creationTime. * @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 onStream(streamName: string, creationTime: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kinesisvideo:${Region}:${Account}:stream/${StreamName}/${CreationTime}'; arn = arn.replace('${StreamName}', streamName); arn = arn.replace('${CreationTime}', creationTime); 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 channel to the statement * * https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/kinesisvideostreams-webrtc-dg/latest/devguide/kvswebrtc-how-it-works.html * * @param channelName - Identifier for the channelName. * @param creationTime - Identifier for the creationTime. * @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 onChannel(channelName: string, creationTime: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kinesisvideo:${Region}:${Account}:channel/${ChannelName}/${CreationTime}'; arn = arn.replace('${ChannelName}', channelName); arn = arn.replace('${CreationTime}', creationTime); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { Component } from 'react'; import { RouteComponentProps, withRouter } from 'react-router-dom'; import Loadable, { LoadingComponentProps } from 'react-loadable'; import classnames from 'classnames'; import axios, { AxiosResponse } from 'axios'; import produce from 'immer'; import qs from 'query-string'; import { isEqual, mapValues, pick, size } from 'lodash'; import type { TimePeriod, Venue, VenueDetailList, VenueSearchOptions } from 'types/venues'; import type { Subtract } from 'types/utils'; import type { WithBreakpoint } from 'views/hocs/makeResponsive'; import deferComponentRender from 'views/hocs/deferComponentRender'; import ApiError from 'views/errors/ApiError'; import Warning from 'views/errors/Warning'; import LoadingSpinner from 'views/components/LoadingSpinner'; import SearchBox from 'views/components/SearchBox'; import { Clock, Map } from 'react-feather'; import { venuePage } from 'views/routes/paths'; import Modal from 'views/components/Modal'; import Title from 'views/components/Title'; import NoFooter from 'views/layout/NoFooter'; import MapContext from 'views/components/map/MapContext'; import makeResponsive from 'views/hocs/makeResponsive'; import config from 'config'; import nusmods from 'apis/nusmods'; import HistoryDebouncer from 'utils/HistoryDebouncer'; import { clampClassDuration, filterAvailability, searchVenue, sortVenues } from 'utils/venues'; import { breakpointDown } from 'utils/css'; import { defer } from 'utils/react'; import { convertIndexToTime } from 'utils/timify'; import AvailabilitySearch, { defaultSearchOptions } from './AvailabilitySearch'; import VenueList from './VenueList'; import VenueDetails from './VenueDetails'; import VenueLocation from './VenueLocation'; import styles from './VenuesContainer.scss'; export type Params = { q: string; venue: string; }; type LoadedProps = { venues: VenueDetailList }; type Props = RouteComponentProps<Params> & LoadedProps & WithBreakpoint; type State = { // View state isMapExpanded: boolean; // Search state searchBoxValue: string; // Value of the controlled search box; updated real-time searchTerm: string; // Actual string to search with; deferred update isAvailabilityEnabled: boolean; searchOptions: VenueSearchOptions; pristineSearchOptions: boolean; }; const pageHead = <Title>Venues</Title>; export class VenuesContainerComponent extends Component<Props, State> { history: HistoryDebouncer; constructor(props: Props) { super(props); const { location, history } = props; const params = qs.parse(location.search); // Extract searchOptions from the query string if they are present const isAvailabilityEnabled = !!(params.time && params.day && params.duration); const searchOptions = isAvailabilityEnabled ? (mapValues(pick(params, ['time', 'day', 'duration']), (i) => { if (!i) return NaN; if (Array.isArray(i)) return parseInt(i[0], 10); return parseInt(i, 10); }) as VenueSearchOptions) : defaultSearchOptions(); this.history = new HistoryDebouncer(history); let searchTerm = params.q || ''; if (Array.isArray(searchTerm)) [searchTerm] = searchTerm; this.state = { searchOptions, isAvailabilityEnabled, isMapExpanded: false, searchTerm, searchBoxValue: searchTerm, // eslint-disable-next-line react/no-unused-state pristineSearchOptions: !isAvailabilityEnabled, }; } componentDidMount() { VenueLocation.preload(); } componentDidUpdate(prevProps: Props, prevState: State) { // Update URL if any of these props have changed const { searchOptions, searchTerm, isAvailabilityEnabled } = this.state; if (isAvailabilityEnabled !== prevState.isAvailabilityEnabled) { this.updateURL(false); } else if (searchOptions !== prevState.searchOptions || searchTerm !== prevState.searchTerm) { this.updateURL(); } } onFindFreeRoomsClicked = () => { this.setState( produce((draft) => { const { pristineSearchOptions, isAvailabilityEnabled } = draft; draft.isAvailabilityEnabled = !isAvailabilityEnabled; // Only reset search options if the user has never changed it, and if the // search box is being opened. By resetting the option when the box is opened, // the time when the box is opened will be used, instead of the time when the // page is loaded if (pristineSearchOptions && !isAvailabilityEnabled) { draft.searchOptions = defaultSearchOptions(); } }), ); }; onClearVenueSelect = () => this.props.history.push({ ...this.props.history.location, pathname: venuePage(), }); onSearchBoxChange = (searchBoxValue: string) => { this.setState({ searchBoxValue }); }; onSearch = () => { defer(() => this.setState((prevState) => ({ searchTerm: prevState.searchBoxValue.trim() }))); }; onAvailabilityUpdate = (searchOptions: VenueSearchOptions) => { if (!isEqual(searchOptions, this.state.searchOptions)) { this.setState({ searchOptions: clampClassDuration(searchOptions), // eslint-disable-next-line react/no-unused-state pristineSearchOptions: false, // user changed searchOptions }); } }; onToggleMapExpanded = (isMapExpanded: boolean) => { this.setState({ isMapExpanded }); }; updateURL = (debounce = true) => { const { searchTerm, isAvailabilityEnabled, searchOptions } = this.state; let query: Partial<Params> = {}; if (searchTerm) query.q = searchTerm; if (isAvailabilityEnabled) query = { ...query, ...searchOptions }; const pathname = venuePage(this.selectedVenue()); const history = debounce ? this.history : this.props.history; history.push({ ...this.props.location, search: qs.stringify(query), pathname, }); }; getHighlightPeriod(): TimePeriod | undefined { const { isAvailabilityEnabled, searchOptions } = this.state; if (!isAvailabilityEnabled) return undefined; return { day: searchOptions.day, startTime: convertIndexToTime(searchOptions.time * 2), endTime: convertIndexToTime(2 * (searchOptions.time + searchOptions.duration)), }; } selectedVenue(): Venue | null { const { venue } = this.props.match.params; if (!venue) return null; return decodeURIComponent(venue); } renderSearch() { const { searchBoxValue, isAvailabilityEnabled, searchOptions } = this.state; return ( <div className={styles.venueSearch}> <h3>Venue Search</h3> <SearchBox className={styles.searchBox} throttle={0} useInstantSearch isLoading={false} value={searchBoxValue} placeholder="e.g. LT27" onChange={this.onSearchBoxChange} onSearch={this.onSearch} /> <button className={classnames( 'btn btn-block btn-svg', styles.availabilityToggle, isAvailabilityEnabled ? 'btn-primary' : 'btn-outline-primary', )} onClick={this.onFindFreeRoomsClicked} type="button" > <Clock className="svg" /> Find free rooms </button> {isAvailabilityEnabled && ( <div className={styles.availabilitySearch}> <AvailabilitySearch isEnabled={isAvailabilityEnabled} searchOptions={searchOptions} onUpdate={this.onAvailabilityUpdate} /> </div> )} </div> ); } renderNoResult(unfilteredCount: number) { const { isAvailabilityEnabled } = this.state; return ( <> <Warning message="No matching venues found" /> {!!unfilteredCount && isAvailabilityEnabled && ( <p className="text-center text-muted"> {unfilteredCount === 1 ? 'There is a venue that is not shown because it is not free' : `There are ${unfilteredCount} venues that are not shown because they are not free`} <br /> <button type="button" className="btn btn-link" onClick={() => this.setState({ isAvailabilityEnabled: false })} > Show all rooms </button> </p> )} </> ); } renderSelectedVenue(matchedVenues: VenueDetailList) { const selectedVenue = this.selectedVenue(); const { venues } = this.props; if (!venues || !selectedVenue) return null; // Find the index of the current venue on the list of matched venues so // we can obtain the previous and next item const lowercaseSelectedVenue = selectedVenue.toLowerCase(); const venueIndex = matchedVenues.findIndex( ([venue]) => venue.toLowerCase() === lowercaseSelectedVenue, ); // The selected item may not be in the list of matched venues (if the user // changed their search options afterwards), in which case we look for it in all // venues if (venueIndex === -1) { const venueDetail = venues.find(([venue]) => venue.toLowerCase() === lowercaseSelectedVenue); if (!venueDetail) return null; const [venue, availability] = venueDetail; return ( <VenueDetails venue={venue} availability={availability} highlightPeriod={this.getHighlightPeriod()} /> ); } const [venue, availability] = matchedVenues[venueIndex]; const [previous] = matchedVenues[venueIndex - 1] || ([] as string[]); const [next] = matchedVenues[venueIndex + 1] || ([] as string[]); return ( <VenueDetails venue={venue} availability={availability} next={next} previous={previous} highlightPeriod={this.getHighlightPeriod()} /> ); } render() { const selectedVenue = this.selectedVenue(); const { searchTerm, isAvailabilityEnabled, isMapExpanded, searchOptions } = this.state; const { venues } = this.props; let matchedVenues = searchVenue(venues, searchTerm); const unfilteredCount = size(matchedVenues); if (isAvailabilityEnabled) { matchedVenues = filterAvailability(matchedVenues, searchOptions); } return ( <div className={classnames('page-container', styles.pageContainer)}> {pageHead} <div className={styles.venuesList}> {this.renderSearch()} {size(matchedVenues) === 0 ? ( this.renderNoResult(unfilteredCount) ) : ( <VenueList venues={matchedVenues.map(([venue]) => venue)} selectedVenue={selectedVenue} /> )} </div> <MapContext.Provider value={{ toggleMapExpanded: this.onToggleMapExpanded }}> {this.props.matchBreakpoint ? ( <Modal isOpen={selectedVenue != null} onRequestClose={this.onClearVenueSelect} className={styles.venueDetailModal} fullscreen > <button type="button" className={classnames('btn btn-outline-primary btn-block', styles.closeButton)} onClick={this.onClearVenueSelect} > Back to Venues </button> {this.renderSelectedVenue(matchedVenues)} </Modal> ) : ( <> <div className={classnames(styles.venueDetail, { [styles.mapExpanded]: isMapExpanded, })} > {selectedVenue == null ? ( <div className={styles.noVenueSelected}> <Map /> <p>Select a venue on the left to see its timetable</p> </div> ) : ( this.renderSelectedVenue(matchedVenues) )} </div> <NoFooter /> </> )} </MapContext.Provider> </div> ); } } // Explicitly declare top level components for React hot reloading to work. const ResponsiveVenuesContainer = makeResponsive(VenuesContainerComponent, breakpointDown('sm')); const RoutedVenuesContainer = withRouter(ResponsiveVenuesContainer); const AsyncVenuesContainer = Loadable.Map<Subtract<Props, LoadedProps>, { venues: AxiosResponse }>({ loader: { venues: () => axios.get(nusmods.venuesUrl(config.semester)), }, loading: (props: LoadingComponentProps) => { if (props.error) { return <ApiError dataName="venue information" retry={props.retry} />; } if (props.pastDelay) { return <LoadingSpinner />; } return null; }, render(loaded, props) { return <RoutedVenuesContainer venues={sortVenues(loaded.venues.data)} {...props} />; }, }); export default deferComponentRender(AsyncVenuesContainer); export function preload() { AsyncVenuesContainer.preload(); VenueLocation.preload(); }
the_stack
import { CdmDocumentDefinition, CdmEntityDefinition, CdmManifestDefinition, cdmStatusLevel, CdmCorpusDefinition, cdmObjectType, cdmLogCode, CdmTypeAttributeDefinition, CdmDataPartitionDefinition, CdmDataPartitionPatternDefinition } from '../../internal'; import { testHelper } from '../testHelper'; describe('Utilities.EventList', () => { const testsSubpath: string = 'Utilities'; /** Dummy value used for correlation ID testing. */ const DummyCorrelationId: string = '12345'; /** Declare a blackhole callback. We're focusing on event recorder, don't care about output going to the standard log stream. */ const eventCallback = () => { } /** * Test update and fetch list lookup default value without attributeValue and displayOrder. */ it('TestWithoutNesting', async () => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEventList'); corpus.setEventCallback(eventCallback, cdmStatusLevel.warning, DummyCorrelationId); // Test fetching an object from invalid namespace results in at least one error message in the recorder await corpus.fetchObjectAsync('foo:/bar'); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageAdapterNotFound, true) // Test fetching a good object, this should leave event recorder empty await corpus.fetchObjectAsync('local:/default.manifest.cdm.json'); TestNoLogsState(corpus); // Test saving a manifest to invalid namespace results in at least one error message in the recorder let manifest: CdmManifestDefinition = corpus.MakeObject(cdmObjectType.manifestDef, 'dummy'); await manifest.saveAsAsync('foo:/bar', true); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrValdnMissingDoc, true) // Test resolving a manifest not added to a folder, this should yield at least one error message in the recorder await manifest.createResolvedManifestAsync('new dummy', null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrResolveManifestFailed, true) // Test resolving an entity without WRT doc, this should yield at least one error message in the recorder let entity2: CdmEntityDefinition = corpus.MakeObject(cdmObjectType.entityDef, 'MyEntity2'); await entity2.createResolvedEntityAsync('MyEntity2-Resolved'); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrDocWrtDocNotfound, true) // Test invoking FileStatusCheckAsync on the manifest, this should yield at least one error message in the recorder await manifest.fileStatusCheckAsync(); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageNullNamespace, true) // Repeat the same test but with status level 'None', no events should be recorded corpus.ctx.reportAtLevel = cdmStatusLevel.none; await entity2.createResolvedEntityAsync('MyEntity2-Resolved'); TestNoLogsState(corpus); // Test checking file status on a data partition // We're at log level 'Progress', so we get the EnterScope/LeaveScope messages too corpus.ctx.reportAtLevel = cdmStatusLevel.progress; const part: CdmDataPartitionDefinition = corpus.MakeObject(cdmObjectType.dataPartitionDef, 'part'); await part.fileStatusCheckAsync(); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrPathNullObjectPath, true); // Test checking file status on a data partition pattern const refDoc: CdmDocumentDefinition = corpus.MakeObject(cdmObjectType.documentDef, 'RefEntDoc'); const partPattern: CdmDataPartitionPatternDefinition = corpus.MakeObject(cdmObjectType.dataPartitionPatternDef, 'partPattern'); partPattern.inDocument = refDoc; await partPattern.fileStatusCheckAsync(); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageNullCorpusPath, true); // Test calculating relationships - no errors/warnings await corpus.calculateEntityGraphAsync(manifest); TestBasicLogsState(corpus); // Test populating relationships in manifest - no errors/warnings await manifest.populateManifestRelationshipsAsync(); TestBasicLogsState(corpus); // Test filtering code logic corpus.ctx.suppressedLogCodes.add(cdmLogCode.ErrPathNullObjectPath); const part2: CdmDataPartitionDefinition = corpus.MakeObject(cdmObjectType.dataPartitionDef, 'part2'); await part2.fileStatusCheckAsync(); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrPathNullObjectPath, false); }); /** * Tests a use case where recording nesting happens, such as CreateResolvedManifestAsync making calls to CreateResolvedEntityAsync. */ it('TestWithNesting', async () => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEventList'); corpus.setEventCallback(eventCallback, cdmStatusLevel.warning, DummyCorrelationId); let manifest: CdmManifestDefinition = corpus.MakeObject(cdmObjectType.manifestDef, 'dummy'); // Test resolving a manifest (added to a folder) with an entity in it, this should collect messages from // CreateResolvedManifestAsync and CreateResolvedEntityAsync functions corpus.storage.fetchRootFolder('local').documents.push(manifest); let entity1: CdmEntityDefinition = corpus.MakeObject(cdmObjectType.entityDef, 'MyEntity1'); let someAttrib1: CdmTypeAttributeDefinition = corpus.MakeObject(cdmObjectType.typeAttributeDef, 'someAttrib1', false); someAttrib1.dataType = corpus.MakeRef(cdmObjectType.dataTypeRef, 'entityId', true); entity1.attributes.push(someAttrib1); let entity1Doc: CdmDocumentDefinition = corpus.MakeObject(cdmObjectType.documentDef, 'MyEntity1.cdm.json'); entity1Doc.definitions.push(entity1); corpus.storage.fetchRootFolder('local').documents.push(entity1Doc); manifest.entities.push(entity1); await manifest.createResolvedManifestAsync('new dummy 2', null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrResolveReferenceFailure, true) // Keep for debugging // corpus.ctx.events.allItems.forEach(logEntry => { // logEntry.forEach((key: string, value: string) => console.log(`${key}=${value}`)) // }); }); /** * Tests events generated in StorageManager APIs */ it('TestStorageManagerEvents', async () => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEventList'); corpus.setEventCallback(eventCallback, cdmStatusLevel.info, DummyCorrelationId); corpus.storage.mount('dummy', null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageNullAdapter, true); corpus.storage.unMount('nothing'); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.WarnStorageRemoveAdapterFailed, true); // No errors/warnings expected here corpus.storage.fetchRootFolder(null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageNullNamespace, true); corpus.storage.adapterPathToCorpusPath('Test'); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageInvalidAdapterPath, true); corpus.storage.corpusPathToAdapterPath('unknown:/Test'); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageAdapterNotFound, true); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrStorageNamespaceNotRegistered, true); corpus.storage.createAbsoluteCorpusPath(null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrPathNullObjectPath, true); corpus.storage.createRelativeCorpusPath(null); TestBasicLogsState(corpus); testHelper.expectCdmLogCodeEquality(corpus, cdmLogCode.ErrPathNullObjectPath, true); }); /** * Test logging of API scope entry/exit. */ it('TestScoping', async () => { const corpus: CdmCorpusDefinition = testHelper.getLocalCorpus(testsSubpath, 'TestEventList'); // For scoping test we need to use log level info corpus.setEventCallback(eventCallback, cdmStatusLevel.info, DummyCorrelationId); await corpus.fetchObjectAsync('local:/default.manifest.cdm.json'); expect(corpus.ctx.events.isRecording).toBe(false); expect(corpus.ctx.events.length).toBeGreaterThan(2); TestBasicLogsState(corpus); // Verify method on entry/exit event expect(corpus.ctx.events.allItems[0].get('method')).toBe('fetchObjectAsync') expect(corpus.ctx.events.allItems[corpus.ctx.events.length - 1].get('method')).toBe('fetchObjectAsync') // Keep for debugging // corpus.ctx.events.allItems.forEach(logEntry => { // logEntry.forEach((key: string, value: string) => console.log(`${key}=${value}`)) // }); }); /// <summary> /// Helper function to test that recording is stopped and no logs are recorded. /// </summary> /// <param name="corpus"></param> function TestNoLogsState(corpus: CdmCorpusDefinition): void { TestBasicLogsState(corpus, true); } /// <summary> /// Helper function to check for event list state and presence of scope enter/leave logs. /// </summary> /// <param name="corpus"></param> /// <param name="expectNoLogs">If true, tests that recording is stopped and there are no logs in EventList. If false, /// tests that there are multiple entries and log enter/exit events were logged.</param> function TestBasicLogsState(corpus: CdmCorpusDefinition, expectNoLogs: boolean = false): void { expect(corpus.ctx.events).not.toBeUndefined(); expect(corpus.ctx.events.isRecording).toBe(false); if (expectNoLogs) { expect(corpus.ctx.events.length).toBe(0); } else { expect(corpus.ctx.events.length).toBeGreaterThan(0); expect(corpus.ctx.events.allItems[0].has('timestamp')).toBe(true); expect(corpus.ctx.events.allItems[0].get('cid')).toBe(DummyCorrelationId); if (corpus.ctx.reportAtLevel == cdmStatusLevel.progress) { expect(corpus.ctx.events.allItems[0].get('message')).toBe('Entering scope'); expect(corpus.ctx.events.allItems[corpus.ctx.events.length - 1].get('message').startsWith('Leaving scope')).toBe(true); } } } });
the_stack
import { resetAllWhenMocks, verifyAllWhenMocksCalled } from 'jest-when'; import { ExposesEntry } from '../src/z2mModels'; import { setHap, hap } from '../src/hap'; import * as hapNodeJs from 'hap-nodejs'; import 'jest-chain'; import { ServiceHandlersTestHarness, testJsonDeviceListEntry } from './testHelpers'; jest.useFakeTimers(); describe('Cover', () => { beforeEach(() => { setHap(hapNodeJs); }); describe('IKEA KADRILJ roller blind', () => { const deviceModelJson = `{ "date_code": "20190311", "definition": { "description": "KADRILJ roller blind", "exposes": [ { "features": [ { "access": 7, "name": "state", "property": "state", "type": "binary", "value_off": "CLOSE", "value_on": "OPEN" }, { "access": 7, "description": "Position of this cover", "name": "position", "property": "position", "type": "numeric", "value_max": 100, "value_min": 0 } ], "type": "cover" }, { "access": 1, "description": "Remaining battery in %", "name": "battery", "property": "battery", "type": "numeric", "unit": "%", "value_max": 100, "value_min": 0 }, { "access": 1, "description": "Link quality (signal strength)", "name": "linkquality", "property": "linkquality", "type": "numeric", "unit": "lqi", "value_max": 255, "value_min": 0 } ], "model": "E1926", "vendor": "IKEA" }, "endpoints": { "1": { "bindings": [ { "cluster": "genPowerCfg", "target": { "endpoint": 1, "ieee_address": "0x00124b001caa69fb", "type": "endpoint" } }, { "cluster": "closuresWindowCovering", "target": { "endpoint": 1, "ieee_address": "0x00124b001caa69fb", "type": "endpoint" } } ], "clusters": { "input": [ "genBasic", "genPowerCfg", "genIdentify", "genGroups", "genScenes", "genPollCtrl", "closuresWindowCovering", "touchlink" ], "output": [ "genOta", "touchlink" ] } } }, "friendly_name": "blinds_livingroom_side", "ieee_address": "0x000d6ffffea9430d", "interview_completed": true, "interviewing": false, "network_address": 13941, "power_source": "Battery", "software_build_id": "2.2.009", "supported": true, "type": "EndDevice" }`; // Shared "state" let deviceExposes: ExposesEntry[] = []; let harness: ServiceHandlersTestHarness; beforeEach(() => { // Only test service creation for first test case and reuse harness afterwards if (deviceExposes.length === 0 && harness === undefined) { // Test JSON Device List entry const device = testJsonDeviceListEntry(deviceModelJson); deviceExposes = device?.definition?.exposes ?? []; expect(deviceExposes?.length).toBeGreaterThan(0); const newHarness = new ServiceHandlersTestHarness(); // Check service creation const windowCovering = newHarness.getOrAddHandler(hap.Service.WindowCovering) .addExpectedCharacteristic('position', hap.Characteristic.CurrentPosition, false) .addExpectedCharacteristic('target_position', hap.Characteristic.TargetPosition, true, undefined, false) .addExpectedCharacteristic('position_state', hap.Characteristic.PositionState, false, undefined, false); newHarness.prepareCreationMocks(); const positionCharacteristicMock = windowCovering.getCharacteristicMock('position'); if (positionCharacteristicMock !== undefined) { positionCharacteristicMock.props.minValue = 0; positionCharacteristicMock.props.maxValue = 100; } const targetPositionCharacteristicMock = windowCovering.getCharacteristicMock('target_position'); if (targetPositionCharacteristicMock !== undefined) { targetPositionCharacteristicMock.props.minValue = 0; targetPositionCharacteristicMock.props.maxValue = 100; } newHarness.callCreators(deviceExposes); newHarness.checkCreationExpectations(); newHarness.checkExpectedGetableKeys(['position']); harness = newHarness; } harness?.clearMocks(); }); afterEach(() => { verifyAllWhenMocksCalled(); resetAllWhenMocks(); }); test('Status update is handled: Position changes', () => { expect(harness).toBeDefined(); // First update (previous state is unknown, so) harness.checkUpdateState('{"position":100}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 100], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 100], ])); harness.clearMocks(); }); test('HomeKit: Change target position', () => { expect(harness).toBeDefined(); // Set current position to a known value, to check assumed position state harness.checkUpdateState('{"position":50}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 50], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 50], ])); harness.clearMocks(); // Check changing the position to a higher value harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 51, { position: 51 }); const windowCovering = harness.getOrAddHandler(hap.Service.WindowCovering).checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.INCREASING], ])); harness.clearMocks(); // Receive status update with target position that was previously send. // This should be ignored. harness.checkUpdateStateIsIgnored('{"position":51}'); harness.clearMocks(); // Check changing the position to a lower value harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 49, { position: 49 }); windowCovering.checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.DECREASING], ])); harness.clearMocks(); // Send two updates - should stop timer harness.checkUpdateState('{"position":51}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 51], ])); harness.clearMocks(); harness.checkUpdateState('{"position":49}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 49], ])); harness.clearMocks(); harness.checkUpdateState('{"position":49}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 49], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 49], ])); harness.clearMocks(); // Check timer - should request position jest.runOnlyPendingTimers(); windowCovering.checkNoCharacteristicUpdates(); harness.checkNoGetKeysQueued(); // Check changing the position to the same value as was last received harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 49, { position: 49 }); windowCovering.checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], ])); harness.clearMocks(); // Check timer - should request position jest.runOnlyPendingTimers(); harness.checkGetKeysQueued('position'); harness.clearMocks(); }); }); describe('Insta Flush-Mount Blinds Actuator', () => { const deviceModelJson = `{ "date_code": "", "definition": { "description": "Blinds actor with Lift/Tilt Calibration & with inputs for wall switches", "exposes": [ { "features": [ { "access": 3, "name": "state", "property": "state", "type": "binary", "value_off": "CLOSE", "value_on": "OPEN" }, { "access": 7, "description": "Position of this cover", "name": "position", "property": "position", "type": "numeric", "value_max": 100, "value_min": 0 }, { "access": 7, "description": "Tilt of this cover", "name": "tilt", "property": "tilt", "type": "numeric", "value_max": 100, "value_min": 0 } ], "type": "cover" }, { "access": 1, "description": "Link quality (signal strength)", "name": "linkquality", "property": "linkquality", "type": "numeric", "unit": "lqi", "value_max": 255, "value_min": 0 } ], "model": "57008000", "supports_ota": false, "vendor": "Insta GmbH" }, "endpoints": { "6": { "bindings": [ { "cluster": "genOta", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } }, { "cluster": "closuresWindowCovering", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } }, { "cluster": "genBasic", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } }, { "cluster": "genOnOff", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } } ], "clusters": { "input": [ "genBasic", "genIdentify", "genGroups", "genScenes", "closuresWindowCovering" ], "output": [ "genIdentify", "genOta" ] }, "configured_reportings": [ { "attribute": "currentPositionLiftPercentage", "cluster": "closuresWindowCovering", "maximum_report_interval": 62000, "minimum_report_interval": 1, "reportable_change": 1 } ] }, "7": { "bindings": [ { "cluster": "genBasic", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } }, { "cluster": "closuresWindowCovering", "target": { "endpoint": 1, "ieee_address": "0x00212effff06eebd", "type": "endpoint" } } ], "clusters": { "input": [ "genBasic", "genIdentify" ], "output": [ "genIdentify", "genGroups", "genOta", "closuresWindowCovering" ] }, "configured_reportings": [] }, "242": { "bindings": [], "clusters": { "input": [], "output": [ "greenPower" ] }, "configured_reportings": [] } }, "friendly_name": "Rollo", "ieee_address": "0x842e14fffea1cd5f", "interview_completed": true, "interviewing": false, "model_id": "Generic UP Device", "network_address": 22147, "power_source": "Mains (single phase)", "software_build_id": "00.47.00", "supported": true, "type": "Router" }`; // Shared "state" let deviceExposes: ExposesEntry[] = []; let harness: ServiceHandlersTestHarness; beforeEach(() => { // Only test service creation for first test case and reuse harness afterwards if (deviceExposes.length === 0 && harness === undefined) { // Test JSON Device List entry const device = testJsonDeviceListEntry(deviceModelJson); deviceExposes = device?.definition?.exposes ?? []; expect(deviceExposes?.length).toBeGreaterThan(0); const newHarness = new ServiceHandlersTestHarness(); // Check service creation const windowCovering = newHarness.getOrAddHandler(hap.Service.WindowCovering) .addExpectedCharacteristic('position', hap.Characteristic.CurrentPosition, false) .addExpectedCharacteristic('target_position', hap.Characteristic.TargetPosition, true, undefined, false) .addExpectedCharacteristic('position_state', hap.Characteristic.PositionState, false, undefined, false) .addExpectedCharacteristic('tilt', hap.Characteristic.CurrentHorizontalTiltAngle, false) .addExpectedCharacteristic('target_tilt', hap.Characteristic.TargetHorizontalTiltAngle, true, undefined, false); newHarness.prepareCreationMocks(); const positionCharacteristicMock = windowCovering.getCharacteristicMock('position'); if (positionCharacteristicMock !== undefined) { positionCharacteristicMock.props.minValue = 0; positionCharacteristicMock.props.maxValue = 100; } const targetPositionCharacteristicMock = windowCovering.getCharacteristicMock('target_position'); if (targetPositionCharacteristicMock !== undefined) { targetPositionCharacteristicMock.props.minValue = 0; targetPositionCharacteristicMock.props.maxValue = 100; } const tiltCharacteristicMock = windowCovering.getCharacteristicMock('tilt'); if (tiltCharacteristicMock !== undefined) { tiltCharacteristicMock.props.minValue = -90; tiltCharacteristicMock.props.maxValue = 90; } const targetTiltCharacteristicMock = windowCovering.getCharacteristicMock('target_tilt'); if (targetTiltCharacteristicMock !== undefined) { targetTiltCharacteristicMock.props.minValue = -90; targetTiltCharacteristicMock.props.maxValue = 90; } newHarness.callCreators(deviceExposes); newHarness.checkCreationExpectations(); newHarness.checkExpectedGetableKeys(['position', 'tilt']); harness = newHarness; } harness?.clearMocks(); }); afterEach(() => { verifyAllWhenMocksCalled(); resetAllWhenMocks(); }); test('Check new changed Tilt', () => { expect(harness).toBeDefined(); // Expect CurrentHorizontalTiltAngle to be retrieved to determine range harness.getOrAddHandler(hap.Service.WindowCovering).prepareGetCharacteristicMock('tilt'); // External tilt update 100% harness.checkUpdateState('{"position":100, "tilt":100}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 100], [hap.Characteristic.CurrentHorizontalTiltAngle, 90], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 100], ])); harness.clearMocks(); // External tilt update 50% harness.checkUpdateState('{"position":100, "tilt":50}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 100], [hap.Characteristic.CurrentHorizontalTiltAngle, 0], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 100], ])); harness.clearMocks(); // External tilt update 0% harness.checkUpdateState('{"position":100, "tilt":0}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 100], [hap.Characteristic.CurrentHorizontalTiltAngle, -90], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 100], ])); }); test('HomeKit: Change target tilt', () => { expect(harness).toBeDefined(); // Check changing the tilt to -90° harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_tilt', -90, { tilt: 0 }); harness.clearMocks(); // Check changing the tilt to -90° harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_tilt', 0, { tilt: 50 }); harness.clearMocks(); // Check changing the tilt to -90° harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_tilt', 90, { tilt: 100 }); harness.clearMocks(); }); }); describe('Current Products Corp CP180335E-01', () => { const deviceModelJson = `{ "date_code":"", "definition":{ "description":"Gen. 2 hybrid E-Wand", "exposes":[ { "access":1, "description":"Remaining battery in %", "name":"battery", "property":"battery", "type":"numeric", "unit":"%", "value_max":100, "value_min":0 }, { "features":[ { "access":3, "name":"state", "property":"state", "type":"enum", "values":[ "OPEN", "CLOSE", "STOP" ] }, { "access":7, "description":"Tilt of this cover", "name":"tilt", "property":"tilt", "type":"numeric", "value_max":100, "value_min":0 } ], "type":"cover" }, { "access":1, "description":"Link quality (signal strength)", "name":"linkquality", "property":"linkquality", "type":"numeric", "unit":"lqi", "value_max":255, "value_min":0 } ], "model":"CP180335E-01", "supports_ota":false, "vendor":"Current Products Corp" }, "endpoints":{ "1":{ "bindings":[ { "cluster":"genPowerCfg", "target":{ "endpoint":1, "ieee_address":"0x00212effff074469", "type":"endpoint" } }, { "cluster":"closuresWindowCovering", "target":{ "endpoint":1, "ieee_address":"0x00212effff074469", "type":"endpoint" } } ], "clusters":{ "input":[ "genBasic", "genPowerCfg", "genIdentify", "genGroups", "genScenes", "genOnOff", "genLevelCtrl", "genPollCtrl", "closuresWindowCovering", "haDiagnostic" ], "output":[ "genIdentify", "genOta" ] }, "configured_reportings":[ { "attribute":"batteryPercentageRemaining", "cluster":"genPowerCfg", "maximum_report_interval":62000, "minimum_report_interval":3600, "reportable_change":0 }, { "attribute":"currentPositionTiltPercentage", "cluster":"closuresWindowCovering", "maximum_report_interval":62000, "minimum_report_interval":1, "reportable_change":1 } ] } }, "friendly_name":"0x847127fffe4cf99c", "ieee_address":"0x847127fffe4cf99c", "interview_completed":true, "interviewing":false, "manufacturer":"Current Products Corp", "model_id":"E-Wand", "network_address":57023, "power_source":"Battery", "supported":true, "type":"EndDevice" }`; // Shared "state" let deviceExposes: ExposesEntry[] = []; let harness: ServiceHandlersTestHarness; beforeEach(() => { // Only test service creation for first test case and reuse harness afterwards if (deviceExposes.length === 0 && harness === undefined) { // Test JSON Device List entry const device = testJsonDeviceListEntry(deviceModelJson); deviceExposes = device?.definition?.exposes ?? []; expect(deviceExposes?.length).toBeGreaterThan(0); const newHarness = new ServiceHandlersTestHarness(); // Check service creation const windowCovering = newHarness.getOrAddHandler(hap.Service.WindowCovering) .addExpectedCharacteristic('position', hap.Characteristic.CurrentPosition, false, 'tilt') .addExpectedCharacteristic('target_position', hap.Characteristic.TargetPosition, true, undefined, false) .addExpectedCharacteristic('position_state', hap.Characteristic.PositionState, false, undefined, false); newHarness.prepareCreationMocks(); const positionCharacteristicMock = windowCovering.getCharacteristicMock('position'); if (positionCharacteristicMock !== undefined) { positionCharacteristicMock.props.minValue = 0; positionCharacteristicMock.props.maxValue = 100; } const targetPositionCharacteristicMock = windowCovering.getCharacteristicMock('target_position'); if (targetPositionCharacteristicMock !== undefined) { targetPositionCharacteristicMock.props.minValue = 0; targetPositionCharacteristicMock.props.maxValue = 100; } newHarness.callCreators(deviceExposes); newHarness.checkCreationExpectations(); harness = newHarness; } harness?.clearMocks(); }); afterEach(() => { verifyAllWhenMocksCalled(); resetAllWhenMocks(); }); test('Status update is handled: Position changes', () => { expect(harness).toBeDefined(); // First update (previous state is unknown, so) harness.checkUpdateState('{"tilt":100}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 100], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 100], ])); harness.clearMocks(); }); test('HomeKit: Change target position', () => { expect(harness).toBeDefined(); // Set current position to a known value, to check assumed position state harness.checkUpdateState('{"tilt":50}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 50], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 50], ])); harness.clearMocks(); // Check changing the position to a higher value harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 51, { tilt: 51 }); const windowCovering = harness.getOrAddHandler(hap.Service.WindowCovering).checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.INCREASING], ])); harness.clearMocks(); // Receive status update with target position that was previously send. // This should be ignored. harness.checkUpdateStateIsIgnored('{"tilt":51}'); harness.clearMocks(); // Check changing the position to a lower value harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 49, { tilt: 49 }); windowCovering.checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.DECREASING], ])); harness.clearMocks(); // Send two updates - should stop timer harness.checkUpdateState('{"tilt":51}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 51], ])); harness.clearMocks(); harness.checkUpdateState('{"tilt":49}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 49], ])); harness.clearMocks(); harness.checkUpdateState('{"tilt":49}', hap.Service.WindowCovering, new Map([ [hap.Characteristic.CurrentPosition, 49], [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], [hap.Characteristic.TargetPosition, 49], ])); harness.clearMocks(); // Check timer - should request position jest.runOnlyPendingTimers(); windowCovering.checkNoCharacteristicUpdates(); harness.checkNoGetKeysQueued(); // Check changing the position to the same value as was last received harness.checkHomeKitUpdate(hap.Service.WindowCovering, 'target_position', 49, { tilt: 49 }); windowCovering.checkCharacteristicUpdates(new Map([ [hap.Characteristic.PositionState, hap.Characteristic.PositionState.STOPPED], ])); harness.clearMocks(); // Check timer - should request position jest.runOnlyPendingTimers(); harness.checkGetKeysQueued('tilt'); harness.clearMocks(); }); }); });
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://streetviewpublish.googleapis.com/$discovery/rest?version=v1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Street View Publish API v1 */ function load(name: "streetviewpublish", version: "v1"): PromiseLike<void>; function load(name: "streetviewpublish", version: "v1", callback: () => any): void; const photo: streetviewpublish.PhotoResource; const photos: streetviewpublish.PhotosResource; namespace streetviewpublish { interface BatchDeletePhotosRequest { /** * Required. IDs of the Photos. For HTTP * GET requests, the URL query parameter should be * `photoIds=<id1>&photoIds=<id2>&...`. */ photoIds?: string[]; } interface BatchDeletePhotosResponse { /** * The status for the operation to delete a single * Photo in the batch request. */ status?: Status[]; } interface BatchGetPhotosResponse { /** * List of results for each individual * Photo requested, in the same order as * the requests in * BatchGetPhotos. */ results?: PhotoResponse[]; } interface BatchUpdatePhotosRequest { /** * Required. List of * UpdatePhotoRequests. */ updatePhotoRequests?: UpdatePhotoRequest[]; } interface BatchUpdatePhotosResponse { /** * List of results for each individual * Photo updated, in the same order as * the request. */ results?: PhotoResponse[]; } interface Connection { /** * Required. The destination of the connection from the containing photo to * another photo. */ target?: PhotoId; } interface LatLng { /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } interface Level { /** * Required. A name assigned to this Level, restricted to 3 characters. * Consider how the elevator buttons would be labeled for this level if there * was an elevator. */ name?: string; /** * Floor number, used for ordering. 0 indicates the ground level, 1 indicates * the first level above ground level, -1 indicates the first level under * ground level. Non-integer values are OK. */ number?: number; } interface ListPhotosResponse { /** * Token to retrieve the next page of results, or empty if there are no more * results in the list. */ nextPageToken?: string; /** * List of photos. The maximum number of items returned is based on the * pageSize field * in the request. */ photos?: Photo[]; } interface Operation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** The error result of the operation in case of failure or cancellation. */ error?: Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should have the format of `operations/some/unique/name`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } interface Photo { /** * Absolute time when the photo was captured. * When the photo has no exif timestamp, this is used to set a timestamp in * the photo metadata. */ captureTime?: string; /** * Connections to other photos. A connection represents the link from this * photo to another photo. */ connections?: Connection[]; /** * Output only. The download URL for the photo bytes. This field is set only * when * GetPhotoRequest.view * is set to * PhotoView.INCLUDE_DOWNLOAD_URL. */ downloadUrl?: string; /** * Required when updating a photo. Output only when creating a photo. * Identifier for the photo, which is unique among all photos in * Google. */ photoId?: PhotoId; /** Places where this photo belongs. */ places?: Place[]; /** Pose of the photo. */ pose?: Pose; /** Output only. The share link for the photo. */ shareLink?: string; /** Output only. The thumbnail URL for showing a preview of the given photo. */ thumbnailUrl?: string; /** * Required when creating a photo. Input only. The resource URL where the * photo bytes are uploaded to. */ uploadReference?: UploadRef; /** Output only. View count of the photo. */ viewCount?: string; } interface PhotoId { /** Required. A unique identifier for a photo. */ id?: string; } interface PhotoResponse { /** * The Photo resource, if the request * was successful. */ photo?: Photo; /** * The status for the operation to get or update a single photo in the batch * request. */ status?: Status; } interface Place { /** * Place identifier, as described in * https://developers.google.com/places/place-id. */ placeId?: string; } interface Pose { /** * Altitude of the pose in meters above ground level (as defined by WGS84). * NaN indicates an unmeasured quantity. */ altitude?: number; /** * Compass heading, measured at the center of the photo in degrees clockwise * from North. Value must be >=0 and <360. * NaN indicates an unmeasured quantity. */ heading?: number; /** * Latitude and longitude pair of the pose, as explained here: * https://cloud.google.com/datastore/docs/reference/rest/Shared.Types/LatLng * When creating a Photo, if the * latitude and longitude pair are not provided here, the geolocation from the * exif header will be used. If the latitude and longitude pair is not * provided and cannot be found in the exif header, the create photo process * will fail. */ latLngPair?: LatLng; /** Level (the floor in a building) used to configure vertical navigation. */ level?: Level; /** * Pitch, measured at the center of the photo in degrees. Value must be >=-90 * and <= 90. A value of -90 means looking directly down, and a value of 90 * means looking directly up. * NaN indicates an unmeasured quantity. */ pitch?: number; /** * Roll, measured in degrees. Value must be >= 0 and <360. A value of 0 * means level with the horizon. * NaN indicates an unmeasured quantity. */ roll?: number; } interface Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface UpdatePhotoRequest { /** * Required. Photo object containing the * new metadata. */ photo?: Photo; /** * Mask that identifies fields on the photo metadata to update. * If not present, the old Photo * metadata will be entirely replaced with the * new Photo metadata in this request. * The update fails if invalid fields are specified. Multiple fields can be * specified in a comma-delimited list. * * The following fields are valid: * * &#42; `pose.heading` * &#42; `pose.latLngPair` * &#42; `pose.pitch` * &#42; `pose.roll` * &#42; `pose.level` * &#42; `pose.altitude` * &#42; `connections` * &#42; `places` * * * <aside class="note"><b>Note:</b> Repeated fields in * updateMask * mean the entire set of repeated values will be replaced with the new * contents. For example, if * updateMask * contains `connections` and `UpdatePhotoRequest.photo.connections` is empty, * all connections will be removed.</aside> */ updateMask?: string; } interface UploadRef { /** * Required. An upload reference should be unique for each user. It follows * the form: * "https://streetviewpublish.googleapis.com/media/user/{account_id}/photo/{upload_reference}" */ uploadUrl?: string; } interface PhotoResource { /** * After the client finishes uploading the photo with the returned * UploadRef, * CreatePhoto * publishes the uploaded Photo to * Street View on Google Maps. * * Currently, the only way to set heading, pitch, and roll in CreatePhoto is * through the [Photo Sphere XMP * metadata](https://developers.google.com/streetview/spherical-metadata) in * the photo bytes. The `pose.heading`, `pose.pitch`, `pose.roll`, * `pose.altitude`, and `pose.level` fields in Pose are ignored for * CreatePhoto. * * This method returns the following error codes: * * &#42; google.rpc.Code.INVALID_ARGUMENT if the request is malformed. * &#42; google.rpc.Code.NOT_FOUND if the upload reference does not exist. * &#42; google.rpc.Code.RESOURCE_EXHAUSTED if the account has reached the * storage limit. */ create(request: { /** 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Photo>; /** * Deletes a Photo and its metadata. * * This method returns the following error codes: * * &#42; google.rpc.Code.PERMISSION_DENIED if the requesting user did not * create the requested photo. * &#42; google.rpc.Code.NOT_FOUND if the photo ID does not exist. */ delete(request: { /** 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; /** Required. ID of the Photo. */ photoId: 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** * Gets the metadata of the specified * Photo. * * This method returns the following error codes: * * &#42; google.rpc.Code.PERMISSION_DENIED if the requesting user did not * create the requested Photo. * &#42; google.rpc.Code.NOT_FOUND if the requested * Photo does not exist. */ get(request: { /** 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; /** Required. ID of the Photo. */ photoId: 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * Specifies if a download URL for the photo bytes should be returned in the * Photo response. */ view?: string; }): Request<Photo>; /** * Creates an upload session to start uploading photo bytes. The upload URL of * the returned UploadRef is used to * upload the bytes for the Photo. * * In addition to the photo requirements shown in * https://support.google.com/maps/answer/7012050?hl=en&ref_topic=6275604, * the photo must also meet the following requirements: * * &#42; Photo Sphere XMP metadata must be included in the photo medadata. See * https://developers.google.com/streetview/spherical-metadata for the * required fields. * &#42; The pixel size of the photo must meet the size requirements listed in * https://support.google.com/maps/answer/7012050?hl=en&ref_topic=6275604, and * the photo must be a full 360 horizontally. * * After the upload is complete, the * UploadRef is used with * CreatePhoto * to create the Photo object entry. */ startUpload(request: { /** 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<UploadRef>; /** * Updates the metadata of a Photo, such * as pose, place association, connections, etc. Changing the pixels of a * photo is not supported. * * Only the fields specified in the * updateMask * field are used. If `updateMask` is not present, the update applies to all * fields. * * <aside class="note"><b>Note:</b> To update * Pose.altitude, * Pose.latLngPair has to be * filled as well. Otherwise, the request will fail.</aside> * * This method returns the following error codes: * * &#42; google.rpc.Code.PERMISSION_DENIED if the requesting user did not * create the requested photo. * &#42; google.rpc.Code.INVALID_ARGUMENT if the request is malformed. * &#42; google.rpc.Code.NOT_FOUND if the requested photo does not exist. */ update(request: { /** 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; /** Required. A unique identifier for a photo. */ id: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** 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. */ quotaUser?: string; /** * Mask that identifies fields on the photo metadata to update. * If not present, the old Photo * metadata will be entirely replaced with the * new Photo metadata in this request. * The update fails if invalid fields are specified. Multiple fields can be * specified in a comma-delimited list. * * The following fields are valid: * * &#42; `pose.heading` * &#42; `pose.latLngPair` * &#42; `pose.pitch` * &#42; `pose.roll` * &#42; `pose.level` * &#42; `pose.altitude` * &#42; `connections` * &#42; `places` * * * <aside class="note"><b>Note:</b> Repeated fields in * updateMask * mean the entire set of repeated values will be replaced with the new * contents. For example, if * updateMask * contains `connections` and `UpdatePhotoRequest.photo.connections` is empty, * all connections will be removed.</aside> */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Photo>; } interface PhotosResource { /** * Deletes a list of Photos and their * metadata. * * Note that if * BatchDeletePhotos * fails, either critical fields are missing or there was an authentication * error. Even if * BatchDeletePhotos * succeeds, there may have been failures for single photos in the batch. * These failures will be specified in each * PhotoResponse.status * in * BatchDeletePhotosResponse.results. * See * DeletePhoto * for specific failures that can occur per photo. */ batchDelete(request: { /** 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<BatchDeletePhotosResponse>; /** * Gets the metadata of the specified * Photo batch. * * Note that if * BatchGetPhotos * fails, either critical fields are missing or there was an authentication * error. Even if * BatchGetPhotos * succeeds, there may have been failures for single photos in the batch. * These failures will be specified in each * PhotoResponse.status * in * BatchGetPhotosResponse.results. * See * GetPhoto * for specific failures that can occur per photo. */ batchGet(request: { /** 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; /** * Required. IDs of the Photos. For HTTP * GET requests, the URL query parameter should be * `photoIds=<id1>&photoIds=<id2>&...`. */ photoIds?: 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * Specifies if a download URL for the photo bytes should be returned in the * Photo response. */ view?: string; }): Request<BatchGetPhotosResponse>; /** * Updates the metadata of Photos, such * as pose, place association, connections, etc. Changing the pixels of photos * is not supported. * * Note that if * BatchUpdatePhotos * fails, either critical fields are missing or there was an authentication * error. Even if * BatchUpdatePhotos * succeeds, there may have been failures for single photos in the batch. * These failures will be specified in each * PhotoResponse.status * in * BatchUpdatePhotosResponse.results. * See * UpdatePhoto * for specific failures that can occur per photo. * * Only the fields specified in * updateMask * field are used. If `updateMask` is not present, the update applies to all * fields. * * <aside class="note"><b>Note:</b> To update * Pose.altitude, * Pose.latLngPair has to be * filled as well. Otherwise, the request will fail.</aside> */ batchUpdate(request: { /** 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<BatchUpdatePhotosResponse>; /** * Lists all the Photos that belong to * the user. */ list(request: { /** 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; /** * The filter expression. For example: `placeId=ChIJj61dQgK6j4AR4GeTYWZsKWw`. * * The only filter supported at the moment is `placeId`. */ filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * The maximum number of photos to return. * `pageSize` must be non-negative. If `pageSize` is zero or is not provided, * the default page size of 100 will be used. * The number of photos returned in the response may be less than `pageSize` * if the number of photos that belong to the user is less than `pageSize`. */ pageSize?: number; /** * The * nextPageToken * value returned from a previous * ListPhotos * request, if any. */ pageToken?: 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. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * Specifies if a download URL for the photos bytes should be returned in the * Photos response. */ view?: string; }): Request<ListPhotosResponse>; } } }
the_stack
import * as clusters from "../resources/clusters"; import * as console from "../../console"; import * as deployModel from "../../deploymodel"; import * as docker from "../../docker"; import * as loadBalancers from "../resources/loadbalancers"; import * as repositories from "../resources/repositories"; import * as securityGroups from "../resources/securitygroups"; import * as services from "../resources/services"; import * as tags from "../resources/tags"; import * as targetGroups from "../resources/targetgroups"; import * as taskDefinitions from "../resources/taskdefinitions"; import * as vpcs from "../resources/vpcs"; import { getResourceNames } from "./names"; export interface DeployResult { deploymentId: string; repositoryName: string; repositoryImageTag: string; loadBalancerSecurityGroupId: string; loadBalancerArn: string; taskDefinitionArn: string; targetGroupArn: string; loadBalancerListenerArn: string; serviceArn: string; dns: string; } export async function deploy( deploymentSpec: deployModel.DeploymentSpec, deploymentId: string ): Promise<DeployResult> { let deploymentTags = [ tags.SHARED_TAG, tags.clusterNameTag(deploymentSpec.cluster.name), tags.deploymentIdTag(deploymentId) ]; let names = getResourceNames(deploymentId); let cluster: clusters.Cluster | undefined; let dockerImagePushed = false; let loadBalancerSecurityGroupCreated = false; let loadBalancerCreated = false; let taskDefinitionCreated = false; let targetGroupCreated = false; let serviceCreated = false; try { console.logInfo(`Building Docker image ${names.localDockerImage}...`); await docker.createDockerImage( deploymentSpec.container.imageSource.dockerfilePath, names.localDockerImage ); let dockerImageExposedPort = await docker.getExposedPort( names.localDockerImage ); console.logInfo(`✔ Docker image built.`); let repository = await repositories.getOrCreateRepository( deploymentSpec.cluster.region, names.repository ); console.logInfo( `Pushing to ${repository.uri}:${names.remoteDockerImageTag}...` ); let uri = await docker.pushDockerImage( deploymentSpec.cluster.region, names.localDockerImage, repository.uri, names.remoteDockerImageTag, await repositories.getAuthConfig(deploymentSpec.cluster.region) ); console.logInfo(`✔ Docker image pushed to ${uri}.`); dockerImagePushed = true; console.logInfo( `Finding cluster ${deploymentSpec.cluster.name} in region ${ deploymentSpec.cluster.region }...` ); cluster = await clusters.getCluster( deploymentSpec.cluster.region, deploymentSpec.cluster.name ); console.logInfo(`✔ Found cluster ${cluster.name}.`); // Get the default VPC. Create it if necessary. // TODO: Instead, get the VPC associated with the cluster. console.logInfo(`Looking up default VPC and subnets...`); let vpc = await vpcs.getDefaultVpcAndSubnets(deploymentSpec.cluster.region); console.logInfo(`✔ Using default VPC with ID ${vpc.id}.`); // Create security groups (ELB + ECS) and configure their relationship. console.logInfo( `Creating security group ${names.loadBalancerSecurityGroup}...` ); let loadBalancerSecurityGroup = await securityGroups.createLoadBalancerSecurityGroup( deploymentSpec.cluster.region, names.loadBalancerSecurityGroup, vpc.id, deploymentTags ); console.logInfo( `✔ Security group ${names.loadBalancerSecurityGroup} created.` ); loadBalancerSecurityGroupCreated = true; console.logInfo(`Getting default security group for cluster...`); let defaultSecurityGroupId = await securityGroups.getDefaultSecurityGroupId( deploymentSpec.cluster.region, vpc.id ); console.logInfo( `✔ Cluster using default security group with ID ${defaultSecurityGroupId}.` ); // TODO: Support HTTPS on 443. let loadBalancerPort = 80; console.logInfo(`Configuring security group ingress rules...`); await securityGroups.configureSecurityGroups( deploymentSpec.cluster.region, loadBalancerSecurityGroup.id, defaultSecurityGroupId, [loadBalancerPort] ); console.logInfo(`✔ Security group ingress rules set up successfully.`); // Create load balancer. console.logInfo(`Creating load balancer ${names.loadBalancer}...`); let loadBalancer = await loadBalancers.createLoadBalancer( deploymentSpec.cluster.region, names.loadBalancer, vpc.subnetIds, loadBalancerSecurityGroup.id, deploymentTags ); console.logInfo( `✔ Load balancer ${ names.loadBalancer } created successfully. It may take a few minutes to provision...` ); loadBalancerCreated = true; // Register task definition. console.logInfo(`Creating task definition ${names.taskDefinition}...`); let taskDefinition = await taskDefinitions.createTaskDefinition( deploymentSpec.cluster.region, names.taskDefinition, names.container, repository.uri + ":" + names.remoteDockerImageTag, loadBalancer.dns, dockerImageExposedPort, deploymentSpec.container.memory, deploymentSpec.container.cpuUnits, deploymentSpec.environment ); console.logInfo( `✔ Task definition created in family ${taskDefinition.family}.` ); taskDefinitionCreated = true; // Create target group. console.logInfo(`Creating target group ${names.targetGroup}...`); let targetGroup = await targetGroups.createTargetGroup( deploymentSpec.cluster.region, names.targetGroup, vpc.id, loadBalancerPort, deploymentTags ); console.logInfo(`✔ Created target group ${names.targetGroup}.`); targetGroupCreated = true; // Add load balancer listener for target group. console.logInfo( `Creating listener for load balancer ${loadBalancer.name}...` ); let loadBalancerListener = await loadBalancers.createListener( deploymentSpec.cluster.region, loadBalancer.arn, loadBalancerPort, targetGroup.arn ); console.logInfo(`✔ Created load balancer listener.`); // Create service in cluster. console.logInfo(`Creating service ${names.service}...`); let service = await services.createService( deploymentSpec.cluster.region, names.service, names.container, cluster.arn, taskDefinition.arn, targetGroup.arn, deploymentSpec.desiredCount, dockerImageExposedPort ); console.logInfo(`✔ Created service ${names.service}.`); serviceCreated = true; console.logSuccess( `Deployed successfully at http://${ loadBalancer.dns } (live in a few minutes).` ); return { deploymentId, repositoryName: names.repository, repositoryImageTag: names.remoteDockerImageTag, loadBalancerSecurityGroupId: loadBalancerSecurityGroup.id, loadBalancerArn: loadBalancer.arn, taskDefinitionArn: taskDefinition.arn, targetGroupArn: targetGroup.arn, loadBalancerListenerArn: loadBalancerListener.arn, serviceArn: service.arn, dns: loadBalancer.dns }; } catch (e) { console.logError(e); if (cluster) { if (serviceCreated) { console.logInfo(`Rolling back service ${names.service}...`); try { await services.destroyService( deploymentSpec.cluster.region, cluster.arn, names.service ); console.logInfo(`✔ Destroyed service ${names.service}.`); } catch { console.logInfo(`Could not roll back ${names.service}.`); } } if (targetGroupCreated) { console.logInfo(`Rolling back target group ${names.targetGroup}...`); try { await targetGroups.deleteTargetGroup( deploymentSpec.cluster.region, names.targetGroup ); console.logInfo(`✔ Deleted target group ${names.targetGroup}.`); } catch { console.logInfo(`Could not roll back ${names.targetGroup}.`); } } if (taskDefinitionCreated) { console.logInfo( `Rolling back task definition ${names.taskDefinition}...` ); try { await taskDefinitions.deregisterTaskDefinition( deploymentSpec.cluster.region, names.taskDefinition ); console.logInfo( `✔ Deregistered task definition ${names.taskDefinition}.` ); } catch { console.logInfo(`Could not roll back ${names.taskDefinition}.`); } } if (loadBalancerCreated) { console.logInfo(`Rolling back load balancer ${names.loadBalancer}...`); try { await loadBalancers.destroyLoadBalancer( deploymentSpec.cluster.region, names.loadBalancer ); console.logInfo(`✔ Destroyed load balancer ${names.loadBalancer}.`); } catch { console.logInfo(`Could not roll back ${names.loadBalancer}.`); } } if (loadBalancerSecurityGroupCreated) { console.logInfo( `Rolling back load balancer security group ${ names.loadBalancerSecurityGroup }...` ); try { await securityGroups.deleteLoadBalancerSecurityGroup( deploymentSpec.cluster.region, names.loadBalancerSecurityGroup ); console.logInfo( `✔ Deleted load balancer security group ${ names.loadBalancerSecurityGroup }.` ); } catch { console.logInfo( `Could not roll back ${names.loadBalancerSecurityGroup}.` ); } } } if (dockerImagePushed) { console.logInfo( `Rolling back Docker image ${names.repository}:${ names.remoteDockerImageTag }...` ); try { await repositories.deleteImage( deploymentSpec.cluster.region, names.repository, names.remoteDockerImageTag ); console.logInfo( `✔ Deleted Docker image ${names.repository}:${ names.remoteDockerImageTag }.` ); } catch { console.logInfo( `Could not roll back ${names.repository}:${ names.remoteDockerImageTag }.` ); } } throw new console.AlreadyLoggedError(e); } } export async function destroy( region: string, clusterName: string | null, deploymentId: string ) { let names = getResourceNames(deploymentId); // TODO: Error handling around each step. console.logInfo(`Deregistering task definition ${names.taskDefinition}...`); await taskDefinitions.deregisterTaskDefinition(region, names.taskDefinition); console.logInfo(`✔ Deregistered task definition ${names.taskDefinition}.`); if (clusterName) { console.logInfo(`Destroying service ${names.service}...`); await services.destroyService(region, clusterName, names.service); console.logInfo(`✔ Destroyed service ${names.service}.`); } console.logInfo( `Deleting Docker image ${names.repository}:${names.remoteDockerImageTag}...` ); await repositories.deleteImage( region, names.repository, names.remoteDockerImageTag ); console.logInfo( `✔ Deleted Docker image ${names.repository}:${names.remoteDockerImageTag}.` ); console.logInfo(`Destroying load balancer ${names.loadBalancer}...`); await loadBalancers.destroyLoadBalancer(region, names.loadBalancer); console.logInfo(`✔ Destroyed load balancer ${names.loadBalancer}.`); console.logInfo(`Deleting target group ${names.targetGroup}...`); await targetGroups.deleteTargetGroup(region, names.targetGroup); console.logInfo(`✔ Destroyed target group ${names.targetGroup}.`); console.logInfo( `Deleting load balancer security group ${ names.loadBalancerSecurityGroup }...` ); await securityGroups.deleteLoadBalancerSecurityGroup( region, names.loadBalancerSecurityGroup ); console.logInfo( `✔ Destroyed load balancer security group ${ names.loadBalancerSecurityGroup }` ); console.logSuccess(`Destroyed deployment ${deploymentId} successfully.`); }
the_stack
namespace ts.refactor { const refactorName = "Convert import"; const actions = { [ImportKind.Named]: { name: "Convert namespace import to named imports", description: Diagnostics.Convert_namespace_import_to_named_imports.message, kind: "refactor.rewrite.import.named", }, [ImportKind.Namespace]: { name: "Convert named imports to namespace import", description: Diagnostics.Convert_named_imports_to_namespace_import.message, kind: "refactor.rewrite.import.namespace", }, [ImportKind.Default]: { name: "Convert named imports to default import", description: Diagnostics.Convert_named_imports_to_default_import.message, kind: "refactor.rewrite.import.default", }, }; registerRefactor(refactorName, { kinds: getOwnValues(actions).map(a => a.kind), getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context): readonly ApplicableRefactorInfo[] { const info = getImportConversionInfo(context, context.triggerReason === "invoked"); if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { const action = actions[info.convertTo]; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { return getOwnValues(actions).map(action => ({ name: refactorName, description: action.description, actions: [{ ...action, notApplicableReason: info.error }] })); } return emptyArray; }, getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName): RefactorEditInfo { Debug.assert(some(getOwnValues(actions), action => action.name === actionName), "Unexpected action name"); const info = getImportConversionInfo(context); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); const edits = textChanges.ChangeTracker.with(context, t => doChange(context.file, context.program, t, info)); return { edits, renameFilename: undefined, renameLocation: undefined }; } }); // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. type ImportConversionInfo = | { convertTo: ImportKind.Default, import: NamedImports } | { convertTo: ImportKind.Namespace, import: NamedImports } | { convertTo: ImportKind.Named, import: NamespaceImport }; function getImportConversionInfo(context: RefactorContext, considerPartialSpans = true): ImportConversionInfo | RefactorErrorInfo | undefined { const { file } = context; const span = getRefactorContextSpan(context); const token = getTokenAtPosition(file, span.start); const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); if (!importDecl || !isImportDeclaration(importDecl)) return { error: "Selection is not an import declaration." }; const end = span.start + span.length; const nextToken = findNextToken(importDecl, importDecl.parent, file); if (nextToken && end > nextToken.getStart()) return undefined; const { importClause } = importDecl; if (!importClause) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; } if (!importClause.namedBindings) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; } if (importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { return { convertTo: ImportKind.Named, import: importClause.namedBindings }; } const shouldUseDefault = getShouldUseDefault(context.program, importClause); return shouldUseDefault ? { convertTo: ImportKind.Default, import: importClause.namedBindings } : { convertTo: ImportKind.Namespace, import: importClause.namedBindings }; } function getShouldUseDefault(program: Program, importClause: ImportClause) { return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); } function doChange(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, info: ImportConversionInfo): void { const checker = program.getTypeChecker(); if (info.convertTo === ImportKind.Named) { doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === ImportKind.Default); } } function doChangeNamespaceToNamed(sourceFile: SourceFile, checker: TypeChecker, changes: textChanges.ChangeTracker, toConvert: NamespaceImport, allowSyntheticDefaultImports: boolean): void { let usedAsNamespaceOrDefault = false; const nodesToReplace: (PropertyAccessExpression | QualifiedName)[] = []; const conflictingNames = new Map<string, true>(); FindAllReferences.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, id => { if (!isPropertyAccessOrQualifiedName(id.parent)) { usedAsNamespaceOrDefault = true; } else { const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; if (checker.resolveName(exportName, id, SymbolFlags.All, /*excludeGlobals*/ true)) { conflictingNames.set(exportName, true); } Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); nodesToReplace.push(id.parent); } }); // We may need to change `mod.x` to `_x` to avoid a name conflict. const exportNameToImportName = new Map<string, string>(); for (const propertyAccessOrQualifiedName of nodesToReplace) { const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; let importName = exportNameToImportName.get(exportName); if (importName === undefined) { exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); } changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); } const importSpecifiers: ImportSpecifier[] = []; exportNameToImportName.forEach((name, propertyName) => { importSpecifiers.push(factory.createImportSpecifier(/*isTypeOnly*/ false, name === propertyName ? undefined : factory.createIdentifier(propertyName), factory.createIdentifier(name))); }); const importDecl = toConvert.parent.parent; if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { // Need to leave the namespace import alone changes.insertNodeAfter(sourceFile, importDecl, updateImport(importDecl, /*defaultImportName*/ undefined, importSpecifiers)); } else { changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : undefined, importSpecifiers)); } } function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName: PropertyAccessExpression | QualifiedName) { return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; } function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName: PropertyAccessExpression | QualifiedName) { return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; } export function doChangeNamedToNamespaceOrDefault(sourceFile: SourceFile, program: Program, changes: textChanges.ChangeTracker, toConvert: NamedImports, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)): void { const checker = program.getTypeChecker(); const importDecl = toConvert.parent.parent; const { moduleSpecifier } = importDecl; const toConvertSymbols: Set<Symbol> = new Set(); toConvert.elements.forEach(namedImport => { const symbol = checker.getSymbolAtLocation(namedImport.name); if (symbol) { toConvertSymbols.add(symbol); } }); const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? codefix.moduleSpecifierToValidIdentifier(moduleSpecifier.text, ScriptTarget.ESNext) : "module"; function hasNamespaceNameConflict(namedImport: ImportSpecifier): boolean { // We need to check if the preferred namespace name (`preferredName`) we'd like to use in the refactored code will present a name conflict. // A name conflict means that, in a scope where we would like to use the preferred namespace name, there already exists a symbol with that name in that scope. // We are going to use the namespace name in the scopes the named imports being refactored are referenced, // so we look for conflicts by looking at every reference to those named imports. return !!FindAllReferences.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, id => { const symbol = checker.resolveName(preferredName, id, SymbolFlags.All, /*excludeGlobals*/ true); if (symbol) { // There already is a symbol with the same name as the preferred namespace name. if (toConvertSymbols.has(symbol)) { // `preferredName` resolves to a symbol for one of the named import references we are going to transform into namespace import references... return isExportSpecifier(id.parent); // ...but if this reference is an export specifier, it will not be transformed, so it is a conflict; otherwise, it will be renamed and is not a conflict. } return true; // `preferredName` resolves to any other symbol, which will be present in the refactored code and so poses a name conflict. } return false; // There is no symbol with the same name as the preferred namespace name, so no conflict. }); } const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; // Imports that need to be kept as named imports in the refactored code, to avoid changing the semantics. // More specifically, those are named imports that appear in named exports in the original code, e.g. `a` in `import { a } from "m"; export { a }`. const neededNamedImports: Set<ImportSpecifier> = new Set(); for (const element of toConvert.elements) { const propertyName = (element.propertyName || element.name).text; FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, id => { const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); if (isShorthandPropertyAssignment(id.parent)) { changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); } else if (isExportSpecifier(id.parent)) { neededNamedImports.add(element); } else { changes.replaceNode(sourceFile, id, access); } }); } changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { const newNamedImports: ImportSpecifier[] = arrayFrom(neededNamedImports.values()).map(element => factory.createImportSpecifier(element.isTypeOnly, element.propertyName && factory.createIdentifier(element.propertyName.text), factory.createIdentifier(element.name.text))); changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, newNamedImports)); } } function isExportEqualsModule(moduleSpecifier: Expression, checker: TypeChecker) { const externalModule = checker.resolveExternalModuleName(moduleSpecifier); if (!externalModule) return false; const exportEquals = checker.resolveExternalModuleSymbol(externalModule); return externalModule !== exportEquals; } function updateImport(old: ImportDeclaration, defaultImportName: Identifier | undefined, elements: readonly ImportSpecifier[] | undefined): ImportDeclaration { return factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { SubAssessments } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { SecurityCenter } from "../securityCenter"; import { SecuritySubAssessment, SubAssessmentsListAllNextOptionalParams, SubAssessmentsListAllOptionalParams, SubAssessmentsListNextOptionalParams, SubAssessmentsListOptionalParams, SubAssessmentsListAllResponse, SubAssessmentsListResponse, SubAssessmentsGetOptionalParams, SubAssessmentsGetResponse, SubAssessmentsListAllNextResponse, SubAssessmentsListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing SubAssessments operations. */ export class SubAssessmentsImpl implements SubAssessments { private readonly client: SecurityCenter; /** * Initialize a new instance of the class SubAssessments class. * @param client Reference to the service client */ constructor(client: SecurityCenter) { this.client = client; } /** * Get security sub-assessments on all your scanned resources inside a subscription scope * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param options The options parameters. */ public listAll( scope: string, options?: SubAssessmentsListAllOptionalParams ): PagedAsyncIterableIterator<SecuritySubAssessment> { const iter = this.listAllPagingAll(scope, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAllPagingPage(scope, options); } }; } private async *listAllPagingPage( scope: string, options?: SubAssessmentsListAllOptionalParams ): AsyncIterableIterator<SecuritySubAssessment[]> { let result = await this._listAll(scope, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAllNext(scope, continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listAllPagingAll( scope: string, options?: SubAssessmentsListAllOptionalParams ): AsyncIterableIterator<SecuritySubAssessment> { for await (const page of this.listAllPagingPage(scope, options)) { yield* page; } } /** * Get security sub-assessments on all your scanned resources inside a scope * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param assessmentName The Assessment Key - Unique key for the assessment type * @param options The options parameters. */ public list( scope: string, assessmentName: string, options?: SubAssessmentsListOptionalParams ): PagedAsyncIterableIterator<SecuritySubAssessment> { const iter = this.listPagingAll(scope, assessmentName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(scope, assessmentName, options); } }; } private async *listPagingPage( scope: string, assessmentName: string, options?: SubAssessmentsListOptionalParams ): AsyncIterableIterator<SecuritySubAssessment[]> { let result = await this._list(scope, assessmentName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( scope, assessmentName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( scope: string, assessmentName: string, options?: SubAssessmentsListOptionalParams ): AsyncIterableIterator<SecuritySubAssessment> { for await (const page of this.listPagingPage( scope, assessmentName, options )) { yield* page; } } /** * Get security sub-assessments on all your scanned resources inside a subscription scope * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param options The options parameters. */ private _listAll( scope: string, options?: SubAssessmentsListAllOptionalParams ): Promise<SubAssessmentsListAllResponse> { return this.client.sendOperationRequest( { scope, options }, listAllOperationSpec ); } /** * Get security sub-assessments on all your scanned resources inside a scope * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param assessmentName The Assessment Key - Unique key for the assessment type * @param options The options parameters. */ private _list( scope: string, assessmentName: string, options?: SubAssessmentsListOptionalParams ): Promise<SubAssessmentsListResponse> { return this.client.sendOperationRequest( { scope, assessmentName, options }, listOperationSpec ); } /** * Get a security sub-assessment on your scanned resource * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param assessmentName The Assessment Key - Unique key for the assessment type * @param subAssessmentName The Sub-Assessment Key - Unique key for the sub-assessment type * @param options The options parameters. */ get( scope: string, assessmentName: string, subAssessmentName: string, options?: SubAssessmentsGetOptionalParams ): Promise<SubAssessmentsGetResponse> { return this.client.sendOperationRequest( { scope, assessmentName, subAssessmentName, options }, getOperationSpec ); } /** * ListAllNext * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param nextLink The nextLink from the previous successful call to the ListAll method. * @param options The options parameters. */ private _listAllNext( scope: string, nextLink: string, options?: SubAssessmentsListAllNextOptionalParams ): Promise<SubAssessmentsListAllNextResponse> { return this.client.sendOperationRequest( { scope, nextLink, options }, listAllNextOperationSpec ); } /** * ListNext * @param scope Scope of the query, can be subscription * (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management group * (/providers/Microsoft.Management/managementGroups/mgName). * @param assessmentName The Assessment Key - Unique key for the assessment type * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( scope: string, assessmentName: string, nextLink: string, options?: SubAssessmentsListNextOptionalParams ): Promise<SubAssessmentsListNextResponse> { return this.client.sendOperationRequest( { scope, assessmentName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listAllOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Security/subAssessments", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecuritySubAssessmentList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [Parameters.$host, Parameters.scope], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Security/assessments/{assessmentName}/subAssessments", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecuritySubAssessmentList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.scope, Parameters.assessmentName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/{scope}/providers/Microsoft.Security/assessments/{assessmentName}/subAssessments/{subAssessmentName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecuritySubAssessment }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.scope, Parameters.assessmentName, Parameters.subAssessmentName ], headerParameters: [Parameters.accept], serializer }; const listAllNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecuritySubAssessmentList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [Parameters.$host, Parameters.nextLink, Parameters.scope], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecuritySubAssessmentList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.scope, Parameters.assessmentName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Component, OnInit, OnDestroy, Output, EventEmitter } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { CommonResponseService } from '../../../shared/services/common-response.service'; import { environment } from './../../../../environments/environment'; import { LoggerService } from '../../../shared/services/logger.service'; import { ActivatedRoute, UrlSegment, Router } from '@angular/router'; import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service'; import { WorkflowService } from '../../../core/services/workflow.service'; import { PermissionGuardService } from '../../../core/services/permission-guard.service'; import * as d3 from 'd3-selection'; import * as d3Shape from 'd3-shape'; import * as d3Scale from 'd3-scale'; import * as d3Array from 'd3-array'; import * as d3Axis from 'd3-axis'; @Component({ selector: 'app-onprem-patching-graph', templateUrl: './onprem-patching-graph.component.html', styleUrls: ['./onprem-patching-graph.component.css'], providers: [CommonResponseService, LoggerService] }) export class OnpremPatchingGraphComponent implements OnInit, OnDestroy { constructor( private commonResponseService: CommonResponseService, private logger: LoggerService, private assetGroupObservableService: AssetGroupObservableService, private router: Router, private activatedRoute: ActivatedRoute, private workflowService: WorkflowService, private permissions: PermissionGuardService ) { this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe( assetGroupName => { if (assetGroupName) { this.selectedAssetGroup = assetGroupName; this.updateComponent(); } }); } // Subscription variables onpremSubscription: Subscription; subscriptionToAssetGroup: Subscription; // Page Variables dataResponse: any = []; maxVal: any = [0, 0]; axisValues = { 'y0': [], 'y1': [] }; selectedAssetGroup: string; urlToRedirect: string; dataState = 0; percentToday = -1; onpremAccess = false; // Graph colors init darkBlue = '#1C5066'; // Weekly patches completed lightBlue = '#709eb1'; // Weekly patches target lightGreen = '#26BA9D'; // Overall patches // Emitter Events @Output() errorOccurred = new EventEmitter(); @Output() dataSuccess = new EventEmitter(); ngOnInit() { this.urlToRedirect = this.router.routerState.snapshot.url; this.onpremAccess = this.permissions.checkOnPremAdminPermission(); } updateComponent() { this.setGraphParams(); this.getData(); } getData() { this.resetPage(); const url = environment.onPremGraph.url; const queryParam = { ag: this.selectedAssetGroup }; const payload = {}; const method = environment.onPremGraph.method; this.onpremSubscription = this.commonResponseService.getData( url, method, payload, queryParam).subscribe( response => { try { this.dataResponse = response; if (this.dataResponse.projectionByWeek.length === 0) { this.errorOccurred.emit(); this.dataState = -1; } else { this.dataSuccess.emit(); this.dataState = 1; this.processData(this.dataResponse.projectionByWeek); } } catch (e) { this.errorOccurred.emit(); this.dataState = -1; this.logger.log('error', e); } }, error => { this.errorOccurred.emit(); this.dataState = -1; this.logger.log('error', error); }); } resetPage() { if ( this.onpremSubscription ) { this.onpremSubscription.unsubscribe(); } this.dataState = 0; this.dataResponse = []; this.percentToday = -1; this.maxVal = [0, 0]; this.axisValues = { 'y0': [], 'y1': [] }; } setGraphParams() { try { if (document.getElementById('onpremGraph')) { document.getElementById('onpremGraph').innerHTML = ''; document.getElementById('onpremGraph').style.width = document.getElementById('onpremContainer').clientWidth + 'px'; document.getElementById('onpremGraph').style.height = document.getElementById('onpremContainer').clientHeight + 'px'; } } catch (e) { this.logger.log('error', e); } } processData(data) { const firstDay = (new Date(data[0].date)).getTime(); const lastDay = (new Date(data[data.length - 1].date)).getTime() + 7 * 24 * 60 * 60 * 1000; const today = (new Date()).getTime(); this.percentToday = ((today - firstDay) * 100) / (lastDay - firstDay); const graphThis = this; setTimeout(() => { const margin = {top: 40, right: 77, bottom: 45, left: 77}, width = document.getElementById('onpremContainer').clientWidth - margin.left - margin.right, height = document.getElementById('onpremContainer').clientHeight - margin.top - margin.bottom; const barWidth = width / data.length; let xDisplacement = 20; let difference = 17.5; if (Math.ceil(barWidth / 5) < 15) { xDisplacement = Math.ceil(barWidth / 5) + 3; difference = 1.5 + Math.ceil(barWidth / 5); } const strData = JSON.stringify(data); const newData = JSON.parse(strData); const zeroObj = {projected: '0', week: '0', totalPatched: '0', patched: '0', totalProjected: '0'}; newData.unshift(zeroObj); // parse the date / time // var parseTime = d3TimeFormat.timeParse('%d-%b-%y'); // set the ranges of each axis const x = d3Scale.scalePoint().range([0, width]); x.domain(newData.map((d) => d['week'])); const xScale = d3Scale.scaleBand().range([0, width]); xScale.domain(data.map((d) => d['week'])); // .rangeRound([0, width], .3); const y0 = d3Scale.scaleLinear().range([height, 0]); const y1 = d3Scale.scaleLinear().range([height, 0]); // define the 1st line const valueline = d3Shape.line() .x(function(d) { return x(d['week']); }) .y(function(d) { graphThis.findMaxVal(d); return y1(d['totalPatched']); }) .curve(d3Shape.curveMonotoneX); // define the 2nd line const valueline2 = d3Shape.line() .x(function(d) { return x(d['week']); }) .y(function(d) { return y1(d['totalProjected']); }) .curve(d3Shape.curveMonotoneX); // set dimentions of svg const svg = d3.select('#onpremGraph') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); // format the data data.forEach(function(d) { d['week'] = +d['week']; d['totalPatched'] = +d['totalPatched']; d['totalProjected'] = +d['totalProjected']; }); // Scale the range of the data for each axes y0.domain([0, d3Array.max(data, function(d) {return Math.max(d['patched'], d['projected'], 5); })]); y1.domain([0, d3Array.max(newData, function(d) {return Math.max(d['totalPatched'], d['totalProjected'], 5); })]); // Add the X Bottom Band(Bar) Axis svg.append('g') .attr('transform', 'translate(0,' + height + ')') .attr('class', 'bottomAxis') .call(d3Axis.axisBottom(x)) .call(make_x_gridlines() .tickSize(-height) ); // Graph Bars const sets = svg.selectAll('.set') .data(data) .enter() .append('g') .attr('class', 'set') .attr('transform', function(d, i) { return 'translate(' + (xScale(d['week']) - difference + barWidth / 2) + ',0)'; }) ; // bar 2 sets.append('rect') .attr('class', 'local') .attr('shape-rendering', 'crispEdges') .transition() .delay(700) .duration(600) .attr('width', Math.min(Math.ceil(barWidth / 5), 15)) .attr('y', function(d) { return y0(d['projected']); }) .attr('x', xDisplacement) .attr('height', function(d){ return height - y0(d['projected']); }) .attr('fill', graphThis.lightBlue) ; // bar 1 sets.append('rect') .attr('class', 'global') .attr('shape-rendering', 'crispEdges') .transition() .delay(500) .duration(600) .attr('width', Math.min(Math.ceil(barWidth / 5), 15)) .attr('y', function(d) { return y0(d['patched']); }) .attr('height', function(d){ return height - y0(d['patched']); }) .attr('fill', graphThis.darkBlue); // Add the valueline1 path. svg.append('path') .data([newData]) .attr('class', 'line') .style('stroke', graphThis.lightGreen) .attr('d', valueline) ; // Add the valueline2 path. svg.append('path') .data([newData]) .attr('class', 'line line-dashed') .style('stroke', graphThis.lightGreen) .attr('d', valueline2) ; // gridlines in x axis function function make_x_gridlines() { return d3Axis.axisBottom(x) .ticks(5); } }, 10); } findMaxVal(obj) { this.maxVal[0] = Math.max(this.maxVal[0], obj['projected'], obj['patched']); this.maxVal[1] = Math.max(this.maxVal[1], obj['totalProjected'], obj['totalPatched']); for ( let i = 5; i > 0 ; i--) { this.axisValues['y0'].push(Math.ceil(this.maxVal[0] / 5 * i)); this.axisValues['y1'].push(Math.ceil(this.maxVal[1] / 5 * i )); } this.axisValues['y0'] = this.axisValues['y0'].slice(this.axisValues['y0'].length - 5); this.axisValues['y1'] = this.axisValues['y1'].slice(this.axisValues['y1'].length - 5); if (this.axisValues['y0'][0] < 5) { this.axisValues['y0'] = [5, 4, 3, 2, 1]; } if (this.axisValues['y1'][0] < 5) { this.axisValues['y1'] = [5, 4, 3, 2, 1]; } } onResize() { try { this.setGraphParams(); if (this.dataResponse.projectionByWeek.length) { this.processData(this.dataResponse.projectionByWeek); } } catch (e) { this.logger.log('error', e); } } redirectTo(page) { this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root); if (page === 'updateAssets') { this.router.navigate(['../../assets/update-assets'], {relativeTo: this.activatedRoute, queryParamsHandling: 'merge'}); } else if (page === 'patchingProjections') { this.router.navigate(['../patching-projections'], {relativeTo: this.activatedRoute, queryParamsHandling: 'merge'}); } } ngOnDestroy() { if ( this.onpremSubscription ) { this.onpremSubscription.unsubscribe(); } this.subscriptionToAssetGroup.unsubscribe(); } }
the_stack
import { flatten } from "lodash"; import should from "should"; import { handle, Handle, Status } from "../../src"; import { Dependency, DeployHelpers, Relation, RelationOp } from "../../src/deploy/deploy_types"; import { relationInverse, relationIsReady, relationIsReadyStatus, relationToString, toDependencies, } from "../../src/deploy/relation_utils"; import { AllOf, And, AnyOf, Edge, False, Identity, None, Not, Only, Or, True, Value, } from "../../src/deploy/relations"; import { makeHandles } from "./common"; const inverse = relationInverse; const ready = relationIsReady; const toString = relationToString; class MockDeployHelpers implements DeployHelpers { deployedMap = new Map<Dependency, boolean>(); currentElem: Handle | null = null; elementStatus = <S extends Status = Status>(h: Handle): Promise<S | Status | undefined> => { throw new Error(`Not implemented in Mock yet`); } isDeployed = (dep: Dependency): boolean => { return this.deployedMap.get(dep) === true; } dependsOn = (hands: Handle | Handle[]): Relation => { const current = this.currentElem; if (current == null) throw new Error(`currentElem is null`); const toEdge = (h: Handle) => Edge(current, h, this.isDeployed); if (!Array.isArray(hands)) return toEdge(hands); return And(...hands.map(toEdge)); } /* * Mock-specific */ deployed(dep: Dependency, val = true) { this.deployedMap.set(dep, val); } } function makeInputs<T>(nInputs: number, values: T[]): T[][] { if (nInputs === 0) return [[]]; const prev = makeInputs(nInputs - 1, values); let ret: T[][] = []; values.forEach((v) => { const appendVal = (x: T[]) => [v].concat(x); ret = ret.concat(prev.map(appendVal)); }); return ret; } function opTruthTable(relOp: RelationOp, argc: number): boolean[] { const args = makeInputs(argc, [False(), True()]); return args.map((list) => ready(relOp(...list))); } describe("Relations", () => { let helpers: MockDeployHelpers; beforeEach(() => { helpers = new MockDeployHelpers(); }); describe("AllOf", () => { it("Should be done when all dependencies are met", () => { const self = handle(); const deps = makeHandles(4, "dep"); helpers.currentElem = self; const a = AllOf(helpers, deps); helpers.currentElem = null; should(a.description).equal("all of"); if (a.relatesTo == null) throw should(a.relatesTo).not.be.Undefined(); should(flatten(a.relatesTo.map(toDependencies))).eql(deps); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for 4 dependencies", related: deps.map((_h, i) => ({ done: false, status: `Waiting for dependency Handle(dep${i})` })) }); helpers.deployed(deps[3]); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for 3 dependencies", related: [ { done: false, status: `Waiting for dependency Handle(dep0)` }, { done: false, status: `Waiting for dependency Handle(dep1)` }, { done: false, status: `Waiting for dependency Handle(dep2)` }, ] }); helpers.deployed(deps[0]); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for 2 dependencies", related: [ { done: false, status: `Waiting for dependency Handle(dep1)` }, { done: false, status: `Waiting for dependency Handle(dep2)` }, ] }); helpers.deployed(deps[2]); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for 1 dependency", related: [ { done: false, status: `Waiting for dependency Handle(dep1)` }, ] }); helpers.deployed(deps[1]); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(deps[2], false); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for 1 dependency", related: [ { done: false, status: `Waiting for dependency Handle(dep2)` }, ] }); }); it("Should be done with empty dependency list", () => { helpers.currentElem = handle(); const a = AllOf(helpers, []); should(a.description).equal("all of"); should(a.relatesTo).eql([]); should(relationIsReadyStatus(a)).be.True(); }); }); describe("Only", () => { it("Should be done when dependency is met", () => { helpers.currentElem = handle(); const dep = handle("onlydep"); const a = Only(helpers, dep); should(a.description).equal("only"); if (a.relatesTo == null) throw should(a.relatesTo).not.be.Undefined(); should(flatten(a.relatesTo.map(toDependencies))).eql([dep]); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for dependency Handle(onlydep)" }); helpers.deployed(dep); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(dep, false); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for dependency Handle(onlydep)" }); }); }); describe("AnyOf", () => { it("Should be done when any dependency is met", () => { helpers.currentElem = handle(); const deps = makeHandles(4, "any"); const a = AnyOf(helpers, deps); should(a.description).equal("any of"); if (a.relatesTo == null) throw should(a.relatesTo).not.be.Undefined(); should(flatten(a.relatesTo.map(toDependencies))).eql(deps); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for any of 4 dependencies", related: [ { done: false, status: `Waiting for dependency Handle(any0)` }, { done: false, status: `Waiting for dependency Handle(any1)` }, { done: false, status: `Waiting for dependency Handle(any2)` }, { done: false, status: `Waiting for dependency Handle(any3)` }, ] }); helpers.deployed(deps[3]); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(deps[0]); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(deps[2]); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(deps[1]); should(relationIsReadyStatus(a)).be.True(); helpers.deployed(deps[0], false); helpers.deployed(deps[1], false); helpers.deployed(deps[2], false); helpers.deployed(deps[3], false); should(relationIsReadyStatus(a)).eql({ done: false, status: "Waiting for any of 4 dependencies", related: [ { done: false, status: `Waiting for dependency Handle(any0)` }, { done: false, status: `Waiting for dependency Handle(any1)` }, { done: false, status: `Waiting for dependency Handle(any2)` }, { done: false, status: `Waiting for dependency Handle(any3)` }, ] }); }); it("Should be done with empty dependency list", () => { helpers.currentElem = handle(); const a = AnyOf(helpers, []); should(a.description).equal("any of"); should(a.relatesTo).eql([]); should(relationIsReadyStatus(a)).be.True(); }); }); describe("None", () => { it("Should be done", () => { const a = None(); should(a.description).equal("none"); should(a.relatesTo).be.Undefined(); should(relationIsReadyStatus(a)).be.True(); }); }); }); describe("Basic Relation predicates", () => { it("Should construct a tree", () => { let r = True(); should(ready(r)).be.True(); should(toString(r)).equal("True()"); r = Not(r); should(ready(r)).be.False(); should(toString(r)).equal("Not(\n True()\n)"); r = Not(r); should(ready(r)).be.True(); should(toString(r)).equal("Not(\n Not(\n True()\n )\n)"); r = Value(true, "Foo"); should(ready(r)).be.True(); should(toString(r)).equal("Foo(true)"); r = Not(Value(() => false)); should(ready(r)).be.True(); should(toString(r)).equal("Not(\n Value(<function>)\n)"); }); it("Should construct inverse", () => { let r = inverse(True()); should(toString(r)).equal("True()"); should(ready(r)).be.True(); r = inverse(Not(True())); should(toString(r)).equal("Not(\n True()\n)"); should(ready(r)).be.False(); }); it("Should perform basic logic", () => { should(opTruthTable(Not, 1)).eql([true, false]); should(opTruthTable(Identity, 1)).eql([false, true]); should(opTruthTable(And, 2)).eql([false, false, false, true]); should(opTruthTable(Or, 2)).eql([false, true, true, true]); }); it("Should allow variable arguments", () => { should(opTruthTable(And, 0)).eql([true]); should(opTruthTable(And, 1)).eql([false, true]); should(opTruthTable(Or, 0)).eql([true]); should(opTruthTable(Or, 1)).eql([false, true]); let table = opTruthTable(And, 10); should(table).have.length(2 ** 10); table.forEach((v, i) => should(v).equal(i === 1023 ? true : false)); table = opTruthTable(Or, 10); should(table).have.length(2 ** 10); table.forEach((v, i) => should(v).equal(i === 0 ? false : true)); }); it("Should elide operator for 0 arguments", () => { should(And().description).equal("True"); should(Or().description).equal("True"); }); it("Should elide operator for 1 argument", () => { should(And(Value(false, "Foo")).description).equal("Foo"); should(Or(Value(false, "Foo")).description).equal("Foo"); }); }); describe("Relation Edge", () => { let helpers: MockDeployHelpers; beforeEach(() => { helpers = new MockDeployHelpers(); }); it("Should construct an Edge", () => { const deps = makeHandles(2); const e1 = Edge(deps[0], deps[1], helpers.isDeployed); should(toString(e1)).equal("Edge( Handle(0), Handle(1) )"); should(toString(inverse(e1))).equal("Edge( Handle(1), Handle(0) )"); }); interface CheckDeployStatus { inputs: boolean[]; output: boolean; } function checkDeployStatus(rel: Relation, deps: Handle[]): CheckDeployStatus[] { const allInputs = makeInputs(deps.length, [false, true]); return allInputs.map((inputs) => { deps.forEach((d, i) => helpers.deployed(d, inputs[i])); return { inputs, output: ready(rel) }; }); } const outputOnly = (ds: CheckDeployStatus) => ds.output; it("Should reflect deploy status", () => { const deps = makeHandles(2); const e1 = Edge(deps[0], deps[1], helpers.isDeployed); const inv = inverse(e1); // isDeployed: false, false should(ready(e1)).be.False(); should(ready(inv)).be.False(); // isDeployed: false, true helpers.deployed(deps[1], true); should(ready(e1)).be.True(); should(ready(inv)).be.False(); // isDeployed: true, false helpers.deployed(deps[0], true); helpers.deployed(deps[1], false); should(ready(e1)).be.False(); should(ready(inv)).be.True(); // isDeployed: true, true helpers.deployed(deps[1], true); should(ready(e1)).be.True(); should(ready(inv)).be.True(); }); it("Should construct compound inverse", () => { const deps = makeHandles(3); const n1 = And( Edge(deps[0], deps[1], helpers.isDeployed), Edge(deps[0], deps[2], helpers.isDeployed)); should(toString(n1)).equal( "And(\n Edge( Handle(0), Handle(1) ),\n Edge( Handle(0), Handle(2) )\n)"); const inv = inverse(n1); should(toString(inv)).equal( "And(\n Edge( Handle(1), Handle(0) ),\n Edge( Handle(2), Handle(0) )\n)"); }); it("Should reflect 3 node deploy status: And", () => { // A depends on B and C const [ a, b, c ] = makeHandles(3); const aReady = And( Edge(a, b, helpers.isDeployed), // A depends on B Edge(a, c, helpers.isDeployed) // A depends on C ); const bDestroy = inverse(aReady); // Note: cDestroy === bDestroy // A is ready to Deploy only when both B and C are Deployed // deploy state of A doesn't matter. let status = checkDeployStatus(aReady, [a, b, c]).map(outputOnly); should(status).eql([ false, false, false, true, false, false, false, true, ]); // B is ready to Destroy when A is Destroyed. Deploy state of // B and C don't matter. status = checkDeployStatus(bDestroy, [a, b, c]).map(outputOnly); should(status).eql([ false, false, false, false, true, true, true, true, ]); }); it("Should reflect 4 node deploy status: And", () => { // A depends on B and C // D depends on B and C const [ a, b, c, d ] = makeHandles(4); const aReady = And( Edge(a, b, helpers.isDeployed), // A depends on B Edge(a, c, helpers.isDeployed) // A depends on C ); const dReady = And( Edge(d, b, helpers.isDeployed), // D depends on B Edge(d, c, helpers.isDeployed) // D depends on C ); const bDestroy = And(inverse(aReady), inverse(dReady)); // Note: cDestroy === bDestroy // A is ready to Deploy only when both B and C are Deployed // deploy state of A and D doesn't matter. let status = checkDeployStatus(aReady, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false false, false, true, true, // a=false, b=true false, false, false, false, // a=true, b=false false, false, true, true, // a=true, b=true ]); // D is ready under same conditions as A status = checkDeployStatus(dReady, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false false, false, true, true, // a=false, b=true false, false, false, false, // a=true, b=false false, false, true, true, // a=true, b=true ]); // B is ready to Destroy when A and D are Destroyed. Deploy state of // B and C don't matter. status = checkDeployStatus(bDestroy, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false false, false, false, false, // a=false, b=true false, true, false, true, // a=true, b=false false, true, false, true, // a=true, b=true ]); }); it("Should reflect 5 node deploy status: And", () => { // A depends on B and C // D depends on B and C // E depends on C const [ a, b, c, d, e ] = makeHandles(5); const aReady = And( Edge(a, b, helpers.isDeployed), // A depends on B Edge(a, c, helpers.isDeployed) // A depends on C ); const dReady = And( Edge(d, b, helpers.isDeployed), // D depends on B Edge(d, c, helpers.isDeployed) // D depends on C ); const eReady = Edge(e, c, helpers.isDeployed); // E depends on C // Destroy const bDestroy = And(inverse(aReady), inverse(dReady)); const cDestroy = And(inverse(aReady), And(inverse(dReady), inverse(eReady))); // Note: cDestroy === bDestroy // A is ready to Deploy only when both B and C are Deployed // deploy state of A, D, and E doesn't matter. let status = checkDeployStatus(aReady, [a, b, c, d, e]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false, c=false false, false, false, false, // a=false, b=false, c=true false, false, false, false, // a=false, b=true, c=false true, true, true, true, // a=false, b=true, c=true false, false, false, false, // a=true, b=false, c=false false, false, false, false, // a=true, b=false, c=true false, false, false, false, // a=true, b=true, c=false true, true, true, true, // a=true, b=true, c=true ]); // D is ready under same conditions as A status = checkDeployStatus(dReady, [a, b, c, d, e]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false, c=false false, false, false, false, // a=false, b=false, c=true false, false, false, false, // a=false, b=true, c=false true, true, true, true, // a=false, b=true, c=true false, false, false, false, // a=true, b=false, c=false false, false, false, false, // a=true, b=false, c=true false, false, false, false, // a=true, b=true, c=false true, true, true, true, // a=true, b=true, c=true ]); // E is ready when C is Deployed status = checkDeployStatus(eReady, [a, b, c, d, e]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false, c=false true, true, true, true, // a=false, b=false, c=true false, false, false, false, // a=false, b=true, c=false true, true, true, true, // a=false, b=true, c=true false, false, false, false, // a=true, b=false, c=false true, true, true, true, // a=true, b=false, c=true false, false, false, false, // a=true, b=true, c=false true, true, true, true, // a=true, b=true, c=true ]); // B is ready to Destroy when A and D are Destroyed. Deploy state of // B and C don't matter. status = checkDeployStatus(bDestroy, [a, b, c, d, e]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false, c=false false, false, false, false, // a=false, b=false, c=true false, false, false, false, // a=false, b=true, c=false false, false, false, false, // a=false, b=true, c=true false, false, true, true, // a=true, b=false, c=false false, false, true, true, // a=true, b=false, c=true false, false, true, true, // a=true, b=true, c=false false, false, true, true, // a=true, b=true, c=true ]); // C is ready to Destroy when all of A, D, and E are Destroyed. // Deploy state of B and C don't matter. status = checkDeployStatus(cDestroy, [a, b, c, d, e]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false, c=false false, false, false, false, // a=false, b=false, c=true false, false, false, false, // a=false, b=true, c=false false, false, false, false, // a=false, b=true, c=true false, false, false, true, // a=true, b=false, c=false false, false, false, true, // a=true, b=false, c=true false, false, false, true, // a=true, b=true, c=false false, false, false, true, // a=true, b=true, c=true ]); }); it("Should reflect 4 node deploy status: Or", () => { // A depends on B or C // D depends on B or C const [ a, b, c, d ] = makeHandles(4); const aReady = Or( Edge(a, b, helpers.isDeployed), // A depends on B Edge(a, c, helpers.isDeployed) // A depends on C ); const dReady = Or( Edge(d, b, helpers.isDeployed), // D depends on B Edge(d, c, helpers.isDeployed) // D depends on C ); const bDestroy = And(inverse(aReady), inverse(dReady)); // Note: cDestroy === bDestroy // A is ready to Deploy when either B or C are Deployed // deploy state of A and D doesn't matter. let status = checkDeployStatus(aReady, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, true, true, // a=false, b=false true, true, true, true, // a=false, b=true false, false, true, true, // a=true, b=false true, true, true, true, // a=true, b=true ]); // D is ready under same conditions as A status = checkDeployStatus(dReady, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, true, true, // a=false, b=false true, true, true, true, // a=false, b=true false, false, true, true, // a=true, b=false true, true, true, true, // a=true, b=true ]); // B is ready to Destroy when A and D are Destroyed. Deploy state of // B and C don't matter. status = checkDeployStatus(bDestroy, [a, b, c, d]).map(outputOnly); should(status).eql([ false, false, false, false, // a=false, b=false false, false, false, false, // a=false, b=true false, true, false, true, // a=true, b=false false, true, false, true, // a=true, b=true ]); }); });
the_stack
import React, { useState, Dispatch, SetStateAction, useContext, useEffect } from 'react' import StoreContext from '../lib/stores/context' import { fetchArtifact, setFeaturedArtifacts, setPublishApprovedArtifacts } from '../lib/api/artifacts'; import { Artifact, FETCH_ARTIFACT_ASSETS, UPDATE_ARTIFACT_ASSET } from '../lib/stores/artifacts' import { SET_ACTIVE_PAGE } from '../lib/stores/pages'; import { ADD_COMPONENTS_TO_CART, REMOVE_COMPONENTS_OF_TYPE_FROM_CART, ADD_COMPONENT_TO_CART, REMOVE_COMPONENT_FROM_CART } from '../lib/stores/pipeline'; import { capitalize, formatTitle } from '../lib/util'; import Hero from '../components/Hero' import Button from '../components/Button' import Icon from '@material-ui/core/Icon' import Link from '../components/Link' import PageFooter from '../components/PageFooter'; import { Checkbox, Paper, TableHead, TableRow, TableCell, TableSortLabel, Table, TableBody, Toolbar, Typography, withStyles, WithStyles } from '@material-ui/core'; interface MetaAllPageProps extends WithStyles<typeof styles> { type: string tagName: string getTag: (asset: Artifact) => string description: string alternateBG: boolean leftBtn: string leftLink: string leftIcon?: string rightBtn: string rightLink: string rightIcon?: string canEdit?: boolean } enum SortOrder { ASC = 'asc', DESC = 'desc' } const styles = { checkbox: { color: '#1ccdc7' } } function MetaAllPage(props: MetaAllPageProps) { const { type, tagName, getTag, leftBtn, leftLink, leftIcon, rightBtn, rightLink, rightIcon, canEdit, } = props const [ order ] = useState(SortOrder.DESC) const [ orderBy, setOrderBy ] = useState('name') const columns = [ { id: 'name', label: `${capitalize(type).substring(0, type.length-1)} Name`, numeric: false }, { id: 'desc', label: 'Description', numeric: false }, { id: 'feat', label: 'Featured', numeric: false }, { id: 'pub', label: 'Published', numeric: false }, { id: 'cat', label: tagName, numeric: false }, { id: 'del', label: 'Delete', numeric: false }, ] const { store, dispatch } = useContext(StoreContext) const { artifacts, settings, pipeline } = store const assets: {[key: string]: Artifact} = Object.fromEntries((artifacts[type] || []) .map((asset: Artifact) => [asset.name, asset])) const API = settings.endpoints.api.value || settings.endpoints.api.default useEffect(() => { fetchArtifact(API, type) .then(assets => dispatch({ type: FETCH_ARTIFACT_ASSETS, assetType: type, assets })) dispatch({ type: SET_ACTIVE_PAGE, page: type }) }, [API, type, dispatch]) const featured = new Set(Object.entries(assets) .filter(([_, asset]) => asset.featured) .map(([_, asset]) => asset.id)) const publishable = new Set(Object.entries(assets) .filter(([_, asset]) => asset.publish_approved) .map(([_, asset]) => asset.id)) const selected: Set<string> = new Set(pipeline.components .filter((asset: Artifact) => asset.type === type) .map(({ id }: Artifact) => id)) const handleCheckFeatured = async (id: string, change: { featured: boolean } ) => { if (!canEdit) return if (change.featured) featured.add(id) else featured.delete(id) await setFeaturedArtifacts(API, type, Array.from(featured.values())) .then(() => dispatch({ type: UPDATE_ARTIFACT_ASSET, assetType: type, id, payload: { featured: change.featured } })) } const handleCheckPublishApproved = async (id: string, change: { approved: boolean } ) => { if (!canEdit) return if (change.approved) publishable.add(id) else publishable.delete(id) await setPublishApprovedArtifacts(API, type, Array.from(publishable.values())) .then(() => dispatch({ type: UPDATE_ARTIFACT_ASSET, assetType: type, id, payload: { publish_approved: change.approved } })) } const handleSelectAllForPipeline = (event: React.ChangeEvent<HTMLInputElement>) => dispatch((event.target.checked) ? { type: ADD_COMPONENTS_TO_CART, assets: Object.values(assets)} : { type: REMOVE_COMPONENTS_OF_TYPE_FROM_CART, artifactType: type}) const handleSelectAssetForPipeline = (asset: Artifact) => (event: React.ChangeEvent<HTMLInputElement>) => dispatch((event.target.checked) ? { type: ADD_COMPONENT_TO_CART, asset} : { type: REMOVE_COMPONENT_FROM_CART, id: asset.id }) // console.log(pipeline.components.map(({ type }: Artifact) => type)) return ( <> <Hero title={`${type}`} subtitle={`Upload a ${type}`} > <Link to={leftLink}> <Button className="hero-buttons" variant="contained" color="primary" > {leftIcon && <Icon>{leftIcon}</Icon>} {leftBtn} </Button> </Link> <Link to="https://github.com/machine-learning-exchange/mlx"> <Button className="hero-buttons-outline" variant="outlined" color="primary" > Github </Button> </Link> <Link to={rightLink}> <Button className="hero-buttons" variant="contained" color="primary" > {rightIcon && <Icon>{rightIcon}</Icon>} {rightBtn} </Button> </Link> </Hero> <div style={{ margin: '1rem 0.8rem' }}> <Paper> <EnhancedToolbar type={type} numSelected={pipeline.components.length} toggleModal={(e: never) => {}} /> <Table> <TableHeader type={type} columns={columns} order={order} orderBy={orderBy} setOrderBy={setOrderBy} numSelected={selected.size} rowCount={Object.entries(assets).length} onSelectAllClick={handleSelectAllForPipeline} /> <TableBody> {Object.values(assets).map(asset => <TableRow hover tabIndex={-1} key={asset.name} > <TableCell padding="checkbox"> <Checkbox checked={selected.has(asset.id)} onChange={handleSelectAssetForPipeline(asset)} className={selected.has(asset.id) ? 'checkbox' : ''} /> </TableCell> <TableCell component="th" id={asset.id} scope="row" padding="dense" > {formatTitle(asset.name)} </TableCell> <TableCell padding="dense">{asset.description}</TableCell> <TableCell padding="dense"> <Checkbox checked={asset.featured as boolean} disabled={!canEdit || !asset.publish_approved} onChange={() => handleCheckFeatured(asset.id, { featured: !asset.featured })} className={!canEdit || !asset.publish_approved ? '' : 'checkbox'} /> </TableCell> <TableCell padding="dense"> <Checkbox checked={asset.publish_approved as boolean} disabled={!canEdit} onChange={() => handleCheckPublishApproved(asset.id, { approved: !asset.publish_approved })} className={!canEdit || !asset.publish_approved ? '' : 'checkbox'} /> </TableCell> <TableCell padding="dense">{getTag(asset)}</TableCell> <TableCell padding="dense" align="right"> <Button className="delete-button-assetpage" variant="contained" onClick={async function() { await fetch(`${API}/apis/v1alpha1/${asset.type}/${asset.id}`, { method: 'DELETE' }); window.location.reload(); }} > <span className="delete-button-text-assetpage">Delete</span> </Button> </TableCell> </TableRow> )} </TableBody> </Table> </Paper> </div> <PageFooter/> </> ) } interface TableHeaderProps { type: string columns: { id: string, label: string, numeric: boolean }[] order: SortOrder orderBy: string setOrderBy: Dispatch<SetStateAction<string>> numSelected: number rowCount: number onSelectAllClick: Dispatch<SetStateAction<any>> } function TableHeader(props: TableHeaderProps) { const { columns, order, orderBy, setOrderBy, numSelected, rowCount, onSelectAllClick } = props return ( <TableHead> <TableRow> <TableCell padding="checkbox"> <Checkbox indeterminate={numSelected > 0 && numSelected < rowCount} checked={rowCount > 0 && numSelected === rowCount} onChange={onSelectAllClick} className={numSelected === rowCount ? 'checkbox' : ''} /> </TableCell> {columns.map(({ id, label, numeric }) => <TableCell key={id} align={numeric ? 'right' : 'left'} sortDirection={orderBy === id ? order : false} padding="dense" > <TableSortLabel onClick={() => setOrderBy(id)}>{label}</TableSortLabel> </TableCell> )} </TableRow> </TableHead> ) } interface EnhancedToolbarProps { type: string numSelected: number toggleModal: (e: never) => void } function EnhancedToolbar(props: EnhancedToolbarProps) { const { type, numSelected } = props return ( <Toolbar style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }} > <div> <Typography variant="h6" id="tableTitle"> {numSelected ? `${capitalize(type)} (${numSelected} selected)` : `Select ${capitalize(type)} for your pipeline`} </Typography> </div> </Toolbar> ) } export default withStyles(styles)(MetaAllPage)
the_stack
import { DocumentEditorContainer } from '../../src/document-editor-container/document-editor-container'; import { Toolbar } from '../../src/document-editor-container/tool-bar/tool-bar'; import { createElement } from '@syncfusion/ej2-base'; import { ContextMenu } from '../../src/document-editor/implementation/context-menu'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { LineWidget, ParagraphWidget } from '../../src'; /** * Document Editor container */ describe('Document Editor container initialization', () => { let container: DocumentEditorContainer; let element: HTMLElement; beforeAll(() => { element = createElement('div'); document.body.appendChild(element); DocumentEditorContainer.Inject(Toolbar); container = new DocumentEditorContainer({ showPropertiesPane: true }); container.appendTo(element); }); it('Init container with toolbar', () => { console.log('Init container with toolbar'); container.onPropertyChanged({}, {}); expect(container.toolbarContainer.childNodes.length).toBeGreaterThan(0); }); it('Get Persist Data', () => { console.log('Get Persist Data'); expect(container.getPersistData()).toBe('documenteditor-container'); }); it('Test control destroy 1', (done) => { console.log('Test control destroy 1'); let element: HTMLElement = container.element; setTimeout(function () { expect(function () { container.destroy(); }).not.toThrowError(); expect(element.childNodes.length).toBe(0); document.body.innerHTML = ''; element = undefined; container = undefined; done(); }, 1000); }); }); describe('Property vaidation', () => { let container: DocumentEditorContainer; let element: HTMLElement; beforeAll(() => { element = createElement('div'); document.body.appendChild(element); DocumentEditorContainer.Inject(Toolbar); container = new DocumentEditorContainer({ showPropertiesPane: true, enableComment: false }); container.appendTo(element); }); afterAll(() => { container.destroy(); expect(element.childNodes.length).toBe(0); document.body.removeChild(element); expect(() => { container.destroy(); }).not.toThrowError(); document.body.innerHTML = ''; element = undefined; container = undefined; }); it('Check enable comment in DocumentEditor', (done) => { console.log('Check enable comment in DocumentEditor'); setTimeout(() => { expect(container.documentEditor.enableComment).toBe(false); done(); }, 10); }); it('Properties pane enable validation' , ()=> { console.log('Properties pane enable validation'); (container.documentEditor as any).openBlank(); container.restrictEditing = true; container.showPropertiesPane = true; expect(container.showPropertiesPane).toBe(true); }); }); // describe('Restrict editing enable validation', () => { // let container: DocumentEditorContainer; // let menu: ContextMenu; // let element: HTMLElement; // beforeAll(() => { // element = createElement('div'); // document.body.appendChild(element); // DocumentEditorContainer.Inject(Toolbar); // container = new DocumentEditorContainer({ restrictEditing: true, showPropertiesPane: true }); // container.appendTo(element); // }); // afterAll(() => { // container.destroy(); // expect(element.childNodes.length).toBe(0); // document.body.removeChild(element); // expect(() => { container.destroy(); }).not.toThrowError(); // document.body.innerHTML = ''; // element = undefined; // container = undefined; // }); // it('Restrict editing enable validation', () => { // console.log('Restrict editing enable validation'); // (container.documentEditor as any).openBlank(); // let classele: any = document.getElementsByClassName('e-toolbar-item'); // for (let i: number = 0; i< classele.length; i++) { // let ele: any =classele[i]; // let disabled: any = ele.ariaDisabled; // let label: any = ele.children[0]; // if (isNullOrUndefined(label)) // { // continue; // } // let item: any = label.ariaLabel; // if (item === 'New' || item === 'Open' || item ==='Find' || item === 'LocalClipboard' || item === 'RestrictEditing') { // expect(disabled).toBe('false'); // } // if (item === 'Undo' || item === 'Redo' || item === 'Image dropdownbutton' || item === 'Table' || item === 'Link' || item === 'Break dropdownbutton'|| item === 'PageNumber' || item === 'PageSetup' || item === 'Footer' || item === 'FormFields' || item === 'Header' || item === 'Comments' || item === 'TrackChanges' || item === 'Bookmark' || item === 'TableOfContents' ) { // expect(disabled).toBe('true'); // } // } // expect(container.toolbarModule.propertiesPaneButton.element.parentElement.classList.contains('e-de-overlay')).toBe(true); // expect(container.showPropertiesPane).toBe(false); // }); // }); describe('Document Editor container initialization without element id', () => { let container: DocumentEditorContainer; let container2: DocumentEditorContainer; let element: HTMLElement; let element2: HTMLElement; beforeAll(() => { element = createElement('div'); element2 = createElement('div'); document.body.appendChild(element); document.body.appendChild(element2); DocumentEditorContainer.Inject(Toolbar); container = new DocumentEditorContainer({ showPropertiesPane: false }); container.appendTo(element); container2 = new DocumentEditorContainer({ showPropertiesPane: false }); container2.appendTo(element2); }); afterAll(() => { container.destroy(); container2.destroy(); expect(element.childNodes.length).toBe(0); document.body.removeChild(element); document.body.removeChild(element2); expect(() => { container.destroy(); }).not.toThrowError(); document.body.innerHTML = ''; element = undefined; container = undefined; }); it('Open context menu with mutiple document editor in same page', () => { let event: MouseEvent = new MouseEvent('contextmenu', { clientX: 122, clientY: 156 }); container.documentEditor.documentHelper.viewerContainer.dispatchEvent(event); var elements = document.getElementsByClassName('e-contextmenu-wrapper'); for (let j: number = 0; j < elements.length; j++) { expect(elements[j].getElementsByClassName('e-de-copy').length).toBe(1); } }); }); let numberList: any = { "sections": [ { "blocks": [ { "paragraphFormat": { "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 0, "listId": 0 } }, "inlines": [ { "text": "Test" } ] }, { "paragraphFormat": { "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 1, "listId": 0 } }, "inlines": [ { "text": "Test1" } ] }, { "paragraphFormat": { "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 1, "listId": 0 } }, "inlines": [ { "text": "Test2" } ] }, { "paragraphFormat": { "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 0, "listId": 0 } }, "inlines": [ { "text": "Tmsd" } ] } ], "headersFooters": {}, "sectionFormat": { "headerDistance": 36.0, "footerDistance": 36.0, "pageWidth": 612.0, "pageHeight": 792.0, "leftMargin": 72.0, "rightMargin": 72.0, "topMargin": 72.0, "bottomMargin": 72.0, "differentFirstPage": false, "differentOddAndEvenPages": false, "bidi": false, "restartPageNumbering": false, "pageStartingNumber": 0, "endnoteNumberFormat": "LowerCaseRoman", "footNoteNumberFormat": "Arabic", "restartIndexForFootnotes": "DoNotRestart", "restartIndexForEndnotes": "DoNotRestart", "columns": { "column": [ { "width": 468.0, "space": 36.0 } ], "numberOfColumns": 1, "equalWidth": true } } } ], "fontSubstitutionTable": { "DengXian": "等线", "DengXian Light": "等线 Light" }, "characterFormat": { "fontSize": 11.0, "fontFamily": "Calibri", "fontSizeBidi": 11.0, "fontFamilyBidi": "Arial" }, "paragraphFormat": { "afterSpacing": 8.0, "lineSpacing": 1.0791666507720947, "lineSpacingType": "Multiple" }, "lists": [ { "listId": 0, "abstractListId": 0 } ], "abstractLists": [ { "abstractListId": 0, "levels": [ { "startAt": 1, "restartLevel": 0, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%1.", "paragraphFormat": { "leftIndent": 36.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 1, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%2.1", "paragraphFormat": { "leftIndent": 72.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 2, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%3.", "paragraphFormat": { "leftIndent": 108.0, "firstLineIndent": -9.0 } }, { "startAt": 1, "restartLevel": 3, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%4.", "paragraphFormat": { "leftIndent": 144.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 4, "listLevelPattern": "LowLetter", "followCharacter": "Tab", "numberFormat": "%5.", "paragraphFormat": { "leftIndent": 180.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 5, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%6.", "paragraphFormat": { "leftIndent": 216.0, "firstLineIndent": -9.0 } }, { "startAt": 1, "restartLevel": 6, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%7.", "paragraphFormat": { "leftIndent": 252.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 7, "listLevelPattern": "LowLetter", "followCharacter": "Tab", "numberFormat": "%8.", "paragraphFormat": { "leftIndent": 288.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 8, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%9.", "paragraphFormat": { "leftIndent": 324.0, "firstLineIndent": -9.0 } } ] } ], "background": { "color": "#FFFFFFFF" }, "styles": [ { "type": "Paragraph", "name": "Normal", "next": "Normal" }, { "type": "Character", "name": "Default Paragraph Font" }, { "type": "Paragraph", "name": "List Paragraph", "basedOn": "Normal", "next": "List Paragraph", "paragraphFormat": { "leftIndent": 36.0, "contextualSpacing": true } } ], "defaultTabWidth": 36.0, "formatting": false, "trackChanges": false, "protectionType": "NoProtection", "enforcement": false, "dontUseHTMLParagraphAutoSpacing": false, "alignTablesRowByRow": false, "formFieldShading": true, "footnotes": { "separator": [ { "inlines": [ { "text": "\u0003" } ] } ], "continuationSeparator": [ { "inlines": [ { "text": "\u0004" } ] } ], "continuationNotice": [ { "inlines": [] } ] }, "endnotes": { "separator": [ { "inlines": [ { "text": "\u0003" } ] } ], "continuationSeparator": [ { "inlines": [ { "text": "\u0004" } ] } ], "continuationNotice": [ { "inlines": [] } ] }, "compatibilityMode": "Word2013" }; let listAlignmentDoc: any = { "sections": [ { "blocks": [ { "paragraphFormat": { "leftIndent": 18.0, "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 0, "listId": 0 } }, "inlines": [ { "text": "Test1" } ] }, { "paragraphFormat": { "leftIndent": 18.0, "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 1, "listId": 0 } }, "inlines": [ { "text": "Test11" } ] }, { "paragraphFormat": { "leftIndent": 18.0, "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 1, "listId": 0 } }, "inlines": [ { "text": "Test22" } ] }, { "paragraphFormat": { "leftIndent": 18.0, "styleName": "List Paragraph", "listFormat": { "listLevelNumber": 0, "listId": 0 } }, "inlines": [ { "text": "Test2" } ] } ], "headersFooters": {}, "sectionFormat": { "headerDistance": 36.0, "footerDistance": 36.0, "pageWidth": 612.0, "pageHeight": 792.0, "leftMargin": 72.0, "rightMargin": 72.0, "topMargin": 72.0, "bottomMargin": 72.0, "differentFirstPage": false, "differentOddAndEvenPages": false, "bidi": false, "restartPageNumbering": false, "pageStartingNumber": 0, "endnoteNumberFormat": "LowerCaseRoman", "footNoteNumberFormat": "Arabic", "restartIndexForFootnotes": "DoNotRestart", "restartIndexForEndnotes": "DoNotRestart", "columns": { "column": [ { "width": 468.0, "space": 36.0 } ], "numberOfColumns": 1, "equalWidth": true } } } ], "fontSubstitutionTable": { "DengXian": "等线", "DengXian Light": "等线 Light" }, "characterFormat": { "fontSize": 11.0, "fontFamily": "Calibri", "fontSizeBidi": 11.0, "fontFamilyBidi": "Arial" }, "paragraphFormat": { "afterSpacing": 8.0, "lineSpacing": 1.0791666507720947, "lineSpacingType": "Multiple" }, "lists": [ { "listId": 0, "abstractListId": 0 } ], "abstractLists": [ { "abstractListId": 0, "levels": [ { "startAt": 1, "restartLevel": 0, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%1.", "paragraphFormat": { "leftIndent": 36.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 1, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%2.1", "paragraphFormat": { "leftIndent": 72.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 2, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%3.", "paragraphFormat": { "leftIndent": 108.0, "firstLineIndent": -9.0 } }, { "startAt": 1, "restartLevel": 3, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%4.", "paragraphFormat": { "leftIndent": 144.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 4, "listLevelPattern": "LowLetter", "followCharacter": "Tab", "numberFormat": "%5.", "paragraphFormat": { "leftIndent": 180.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 5, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%6.", "paragraphFormat": { "leftIndent": 216.0, "firstLineIndent": -9.0 } }, { "startAt": 1, "restartLevel": 6, "listLevelPattern": "Arabic", "followCharacter": "Tab", "numberFormat": "%7.", "paragraphFormat": { "leftIndent": 252.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 7, "listLevelPattern": "LowLetter", "followCharacter": "Tab", "numberFormat": "%8.", "paragraphFormat": { "leftIndent": 288.0, "firstLineIndent": -18.0 } }, { "startAt": 1, "restartLevel": 8, "listLevelPattern": "LowRoman", "followCharacter": "Tab", "numberFormat": "%9.", "paragraphFormat": { "leftIndent": 324.0, "firstLineIndent": -9.0 } } ] } ], "background": { "color": "#FFFFFFFF" }, "styles": [ { "type": "Paragraph", "name": "Normal", "next": "Normal" }, { "type": "Character", "name": "Default Paragraph Font" }, { "type": "Paragraph", "name": "List Paragraph", "basedOn": "Normal", "next": "List Paragraph", "paragraphFormat": { "leftIndent": 36.0, "contextualSpacing": true } } ], "defaultTabWidth": 36.0, "formatting": false, "trackChanges": false, "protectionType": "NoProtection", "enforcement": false, "dontUseHTMLParagraphAutoSpacing": false, "alignTablesRowByRow": false, "formFieldShading": true, "footnotes": { "separator": [ { "inlines": [ { "text": "\u0003" } ] } ], "continuationSeparator": [ { "inlines": [ { "text": "\u0004" } ] } ], "continuationNotice": [ { "inlines": [] } ] }, "endnotes": { "separator": [ { "inlines": [ { "text": "\u0003" } ] } ], "continuationSeparator": [ { "inlines": [ { "text": "\u0004" } ] } ], "continuationNotice": [ { "inlines": [] } ] }, "compatibilityMode": "Word2013" }; describe('Apply Numbered List', () => { let container: DocumentEditorContainer; let element: HTMLElement; beforeAll(() => { element = createElement('div'); document.body.appendChild(element); DocumentEditorContainer.Inject(Toolbar); container = new DocumentEditorContainer({ showPropertiesPane: true, enableComment: false }); container.appendTo(element); }); afterAll(() => { container.destroy(); expect(element.childNodes.length).toBe(0); document.body.removeChild(element); expect(() => { container.destroy(); }).not.toThrowError(); document.body.innerHTML = ''; element = undefined; container = undefined; }); it('Apply Numbered List' , ()=> { container.documentEditor.open(JSON.stringify(numberList)); container.documentEditor.selection.select('0;1;2','0;1;2'); container.tableProperties.tableTextProperties.paragraph.appliedNumberingStyle = 'lowletter'; container.tableProperties.tableTextProperties.paragraph.applyLastAppliedNumbering(); expect(container.documentEditor.documentHelper.lists[0].abstractList.levels[1].numberFormat).toBe('%2.'); }); it('List Alignment issues', () => { container.documentEditor.open(JSON.stringify(listAlignmentDoc)); let para: ParagraphWidget = container.documentEditor.documentHelper.pages[0].bodyWidgets[0].childWidgets[2] as ParagraphWidget; let line: LineWidget = para.childWidgets[0] as LineWidget; const elementWidth: number = line.children[0].width + line.children[1].width; container.documentEditor.selection.select('0;1;3', '0;1;3'); container.tableProperties.tableTextProperties.paragraph.appliedNumberingStyle = 'lowletter'; container.tableProperties.tableTextProperties.paragraph.applyLastAppliedNumbering(); expect(elementWidth).toBe(line.children[0].width + line.children[1].width); }); });
the_stack
import * as Path from 'path'; import * as v from 'villa'; import { Command, CommandClass, Context, GeneralValidator, HelpInfo, OptionDefinition, ParamDefinition, ParamsDefinition, } from './command'; import {CastableType, Printable, buildCastingContext, cast} from './object'; import {ExpectedError} from './error'; import {existsDir, existsFile} from '../internal-util'; const COMMAND_NAME_REGEX = /^[\w\d]+(?:-[\w\d]+)*$/; const HELP_OPTION_REGEX = /^(?:-[h?]|--help)$/; export interface CommandRoot { label: string; path: string; } export type GeneralCommandRoot = string | CommandRoot; export interface CommandModule { default?: CommandClass; brief?: string; description?: string; subcommands?: SubcommandDefinition[]; } export interface SubcommandDefinition { name: string; alias?: string; aliases?: string[]; brief?: string; } export interface CommandEntry { path: string; module: CommandModule | undefined; } export interface SubcommandSearchBaseResult { name: string; path?: string | undefined; module: CommandModule | undefined; searchBase: string | undefined; } export interface SubcommandSearchInProgressContext extends SubcommandSearchBaseResult { label: string; } export interface SubcommandSearchContext extends SubcommandSearchInProgressContext { searchBase: string; } interface PreProcessResult { sequence: string[]; args: string[]; path: string | undefined; module: CommandModule | undefined; searchContexts: SubcommandSearchContext[]; possibleUnknownCommandName: string | undefined; } /** * Clime command line interface. */ export class CLI { roots: CommandRoot[]; constructor( /** Command entry name. */ public name: string, /** Root directory of command modules. */ roots: GeneralCommandRoot | GeneralCommandRoot[], ) { roots = Array.isArray(roots) ? roots : [roots]; this.roots = roots.map((root) => { let label: string | undefined; let path: string; if (typeof root === 'string') { path = root; } else { label = root.label; path = root.path; } return { label: label || 'Subcommands', path: Path.resolve(path), }; }); } async execute(argv: string[], cwd?: string): Promise<any>; async execute( argv: string[], contextExtension: object, cwd?: string, ): Promise<any>; async execute( argv: string[], contextExtension: object | string | undefined, cwd?: string | undefined, ): Promise<any> { if (typeof contextExtension === 'string') { cwd = contextExtension; contextExtension = undefined; } if (!cwd) { cwd = process.cwd(); } let { sequence, args, path, module, searchContexts, possibleUnknownCommandName, } = await this.preProcessArguments(argv); let description: string | undefined; if (module) { let TargetCommand = module.default; if (TargetCommand && TargetCommand.prototype instanceof Command) { // This is a command module with an actual command. if (!TargetCommand.decorated) { throw new TypeError(`Command defined in module "${path}" does not seem to be initialized, \ make sure to decorate it with \`@command()\``); } TargetCommand.path = path!; TargetCommand.helpBuildingContexts = searchContexts.map((context) => { return { label: context.label, dir: context.searchBase, }; }); TargetCommand.sequence = sequence; let argsParser = new ArgsParser(TargetCommand); let parsedArgs = await argsParser.parse( sequence, args, cwd, contextExtension, ); if (!parsedArgs) { return HelpInfo.build(TargetCommand); } let command = new TargetCommand(); let { args: commandArgs, extraArgs: commandExtraArgs, options: commandOptions, context, } = parsedArgs; return this.executeCommand( command, commandArgs, commandExtraArgs, commandOptions, context, ); } else { // This is a command module with only description and subcommand definitions. description = module.description; } } let helpInfo = await HelpInfo.build({ sequence, contexts: searchContexts.map((context) => { return { label: context.label, dir: context.searchBase, }; }), description, }); if (possibleUnknownCommandName) { throw new UsageError( `Unknown subcommand "${possibleUnknownCommandName}"`, { getHelp() { return helpInfo; }, }, ); } if (args.length && HELP_OPTION_REGEX.test(args[0])) { return helpInfo; } else { throw helpInfo; } } private async preProcessSearchBase( searchBase: string, possibleCommandName: string, aliasMap: Map<string, string>, ): Promise<SubcommandSearchBaseResult> { let definitions = await CLI.getSubcommandDefinitions(searchBase); let definitionMap = new Map<string, SubcommandDefinition>(); for (let definition of definitions) { definitionMap.set(definition.name, definition); let aliases = definition.aliases || (definition.alias && [definition.alias]); if (!aliases) { continue; } for (let alias of aliases) { if (aliasMap.has(alias)) { let targetName = aliasMap.get(alias); if (targetName !== definition.name) { throw new Error(`Alias "${alias}" already exists and points to "${targetName}" \ instead of "${definition.name}"`); } continue; } aliasMap.set(alias, definition.name); } } possibleCommandName = definitionMap.has(possibleCommandName) ? possibleCommandName : aliasMap.get(possibleCommandName) || possibleCommandName; searchBase = Path.join(searchBase, possibleCommandName); let entry = await CLI.findEntryBySearchBase(searchBase); return { name: possibleCommandName, searchBase: existsDir(searchBase) ? searchBase : undefined, path: entry && entry.path, module: entry && entry.module, }; } /** * Mapping the command line arguments to a specific command file. */ private async preProcessArguments(argv: string[]): Promise<PreProcessResult> { let sequence = [this.name]; let possibleUnknownCommandName: string | undefined; let argsIndex = 0; let targetPath: string | undefined; let targetModule: CommandModule | undefined; let contexts: SubcommandSearchContext[] = await v.map( this.roots, async (root) => { let path: string | undefined = Path.join( root.path, CLI.commandModuleDefaultFileName, ); path = (await existsFile(path)) ? path : undefined; let module: CommandModule | undefined; if (path) { module = require(path) as CommandModule; if (module.default || !targetPath) { targetPath = path; targetModule = module; } } return { label: root.label, name: this.name, searchBase: root.path, path, module, }; }, ); for (let i = argsIndex; i < argv.length && contexts.length; i++) { let possibleCommandName = argv[i]; if (!COMMAND_NAME_REGEX.test(possibleCommandName)) { break; } let aliasMap = new Map<string, string>(); let nextContexts: SubcommandSearchInProgressContext[] = await v.map( contexts, async (context) => { let searchBaseContext = await this.preProcessSearchBase( context.searchBase, possibleCommandName, aliasMap, ); return { label: context.label, ...searchBaseContext, }; }, ); let targetContexts = nextContexts.filter((context) => !!context.path); if (!targetContexts.length) { possibleUnknownCommandName = possibleCommandName; break; } let targetContext = targetContexts[0]; for (let context of targetContexts.slice(1)) { let module = context.module; if (module && module.default) { targetContext = context; } } targetPath = targetContext.path; targetModule = targetContext.module; possibleCommandName = targetContext.name; argsIndex = i + 1; sequence.push(possibleCommandName); contexts = nextContexts.filter( (context) => !!context.searchBase, ) as SubcommandSearchContext[]; } return { sequence, args: argv.slice(argsIndex), path: targetPath, module: targetModule, searchContexts: contexts, possibleUnknownCommandName, }; } private executeCommand( command: Command, commandArgs: string[], commandExtraArgs: string[] | undefined, commandOptions: Clime.Dictionary<any> | undefined, context: Context | undefined, ): any { let executeMethodArgs: any[] = commandArgs.concat(); if (commandExtraArgs) { executeMethodArgs.push(commandExtraArgs); } if (commandOptions) { executeMethodArgs.push(commandOptions); } if (context) { executeMethodArgs.push(context); } return command.execute(...executeMethodArgs); } /** * The name of the default sub-command module. * * E.g.: * * ```ts * import {CLI} from 'clime'; * * CLI.commandModuleDefaultName = 'mySpecialDefaultName'; * ``` */ static commandModuleDefaultName = 'default'; /** * The extension to use when looking up sub-command modules. * * E.g.: * * ```ts * import {CLI} from 'clime'; * * CLI.commandModuleExtension = '.cjs' * ``` */ static commandModuleExtension = '.js'; static get commandModuleDefaultFileName(): string { return `${this.commandModuleDefaultName}${this.commandModuleExtension}`; } /** * @internal * Get subcommands definition written as `export subcommands = [...]`. */ static async getSubcommandDefinitions( searchBase: string, ): Promise<SubcommandDefinition[]> { let entry = await this.findEntryBySearchBase(searchBase); if (!entry || !entry.module) { return []; } return entry.module.subcommands || []; } private static async findEntryBySearchBase( searchBase: string, ): Promise<CommandEntry | undefined> { let possiblePaths = [ `${searchBase}${this.commandModuleExtension}`, Path.join(searchBase, this.commandModuleDefaultFileName), ]; for (let possiblePath of possiblePaths) { if (await existsFile(possiblePath)) { return { path: possiblePath, module: require(possiblePath) as CommandModule, }; } } if (await existsDir(searchBase)) { return { path: searchBase, module: undefined, }; } return undefined; } } export interface ParsedArgs { args: any[]; extraArgs?: any[]; options?: Clime.Dictionary<any>; context?: Context; } class ArgsParser { private helpProvider: HelpProvider; private paramDefinitions: ParamDefinition<any>[]; private requiredParamsNumber: number; private paramsDefinition: ParamsDefinition<any>; private optionDefinitionMap: Map<string, OptionDefinition<any>>; private optionFlagMapping: Map<string, string>; private optionsConstructor: Clime.Constructor<Clime.Dictionary<any>>; private optionDefinitions: OptionDefinition<any>[]; private skippedArgsEnabled: boolean; private contextConstructor: typeof Context; constructor(command: typeof Command) { this.helpProvider = command; this.paramDefinitions = command.paramDefinitions; this.requiredParamsNumber = command.requiredParamsNumber; this.paramsDefinition = command.paramsDefinition; this.optionsConstructor = command.optionsConstructor; this.optionDefinitions = command.optionDefinitions; this.skippedArgsEnabled = command.skippedArgsEnabled; this.contextConstructor = command.contextConstructor; if (this.optionDefinitions) { this.optionFlagMapping = new Map<string, string>(); this.optionDefinitionMap = new Map<string, OptionDefinition<any>>(); for (let definition of this.optionDefinitions) { let {name, flag} = definition; this.optionDefinitionMap.set(name, definition); if (flag) { this.optionFlagMapping.set(flag, name); } } } } async parse( sequence: string[], args: string[], cwd: string, contextExtension: object | undefined, ): Promise<ParsedArgs | undefined> { let that = this; let ContextConstructor: Clime.Constructor<Context> = this.contextConstructor || Context; let context = new ContextConstructor( { cwd, commands: sequence, }, contextExtension, ); args = args.concat(); let OptionConstructor = this.optionsConstructor; let optionDefinitions = this.optionDefinitions; let optionDefinitionMap = this.optionDefinitionMap || new Map<string, OptionDefinition<any>>(); let optionFlagMapping = this.optionFlagMapping || new Map<string, string>(); let requiredOptionSet: Set<string> | undefined; let paramDefinitions = this.paramDefinitions || []; let pendingParamDefinitions = paramDefinitions.concat(); let paramsDefinition = this.paramsDefinition; let argsNumber = args.length; let commandArgs = [] as any[]; let commandExtraArgs = paramsDefinition && ([] as any[]); let commandOptions: Clime.Dictionary<any> | undefined; if (OptionConstructor) { commandOptions = new OptionConstructor(); requiredOptionSet = new Set<string>(); for (let definition of optionDefinitions) { let { name, key, type, required, validators, toggle, default: defaultValue, } = definition; if (required) { requiredOptionSet.add(name); } if (toggle) { commandOptions[key] = false; } else { commandOptions[key] = typeof defaultValue === 'string' ? await castArgument(defaultValue, name, type, validators, true) : defaultValue; } } } while (args.length) { let arg = args.shift() as string; if ( arg === '-?' || (arg === '-h' && !optionFlagMapping.has('h')) || (arg === '--help' && !optionDefinitionMap.has('help')) ) { return undefined; } if (this.skippedArgsEnabled && arg === '--') { break; } if (arg[0] === '-' && isNaN(Number(arg))) { if (arg[1] === '-') { await consumeToggleOrOption(arg.substr(2)); } else { await consumeFlags(arg.substr(1)); } } else if (pendingParamDefinitions.length) { let definition = pendingParamDefinitions.shift() as ParamDefinition< any >; let casted = await castArgument( arg, definition.name, definition.type, definition.validators, false, ); commandArgs.push(casted); } else if (paramsDefinition) { let casted = await castArgument( arg, paramsDefinition.name, paramsDefinition.type, paramsDefinition.validators, false, ); commandExtraArgs.push(casted); } else { throw new UsageError( `Expecting ${paramDefinitions.length} parameter(s) at most but got ${argsNumber} instead`, this.helpProvider, ); } } context.skippedArgs = args; { let expecting = this.requiredParamsNumber; let got = commandArgs.length; if (got < expecting) { let missingArgNames = pendingParamDefinitions .slice(0, expecting - got) .map((definition) => `\`${definition.name}\``); throw new UsageError( `Expecting parameter(s) ${missingArgNames.join(', ')}`, this.helpProvider, ); } } let missingOptionNames = requiredOptionSet && Array.from(requiredOptionSet); if (missingOptionNames && missingOptionNames.length) { throw new UsageError( `Missing required option(s) \`${missingOptionNames.join('`, `')}\``, this.helpProvider, ); } for (let definition of pendingParamDefinitions) { let defaultValue = definition.default; let value = typeof defaultValue === 'string' ? await castArgument( defaultValue, definition.name, definition.type, definition.validators, true, ) : defaultValue; commandArgs.push(value); } if ( paramsDefinition && paramsDefinition.required && !commandExtraArgs.length ) { throw new UsageError( `Expecting at least one element for variadic parameters \`${paramsDefinition.name}\``, this.helpProvider, ); } return { args: commandArgs, extraArgs: paramsDefinition && commandExtraArgs, options: commandOptions, context: this.contextConstructor ? context : undefined, }; async function consumeFlags(flags: string): Promise<void> { for (let i = 0; i < flags.length; i++) { let flag = flags[i]; if (!optionFlagMapping.has(flag)) { throw new UsageError( `Unknown option flag "${flag}"`, that.helpProvider, ); } let name = optionFlagMapping.get(flag)!; let definition = optionDefinitionMap.get(name)!; if (definition.required) { requiredOptionSet!.delete(name); } if (definition.toggle) { commandOptions![definition.key] = true; } else { if (i !== flags.length - 1) { throw new UsageError( 'Only the last flag in a sequence can refer to an option instead of a toggle', that.helpProvider, ); } await consumeOption(definition); } } } async function consumeToggleOrOption(name: string): Promise<void> { if (!optionDefinitionMap.has(name)) { throw new UsageError(`Unknown option \`${name}\``, that.helpProvider); } let definition = optionDefinitionMap.get(name)!; if (definition.required) { requiredOptionSet!.delete(name); } if (definition.toggle) { commandOptions![definition.key] = true; } else { await consumeOption(definition); } } async function consumeOption( definition: OptionDefinition<any>, ): Promise<void> { let {name, key, type, validators} = definition; let arg = args.shift(); if (arg === undefined) { throw new UsageError( `Expecting value for option \`${name}\``, that.helpProvider, ); } if (arg[0] === '-' && isNaN(Number(arg))) { throw new UsageError( `Expecting a value instead of an option or toggle "${arg}" for option \`${name}\``, that.helpProvider, ); } commandOptions![key] = await castArgument( arg, name, type, validators, false, ); } async function castArgument( arg: string, name: string, type: CastableType<any>, validators: GeneralValidator<any>[], usingDefault: boolean, ): Promise<any> { let castingContext = buildCastingContext(context, { name, default: usingDefault, validators, }); return cast(arg, type, castingContext); } } } export interface HelpProvider { getHelp(): Promise<HelpInfo> | HelpInfo; } export class UsageError extends ExpectedError implements Printable { constructor(message: string, public helpProvider: HelpProvider) { super(message); } async print( stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, ): Promise<void> { super.print(stdout, stderr); let help = await this.helpProvider.getHelp(); help.print(stdout, stderr); } }
the_stack
import {CapabilitiesResponse, Cdd, DEFAULT_MAX_COPIES, Destination, DestinationCertificateStatus, DestinationConnectionStatus, DestinationOrigin, DestinationStore, DestinationType, GooglePromotedDestinationId, LocalDestinationInfo, MeasurementSystemUnitType, MediaSizeCapability, MediaSizeOption, NativeInitialSettings, VendorCapabilityValueType} from 'chrome://print/print_preview.js'; import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {eventToPromise} from 'chrome://webui-test/test_util.js'; export function getDefaultInitialSettings(isPdf: boolean = false): NativeInitialSettings { return { isInKioskAutoPrintMode: false, isInAppKioskMode: false, pdfPrinterDisabled: false, thousandsDelimiter: ',', decimalDelimiter: '.', previewModifiable: !isPdf, documentTitle: 'title', documentHasSelection: true, shouldPrintSelectionOnly: false, previewIsFromArc: false, printerName: 'FooDevice', serializedAppStateStr: null, serializedDefaultDestinationSelectionRulesStr: null, destinationsManaged: false, uiLocale: 'en-us', unitType: MeasurementSystemUnitType.IMPERIAL, isDriveMounted: true, }; } export function getCddTemplate( printerId: string, opt_printerName?: string): CapabilitiesResponse { const template: CapabilitiesResponse = { printer: { deviceName: printerId, printerName: opt_printerName || '', }, capabilities: { version: '1.0', printer: { collate: {default: true}, copies: {default: 1, max: DEFAULT_MAX_COPIES}, color: { option: [ {type: 'STANDARD_COLOR', is_default: true}, {type: 'STANDARD_MONOCHROME'} ] }, dpi: { option: [ {horizontal_dpi: 200, vertical_dpi: 200, is_default: true}, {horizontal_dpi: 100, vertical_dpi: 100}, ] }, duplex: { option: [ {type: 'NO_DUPLEX', is_default: true}, {type: 'LONG_EDGE'}, {type: 'SHORT_EDGE'} ] }, page_orientation: { option: [ {type: 'PORTRAIT', is_default: true}, {type: 'LANDSCAPE'}, {type: 'AUTO'} ] }, media_size: { option: [ { name: 'NA_LETTER', width_microns: 215900, height_microns: 279400, is_default: true, custom_display_name: 'Letter', }, { name: 'CUSTOM', width_microns: 215900, height_microns: 215900, custom_display_name: 'CUSTOM_SQUARE', } ] } } } }; // <if expr="chromeos_ash or chromeos_lacros"> template.capabilities!.printer.pin = {supported: true}; // </if> return template; } /** * Gets a CDD template and adds some dummy vendor capabilities. For select * capabilities, the values of these options are arbitrary. These values are * provided and read by the destination, so there are no fixed options like * there are for margins or color. * @param opt_printerName Defaults to an empty string. */ export function getCddTemplateWithAdvancedSettings( numSettings: number, printerId: string, opt_printerName?: string): CapabilitiesResponse { const template = getCddTemplate(printerId, opt_printerName); if (numSettings < 1) { return template; } template.capabilities!.printer.vendor_capability = [{ display_name: 'Print Area', id: 'printArea', type: 'SELECT', select_cap: { option: [ {display_name: 'A4', value: 4, is_default: true}, {display_name: 'A6', value: 6}, {display_name: 'A7', value: 7}, ], }, }]; if (numSettings < 2) { return template; } // Add new capability. template.capabilities!.printer.vendor_capability!.push({ display_name: 'Paper Type', id: 'paperType', type: 'SELECT', select_cap: { option: [ {display_name: 'Standard', value: 0, is_default: true}, {display_name: 'Recycled', value: 1}, {display_name: 'Special', value: 2} ] } }); if (numSettings < 3) { return template; } template.capabilities!.printer.vendor_capability!.push({ display_name: 'Watermark', id: 'watermark', type: 'TYPED_VALUE', typed_value_cap: { default: '', } }); if (numSettings < 4) { return template; } template.capabilities!.printer.vendor_capability.push({ display_name: 'Staple', id: 'finishings/4', type: 'TYPED_VALUE', typed_value_cap: { default: '', value_type: VendorCapabilityValueType.BOOLEAN, } }); return template; } /** * Creates a destination with a certificate status tag. * @param id Printer id * @param name Printer display name * @param invalid Whether printer has an invalid certificate. */ export function createDestinationWithCertificateStatus( id: string, name: string, invalid: boolean) { const tags = { certificateStatus: invalid ? DestinationCertificateStatus.NO : DestinationCertificateStatus.UNKNOWN, account: 'foo@chromium.org', }; const dest = new Destination( id, DestinationType.GOOGLE, DestinationOrigin.COOKIES, name, DestinationConnectionStatus.ONLINE, tags); return dest; } /** * @return The capabilities of the Save as PDF destination. */ export function getPdfPrinter(): {capabilities: Cdd} { return { capabilities: { version: '1.0', printer: { page_orientation: { option: [ {type: 'AUTO', is_default: true}, {type: 'PORTRAIT'}, {type: 'LANDSCAPE'} ] }, color: {option: [{type: 'STANDARD_COLOR', is_default: true}]}, media_size: { option: [{ name: 'NA_LETTER', width_microns: 0, height_microns: 0, is_default: true }] } } } }; } /** * Get the default media size for |device|. * @return The width and height of the default media. */ export function getDefaultMediaSize(device: CapabilitiesResponse): MediaSizeOption { const size = device.capabilities!.printer.media_size!.option!.find( opt => !!opt.is_default); return { width_microns: size!.width_microns, height_microns: size!.height_microns }; } /** * Get the default page orientation for |device|. * @return The default orientation. */ export function getDefaultOrientation(device: CapabilitiesResponse): string { const options = device.capabilities!.printer.page_orientation!.option; return assert(options!.find(opt => !!opt.is_default)!.type!); } /** * Creates 5 local destinations, adds them to |localDestinations|. */ export function getDestinations(localDestinations: LocalDestinationInfo[]): Destination[] { const destinations: Destination[] = []; // <if expr="not chromeos and not lacros"> const origin = DestinationOrigin.LOCAL; // </if> // <if expr="chromeos_ash or chromeos_lacros"> const origin = DestinationOrigin.CROS; // </if> // Five destinations. FooDevice is the system default. [{deviceName: 'ID1', printerName: 'One'}, {deviceName: 'ID2', printerName: 'Two'}, {deviceName: 'ID3', printerName: 'Three'}, {deviceName: 'ID4', printerName: 'Four'}, {deviceName: 'FooDevice', printerName: 'FooName'}] .forEach(info => { const destination = new Destination( info.deviceName, DestinationType.LOCAL, origin, info.printerName, DestinationConnectionStatus.ONLINE); localDestinations.push(info); destinations.push(destination); }); return destinations; } /** * Returns a media size capability with custom and localized names. */ export function getMediaSizeCapabilityWithCustomNames(): MediaSizeCapability { const customLocalizedMediaName = 'Vendor defined localized media name'; const customMediaName = 'Vendor defined media name'; return { option: [ { name: 'CUSTOM', width_microns: 15900, height_microns: 79400, is_default: true, custom_display_name_localized: [{locale: navigator.language, value: customLocalizedMediaName}] }, { name: 'CUSTOM', width_microns: 15900, height_microns: 79400, custom_display_name: customMediaName } ] }; } /** * @param input The value to set for the input element. * @param parentElement The element that receives the input-change event. * @return Promise that resolves when the input-change event has fired. */ export function triggerInputEvent( inputElement: HTMLInputElement|CrInputElement, input: string, parentElement: HTMLElement): Promise<void> { inputElement.value = input; inputElement.dispatchEvent( new CustomEvent('input', {composed: true, bubbles: true})); return eventToPromise('input-change', parentElement); } const TestListenerElementBase = WebUIListenerMixin(PolymerElement); class TestListenerElement extends TestListenerElementBase { static get is() { return 'test-listener-element'; } } declare global { interface HTMLElementTagNameMap { 'test-listener-element': TestListenerElement; } } export function setupTestListenerElement(): void { customElements.define(TestListenerElement.is, TestListenerElement); } export function createDestinationStore(): DestinationStore { const testListenerElement = document.createElement('test-listener-element'); document.body.appendChild(testListenerElement); return new DestinationStore( testListenerElement.addWebUIListener.bind(testListenerElement)); } // <if expr="chromeos_ash or chromeos_lacros"> /** * @return The Google Drive destination. */ export function getGoogleDriveDestination(_account: string): Destination { return new Destination( 'Save to Drive CrOS', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'Save to Google Drive', DestinationConnectionStatus.ONLINE); } // </if> // <if expr="not chromeos and not lacros"> /** * @param account The user account the destination should be associated with. * @return The Google Drive destination. */ export function getGoogleDriveDestination(account: string): Destination { return getCloudDestination( GooglePromotedDestinationId.DOCS, GooglePromotedDestinationId.DOCS, account); } // </if> /** * @param account The user account the destination should be associated with. */ export function getCloudDestination( id: string, name: string, account: string): Destination { return new Destination( id, DestinationType.GOOGLE, DestinationOrigin.COOKIES, name, DestinationConnectionStatus.ONLINE, {account: account}); } /** @return The Save as PDF destination. */ export function getSaveAsPdfDestination(): Destination { return new Destination( GooglePromotedDestinationId.SAVE_AS_PDF, DestinationType.LOCAL, DestinationOrigin.LOCAL, loadTimeData.getString('printToPDF'), DestinationConnectionStatus.ONLINE); } /** * @param section The settings section that contains the select to toggle. * @param option The option to select. * @return Promise that resolves when the option has been selected and the * process-select-change event has fired. */ export function selectOption( section: HTMLElement, option: string): Promise<void> { const select = section.shadowRoot!.querySelector('select')!; select.value = option; select.dispatchEvent(new CustomEvent('change')); return eventToPromise('process-select-change', section); }
the_stack
import { Accessor, createContext, createUniqueId, JSX, Show, splitProps, useContext, } from "solid-js"; import { createStore } from "solid-js/store"; import { visuallyHiddenStyles } from "../../styled-system/utils"; import { isFunction } from "../../utils/assertion"; import { classNames } from "../../utils/css"; import { callHandler, chainHandlers } from "../../utils/function"; import { hope } from "../factory"; import { useFormControlContext } from "../form-control/form-control"; import { useFormControl } from "../form-control/use-form-control"; import { ElementType, HTMLHopeProps } from "../types"; import { useCheckboxGroupContext } from "./checkbox-group"; type CheckboxPrimitiveChildrenRenderProp = (props: { state: Accessor<CheckboxPrimitiveState>; }) => JSX.Element; interface CheckboxPrimitiveOptions { /** * The ref to be passed to the internal <input> tag. */ ref?: HTMLInputElement | ((el: HTMLInputElement) => void); /** * The id to be passed to the internal <input> tag. */ id?: string; /** * The css class to be passed to the internal <input> tag. */ inputClass?: string; /** * The name to be passed to the internal <input> tag. */ name?: string; /** * The value to be used in the checkbox input. * This is the value that will be returned on form submission. */ value?: string | number; /** * If `true`, the checkbox will be checked. * You'll need to pass `onChange` to update its value (since it is now controlled) */ checked?: boolean; /** * If `true`, the checkbox will be initially checked. */ defaultChecked?: boolean; /** * If `true`, the checkbox will be indeterminate. * This only affects the icon shown inside checkbox * and does not modify the checked property. */ indeterminate?: boolean; /** * If `true`, the checkbox input is marked as required, * and `required` attribute will be added */ required?: boolean; /** * If `true`, the checkbox will be disabled */ disabled?: boolean; /** * If `true`, the input will have `aria-invalid` set to `true` */ invalid?: boolean; /** * If `true`, the checkbox will be readonly */ readOnly?: boolean; /** * The children of the checkbox. */ children?: JSX.Element | CheckboxPrimitiveChildrenRenderProp; /** * The callback invoked when the checked state of the checkbox changes. */ onChange?: JSX.EventHandlerUnion<HTMLInputElement, Event>; /** * The callback invoked when the checkbox is focused */ onFocus?: JSX.EventHandlerUnion<HTMLInputElement, FocusEvent>; /** * The callback invoked when the checkbox is blurred (loses focus) */ onBlur?: JSX.EventHandlerUnion<HTMLInputElement, FocusEvent>; } export type CheckboxPrimitiveProps<C extends ElementType = "label"> = HTMLHopeProps< C, CheckboxPrimitiveOptions >; export interface CheckboxPrimitiveState { /** * The `checked` state of the checkbox. * (In uncontrolled mode) */ _checked: boolean; /** * If `true`, the checkbox is in controlled mode. * (have checked and onChange props) */ isControlled: boolean; /** * If `true`, the checkbox is currently focused. */ isFocused: boolean; /** * The `checked` state of the checkbox. * (In controlled mode) */ checked: boolean; /** * The value to be used in the checkbox input. * This is the value that will be returned on form submission. */ value?: string | number; /** * The id of the input field in a checkbox. */ id?: string; /** * The name of the input field in a checkbox. */ name?: string; /** * If `true`, the checkbox input is marked as required, * and `required` attribute will be added */ required?: boolean; /** * If `true`, the checkbox will be indeterminate. * This only affects the icon shown inside checkbox * and does not modify the checked property. */ indeterminate?: boolean; /** * If `true`, the checkbox will be disabled */ disabled?: boolean; /** * If `true`, the input will have `aria-invalid` set to `true` */ invalid?: boolean; /** * If `true`, the checkbox will be readonly */ readOnly?: boolean; "aria-required"?: boolean; "aria-disabled"?: boolean; "aria-invalid"?: boolean; "aria-readonly"?: boolean; "aria-label"?: string; "aria-labelledby"?: string; "aria-describedby"?: string; "data-indeterminate"?: string; "data-focus"?: string; "data-checked"?: string; "data-required"?: string; "data-disabled"?: string; "data-invalid"?: string; "data-readonly"?: string; } /** * Contains all the parts of a checkbox. * It renders a `label` with a visualy hidden `input[type=checkbox]`. * You can style this element directly, or you can use it as a wrapper to put other components into, or both. */ export function CheckboxPrimitive<C extends ElementType = "label">( props: CheckboxPrimitiveProps<C> ) { const defaultId = `hope-checkbox-${createUniqueId()}`; const formControlContext = useFormControlContext(); const checkboxGroupContext = useCheckboxGroupContext(); const formControlProps = useFormControl<HTMLInputElement>(props); const [state, setState] = createStore<CheckboxPrimitiveState>({ // eslint-disable-next-line solid/reactivity _checked: !!props.defaultChecked, isFocused: false, get isControlled() { return props.checked !== undefined; }, get checked() { if (checkboxGroupContext) { const checkboxGroupValue = checkboxGroupContext.state.value; return checkboxGroupValue != null ? checkboxGroupValue.some(val => String(props.value) === String(val)) : false; } // Not in CheckboxGroup return this.isControlled ? !!props.checked : this._checked; }, get id() { if (formControlContext && !checkboxGroupContext) { return formControlProps.id; } return props.id ?? defaultId; }, get name() { return props.name ?? checkboxGroupContext?.state.name; }, get value() { return props.value; }, get indeterminate() { return props.indeterminate; }, get required() { return formControlProps.required ?? checkboxGroupContext?.state.required; }, get disabled() { return formControlProps.disabled ?? checkboxGroupContext?.state.disabled; }, get invalid() { return formControlProps.invalid ?? checkboxGroupContext?.state.invalid; }, get readOnly() { return formControlProps.readOnly ?? checkboxGroupContext?.state.readOnly; }, get ["aria-required"]() { return this.required ? true : undefined; }, get ["aria-disabled"]() { return this.disabled ? true : undefined; }, get ["aria-invalid"]() { return this.invalid ? true : undefined; }, get ["aria-readonly"]() { return this.readOnly ? true : undefined; }, get ["aria-label"]() { return props["aria-label"]; }, get ["aria-labelledby"]() { return props["aria-labelledby"]; }, get ["aria-describedby"]() { return props["aria-describedby"]; }, get ["data-indeterminate"]() { return this.indeterminate ? "" : undefined; }, get ["data-focus"]() { return this.isFocused ? "" : undefined; }, get ["data-checked"]() { return this.checked ? "" : undefined; }, get ["data-required"]() { return this.required ? "" : undefined; }, get ["data-disabled"]() { return this.disabled ? "" : undefined; }, get ["data-invalid"]() { return this.invalid ? "" : undefined; }, get ["data-readonly"]() { return this.readOnly ? "" : undefined; }, }); // eslint-disable-next-line @typescript-eslint/no-unused-vars const [local, _, others] = splitProps( props as CheckboxPrimitiveProps<"label">, ["inputClass", "children", "ref", "tabIndex", "onChange"], [ "id", "name", "value", "indeterminate", "checked", "defaultChecked", "required", "disabled", "invalid", "readOnly", "onFocus", "onBlur", ] ); const onChange: JSX.EventHandlerUnion<HTMLInputElement, Event> = event => { if (state.readOnly || state.disabled) { event.preventDefault(); return; } if (!state.isControlled) { const target = event.target as HTMLInputElement; setState("_checked", target.checked); } chainHandlers(checkboxGroupContext?.onChange, local.onChange)(event); }; const onFocus: JSX.EventHandlerUnion<HTMLInputElement, FocusEvent> = event => { setState("isFocused", true); callHandler(formControlProps.onFocus, event); }; const onBlur: JSX.EventHandlerUnion<HTMLInputElement, FocusEvent> = event => { setState("isFocused", false); callHandler(formControlProps.onBlur, event); }; const inputClasses = () => classNames(local.inputClass, visuallyHiddenStyles()); const stateAccessor = () => state; const context: CheckboxPrimitiveContextValue = { state, }; return ( <CheckboxPrimitiveContext.Provider value={context}> <hope.label for={state.id} data-group data-indeterminate={state["data-indeterminate"]} data-focus={state["data-focus"]} data-checked={state["data-checked"]} data-required={state["data-required"]} data-disabled={state["data-disabled"]} data-invalid={state["data-invalid"]} data-readonly={state["data-readonly"]} {...others} > <input type="checkbox" class={inputClasses()} ref={local.ref} tabIndex={local.tabIndex} value={state.value} id={state.id} name={state.name} checked={state.checked} required={state.required} disabled={state.disabled} readOnly={state.readOnly} onChange={onChange} onFocus={onFocus} onBlur={onBlur} aria-required={state["aria-required"]} aria-disabled={state["aria-disabled"]} aria-invalid={state["aria-invalid"]} aria-readonly={state["aria-readonly"]} aria-label={state["aria-label"]} aria-labelledby={state["aria-labelledby"]} aria-describedby={state["aria-describedby"]} /> <Show when={isFunction(local.children)} fallback={local.children as JSX.Element}> {(local.children as CheckboxPrimitiveChildrenRenderProp)?.({ state: stateAccessor })} </Show> </hope.label> </CheckboxPrimitiveContext.Provider> ); } /* ------------------------------------------------------------------------------------------------- * Context * -----------------------------------------------------------------------------------------------*/ interface CheckboxPrimitiveContextValue { state: CheckboxPrimitiveState; } const CheckboxPrimitiveContext = createContext<CheckboxPrimitiveContextValue>(); export function useCheckboxPrimitiveContext() { const context = useContext(CheckboxPrimitiveContext); if (!context) { throw new Error( "[Hope UI]: useCheckboxPrimitiveContext must be used within a `<CheckboxPrimitive />` component" ); } return context; }
the_stack
import { createBoardInfo } from "./boardinfobase"; import { IBoard } from "../boards"; import { hvqfs } from "../fs/hvqfs"; import { strings } from "../fs/strings"; import { arrayToArrayBuffer } from "../utils/arrays"; import { scenes } from "../fs/scenes"; import { toPack } from "../utils/img/ImgPack"; import { mainfs } from "../fs/mainfs"; // DK's Jungle Adventure - (U) ROM const MP1_USA_DK = createBoardInfo("MP1_USA_DK", { name: "DK's Jungle Adventure", canOverwrite: true, boardDefFile: 69, bgDir: 0, pauseBgDir: 4, sceneIndex: 0x36, // 54 mainfsEventFile: [10, 422], mainfsBoardFile: [10, 423], koopaSpaceInst: 0xD54, // 0x002425F4, 0x800F7330 bowserSpaceInst: 0xCB8, // 0x00242558 boosLoopFnOffset: 0x11D8, // 0x00242A78 boosReadbackFnOffset: 0x10D0, // 0x00242970 starSpaceArrOffset: 0x3320, // 0x00244BC0 starSpaceCount: 7, toadSpaceArrOffset: [0x3330, 0x3348], // [0x00244BD0, 0x00244BE8] audioIndexOffset: 0xBBE, // 0x0024245E str: { boardSelect: 652, koopaIntro: 571, starComments: [286, 287, 288, 289, 290, 291, 292], }, img: { boardSelectImg: 17, //gamemasterplc: overwrite ROM offset 0x25FA08 with 0x006B0226 to hide the comic sans board logo far off the bottom of the screen pauseLogoImg: 276, introLogoImg: [356, 357], introLogoImgDimens: [272, 112], titleScreenImg: 385, }, onLoad: function(board: IBoard) { board.otherbg.largescene = hvqfs.readBackground(MP1_USA_DK.bgDir + 1).src; board.otherbg.conversation = hvqfs.readBackground(MP1_USA_DK.bgDir + 2).src; board.otherbg.splashscreen = hvqfs.readBackground(MP1_USA_DK.bgDir + 6).src; }, onAfterOverwrite: function() { // Remove the "box" from the game start scenery. const introSceneView = scenes.getDataView(98); introSceneView.setUint32(0x7098, 0xC57A0000); // 0x2A9598 // Some random float to get it away introSceneView.setUint32(0x709C, 0); // 0x2A959C introSceneView.setUint32(0x70A0, 0); // 0x2A95A0 // Make Bowser's event text a bit more generic. let bytes: number[] = []; bytes = bytes.concat(strings._strToBytes("You're looking for Stars?\nHow about this instead...")); bytes.push(0xFF); // PAUSE bytes.push(0x00); // Null byte let strBuffer = arrayToArrayBuffer(bytes); strings.write(396, strBuffer); strings.write(399, strBuffer); strings.write(402, strBuffer); } }); // spaceEventTables: [ // { upper: 0xBD0, lower: 0xBD8 }, // 0x800F71B0, 0x800F71B8 // { upper: 0xBEC, lower: 0xBF4 }, // 0x800F71CC, 0x800F71D4 // { upper: 0xC08, lower: 0xC10 }, // 0x800F71E8, 0x800F71F0 // { upper: 0xC24, lower: 0xC2C }, // 0x800F7204, 0x800F720C // // tables: 0x800FA0CC // ]; // Peach's Birthday Cake - (U) ROM const MP1_USA_PEACH = createBoardInfo("MP1_USA_PEACH", { name: "Peach's Birthday Cake", canOverwrite: true, boardDefFile: 70, bgDir: 7, pauseBgDir: 14, str: { boardSelect: 653, koopaIntro: 572, }, img: { boardSelectImg: 20, pauseLogoImg: 277, introLogoImg: [359], introLogoImgDimens: [284, 126], titleScreenImg: 382, }, sceneIndex: 0x37, // 55 mainfsEventFile: [10, 424], mainfsBoardFile: [10, 425], eventASMStart: 0x00, // spaceEventsStartAddr: 0x000F7C70 // spaceEventsStartOffset: 0x00246C50 // spaceEventsEndOffset: 0x00246D10 koopaSpaceInst: 0x7C0, // 0x00245D80 bowserSpaceInst: 0x988, // // 0x00245F48 goombaSpaceInst: 0x900, // 0x00245EC0 onLoad: function(board: IBoard) { board.otherbg.largescene = hvqfs.readBackground(MP1_USA_PEACH.bgDir + 1).src; board.otherbg.conversation = hvqfs.readBackground(MP1_USA_PEACH.bgDir + 2).src; board.otherbg.splashscreen = hvqfs.readBackground(MP1_USA_PEACH.bgDir + 10).src; }, onAfterOverwrite: function(board: IBoard) { // Text banner that appears over the logo const oldPack = mainfs.get(10, 360); const imgInfoArr = [{ src: new ArrayBuffer(250 * 50 * 4), width: 250, height: 50, bpp: 32 }]; const newPack = toPack(imgInfoArr, 16, 0, oldPack); mainfs.write(10, 360, newPack); // TODO: There's some cake graphics in the end cutscenes that could be wiped. } }); // Yoshi's Tropical Island - (U) ROM const MP1_USA_YOSHI = createBoardInfo("MP1_USA_YOSHI", { name: "Yoshi's Tropical Island", canOverwrite: true, boardDefFile: 71, bgDir: 18, pauseBgDir: 25, str: { boardSelect: 654, koopaIntro: 573, }, img: { boardSelectImg: 18, pauseLogoImg: 278, introLogoImg: [362], introLogoImgDimens: [270, 120], titleScreenImg: 383, }, sceneIndex: 0x38, // 56 mainfsEventFile: [10, 426], mainfsBoardFile: [10, 427], // spaceEventsStartAddr: 0x000F861C; // spaceEventsStartOffset: 0x00248E2C; // spaceEventsEndOffset: 0x00248EE4; onLoad: function(board: IBoard) { board.otherbg.largescene = hvqfs.readBackground(MP1_USA_YOSHI.bgDir + 1).src; board.otherbg.conversation = hvqfs.readBackground(MP1_USA_YOSHI.bgDir + 2).src; board.otherbg.splashscreen = hvqfs.readBackground(MP1_USA_YOSHI.bgDir + 8).src; }, onAfterOverwrite: function(board: IBoard) { // Text banner that appears over the logo const oldPack = mainfs.get(10, 363); const imgInfoArr = [{ src: new ArrayBuffer(208 * 40 * 4), width: 208, height: 40, bpp: 32 }]; const newPack = toPack(imgInfoArr, 16, 0, oldPack); mainfs.write(10, 363, newPack); // TODO: Yoshis and whirlpools in the intro board showing // TODO: Koopa Troopa rides a shell into the intro } }); // Wario's Battle Canyon = (U) ROM const MP1_USA_WARIO = createBoardInfo("MP1_USA_WARIO", { name: "Wario's Battle Canyon", canOverwrite: true, boardDefFile: 72, bgDir: 27, pauseBgDir: 36, str: { boardSelect: 655, koopaIntro: 574, }, img: { boardSelectImg: 19, pauseLogoImg: 279, introLogoImg: [365], introLogoImgDimens: [290, 114], titleScreenImg: 384, }, sceneIndex: 0x39, // 57 mainfsEventFile: [10, 428], mainfsBoardFile: [10, 429], // spaceEventsStartAddr: 0x000F99C4, // spaceEventsStartOffset: 0x0024C2E4, // spaceEventsEndOffset: 0x0024C38C, koopaSpaceInst: 0xED0, // 0x00249DD0, bowserSpaceInst: 0xDA8, // 0x00249CA8, boosLoopFnOffset: 0x119C, // 0x0024A09C, boosReadbackFnOffset: 0x1094, // 0x00249F94, starSpaceArrOffset: 0x3240, // 0x0024C140, starSpaceCount: 7, toadSpaceArrOffset: [0x3250, 0x3270], // [0x0024C150, 0x0024C170] onLoad: function(board: IBoard) { board.otherbg.largescene = hvqfs.readBackground(MP1_USA_WARIO.bgDir + 1).src; board.otherbg.conversation = hvqfs.readBackground(MP1_USA_WARIO.bgDir + 2).src; board.otherbg.splashscreen = hvqfs.readBackground(MP1_USA_WARIO.bgDir + 11).src; }, onAfterOverwrite: function(board: IBoard) { // Text banner that appears over the logo const oldPack = mainfs.get(10, 366); const imgInfoArr = [{ src: new ArrayBuffer(280 * 76 * 4), width: 280, height: 76, bpp: 32 }]; const newPack = toPack(imgInfoArr, 16, 0, oldPack); mainfs.write(10, 366, newPack); } }); // Luigi's Engine Room - (U) ROM const MP1_USA_LUIGI = createBoardInfo("MP1_USA_LUIGI"); MP1_USA_LUIGI.name = "Luigi's Engine Room"; MP1_USA_LUIGI.boardDefFile = 73; MP1_USA_LUIGI.bgDir = 39; MP1_USA_LUIGI.str = { boardSelect: 656, koopaIntro: 575, }; MP1_USA_LUIGI.img = { boardSelectImg: 21, pauseLogoImg: 280, introLogoImg: [368], introLogoImgDimens: [276, 128], titleScreenImg: 381, }; MP1_USA_LUIGI.sceneIndex = 0x3A; // 58 MP1_USA_LUIGI.eventASMStart = 0x00; // MP1_USA_LUIGI.spaceEventsStartAddr = 0x000F9B90; // MP1_USA_LUIGI.spaceEventsStartOffset = 0x0024F940; // MP1_USA_LUIGI.spaceEventsEndOffset = 0x0024FA70; MP1_USA_LUIGI.starSpaceArrOffset = 0x2F60; // 0x0024F2F0; MP1_USA_LUIGI.starSpaceCount = 7; MP1_USA_LUIGI.toadSpaceArrOffset = [0x2F70, 0x2FF4]; // [0x0024F300, 0x0024F384]; // Mario's Rainbow Castle - (U) ROM const MP1_USA_MARIO = createBoardInfo("MP1_USA_MARIO"); MP1_USA_MARIO.name = "Mario's Rainbow Castle"; MP1_USA_MARIO.boardDefFile = 74; MP1_USA_MARIO.bgDir = 47; MP1_USA_MARIO.str = { boardSelect: 657, koopaIntro: 576, }; MP1_USA_MARIO.img = { boardSelectImg: 22, pauseLogoImg: 281, introLogoImg: [371], introLogoImgDimens: [270, 96], titleScreenImg: 380, }; MP1_USA_MARIO.sceneIndex = 0x3B; // 59 MP1_USA_MARIO.eventASMStart = 0x00; // MP1_USA_MARIO.spaceEventsStartAddr = 0x000F8390; // MP1_USA_MARIO.spaceEventsStartOffset = 0x00251830; // MP1_USA_MARIO.spaceEventsEndOffset = 0x002518D0; // Bowser's Magma Mountain - (U) ROM const MP1_USA_BOWSER = createBoardInfo("MP1_USA_BOWSER"); MP1_USA_BOWSER.name = "Bowser's Magma Mountain"; MP1_USA_BOWSER.boardDefFile = 75; MP1_USA_BOWSER.bgDir = 56; MP1_USA_BOWSER.str = { boardSelect: 658, koopaIntro: 577, }; MP1_USA_BOWSER.img = { boardSelectImg: 23, pauseLogoImg: 282, introLogoImg: [374], introLogoImgDimens: [270, 106], }; MP1_USA_BOWSER.sceneIndex = 0x3C; // 60 MP1_USA_BOWSER.eventASMStart = 0x00; // MP1_USA_BOWSER.spaceEventsStartAddr = 0x000F9080; // MP1_USA_BOWSER.spaceEventsStartOffset = 0x00254370; // MP1_USA_BOWSER.spaceEventsEndOffset = 0x00254450; MP1_USA_BOWSER.starSpaceArrOffset = 0x2298; // 0x00253B68; MP1_USA_BOWSER.starSpaceCount = 7; MP1_USA_BOWSER.toadSpaceArrOffset = [0x22A8, 0x22C8]; // [0x00253B78, 0x00253B98]; // Eternal Star - (U) ROM const MP1_USA_ETERNALSTAR = createBoardInfo("MP1_USA_ETERNALSTAR"); MP1_USA_ETERNALSTAR.name = "Eternal Star"; MP1_USA_ETERNALSTAR.boardDefFile = 76; MP1_USA_ETERNALSTAR.bgDir = 68; MP1_USA_ETERNALSTAR.str = { boardSelect: [659, 660], koopaIntro: 578, }; MP1_USA_ETERNALSTAR.img = { boardSelectImg: 24, pauseLogoImg: 283, introLogoImg: [378], //introLogoImgDimens: [276, 92], // The text 377 //introLogoImgDimens: [252, 128], // The star 378 }; MP1_USA_ETERNALSTAR.sceneIndex = 0x3D; // 61 MP1_USA_ETERNALSTAR.eventASMStart = 0x00; // MP1_USA_ETERNALSTAR.spaceEventsStartAddr = 0x000F905C; // MP1_USA_ETERNALSTAR.spaceEventsStartOffset = 0x00256ECC; // MP1_USA_ETERNALSTAR.spaceEventsEndOffset = 0x00256FF0; MP1_USA_ETERNALSTAR.bowserSpaceInst = 0xDDC; // 0x0025522C; MP1_USA_ETERNALSTAR.starSpaceArrOffset = 0x25F0; // 0x00256A40; MP1_USA_ETERNALSTAR.starSpaceCount = 7; MP1_USA_ETERNALSTAR.toadSpaceArrOffset = 0x2600; // 0x00256A50; // Training - (U) ROM const MP1_USA_TRAINING = createBoardInfo("MP1_USA_TRAINING"); MP1_USA_TRAINING.name = "Training"; MP1_USA_TRAINING.boardDefFile = 77; MP1_USA_TRAINING.bgDir = 77; MP1_USA_TRAINING.str = {}; MP1_USA_TRAINING.img = {}; MP1_USA_TRAINING.sceneIndex = 0x3E; // 62 MP1_USA_TRAINING.eventASMStart = 0x00; // MP1_USA_TRAINING.spaceEventsStartAddr = 0x000F87A8; // MP1_USA_TRAINING.spaceEventsStartOffset = 0x002591B8; // MP1_USA_TRAINING.spaceEventsEndOffset = 0x002591E8; MP1_USA_TRAINING.bowserSpaceInst = 0x32C; // 0x0025731C; MP1_USA_TRAINING.toadSpaceInst = 0x16C; // 0x0025715C; MP1_USA_TRAINING.koopaSpaceInst = 0x1F4; // 0x002571E4; MP1_USA_TRAINING.booSpaceInst = 0x2A4; // 0x00257294; // Mini-Game Stadium - (U) ROM const MP1_USA_STADIUM = createBoardInfo("MP1_USA_STADIUM"); MP1_USA_STADIUM.name = "Mini-Game Stadium"; MP1_USA_STADIUM.boardDefFile = 83; MP1_USA_STADIUM.bgDir = 99; MP1_USA_STADIUM.str = {}; MP1_USA_STADIUM.img = {}; //MP1_USA_STADIUM.sceneIndex = 0x3F; // 63 // Mini-Game Island - (U) ROM const MP1_USA_ISLAND = createBoardInfo("MP1_USA_ISLAND"); MP1_USA_ISLAND.name = "Mini-Game Island"; MP1_USA_ISLAND.boardDefFile = 78; MP1_USA_ISLAND.bgDir = 79; MP1_USA_ISLAND.str = {}; MP1_USA_ISLAND.img = {}; MP1_USA_ISLAND.sceneIndex = 0x72; // 114 MP1_USA_ISLAND.eventASMStart = 0x00; // MP1_USA_ISLAND.spaceEventsStartAddr = 0x000F8448; // MP1_USA_ISLAND.spaceEventsStartOffset = 0x002F8EE8; // MP1_USA_ISLAND.spaceEventsEndOffset = 0x002F9040; export function getBoardInfos() { return [ MP1_USA_DK, MP1_USA_PEACH, MP1_USA_YOSHI, MP1_USA_WARIO, MP1_USA_LUIGI, MP1_USA_MARIO, MP1_USA_BOWSER, MP1_USA_ETERNALSTAR, MP1_USA_TRAINING, MP1_USA_ISLAND, MP1_USA_STADIUM, ]; }
the_stack
import { statuses } from '@tanker/core'; import type { b64string, Tanker } from '@tanker/core'; import { getPublicIdentity } from '@tanker/identity'; import { expect, uuid } from '@tanker/test-utils'; import { expectDecrypt } from './helpers'; import type { TestArgs, AppHelper } from './helpers'; import type { AppProvisionalUser } from './helpers/AppHelper'; const retry = async <T>(operation: () => Promise<T>, nbTries: number, ...expectedErrors: string[]): Promise<T> => { for (let index = 0; index < nbTries; index++) { try { return await operation(); } catch (e) { if (expectedErrors.length > 0) { expect((e as Error).toString()).to.contain.oneOf(expectedErrors); } } } throw new Error(`operation did not succeed within ${nbTries} tries`); }; export const generateConcurrencyTests = (args: TestArgs) => { const makeTanker = (b64AppId?: b64string) => { const tanker = args.makeTanker(b64AppId); // eslint-disable-next-line no-underscore-dangle tanker._clientOptions.sdkInfo.type = `${tanker._clientOptions.sdkInfo.type}-concurrency`; return tanker; }; describe('concurrent Identity usage on unique device', () => { const tabCount = 3; let appHelper: AppHelper; let bobIdentity: b64string; let bobPublicIdentity: b64string; let aliceIdentity: b64string; let aliceLaptop: Tanker; let alicePublicIdentity: b64string; let firstTab: Tanker; let otherTabs: Array<Tanker> = []; let bobSessions: Array<Tanker> = []; before(async () => { ({ appHelper } = args); aliceIdentity = await appHelper.generateIdentity(uuid.v4()); alicePublicIdentity = await getPublicIdentity(aliceIdentity); aliceLaptop = makeTanker(); await aliceLaptop.start(aliceIdentity); aliceLaptop.registerIdentity({ passphrase: 'password' }); }); beforeEach(async () => { const bobId = uuid.v4(); bobIdentity = await appHelper.generateIdentity(bobId); bobPublicIdentity = await getPublicIdentity(bobIdentity); firstTab = makeTanker(); for (let index = 1; index < tabCount; index++) { otherTabs.push(makeTanker()); } bobSessions.push(firstTab, ...otherTabs); }); afterEach(async () => { await Promise.all(bobSessions.map((session) => session.stop())); bobSessions = []; otherTabs = []; }); after(async () => { await aliceLaptop.stop(); }); it('starts without error', async () => { await expect(Promise.all([ firstTab.start(bobIdentity), ...otherTabs.map((tanker) => tanker.start(bobIdentity)), ]), 'failed to start both sessions').be.fulfilled; }); it('registers only one of the sessions, others should restart', async () => { await firstTab.start(bobIdentity); await Promise.all(otherTabs.map((tanker) => tanker.start(bobIdentity))); let nbRegisteredSessions = 0; // every sessions will try to register but only one will succeed await expect(Promise.all( bobSessions.map(async (session) => { try { await session.registerIdentity({ passphrase: 'password' }); nbRegisteredSessions += 1; } catch (error) { expect((error as Error).message).to.contain('user_already_exists'); expect(session.status).to.equal(statuses.STOPPED); // the dead session should restart. await expect(session.start(bobIdentity)).to.be.fulfilled; } }), ), 'failed to register or restart sessions').be.fulfilled; expect(nbRegisteredSessions, 'Only one session should be registered').to.equal(1); }); it('reaches READY after verifying the restarted sessions', async () => { await firstTab.start(bobIdentity); await Promise.all(otherTabs.map((tanker) => tanker.start(bobIdentity))); await firstTab.registerIdentity({ passphrase: 'password' }); await Promise.all( otherTabs.map(tanker => expect( tanker.registerIdentity({ passphrase: 'password' }), ).to.be.rejectedWith('user_already_exists')), ); await expect(Promise.all( bobSessions.map(async (session) => { if (session.status === statuses.READY) return ''; return retry( async () => { await session.start(bobIdentity); return session.verifyIdentity({ passphrase: 'password' }); }, otherTabs.length, 'conflict with a concurrent operation', ); }), ), 'failed to verify restarted sessions').to.be.fulfilled; for (const session of bobSessions) { expect(session.status).to.equal(statuses.READY); } }); describe('once Tanker are started', () => { beforeEach(async () => { await firstTab.start(bobIdentity); await firstTab.registerIdentity({ passphrase: 'password' }); for (const tanker of otherTabs) { await tanker.start(bobIdentity); await tanker.verifyIdentity({ passphrase: 'password' }); } }); it('decrypt concurrently', async () => { const clearData = 'a beautiful word'; const encryptedData = await aliceLaptop.encrypt(clearData, { shareWithUsers: [bobPublicIdentity] }); const decryptedDataArray = await expect(Promise.all( bobSessions.map((session) => session.decrypt(encryptedData)), ), 'failed to decrypt from both sessions').to.be.fulfilled; for (const decryptedData of decryptedDataArray) { expect(decryptedData).to.equal(clearData); } }); it('decrypt resource shared through group concurrently', async () => { const clearData = 'a beautiful word'; const groupID = await aliceLaptop.createGroup([bobPublicIdentity]); const encryptedData = await aliceLaptop.encrypt(clearData, { shareWithGroups: [groupID] }); const decryptedDataArray = await expect(Promise.all( bobSessions.map((session) => session.decrypt(encryptedData)), ), 'failed to decrypt from both sessions').to.be.fulfilled; for (const decryptedData of decryptedDataArray) { expect(decryptedData).to.equal(clearData); } }); it('encrypt concurrently', async () => { const clearData = 'an unexpected response'; const encryptedDataArray = await expect(Promise.all( bobSessions.map((session) => session.encrypt(clearData, { shareWithUsers: [alicePublicIdentity] })), ), 'failed to encrypt from both sessions').to.be.fulfilled as Array<Uint8Array>; await Promise.all( encryptedDataArray.map((encryptedData) => expectDecrypt([aliceLaptop], clearData, encryptedData)), ); }); it('share concurrently', async () => { const clearData = 'an unexpected response'; const encryptedData = await bobSessions[0]!.encrypt(clearData); const resourceID = await bobSessions[0]!.getResourceId(encryptedData); await expect(Promise.all( bobSessions.map((session) => session.share([resourceID], { shareWithUsers: [alicePublicIdentity] })), ), 'failed to share from both sessions').to.be.fulfilled; await expectDecrypt([aliceLaptop], clearData, encryptedData); }); describe('handling group', () => { let clearData: string; let encryptedData: Uint8Array; let resourceID: b64string; beforeEach(async () => { clearData = 'whining to the group'; encryptedData = await bobSessions[0]!.encrypt(clearData); resourceID = await bobSessions[0]!.getResourceId(encryptedData); }); it('create group concurrently', async () => { const groups = await expect(Promise.all( bobSessions.map(session => session.createGroup([alicePublicIdentity])), ), 'failed to createGroup from both sessions').to.be.fulfilled as Array<b64string>; await Promise.all( groups.map((groupID, index) => bobSessions[index]!.share([resourceID], { shareWithGroups: [groupID] })), ); await expectDecrypt([aliceLaptop], clearData, encryptedData); }); it('add member to a group concurrently', async () => { const groupID = await bobSessions[0]!.createGroup([bobPublicIdentity]); await bobSessions[0]!.share([resourceID], { shareWithGroups: [groupID] }); await expect(Promise.all( bobSessions.map(session => retry( () => session.updateGroupMembers(groupID, { usersToAdd: [alicePublicIdentity] }), bobSessions.length, 'Invalid user group addition block', // verify failed: previous operation processed before verif 'There was a conflict with a concurrent operation', // DB upsert failed: previous operation not processed before verif )), ), 'failed to updateGroupMember from both sessions').to.be.fulfilled; await expectDecrypt([aliceLaptop], clearData, encryptedData); }); }); describe('handling provisional identities', () => { let provisionalIdentity: AppProvisionalUser; let clearData: string; let encryptedData: Uint8Array; beforeEach(async () => { provisionalIdentity = await appHelper.generateEmailProvisionalIdentity(); clearData = 'throwing a bottle in the sea'; encryptedData = await aliceLaptop.encrypt(clearData, { shareWithUsers: [provisionalIdentity.publicIdentity] }); }); it('attach using verification code', async () => { await Promise.all( bobSessions.map(session => appHelper.attachVerifyEmailProvisionalIdentity(session, provisionalIdentity) .catch((error) => expect(error.message).to.contain.oneOf([ 'invalid_verification_code', 'verification_code_not_found', 'provisional_identity_already_attached', ]))), ); // ensure the second tab can attach after a retry await expect(Promise.all( bobSessions.map(session => session.attachProvisionalIdentity(provisionalIdentity.identity)), )).to.be.fulfilled; await expectDecrypt(bobSessions, clearData, encryptedData); }); it('attach using verification code using the fast path', async () => { const verificationCode = await appHelper.getEmailVerificationCode(provisionalIdentity.value); await bobSessions[0]!.setVerificationMethod({ email: provisionalIdentity.value, verificationCode }); await Promise.all( bobSessions.map(session => session.attachProvisionalIdentity(provisionalIdentity.identity) .catch(error => expect(error.message).to.contain( 'provisional_identity_already_attached', ))), ); }); }); }); }); };
the_stack
import { BuiltinTypes, CORE_ANNOTATIONS, ElemID, ObjectType, createRestriction, ListType, createRefToElmWithValue, } from '@salto-io/adapter-api' import * as constants from '../constants' export const savedsearchInnerTypes: ObjectType[] = [] const savedSearchElemID = new ElemID(constants.NETSUITE, 'savedsearch') export const savedSearchDependenciesElemID = new ElemID(constants.NETSUITE, 'savedsearch_dependencies') const savedSearchFilterRecordElemID = new ElemID(constants.NETSUITE, 'savedsearch_filterRecord') const savedSearchAvailableFilterElemID = new ElemID(constants.NETSUITE, 'savedsearch_availableFilter') const savedSearchReturnFieldElemID = new ElemID(constants.NETSUITE, 'savedsearch_returnField') const savedSearchSortColumnsElemID = new ElemID(constants.NETSUITE, 'savedsearch_sortColumns') const savedSearchAlertRecipientsElemID = new ElemID(constants.NETSUITE, 'savedsearch_alertRecipients') const savedSearchFilterElemID = new ElemID(constants.NETSUITE, 'savedsearch_filter') const savedSearchAudienceElemID = new ElemID(constants.NETSUITE, 'savedsearch_audience') const savedSearchFilterRecord = new ObjectType({ elemID: savedSearchFilterRecordElemID, annotations: { }, fields: { KEY_ID: { refType: BuiltinTypes.NUMBER }, FIELD_VALUE: { refType: BuiltinTypes.STRING }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchFilter = new ObjectType({ elemID: savedSearchFilterElemID, annotations: { }, fields: { FLAG_DATE_TIME_SECOND: { refType: BuiltinTypes.BOOLEAN }, FLAG_FROM_AVAILABLE_FILTER: { refType: BuiltinTypes.BOOLEAN }, FLAG_NOT: { refType: BuiltinTypes.BOOLEAN }, FLAG_OR: { refType: BuiltinTypes.BOOLEAN }, FIELD_OR_CLAUSE_STATUS: { refType: BuiltinTypes.STRING }, FIELD_NUM_LEFT_PARENS: { refType: BuiltinTypes.NUMBER }, FIELD_NUM_RIGHT_PARENS: { refType: BuiltinTypes.NUMBER }, FIELD_FILTER_NAME: { refType: BuiltinTypes.STRING }, FIELD_FORMULA: { refType: BuiltinTypes.STRING }, FIELD_MODIFIER: { refType: BuiltinTypes.STRING }, FIELD_ATTRIBUTE: { refType: BuiltinTypes.STRING }, FIELD_TYPE: { refType: BuiltinTypes.STRING }, RECORDS: { refType: new ListType(savedSearchFilterRecord) }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchAvailableFilter = new ObjectType({ elemID: savedSearchAvailableFilterElemID, annotations: { }, fields: { SEQ_NUMBER: { refType: BuiltinTypes.NUMBER }, FIELD_NAME: { refType: BuiltinTypes.STRING }, FIELD_CUSTOM_LABEL: { refType: BuiltinTypes.STRING }, FLAG_FOOTER: { refType: BuiltinTypes.BOOLEAN }, FLAG_FOOTER_MULTI_SELECT: { refType: BuiltinTypes.BOOLEAN }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchReturnField = new ObjectType({ elemID: savedSearchReturnFieldElemID, annotations: { }, fields: { FIELD_ALIAS: { refType: BuiltinTypes.STRING }, FIELD_INDEX: { refType: BuiltinTypes.NUMBER }, FIELD_LABEL: { refType: BuiltinTypes.STRING }, FIELD_SUMMARY_LABEL: { refType: BuiltinTypes.STRING }, FIELD_SUMMARY_TYPE: { refType: BuiltinTypes.STRING }, FIELD_FUNCTION: { refType: BuiltinTypes.STRING }, FIELD_FORMULA: { refType: BuiltinTypes.STRING }, FIELD_FORMULA_ERROR: { refType: BuiltinTypes.BOOLEAN }, FIELD_ORDERED_BY_ALIAS: { refType: BuiltinTypes.STRING }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchSortColumns = new ObjectType({ elemID: savedSearchSortColumnsElemID, annotations: { }, fields: { KEY_FIELD: { refType: BuiltinTypes.STRING }, FILELD_ORDER: { refType: BuiltinTypes.NUMBER }, FLAG_DESCENDING: { refType: BuiltinTypes.BOOLEAN }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchAlertRecipients = new ObjectType({ elemID: savedSearchAlertRecipientsElemID, annotations: { }, fields: { FIELD_NAME: { refType: BuiltinTypes.STRING }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchAudience = new ObjectType({ elemID: savedSearchAudienceElemID, annotations: { }, fields: { FLAG_AUDIENCE_ALL_CUSTOMERS: { refType: BuiltinTypes.BOOLEAN }, FLAG_AUDIENCE_ALL_EMPLOYEES: { refType: BuiltinTypes.BOOLEAN }, FLAG_AUDIENCE_ALL_PARTNERS: { refType: BuiltinTypes.BOOLEAN }, FLAG_AUDIENCE_ALL_ROLES: { refType: BuiltinTypes.BOOLEAN }, FLAG_AUDIENCE_ALL_VENDORS: { refType: BuiltinTypes.BOOLEAN }, FIELD_AUDIENCE_ROLES: { refType: BuiltinTypes.STRING }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) const savedSearchDependencies = new ObjectType({ elemID: savedSearchDependenciesElemID, annotations: { }, fields: { dependency: { refType: createRefToElmWithValue(new ListType(BuiltinTypes.STRING)), annotations: { [CORE_ANNOTATIONS.REQUIRED]: true, }, }, /* Original description: This definition field is set by defining a saved search in NetSuite. For more information, see Defining a Saved Search. To redefine a saved search, you should customize it in NetSuite and then import the savedsearch object into the SDF project again. You must not manually edit saved searches in SDF. Modifications to the system-generated XML may result in validation and deployment failures. For more information, see Saved Searches as XML Definitions. This field only accepts references to any custom type. */ }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], }) savedsearchInnerTypes.push(savedSearchDependencies) savedsearchInnerTypes.push(savedSearchAlertRecipients) savedsearchInnerTypes.push(savedSearchSortColumns) savedsearchInnerTypes.push(savedSearchReturnField) savedsearchInnerTypes.push(savedSearchAvailableFilter) savedsearchInnerTypes.push(savedSearchFilterRecord) savedsearchInnerTypes.push(savedSearchFilter) savedsearchInnerTypes.push(savedSearchAudience) export const savedsearch = new ObjectType({ elemID: savedSearchElemID, annotations: { }, fields: { KEY_PACKAGE: { refType: BuiltinTypes.STRING }, KEY_SCRIPT_ID: { refType: BuiltinTypes.STRING }, FIELD_DEFAULT_NAME: { refType: BuiltinTypes.STRING }, FIELD_SEARCH_TYPE: { refType: BuiltinTypes.STRING }, FLAG_PUBLIC: { refType: BuiltinTypes.BOOLEAN }, FLAG_LIST: { refType: BuiltinTypes.BOOLEAN }, FLAG_PORTLET: { refType: BuiltinTypes.BOOLEAN }, FLAG_MACHINE: { refType: BuiltinTypes.BOOLEAN }, FLAG_REMINDER: { refType: BuiltinTypes.BOOLEAN }, FLAG_SHOW_LINK: { refType: BuiltinTypes.BOOLEAN }, FLAG_PREFERRED_LIST: { refType: BuiltinTypes.BOOLEAN }, FLAG_PREFERRED_PORTLET: { refType: BuiltinTypes.BOOLEAN }, FLAG_PREFERRED_MACHINE: { refType: BuiltinTypes.BOOLEAN }, FLAG_PREFERRED_FORM: { refType: BuiltinTypes.BOOLEAN }, FLAG_PREFERRED_RESULTS: { refType: BuiltinTypes.BOOLEAN }, KEY_MACHINE_TYPE: { refType: BuiltinTypes.STRING }, KEY_MACHINE: { refType: BuiltinTypes.STRING }, FLAG_VIEW_AS_REPORT: { refType: BuiltinTypes.BOOLEAN }, FLAG_VIEW_AS_GRAPH: { refType: BuiltinTypes.BOOLEAN }, FLAG_VIEW_AS_GRID: { refType: BuiltinTypes.BOOLEAN }, FLAG_UNRESTRICTED: { refType: BuiltinTypes.BOOLEAN }, MAX_ROWS: { refType: BuiltinTypes.NUMBER }, FLAG_DISABLE_DRILL_DOWN: { refType: BuiltinTypes.BOOLEAN }, FIELD_CURRENCY_RATE_TYPE: { refType: BuiltinTypes.STRING }, FLAG_HIDE_FILTER_DROPDOWNS: { refType: BuiltinTypes.BOOLEAN }, KEY_DEFAULT_TEXT_FIELD_FILTER: { refType: BuiltinTypes.STRING }, FLAG_AVAILABLE_AS_FEED: { refType: BuiltinTypes.BOOLEAN }, FLAG_GLOBAL_EDIT: { refType: BuiltinTypes.BOOLEAN }, FLAG_CSV: { refType: BuiltinTypes.BOOLEAN }, FLAG_EXCEL: { refType: BuiltinTypes.BOOLEAN }, FLAG_PDF: { refType: BuiltinTypes.BOOLEAN }, FIELD_EMAIL_FROM: { refType: BuiltinTypes.STRING }, FIELD_EMAIL_SUBJECT: { refType: BuiltinTypes.STRING }, FIELD_EMAIL_BODY: { refType: BuiltinTypes.STRING }, FIELD_EMAIL_COMMENT: { refType: BuiltinTypes.STRING }, FLAG_TRIGGERED_ALERT: { refType: BuiltinTypes.BOOLEAN }, FLAG_SCHEDULED_ALERT: { refType: BuiltinTypes.BOOLEAN }, FLAG_SCHEDULED_ALERT_SUMMARIES: { refType: BuiltinTypes.BOOLEAN }, FLAG_SEND_EMPTY_RESULTS: { refType: BuiltinTypes.BOOLEAN }, FLAG_ALERT_ALLOW_SUBSCRIBE: { refType: BuiltinTypes.BOOLEAN }, FLAG_ALERT_INCLUDE_VIEW_LINK: { refType: BuiltinTypes.BOOLEAN }, FLAG_HAS_TOTALS: { refType: BuiltinTypes.BOOLEAN }, FLAG_INCLUDE_PERIOD_END_TRANSACTIONS: { refType: BuiltinTypes.BOOLEAN }, FIELD_BULK_OP_CODE: { refType: BuiltinTypes.STRING }, FIELD_BULK_ENTRY_FORM_PARAMS: { refType: BuiltinTypes.STRING }, FLAG_BUILT_IN: { refType: BuiltinTypes.BOOLEAN }, FIELD_OPTIMIZER_HINT: { refType: BuiltinTypes.STRING }, FLAG_SEND_ON_UPDATE: { refType: BuiltinTypes.BOOLEAN }, FLAG_SHOW_AUDIT_TRAIL: { refType: BuiltinTypes.BOOLEAN }, KEY_AUDIENCE: { refType: BuiltinTypes.NUMBER }, scriptid: { refType: createRefToElmWithValue(BuiltinTypes.SERVICE_ID), annotations: { [CORE_ANNOTATIONS.REQUIRED]: true, [constants.IS_ATTRIBUTE]: true, [CORE_ANNOTATIONS.RESTRICTION]: createRestriction({ regex: '^customsearch[0-9a-z_]+' }), }, }, /* Original description: This attribute value can be up to 40 characters long. The default value is ‘customsearch’. */ definition: { refType: createRefToElmWithValue(BuiltinTypes.STRING), annotations: { [CORE_ANNOTATIONS.REQUIRED]: true, }, }, dependencies: { refType: createRefToElmWithValue(savedSearchDependencies), annotations: { }, }, search_filters: { refType: createRefToElmWithValue(new ListType(savedSearchFilter)), }, search_summary_filters: { refType: createRefToElmWithValue(new ListType(savedSearchFilter)), }, available_filters: { refType: createRefToElmWithValue(new ListType(savedSearchAvailableFilter)), }, return_fields: { refType: createRefToElmWithValue(new ListType(savedSearchReturnField)), }, detail_fields: { refType: createRefToElmWithValue(new ListType(savedSearchReturnField)), }, sort_columns: { refType: createRefToElmWithValue(savedSearchSortColumns), }, audience: { refType: createRefToElmWithValue(savedSearchAudience), }, alert_recipients: { refType: createRefToElmWithValue(new ListType(savedSearchAlertRecipients)), }, [constants.LAST_FETCH_TIME]: { refType: BuiltinTypes.STRING, annotations: { [CORE_ANNOTATIONS.HIDDEN_VALUE]: true }, }, }, path: [constants.NETSUITE, constants.TYPES_PATH, savedSearchElemID.name], })
the_stack
import { JsPsych, JsPsychPlugin, ParameterType, TrialType } from "jspsych"; const info = <const>{ name: "webgazer-validate", parameters: { /** Array of points in [x,y] coordinates */ validation_points: { type: ParameterType.INT, // TO DO: nested array, so different type? default: [ [10, 10], [10, 50], [10, 90], [50, 10], [50, 50], [50, 90], [90, 10], [90, 50], [90, 90], ], array: true, }, /** * Are the validation_points specified as percentages of screen width and height, or the distance in pixels from the center of the screen? * Options are 'percent' and 'center-offset-pixels' */ validation_point_coordinates: { type: ParameterType.SELECT, default: "percent", options: ["percent", "center-offset-pixels"], }, /** Tolerance around validation point in pixels */ roi_radius: { type: ParameterType.INT, default: 200, }, /** Whether or not to randomize the order of validation points */ randomize_validation_order: { type: ParameterType.BOOL, default: false, }, /** Delay before validating after showing a point */ time_to_saccade: { type: ParameterType.INT, default: 1000, }, /** Length of time to show each point */ validation_duration: { type: ParameterType.INT, default: 2000, }, /** Validation point size in pixels */ point_size: { type: ParameterType.INT, default: 20, }, /** If true, then validation data will be shown on the screen after validation is complete */ show_validation_data: { type: ParameterType.BOOL, default: false, }, }, }; type Info = typeof info; /** * **webgazer-validate** * * jsPsych plugin for measuring the accuracy and precision of eye gaze predictions. * Intended for use with the Webgazer eye-tracking extension, after the webcam has been initialized with the * `webgazer-init-camera` plugin and calibrated with the `webgazer-calibrate` plugin. * * @author Josh de Leeuw * @see {@link https://www.jspsych.org/plugins/jspsych-webgazer-validate/ webgazer-validate plugin} and * {@link https://www.jspsych.org/overview/eye-tracking/ eye-tracking overview} documentation on jspsych.org */ class WebgazerValidatePlugin implements JsPsychPlugin<Info> { static info = info; constructor(private jsPsych: JsPsych) {} trial(display_element: HTMLElement, trial: TrialType<Info>) { var trial_data = <any>{}; trial_data.raw_gaze = []; trial_data.percent_in_roi = []; trial_data.average_offset = []; trial_data.validation_points = null; var html = ` <div id='webgazer-validate-container' style='position: relative; width:100vw; height:100vh; overflow: hidden;'> </div>`; display_element.innerHTML = html; var wg_container = display_element.querySelector("#webgazer-validate-container"); var points_completed = -1; var val_points = null; var start = performance.now(); // function to end trial when it is time const end_trial = () => { this.jsPsych.extensions.webgazer.stopSampleInterval(); // kill any remaining setTimeout handlers this.jsPsych.pluginAPI.clearAllTimeouts(); // clear the display display_element.innerHTML = ""; // move on to the next trial this.jsPsych.finishTrial(trial_data); }; const validation_display = (pt) => { var pt_html = drawValidationPoint(pt[0], pt[1]); wg_container.innerHTML = pt_html; var pt_dom = wg_container.querySelector(".validation-point"); var br = pt_dom.getBoundingClientRect(); var x = br.left + br.width / 2; var y = br.top + br.height / 2; var pt_start_val = performance.now() + trial.time_to_saccade; var pt_finish = pt_start_val + trial.validation_duration; var pt_data = []; var cancelGazeUpdate = this.jsPsych.extensions["webgazer"].onGazeUpdate((prediction) => { if (performance.now() > pt_start_val) { pt_data.push({ x: prediction.x, y: prediction.y, dx: prediction.x - x, dy: prediction.y - y, t: Math.round(prediction.t - start), }); } }); requestAnimationFrame(function watch_dot() { if (performance.now() < pt_finish) { requestAnimationFrame(watch_dot); } else { trial_data.raw_gaze.push(pt_data); cancelGazeUpdate(); next_validation_point(); } }); }; const next_validation_point = () => { points_completed++; if (points_completed == val_points.length) { validation_done(); } else { var pt = val_points[points_completed]; validation_display(pt); } }; const validate = () => { if (trial.randomize_validation_order) { val_points = this.jsPsych.randomization.shuffle(trial.validation_points); } else { val_points = trial.validation_points; } trial_data.validation_points = val_points; points_completed = -1; //jsPsych.extensions['webgazer'].resume(); this.jsPsych.extensions.webgazer.startSampleInterval(); //jsPsych.extensions.webgazer.showPredictions(); next_validation_point(); }; const show_validation_data = () => { var html = ""; for (var i = 0; i < trial.validation_points.length; i++) { html += drawValidationPoint(trial.validation_points[i][0], trial.validation_points[i][1]); html += drawCircle( trial.validation_points[i][0], trial.validation_points[i][1], 0, 0, trial.roi_radius ); for (var j = 0; j < trial_data.raw_gaze[i].length; j++) { html += drawRawDataPoint( trial.validation_points[i][0], trial.validation_points[i][1], trial_data.raw_gaze[i][j].dx, trial_data.raw_gaze[i][j].dy ); } } html += '<button id="cont" style="position:absolute; top: 50%; left:calc(50% - 50px); width: 100px;" class="jspsych-btn">Continue</btn>'; wg_container.innerHTML = html; wg_container.querySelector("#cont").addEventListener("click", () => { this.jsPsych.extensions.webgazer.pause(); end_trial(); }); // turn on webgazer's loop this.jsPsych.extensions.webgazer.showPredictions(); this.jsPsych.extensions.webgazer.stopSampleInterval(); this.jsPsych.extensions.webgazer.resume(); }; const validation_done = () => { trial_data.samples_per_sec = calculateSampleRate(trial_data.raw_gaze).toFixed(2); for (var i = 0; i < trial.validation_points.length; i++) { trial_data.percent_in_roi[i] = calculatePercentInROI(trial_data.raw_gaze[i]); trial_data.average_offset[i] = calculateGazeCentroid(trial_data.raw_gaze[i]); } if (trial.show_validation_data) { show_validation_data(); } else { end_trial(); } }; validate(); // @ts-expect-error function drawValidationPoint(x, y) { if (trial.validation_point_coordinates == "percent") { return drawValidationPoint_PercentMode(x, y); } if (trial.validation_point_coordinates == "center-offset-pixels") { return drawValidationPoint_CenterOffsetMode(x, y); } } function drawValidationPoint_PercentMode(x, y) { return `<div class="validation-point" style="width:${trial.point_size}px; height:${trial.point_size}px; border-radius:${trial.point_size}px; border: 1px solid #000; background-color: #333; position: absolute; left:${x}%; top:${y}%;"></div>`; } function drawValidationPoint_CenterOffsetMode(x, y) { return `<div class="validation-point" style="width:${trial.point_size}px; height:${ trial.point_size }px; border-radius:${ trial.point_size }px; border: 1px solid #000; background-color: #333; position: absolute; left:calc(50% - ${ trial.point_size / 2 }px + ${x}px); top:calc(50% - ${trial.point_size / 2}px + ${y}px);"></div>`; } // @ts-expect-error function drawCircle(target_x, target_y, dx, dy, r) { if (trial.validation_point_coordinates == "percent") { return drawCircle_PercentMode(target_x, target_y, dx, dy, r); } if (trial.validation_point_coordinates == "center-offset-pixels") { return drawCircle_CenterOffsetMode(target_x, target_y, dx, dy, r); } } function drawCircle_PercentMode(target_x, target_y, dx, dy, r) { var html = ` <div class="validation-centroid" style="width:${r * 2}px; height:${ r * 2 }px; border: 2px dotted #ccc; border-radius: ${r}px; background-color: transparent; position: absolute; left:calc(${target_x}% + ${ dx - r }px); top:calc(${target_y}% + ${dy - r}px);"></div> `; return html; } function drawCircle_CenterOffsetMode(target_x, target_y, dx, dy, r) { var html = ` <div class="validation-centroid" style="width:${r * 2}px; height:${ r * 2 }px; border: 2px dotted #ccc; border-radius: ${r}px; background-color: transparent; position: absolute; left:calc(50% + ${target_x}px + ${ dx - r }px); top:calc(50% + ${target_y}px + ${dy - r}px);"></div> `; return html; } // @ts-expect-error function drawRawDataPoint(target_x, target_y, dx, dy) { if (trial.validation_point_coordinates == "percent") { return drawRawDataPoint_PercentMode(target_x, target_y, dx, dy); } if (trial.validation_point_coordinates == "center-offset-pixels") { return drawRawDataPoint_CenterOffsetMode(target_x, target_y, dx, dy); } } function drawRawDataPoint_PercentMode(target_x, target_y, dx, dy) { var color = Math.sqrt(dx * dx + dy * dy) <= trial.roi_radius ? "#afa" : "#faa"; return `<div class="raw-data-point" style="width:5px; height:5px; border-radius:5px; background-color: ${color}; opacity:0.8; position: absolute; left:calc(${target_x}% + ${ dx - 2 }px); top:calc(${target_y}% + ${dy - 2}px);"></div>`; } function drawRawDataPoint_CenterOffsetMode(target_x, target_y, dx, dy) { var color = Math.sqrt(dx * dx + dy * dy) <= trial.roi_radius ? "#afa" : "#faa"; return `<div class="raw-data-point" style="width:5px; height:5px; border-radius:5px; background-color: ${color}; opacity:0.8; position: absolute; left:calc(50% + ${target_x}px + ${ dx - 2 }px); top:calc(50% + ${target_y}px + ${dy - 2}px);"></div>`; } function median(arr) { var mid = Math.floor(arr.length / 2); var sorted_arr = arr.sort((a, b) => a - b); if (arr.length % 2 == 0) { return sorted_arr[mid - 1] + sorted_arr[mid] / 2; } else { return sorted_arr[mid]; } } function calculateGazeCentroid(gazeData) { var x_diff_m = gazeData.reduce((accumulator, currentValue, index) => { accumulator += currentValue.dx; if (index == gazeData.length - 1) { return accumulator / gazeData.length; } else { return accumulator; } }, 0); var y_diff_m = gazeData.reduce((accumulator, currentValue, index) => { accumulator += currentValue.dy; if (index == gazeData.length - 1) { return accumulator / gazeData.length; } else { return accumulator; } }, 0); var median_distance = median( gazeData.map((x) => Math.sqrt(Math.pow(x.dx - x_diff_m, 2) + Math.pow(x.dy - y_diff_m, 2))) ); return { x: x_diff_m, y: y_diff_m, r: median_distance, }; } function calculatePercentInROI(gazeData) { var distances = gazeData.map((p) => Math.sqrt(Math.pow(p.dx, 2) + Math.pow(p.dy, 2))); var sum_in_roi = distances.reduce((accumulator, currentValue) => { if (currentValue <= trial.roi_radius) { accumulator++; } return accumulator; }, 0); var percent = (sum_in_roi / gazeData.length) * 100; return percent; } function calculateSampleRate(gazeData) { var mean_diff = []; if (gazeData.length == 0) { return 0; } for (var i = 0; i < gazeData.length; i++) { if (gazeData[i].length > 1) { var t_diff = []; for (var j = 1; j < gazeData[i].length; j++) { t_diff.push(gazeData[i][j].t - gazeData[i][j - 1].t); } mean_diff.push(t_diff.reduce((a, b) => a + b, 0) / t_diff.length); } } if (mean_diff.length > 0) { return 1000 / (mean_diff.reduce((a, b) => a + b, 0) / mean_diff.length); } else { return null; } } } } export default WebgazerValidatePlugin;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Creates a table resource in a dataset for Google BigQuery. For more information see * [the official documentation](https://cloud.google.com/bigquery/docs/) and * [API](https://cloud.google.com/bigquery/docs/reference/rest/v2/tables). * * > **Note**: On newer versions of the provider, you must explicitly set `deletion_protection=false` * (and run `pulumi update` to write the field to state) in order to destroy an instance. * It is recommended to not set this field (or set it to true) until you're ready to destroy. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const defaultDataset = new gcp.bigquery.Dataset("defaultDataset", { * datasetId: "foo", * friendlyName: "test", * description: "This is a test description", * location: "EU", * defaultTableExpirationMs: 3600000, * labels: { * env: "default", * }, * }); * const defaultTable = new gcp.bigquery.Table("defaultTable", { * datasetId: defaultDataset.datasetId, * tableId: "bar", * timePartitioning: { * type: "DAY", * }, * labels: { * env: "default", * }, * schema: `[ * { * "name": "permalink", * "type": "STRING", * "mode": "NULLABLE", * "description": "The Permalink" * }, * { * "name": "state", * "type": "STRING", * "mode": "NULLABLE", * "description": "State where the head office is located" * } * ] * `, * }); * const sheet = new gcp.bigquery.Table("sheet", { * datasetId: defaultDataset.datasetId, * tableId: "sheet", * externalDataConfiguration: { * autodetect: true, * sourceFormat: "GOOGLE_SHEETS", * googleSheetsOptions: { * skipLeadingRows: 1, * }, * sourceUris: ["https://docs.google.com/spreadsheets/d/123456789012345"], * }, * }); * ``` * * ## Import * * BigQuery tables can be imported using the `project`, `dataset_id`, and `table_id`, e.g. * * ```sh * $ pulumi import gcp:bigquery/table:Table default gcp-project/foo/bar * ``` */ export class Table extends pulumi.CustomResource { /** * Get an existing Table 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?: TableState, opts?: pulumi.CustomResourceOptions): Table { return new Table(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:bigquery/table:Table'; /** * Returns true if the given object is an instance of Table. 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 Table { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Table.__pulumiType; } /** * Specifies column names to use for data clustering. * Up to four top-level columns are allowed, and should be specified in * descending priority order. */ public readonly clusterings!: pulumi.Output<string[] | undefined>; /** * The time when this table was created, in milliseconds since the epoch. */ public /*out*/ readonly creationTime!: pulumi.Output<number>; /** * The dataset ID to create the table in. * Changing this forces a new resource to be created. */ public readonly datasetId!: pulumi.Output<string>; /** * Whether or not to allow the provider to destroy the instance. Unless this field is set to false * in state, a `=destroy` or `=update` that would delete the instance will fail. */ public readonly deletionProtection!: pulumi.Output<boolean | undefined>; /** * The field description. */ public readonly description!: pulumi.Output<string | undefined>; /** * Specifies how the table should be encrypted. * If left blank, the table will be encrypted with a Google-managed key; that process * is transparent to the user. Structure is documented below. */ public readonly encryptionConfiguration!: pulumi.Output<outputs.bigquery.TableEncryptionConfiguration | undefined>; /** * A hash of the resource. */ public /*out*/ readonly etag!: pulumi.Output<string>; /** * The time when this table expires, in * milliseconds since the epoch. If not present, the table will persist * indefinitely. Expired tables will be deleted and their storage * reclaimed. */ public readonly expirationTime!: pulumi.Output<number>; /** * Describes the data format, * location, and other properties of a table stored outside of BigQuery. * By defining these properties, the data source can then be queried as * if it were a standard BigQuery table. Structure is documented below. */ public readonly externalDataConfiguration!: pulumi.Output<outputs.bigquery.TableExternalDataConfiguration | undefined>; /** * A descriptive name for the table. */ public readonly friendlyName!: pulumi.Output<string | undefined>; /** * A mapping of labels to assign to the resource. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The time when this table was last modified, in milliseconds since the epoch. */ public /*out*/ readonly lastModifiedTime!: pulumi.Output<number>; /** * The geographic location where the table resides. This value is inherited from the dataset. */ public /*out*/ readonly location!: pulumi.Output<string>; /** * If specified, configures this table as a materialized view. * Structure is documented below. */ public readonly materializedView!: pulumi.Output<outputs.bigquery.TableMaterializedView | undefined>; /** * The size of this table in bytes, excluding any data in the streaming buffer. */ public /*out*/ readonly numBytes!: pulumi.Output<number>; /** * The number of bytes in the table that are considered "long-term storage". */ public /*out*/ readonly numLongTermBytes!: pulumi.Output<number>; /** * The number of rows of data in this table, excluding any data in the streaming buffer. */ public /*out*/ readonly numRows!: pulumi.Output<number>; /** * The ID of the project in which the resource belongs. If it * is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * If specified, configures range-based * partitioning for this table. Structure is documented below. */ public readonly rangePartitioning!: pulumi.Output<outputs.bigquery.TableRangePartitioning | undefined>; /** * A JSON schema for the external table. Schema is required * for CSV and JSON formats if autodetect is not on. Schema is disallowed * for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and Parquet formats. * ~>**NOTE:** Because this field expects a JSON string, any changes to the * string will create a diff, even if the JSON itself hasn't changed. * Furthermore drift for this field cannot not be detected because BigQuery * only uses this schema to compute the effective schema for the table, therefore * any changes on the configured value will force the table to be recreated. * This schema is effectively only applied when creating a table from an external * datasource, after creation the computed schema will be stored in * `google_bigquery_table.schema` */ public readonly schema!: pulumi.Output<string>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * A unique ID for the resource. * Changing this forces a new resource to be created. */ public readonly tableId!: pulumi.Output<string>; /** * If specified, configures time-based * partitioning for this table. Structure is documented below. */ public readonly timePartitioning!: pulumi.Output<outputs.bigquery.TableTimePartitioning | undefined>; /** * The supported types are DAY, HOUR, MONTH, and YEAR, * which will generate one partition per day, hour, month, and year, respectively. */ public /*out*/ readonly type!: pulumi.Output<string>; /** * If specified, configures this table as a view. * Structure is documented below. */ public readonly view!: pulumi.Output<outputs.bigquery.TableView | undefined>; /** * Create a Table 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: TableArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: TableArgs | TableState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as TableState | undefined; inputs["clusterings"] = state ? state.clusterings : undefined; inputs["creationTime"] = state ? state.creationTime : undefined; inputs["datasetId"] = state ? state.datasetId : undefined; inputs["deletionProtection"] = state ? state.deletionProtection : undefined; inputs["description"] = state ? state.description : undefined; inputs["encryptionConfiguration"] = state ? state.encryptionConfiguration : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["expirationTime"] = state ? state.expirationTime : undefined; inputs["externalDataConfiguration"] = state ? state.externalDataConfiguration : undefined; inputs["friendlyName"] = state ? state.friendlyName : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["lastModifiedTime"] = state ? state.lastModifiedTime : undefined; inputs["location"] = state ? state.location : undefined; inputs["materializedView"] = state ? state.materializedView : undefined; inputs["numBytes"] = state ? state.numBytes : undefined; inputs["numLongTermBytes"] = state ? state.numLongTermBytes : undefined; inputs["numRows"] = state ? state.numRows : undefined; inputs["project"] = state ? state.project : undefined; inputs["rangePartitioning"] = state ? state.rangePartitioning : undefined; inputs["schema"] = state ? state.schema : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["tableId"] = state ? state.tableId : undefined; inputs["timePartitioning"] = state ? state.timePartitioning : undefined; inputs["type"] = state ? state.type : undefined; inputs["view"] = state ? state.view : undefined; } else { const args = argsOrState as TableArgs | undefined; if ((!args || args.datasetId === undefined) && !opts.urn) { throw new Error("Missing required property 'datasetId'"); } if ((!args || args.tableId === undefined) && !opts.urn) { throw new Error("Missing required property 'tableId'"); } inputs["clusterings"] = args ? args.clusterings : undefined; inputs["datasetId"] = args ? args.datasetId : undefined; inputs["deletionProtection"] = args ? args.deletionProtection : undefined; inputs["description"] = args ? args.description : undefined; inputs["encryptionConfiguration"] = args ? args.encryptionConfiguration : undefined; inputs["expirationTime"] = args ? args.expirationTime : undefined; inputs["externalDataConfiguration"] = args ? args.externalDataConfiguration : undefined; inputs["friendlyName"] = args ? args.friendlyName : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["materializedView"] = args ? args.materializedView : undefined; inputs["project"] = args ? args.project : undefined; inputs["rangePartitioning"] = args ? args.rangePartitioning : undefined; inputs["schema"] = args ? args.schema : undefined; inputs["tableId"] = args ? args.tableId : undefined; inputs["timePartitioning"] = args ? args.timePartitioning : undefined; inputs["view"] = args ? args.view : undefined; inputs["creationTime"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["lastModifiedTime"] = undefined /*out*/; inputs["location"] = undefined /*out*/; inputs["numBytes"] = undefined /*out*/; inputs["numLongTermBytes"] = undefined /*out*/; inputs["numRows"] = undefined /*out*/; inputs["selfLink"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Table.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Table resources. */ export interface TableState { /** * Specifies column names to use for data clustering. * Up to four top-level columns are allowed, and should be specified in * descending priority order. */ clusterings?: pulumi.Input<pulumi.Input<string>[]>; /** * The time when this table was created, in milliseconds since the epoch. */ creationTime?: pulumi.Input<number>; /** * The dataset ID to create the table in. * Changing this forces a new resource to be created. */ datasetId?: pulumi.Input<string>; /** * Whether or not to allow the provider to destroy the instance. Unless this field is set to false * in state, a `=destroy` or `=update` that would delete the instance will fail. */ deletionProtection?: pulumi.Input<boolean>; /** * The field description. */ description?: pulumi.Input<string>; /** * Specifies how the table should be encrypted. * If left blank, the table will be encrypted with a Google-managed key; that process * is transparent to the user. Structure is documented below. */ encryptionConfiguration?: pulumi.Input<inputs.bigquery.TableEncryptionConfiguration>; /** * A hash of the resource. */ etag?: pulumi.Input<string>; /** * The time when this table expires, in * milliseconds since the epoch. If not present, the table will persist * indefinitely. Expired tables will be deleted and their storage * reclaimed. */ expirationTime?: pulumi.Input<number>; /** * Describes the data format, * location, and other properties of a table stored outside of BigQuery. * By defining these properties, the data source can then be queried as * if it were a standard BigQuery table. Structure is documented below. */ externalDataConfiguration?: pulumi.Input<inputs.bigquery.TableExternalDataConfiguration>; /** * A descriptive name for the table. */ friendlyName?: pulumi.Input<string>; /** * A mapping of labels to assign to the resource. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The time when this table was last modified, in milliseconds since the epoch. */ lastModifiedTime?: pulumi.Input<number>; /** * The geographic location where the table resides. This value is inherited from the dataset. */ location?: pulumi.Input<string>; /** * If specified, configures this table as a materialized view. * Structure is documented below. */ materializedView?: pulumi.Input<inputs.bigquery.TableMaterializedView>; /** * The size of this table in bytes, excluding any data in the streaming buffer. */ numBytes?: pulumi.Input<number>; /** * The number of bytes in the table that are considered "long-term storage". */ numLongTermBytes?: pulumi.Input<number>; /** * The number of rows of data in this table, excluding any data in the streaming buffer. */ numRows?: pulumi.Input<number>; /** * The ID of the project in which the resource belongs. If it * is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * If specified, configures range-based * partitioning for this table. Structure is documented below. */ rangePartitioning?: pulumi.Input<inputs.bigquery.TableRangePartitioning>; /** * A JSON schema for the external table. Schema is required * for CSV and JSON formats if autodetect is not on. Schema is disallowed * for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and Parquet formats. * ~>**NOTE:** Because this field expects a JSON string, any changes to the * string will create a diff, even if the JSON itself hasn't changed. * Furthermore drift for this field cannot not be detected because BigQuery * only uses this schema to compute the effective schema for the table, therefore * any changes on the configured value will force the table to be recreated. * This schema is effectively only applied when creating a table from an external * datasource, after creation the computed schema will be stored in * `google_bigquery_table.schema` */ schema?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; /** * A unique ID for the resource. * Changing this forces a new resource to be created. */ tableId?: pulumi.Input<string>; /** * If specified, configures time-based * partitioning for this table. Structure is documented below. */ timePartitioning?: pulumi.Input<inputs.bigquery.TableTimePartitioning>; /** * The supported types are DAY, HOUR, MONTH, and YEAR, * which will generate one partition per day, hour, month, and year, respectively. */ type?: pulumi.Input<string>; /** * If specified, configures this table as a view. * Structure is documented below. */ view?: pulumi.Input<inputs.bigquery.TableView>; } /** * The set of arguments for constructing a Table resource. */ export interface TableArgs { /** * Specifies column names to use for data clustering. * Up to four top-level columns are allowed, and should be specified in * descending priority order. */ clusterings?: pulumi.Input<pulumi.Input<string>[]>; /** * The dataset ID to create the table in. * Changing this forces a new resource to be created. */ datasetId: pulumi.Input<string>; /** * Whether or not to allow the provider to destroy the instance. Unless this field is set to false * in state, a `=destroy` or `=update` that would delete the instance will fail. */ deletionProtection?: pulumi.Input<boolean>; /** * The field description. */ description?: pulumi.Input<string>; /** * Specifies how the table should be encrypted. * If left blank, the table will be encrypted with a Google-managed key; that process * is transparent to the user. Structure is documented below. */ encryptionConfiguration?: pulumi.Input<inputs.bigquery.TableEncryptionConfiguration>; /** * The time when this table expires, in * milliseconds since the epoch. If not present, the table will persist * indefinitely. Expired tables will be deleted and their storage * reclaimed. */ expirationTime?: pulumi.Input<number>; /** * Describes the data format, * location, and other properties of a table stored outside of BigQuery. * By defining these properties, the data source can then be queried as * if it were a standard BigQuery table. Structure is documented below. */ externalDataConfiguration?: pulumi.Input<inputs.bigquery.TableExternalDataConfiguration>; /** * A descriptive name for the table. */ friendlyName?: pulumi.Input<string>; /** * A mapping of labels to assign to the resource. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * If specified, configures this table as a materialized view. * Structure is documented below. */ materializedView?: pulumi.Input<inputs.bigquery.TableMaterializedView>; /** * The ID of the project in which the resource belongs. If it * is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * If specified, configures range-based * partitioning for this table. Structure is documented below. */ rangePartitioning?: pulumi.Input<inputs.bigquery.TableRangePartitioning>; /** * A JSON schema for the external table. Schema is required * for CSV and JSON formats if autodetect is not on. Schema is disallowed * for Google Cloud Bigtable, Cloud Datastore backups, Avro, ORC and Parquet formats. * ~>**NOTE:** Because this field expects a JSON string, any changes to the * string will create a diff, even if the JSON itself hasn't changed. * Furthermore drift for this field cannot not be detected because BigQuery * only uses this schema to compute the effective schema for the table, therefore * any changes on the configured value will force the table to be recreated. * This schema is effectively only applied when creating a table from an external * datasource, after creation the computed schema will be stored in * `google_bigquery_table.schema` */ schema?: pulumi.Input<string>; /** * A unique ID for the resource. * Changing this forces a new resource to be created. */ tableId: pulumi.Input<string>; /** * If specified, configures time-based * partitioning for this table. Structure is documented below. */ timePartitioning?: pulumi.Input<inputs.bigquery.TableTimePartitioning>; /** * If specified, configures this table as a view. * Structure is documented below. */ view?: pulumi.Input<inputs.bigquery.TableView>; }
the_stack
import { Color } from "color"; export class Colors { //reds get md_red_50() { return new Color("#FFEBEE").android } get md_red_100() { return new Color("#FFCDD2").android } get md_red_200() { return new Color("#EF9A9A").android } get md_red_300() { return new Color("#E57373").android } get md_red_400() { return new Color("#EF5350").android } get md_red_500() { return new Color("#F44336").android } get md_red_600() { return new Color("#E53935").android } get md_red_700() { return new Color("#D32F2F").android } get md_red_800() { return new Color("#C62828").android } get md_red_900() { return new Color("#B71C1C").android } get md_red_A100() { return new Color("#FF8A80").android } get md_red_A200() { return new Color("#FF5252").android } get md_red_A400() { return new Color("#FF1744").android } get md_red_A700() { return new Color("#D50000").android } // pinks get md_pink_50() { return new Color("#FCE4EC").android } get md_pink_100() { return new Color("#F8BBD0").android } get md_pink_200() { return new Color("#F48FB1").android } get md_pink_300() { return new Color("#F06292").android } get md_pink_400() { return new Color("#EC407A").android } get md_pink_500() { return new Color("#E91E63").android } get md_pink_600() { return new Color("#D81B60").android } get md_pink_700() { return new Color("#C2185B").android } get md_pink_800() { return new Color("#AD1457").android } get md_pink_900() { return new Color("#880E4F").android } get md_pink_A100() { return new Color("#FF80AB").android } get md_pink_A200() { return new Color("#FF4081").android } get md_pink_A400() { return new Color("#F50057").android } get md_pink_A700() { return new Color("#C51162").android } // purples get md_purple_50() { return new Color("#F3E5F5").android } get md_purple_100() { return new Color("#E1BEE7").android } get md_purple_200() { return new Color("#CE93D8").android } get md_purple_300() { return new Color("#BA68C8").android } get md_purple_400() { return new Color("#AB47BC").android } get md_purple_500() { return new Color("#9C27B0").android } get md_purple_600() { return new Color("#8E24AA").android } get md_purple_700() { return new Color("#7B1FA2").android } get md_purple_800() { return new Color("#6A1B9A").android } get md_purple_900() { return new Color("#4A148C").android } get md_purple_A100() { return new Color("#EA80FC").android } get md_purple_A200() { return new Color("#E040FB").android } get md_purple_A400() { return new Color("#D500F9").android } get md_purple_A700() { return new Color("#AA00FF").android } // deep purples get md_deep_purple_50() { return new Color("#EDE7F6").android } get md_deep_purple_100() { return new Color("#D1C4E9").android } get md_deep_purple_200() { return new Color("#B39DDB").android } get md_deep_purple_300() { return new Color("#9575CD").android } get md_deep_purple_400() { return new Color("#7E57C2").android } get md_deep_purple_500() { return new Color("#673AB7").android } get md_deep_purple_600() { return new Color("#5E35B1").android } get md_deep_purple_700() { return new Color("#512DA8").android } get md_deep_purple_800() { return new Color("#4527A0").android } get md_deep_purple_900() { return new Color("#311B92").android } get md_deep_purple_A100() { return new Color("#B388FF").android } get md_deep_purple_A200() { return new Color("#7C4DFF").android } get md_deep_purple_A400() { return new Color("#651FFF").android } get md_deep_purple_A700() { return new Color("#6200EA").android } // indigo get md_indigo_50() { return new Color("#E8EAF6").android } get md_indigo_100() { return new Color("#C5CAE9").android } get md_indigo_200() { return new Color("#9FA8DA").android } get md_indigo_300() { return new Color("#7986CB").android } get md_indigo_400() { return new Color("#5C6BC0").android } get md_indigo_500() { return new Color("#3F51B5").android } get md_indigo_600() { return new Color("#3949AB").android } get md_indigo_700() { return new Color("#303F9F").android } get md_indigo_800() { return new Color("#283593").android } get md_indigo_900() { return new Color("#1A237E").android } get md_indigo_A100() { return new Color("#8C9EFF").android } get md_indigo_A200() { return new Color("#536DFE").android } get md_indigo_A400() { return new Color("#3D5AFE").android } get md_indigo_A700() { return new Color("#304FFE").android } //blue get md_blue_50() { return new Color("#E3F2FD").android } get md_blue_100() { return new Color("#BBDEFB").android } get md_blue_200() { return new Color("#90CAF9").android } get md_blue_300() { return new Color("#64B5F6").android } get md_blue_400() { return new Color("#42A5F5").android } get md_blue_500() { return new Color("#2196F3").android } get md_blue_600() { return new Color("#1E88E5").android } get md_blue_700() { return new Color("#1976D2").android } get md_blue_800() { return new Color("#1565C0").android } get md_blue_900() { return new Color("#0D47A1").android } get md_blue_A100() { return new Color("#82B1FF").android } get md_blue_A200() { return new Color("#448AFF").android } get md_blue_A400() { return new Color("#2979FF").android } get md_blue_A700() { return new Color("#2962FF").android } // light blue get md_light_blue_50() { return new Color("#E1F5FE").android } get md_light_blue_100() { return new Color("#B3E5FC").android } get md_light_blue_200() { return new Color("#81D4fA").android } get md_light_blue_300() { return new Color("#4fC3F7").android } get md_light_blue_400() { return new Color("#29B6FC").android } get md_light_blue_500() { return new Color("#03A9F4").android } get md_light_blue_600() { return new Color("#039BE5").android } get md_light_blue_700() { return new Color("#0288D1").android } get md_light_blue_800() { return new Color("#0277BD").android } get md_light_blue_900() { return new Color("#01579B").android } get md_light_blue_A100() { return new Color("#80D8FF").android } get md_light_blue_A200() { return new Color("#40C4FF").android } get md_light_blue_A400() { return new Color("#00B0FF").android } get md_light_blue_A700() { return new Color("#0091EA").android } // cyan get md_cyan_50() { return new Color("#E0F7FA").android } get md_cyan_100() { return new Color("#B2EBF2").android } get md_cyan_200() { return new Color("#80DEEA").android } get md_cyan_300() { return new Color("#4DD0E1").android } get md_cyan_400() { return new Color("#26C6DA").android } get md_cyan_500() { return new Color("#00BCD4").android } get md_cyan_600() { return new Color("#00ACC1").android } get md_cyan_700() { return new Color("#0097A7").android } get md_cyan_800() { return new Color("#00838F").android } get md_cyan_900() { return new Color("#006064").android } get md_cyan_A100() { return new Color("#84FFFF").android } get md_cyan_A200() { return new Color("#18FFFF").android } get md_cyan_A400() { return new Color("#00E5FF").android } get md_cyan_A700() { return new Color("#00B8D4").android } // teal get md_teal_50() { return new Color("#E0F2F1").android } get md_teal_100() { return new Color("#B2DFDB").android } get md_teal_200() { return new Color("#80CBC4").android } get md_teal_300() { return new Color("#4DB6AC").android } get md_teal_400() { return new Color("#26A69A").android } get md_teal_500() { return new Color("#009688").android } get md_teal_600() { return new Color("#00897B").android } get md_teal_700() { return new Color("#00796B").android } get md_teal_800() { return new Color("#00695C").android } get md_teal_900() { return new Color("#004D40").android } get md_teal_A100() { return new Color("#A7FFEB").android } get md_teal_A200() { return new Color("#64FFDA").android } get md_teal_A400() { return new Color("#1DE9B6").android } get md_teal_A700() { return new Color("#00BFA5").android } // green get md_green_50() { return new Color("#E8F5E9").android } get md_green_100() { return new Color("#C8E6C9").android } get md_green_200() { return new Color("#A5D6A7").android } get md_green_300() { return new Color("#81C784").android } get md_green_400() { return new Color("#66BB6A").android } get md_green_500() { return new Color("#4CAF50").android } get md_green_600() { return new Color("#43A047").android } get md_green_700() { return new Color("#388E3C").android } get md_green_800() { return new Color("#2E7D32").android } get md_green_900() { return new Color("#1B5E20").android } get md_green_A100() { return new Color("#B9F6CA").android } get md_green_A200() { return new Color("#69F0AE").android } get md_green_A400() { return new Color("#00E676").android } get md_green_A700() { return new Color("#00C853").android } //light green get md_light_green_50() { return new Color("#F1F8E9").android } get md_light_green_100() { return new Color("#DCEDC8").android } get md_light_green_200() { return new Color("#C5E1A5").android } get md_light_green_300() { return new Color("#AED581").android } get md_light_green_400() { return new Color("#9CCC65").android } get md_light_green_500() { return new Color("#8BC34A").android } get md_light_green_600() { return new Color("#7CB342").android } get md_light_green_700() { return new Color("#689F38").android } get md_light_green_800() { return new Color("#558B2F").android } get md_light_green_900() { return new Color("#33691E").android } get md_light_green_A100() { return new Color("#CCFF90").android } get md_light_green_A200() { return new Color("#B2FF59").android } get md_light_green_A400() { return new Color("#76FF03").android } get md_light_green_A700() { return new Color("#64DD17").android } // lime get md_lime_50() { return new Color("#F9FBE7").android } get md_lime_100() { return new Color("#F0F4C3").android } get md_lime_200() { return new Color("#E6EE9C").android } get md_lime_300() { return new Color("#DCE775").android } get md_lime_400() { return new Color("#D4E157").android } get md_lime_500() { return new Color("#CDDC39").android } get md_lime_600() { return new Color("#C0CA33").android } get md_lime_700() { return new Color("#A4B42B").android } get md_lime_800() { return new Color("#9E9D24").android } get md_lime_900() { return new Color("#827717").android } get md_lime_A100() { return new Color("#F4FF81").android } get md_lime_A200() { return new Color("#EEFF41").android } get md_lime_A400() { return new Color("#C6FF00").android } get md_lime_A700() { return new Color("#AEEA00").android } //yellow get md_yellow_50() { return new Color("#FFFDE7").android } get md_yellow_100() { return new Color("#FFF9C4").android } get md_yellow_200() { return new Color("#FFF590").android } get md_yellow_300() { return new Color("#FFF176").android } get md_yellow_400() { return new Color("#FFEE58").android } get md_yellow_500() { return new Color("#FFEB3B").android } get md_yellow_600() { return new Color("#FDD835").android } get md_yellow_700() { return new Color("#FBC02D").android } get md_yellow_800() { return new Color("#F9A825").android } get md_yellow_900() { return new Color("#F57F17").android } get md_yellow_A100() { return new Color("#FFFF82").android } get md_yellow_A200() { return new Color("#FFFF00").android } get md_yellow_A400() { return new Color("#FFEA00").android } get md_yellow_A700() { return new Color("#FFD600").android } //amber get md_amber_50() { return new Color("#FFF8E1").android } get md_amber_100() { return new Color("#FFECB3").android } get md_amber_200() { return new Color("#FFE082").android } get md_amber_300() { return new Color("#FFD54F").android } get md_amber_400() { return new Color("#FFCA28").android } get md_amber_500() { return new Color("#FFC107").android } get md_amber_600() { return new Color("#FFB300").android } get md_amber_700() { return new Color("#FFA000").android } get md_amber_800() { return new Color("#FF8F00").android } get md_amber_900() { return new Color("#FF6F00").android } get md_amber_A100() { return new Color("#FFE57F").android } get md_amber_A200() { return new Color("#FFD740").android } get md_amber_A400() { return new Color("#FFC400").android } get md_amber_A700() { return new Color("#FFAB00").android } //orange get md_orange_50() { return new Color("#FFF3E0").android } get md_orange_100() { return new Color("#FFE0B2").android } get md_orange_200() { return new Color("#FFCC80").android } get md_orange_300() { return new Color("#FFB74D").android } get md_orange_400() { return new Color("#FFA726").android } get md_orange_500() { return new Color("#FF9800").android } get md_orange_600() { return new Color("#FB8C00").android } get md_orange_700() { return new Color("#F57C00").android } get md_orange_800() { return new Color("#EF6C00").android } get md_orange_900() { return new Color("#E65100").android } get md_orange_A100() { return new Color("#FFD180").android } get md_orange_A200() { return new Color("#FFAB40").android } get md_orange_A400() { return new Color("#FF9100").android } get md_orange_A700() { return new Color("#FF6D00").android } //deep orange get md_deep_orange_50() { return new Color("#FBE9A7").android } get md_deep_orange_100() { return new Color("#FFCCBC").android } get md_deep_orange_200() { return new Color("#FFAB91").android } get md_deep_orange_300() { return new Color("#FF8A65").android } get md_deep_orange_400() { return new Color("#FF7043").android } get md_deep_orange_500() { return new Color("#FF5722").android } get md_deep_orange_600() { return new Color("#F4511E").android } get md_deep_orange_700() { return new Color("#E64A19").android } get md_deep_orange_800() { return new Color("#D84315").android } get md_deep_orange_900() { return new Color("#BF360C").android } get md_deep_orange_A100() { return new Color("#FF9E80").android } get md_deep_orange_A200() { return new Color("#FF6E40").android } get md_deep_orange_A400() { return new Color("#FF3D00").android } get md_deep_orange_A700() { return new Color("#DD2600").android } //brown get md_brown_50() { return new Color("#EFEBE9").android } get md_brown_100() { return new Color("#D7CCC8").android } get md_brown_200() { return new Color("#BCAAA4").android } get md_brown_300() { return new Color("#A1887F").android } get md_brown_400() { return new Color("#8D6E63").android } get md_brown_500() { return new Color("#795548").android } get md_brown_600() { return new Color("#6D4C41").android } get md_brown_700() { return new Color("#5D4037").android } get md_brown_800() { return new Color("#4E342E").android } get md_brown_900() { return new Color("#3E2723").android } //grey get md_grey_50() { return new Color("#FAFAFA").android } get md_grey_100() { return new Color("#F5F5F5").android } get md_grey_200() { return new Color("#EEEEEE").android } get md_grey_300() { return new Color("#E0E0E0").android } get md_grey_400() { return new Color("#BDBDBD").android } get md_grey_500() { return new Color("#9E9E9E").android } get md_grey_600() { return new Color("#757575").android } get md_grey_700() { return new Color("#616161").android } get md_grey_800() { return new Color("#424242").android } get md_grey_900() { return new Color("#212121").android } get md_black_1000() { return new Color("#000000").android } get md_white_1000() { return new Color("#ffffff").android } //blue grey get md_blue_grey_50() { return new Color("#ECEFF1").android } get md_blue_grey_100() { return new Color("#CFD8DC").android } get md_blue_grey_200() { return new Color("#B0BBC5").android } get md_blue_grey_300() { return new Color("#90A4AE").android } get md_blue_grey_400() { return new Color("#78909C").android } get md_blue_grey_500() { return new Color("#607D8B").android } get md_blue_grey_600() { return new Color("#546E7A").android } get md_blue_grey_700() { return new Color("#455A64").android } get md_blue_grey_800() { return new Color("#37474F").android } get md_blue_grey_900() { return new Color("#263238").android } }
the_stack
import * as React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import ContentItem from '@synerise/ds-manageable-list/dist/Item/ContentItem/ContentItem'; import { Tag, TagShape } from '@synerise/ds-tags'; import theme from '@synerise/ds-core/dist/js/DSProvider/ThemeProvider/theme'; import Button from '@synerise/ds-button'; import { v4 as uuid } from 'uuid'; import { Month, MonthlyFilterProps, MonthlyFilterState } from './MonthlyFilter.types'; import { MONTH_DAYS, DEFAULT_DAYS_OF_PERIODS, DEFAULT_COUNTED_FROM, defaultId, DAYS_OF_PERIOD_ENUM, COUNTED_FROM_ENUM, SPACE_UNICODE, } from '../../constants'; import * as S from './MonthlyFilter.styles'; import TimeWindow from '../../Shared/TimeWindow/TimeWindow'; import { TimeWindowProps } from '../../Shared/TimeWindow/TimeWindow.types'; class MonthlyFilter extends React.PureComponent<MonthlyFilterProps, MonthlyFilterState> { static defaultProps = { maxEntries: 4, }; state = { visible: { [defaultId]: true, }, }; componentDidMount(): void { const { value } = this.props; value.length && this.handleCollapse(value[0].id); } setData = (definition: Month[]): void => { const { onChange } = this.props; return onChange(definition); }; handleAddRow = (): void => { const id = uuid(); const { value, countedFromPeriods, daysOfPeriods } = this.props; const defaultPeriod = (daysOfPeriods || DEFAULT_DAYS_OF_PERIODS)[0].value; const defaultPeriodType = (countedFromPeriods || DEFAULT_DAYS_OF_PERIODS)[0].value; this.setData([...value, { period: defaultPeriod, periodType: defaultPeriodType, definition: {}, id }]); this.handleCollapse(id); }; handleRemoveRow = (index: React.ReactText): void => { const { value } = this.props; const result = value.filter((item, key) => key !== index); this.handleRemoveRowCollapse(value[index].id); this.setData([...result]); }; handleRemoveRowCollapse = (deletedId: string): void => { const { value } = this.props; const { visible } = this.state; const itemKey = value.findIndex(item => item.id === deletedId); const next = value[itemKey + 1]; const prev = value[itemKey - 1]; visible[deletedId] && (next || prev) && this.handleCollapse(next ? next.id : prev.id); }; handleTypeChange = (val: string, index: number): void => { const { value } = this.props; value[index] = { ...value[index], period: val, definition: {}, }; this.setData(value); }; handlePeriodTypeChange = (val: string, index: number): void => { const { value } = this.props; const data = [...value]; data[index] = { ...data[index], periodType: val, }; this.setData(data); }; handleDefinitionChange = (definition: Month, index: number): void => { const { value } = this.props; const data = [...value]; const currentDefinition: Month = data[index]; data[index] = { ...currentDefinition, definition, }; this.setData(data); }; dayWeekFormatter = (index: number, long: boolean): string => { const { intl } = this.props; const weekStartIndex = Math.floor(index / 7); const dayOfWeek = index - weekStartIndex * 7; const weekday = intl.formatMessage({ id: `DS.DATE-RANGE-PICKER.WEEKDAYS_LONG.${dayOfWeek + 1}` }); const nthWeek = intl.formatMessage({ id: `DS.DATE-RANGE-PICKER.NTH.${weekStartIndex === 5 ? 'LAST' : weekStartIndex + 1}`, }); return long ? `${nthWeek} ${weekday}` : intl.formatMessage({ id: `DS.DATE-RANGE-PICKER.WEEKDAYS-SHORT-${dayOfWeek}` }); }; dayMonthFormatter = (i: number, long: boolean): string => { const { intl } = this.props; const locale = intl.locale.substring(0, 2); return long ? intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.NTH-DAY-OF-MONTH' }, { nth: MONTH_DAYS(locale)[i] }) : MONTH_DAYS(locale)[i]; }; dayTemplate = (index: number): { week: number; day: number } => { const weekStartIndex = Math.floor(index / 7); return { week: weekStartIndex, day: index - weekStartIndex * 7 }; }; getTimeWindowSettings = (item: Month): Partial<TimeWindowProps> => { const { intl } = this.props; const settings = { [DAYS_OF_PERIOD_ENUM.DAY_OF_MONTH]: { numberOfDays: 31, reverseGroup: 1, inverted: item.periodType === COUNTED_FROM_ENUM.ENDING, dayTemplate: (dayOfMonth: number): { day: number } => ({ day: dayOfMonth }), dayFormatter: this.dayMonthFormatter, }, [DAYS_OF_PERIOD_ENUM.DAY_OF_WEEK]: { numberOfDays: 7 * 5, reverseGroup: 7, dayTemplate: this.dayTemplate, dayFormatter: this.dayWeekFormatter, labelInverted: item.periodType === COUNTED_FROM_ENUM.ENDING, inverted: item.periodType === COUNTED_FROM_ENUM.ENDING, rowLabelFormatter: (rowIndex: number): string => intl.formatMessage({ id: `DS.DATE-RANGE-PICKER.NTH.${rowIndex + 1}`, }), }, }; return settings[item.period] as Partial<TimeWindowProps>; }; handleCollapse = (id: React.ReactText): void => { const { visible } = this.state; const updatedVisible = {}; const visibleKeys = visible ? Object.keys(visible) : []; for (let i = 0; i < visibleKeys.length; i += 1) { const currentIndex = visibleKeys[i]; updatedVisible[currentIndex] = false; } updatedVisible[id] = true; this.setState({ visible: updatedVisible, }); }; renderDaysOfField = (item: Month, key: number): React.ReactNode => { const { intl, daysOfPeriods, disabled } = this.props; if (daysOfPeriods?.length === 1) { return ( <S.PeriodMode> <FormattedMessage id={daysOfPeriods[0].translationKey} /> </S.PeriodMode> ); } const dataSource = (daysOfPeriods || DEFAULT_DAYS_OF_PERIODS).map(period => ({ checked: item?.period === period.value, text: intl.formatMessage({ id: period.translationKey as string }), onSelect: (): void => { this.handleTypeChange(period.value as string, key); }, })); return ( <S.Select disabled={disabled} expanded={false} dropdownOverlayStyle={{ minWidth: '150px', }} dropdownProps={{ getPopupContainer: (): HTMLElement => document.querySelector('.monthly-wrapper') || document.body, }} placeholder={intl.formatMessage({ id: (daysOfPeriods || DEFAULT_DAYS_OF_PERIODS)[0].translationKey })} input={{ name: 'days-of-period', maxLength: 120, }} dataSource={dataSource} size="small" /> ); }; renderCountedFromField = (item: Month, key: number): React.ReactNode => { const { intl, countedFromPeriods, disabled } = this.props; if (countedFromPeriods?.length === 1) { return ( <S.PeriodMode> <FormattedMessage id={countedFromPeriods[0].translationKey} /> </S.PeriodMode> ); } const dataSource = (countedFromPeriods || DEFAULT_COUNTED_FROM).map(i => ({ checked: item?.periodType === i.value, text: intl.formatMessage({ id: i.translationKey as string }), onSelect: (): void => { this.handlePeriodTypeChange(i.value as string, key); }, })); return ( <S.Select disabled={disabled} expanded={false} dropdownProps={{ getPopupContainer: (): HTMLElement => document.querySelector('.monthly-wrapper') || document.body, }} dropdownOverlayStyle={{ minWidth: '150px', }} placeholder={intl.formatMessage({ id: (countedFromPeriods || DEFAULT_COUNTED_FROM)[0].translationKey })} input={{ name: 'counted-from-select', maxLength: 120, }} dataSource={dataSource} size="small" /> ); }; render(): JSX.Element { const { value, onRangeCopy, onRangePaste, onRangeClear, rangeClipboard, intl, texts, valueSelectionModes, timePickerProps, disabled, renderRangeFormSuffix, maxEntries, } = this.props; const { visible } = this.state; const data = [...value]; return ( <S.MonthlyFilterWrapper className="monthly-wrapper"> {data.map((item, key) => ( <ContentItem key={item.id} hideExpander={false} onExpand={this.handleCollapse} expanded={visible[item.id]} onRemove={(): void => this.handleRemoveRow(key)} item={{ tag: ( <Tag name={String(key + 1)} shape={TagShape.SINGLE_CHARACTER_ROUND} color={theme.palette['grey-100']} textColor={theme.palette['grey-500']} /> ), canDelete: !disabled, id: item.id as string, // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore name: ( <S.DropdownHeader className={visible[item.id] ? 'dropdown-header-visible' : 'dropdown-header'}> <S.DropdownLabel> <FormattedMessage id="DS.DATE-RANGE-PICKER.DAYS-OF" defaultMessage="Days of" /> {SPACE_UNICODE} </S.DropdownLabel> {this.renderDaysOfField(item, key)} <S.DropdownLabel> {SPACE_UNICODE} <FormattedMessage id="DS.DATE-RANGE-PICKER.COUNTED-FROM" defaultMessage="counted from" /> {SPACE_UNICODE} </S.DropdownLabel> {this.renderCountedFromField(item, key)} </S.DropdownHeader> ), content: visible[item.id] ? ( <S.ContentWrapper> <TimeWindow disabled={disabled} readOnly={!!disabled} texts={texts} // eslint-disable-next-line react/no-array-index-key key={`${item.period}_${key}`} showSelectAll invertibleTime numberOfDaysPerRow={7} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-expect-error: FIXME: Type '{ [day: number]: DenormalizedFilter; }' is not assignable to type 'Days'. days={item.definition} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-expect-error: FIXME: Type '(definition: Month) => void' is not assignable to type '(days: Days) => void'. onChange={(definition: Month): void => this.handleDefinitionChange(definition, key)} onRangeClear={onRangeClear} onRangeCopy={onRangeCopy} onRangePaste={onRangePaste} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-expect-error: FIXME: Type 'Partial<FilterDefinition> | undefined' is not assignable to type 'Partial<FilterDefinition>'. rangeClipboard={rangeClipboard} monthlyFilterPeriod={data[key].period} // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-expect-error: FIXME: Type 'Partial<FilterDefinition> | undefined' is not assignable to type 'Partial<FilterDefinition>'. valueSelectionModes={valueSelectionModes} renderRangeFormSuffix={renderRangeFormSuffix} timePickerProps={timePickerProps} {...this.getTimeWindowSettings(item)} monthlyFilter /> </S.ContentWrapper> ) : ( <div /> ), }} texts={{ itemActionDeleteTooltip: intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.REMOVE', defaultMessage: 'Remove', }), }} /> ))} <S.AddContainer> {!disabled && value.length < Number(maxEntries) && ( <Button.Creator label={intl.formatMessage({ id: 'DS.DATE-RANGE-PICKER.ADD-RULE', defaultMessage: 'Add rule' })} onClick={this.handleAddRow} block /> )} </S.AddContainer> </S.MonthlyFilterWrapper> ); } } export default injectIntl(MonthlyFilter);
the_stack
import { Type } from '@angular/core'; import { ComponentFixture, fakeAsync, tick, } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule, } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { KEYS } from '@terminus/ngx-tools/keycodes'; import { createComponent as createComponentInner, createFakeEvent, dispatchFakeEvent, dispatchKeyboardEvent, dispatchMouseEvent, typeInElement, } from '@terminus/ngx-tools/testing'; import { getAllChipInstances, getChipElement, getChipInstance, getChipRemoveButton, } from '@terminus/ui/chip/testing'; import { TsOptionComponent, TsOptionModule, } from '@terminus/ui/option'; import * as testComponents from '@terminus/ui/selection-list/testing'; // eslint-disable-next-line no-duplicate-imports import { getAllOptionInstances, getOptionElement, getOptionInstance, getSelectionListElement, getSelectionListInput, getSelectionListInstance, getSelectionListTriggerElement, } from '@terminus/ui/selection-list/testing'; import { getValidationMessageElement } from '@terminus/ui/validation-messages/testing'; import { STATES } from '../testing/src/test-components'; import { TsSelectionListTriggerDirective } from './selection-list-panel/selection-list-trigger.directive'; import { TsSelectionListComponent } from './selection-list.component'; import { TsSelectionListModule } from './selection-list.module'; /** * Create test host component * * @param component */ function createComponent<T>(component: Type<T>): ComponentFixture<T> { const moduleImports = [ FormsModule, ReactiveFormsModule, TsSelectionListModule, TsOptionModule, NoopAnimationsModule, ]; return createComponentInner(component, undefined, moduleImports); } describe(`TsSelectionListComponent`, function() { test(`should exist`, function() { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); expect(fixture.debugElement.query(By.css('.ts-selection-list'))).toBeTruthy(); }); test(`should show a progress indicator`, () => { jest.useFakeTimers(); const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); let spinner = fixture.debugElement.query(By.css('.c-selection-list__spinner')); expect(spinner).toBeFalsy(); fixture.componentInstance.showProgress = true; fixture.detectChanges(); spinner = fixture.debugElement.query(By.css('.c-selection-list__spinner')); expect(spinner).toBeTruthy(); expect.assertions(2); }); test(`should set the disabled state when called`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const selectionList = fixture.debugElement.query(By.css('.ts-selection-list')).nativeElement; instance['changeDetectorRef'].markForCheck = jest.fn(); instance.stateChanges.next = jest.fn(); instance.setDisabledState(true); fixture.detectChanges(); expect(instance['changeDetectorRef'].markForCheck).toHaveBeenCalled(); expect(instance.stateChanges.next).toHaveBeenCalled(); expect(instance.isDisabled).toEqual(true); expect(selectionList.classList).toContain('ts-selection-list--disabled'); }); test(`should not open when disabled`, () => { const fixture = createComponent(testComponents.Disabled); fixture.detectChanges(); const trigger = getSelectionListTriggerElement(fixture); dispatchMouseEvent(trigger, 'click'); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); expect(instance.panelOpen).toEqual(false); }); describe(`chips`, function() { describe(`seed value`, () => { test(`should show selections as chips when seeded manually`, () => { const fixture = createComponent(testComponents.ManualSeeded); fixture.detectChanges(); let chipElement; chipElement = fixture.debugElement.nativeElement.querySelectorAll('ts-chip'); expect(chipElement.length).toBe(0); fixture.componentInstance.myCtrl.setValue([STATES[4]]); fixture.detectChanges(); chipElement = fixture.debugElement.nativeElement.querySelectorAll('ts-chip'); expect(chipElement.length).toBe(1); }); test(`should show selections as chips when seeded while component starts up`, () => { const fixture = createComponent(testComponents.Seeded); fixture.detectChanges(); const chipElement = fixture.debugElement.nativeElement.querySelectorAll('ts-chip'); expect(chipElement.length).toBe(1); }); }); test(`should allow chips to be removed`, fakeAsync(() => { const fixture = createComponent(testComponents.Seeded); fixture.detectChanges(); let chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); // const chip = getChipElement(fixture); const chipRemovalButton = getChipRemoveButton(chips[0]); const instance = getSelectionListInstance(fixture); // Open the panel so that overlayRef is created instance.trigger.handleFocus(); instance.trigger.overlayRef!.updatePosition = jest.fn(); dispatchMouseEvent(chipRemovalButton, 'click'); fixture.detectChanges(); chips = getAllChipInstances(fixture); expect(chips.length).toEqual(0); const input = getSelectionListInput(fixture); expect(document.activeElement).toEqual(input); tick(1000); expect(instance.trigger.overlayRef!.updatePosition).toHaveBeenCalled(); })); test(`should allow removal with the backspace key`, () => { // NOTE: The CDK relies on `keyCode` being set which our helper doesn't currently do. const event = document.createEvent('KeyboardEvent'); event.initEvent('keydown', true, false); Object.defineProperties(event, { keyCode: { get: () => KEYS.BACKSPACE.keyCode }, key: { get: () => KEYS.BACKSPACE.code }, code: { get: () => KEYS.BACKSPACE.code }, }); const fixture = createComponent(testComponents.Seeded); fixture.detectChanges(); let chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); const chip = getChipElement(fixture); // The first backspace selects the previous chip chip.dispatchEvent(event); fixture.detectChanges(); chip.dispatchEvent(event); fixture.detectChanges(); chips = getAllChipInstances(fixture); expect(chips.length).toEqual(0); }); }); describe(`debounce`, function() { test(`should debounce the stream`, () => { jest.useFakeTimers(); const fixture = createComponent(testComponents.Debounce); fixture.componentInstance.change = jest.fn(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('abc'); jest.advanceTimersByTime(1); instance.querySubject.next('abcd'); jest.runAllTimers(); expect(fixture.componentInstance.change).toHaveBeenCalledTimes(1); }); test(`should allow a custom debounce delay`, () => { jest.useFakeTimers(); const fixture = createComponent(testComponents.CustomDebounce); fixture.componentInstance.change = jest.fn(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('abc'); jest.advanceTimersByTime(1); instance.querySubject.next('abcd'); jest.runAllTimers(); expect(fixture.componentInstance.change).toHaveBeenCalledTimes(3); }); }); describe(`minimumCharacters`, function() { test(`should only emit query once past the minimum character count`, () => { jest.useFakeTimers(); const fixture = createComponent(testComponents.CustomCharacterCount); fixture.componentInstance.change = jest.fn(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.querySubject.next(''); jest.advanceTimersByTime(1); instance.querySubject.next('a'); jest.advanceTimersByTime(1); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('abc'); jest.runAllTimers(); expect(fixture.componentInstance.change).toHaveBeenCalledTimes(3); }); test(`should allow a custom minimum character count`, () => { jest.useFakeTimers(); const fixture = createComponent(testComponents.CustomCharacterCount); fixture.componentInstance.customCount = 1; fixture.componentInstance.change = jest.fn(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.querySubject.next(''); jest.advanceTimersByTime(1); instance.querySubject.next('a'); jest.advanceTimersByTime(1); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('abc'); jest.runAllTimers(); expect(fixture.componentInstance.change).toHaveBeenCalledTimes(4); }); }); test(`should only allow unique queries`, function() { jest.useFakeTimers(); const fixture = createComponent(testComponents.Debounce); fixture.componentInstance.change = jest.fn(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('ab'); jest.advanceTimersByTime(1); instance.querySubject.next('ab'); jest.runAllTimers(); expect(fixture.componentInstance.change).toHaveBeenCalledTimes(1); }); describe(`duplicate selections`, function() { // NOTE: Even though we are simulating a typed query, the list of states is not actually changing. test(`should not be allowed by default but should emit an event`, fakeAsync(function() { const fixture = createComponent(testComponents.Seeded); fixture.componentInstance.duplicate = jest.fn(); fixture.detectChanges(); const component = fixture.componentInstance; component.duplicate = jest.fn(); let chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); const input = getSelectionListInput(fixture); typeInElement(fixture.componentInstance.states[3].name.substring(0, 3), input); tick(1000); fixture.detectChanges(); // Select Florida (it's selected by default in this test component) const opt = getOptionElement(fixture, 0, 4); opt.click(); tick(1000); fixture.detectChanges(); // Verify the selection did NOT work chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); // TODO: Why are these ignores needed? // @ts-ignore expect(fixture.componentInstance.duplicate.mock.calls[0][0].source).toBeInstanceOf(TsSelectionListComponent); // @ts-ignore expect(fixture.componentInstance.duplicate.mock.calls[0][0].value).toEqual(expect.objectContaining({ name: 'Florida' })); expect.assertions(4); })); describe(`when allowed`, function() { test(`should allow a duplicate selection`, fakeAsync(() => { const fixture = createComponent(testComponents.Seeded); fixture.componentInstance.allowDuplicates = true; fixture.detectChanges(); let chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); const input = getSelectionListInput(fixture); const states = fixture.componentInstance.states; typeInElement(states[4].name.substring(0, 2), input); tick(1000); fixture.detectChanges(); // Select Florida (it's selected by default in this test component) const opt = getOptionElement(fixture, 0, 4); opt.click(); tick(1000); fixture.detectChanges(); // Verify the selection DID work chips = getAllChipInstances(fixture); expect(chips.length).toEqual(2); const instance = getSelectionListInstance(fixture); expect(instance.selectionListFormControl.value).toEqual([states[4], states[4]]); expect.assertions(3); })); }); }); describe(`trigger`, function() { describe(`in single selection mode`, function() { test(`should set single value`, fakeAsync(() => { const fixture = createComponent(testComponents.Seeded); fixture.componentInstance.allowMultiple = false; fixture.componentInstance.keepOpen = false; tick(1000); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const input = getSelectionListInput(fixture); const states = fixture.componentInstance.states; typeInElement(states[4].name.substring(0, 2), input); tick(1000); fixture.detectChanges(); const opt = getOptionElement(fixture); opt.click(); tick(1000); fixture.detectChanges(); expect(instance.selectionListFormControl.value).toEqual([states[0]]); })); test.todo(`should set a value using the displayFormatter if it exists`); }); test(`should reset the query when a selection is made`, fakeAsync(function() { const fixture = createComponent(testComponents.AllowMultipleNoReopen); fixture.detectChanges(); const input = getSelectionListInput(fixture); const states = fixture.componentInstance.states; const name = states[3].name.substring(0, 2); typeInElement(name, input); tick(1000); fixture.detectChanges(); expect(input.value).toEqual(name); const opt = getOptionElement(fixture, 0, 4); opt.click(); tick(1000); fixture.detectChanges(); expect(input.value).toEqual(''); })); test(`should throw an error if a form control is set who's value isn't an array`, () => { const fixture = createComponent(testComponents.SeededNonArray); expect(() => fixture.detectChanges()).toThrowError(`TsSelectionListComponent: Form control values must be an array of values`); }); describe(`ngModel`, () => { test(`should seed the model after timeout when using ngModel`, fakeAsync(function() { const fixture = createComponent(testComponents.SeededNgModel); fixture.detectChanges(); const states = fixture.componentInstance.states; tick(1000); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); expect(instance.selectionListFormControl.value).toEqual([states[4]]); })); }); test(`should allow a value seeded by a FormControl`, fakeAsync(function() { const fixture = createComponent(testComponents.AllowMultipleNoReopen); fixture.detectChanges(); const states = fixture.componentInstance.states; const input = getSelectionListInput(fixture); const name = states[4].name.substring(0, 2); typeInElement(name, input); tick(1000); fixture.detectChanges(); const opt = getOptionElement(fixture, 0, 2); opt.click(); tick(1000); fixture.detectChanges(); expect(getSelectionListInstance(fixture).selectionListFormControl.value).toEqual([states[2]]); })); test(`should close the panel if open when getting a blur event that isn't from a selection`, function() { const fixture = createComponent(testComponents.Basic); fixture.componentInstance.disabled = true; fixture.detectChanges(); const input = getSelectionListInput(fixture); const instance = getSelectionListInstance(fixture); const triggerInstance = instance.trigger; // Focus the input instance.focusInput(); // Make sure the panel is open triggerInstance.openPanel(); fixture.detectChanges(); expect(triggerInstance.panelOpen).toEqual(true); const event = createFakeEvent('blur'); fixture.componentInstance.states.length = 0; fixture.detectChanges(); input.dispatchEvent(event); fixture.detectChanges(); expect(triggerInstance.panelOpen).toEqual(false); expect(instance.panelOpen).toEqual(false); }); test(`should close the panel when focusing on another instance`, () => { const fixture = createComponent(testComponents.Multiple); fixture.detectChanges(); const input2 = getSelectionListInput(fixture, 1); const instance = getSelectionListInstance(fixture); const triggerInstance = instance.trigger; instance.focusInput(); triggerInstance.openPanel(); fixture.detectChanges(); expect(triggerInstance.panelOpen).toEqual(true); input2.click(); fixture.detectChanges(); expect(instance.panelOpen).toEqual(false); }); test(`should update the overlay position when a chip is removed`, fakeAsync(() => { const fixture = createComponent(testComponents.Seeded); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const triggerInstance = instance.trigger; const chip = getChipInstance(fixture); const chipRemovalButton = getChipRemoveButton(chip); triggerInstance.openPanel(); fixture.detectChanges(); instance.trigger.overlayRef!.updatePosition = jest.fn(); dispatchMouseEvent(chipRemovalButton, 'click'); tick(1000); fixture.detectChanges(); expect(instance.trigger.overlayRef!.updatePosition).toHaveBeenCalled(); })); describe(`required`, () => { test(`should set required if the form control is required`, () => { const fixture = createComponent(testComponents.ValidateOnChange); fixture.detectChanges(); const component = getSelectionListElement(fixture); const selectTrigger = getSelectionListTriggerElement(fixture); dispatchMouseEvent(selectTrigger, 'click'); dispatchMouseEvent(component, 'click'); const validationMessage = getValidationMessageElement(fixture); expect(validationMessage).toBeTruthy(); }); test(`should set required if the form control is required`, () => { const fixture = createComponent(testComponents.Required); fixture.detectChanges(); const component = getSelectionListInput(fixture); const selectTrigger = getSelectionListTriggerElement(fixture); dispatchMouseEvent(selectTrigger, 'click'); dispatchMouseEvent(component, 'click'); const validationMessage = getValidationMessageElement(fixture); expect(validationMessage).toBeTruthy(); }); }); }); describe(`panel`, function() { test(`should support a custom ID`, () => { const fixture = createComponent(testComponents.Basic); fixture.componentInstance.disabled = true; fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.trigger.openPanel(); fixture.detectChanges(); const panel = fixture.debugElement.query(By.css('.ts-selection-list-panel__inner')).nativeElement as HTMLElement; expect(instance.panel.isOpen).toEqual(true); expect(panel.getAttribute('id')).toEqual(expect.stringContaining('-panel')); }); }); test(`should be able to hide the required marker`, function() { const fixture = createComponent(testComponents.HideRequired); fixture.detectChanges(); let marker = fixture.debugElement.query(By.css('.ts-form-field-required-marker')); expect(marker).toBeTruthy(); fixture.componentInstance.hideRequired = true; fixture.detectChanges(); marker = fixture.debugElement.query(By.css('.ts-form-field-required-marker')); expect(marker).toBeFalsy(); }); test(`should support a custom hint`, function() { const fixture = createComponent(testComponents.Hint); fixture.detectChanges(); const hintElement = fixture.debugElement.query(By.css('.ts-form-field__hint-wrapper')); const contents = fixture.debugElement.query(By.css('.c-input__hint')); expect(hintElement).toBeTruthy(); expect(contents.nativeElement.textContent.trim()).toEqual('foo'); }); describe(`ID`, function() { test(`should support a custom ID`, () => { const fixture = createComponent(testComponents.Id); fixture.detectChanges(); const trigger = getSelectionListTriggerElement(fixture); expect(trigger.getAttribute('id')).toEqual('foo'); }); test(`should fall back to the UID if no ID is passed in`, () => { const fixture = createComponent(testComponents.Id); fixture.componentInstance.myId = undefined as any; fixture.detectChanges(); const trigger = getSelectionListTriggerElement(fixture); expect(trigger.getAttribute('id')).toEqual(expect.stringContaining('ts-selection-list-')); }); }); test(`should show error immediately if validating on change`, function() { const fixture = createComponent(testComponents.ValidateOnChange); fixture.detectChanges(); const messageContainer = fixture.debugElement.query(By.css('.c-validation-message')); expect(messageContainer.nativeElement.textContent.trim()).toEqual('Required'); }); describe(`option`, function() { test(`should throw error if template is used but no option is passed in`, () => { const create = () => { const fixture = createComponent(testComponents.OptionError); fixture.detectChanges(); }; expect(create).toThrowError(`TsOptionComponent: The full 'option' object must be passed in when using a custom template.`); }); describe(`id`, function() { test(`should support custom IDs`, () => { const fixture = createComponent(testComponents.OptionId); fixture.detectChanges(); const option = getOptionInstance(fixture, 0, 1); expect(option.id).toEqual('Alabama'); }); test(`should fall back to UID`, () => { const fixture = createComponent(testComponents.OptionId); fixture.detectChanges(); const option = getOptionInstance(fixture, 0, 1); option.id = undefined as any; fixture.detectChanges(); expect(option.id).toEqual(expect.stringContaining('ts-option-')); }); }); describe(`getLabel`, function() { test(`should return the viewValue`, () => { const fixture = createComponent(testComponents.OptionId); fixture.detectChanges(); const option = getOptionInstance(fixture, 0, 1); expect(option.getLabel()).toEqual('Alabama'); }); }); describe(`option`, function() { test(`should retrieve the option object`, () => { const fixture = createComponent(testComponents.OptionId); fixture.detectChanges(); const option = getOptionInstance(fixture, 0, 1); expect(option.option).toEqual(expect.objectContaining({ name: 'Alabama' })); }); }); describe(`deselect`, function() { test(`should emit event not from user interaction`, () => { const fixture = createComponent(testComponents.OptionId); fixture.detectChanges(); const option = getOptionInstance(fixture, 0, 2); option.select(); fixture.detectChanges(); option['emitSelectionChangeEvent'] = jest.fn(); option.deselect(); fixture.detectChanges(); expect(option['emitSelectionChangeEvent'].mock.calls.length).toEqual(1); // Verify it was not called with the boolean expect(option['emitSelectionChangeEvent'].mock.calls[0]).toEqual([]); }); }); describe(`checkbox`, function() { test(`should not have checkbox in front of an item list`, fakeAsync(() => { const fixture = createComponent(testComponents.AllowMultipleNoReopen); fixture.detectChanges(); const input = getSelectionListInput(fixture); typeInElement('al', input); tick(1000); fixture.detectChanges(); const opt = getOptionElement(fixture, 0, 1); fixture.detectChanges(); expect(opt.querySelectorAll('ts-checkbox')).toHaveLength(0); })); }); }); describe(`when clicking the container`, () => { test('should focus the input', () => { const fixture = createComponent(testComponents.Seeded); const instance = getSelectionListInstance(fixture); instance.focusInput = jest.fn(); instance.onContainerClick(); expect(instance.focusInput).toHaveBeenCalled(); }); }); describe(`value getter/setter`, () => { test('should set and retrieve the value', () => { const fixture = createComponent(testComponents.Seeded); const instance = getSelectionListInstance(fixture); instance.value = 'testing'; expect(instance.value).toEqual('testing'); }); }); describe(`displayFormatter`, () => { test(`should default to returning the value as a string`, () => { const fixture = createComponent(testComponents.Basic); const instance = getSelectionListInstance(fixture); instance.displayFormatter = void 0 as any; const myString = 'foo' as any; expect(instance.displayFormatter(myString)).toEqual(expect.stringContaining('foo')); }); test(`should format the display value`, () => { const fixture = createComponent(testComponents.Formatter); const instance = getSelectionListInstance(fixture); fixture.detectChanges(); const chipElement = getChipElement(fixture); expect(instance.displayFormatter).toEqual(expect.any(Function)); expect(chipElement.textContent).toEqual(expect.stringContaining('ARKANSAS')); }); }); test.todo(`should reset optionSelections stream if no options were initially found`); test.todo(`should do nothing if tabOut happens but the overlay is not attached`); describe(`tsSelectionListTriggerDisabled`, () => { test.todo(`should set the disabled value`); }); describe(`handleFocus`, () => { test.todo(`should set a flag`); }); test.todo(`should correctly parse a number value`); describe(`handleKeydown`, () => { test.todo(`should prevent default when ESCAPE is clicked`); test.todo(`should select an item when ENTER is pressed`); test.todo(`should pass keydown event to the key manager`); test.todo(`should open the panel if an arrow key is used`); }); describe(`setDisabledState`, () => { test(`should disable the DOM element`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const trigger = instance.trigger; expect(trigger.elementRef.nativeElement.disabled).toEqual(false); trigger.setDisabledState(true); expect(trigger.elementRef.nativeElement.disabled).toEqual(true); }); }); describe(`attachOverlay`, () => { test(`should throw an error if no panel exists`, () => { const fixture = createComponent(testComponents.Basic); const instance = getSelectionListInstance(fixture); fixture.detectChanges(); instance.trigger.selectionListPanel = undefined as any; const actual = () => { instance.trigger.openPanel(); }; expect(actual).toThrowError(expect.objectContaining({ message: expect.stringContaining('undefined instance') })); }); test(`should reset and close if ESCAPE or ALT+UP is pressed`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const triggerInstance = instance.trigger; const event = document.createEvent('KeyboardEvent'); event.initEvent('keydown', true, false); Object.defineProperties(event, { keyCode: { get: () => KEYS.ESCAPE.keyCode }, code: { get: () => KEYS.ESCAPE.code }, }); instance.focusInput(); triggerInstance.openPanel(); fixture.detectChanges(); triggerInstance['resetActiveItem'] = jest.fn(); triggerInstance['closeKeyEventStream'].next = jest.fn(); const overlayElement = triggerInstance.overlayRef!.overlayElement; overlayElement.dispatchEvent(event); fixture.detectChanges(); expect(triggerInstance['resetActiveItem']).toHaveBeenCalled(); expect(triggerInstance['closeKeyEventStream'].next).toHaveBeenCalled(); }); test(`should trigger an overlayRef resize when the viewport size changes`, fakeAsync(() => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.focusInput(); instance.trigger.openPanel(); fixture.detectChanges(); instance.trigger.overlayRef!.updateSize = jest.fn(); dispatchFakeEvent(window, 'resize'); tick(1337); // Number from CDK overlay specs fixture.detectChanges(); expect(instance.trigger.overlayRef!.updateSize).toHaveBeenCalledWith({ width: expect.any(Number) }); })); }); test(`should be able to clear all options programmatically`, fakeAsync(() => { const fixture = createComponent(testComponents.Seeded); fixture.componentInstance.allowDuplicates = true; fixture.detectChanges(); let chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); let instance = getSelectionListInstance(fixture); instance.selectionListFormControl.setValue([]); tick(1000); fixture.detectChanges(); chips = getAllChipInstances(fixture); expect(chips.length).toEqual(0); const input = getSelectionListInput(fixture); const states = fixture.componentInstance.states; typeInElement(states[5].name.substring(0, 2), input); tick(1000); fixture.detectChanges(); const opt = getOptionElement(fixture, 0, 5); opt.click(); tick(1000); fixture.detectChanges(); chips = getAllChipInstances(fixture); expect(chips.length).toEqual(1); instance = getSelectionListInstance(fixture); expect(instance.selectionListFormControl.value).toEqual([states[5]]); })); describe(`clearPreviousSelectedOption`, () => { let fixture: ComponentFixture<testComponents.Seeded>; let trigger: TsSelectionListTriggerDirective; let options: TsOptionComponent[]; beforeEach(() => { fixture = createComponent(testComponents.Seeded); fixture.componentInstance.setNewStates(); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); trigger = instance.trigger; options = trigger.selectionListPanel.options.toArray(); options[0].selected = true; options[1].selected = true; fixture.detectChanges(); }); test(`should deselect all options`, () => { let selected = getAllOptionInstances(fixture).filter(o => o.selected); expect(selected.length).toEqual(2); trigger['clearPreviousSelectedOption'](options[2]); selected = getAllOptionInstances(fixture).filter(o => o.selected); expect(selected.length).toEqual(0); }); test(`should skip a passed in option`, () => { let selected = getAllOptionInstances(fixture).filter(o => o.selected); expect(selected.length).toEqual(2); trigger['clearPreviousSelectedOption'](options[1]); selected = getAllOptionInstances(fixture).filter(o => o.selected); expect(selected.length).toEqual(1); }); }); describe(`getConnectedElement`, () => { test(`should fall back to the elementRef if getConnectedOverlayOrigin returns nothing`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const trigger = instance.trigger; trigger['formField'] = undefined as any; expect(trigger['getConnectedElement']().nativeElement.classList).toContain('ts-selection-list-trigger'); }); }); describe(`select and deselect should fall back to empty arrays if the control value isn't set`, () => { test(`should fallback to an array when selecting`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const item = { source: {} as any, option: { value: 'apple' } as any, }; instance.selectionListFormControl.setValue(null); const actual = () => { instance.selectItem(item); }; expect(actual).not.toThrowError(); }); test(`should fallback to an array when deselecting`, () => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); const item = { source: {} as any, option: { value: 'apple' } as any, } as any; instance.selectionListFormControl.setValue(null); const actual = () => { instance.deselectItem(item); }; expect(actual).not.toThrowError(); }); }); test(`should emit on backdrop clicks`, fakeAsync(() => { const fixture = createComponent(testComponents.BackdropClick); fixture.detectChanges(); fixture.componentInstance.clicked = jest.fn(); const trigger = getSelectionListTriggerElement(fixture); dispatchKeyboardEvent(trigger, 'keydown', KEYS.DOWN_ARROW); fixture.detectChanges(); const backdrop = document.querySelector('.cdk-overlay-backdrop')! as HTMLElement; backdrop.click(); tick(1000); fixture.detectChanges(); expect(fixture.componentInstance.clicked).toHaveBeenCalled(); })); // Note: Simply dispatching the arrow down key on the trigger repeatedly did not work test.todo(`should update panel scroll position when focusing an out-of-view option`); test(`should focus first option when the options collection changes`, fakeAsync(() => { const fixture = createComponent(testComponents.Basic); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); expect(instance.panel.keyManager.activeItemIndex).toEqual(-1); const input = getSelectionListInput(fixture); const states = fixture.componentInstance.states; const name = states[3].name.substring(0, 2); typeInElement(name, input); tick(1000); fixture.detectChanges(); expect(instance.panel.keyManager.activeItemIndex).toEqual(0); })); // TODO: Not currently supported by Jest // Waiting for https://github.com/jsdom/jsdom/issues/317 to land test.todo(`should select all existing text when the input is focused`); describe(`should scroll populated item into view`, () => { test(`should have panel open with the preset value`, fakeAsync(() => { const fixture = createComponent(testComponents.SeededSingleSelect); fixture.detectChanges(); const instance = getSelectionListInstance(fixture); instance.trigger.handleFocus(); tick(1000); expect(instance.panel.keyManager.activeItemIndex).toEqual(6); })); }); describe(`noValidationOrHint`, () => { test(`should not have validation or hint added if set to true`, () => { const fixture = createComponent(testComponents.NoValidationOrHint); fixture.detectChanges(); const validationBlock = fixture.debugElement.query(By.css('.ts-form-field__subscript-wrapper')); expect(validationBlock).toBeFalsy(); }); }); });
the_stack
import { expect } from 'chai'; import { distinctUntilKeyChanged, mergeMap, map, take } from 'rxjs/operators'; import { TestScheduler } from 'rxjs/testing'; import { of, Observable } from 'rxjs'; import { observableMatcher } from '../helpers/observableMatcher'; /** @test {distinctUntilKeyChanged} */ describe('distinctUntilKeyChanged', () => { let testScheduler: TestScheduler; beforeEach(() => { testScheduler = new TestScheduler(observableMatcher); }); it('should distinguish between values', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { k: 1 }, b: { k: 2 }, c: { k: 3 } }; const e1 = hot(' -a--b-b----a-c-|', values); const e1Subs = ' ^--------------!'; const expected = '-a--b------a-c-|'; const result = e1.pipe(distinctUntilKeyChanged('k')); expectObservable(result).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1Subs); }); }); it('should distinguish between values', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 } }; const e1 = hot(' --a--a--a--b--b--a--|', values); const e1subs = ' ^-------------------!'; const expected = '--a--------b-----a--|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should distinguish between values and does not complete', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 } }; const e1 = hot(' --a--a--a--b--b--a-', values); const e1subs = ' ^ '; const expected = '--a--------b-----a-'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should distinguish between values with key', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { valOther: 1 }, c: { valOther: 3 }, d: { val: 1 }, e: { val: 5 } }; const e1 = hot<any>('--a--b--c--d--e--|', values); const e1subs = ' ^----------------!'; const expected = ' --a--b-----d--e--|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should not compare if source does not have element with key', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { valOther: 1 }, b: { valOther: 1 }, c: { valOther: 3 }, d: { valOther: 1 }, e: { valOther: 5 } }; const e1 = hot<any>('--a--b--c--d--e--|', values); const e1subs = ' ^----------------!'; const expected = ' --a--------------|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should not complete if source never completes', () => { testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => { const e1 = cold<any>('-'); const e1subs = ' ^'; const expected = ' -'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should not complete if source does not complete', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const e1 = hot<any>('-'); const e1subs = ' ^'; const expected = ' -'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should complete if source is empty', () => { testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => { const e1 = cold<any>('|'); const e1subs = ' (^!)'; const expected = ' |'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should complete if source does not emit', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const e1 = hot<any>('------|'); const e1subs = ' ^-----!'; const expected = ' ------|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should emit if source emits single element only', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 } }; const e1 = hot(' --a--|', values); const e1subs = ' ^----!'; const expected = '--a--|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should emit if source is scalar', () => { testScheduler.run(({ expectObservable }) => { const values = { a: { val: 1 } }; const e1 = of(values.a); const expected = '(a|)'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); }); }); it('should raise error if source raises error', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 } }; const e1 = hot(' --a--a--#', values); const e1subs = ' ^-------!'; const expected = '--a-----#'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should raise error if source throws', () => { testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => { const e1 = cold<any>('# '); const e1subs = ' (^!)'; const expected = ' # '; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should not omit if source elements are all different', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--c--d--e--|', values); const e1subs = ' ^----------------!'; const expected = '--a--b--c--d--e--|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should allow unsubscribing early and explicitly', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--b--d--a--e--|', values); const e1subs = ' ^---------! '; const expected = '--a--b----- '; const unsub = ' ----------! '; const result = e1.pipe(distinctUntilKeyChanged('val')); expectObservable(result, unsub).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should not break unsubscription chains when unsubscribed explicitly', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--b--d--a--e--|', values); const e1subs = ' ^---------! '; const expected = '--a--b----- '; const unsub = ' ----------! '; const result = e1.pipe( mergeMap((x: any) => of(x)), distinctUntilKeyChanged('val'), mergeMap((x: any) => of(x)) ); expectObservable(result, unsub).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should emit once if source elements are all same', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 } }; const e1 = hot(' --a--a--a--a--a--a--|', values); const e1subs = ' ^-------------------!'; const expected = '--a-----------------|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val'))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should emit once if comparer returns true always regardless of source emits', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--c--d--e--|', values); const e1subs = ' ^----------------!'; const expected = '--a--------------|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val', () => true))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should emit all if comparer returns false always regardless of source emits', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 } }; const e1 = hot(' --a--a--a--a--a--a--|', values); const e1subs = ' ^-------------------!'; const expected = '--a--a--a--a--a--a--|'; expectObservable(e1.pipe(distinctUntilKeyChanged('val', () => false))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should distinguish values by selector', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--c--d--e--|', values); const e1subs = ' ^----------------!'; const expected = '--a-----c-----e--|'; const selector = (x: number, y: number) => y % 2 === 0; expectObservable(e1.pipe(distinctUntilKeyChanged('val', selector))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should raise error when comparer throws', () => { testScheduler.run(({ hot, expectObservable, expectSubscriptions }) => { const values = { a: { val: 1 }, b: { val: 2 }, c: { val: 3 }, d: { val: 4 }, e: { val: 5 } }; const e1 = hot(' --a--b--c--d--e--|', values); const e1subs = ' ^----------! '; const expected = '--a--b--c--# '; const selector = (x: number, y: number) => { if (y === 4) { throw 'error'; } return x === y; }; expectObservable(e1.pipe(distinctUntilKeyChanged('val', selector))).toBe(expected, values); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); }); it('should stop listening to a synchronous observable when unsubscribed', () => { const sideEffects: number[] = []; const synchronousObservable = new Observable<number>((subscriber) => { // This will check to see if the subscriber was closed on each loop // when the unsubscribe hits (from the `take`), it should be closed for (let i = 0; !subscriber.closed && i < 10; i++) { sideEffects.push(i); subscriber.next(i); } }); synchronousObservable .pipe( map((value) => ({ value })), distinctUntilKeyChanged('value'), take(3) ) .subscribe(() => { /* noop */ }); expect(sideEffects).to.deep.equal([0, 1, 2]); }); });
the_stack
import * as fs from 'fs-extra' import { clone } from 'lodash' import * as os from 'os' import * as path from 'path' import * as uuid from 'uuid/v4' import { App } from '../lib/app' import { Config } from '../lib/config' import { ICodeRepository } from '../lib/service' import { EventEmitter } from '../lib/utility/eventemitter' import { Log } from './log' import * as type from './type' const tempDir = path.resolve(os.tmpdir(), 'houston') export class Worker extends EventEmitter implements type.IWorker { /** * app * The base App container. Used for roles that need access to something. * * @var {App} */ public app: App /** * config * The configuration to use during processing * * @var {Config} */ public get config (): Config { return this.app.get<Config>(Config) } /** * repository * A repository to use for this process * * @var {ICodeRepository} */ public repository: ICodeRepository /** * context * The data to use for the build * * @var {IContext} */ public context: type.IContext /** * workspace * The directory that contains the working files * * @var {string} */ public workspace: string /** * tasks * All of the tasks to run. * * @var {ITaskConstructor[]} */ public tasks: type.ITaskConstructor[] = [] /** * postTasks * These tasks run after all the tasks and forks are ran. They are usually * processing the end result, like uploading packages or logs after the * regular tasks are finished. * * @var {ITaskConstructor[]} */ public postTasks: type.ITaskConstructor[] = [] /** * forks * All of the forks we are going to run after the current task ends. * * @var {Worker[]} */ public forks: Worker[] = [] /** * If we are currently running the worker * * @var {Workable} */ public running: type.ITask | null /** * Creates a new worker process * * @param {App} app - The base App container * @param {ICodeRepository} repository - The repository to process on * @param {IContext} context - The starting context for building */ constructor (app: App, repository: ICodeRepository, context: type.IContext) { super() this.app = app this.repository = repository this.context = context this.workspace = path.resolve(tempDir, uuid()) } /** * fails * Checks if the worker fails * * @return {boolean} */ public get fails (): boolean { return this.result.failed } /** * passes * Checks if the worker passes * * @return {boolean} */ public get passes (): boolean { return (this.fails === false) } /** * contexts * Returns a list of all the contexts this worker has, and all of it's forks * * @return {IContext[]} */ public get contexts (): type.IContext[] { return [ this.context, ...this.forks .map((worker) => worker.contexts) .reduce((a, b) => [...a, ...b], []) ] } /** * runningIndex * Returns the currently running task index * * @return {Number} */ protected get runningIndex (): number { if (this.running != null) { const tI = this.tasks.findIndex((task) => { return (this.running instanceof task) }) if (tI !== -1) { return tI } else { return this.postTasks.findIndex((task) => { return (this.running instanceof task) }) } } } /** * Returns all the logs that the worker had created. Inserts some helpful * information like architecture, distribution, and references to the log as * well. * * @return {ILog[]} */ protected get resultLogs (): type.ILog[] { return this.contexts .map((ctx) => ctx.logs) .reduce((a, b) => [...a, ...b], []) .filter((l) => (l != null)) .reduce((currentLogs, log, i, allLogs) => { const allSimilarLogs = allLogs .filter((l) => (l.title === log.title)) const contexts = [...allSimilarLogs, log] .map((l) => this.getContextForLog(l)) .filter((c) => (c != null)) log.body = this.getContextLogBody(log, contexts) const similarLogs = currentLogs .filter((l) => (l.title === log.title)) if (similarLogs.length === 0) { return [...currentLogs, log] } else { return currentLogs } }, []) } /** * result * Returns the result of the worker. Possible, but incomplete if not stopped. * * @return {IResult} */ public get result (): type.IResult { const packages = this.contexts .map((ctx) => ctx.package) .filter((p) => (p != null)) // We just assume the longest appcenter and appstream fields are the best const appcenters = this.contexts .map((ctx) => ctx.appcenter) .filter((a) => (a != null)) .sort((a, b) => (JSON.stringify(b).length - JSON.stringify(a).length)) const appstreams = this.contexts .map((ctx) => ctx.appstream) .filter((a) => (a != null)) .sort((a, b) => (b.length - a.length)) const logs = this.resultLogs const failed = logs .some((l) => (l.level === Log.Level.ERROR)) return { appcenter: appcenters[0], appstream: appstreams[0], failed, logs: (logs || []), // TODO: Why can `logs` be undefined? packages } } /** * setup * Creates a workspace for the process * * @async * @return {void} */ public async setup (): Promise<void> { await this.emitAsync('setup:start') await fs.ensureDir(this.workspace) await this.emitAsync('setup:end') } /** * run * Runs a bun of tasks. The first param is do match the ITask. * * @async */ public async run (): Promise<void> { await this.emitAsync('run:start') for (const task of this.tasks) { // Run the tasks given to us try { const taskConstructor = await this.emitAsyncChain<type.ITaskConstructor>('task:start', task) this.running = new taskConstructor(this) await this.running.run() } catch (err) { this.report(err) } if (this.running == null) { break } // And if we have any forks, stop running the tasks, and run the forks if (this.forks.length > 0) { const todoTasks = this.tasks.splice(this.runningIndex + 1) this.forks.forEach((fork) => { fork.tasks = todoTasks }) await Promise.all(this.forks.map((fork) => fork.run())) } } for (const task of this.postTasks) { try { const taskConstructor = await this.emitAsyncChain<type.ITaskConstructor>('task:start', task) this.running = new taskConstructor(this) await this.running.run() } catch (err) { this.report(err) } } await this.emitAsync('run:end') this.stop() } /** * fork * Creates a new worker, copying most of the properties from this instance. * It will then run all of these forks _AFTER_ the current task is done. * * @example * Some tests, like setting up the workspace, can have multiple outputs. In * an effort to keep things linear and _hopefully_ easy to understand the * order, this is the way we would make multiple outputs possible. If the * task, it will look at all the repository references and determine what * kinds of packages it can make. Then, for each distribution, it forks. * We end up with 3 different `Worker`s running, and on exit, merging * storages. * * @async * @param {Object} [context] - Overwrite for the forked context * @return {Worker} */ public async fork (context = {}): Promise<Worker> { const newContext = Object.assign({}, this.context, context, { logs: [] }) const fork = new Worker(this.app, this.repository, newContext) this.forks.push(fork) return fork } /** * teardown * Removes files and cleans up remaining files * * @async * @return {void} */ public async teardown (): Promise<void> { await this.emitAsync('teardown:start') await fs.remove(this.workspace) await this.emitAsync('teardown:end') } /** * Adds a log/error to storage * * @param {Error} err * @return {Worker} */ public report (err: Error) { // A real error. Not a Log if (!(err instanceof Log)) { this.emit('run:error', err) const log = new Log(Log.Level.ERROR, 'Internal error while running') .setError(err) this.context.logs.push(log) this.stop() } else { this.context.logs.push(err) if (err.level === Log.Level.ERROR) { this.stop() } } return this } /** * Stops the build if it's currently running * * @return {IResult} */ public stop (): type.IResult { this.running = null return this.result } /** * Given a log, we can find what context, or context of a fork the log belongs * to. This is useful to get more information about the log's origin like * architecture and distribution. * * @param {ILog} log * @return {IContext|null} */ protected getContextForLog (log: type.ILog): type.IContext | null { for (const l of this.context.logs) { if (l === log) { return this.context } } for (const fork of this.forks) { const foundChildForkContext = fork.getContextForLog(log) if (foundChildForkContext != null) { return foundChildForkContext } } return null } /** * Adds some context information to the end of the log * * @param {type.ILog} log The log to add information to * @param {type.IContext[]} contexts Information to add to the log * @return {string} New Log body text */ protected getContextLogBody (log: type.ILog, contexts: type.IContext[]): string { if (log.body == null || log.body.includes('### Build Information')) { return log.body } const architectures = Array.from(new Set(contexts.map((c) => c.architecture))) .filter((a) => (a != null)) const distributions = Array.from(new Set(contexts.map((c) => c.distribution))) .filter((d) => (d != null)) const references = Array.from(new Set(this.getContextForLog(log).references)) .filter((r) => (r != null)) let body = (log.body || '').trim() body += '\n\n### Build Information' if (architectures.length > 1) { body += `\nAffects Architectures: ${architectures.join(', ')}` } else if (architectures.length === 1) { body += `\nAffects Architecture: ${architectures[0]}` } if (distributions.length > 1) { body += `\nAffects Distributions: ${distributions.join(', ')}` } else if (distributions.length === 1) { body += `\nAffects Distribution: ${distributions[0]}` } if (references.length > 0) { body += '\nBuilt with the following references:' for (const reference of references) { body += `\n- ${reference}` } } return body } }
the_stack
import { MissingParametersPlaceholder, defaultModelAssessmentContext, ModelAssessmentContext, OverallMetricChart, BinaryClassificationMetrics, RegressionMetrics, JointDataset, generateMetrics, ModelTypes, classificationTask, FabricStyles, MulticlassClassificationMetrics, ErrorCohort, ILabeledStatistic } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { Stack, Text, Pivot, PivotItem, IComboBox, IComboBoxOption, ComboBox, ActionButton, MessageBar, Toggle } from "office-ui-fabric-react"; import React from "react"; import { ChartConfigurationFlyout } from "./ChartConfigurationFlyout"; import { defaultNumberOfContinuousFeatureBins } from "./Constants"; import { DatasetCohortStatsTable } from "./DatasetCohortStatsTable"; import { DisaggregatedAnalysisTable } from "./DisaggregatedAnalysisTable"; import { generateOverlappingFeatureBasedCohorts } from "./DisaggregatedAnalysisUtils"; import { FeatureConfigurationFlyout } from "./FeatureConfigurationFlyout"; import { MetricConfigurationFlyout } from "./MetricConfigurationFlyout"; import { modelOverviewStyles } from "./ModelOverview.styles"; import { ModelOverviewMetricChart } from "./ModelOverviewMetricChart"; import { ProbabilityDistributionChart } from "./ProbabilityDistributionChart"; import { getSelectableMetrics } from "./StatsTableUtils"; interface IModelOverviewProps { showNewModelOverviewExperience: boolean; } interface IModelOverviewState { selectedMetrics: string[]; selectedFeatures: number[]; selectedFeaturesContinuousFeatureBins: { [featureIndex: number]: number }; selectedDatasetCohorts?: number[]; selectedFeatureBasedCohorts?: number[]; chartConfigurationIsVisible: boolean; datasetCohortViewIsVisible: boolean; datasetCohortChartIsVisible: boolean; featureConfigurationIsVisible: boolean; metricConfigurationIsVisible: boolean; showHeatmapColors: boolean; } const datasetCohortViewPivotKey = "datasetCohortView"; const disaggregatedAnalysisPivotKey = "disaggregatedAnalysis"; export class ModelOverview extends React.Component< IModelOverviewProps, IModelOverviewState > { public static contextType = ModelAssessmentContext; public context: React.ContextType<typeof ModelAssessmentContext> = defaultModelAssessmentContext; private featureComboBoxRef = React.createRef<IComboBox>(); constructor(props: IModelOverviewProps) { super(props); this.state = { chartConfigurationIsVisible: false, datasetCohortChartIsVisible: true, datasetCohortViewIsVisible: true, featureConfigurationIsVisible: false, metricConfigurationIsVisible: false, selectedFeatures: [], selectedFeaturesContinuousFeatureBins: {}, selectedMetrics: [], showHeatmapColors: false }; } public componentDidMount(): void { let defaultSelectedMetrics: string[] = []; if (this.context.dataset.task_type === classificationTask) { if (this.context.jointDataset.getModelType() === ModelTypes.Binary) { defaultSelectedMetrics = [ BinaryClassificationMetrics.Accuracy, BinaryClassificationMetrics.FalsePositiveRate, BinaryClassificationMetrics.FalseNegativeRate, BinaryClassificationMetrics.SelectionRate ]; } else { defaultSelectedMetrics = [MulticlassClassificationMetrics.Accuracy]; } } else { // task_type === "regression" defaultSelectedMetrics = [ RegressionMetrics.MeanAbsoluteError, RegressionMetrics.MeanSquaredError, RegressionMetrics.MeanPrediction ]; } this.setState({ selectedDatasetCohorts: this.context.errorCohorts.map( (_cohort, index) => { return index; } ), selectedMetrics: defaultSelectedMetrics }); } public render(): React.ReactNode { if (this.context.dataset.predicted_y === undefined) { return ( <MissingParametersPlaceholder> {localization.Interpret.ModelPerformance.missingParameters} </MissingParametersPlaceholder> ); } const classNames = modelOverviewStyles(); const selectableMetrics = getSelectableMetrics( this.context.dataset.task_type, this.context.jointDataset.getModelType() === ModelTypes.Multiclass ); const columns: string[] = [ localization.ModelAssessment.ModelOverview.countColumnHeader ]; columns.push( ...selectableMetrics .filter((element) => this.state.selectedMetrics.includes(element.key.toString()) ) .map((element) => { return element.text; }) ); // generate table contents for dataset cohorts const datasetCohortLabeledStatistics = generateMetrics( this.context.jointDataset, this.context.errorCohorts.map((errorCohort) => errorCohort.cohort.unwrap(JointDataset.IndexLabel) ), this.context.modelMetadata.modelType ); // generate table contents for selected feature cohorts const featureBasedCohorts = generateOverlappingFeatureBasedCohorts( this.context.baseErrorCohort, this.context.jointDataset, this.context.dataset, this.state.selectedFeatures, this.state.selectedFeaturesContinuousFeatureBins ); const featureBasedCohortLabeledStatistics = generateMetrics( this.context.jointDataset, featureBasedCohorts.map((errorCohort) => errorCohort.cohort.unwrap(JointDataset.IndexLabel) ), this.context.modelMetadata.modelType ); const featureSelectionLimitReached = this.state.selectedFeatures.length >= 2; const featureSelectionOptions: IComboBoxOption[] = this.context.dataset.feature_names.map((featureName, index) => { return { disabled: featureSelectionLimitReached && !this.state.selectedFeatures.includes(index), key: index, text: featureName }; }); let chartCohorts: ErrorCohort[]; let someCohortSelected: boolean; let selectedChartCohorts: number[]; let labeledStatistics: ILabeledStatistic[][]; if (this.state.datasetCohortChartIsVisible) { chartCohorts = this.context.errorCohorts; someCohortSelected = this.state.selectedDatasetCohorts !== undefined && this.state.selectedDatasetCohorts.length > 0; selectedChartCohorts = this.state.selectedDatasetCohorts ?? []; labeledStatistics = datasetCohortLabeledStatistics; } else { chartCohorts = featureBasedCohorts; someCohortSelected = this.state.selectedFeatureBasedCohorts !== undefined && this.state.selectedFeatureBasedCohorts.length > 0; selectedChartCohorts = this.state.selectedFeatureBasedCohorts ?? []; labeledStatistics = featureBasedCohortLabeledStatistics; } // only show heatmap toggle if there are multiple cohorts since there won't be a color gradient otherwise. const showHeatmapToggleInDatasetCohortView = this.state.datasetCohortViewIsVisible && this.context.errorCohorts.length > 1; const showHeatmapToggleInFeatureCohortView = !this.state.datasetCohortViewIsVisible && this.state.selectedFeatures.length > 0 && featureBasedCohorts.length > 1; return ( <Stack className={classNames.sectionStack} tokens={{ childrenGap: "10px" }} > {!this.props.showNewModelOverviewExperience && ( <> <Text variant="medium" className={classNames.descriptionText}> {localization.Interpret.ModelPerformance.helperText} </Text> <OverallMetricChart /> </> )} {this.props.showNewModelOverviewExperience && ( <Stack tokens={{ childrenGap: "10px" }}> <Text variant="medium" className={classNames.descriptionText}> {localization.ModelAssessment.ModelOverview.topLevelDescription} </Text> <Pivot onLinkClick={this.handleViewPivot}> <PivotItem headerText={ localization.ModelAssessment.ModelOverview .dataCohortsChartSelectionHeader } itemKey={datasetCohortViewPivotKey} /> <PivotItem headerText={ localization.ModelAssessment.ModelOverview .disaggregatedAnalysisHeatmapHeader } itemKey={disaggregatedAnalysisPivotKey} /> </Pivot> {!this.state.datasetCohortViewIsVisible && ( <Text> { localization.ModelAssessment.ModelOverview .featureBasedViewDescription } </Text> )} <Stack horizontal tokens={{ childrenGap: "10px" }}> <ComboBox placeholder={ localization.ModelAssessment.ModelOverview .metricSelectionDropdownPlaceholder } label={ localization.ModelAssessment.ModelOverview.metricsDropdown } selectedKey={this.state.selectedMetrics} options={selectableMetrics} onChange={this.onMetricSelectionChange} multiSelect className={classNames.dropdown} styles={FabricStyles.limitedSizeMenuDropdown} /> <ActionButton className={classNames.configurationActionButton} onClick={() => this.setState({ metricConfigurationIsVisible: true }) } iconProps={{ iconName: "ColumnOptions" }} > { localization.ModelAssessment.ModelOverview .helpMeChooseMetricsButton } </ActionButton> </Stack> {!this.state.datasetCohortViewIsVisible && ( <Stack horizontal tokens={{ childrenGap: "10px" }}> <ComboBox componentRef={this.featureComboBoxRef} placeholder={ localization.ModelAssessment.ModelOverview .featureSelectionDropdownPlaceholder } label={ localization.ModelAssessment.ModelOverview.featuresDropdown } selectedKey={this.state.selectedFeatures} options={featureSelectionOptions} onChange={this.onFeatureSelectionChange} multiSelect className={classNames.dropdown} styles={FabricStyles.limitedSizeMenuDropdown} /> <ActionButton className={classNames.configurationActionButton} onClick={() => this.setState({ featureConfigurationIsVisible: true }) } iconProps={{ iconName: "ColumnOptions" }} > { localization.ModelAssessment.ModelOverview .helpMeChooseFeaturesButton } </ActionButton> </Stack> )} {(showHeatmapToggleInDatasetCohortView || showHeatmapToggleInFeatureCohortView) && ( <Toggle label={ localization.ModelAssessment.ModelOverview .visualDisplayToggleLabel } inlineLabel onChange={this.onVisualDisplayToggleChange} /> )} {this.state.datasetCohortViewIsVisible ? ( <DatasetCohortStatsTable selectableMetrics={selectableMetrics} selectedMetrics={this.state.selectedMetrics} showHeatmapColors={this.state.showHeatmapColors} /> ) : ( <> {this.state.selectedFeatures.length === 0 && ( <MissingParametersPlaceholder> { localization.ModelAssessment.ModelOverview .disaggregatedAnalysisFeatureSelectionPlaceholder } </MissingParametersPlaceholder> )} {this.state.selectedFeatures.length > 0 && ( <> <Text className={classNames.generalSemiBoldText}> {localization.formatString( localization.ModelAssessment.ModelOverview .disaggregatedAnalysisBaseCohortDislaimer, this.context.baseErrorCohort.cohort.name )} </Text> {this.context.baseErrorCohort.cohort.filters.length + this.context.baseErrorCohort.cohort.compositeFilters .length > 0 && ( <MessageBar> {localization.formatString( localization.ModelAssessment.ModelOverview .disaggregatedAnalysisBaseCohortWarning, localization.ErrorAnalysis.Cohort.defaultLabel, this.context.baseErrorCohort.cohort.name )} </MessageBar> )} </> )} <DisaggregatedAnalysisTable selectableMetrics={selectableMetrics} selectedMetrics={this.state.selectedMetrics} selectedFeatures={this.state.selectedFeatures} featureBasedCohorts={featureBasedCohorts} showHeatmapColors={this.state.showHeatmapColors} /> </> )} <ChartConfigurationFlyout isOpen={this.state.chartConfigurationIsVisible} onDismissFlyout={this.onDismissChartConfigurationFlyout} datasetCohorts={this.context.errorCohorts} featureBasedCohorts={featureBasedCohorts} selectedDatasetCohorts={this.state.selectedDatasetCohorts} selectedFeatureBasedCohorts={ this.state.selectedFeatureBasedCohorts } updateCohortSelection={this.updateCohortSelection} datasetCohortViewIsSelected={ this.state.datasetCohortChartIsVisible } /> <FeatureConfigurationFlyout isOpen={this.state.featureConfigurationIsVisible} onDismissFlyout={this.onDismissFeatureConfigurationFlyout} selectedFeatures={this.state.selectedFeatures} numberOfContinuousFeatureBins={ this.state.selectedFeaturesContinuousFeatureBins } updateSelectedFeatures={this.onFeatureConfigurationChange} /> <MetricConfigurationFlyout isOpen={this.state.metricConfigurationIsVisible} onDismissFlyout={() => { this.setState({ metricConfigurationIsVisible: false }); }} selectedMetrics={this.state.selectedMetrics} updateSelectedMetrics={this.onMetricConfigurationChange} selectableMetrics={selectableMetrics} /> {someCohortSelected && ( <Pivot> {this.context.modelMetadata.modelType === ModelTypes.Binary && ( <PivotItem headerText={ localization.ModelAssessment.ModelOverview .probabilityDistributionPivotItem } > <ProbabilityDistributionChart onChooseCohorts={this.onChooseCohorts} cohorts={chartCohorts} selectedCohorts={selectedChartCohorts} /> </PivotItem> )} <PivotItem headerText={ localization.ModelAssessment.ModelOverview .metricsVisualizationsPivotItem } > <ModelOverviewMetricChart onChooseCohorts={this.onChooseCohorts} selectableMetrics={selectableMetrics} cohorts={chartCohorts} cohortStats={labeledStatistics} selectedCohorts={selectedChartCohorts} /> </PivotItem> </Pivot> )} </Stack> )} </Stack> ); } private onDismissChartConfigurationFlyout = () => { this.setState({ chartConfigurationIsVisible: false }); }; private onDismissFeatureConfigurationFlyout = () => { this.setState({ featureConfigurationIsVisible: false }); }; private onVisualDisplayToggleChange = ( _event: React.MouseEvent<HTMLElement, MouseEvent>, checked?: boolean | undefined ) => { if (checked !== undefined) { this.setState({ showHeatmapColors: checked }); } }; private onChooseCohorts = () => this.setState({ chartConfigurationIsVisible: true }); private updateCohortSelection = ( selectedDatasetCohorts: number[], selectedFeatureBasedCohorts: number[], datasetCohortChartIsSelected: boolean ) => this.setState({ chartConfigurationIsVisible: false, datasetCohortChartIsVisible: datasetCohortChartIsSelected, selectedDatasetCohorts, selectedFeatureBasedCohorts }); private onMetricSelectionChange = ( _: React.FormEvent<IComboBox>, item?: IComboBoxOption ): void => { if (item && item.selected !== undefined) { const metric = item.key.toString(); if (item.selected && !this.state.selectedMetrics.includes(metric)) { this.setState({ selectedMetrics: this.state.selectedMetrics.concat([metric]) }); } if (!item.selected && this.state.selectedMetrics.includes(metric)) { const selectedMetrics = this.state.selectedMetrics; const unselectedMetricIndex = selectedMetrics.findIndex( (key) => key === metric ); // remove unselected metric selectedMetrics.splice(unselectedMetricIndex, 1); this.setState({ selectedMetrics }); } } }; private onFeatureConfigurationChange = ( newSelectedFeatures: number[], numberOfContinuousFeatureBins: { [featureIndex: number]: number; } ): void => { const featureBasedCohorts = this.generateFeatureBasedCohorts( newSelectedFeatures, numberOfContinuousFeatureBins ); this.setState({ featureConfigurationIsVisible: false, selectedFeatureBasedCohorts: featureBasedCohorts.map((_, index) => index), selectedFeatures: newSelectedFeatures, selectedFeaturesContinuousFeatureBins: numberOfContinuousFeatureBins }); }; private onMetricConfigurationChange = (metrics: string[]): void => { this.setState({ metricConfigurationIsVisible: false, selectedMetrics: metrics }); }; private onFeatureSelectionChange = ( _: React.FormEvent<IComboBox>, item?: IComboBoxOption ): void => { if (item && item.selected !== undefined && typeof item.key === "number") { let newlySelectedFeatures = this.state.selectedFeatures; // technically we know it's only numbers but item.key has type string | number if (item.selected && !this.state.selectedFeatures.includes(item.key)) { newlySelectedFeatures = newlySelectedFeatures.concat([ item.key as number ]); } if (!item.selected && this.state.selectedFeatures.includes(item.key)) { const unselectedFeatureIndex = newlySelectedFeatures.findIndex( (key) => key === item.key ); // remove unselected feature newlySelectedFeatures.splice(unselectedFeatureIndex, 1); } const numberOfContinuousFeatureBins: { [featureIndex: number]: number; } = {}; newlySelectedFeatures.forEach((featureIndex) => { numberOfContinuousFeatureBins[featureIndex] = this.state.selectedFeaturesContinuousFeatureBins[featureIndex] ?? defaultNumberOfContinuousFeatureBins; }); const featureBasedCohorts = this.generateFeatureBasedCohorts( newlySelectedFeatures, numberOfContinuousFeatureBins ); this.setState({ selectedFeatureBasedCohorts: featureBasedCohorts.map( (_, index) => index ), selectedFeatures: newlySelectedFeatures, selectedFeaturesContinuousFeatureBins: numberOfContinuousFeatureBins }); } }; private generateFeatureBasedCohorts( selectedFeatures: number[], numberOfContinuousFeatureBins: { [featureIndex: number]: number } ) { return generateOverlappingFeatureBasedCohorts( this.context.baseErrorCohort, this.context.jointDataset, this.context.dataset, selectedFeatures, numberOfContinuousFeatureBins ); } private handleViewPivot = (item?: PivotItem | undefined): void => { if (item) { // The table and chart are handled with separate flags here // because users may still want to configure the chart differently // from the table. However, by default we present the chart matching // the table, i.e., if the dataset cohort view is chosen we show // the dataset cohort chart and if the disaggregated analysis view // is chosen we show the feature-based cohort chart. if (item.props.itemKey === datasetCohortViewPivotKey) { this.setState({ datasetCohortChartIsVisible: true, datasetCohortViewIsVisible: true }); } if (item.props.itemKey === disaggregatedAnalysisPivotKey) { this.setState({ datasetCohortChartIsVisible: false, datasetCohortViewIsVisible: false }); } } }; }
the_stack
import AuralRendering from '../audio/aural_rendering'; import * as Enrich from '../enrich_mathml/enrich'; import {Highlighter} from '../highlighter/highlighter'; import * as HighlighterFactory from '../highlighter/highlighter_factory'; import * as Semantic from '../semantic_tree/semantic'; import {SpeechGenerator} from '../speech_generator/speech_generator'; import * as SpeechGeneratorFactory from '../speech_generator/speech_generator_factory'; import * as SpeechGeneratorUtil from '../speech_generator/speech_generator_util'; import {Walker} from '../walker/walker'; import * as WalkerFactory from '../walker/walker_factory'; import * as WalkerUtil from '../walker/walker_util'; import * as DomUtil from './dom_util'; import {Engine, EngineConst, SREError} from './engine'; import {KeyCode} from './event_util'; import XpathUtil from './xpath_util'; export namespace ProcessorFactory { const PROCESSORS = new Map(); /** * Adds a processor to the processor map. * @param name The name of the processor. * @param processor The processor object. */ export function set<T>(name: string, processor: Processor<T>) { PROCESSORS.set(name, processor); } /** * Gets the named processor. Throws an error if the processor does not exist! * @param name The name of the processor. * @return The processor. */ function get_<T>(name: string): Processor<T> { let processor = PROCESSORS.get(name.toLowerCase()); if (!processor) { throw new SREError('Unknown processor ' + name); } return processor; } /** * Processes an expression with the given processor. * @param name The name of the processor. * @param expr The expression to process. * @return The data structure resulting from the processing the expression. */ export function process<T>(name: string, expr: string): T { let processor = get_(name); return processor.processor(expr) as T; } /** * Processes an expression with the given processor. * @param name The name of the processor. * @param expr The expression to process. * @return The data structure resulting from the processing the expression. */ export function processOnly<T>(name: string, expr: string): T { let processor = get_(name); return processor.process(expr) as T; } /** * Prints a processed expression with given processor. * @param name The name of the processor. * @param data The data structure that's the result of this processor. * @return A string representation of the result. */ export function print<T>(name: string, data: T): string { let processor = get_(name); return Engine.getInstance().pprint ? processor.pprint(data) : processor.print(data); } /** * Convenience method that combines processing and printing. * @param name The name of the processor. * @param expr The expression to process. * @return A string representation of the result. */ export function output(name: string, expr: string): string { let processor = get_(name); let data = processor.processor(expr); return Engine.getInstance().pprint ? processor.pprint(data) : processor.print(data); } /** * Convenience method that combines key processing, processing and printing. * @param name The name of the processor. * @param expr The key stroke to process. * @return A string representation of the result. */ export function keypress(name: string, expr: KeyCode|string): string { let processor = get_(name); let key = (processor instanceof KeyProcessor) ? processor.key(expr) : expr; let data = processor.processor(key as string); return Engine.getInstance().pprint ? processor.pprint(data) : processor.print(data); } } export class Processor<T> { /** * A state object for stateful processors. */ public static LocalState: { walker: Walker, speechGenerator: SpeechGenerator, highlighter: Highlighter } = {walker: null, speechGenerator: null, highlighter: null}; /** * processor The actual processing method. */ public process: (p1: string) => T; /** * postprocessor Optional postprocessing of the result. */ public postprocess: (p1: T, p2: string) => T; /** * print The printing method. If none is given, defaults to toString(). */ public print: (p1: T) => string; /** * pprint The pretty printing method. If none is given, defaults print. */ public pprint: (p1: T) => string; /** * The combined processing method. Runs first the process method followed by * the postprocessor method if the latter exists. */ public processor: (p1: string) => T; /** * Default method to stringify processed data. * @param x Input data. * @return Resulting string. */ private static stringify_<T>(x: T): string { return x ? x.toString() : (x as any) as string; } /** * Processors bundles a processing method with a collection of output methods. * @param name The name of the processor. * @param {{processor: function(string): T, * postprocessor: (undefined|function(T, string): T), * print: (undefined|function(T): string), * pprint: (undefined|function(T): string)}} methods */ constructor(public name: string, methods: { processor: (p1: string) => T, postprocessor?: ((p1: T, p2: string) => T), print?: ((p1: T) => string), pprint?: ((p1: T) => string) }) { this.process = methods.processor; this.postprocess = methods.postprocessor || ((x, _y) => x) as (p1: T, p2: string) => T; this.processor = this.postprocess ? (function(x) { return this.postprocess(this.process(x), x); } as (p1: string) => T) : this.process; this.print = methods.print || Processor.stringify_; this.pprint = methods.pprint || this.print; ProcessorFactory.set(this.name, this); } } export class KeyProcessor<T> extends Processor<T> { /** * The method handling the keypress. */ public key: (p1: KeyCode|string) => KeyCode; /** * Default method to stringify input key codes. If the key code is already a * string, it is returned. * @param key The key code. * @return The corresponding string. */ private static getKey_(key: KeyCode|string): KeyCode { return typeof key === 'string' ? // TODO (TS): Check if this really works! KeyCode[key.toUpperCase() as keyof typeof KeyCode] : key; } /** * @param name The name of the processor. * @param {{processor: function(string): T, * key: (undefined|function((sre.EventUtil.KeyCode|string)): * sre.EventUtil.KeyCode), * print: (undefined|function(T): string), * pprint: (undefined|function(T): string)}} methods * @override */ constructor(name: string, methods: { processor: (p1: string) => T, key?: ((p1: KeyCode|string) => KeyCode), print?: ((p1: T) => string), pprint?: ((p1: T) => string) }) { super(name, methods); /** * Transforms key values into strings. */ this.key = methods.key || KeyProcessor.getKey_; } } // semantic: XML of semantic tree. new Processor<Element>('semantic', { processor: function(expr) { let mml = DomUtil.parseInput(expr); return Semantic.xmlTree(mml) as Element; }, postprocessor: function(xml, _expr) { let setting = Engine.getInstance().speech; if (setting === EngineConst.Speech.NONE) { return xml; } // This avoids temporary attributes (e.g., for grammar) to bleed into // the tree. let clone = xml.cloneNode(true) as Element; let speech = SpeechGeneratorUtil.computeMarkup(clone); if (setting === EngineConst.Speech.SHALLOW) { xml.setAttribute('speech', AuralRendering.finalize(speech)); return xml; } let nodesXml = XpathUtil.evalXPath('.//*[@id]', xml) as Element[]; let nodesClone = XpathUtil.evalXPath('.//*[@id]', clone) as Element[]; for (let i = 0, orig, node; orig = nodesXml[i], node = nodesClone[i]; i++) { speech = SpeechGeneratorUtil.computeMarkup(node); orig.setAttribute('speech', AuralRendering.finalize(speech)); } return xml; }, pprint: function(tree) { return DomUtil.formatXml(tree.toString()); } }); // speech: Aural rendering string. new Processor('speech', { processor: function(expr) { let mml = DomUtil.parseInput(expr); let xml = Semantic.xmlTree(mml); let descrs = SpeechGeneratorUtil.computeSpeech(xml); return AuralRendering.finalize(AuralRendering.markup(descrs)); }, pprint: function(speech) { let str = speech.toString(); // Pretty Printing wrt. markup renderer. return AuralRendering.isXml() ? DomUtil.formatXml(str) : str; } }); // json: Json version of the semantic tree. new Processor('json', { processor: function(expr) { let mml = DomUtil.parseInput(expr); let stree = Semantic.getTree(mml); return stree.toJson(); }, postprocessor: function(json: any, expr) { let setting = Engine.getInstance().speech; if (setting === EngineConst.Speech.NONE) { return json; } let mml = DomUtil.parseInput(expr); let xml = Semantic.xmlTree(mml); let speech = SpeechGeneratorUtil.computeMarkup(xml); if (setting === EngineConst.Speech.SHALLOW) { json.stree.speech = AuralRendering.finalize(speech); return json; } let addRec = (json: any) => { let node = XpathUtil.evalXPath(`.//*[@id=${json.id}]`, xml)[0] as Element; let speech = SpeechGeneratorUtil.computeMarkup(node); json.speech = AuralRendering.finalize(speech); if (json.children) { json.children.forEach(addRec); } }; addRec(json.stree); return json; }, print: function(json) { return JSON.stringify(json); }, pprint: function(json) { return JSON.stringify(json, null, 2); } }); // description: List of auditory descriptions. new Processor('description', { processor: function(expr) { let mml = DomUtil.parseInput(expr); let xml = Semantic.xmlTree(mml); let descrs = SpeechGeneratorUtil.computeSpeech(xml); return descrs; }, print: function(descrs) { return JSON.stringify(descrs); }, pprint: function(descrs) { return JSON.stringify(descrs, null, 2); } }); // enriched: Enriched MathML node. new Processor<Element>('enriched', { processor: function(expr) { return Enrich.semanticMathmlSync(expr); }, postprocessor: function(enr, _expr) { let root = WalkerUtil.getSemanticRoot(enr); switch (Engine.getInstance().speech) { case EngineConst.Speech.NONE: break; case EngineConst.Speech.SHALLOW: let generator = SpeechGeneratorFactory.generator('Adhoc'); generator.getSpeech(root, enr); break; case EngineConst.Speech.DEEP: generator = SpeechGeneratorFactory.generator('Tree'); generator.getSpeech(root, enr); break; default: break; } return enr; }, pprint: function(tree) { return DomUtil.formatXml(tree.toString()); } }); new Processor('walker', { processor: function(expr) { let generator = SpeechGeneratorFactory.generator('Node'); Processor.LocalState.speechGenerator = generator; Processor.LocalState.highlighter = HighlighterFactory.highlighter( {color: 'black'}, {color: 'white'}, {renderer: 'NativeMML'}); let node = ProcessorFactory.process('enriched', expr) as Element; let eml = ProcessorFactory.print('enriched', node); Processor.LocalState.walker = WalkerFactory.walker( Engine.getInstance().walker, node, generator, Processor.LocalState.highlighter, eml); return Processor.LocalState.walker; }, print: function(_walker) { return Processor.LocalState.walker.speech(); } }); // TODO: This one should probably return the now highlighted node. new KeyProcessor('move', { processor: function(direction) { if (!Processor.LocalState.walker) { return null; } let move = Processor.LocalState.walker.move(direction as any); return move === false ? AuralRendering.error(direction) : Processor.LocalState.walker.speech(); } });
the_stack
namespace pxsim.music { let synth: SoundEmojiSynthesizer; let soundPromise: Promise<void>; //% export function __playSoundExpression(notes: string, waitTillDone: boolean): void { const cb = getResume(); const b = board(); // v2 only... b.ensureHardwareVersion(2); if (!synth) synth = new SoundEmojiSynthesizer(0); if (!soundPromise) soundPromise = Promise.resolve(); soundPromise = soundPromise.then(() => { notes = builtin.lookupBuiltIn(notes); const soundEffects = parseSoundEffects(notes); synth.play(soundEffects); let cancelled = false; return Promise.race([ delayAsync(synth.totalDuration()) .then(() => { // If safari didn't allow the sound to play for some reason, // it will get delayed until the user does something that // unmutes it. make sure we cancel it so that it doesn't // play long after it was supposed to cancelled = true }), AudioContextManager.playPCMBufferStreamAsync(() => { if (!synth.effect) return undefined; const buff = synth.pull(); const arr = new Float32Array(buff.length); for (let i = 0; i < buff.length; i++) { // Buffer is (0, 1023) we need to map it to (-1, 1) arr[i] = ((buff[i] - 512) / 512); } return arr; }, synth.sampleRate, 0.03, () => cancelled) ]); }); if (!waitTillDone) cb(); else soundPromise = soundPromise.then(cb); } export function __stopSoundExpressions() { AudioContextManager.stopAll(); } /** * Adapted from lancaster-university/codal-microbit-v2 * https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp */ function parseSoundEffects(notes: string) { // https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp#L57 // 72 characters of sound data comma separated const charsPerEffect = 72; const effectCount = Math.floor((notes.length + 1) / (charsPerEffect + 1)); const expectedLength = effectCount * (charsPerEffect + 1) - 1; if (notes.length != expectedLength) { return []; } const soundEffects: SoundEffect[] = []; for (let i = 0; i < effectCount; ++i) { const start = i * charsPerEffect + i; if (start > 0 && notes[start - 1] != ',') { return []; } const effect = blankSoundEffect(); if (!parseSoundExpression(notes.substr(start), effect)) { return []; } soundEffects.push(effect); } return soundEffects; } export interface TonePrint { tonePrint: (arg: number[], position: number) => number; parameter: number[]; } export interface ToneEffect { effect: (synth: SoundEmojiSynthesizer, context: ToneEffect) => void; step: number; steps: number; parameter: number[]; parameter_p: Progression[]; } export interface SoundEffect { frequency: number; volume: number; duration: number; tone: TonePrint; effects: ToneEffect[]; } export function parseSoundExpression(soundChars: string, fx: SoundEffect) { // https://github.com/lancaster-university/codal-microbit-v2/blob/master/source/SoundExpressions.cpp#L115 // Encoded as a sequence of zero padded decimal strings. // This encoding is worth reconsidering if we can! // The ADSR effect (and perhaps others in future) has two parameters which cannot be expressed. // 72 chars total // [0] 0-4 wave let wave = parseInt(soundChars.substr(0, 1)); // [1] 0000-1023 volume let effectVolume = parseInt(soundChars.substr(1, 4)); // [5] 0000-9999 frequency let frequency = parseInt(soundChars.substr(5, 4)); // [9] 0000-9999 duration let duration = parseInt(soundChars.substr(9, 4)); // [13] 00 shape (specific known values) let shape = parseInt(soundChars.substr(13, 2)); // [15] XXX unused/bug. This was startFrequency but we use frequency above. // [18] 0000-9999 end frequency let endFrequency = parseInt(soundChars.substr(18, 4)); // [22] XXXX unused. This was start volume but we use volume above. // [26] 0000-1023 end volume let endVolume = parseInt(soundChars.substr(26, 4)); // [30] 0000-9999 steps let steps = parseInt(soundChars.substr(30, 4)); // [34] 00-03 fx choice let fxChoice = parseInt(soundChars.substr(34, 2)); // [36] 0000-9999 fxParam let fxParam = parseInt(soundChars.substr(36, 4)); // [40] 0000-9999 fxnSteps let fxnSteps = parseInt(soundChars.substr(40, 4)); // Details that encoded randomness to be applied when frame is used: // Can the randomness cause any parameters to go out of range? // [44] 0000-9999 frequency random frequency = applyRandom(frequency, parseInt(soundChars.substr(44, 4))); // [48] 0000-9999 end frequency random endFrequency = applyRandom(endFrequency, parseInt(soundChars.substr(48, 4))); // [52] 0000-9999 volume random effectVolume = applyRandom(effectVolume, parseInt(soundChars.substr(52, 4))); // [56] 0000-9999 end volume random endVolume = applyRandom(endVolume, parseInt(soundChars.substr(56, 4))); // [60] 0000-9999 duration random duration = applyRandom(duration, parseInt(soundChars.substr(60, 4))); // [64] 0000-9999 fxParamRandom fxParam = applyRandom(fxParam, parseInt(soundChars.substr(64, 4))); // [68] 0000-9999 fxnStepsRandom fxnSteps = applyRandom(fxnSteps, parseInt(soundChars.substr(68, 4))); if (frequency == -1 || endFrequency == -1 || effectVolume == -1 || endVolume == -1 || duration == -1 || fxParam == -1 || fxnSteps == -1) { return false; } let volumeScaleFactor = 1; switch(wave) { case 0: fx.tone.tonePrint = Synthesizer.SineTone; break; case 1: fx.tone.tonePrint = Synthesizer.SawtoothTone; break; case 2: fx.tone.tonePrint = Synthesizer.TriangleTone; break; case 3: fx.tone.tonePrint = Synthesizer.SquareWaveTone; break; case 4: fx.tone.tonePrint = Synthesizer.NoiseTone; break; } fx.frequency = frequency; fx.duration = duration; fx.effects[0].steps = steps; switch(shape) { case 0: fx.effects[0].effect = SoundSynthesizerEffects.noInterpolation; break; case 1: fx.effects[0].effect = SoundSynthesizerEffects.linearInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 2: fx.effects[0].effect = SoundSynthesizerEffects.curveInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 5: fx.effects[0].effect = SoundSynthesizerEffects.exponentialRisingInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 6: fx.effects[0].effect = SoundSynthesizerEffects.exponentialFallingInterpolation; fx.effects[0].parameter[0] = endFrequency; break; case 8: // various ascending scales - see next switch case 10: case 12: case 14: case 16: fx.effects[0].effect = SoundSynthesizerEffects.appregrioAscending; break; case 9: // various descending scales - see next switch case 11: case 13: case 15: case 17: fx.effects[0].effect = SoundSynthesizerEffects.appregrioDescending; break; case 18: fx.effects[0].effect = SoundSynthesizerEffects.logarithmicInterpolation; break; } // Scale switch(shape) { case 8: case 9: fx.effects[0].parameter_p[0] = MusicalProgressions.majorScale; break; case 10: case 11: fx.effects[0].parameter_p[0] = MusicalProgressions.minorScale; break; case 12: case 13: fx.effects[0].parameter_p[0] = MusicalProgressions.diminished; break; case 14: case 15: fx.effects[0].parameter_p[0] = MusicalProgressions.chromatic; break; case 16: case 17: fx.effects[0].parameter_p[0] = MusicalProgressions.wholeTone; break; } // Volume envelope let effectVolumeFloat = CLAMP(0, effectVolume, 1023) / 1023.0; let endVolumeFloat = CLAMP(0, endVolume, 1023) / 1023.0; fx.volume = volumeScaleFactor * effectVolumeFloat; fx.effects[1].effect = SoundSynthesizerEffects.volumeRampEffect; fx.effects[1].steps = 36; fx.effects[1].parameter[0] = volumeScaleFactor * endVolumeFloat; // Vibrato effect // Steps need to be spread across duration evenly. let normalizedFxnSteps = (fx.duration / 10000) * fxnSteps; switch(fxChoice) { case 1: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.frequencyVibratoEffect; fx.effects[2].parameter[0] = fxParam; break; case 2: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.volumeVibratoEffect; fx.effects[2].parameter[0] = fxParam; break; case 3: fx.effects[2].steps = normalizedFxnSteps; fx.effects[2].effect = SoundSynthesizerEffects.warbleInterpolation; fx.effects[2].parameter[0] = fxParam; break; } return true; } function random(max: number) { return Math.floor(Math.random() * max); } function CLAMP(min: number, value: number, max: number) { return Math.min(max, Math.max(min, value)); } function applyRandom(value: number, rand: number) { if (value < 0 || rand < 0) { return -1; } const delta = random(rand * 2 + 1) - rand; return Math.abs(value + delta); } function blankSoundEffect() { const res: SoundEffect = { frequency: 0, volume: 1, duration: 0, tone: { tonePrint: undefined, parameter: [0] }, effects: [] }; for(let i = 0; i < EMOJI_SYNTHESIZER_TONE_EFFECTS; i++) { res.effects.push({ effect: undefined, step: 0, steps: 0, parameter: [], parameter_p: [] }); } return res; } function delayAsync(millis: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, millis)); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/dataConnectionsMappers"; import * as Parameters from "../models/parameters"; import { KustoManagementClientContext } from "../kustoManagementClientContext"; /** Class representing a DataConnections. */ export class DataConnections { private readonly client: KustoManagementClientContext; /** * Create a DataConnections. * @param {KustoManagementClientContext} client Reference to the service client. */ constructor(client: KustoManagementClientContext) { this.client = client; } /** * Returns the list of data connections of the given Kusto database. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsListByDatabaseResponse> */ listByDatabase( resourceGroupName: string, clusterName: string, databaseName: string, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsListByDatabaseResponse>; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param callback The callback */ listByDatabase( resourceGroupName: string, clusterName: string, databaseName: string, callback: msRest.ServiceCallback<Models.DataConnectionListResult> ): void; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param options The optional parameters * @param callback The callback */ listByDatabase( resourceGroupName: string, clusterName: string, databaseName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataConnectionListResult> ): void; listByDatabase( resourceGroupName: string, clusterName: string, databaseName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataConnectionListResult>, callback?: msRest.ServiceCallback<Models.DataConnectionListResult> ): Promise<Models.DataConnectionsListByDatabaseResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, databaseName, options }, listByDatabaseOperationSpec, callback ) as Promise<Models.DataConnectionsListByDatabaseResponse>; } /** * Checks that the data connection parameters are valid. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param parameters The data connection parameters supplied to the CreateOrUpdate operation. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsDataConnectionValidationMethodResponse> */ dataConnectionValidationMethod( resourceGroupName: string, clusterName: string, databaseName: string, parameters: Models.DataConnectionValidation, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsDataConnectionValidationMethodResponse> { return this.beginDataConnectionValidationMethod( resourceGroupName, clusterName, databaseName, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise< Models.DataConnectionsDataConnectionValidationMethodResponse >; } /** * Checks that the data connection name is valid and is not already in use. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsCheckNameAvailabilityResponse> */ checkNameAvailability( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: Models.DataConnectionCheckNameRequest, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsCheckNameAvailabilityResponse>; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param callback The callback */ checkNameAvailability( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: Models.DataConnectionCheckNameRequest, callback: msRest.ServiceCallback<Models.CheckNameResult> ): void; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param options The optional parameters * @param callback The callback */ checkNameAvailability( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: Models.DataConnectionCheckNameRequest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CheckNameResult> ): void; checkNameAvailability( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: Models.DataConnectionCheckNameRequest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CheckNameResult>, callback?: msRest.ServiceCallback<Models.CheckNameResult> ): Promise<Models.DataConnectionsCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, databaseName, dataConnectionName, options }, checkNameAvailabilityOperationSpec, callback ) as Promise<Models.DataConnectionsCheckNameAvailabilityResponse>; } /** * Returns a data connection. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsGetResponse> */ get( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsGetResponse>; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param callback The callback */ get( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, callback: msRest.ServiceCallback<Models.DataConnectionUnion> ): void; /** * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param options The optional parameters * @param callback The callback */ get( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DataConnectionUnion> ): void; get( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DataConnectionUnion>, callback?: msRest.ServiceCallback<Models.DataConnectionUnion> ): Promise<Models.DataConnectionsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, clusterName, databaseName, dataConnectionName, options }, getOperationSpec, callback ) as Promise<Models.DataConnectionsGetResponse>; } /** * Creates or updates a data connection. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param parameters The data connection parameters supplied to the CreateOrUpdate operation. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsCreateOrUpdateResponse> */ createOrUpdate( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, parameters: Models.DataConnectionUnion, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsCreateOrUpdateResponse> { return this.beginCreateOrUpdate( resourceGroupName, clusterName, databaseName, dataConnectionName, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise< Models.DataConnectionsCreateOrUpdateResponse >; } /** * Updates a data connection. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param parameters The data connection parameters supplied to the Update operation. * @param [options] The optional parameters * @returns Promise<Models.DataConnectionsUpdateResponse> */ update( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, parameters: Models.DataConnectionUnion, options?: msRest.RequestOptionsBase ): Promise<Models.DataConnectionsUpdateResponse> { return this.beginUpdate( resourceGroupName, clusterName, databaseName, dataConnectionName, parameters, options ).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise< Models.DataConnectionsUpdateResponse >; } /** * Deletes the data connection with the given name. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse> { return this.beginDeleteMethod( resourceGroupName, clusterName, databaseName, dataConnectionName, options ).then((lroPoller) => lroPoller.pollUntilFinished()); } /** * Checks that the data connection parameters are valid. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param parameters The data connection parameters supplied to the CreateOrUpdate operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDataConnectionValidationMethod( resourceGroupName: string, clusterName: string, databaseName: string, parameters: Models.DataConnectionValidation, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, databaseName, parameters, options }, beginDataConnectionValidationMethodOperationSpec, options ); } /** * Creates or updates a data connection. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param parameters The data connection parameters supplied to the CreateOrUpdate operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, parameters: Models.DataConnectionUnion, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, databaseName, dataConnectionName, parameters, options }, beginCreateOrUpdateOperationSpec, options ); } /** * Updates a data connection. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param parameters The data connection parameters supplied to the Update operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginUpdate( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, parameters: Models.DataConnectionUnion, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, databaseName, dataConnectionName, parameters, options }, beginUpdateOperationSpec, options ); } /** * Deletes the data connection with the given name. * @param resourceGroupName The name of the resource group containing the Kusto cluster. * @param clusterName The name of the Kusto cluster. * @param databaseName The name of the database in the Kusto cluster. * @param dataConnectionName The name of the data connection. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod( resourceGroupName: string, clusterName: string, databaseName: string, dataConnectionName: string, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, clusterName, databaseName, dataConnectionName, options }, beginDeleteMethodOperationSpec, options ); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByDatabaseOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.DataConnectionListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const checkNameAvailabilityOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/checkNameAvailability", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "dataConnectionName", mapper: { ...Mappers.DataConnectionCheckNameRequest, required: true } }, responses: { 200: { bodyMapper: Mappers.CheckNameResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.dataConnectionName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.DataConnection }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDataConnectionValidationMethodOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnectionValidation", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DataConnectionValidation, required: true } }, responses: { 200: { bodyMapper: Mappers.DataConnectionValidationListResult }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.dataConnectionName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DataConnection, required: true } }, responses: { 200: { bodyMapper: Mappers.DataConnection }, 201: { bodyMapper: Mappers.DataConnection }, 202: { bodyMapper: Mappers.DataConnection }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.dataConnectionName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DataConnection, required: true } }, responses: { 200: { bodyMapper: Mappers.DataConnection }, 201: { bodyMapper: Mappers.DataConnection }, 202: { bodyMapper: Mappers.DataConnection }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/clusters/{clusterName}/databases/{databaseName}/dataConnections/{dataConnectionName}", urlParameters: [ Parameters.resourceGroupName, Parameters.clusterName, Parameters.databaseName, Parameters.dataConnectionName, Parameters.subscriptionId ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as vscode from "vscode"; import * as asyncfs from "fs/promises"; import * as path from "path"; import { createTestConfiguration, createDarwinTestConfiguration } from "../debugger/launch"; import { FolderContext } from "../FolderContext"; import { execFileStreamOutput } from "../utilities/utilities"; import { getBuildAllTask } from "../SwiftTaskProvider"; import * as Stream from "stream"; import configuration from "../configuration"; import { WorkspaceContext } from "../WorkspaceContext"; /** Class used to run tests */ export class TestRunner { private testRun: vscode.TestRun; private testItems: vscode.TestItem[]; /** * Constructor for TestRunner * @param request Test run request * @param folderContext Folder tests are being run in * @param controller Test controller */ constructor( private request: vscode.TestRunRequest, private folderContext: FolderContext, private controller: vscode.TestController ) { this.testRun = this.controller.createTestRun(this.request); this.testItems = this.createTestList(); } get workspaceContext(): WorkspaceContext { return this.folderContext.workspaceContext; } /** * Setup debug and run test profiles * @param controller Test controller * @param folderContext Folder tests are running in */ static setupProfiles(controller: vscode.TestController, folderContext: FolderContext) { // Add non-debug profile controller.createRunProfile( "Run", vscode.TestRunProfileKind.Run, async (request, token) => { const runner = new TestRunner(request, folderContext, controller); await runner.runHandler(false, token); } ); // Add debug profile controller.createRunProfile( "Debug", vscode.TestRunProfileKind.Debug, async (request, token) => { const runner = new TestRunner(request, folderContext, controller); await runner.runHandler(true, token); } ); } /** Construct test item list from TestRequest */ createTestList(): vscode.TestItem[] { const queue: vscode.TestItem[] = []; // Loop through all included tests, or all known tests, and add them to our queue if (this.request.include) { this.request.include.forEach(test => queue.push(test)); } else { this.controller.items.forEach(test => queue.push(test)); } // create test list const list: vscode.TestItem[] = []; while (queue.length > 0) { const test = queue.pop()!; // Skip tests the user asked to exclude if (this.request.exclude?.includes(test)) { continue; } if (test.children.size > 0) { test.children.forEach(test => queue.push(test)); continue; } list.push(test); } return list; } /** * Test run handler. Run a series of tests and extracts the results from the output * @param shouldDebug Should we run the debugger * @param token Cancellation token * @returns When complete */ async runHandler(shouldDebug: boolean, token: vscode.CancellationToken) { try { // run associated build task const task = await getBuildAllTask(this.folderContext); const exitCode = await this.workspaceContext.tasks.executeTaskAndWait(task, token); // if build failed then exit if (exitCode === undefined || exitCode !== 0) { this.testRun.end(); return; } if (shouldDebug) { await this.debugSession(token); } else { await this.runSession(token); } } catch (error) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const reason = error as any; if (reason) { this.testRun.appendOutput(reason.toString()); } console.log(error); } this.testRun.end(); } /** * Edit launch configuration to run tests * @param debugging Do we need this configuration for debugging * @param outputFile Debug output file * @returns */ private createLaunchConfigurationForTesting( debugging: boolean, outputFile: string | null = null ): vscode.DebugConfiguration | null { const testList = this.testItems.map(item => item.id).join(","); if (process.platform === "darwin") { // if debugging on macOS need to create a custom launch configuration so we can set the // the system architecture if (debugging && outputFile) { const testBuildConfig = createDarwinTestConfiguration( this.folderContext, `-XCTest ${testList}`, outputFile ); if (testBuildConfig === null) { return null; } return testBuildConfig; } else { const testBuildConfig = createTestConfiguration(this.folderContext, true); if (testBuildConfig === null) { return null; } testBuildConfig.args = ["-XCTest", testList, ...testBuildConfig.args]; // send stdout to testOutputPath. Cannot send both stdout and stderr to same file as it // doesn't come out in the correct order testBuildConfig.stdio = [null, null, outputFile]; return testBuildConfig; } } else { const testBuildConfig = createTestConfiguration(this.folderContext, true); if (testBuildConfig === null) { return null; } testBuildConfig.args = [testList]; // send stdout to testOutputPath. Cannot send both stdout and stderr to same file as it // doesn't come out in the correct order testBuildConfig.stdio = [null, outputFile, null]; return testBuildConfig; } } /** Run test session without attaching to a debugger */ async runSession(token: vscode.CancellationToken) { // create launch config for testing const testBuildConfig = this.createLaunchConfigurationForTesting(false); if (testBuildConfig === null) { return; } // Use WriteStream to log results const writeStream = new Stream.Writable(); writeStream._write = (chunk, encoding, next) => { const text = chunk.toString("utf8"); this.testRun.appendOutput(text.replace(/\n/g, "\r\n")); if (process.platform === "darwin") { this.parseResultDarwin(text); } else { this.parseResultNonDarwin(text); } next(); }; writeStream.on("close", () => { writeStream.end(); }); const stdout: Stream.Writable = writeStream; const stderr: Stream.Writable = writeStream; if (token.isCancellationRequested) { writeStream.end(); return; } this.testRun.appendOutput(`> Test run started at ${new Date().toLocaleString()} <\r\n\r\n`); // show test results pane vscode.commands.executeCommand("testing.showMostRecentOutput"); try { await execFileStreamOutput( testBuildConfig.program, testBuildConfig.args, stdout, stderr, token, { cwd: testBuildConfig.cwd, env: { ...process.env, ...testBuildConfig.env }, }, this.folderContext, false ); } catch { // ignore errors from execFileStreamOutput. As stderr output is already parsed } } /** Run test session inside debugger */ async debugSession(token: vscode.CancellationToken) { const testOutputPath = this.workspaceContext.tempFolder.filename("TestOutput", "txt"); // create launch config for testing const testBuildConfig = this.createLaunchConfigurationForTesting(true, testOutputPath); if (testBuildConfig === null) { return; } // given we have already run a build task there is no need to have a pre launch task // to build the tests testBuildConfig.preLaunchTask = undefined; // output test build configuration if (configuration.diagnostics) { const configJSON = JSON.stringify(testBuildConfig); this.workspaceContext.outputChannel.logDiagnostic( `Debug Config: ${configJSON}`, this.folderContext.name ); } const subscriptions: vscode.Disposable[] = []; // add cancelation const startSession = vscode.debug.onDidStartDebugSession(session => { this.workspaceContext.outputChannel.logDiagnostic( "Start Test Debugging", this.folderContext.name ); const cancellation = token.onCancellationRequested(() => { this.workspaceContext.outputChannel.logDiagnostic( "Test Debugging Cancelled", this.folderContext.name ); vscode.debug.stopDebugging(session); }); subscriptions.push(cancellation); }); subscriptions.push(startSession); return new Promise<void>((resolve, reject) => { vscode.debug.startDebugging(this.folderContext.workspaceFolder, testBuildConfig).then( started => { if (started) { this.testRun.appendOutput( `> Test run started at ${new Date().toLocaleString()} <\r\n\r\n` ); // show test results pane vscode.commands.executeCommand("testing.showMostRecentOutput"); const terminateSession = vscode.debug.onDidTerminateDebugSession( async () => { this.workspaceContext.outputChannel.logDiagnostic( "Stop Test Debugging", this.folderContext.name ); try { if (!token.isCancellationRequested) { const debugOutput = await asyncfs.readFile(testOutputPath, { encoding: "utf8", }); this.testRun.appendOutput( debugOutput.replace(/\n/g, "\r\n") ); if (process.platform === "darwin") { this.parseResultDarwin(debugOutput); } else { this.parseResultNonDarwin(debugOutput); } } asyncfs.rm(testOutputPath); } catch { // ignore error } // dispose terminate debug handler subscriptions.forEach(sub => sub.dispose()); resolve(); } ); subscriptions.push(terminateSession); } else { asyncfs.rm(testOutputPath); subscriptions.forEach(sub => sub.dispose()); reject(); } }, reason => { asyncfs.rm(testOutputPath); subscriptions.forEach(sub => sub.dispose()); reject(reason); } ); }); } /** * Parse results from `swift test` and update tests accordingly for Darwin platforms * @param output Output from `swift test` */ private parseResultDarwin(output: string) { const lines = output.split("\n").map(item => item.trim()); for (const line of lines) { // Regex "Test Case '-[<test target> <class.function>]' passed" const passedMatch = /^Test Case '-\[(\S+)\s(.*)\]' passed/.exec(line); if (passedMatch) { const testId = `${passedMatch[1]}/${passedMatch[2]}`; const passedTestIndex = this.testItems.findIndex(item => item.id === testId); if (passedTestIndex !== -1) { this.testRun.passed(this.testItems[passedTestIndex]); this.testItems.splice(passedTestIndex, 1); } continue; } // Regex "<path/to/test>:<line number>: error: -[<test target> <class.function>] : <error>" const failedMatch = /^(.+):(\d+):\serror:\s-\[(\S+)\s(.*)\] : (.*)$/.exec(line); if (failedMatch) { const testId = `${failedMatch[3]}/${failedMatch[4]}`; const failedTestIndex = this.testItems.findIndex(item => item.id === testId); if (failedTestIndex !== -1) { const message = new vscode.TestMessage(failedMatch[5]); message.location = new vscode.Location( vscode.Uri.file(failedMatch[1]), new vscode.Position(parseInt(failedMatch[2]) - 1, 0) ); this.testRun.failed(this.testItems[failedTestIndex], message); this.testItems.splice(failedTestIndex, 1); } continue; } // Regex "<path/to/test>:<line number>: -[<test target> <class.function>] : Test skipped" const skippedMatch = /^(.+):(\d+):\s-\[(\S+)\s(.*)\] : Test skipped/.exec(line); if (skippedMatch) { const testId = `${skippedMatch[3]}/${skippedMatch[4]}`; const skippedTestIndex = this.testItems.findIndex(item => item.id === testId); if (skippedTestIndex !== -1) { this.testRun.skipped(this.testItems[skippedTestIndex]); this.testItems.splice(skippedTestIndex, 1); } continue; } } } /** * Parse results from `swift test` and update tests accordingly for non Darwin * platforms eg Linux and Windows * @param output Output from `swift test` */ private parseResultNonDarwin(output: string) { const lines = output.split("\n").map(item => item.trim()); // Non-Darwin test output does not include the test target name. The only way to find out // the target for a test is when it fails and returns a file name. If we find failed tests // first and then remove them from the list we cannot set them to passed by mistake. // We extract the file name from the error and use that to check whether the file belongs // to the target associated with the TestItem. This does not work 100% as the error could // occur in another target, so we revert to just searching for class and function name if // the above method is unsuccessful. for (const line of lines) { // Regex "<path/to/test>:<line number>: error: <class>.<function> : <error>" const failedMatch = /^(.+):(\d+):\serror:\s*(.*)\.(.*) : (.*)/.exec(line); if (failedMatch) { const testName = `${failedMatch[3]}/${failedMatch[4]}`; let failedTestIndex = this.testItems.findIndex(item => this.isTestWithFilenameInTarget(testName, failedMatch[1], item) ); // didn't find failed test so just search using class name and test function name if (failedTestIndex === -1) { failedTestIndex = this.testItems.findIndex(item => item.id.endsWith(testName)); } if (failedTestIndex !== -1) { const message = new vscode.TestMessage(failedMatch[5]); message.location = new vscode.Location( vscode.Uri.file(failedMatch[1]), new vscode.Position(parseInt(failedMatch[2]), 0) ); this.testRun.failed(this.testItems[failedTestIndex], message); // remove from test item list as its status has been set this.testItems.splice(failedTestIndex, 1); } continue; } // Regex "<path/to/test>:<line number>: <class>.<function> : Test skipped:" const skippedMatch = /^(.+):(\d+):\s*(.*)\.(.*) : Test skipped:/.exec(line); if (skippedMatch) { const testName = `${skippedMatch[3]}/${skippedMatch[4]}`; let skippedTestIndex = this.testItems.findIndex(item => this.isTestWithFilenameInTarget(testName, skippedMatch[1], item) ); if (skippedTestIndex === -1) { skippedTestIndex = this.testItems.findIndex(item => item.id.endsWith(testName)); } if (skippedTestIndex !== -1) { this.testRun.skipped(this.testItems[skippedTestIndex]); // remove from test item list as its status has been set this.testItems.splice(skippedTestIndex, 1); } continue; } } for (const line of lines) { // Regex "Test Case '<class>.<function>' passed" const passedMatch = /^Test Case '(.*)\.(.*)' passed/.exec(line); if (passedMatch) { const testName = `${passedMatch[1]}/${passedMatch[2]}`; const passedTestIndex = this.testItems.findIndex(item => item.id.endsWith(testName) ); if (passedTestIndex !== -1) { this.testRun.passed(this.testItems[passedTestIndex]); // remove from test item list as its status has been set this.testItems.splice(passedTestIndex, 1); } continue; } } } /** * Linux test output does not include the target name. So I have to work out which target * the test is in via the test name and if it failed the filename from the error. In theory * if a test fails the filename for where it failed should indicate which target it is in. * * @param testName Test name * @param filename File name of where test failed * @param item TestItem * @returns Is it this TestItem */ private isTestWithFilenameInTarget( testName: string, filename: string, item: vscode.TestItem ): boolean { if (!item.id.endsWith(testName)) { return false; } // get target test item const targetTestItem = item.parent?.parent; if (!targetTestItem) { return false; } // get target from Package const target = this.folderContext.swiftPackage.targets.find( item => targetTestItem.label === item.name ); if (target) { const fileErrorIsIn = filename; const targetPath = path.join(this.folderContext.folder.fsPath, target.path); const relativePath = path.relative(targetPath, fileErrorIsIn); return target.sources.find(source => source === relativePath) !== undefined; } return false; } }
the_stack
import { createConnection, Diagnostic, DiagnosticSeverity, Position, Range, TextDocuments, DidOpenTextDocumentParams, DidOpenTextDocumentNotification } from 'vscode-languageserver/node'; // prettier-ignore import { TextDocument } from 'vscode-languageserver-textdocument'; import * as vscode from 'vscode'; import { Uri, workspace } from 'vscode'; import * as path from 'path'; import * as assert from 'assert'; import { beforeEach } from 'mocha'; import { Duplex } from 'stream'; import { ANTLRBackend } from '../compiling/ANTLRBackend'; // This file contains code for testing the antlr backend // Mocks the document open notification to test full results including call from server const testFolderLocation = '../../src/test/test-files/ANTLRCompiler.test'; const TEST_LANGUAGE_ID = 'typescript'; /* eslint-disable no-underscore-dangle */ class TestStream extends Duplex { _write(chunk: string, _encoding: string, done: () => void) { this.emit('data', chunk); done(); } _read(_size: number) {} } /* eslint-enable no-underscore-dangle */ const up = new TestStream(); const down = new TestStream(); const server = createConnection(up, down); const client = createConnection(down, up); server.listen(); client.listen(); function mockOpenDocNotif(config: { version: number; uri: string; text: string }): DidOpenTextDocumentParams { const { version, uri, text } = config; return { textDocument: { uri, languageId: TEST_LANGUAGE_ID, version, text } }; } function sleep(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); }); } const filePath = path.join(__dirname, testFolderLocation, 'single_error.sv'); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: 'Basic testing text!!!' }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); let documents: TextDocuments<TextDocument>; suite('ANTLRBackend Tests', () => { beforeEach(() => { documents = new TextDocuments(TextDocument); documents.listen(server); }); test('test #1: Diagnostics for single syntax error', async () => { const filePath = path.join(__dirname, testFolderLocation, 'single_error.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 1); // Check that every diagnostic is an Error collection.forEach((diagnostic: Diagnostic) => { if (diagnostic.severity !== DiagnosticSeverity.Error) { assert.fail(); } }); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #2: Diagnostics for multiple syntax errors', async () => { const filePath = path.join(__dirname, testFolderLocation, 'several_error.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 3); // Check that every diagnostic is an Error collection.forEach((diagnostic: Diagnostic) => { if (diagnostic.severity !== DiagnosticSeverity.Error) { assert.fail(); } }); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #3: Diagnostics for correct code', async () => { const filePath = path.join(__dirname, testFolderLocation, 'correct.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 0); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #4: Diagnostics for empty document', async () => { const filePath = path.join(__dirname, testFolderLocation, 'empty.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 0); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #5: Diagnostics for a document containing unicode characters', async () => { const filePath = path.join(__dirname, testFolderLocation, 'unicode.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 2); // Check that every diagnostic is an Error collection.forEach((diagnostic: Diagnostic) => { if (diagnostic.severity !== DiagnosticSeverity.Error) { assert.fail(); } }); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #6: Diagnostics for verilog document', async () => { const filePath = path.join(__dirname, testFolderLocation, 'single_error.v'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { const collection = result.get(document.uri); assert.strictEqual(collection.length, 1); // Check that every diagnostic is an Error collection.forEach((diagnostic: Diagnostic) => { if (diagnostic.severity !== DiagnosticSeverity.Error) { assert.fail(); } }); }, (error) => { assert.fail(); } ); }).timeout(10000); test('test #7: Diagnostics for non-Verilog/SystemVerilog document', async () => { const filePath = path.join(__dirname, testFolderLocation, 'single_error.txt'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(document).then( (result) => { assert.fail(); }, (error) => { // Success } ); }).timeout(10000); test('test #8: Diagnostics for invalid document with open document', async () => { const filePath = path.join(__dirname, testFolderLocation, 'single_error.sv'); const uriDoc = Uri.file(filePath); const documentWorkspace = await workspace.openTextDocument(uriDoc); const document: TextDocument = castTextDocument(documentWorkspace); const openDocNotif = mockOpenDocNotif({ version: 1, uri: filePath, text: document.getText() }); client.sendNotification(DidOpenTextDocumentNotification.type, openDocNotif); while (documents.keys().length === 0) await sleep(10); // eslint-disable-line no-await-in-loop const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(undefined).then( (result) => { assert.fail(); }, (error) => { // Success } ); }).timeout(10000); test('test #9: Diagnostics for invalid document without open document', async () => { const documentCompiler = new ANTLRBackend(); await documentCompiler.getDiagnostics(undefined).then( (result) => { assert.fail(); }, (error) => { // Success } ); }).timeout(10000); }); /** * Converts a given `document` from vscode.TextDocument to vscode-languageserver.TextDocument * * @param document the document to convert * @returns a converted document */ function castTextDocument(document: vscode.TextDocument): TextDocument { return { uri: document.uri.fsPath, languageId: document.languageId, version: document.version, getText(range?: Range): string { if (range) return document.getText(castRange(range)); return document.getText(); }, lineCount: document.lineCount, positionAt(offset: number): Position { const position = document.positionAt(offset); return { line: position.line, character: position.character }; }, offsetAt(position: Position) { return document.offsetAt(castPosition(position)); } }; } /** * Converts a given `range` from vscode-languageserver.Range to vscode.Range * * @param document the range to convert * @returns a converted range */ function castRange(range: Range) { const startOld = range.start; const endOld = range.end; const start = new vscode.Position(startOld.line, startOld.character); const end = new vscode.Position(endOld.line, endOld.character); return new vscode.Range(start, end); } /** * Converts a given `position` from vscode-languageserver.Position to vscode.Position * * @param document the position to convert * @returns a converted position */ function castPosition(position: Position) { return new vscode.Position(position.line, position.character); }
the_stack
import * as assert from "@esfx/internal-assert"; import * as fn from "@esfx/async-iter-fn"; import * as sync_fn from "@esfx/iter-fn"; import { ConsumeAsyncOptions } from "@esfx/async-iter-fn"; import { toAsyncIterable } from '@esfx/async-iter-fromsync'; import { AsyncHierarchyIterable, AsyncOrderedHierarchyIterable } from '@esfx/async-iter-hierarchy'; import { AsyncOrderedIterable } from "@esfx/async-iter-ordered"; import { IndexedCollection } from '@esfx/collection-core'; import { HashMap } from '@esfx/collections-hashmap'; import { HashSet } from '@esfx/collections-hashset'; import { Comparer, Comparison, Equaler, EqualityComparison } from '@esfx/equatable'; import { Index } from "@esfx/interval"; import { Grouping, HierarchyGrouping } from '@esfx/iter-grouping'; import { Hierarchical, HierarchyIterable, HierarchyProvider, OrderedHierarchyIterable } from '@esfx/iter-hierarchy'; import { Lookup } from '@esfx/iter-lookup'; import { OrderedIterable } from "@esfx/iter-ordered"; import { HierarchyPage, Page } from '@esfx/iter-page'; import { Query, OrderedQuery, HierarchyQuery, OrderedHierarchyQuery, UnorderedQueryFlow } from '@esfx/iter-query'; export { ConsumeAsyncOptions }; const kSource = Symbol("[[Source]]"); export type AsyncUnorderedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? AsyncHierarchyQuery<TNode, TNode & T> : AsyncQuery<T>; export type AsyncOrderedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? AsyncOrderedHierarchyQuery<TNode, TNode & T> : AsyncOrderedQuery<T>; export type AsyncQueryFlow<S, T> = S extends AsyncOrderedIterable<any> | OrderedIterable<any> ? AsyncOrderedQueryFlow<S, T> : AsyncUnorderedQueryFlow<S, T>; export type AsyncPagedQueryFlow<S, T> = S extends Hierarchical<infer TNode> ? AsyncQuery<HierarchyPage<TNode, TNode & T>> : AsyncQuery<Page<T>>; export type AsyncGroupedQueryFlow<S, K, T> = S extends Hierarchical<infer TNode> ? AsyncQuery<HierarchyGrouping<K, TNode, TNode & T>> : AsyncQuery<Grouping<K, T>>; export type AsyncHierarchyQueryFlow<S, TNode extends (T extends TNode ? unknown : never), T> = S extends AsyncOrderedIterable<any> | OrderedIterable<any> ? AsyncOrderedHierarchyQuery<TNode, TNode & T> : AsyncHierarchyQuery<TNode, TNode & T>; export type AsyncMergeQueryFlow<L, R, T> = L extends Hierarchical<infer LTNode> ? R extends Hierarchical<infer RTNode> ? AsyncHierarchyQuery<LTNode | RTNode, LTNode & T | RTNode & T> : AsyncHierarchyQuery<LTNode, LTNode & T> : R extends Hierarchical<infer RTNode> ? AsyncHierarchyQuery<RTNode, RTNode & T> : AsyncQuery<T>; /** * Creates a `AsyncQuery` from an `AsyncIterable` or `Iterable` source. */ export function fromAsync<TNode, T extends TNode>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>): AsyncOrderedHierarchyQuery<TNode, T>; export function fromAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyQuery<TNode, T>; export function fromAsync<TNode, T extends TNode>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, provider: HierarchyProvider<TNode>): AsyncOrderedHierarchyQuery<TNode, T>; export function fromAsync<TNode, T extends TNode>(source: AsyncIterable<T> | Iterable<T>, provider: HierarchyProvider<TNode>): AsyncHierarchyQuery<TNode, T>; export function fromAsync<T>(source: AsyncOrderedIterable<T> | OrderedIterable<T>): AsyncOrderedQuery<T>; export function fromAsync<T extends readonly unknown[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; export function fromAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; export function fromAsync<TNode, T extends TNode>(source: AsyncIterable<T> | Iterable<T>, provider?: HierarchyProvider<TNode>): AsyncQuery<TNode | T> { return AsyncQuery.from(source, provider!); } function getSource<TNode, T extends TNode>(source: AsyncOrderedHierarchyIterable<TNode, T>): AsyncOrderedHierarchyIterable<TNode, T>; function getSource<TNode, T extends TNode>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>): AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>; function getSource<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, T>; function getSource<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>; function getSource<T>(source: AsyncOrderedIterable<T>): AsyncOrderedIterable<T>; function getSource<T>(source: AsyncOrderedIterable<T> | OrderedIterable<T>): AsyncOrderedIterable<T> | OrderedIterable<T>; function getSource<T>(source: AsyncIterable<T>): AsyncIterable<T>; function getSource<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> | Iterable<PromiseLike<T> | T>; function getSource<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncIterable<T> | Iterable<PromiseLike<T> | T> { if (source instanceof AsyncQuery) { return (source as AsyncQuery<T>)[kSource]; } return source; } function wrapResultSelector<I, O, R>(query: AsyncQuery<any>, selector: ((inner: I, outer: Query<O>) => R)): ((inner: I, outer: Iterable<O>) => R); function wrapResultSelector<I, O, R>(query: AsyncQuery<any>, selector: ((inner: I, outer: Query<O>) => R) | undefined): ((inner: I, outer: Iterable<O>) => R) | undefined; function wrapResultSelector<I, O, R>(query: AsyncQuery<any>, selector: ((inner: I, outer: Query<O>) => R) | undefined) { if (typeof selector === "function") { return (inner: I, outer: Iterable<O>) => selector(inner, query["_fromSync"](outer)); } return selector; } function wrapPageSelector<S extends AsyncQuery<any>, T, R>(query: S, selector: ((page: number, offset: number, values: Query<T>) => R)): (page: number, offset: number, values: Iterable<T>) => R; function wrapPageSelector<S extends AsyncQuery<any>, T, R>(query: S, selector: ((page: number, offset: number, values: Query<T>) => R) | undefined): ((page: number, offset: number, values: Iterable<T>) => R) | undefined; function wrapPageSelector<S extends AsyncQuery<any>, T, R>(query: S, selector: ((page: number, offset: number, values: Query<T>) => R) | undefined) { if (typeof selector === "function") { return (page: number, offset: number, values: Iterable<T>) => selector(page, offset, query["_fromSync"](values)); } return selector; } function wrapSpans(query: AsyncQuery<any>) { return <T>([left, right]: [Iterable<T>, AsyncIterable<T> | Iterable<PromiseLike<T> | T>]): [Query<T>, AsyncQuery<T>] => { return [query["_fromSync"](left), query["_fromAsync"](right)]; }; }; /** * A `AsyncQuery` represents a series of operations that act upon an `Iterable` or ArrayLike. Evaluation of * these operations is deferred until the either a scalar value is requested from the `AsyncQuery` or the * `AsyncQuery` is iterated. */ export class AsyncQuery<T> implements AsyncIterable<T> { private [kSource]: AsyncIterable<T>; /** * Creates an `AsyncQuery` from an `AsyncIterable` source. * * @param source An `AsyncIterable` object. */ constructor(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>) { assert.mustBeAsyncOrSyncIterableObject(source, "source"); this[kSource] = getSource(toAsyncIterable(source)); } // #region Query /** * Creates an `AsyncQuery` from an `AsyncIterable` or `Iterable` source. * * @category Query */ static from<TNode, T extends TNode>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>): AsyncOrderedHierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, provider: HierarchyProvider<TNode>): AsyncOrderedHierarchyQuery<TNode, T>; static from<TNode, T extends TNode>(source: AsyncIterable<T> | Iterable<T>, provider: HierarchyProvider<TNode>): AsyncHierarchyQuery<TNode, T>; static from<T>(source: AsyncOrderedIterable<T> | OrderedIterable<T>): AsyncOrderedQuery<T>; static from<T extends readonly unknown[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; static from<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; static from(source: AsyncIterable<any> | Iterable<any>, provider?: HierarchyProvider<any>): AsyncQuery<any> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeTypeOrUndefined(HierarchyProvider.hasInstance, provider, "provider"); if (provider) source = fn.toHierarchyAsync(source, provider); return source instanceof AsyncQuery ? source : AsyncOrderedHierarchyIterable.hasInstance(source) || OrderedHierarchyIterable.hasInstance(source) ? new AsyncOrderedHierarchyQuery(source) : AsyncHierarchyIterable.hasInstance(source) || HierarchyIterable.hasInstance(source) ? new AsyncHierarchyQuery(source) : AsyncOrderedIterable.hasInstance(source) || OrderedIterable.hasInstance(source) ? new AsyncOrderedQuery(source) : new AsyncQuery(source); } /** * Creates a `AsyncQuery` for the provided elements. * * @param elements The elements of the `AsyncQuery`. * @category Query */ static of<T>(...elements: (PromiseLike<T> | T)[]): AsyncQuery<T>; static of<T>(): AsyncQuery<T> { return this.from(arguments); } /** * Creates a `AsyncQuery` with no elements. * * @category Query */ static empty<T>(): AsyncQuery<T> { return this.from(fn.emptyAsync<T>()); } /** * Creates a `AsyncQuery` over a single element. * * @param value The only element for the `AsyncQuery`. * @category Query */ static once<T>(value: PromiseLike<T> | T): AsyncQuery<T> { return this.from(fn.onceAsync(value)); } /** * Creates a `AsyncQuery` for a value repeated a provided number of times. * * @param value The value for each element of the `AsyncQuery`. * @param count The number of times to repeat the value. * @category Query */ static repeat<T>(value: PromiseLike<T> | T, count: number): AsyncQuery<T> { return this.from(fn.repeatAsync(value, count)); } /** * Creates a `AsyncQuery` over a range of numbers. * * @param start The starting number of the range. * @param end The ending number of the range. * @param increment The amount by which to change between each itereated value. * @category Query */ static range(start: number, end: number, increment?: number) { return this.from(sync_fn.range(start, end, increment)); } /** * Creates a `AsyncQuery` that repeats the provided value forever. * * @param value The value for each element of the `AsyncQuery`. * @category Query */ static continuous<T>(value: PromiseLike<T> | T) { return this.from(fn.continuousAsync(value)); } /** * Creates a `AsyncQuery` whose values are provided by a callback executed a provided number of * times. * * @param count The number of times to execute the callback. * @param generator The callback to execute. * @category Query */ static generate<T>(count: number, generator: (offset: number) => PromiseLike<T> | T) { return this.from(fn.generateAsync(count, generator)); } /** * Creates a `AsyncQuery` that, when iterated, consumes the provided `AsyncIterator`. * * @param iterator An `AsyncIterator` object. * @category Query */ static consume<T>(iterator: AsyncIterator<T>, options?: ConsumeAsyncOptions) { return this.from(fn.consumeAsync(iterator, options)); } // #endregion Query // #region Subquery /** * Creates a subquery whose elements match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filter<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncUnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filter(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T>; filter(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { return this._fromAsync(fn.filterAsync(getSource(this), predicate)); } /** * Creates a subquery where the selected key for each element matches the supplied predicate. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.filterByAsync(getSource(this), keySelector, predicate)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements are neither `null` nor `undefined`. * * @category Subquery */ filterDefined(): AsyncUnorderedQueryFlow<this, NonNullable<T>> { return this._fromAsync(fn.filterDefinedAsync(getSource(this))) as AsyncUnorderedQueryFlow<this, NonNullable<T>>; } /** * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ filterDefinedBy<K>(keySelector: (element: T) => K): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.filterDefinedByAsync(getSource(this), keySelector)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements match the supplied predicate. * * NOTE: This is an alias for `filter`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ where<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncUnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements match the supplied predicate. * * NOTE: This is an alias for `filter`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ where(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T>; where(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { return this.filter(predicate); } /** * Creates a subquery where the selected key for each element matches the supplied predicate. * * NOTE: This is an alias for `filterBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this.filterBy(keySelector, predicate); } /** * Creates a subquery whose elements are neither `null` nor `undefined`. * * NOTE: This is an alias for `filterDefined`. * * @category Subquery */ whereDefined(): AsyncUnorderedQueryFlow<this, NonNullable<T>> { return this.filterDefined(); } /** * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. * * NOTE: This is an alias for `filterDefinedBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ whereDefinedBy<K>(keySelector: (element: T) => K): AsyncUnorderedQueryFlow<this, T> { return this.filterDefinedBy(keySelector) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNot<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncUnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T>; filterNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { return this._fromAsync(fn.filterNotAsync(getSource(this), predicate)); } /** * Creates a subquery where the selected key for each element does not match the supplied predicate. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ filterNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.filterNotByAsync(getSource(this), keySelector, predicate)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery where the selected key for each element is either `null` or `undefined`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ filterNotDefinedBy<K>(keySelector: (element: T) => K): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.filterNotDefinedByAsync(getSource(this), keySelector)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements do not match the supplied predicate. * * NOTE: This is an alias for `filterNot`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNot<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncUnorderedQueryFlow<this, U>; /** * Creates a subquery whose elements do not match the supplied predicate. * * NOTE: This is an alias for `filterNot`. * * @param predicate A callback used to match each element. * @param predicate.element The element to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T>; whereNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { return this.filterNot(predicate); } /** * Creates a subquery where the selected key for each element does not match the supplied predicate. * * NOTE: This is an alias for `filterNotBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @param predicate A callback used to match each key. * @param predicate.key The key to test. * @param predicate.offset The offset from the start of the source iterable. * @category Subquery */ whereNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this.filterNotBy(keySelector, predicate) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery where the selected key for each element is either `null` or `undefined`. * * NOTE: This is an alias for `filterNotDefinedBy`. * * @param keySelector A callback used to select the key for each element. * @param keySelector.element The element from which to select a key. * @category Subquery */ whereNotDefinedBy<K>(keySelector: (element: T) => K): AsyncUnorderedQueryFlow<this, T> { return this.filterNotDefinedBy(keySelector) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery by applying a callback to each element. * * @param selector A callback used to map each element. * @param selector.element The element to map. * @param selector.offset The offset from the start of the source iterable. * @category Subquery */ map<U>(selector: (element: T, offset: number) => PromiseLike<U> | U): AsyncQuery<U> { return this._fromAsync(fn.mapAsync(getSource(this), selector)); } /** * Creates a subquery by applying a callback to each element. * * NOTE: This is an alias for `map`. * * @param selector A callback used to map each element. * @param selector.element The element to map. * @param selector.offset The offset from the start of the source `Iterable`. * @category Subquery */ select<U>(selector: (element: T, offset: number) => PromiseLike<U> | U): AsyncQuery<U> { return this.map(selector); } /** * Creates a subquery that iterates the results of applying a callback to each element. * * @param projection A callback used to map each element into an `AsyncIterable` or `Iterable` object. * @param projection.element The element to map. * @category Subquery */ flatMap<U>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>): AsyncQuery<U>; /** * Creates a subquery that iterates the results of applying a callback to each element. * * @param projection A callback used to map each element into an `AsyncIterable` or `Iterable` object. * @param projection.element The outer element to map. * @param resultSelector An optional callback used to map the outer and projected inner elements. * @param resultSelector.element The outer element to map. * @param resultSelector.innerElement An inner element produced by the `projection` of the outer element. * @category Subquery */ flatMap<U, R>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector: (element: T, innerElement: U) => PromiseLike<R> | R): AsyncQuery<R>; flatMap<U, R>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector?: (element: T, innerElement: U) => PromiseLike<R> | R) { return this._fromAsync(fn.flatMapAsync(getSource(this), projection, resultSelector!)); } /** * Creates a subquery that iterates the results of applying a callback to each element. * * NOTE: This is an alias for `flatMap`. * * @param projection A callback used to map each element into an iterable. * @param projection.element The element to map. * @category Subquery */ selectMany<U>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>): AsyncQuery<U>; /** * Creates a subquery that iterates the results of applying a callback to each element. * * NOTE: This is an alias for `flatMap`. * * @param projection A callback used to map each element into an iterable. * @param projection.element The element to map. * @param resultSelector An optional callback used to map the outer and projected inner elements. * @param resultSelector.element The outer element to map. * @param resultSelector.innerElement An inner element produced by the `projection` of the outer element. * @category Subquery */ selectMany<U, R>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector: (element: T, innerElement: U) => PromiseLike<R> | R): AsyncQuery<R>; selectMany<U, R>(projection: (element: T) => AsyncIterable<U> | Iterable<PromiseLike<U> | U>, resultSelector?: (element: T, innerElement: U) => PromiseLike<R> | R) { return this.flatMap(projection, resultSelector!); } /** * Lazily invokes a callback as each element of the `AsyncQuery` is iterated. * * @param callback The callback to invoke. * @param callback.element An element of the source. * @param callback.offset The offset from the start of the source iterable. * @category Subquery */ tap(callback: (element: T, offset: number) => PromiseLike<void> | void): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.tapAsync(getSource(this), callback)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery whose elements are in the reverse order. * * @category Subquery */ reverse(): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.reverseAsync(getSource(this))) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery with every instance of the specified value removed. * * @param values The values to exclude. * @category Subquery */ exclude(...values: [PromiseLike<T> | T, ...(PromiseLike<T> | T)[]]): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.excludeAsync(getSource(this), ...values)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements up to the supplied * count. * * @param count The number of elements to drop. * @category Subquery */ drop(count: number): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.dropAsync(getSource(this), count)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the last elements up to the supplied * count. * * @param count The number of elements to drop. * @category Subquery */ dropRight(count: number): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.dropRightAsync(getSource(this), count)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements that match * the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ dropWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.dropWhileAsync(getSource(this), predicate)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements that don't match * the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ dropUntil(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.dropUntilAsync(getSource(this), predicate)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing all elements except the first elements up to the supplied * count. * * NOTE: This is an alias for `drop`. * * @param count The number of elements to skip. * @category Subquery */ skip(count: number): AsyncUnorderedQueryFlow<this, T> { return this.drop(count); } /** * Creates a subquery containing all elements except the last elements up to the supplied * count. * * NOTE: This is an alias for `dropRight`. * * @param count The number of elements to skip. * @category Subquery */ skipRight(count: number): AsyncUnorderedQueryFlow<this, T> { return this.dropRight(count); } /** * Creates a subquery containing all elements except the first elements that match * the supplied predicate. * * NOTE: This is an alias for `dropWhile`. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ skipWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this.dropWhile(predicate); } /** * Creates a subquery containing all elements except the first elements that don't match * the supplied predicate. * * NOTE: This is an alias for `dropUntil`. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ skipUntil(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this.dropUntil(predicate); } /** * Creates a subquery containing the first elements up to the supplied * count. * * @param count The number of elements to take. * @category Subquery */ take(count: number): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.takeAsync(getSource(this), count)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing the last elements up to the supplied * count. * * @param count The number of elements to take. * @category Subquery */ takeRight(count: number): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.takeRightAsync(getSource(this), count)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery containing the first elements that match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ takeWhile<U extends T>(predicate: (element: T) => element is U): AsyncUnorderedQueryFlow<this, U>; /** * Creates a subquery containing the first elements that match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. */ takeWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T>; takeWhile(predicate: (element: T) => PromiseLike<boolean> | boolean) { return this._fromAsync(fn.takeWhileAsync(getSource(this), predicate)); } /** * Creates a subquery containing the first elements that do not match the supplied predicate. * * @param predicate A callback used to match each element. * @param predicate.element The element to match. * @category Subquery */ takeUntil(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.takeUntilAsync(getSource(this), predicate)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ intersect<R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, equaler?: Equaler<T>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ intersect(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncQuery<T>; intersect(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): any { return this._fromAsync(fn.intersectAsync(getSource(this), right, equaler)); } /** * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ intersectBy<K, R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ intersectBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<T>; intersectBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._fromAsync(fn.intersectByAsync(getSource(this), getSource(right), keySelector, keyEqualer)); } /** * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ union<R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, equaler?: Equaler<T>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ union(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncQuery<T>; union(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): any { return this._fromAsync(fn.unionAsync(getSource(this), getSource(right), equaler)); } /** * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ unionBy<K, R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ unionBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<T>; unionBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._fromAsync(fn.unionByAsync(getSource(this), getSource(right), keySelector, keyEqualer)); } /** * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ except(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.exceptAsync(getSource(this), getSource(right), equaler)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ exceptBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.exceptByAsync(getSource(this), getSource(right), keySelector, keyEqualer)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`. * * NOTE: This is an alias for `except`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ relativeComplement(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncUnorderedQueryFlow<this, T> { return this.except(right, equaler); } /** * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * NOTE: This is an alias for `exceptBy`. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ relativeComplementBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncUnorderedQueryFlow<this, T> { return this.exceptBy(right, keySelector, keyEqualer) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ symmetricDifference<R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, equaler?: Equaler<T>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Subquery */ symmetricDifference(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncQuery<T>; symmetricDifference(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): any { return this._fromAsync(fn.symmetricDifferenceAsync(getSource(this), getSource(right), equaler)); } /** * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ symmetricDifferenceBy<K, R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ symmetricDifferenceBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<T>; symmetricDifferenceBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): any { return this._fromAsync(fn.symmetricDifferenceByAsync(getSource(this), getSource(right), keySelector, keyEqualer)); } // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`. // * // * NOTE: This is an alias for `symmetricDifference`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // xor<TNode, T extends TNode>(this: AsyncQuery<T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T>; // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`. // * // * NOTE: This is an alias for `symmetricDifference`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // xor(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncQuery<T>; // xor(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncQuery<T> | AsyncHierarchyQuery<T> { // return this.symmetricDifference(right, equaler); // } // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * NOTE: This is an alias for `symmetricDifferenceBy`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // xorBy<TNode, T extends TNode, K>(this: AsyncQuery<T>, right: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T>; // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * NOTE: This is an alias for `symmetricDifferenceBy`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // xorBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<T>; // xorBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<T> | AsyncHierarchyQuery<T> { // return this.symmetricDifferenceBy(right, keySelector, keyEqualer); // } /** * Creates a subquery that concatenates this `AsyncQuery` with another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @category Subquery */ concat<R extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>>(right: R): AsyncMergeQueryFlow<this, R, T>; /** * Creates a subquery that concatenates this `AsyncQuery` with another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @category Subquery */ concat(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; concat(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): any { return this._fromAsync(fn.concatAsync(getSource(this), getSource(right))); } /** * Creates a subquery for the distinct elements of this `AsyncQuery`. * * @param equaler An `Equaler` object used to compare key equality. * @category Subquery */ distinct(equaler?: Equaler<T>): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.distinctAsync(getSource(this), equaler)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the distinct elements of this `AsyncQuery`. * * @param keySelector A callback used to select the key to determine uniqueness. * @param keySelector.value An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ distinctBy<K>(keySelector: (value: T) => K, keyEqualer?: Equaler<K>): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.distinctByAsync(getSource(this), keySelector, keyEqualer)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `AsyncQuery` with the provided value appended to the end. * * @param value The value to append. * @category Subquery */ append(value: PromiseLike<T> | T): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.appendAsync(getSource(this), value)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `AsyncQuery` with the provided value prepended to the beginning. * * @param value The value to prepend. * @category Subquery */ prepend(value: PromiseLike<T> | T): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.prependAsync(getSource(this), value)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery for the elements of this `AsyncQuery` with the provided range * patched into the results. * * @param start The offset at which to patch the range. * @param skipCount The number of elements to skip from start. * @param range The range to patch into the result. * @category Subquery */ patch(start: number, skipCount?: number, range?: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.patchAsync(getSource(this), start, skipCount, range && getSource(range))) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery that contains the provided default value if this `AsyncQuery` * contains no elements. * * @param defaultValue The default value. * @category Subquery */ defaultIfEmpty(defaultValue: PromiseLike<T> | T): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.defaultIfEmptyAsync(getSource(this), defaultValue)) as AsyncUnorderedQueryFlow<this, T>; } /** * Creates a subquery that splits this `AsyncQuery` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param pageSize The number of elements per page. * @category Subquery */ pageBy(pageSize: number): AsyncPagedQueryFlow<this, T>; /** * Creates a subquery that splits this `AsyncQuery` into one or more pages. * While advancing from page to page is evaluated lazily, the elements of the page are * evaluated eagerly. * * @param pageSize The number of elements per page. * @category Subquery */ pageBy<R>(pageSize: number, pageSelector: (page: number, offset: number, values: UnorderedQueryFlow<this, T>) => R): AsyncQuery<R>; pageBy<R>(pageSize: number, pageSelector?: (page: number, offset: number, values: UnorderedQueryFlow<this, T>) => R) { return this._fromAsync(fn.pageByAsync(getSource(this), pageSize, wrapPageSelector(this, pageSelector as (page: number, offset: number, values: Query<T>) => R))); } /** * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @category Subquery */ spanMap<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncGroupedQueryFlow<this, K, T>; /** * Creates a subquery whose values are computed from each element of the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @category Subquery */ spanMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): AsyncGroupedQueryFlow<this, K, V>; /** * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param spanSelector A callback used to select a result from a contiguous range. * @param spanSelector.key The key for the span. * @param spanSelector.elements The elements for the span. * @category Subquery */ spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, spanSelector: (key: K, elements: Query<V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; /** * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param spanSelector A callback used to select a result from a contiguous range. * @param spanSelector.key The key for the span. * @param spanSelector.elements The elements for the span. * @category Subquery */ spanMap<K, R>(keySelector: (element: T) => K, elementSelector: undefined, spanSelector: (key: K, elements: Query<T>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K>, spanSelector?: ((key: K, elements: Query<T | V>) => Grouping<K, T | V> | PromiseLike<R> | R) | Equaler<K>, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { keyEqualer = elementSelector; elementSelector = fn.identity; } if (typeof spanSelector === "object") { keyEqualer = spanSelector; spanSelector = Grouping.from; } return this._fromAsync(fn.spanMapAsync(getSource(this), keySelector, elementSelector!, wrapResultSelector(this, spanSelector!), keyEqualer)); } /** * Groups each element of this `AsyncQuery` by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncGroupedQueryFlow<this, K, T>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): AsyncGroupedQueryFlow<this, K, V>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param resultSelector A callback used to select a result from a group. * @param resultSelector.key The key for the group. * @param resultSelector.elements The elements for the group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, resultSelector: (key: K, elements: Query<V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; /** * Groups each element by its key. * * @param keySelector A callback used to select the key for an element. * @param keySelector.element An element from which to select a key. * @param elementSelector A callback used to select a value for an element. * @param elementSelector.element An element from which to select a value. * @param resultSelector A callback used to select a result from a group. * @param resultSelector.key The key for the group. * @param resultSelector.elements The elements for the group. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Subquery */ groupBy<K, R>(keySelector: (element: T) => K, elementSelector: undefined, resultSelector: (key: K, elements: Query<T>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => PromiseLike<V> | V) | Equaler<K>, resultSelector?: ((key: K, elements: Query<V>) => PromiseLike<R> | R) | Equaler<K>, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { resultSelector = elementSelector; elementSelector = undefined; } if (typeof resultSelector === "object") { keyEqualer = resultSelector; resultSelector = undefined; } return this._fromAsync(fn.groupByAsync(getSource(this), keySelector, elementSelector!, wrapResultSelector(this, resultSelector!), keyEqualer)); } /** * Creates a subquery containing the cumulative results of applying the provided callback to each element. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Subquery */ scan(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): AsyncQuery<T>; /** * Creates a subquery containing the cumulative results of applying the provided callback to each element. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Subquery */ scan<U>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U): AsyncQuery<U>; scan(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T): AsyncQuery<T> { return this._fromAsync(arguments.length > 1 ? fn.scanAsync(getSource(this), accumulator, seed as T) : fn.scanAsync(getSource(this), accumulator)); } /** * Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Subquery */ scanRight(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): AsyncQuery<T>; /** * Creates a subquery containing the cumulative results of applying the provided callback to each element in reverse. * * @param accumulator The callback used to compute each result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Subquery */ scanRight<U>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed?: U): AsyncQuery<U>; scanRight(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T): AsyncQuery<T> { return this._fromAsync(arguments.length > 1 ? fn.scanRightAsync(getSource(this), accumulator, seed as T) : fn.scanRightAsync(getSource(this), accumulator)); } /** * Pass the entire `AsyncQuery` to the provided callback, creating a new `AsyncQuery` from the result. * * @param callback A callback function. * @param callback.source The outer `AsyncQuery`. * @category Subquery */ through<R extends AsyncIterable<any> | Iterable<any>>(callback: (source: this) => R): AsyncQueryFlow<R, R extends AsyncIterable<infer U> ? U : R extends Iterable<infer U> ? U extends PromiseLike<infer P> ? P : U : unknown> { return this._fromAsync(fn.intoAsync(this, callback)) as AsyncQueryFlow<R, R extends AsyncIterable<infer U> ? U : R extends Iterable<infer U> ? U extends PromiseLike<infer P> ? P : U : unknown>; } /** * Eagerly evaluate the `AsyncQuery`, returning a new `AsyncQuery`. * * @category Subquery */ materialize(): AsyncUnorderedQueryFlow<this, T> { return this._fromAsync(fn.materializeAsync(getSource(this))) as AsyncUnorderedQueryFlow<this, T>; } // #endregion Subquery // #region Join /** * Creates a grouped subquery for the correlated elements of this `AsyncQuery` and another `AsyncIterable` or `Iterable` object. * * @param inner An `AsyncIterable` or `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `AsyncQuery`. * @param innerKeySelector A callback used to select the key for an element in the other `Iterable` object. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ groupJoin<I, K, R>(inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T, inner: Query<I>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R> { return this._fromAsync(fn.groupJoinAsync(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, wrapResultSelector(this, resultSelector), keyEqualer)); } /** * Creates a subquery for the correlated elements of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param inner An `AsyncIterable` or `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `AsyncQuery`. * @param innerKeySelector A callback used to select the key for an element in the other Iterable. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ join<I, K, R>(inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T, inner: I) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R> { return this._fromAsync(fn.joinAsync(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, resultSelector, keyEqualer)); } /** * Creates a subquery for the correlated elements of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. * * @param inner An `AsyncIterable` or `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in this `AsyncQuery`. * @param innerKeySelector A callback used to select the key for an element in the other Iterable. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ fullJoin<I, K, R>(inner: AsyncIterable<I> | Iterable<PromiseLike<I> | I>, outerKeySelector: (element: T) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: T | undefined, inner: I | undefined) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R> { return this._fromAsync(fn.fullJoinAsync(getSource(this), getSource(inner), outerKeySelector, innerKeySelector, resultSelector, keyEqualer)); } /** * Creates a subquery that combines this `AsyncQuery` with another `AsyncIterable` or `Iterable` by combining elements * in tuples. * * @param right An `AsyncIterable` or `Iterable` object. * @category Join */ zip<U>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>): AsyncQuery<[T, U]>; /** * Creates a subquery that combines this `AsyncQuery` with another `AsyncIterable` or `Iterable` by combining elements * using the supplied callback. * * @param right An `AsyncIterable` or `Iterable` object. * @param selector A callback used to combine two elements. * @category Join */ zip<U, R>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, selector: (left: T, right: U) => PromiseLike<R> | R): AsyncQuery<R>; zip<U, R>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, selector?: (left: T, right: U) => PromiseLike<R> | R): AsyncQuery<R> { return this._fromAsync(fn.zipAsync(getSource(this), getSource(right), selector!)); } // #endregion Join // #region Order /** * Creates an ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ orderBy<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedQueryFlow<this, T> { return this._fromAsync(fn.orderByAsync(getSource(this), keySelector, comparer)) as AsyncOrderedQueryFlow<this, T>; } /** * Creates an ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ orderByDescending<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedQueryFlow<this, T> { return this._fromAsync(fn.orderByDescendingAsync(getSource(this), keySelector, comparer)) as AsyncOrderedQueryFlow<this, T>; } // #endregion Order // #region Hierarchy /** * Creates an `AsyncHierarchyQuery` using the provided `HierarchyProvider`. * * @param provider A `HierarchyProvider`. * @category Hierarchy */ toHierarchy<TNode extends (T extends TNode ? unknown : never)>(provider: HierarchyProvider<TNode>): AsyncHierarchyQueryFlow<this, TNode, T> { return this._fromAsync(fn.toHierarchyAsync(getSource(this) as AsyncIterable<TNode & T>, provider)) as AsyncHierarchyQueryFlow<this, TNode, T>; } // #endregion Hierarchy // #region Scalar /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @category Scalar */ reduce(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): Promise<T>; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @category Scalar */ reduce<U>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U>, seed: U, resultSelector?: (result: U, count: number) => PromiseLike<U> | U): Promise<U>; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param accumulator the callback used to compute the result. * @param accumulator.current The current accumulated value. * @param accumulator.element The value to accumulate. * @param accumulator.offset The offset from the start of the underlying `Iterable`. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ reduce<U, R>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U, resultSelector: (result: U, count: number) => PromiseLike<R> | R): Promise<R>; reduce(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T, resultSelector?: (result: T, count: number) => PromiseLike<T> | T): Promise<T> { return arguments.length > 1 ? fn.reduceAsync(getSource(this), accumulator, seed!, resultSelector!) : fn.reduceAsync(getSource(this), accumulator); } /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @category Scalar */ reduceRight(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): Promise<T>; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @category Scalar */ reduceRight<U>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U, resultSelector?: (result: U, count: number) => PromiseLike<U> | U): Promise<U>; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ reduceRight<U, R>(accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U, resultSelector: (result: U, count: number) => PromiseLike<R> | R): Promise<R>; reduceRight(accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T, resultSelector?: (result: T, count: number) => PromiseLike<T> | T): Promise<T> { return arguments.length > 1 ? fn.reduceRightAsync(getSource(this), accumulator, seed!, resultSelector!) : fn.reduceRightAsync(getSource(this), accumulator); } /** * Counts the number of elements in the `AsyncQuery`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ count(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<number> { return fn.countAsync(getSource(this), predicate); } /** * Gets the first element in the `AsyncQuery`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ first<U extends T>(predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the first element in the `AsyncQuery`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ first(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; first(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined> { return fn.firstAsync(getSource(this), predicate); } /** * Gets the last element in the `AsyncQuery`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ last<U extends T>(predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the last element in the `AsyncQuery`, optionally filtering elements using the supplied * callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ last(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; last(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined> { return fn.lastAsync(getSource(this), predicate); } /** * Gets the only element in the `AsyncQuery`, or returns `undefined`. * * @param predicate An optional callback used to match each element. * @category Scalar */ single<U extends T>(predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the only element in the `AsyncQuery`, or returns undefined. * * @param predicate An optional callback used to match each element. * @category Scalar */ single(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; single(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined> { return fn.singleAsync(getSource(this), predicate); } /** * Gets the minimum element in the `AsyncQuery`, optionally comparing elements using the supplied * callback. * * @param comparer An optional callback used to compare two elements. * @category Scalar */ min(comparer?: Comparison<T> | Comparer<T>): Promise<T | undefined> { return fn.minAsync(getSource(this), comparer); } /** * Gets the minimum element by its key in the `AsyncQuery`, optionally comparing the keys of each element using the supplied callback. * * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ minBy<K>(keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): Promise<T | undefined> { return fn.minByAsync(getSource(this), keySelector, keyComparer); } /** * Gets the maximum element in the `AsyncQuery`, optionally comparing elements using the supplied * callback. * * @param comparer An optional callback used to compare two elements. * @category Scalar */ max(comparer?: Comparison<T> | Comparer<T>): Promise<T | undefined> { return fn.maxAsync(getSource(this), comparer); } /** * Gets the maximum element by its key in the `AsyncQuery`, optionally comparing the keys of each element using the supplied callback. * * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ maxBy<K>(keySelector: (element: T) => K, keyComparer?: Comparison<K> | Comparer<K>): Promise<T | undefined> { return fn.maxByAsync(getSource(this), keySelector, keyComparer); } /** * Computes the sum for a series of numbers. * * @category Scalar */ sum(): Promise<T extends number ? number : never>; /** * Computes the sum for a series of numbers. * * @category Scalar */ sum(elementSelector: (element: T) => PromiseLike<number> | number): Promise<number>; sum(elementSelector?: (element: T) => PromiseLike<number> | number): Promise<number> { return fn.sumAsync(getSource(this), elementSelector!); } /** * Computes the average for a series of numbers. * * @category Scalar */ average(): Promise<T extends number ? number : never>; /** * Computes the average for a series of numbers. * * @category Scalar */ average(elementSelector: (element: T) => PromiseLike<number> | number): Promise<number>; average(elementSelector?: (element: T) => PromiseLike<number> | number): Promise<number> { return fn.averageAsync(getSource(this), elementSelector!); } /** * Computes a scalar value indicating whether the `AsyncQuery` contains any elements, * optionally filtering the elements using the supplied callback. * * @param predicate An optional callback used to match each element. * @category Scalar */ some(predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean> { return fn.someAsync(getSource(this), predicate); } /** * Computes a scalar value indicating whether all elements of the `AsyncQuery` * match the supplied callback. * * @param predicate A callback used to match each element. * @category Scalar */ every(predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean>; every(predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean> { return fn.everyAsync(getSource(this), predicate); } /** * Computes a scalar value indicating whether every element in this `AsyncQuery` corresponds to a matching element * in another `AsyncIterable` or `Iterable` at the same position. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ corresponds(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether every element in this `AsyncQuery` corresponds to a matching element * in another `AsyncIterable` or `Iterable` at the same position. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ corresponds<U>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; corresponds(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean> { return fn.correspondsAsync(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether every element in this `AsyncQuery` corresponds to a matching element * in another `AsyncIterable` or `Iterable` at the same position. * * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @param keyEqualer An `Equaler` used to compare the equality of two keys. * @category Scalar */ correspondsBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Promise<boolean>; /** * Computes a scalar value indicating whether the key for every element in this `AsyncQuery` corresponds to a matching key * in `right` at the same position. * * @param right An `AsyncIterable` or `Iterable` object. * @param leftKeySelector A callback used to select the key for each element in this `AsyncQuery`. * @param rightKeySelector A callback used to select the key for each element in `right`. * @param keyEqualer An optional callback used to compare the equality of two keys. * @category Scalar */ correspondsBy<U, K>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, leftKeySelector: (element: T) => K, rightKeySelector: (element: U) => K, keyEqualer?: EqualityComparison<K> | Equaler<K>): Promise<boolean>; correspondsBy<U, K>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, leftKeySelector: (element: T) => K, rightKeySelector?: ((element: U) => K) | Equaler<K>, keyEqualer?: EqualityComparison<K> | Equaler<K>): Promise<boolean> { if (typeof rightKeySelector === "object") { keyEqualer = rightKeySelector; rightKeySelector = undefined; } return fn.correspondsByAsync(getSource(this), getSource(right), leftKeySelector, rightKeySelector!, keyEqualer); } /** * Computes a scalar value indicating whether the provided value is included in the `AsyncQuery`. * * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ includes(value: T, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the provided value is included in the `AsyncQuery`. * * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ includes<U>(value: U, equaler: (left: T, right: U) => boolean): Promise<boolean>; includes(value: T, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean> { return fn.includesAsync(getSource(this), value, equaler!); } /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` include * an exact sequence of elements from another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ includesSequence(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` include * an exact sequence of elements from another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ includesSequence<U>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; includesSequence(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean> { return fn.includesSequenceAsync(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` start * with the same sequence of elements in another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ startsWith(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` start * with the same sequence of elements in another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ startsWith<U>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; startsWith(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean> { return fn.startsWithAsync(getSource(this), getSource(right), equaler!); } /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` end * with the same sequence of elements in another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ endsWith(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of this `AsyncQuery` end * with the same sequence of elements in another `AsyncIterable` or `Iterable`. * * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ endsWith<U>(right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; endsWith(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean> { return fn.endsWithAsync(getSource(this), getSource(right), equaler!); } /** * Finds the value in the `AsyncQuery` at the provided offset. A negative offset starts from the * last element. * * @param offset An offset. * @category Scalar */ elementAt(offset: number | Index): Promise<T | undefined> { return fn.elementAtAsync(getSource(this), offset); } /** * Finds the value in the `AsyncQuery` at the provided offset. A negative offset starts from the * last element. * * NOTE: This is an alias for `elementAt`. * * @param offset An offset. * @category Scalar */ nth(offset: number | Index): Promise<T | undefined> { return fn.nthAsync(getSource(this), offset); } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ span<U extends T>(predicate: (element: T, offset: number) => element is U): Promise<[UnorderedQueryFlow<this, U>, AsyncUnorderedQueryFlow<this, T>]>; /** * Creates a tuple whose first element is a subquery containing the first span of * elements that match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ span(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[UnorderedQueryFlow<this, T>, AsyncUnorderedQueryFlow<this, T>]>; span(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { return fn.spanAsync(getSource(this), predicate).then(wrapSpans(this)) as Promise<[UnorderedQueryFlow<this, T>, AsyncUnorderedQueryFlow<this, T>]>; } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that do not match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * @param predicate The predicate used to match elements. * @category Scalar */ spanUntil(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[UnorderedQueryFlow<this, T>, AsyncUnorderedQueryFlow<this, T>]> { return fn.spanUntilAsync(getSource(this), predicate).then(wrapSpans(this)) as Promise<[UnorderedQueryFlow<this, T>, AsyncUnorderedQueryFlow<this, T>]>; } /** * Creates a tuple whose first element is a subquery containing the first span of * elements that do not match the supplied predicate, and whose second element is a subquery * containing the remaining elements. * * The first subquery is eagerly evaluated, while the second subquery is lazily * evaluated. * * NOTE: This is an alias for `spanUntil`. * * @param predicate The predicate used to match elements. * @category Scalar */ break(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[UnorderedQueryFlow<this, T>, AsyncUnorderedQueryFlow<this, T>]> { return this.spanUntil(predicate); } /** * Invokes a callback for each element of the `AsyncQuery`. * * @param callback The callback to invoke. * @category Scalar */ forEach(callback: (element: T, offset: number) => void | PromiseLike<void>): Promise<void> { return fn.forEachAsync(getSource(this), callback); } // /** // * Iterates over all of the elements in the `AsyncQuery`, ignoring the results. // * @category Scalar // */ // drain(): void { // fn.drainAsync(getSource(this)); // } /** * Unzips a sequence of tuples into a tuple of sequences. * * @param source An `AsyncIterable` or `Iterable` object. * @category Scalar */ unzip(): Promise<T extends readonly unknown[] | [] ? { -readonly [I in keyof T]: T[I][]; } : unknown[]>; /** * Unzips a sequence of tuples into a tuple of sequences. * * @param source An `AsyncIterable` or `Iterable` object. * @param partSelector A callback that converts a result into a tuple. * @category Scalar */ unzip<U extends readonly unknown[] | []>(partSelector: (value: T) => U): Promise<{ -readonly [I in keyof U]: U[I][]; }>; unzip<U extends readonly unknown[] | []>(partSelector?: (value: T) => U): Promise<object> { return fn.unzipAsync(getSource(this), partSelector!); } /** * Creates an Array for the elements of the `AsyncQuery`. * * @category Scalar */ toArray(): Promise<T[]>; /** * Creates an Array for the elements of the `AsyncQuery`. * * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toArray<V>(elementSelector: (element: T) => PromiseLike<V> | V): Promise<V[]>; toArray<V>(elementSelector?: (element: T) => PromiseLike<V> | V): Promise<V[]> { return fn.toArrayAsync(getSource(this), elementSelector!); } /** * Creates a `Set` for the elements of the `AsyncQuery`. * * @category Scalar */ toSet(): Promise<Set<T>>; /** * Creates a `Set` for the elements of the `AsyncQuery`. * * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toSet<V>(elementSelector: (element: T) => PromiseLike<V> | V): Promise<Set<V>>; toSet<V>(elementSelector?: (element: T) => PromiseLike<V> | V): Promise<Set<T | V>> { return fn.toSetAsync(getSource(this), elementSelector!); } /** * Creates a `HashSet` for the elements of the `AsyncQuery`. * * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ toHashSet(equaler?: Equaler<T>): Promise<HashSet<T>>; /** * Creates a `HashSet` for the elements of the `AsyncQuery`. * * @param elementSelector A callback that selects a value for each element. * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ toHashSet<V>(elementSelector: (element: T) => PromiseLike<V> | V, equaler: Equaler<V>): Promise<HashSet<V>>; toHashSet<V>(elementSelector?: ((element: T) => PromiseLike<V> | V) | Equaler<T | V>, equaler?: Equaler<T | V>): Promise<HashSet<T | V>> { return fn.toHashSetAsync(getSource(this), elementSelector as (element: T) => PromiseLike<V> | V, equaler!); } /** * Creates a `Map` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @category Scalar */ toMap<K>(keySelector: (element: T) => K): Promise<Map<K, T>>; /** * Creates a `Map` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @category Scalar */ toMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V): Promise<Map<K, V>>; toMap<K, V>(keySelector: (element: T) => K, elementSelector?: (element: T) => PromiseLike<T | V> | T | V) { return fn.toMapAsync(getSource(this), keySelector, elementSelector!); } /** * Creates a `HashMap` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toHashMap<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Promise<HashMap<K, T>>; /** * Creates a `HashMap` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toHashMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): Promise<HashMap<K, V>>; toHashMap<K, V>(keySelector: (element: T) => K, elementSelector?: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K>, keyEqualer?: Equaler<K>) { return fn.toHashMapAsync(getSource(this), keySelector, elementSelector as (element: T) => PromiseLike<T | V> | T | V, keyEqualer!); } /** * Creates a `Lookup` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toLookup<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Promise<Lookup<K, T>>; /** * Creates a `Lookup` for the elements of the `AsyncQuery`. * * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ toLookup<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): Promise<Lookup<K, V>>; toLookup<K, V>(keySelector: (element: T) => K, elementSelector?: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K>, keyEqualer?: Equaler<K>): Promise<Lookup<K, T | V>> { return fn.toLookupAsync(getSource(this), keySelector, elementSelector as (element: T) => PromiseLike<T | V> | T | V, keyEqualer!); } /** * Creates an Object for the elements of the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<TProto extends object, K extends PropertyKey>(prototype: TProto, keySelector: (element: T) => K): Promise<TProto & Record<K, T>>; /** * Creates an Object for the elements of the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<TProto extends object>(prototype: TProto, keySelector: (element: T) => PropertyKey): Promise<TProto & Record<PropertyKey, T>>; /** * Creates an Object for the elements of the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject<K extends PropertyKey>(prototype: object | null | undefined, keySelector: (element: T) => K): Promise<Record<PropertyKey, T>>; /** * Creates an Object for the elements of the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ toObject(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey): Promise<object>; /** * Creates an Object for the elements the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<TProto extends object, K extends PropertyKey, V>(prototype: TProto, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: K, element: V) => TypedPropertyDescriptor<V>): Promise<TProto & Record<K, V>>; /** * Creates an Object for the elements the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<TProto extends object, V>(prototype: TProto, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, element: V) => TypedPropertyDescriptor<V>): Promise<TProto & Record<PropertyKey, V>>; /** * Creates an Object for the elements the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<K extends PropertyKey, V>(prototype: object | null | undefined, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: K, element: V) => TypedPropertyDescriptor<V>): Promise<Record<K, V>>; /** * Creates an Object for the elements the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, element: V) => TypedPropertyDescriptor<V>): Promise<Record<PropertyKey, V>>; /** * Creates an Object for the elements the `AsyncQuery`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = from(`"`, 1], ["y", 2]]).toObject(undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = from(`"`, 1], ["y", 2]]).toObject(baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = from(`"`, 1], ["y", 2]]).toObject(null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, element: V) => PropertyDescriptor): Promise<object>; toObject<V>(prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector?: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, element: V) => PropertyDescriptor): Promise<object> { return fn.toObjectAsync(getSource(this), prototype, keySelector, elementSelector!, descriptorSelector); } /** * Writes each element to a destination. The destination must already * have enough space to write the requested number of elements (i.e. * arrays are *not* resized). * * @param dest The destination array. * @param start The offset into the array at which to start writing. * @param count The number of elements to write to the array. * @category Scalar */ copyTo<U extends IndexedCollection<T> | T[]>(dest: U, start?: number, count?: number): Promise<U> { return fn.copyToAsync(getSource(this), dest, start, count); } /** * Pass the entire `AsyncQuery` to the provided callback, returning the result. * * @param callback A callback function. * @param callback.source The outer `AsyncQuery`. * @category Scalar */ into<R>(callback: (source: this) => R) { return fn.intoAsync(this, callback); } // #endregion Scalar [Symbol.asyncIterator](): AsyncIterator<T> { return this[kSource][Symbol.asyncIterator](); } protected _fromAsync<TNode, T extends TNode>(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>): AsyncOrderedHierarchyQuery<TNode, T>; protected _fromAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>): AsyncHierarchyQuery<TNode, T>; protected _fromAsync<TNode, T extends TNode>(source: AsyncOrderedIterable<T> | OrderedIterable<T>, provider: HierarchyProvider<TNode>): AsyncOrderedHierarchyQuery<TNode, T>; protected _fromAsync<TNode, T extends TNode>(source: AsyncIterable<T> | Iterable<T>, provider: HierarchyProvider<TNode>): AsyncHierarchyQuery<TNode, T>; protected _fromAsync<T>(source: AsyncOrderedIterable<T> | OrderedIterable<T>): AsyncOrderedQuery<T>; protected _fromAsync<T extends readonly unknown[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; protected _fromAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncQuery<T>; protected _fromAsync<TNode, T extends TNode>(source: AsyncIterable<T> | Iterable<T>, provider?: HierarchyProvider<TNode>): AsyncQuery<T> { return (this.constructor as typeof AsyncQuery).from(source, provider!) as any; } protected _fromSync<TNode, T extends TNode>(source: OrderedHierarchyIterable<TNode, T>): OrderedHierarchyQuery<TNode, T>; protected _fromSync<TNode, T extends TNode>(source: HierarchyIterable<TNode, T>): HierarchyQuery<TNode, T>; protected _fromSync<TNode, T extends TNode>(source: OrderedIterable<T>, provider: HierarchyProvider<TNode>): OrderedHierarchyQuery<TNode, T>; protected _fromSync<TNode, T extends TNode>(source: Iterable<T>, provider: HierarchyProvider<TNode>): HierarchyQuery<TNode, T>; protected _fromSync<T>(source: OrderedIterable<T>): OrderedQuery<T>; protected _fromSync<T extends readonly unknown[] | []>(source: Iterable<T>): Query<T>; protected _fromSync<T>(source: Iterable<T>): Query<T>; protected _fromSync<TNode, T extends TNode>(source: Iterable<T>, provider?: HierarchyProvider<TNode>): Query<T> { return Query.from(source, provider!); } } // Inline aliases to simplify call stacks AsyncQuery.prototype.where = AsyncQuery.prototype.filter; AsyncQuery.prototype.whereBy = AsyncQuery.prototype.filterBy; AsyncQuery.prototype.whereDefined = AsyncQuery.prototype.filterDefined; AsyncQuery.prototype.whereDefinedBy = AsyncQuery.prototype.filterDefinedBy; AsyncQuery.prototype.whereNot = AsyncQuery.prototype.filterNot; AsyncQuery.prototype.whereNotBy = AsyncQuery.prototype.filterNotBy; AsyncQuery.prototype.whereNotDefinedBy = AsyncQuery.prototype.filterNotDefinedBy; AsyncQuery.prototype.select = AsyncQuery.prototype.map; AsyncQuery.prototype.selectMany = AsyncQuery.prototype.flatMap; AsyncQuery.prototype.skip = AsyncQuery.prototype.drop; AsyncQuery.prototype.skipRight = AsyncQuery.prototype.dropRight; AsyncQuery.prototype.skipWhile = AsyncQuery.prototype.dropWhile; AsyncQuery.prototype.skipUntil = AsyncQuery.prototype.dropUntil; AsyncQuery.prototype.relativeComplement = AsyncQuery.prototype.except; AsyncQuery.prototype.relativeComplementBy = AsyncQuery.prototype.exceptBy; AsyncQuery.prototype.nth = AsyncQuery.prototype.elementAt; AsyncQuery.prototype.break = AsyncQuery.prototype.spanUntil; /** * Represents an ordered sequence of elements. */ export class AsyncOrderedQuery<T> extends AsyncQuery<T> implements AsyncOrderedIterable<T> { constructor(source: AsyncOrderedIterable<T> | OrderedIterable<T>) { assert.assertType(AsyncOrderedIterable.hasInstance(source) || OrderedIterable.hasInstance(source), "source"); super(source); } // #region Order /** * Creates a subsequent ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ thenBy<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedQuery<T> { return this._fromAsync(fn.thenByAsync(getSource(this), keySelector, comparer)); } /** * Creates a subsequent ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparer An optional callback used to compare two keys. * @category Order */ thenByDescending<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedQuery<T> { return this._fromAsync(fn.thenByDescendingAsync(getSource(this), keySelector, comparer)); } // #endregion Order [AsyncOrderedIterable.thenByAsync]<K>(keySelector: (element: T) => K, comparer: Comparison<K> | Comparer<K>, descending: boolean): AsyncOrderedIterable<T> { return getSource(this)[AsyncOrderedIterable.thenByAsync](keySelector, comparer, descending); } } /** * Represents a sequence of hierarchically organized values. */ export class AsyncHierarchyQuery<TNode, T extends TNode = TNode> extends AsyncQuery<T> implements AsyncHierarchyIterable<TNode, T> { constructor(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>); constructor(source: AsyncIterable<T> | Iterable<T>, provider: HierarchyProvider<TNode>); constructor(source: AsyncHierarchyIterable<TNode, T> | AsyncIterable<T> | HierarchyIterable<TNode, T> | Iterable<T>, provider?: HierarchyProvider<TNode>) { if (provider !== undefined) { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeType(HierarchyProvider.hasInstance, provider, "provider"); source = fn.toHierarchyAsync(source, provider); } else { assert.assertType(AsyncHierarchyIterable.hasInstance(source) || HierarchyIterable.hasInstance(source), "source"); } super(source); } // // #region Subquery // /** // * Creates a subquery whose elements match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filter<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncHierarchyQuery<TNode, U>; // /** // * Creates a subquery whose elements match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filter(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; // filter(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { // return super.filter(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery where the selected key for each element matches the supplied predicate. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @param predicate A callback used to match each key. // * @param predicate.key The key to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filterBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.filterBy(keySelector, predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery whose elements are neither `null` nor `undefined`. // * // * @category Subquery // */ // filterDefined(): AsyncHierarchyQuery<TNode, NonNullable<T>> { // return super.filterDefined() as AsyncHierarchyQuery<TNode, NonNullable<T>>; // } // /** // * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @category Subquery // */ // filterDefinedBy<K>(keySelector: (element: T) => K): AsyncHierarchyQuery<TNode, T> { // return super.filterDefinedBy(keySelector) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery whose elements match the supplied predicate. // * // * NOTE: This is an alias for `filter`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // where<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncHierarchyQuery<TNode, U>; // /** // * Creates a subquery whose elements match the supplied predicate. // * // * NOTE: This is an alias for `filter`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // where(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; // where(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { // return this.filter(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery where the selected key for each element matches the supplied predicate. // * // * NOTE: This is an alias for `filterBy`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @param predicate A callback used to match each key. // * @param predicate.key The key to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // whereBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean) { // return this.filterBy(keySelector, predicate); // } // /** // * Creates a subquery whose elements are neither `null` nor `undefined`. // * // * NOTE: This is an alias for `filterDefined`. // * // * @category Subquery // */ // whereDefined() { // return this.filterDefined(); // } // /** // * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. // * // * NOTE: This is an alias for `filterDefinedBy`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @category Subquery // */ // whereDefinedBy<K>(keySelector: (element: T) => K) { // return this.filterDefinedBy(keySelector); // } // /** // * Creates a subquery whose elements do not match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filterNot<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncHierarchyQuery<TNode, U>; // /** // * Creates a subquery whose elements do not match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filterNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; // filterNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { // return super.filterNot(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery where the selected key for each element does not match the supplied predicate. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @param predicate A callback used to match each key. // * @param predicate.key The key to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // filterNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.filterNotBy(keySelector, predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @category Subquery // */ // filterNotDefinedBy<K>(keySelector: (element: T) => K): AsyncHierarchyQuery<TNode, T> { // return super.filterNotDefinedBy(keySelector) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery whose elements do not match the supplied predicate. // * // * NOTE: This is an alias for `filterNot`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // whereNot<U extends T>(predicate: (element: T, offset: number) => element is U): AsyncHierarchyQuery<TNode, U>; // /** // * Creates a subquery whose elements do not match the supplied predicate. // * // * NOTE: This is an alias for `filterNot`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // whereNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; // whereNot(predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean) { // return this.filterNot(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery where the selected key for each element does not match the supplied predicate. // * // * NOTE: This is an alias for `filterNotBy`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @param predicate A callback used to match each key. // * @param predicate.key The key to test. // * @param predicate.offset The offset from the start of the source iterable. // * @category Subquery // */ // whereNotBy<K>(keySelector: (element: T) => K, predicate: (key: K, offset: number) => PromiseLike<boolean> | boolean) { // return this.filterNotBy(keySelector, predicate); // } // /** // * Creates a subquery where the selected key for each element is neither `null` nor `undefined`. // * // * NOTE: This is an alias for `filterNotDefinedBy`. // * // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element The element from which to select a key. // * @category Subquery // */ // whereNotDefinedBy<K>(keySelector: (element: T) => K) { // return this.filterDefinedBy(keySelector); // } // /** // * Creates a subquery whose elements are in the reverse order. // * // * @category Subquery // */ // reverse(): AsyncHierarchyQuery<TNode, T> { // return super.reverse() as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery with every instance of the specified value removed. // * // * @param values The values to exclude. // * @category Subquery // */ // exclude(...values: [PromiseLike<T> | T, ...(PromiseLike<T> | T)[]]): AsyncHierarchyQuery<TNode, T> { // return super.exclude(...values) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing all elements except the first elements up to the supplied // * count. // * // * @param count The number of elements to drop. // * @category Subquery // */ // drop(count: number): AsyncHierarchyQuery<TNode, T> { // return super.drop(count) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing all elements except the last elements up to the supplied // * count. // * // * @param count The number of elements to drop. // * @category Subquery // */ // dropRight(count: number): AsyncHierarchyQuery<TNode, T> { // return super.dropRight(count) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing all elements except the first elements that match // * the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // dropWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.dropWhile(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing all elements except the first elements that don't match // * the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // dropUntil(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.dropUntil(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing all elements except the first elements up to the supplied // * count. // * // * NOTE: This is an alias for `drop`. // * // * @param count The number of elements to skip. // * @category Subquery // */ // skip(count: number) { // return this.drop(count); // } // /** // * Creates a subquery containing all elements except the last elements up to the supplied // * count. // * // * NOTE: This is an alias for `dropRight`. // * // * @param count The number of elements to skip. // * @category Subquery // */ // skipRight(count: number) { // return this.dropRight(count); // } // /** // * Creates a subquery containing all elements except the first elements that match // * the supplied predicate. // * // * NOTE: This is an alias for `dropWhile`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // skipWhile(predicate: (element: T) => PromiseLike<boolean> | boolean) { // return this.dropWhile(predicate); // } // /** // * Creates a subquery containing all elements except the first elements that don't match // * the supplied predicate. // * // * NOTE: This is an alias for `dropUntil`. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // skipUntil(predicate: (element: T) => PromiseLike<boolean> | boolean) { // return this.dropUntil(predicate); // } // /** // * Creates a subquery containing the first elements up to the supplied // * count. // * // * @param count The number of elements to take. // * @category Subquery // */ // take(count: number): AsyncHierarchyQuery<TNode, T> { // return super.take(count) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing the last elements up to the supplied // * count. // * // * @param count The number of elements to take. // * @category Subquery // */ // takeRight(count: number): AsyncHierarchyQuery<TNode, T> { // return super.takeRight(count) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing the first elements that match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // takeWhile<U extends T>(predicate: (element: T) => element is U): AsyncHierarchyQuery<TNode, U>; // /** // * Creates a subquery containing the first elements that match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // */ // takeWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; // takeWhile(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.takeWhile(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery containing the first elements that do not match the supplied predicate. // * // * @param predicate A callback used to match each element. // * @param predicate.element The element to match. // * @category Subquery // */ // takeUntil(predicate: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { // return super.takeUntil(predicate) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // intersect(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T> { // return super.intersect(right, equaler) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set intersection of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // intersectBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T> { // return super.intersectBy(right, keySelector, keyEqualer) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // union(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T> { // return super.union(right, equaler) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set union of this `AsyncQuery` and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // unionBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T> { // return super.unionBy(right, keySelector, keyEqualer) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // except(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T> { // return super.except(right, equaler) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // exceptBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T> { // return super.exceptBy(right, keySelector, keyEqualer) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`. // * // * NOTE: This is an alias for `except`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // relativeComplement(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>) { // return this.except(right, equaler); // } // /** // * Creates a subquery for the set difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * NOTE: This is an alias for `exceptBy`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // relativeComplementBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>) { // return this.exceptBy(right, keySelector, keyEqualer); // } // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param equaler An `Equaler` object used to compare equality. // * @category Subquery // */ // symmetricDifference(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T> { // return super.symmetricDifference(right, equaler) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the symmetric difference between this and another `AsyncIterable` or `Iterable`, where set identity is determined by the selected key. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @param keySelector A callback used to select the key for each element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // symmetricDifferenceBy<K>(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T> { // return super.symmetricDifferenceBy(right, keySelector, keyEqualer) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery that concatenates this `AsyncQuery` with another `AsyncIterable` or `Iterable`. // * // * @param right An `AsyncIterable` or `Iterable` object. // * @category Subquery // */ // concat(right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncHierarchyQuery<TNode, T> { // return super.concat(right) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the distinct elements of this `AsyncQuery`. // * @param equaler An `Equaler` object used to compare key equality. // * @category Subquery // */ // distinct(equaler?: Equaler<T>): AsyncHierarchyQuery<TNode, T> { // return super.distinct(equaler) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the distinct elements of this `AsyncQuery`. // * // * @param keySelector A callback used to select the key to determine uniqueness. // * @param keySelector.value An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // distinctBy<K>(keySelector: (value: T) => K, keyEqualer?: Equaler<K>): AsyncHierarchyQuery<TNode, T> { // return super.distinctBy(keySelector, keyEqualer) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the elements of this `AsyncQuery` with the provided value appended to the end. // * // * @param value The value to append. // * @category Subquery // */ // append(value: PromiseLike<T> | T): AsyncHierarchyQuery<TNode, T> { // return super.append(value) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the elements of this `AsyncQuery` with the provided value prepended to the beginning. // * // * @param value The value to prepend. // * @category Subquery // */ // prepend(value: PromiseLike<T> | T): AsyncHierarchyQuery<TNode, T> { // return super.prepend(value) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery for the elements of this `AsyncQuery` with the provided range // * patched into the results. // * // * @param start The offset at which to patch the range. // * @param skipCount The number of elements to skip from start. // * @param range The range to patch into the result. // * @category Subquery // */ // patch(start: number, skipCount?: number, range?: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): AsyncHierarchyQuery<TNode, T> { // return super.patch(start, skipCount, range) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery that contains the provided default value if this `AsyncQuery` // * contains no elements. // * // * @param defaultValue The default value. // * @category Subquery // */ // defaultIfEmpty(defaultValue: PromiseLike<T> | T): AsyncHierarchyQuery<TNode, T> { // return super.defaultIfEmpty(defaultValue) as AsyncHierarchyQuery<TNode, T>; // } // /** // * Creates a subquery that splits this `AsyncQuery` into one or more pages. // * While advancing from page to page is evaluated lazily, the elements of the page are // * evaluated eagerly. // * // * @param pageSize The number of elements per page. // * @category Subquery // */ // pageBy(pageSize: number): AsyncQuery<HierarchyPage<TNode, T>>; // /** // * Creates a subquery that splits this `AsyncQuery` into one or more pages. // * While advancing from page to page is evaluated lazily, the elements of the page are // * evaluated eagerly. // * // * @param pageSize The number of elements per page. // * @category Subquery // */ // pageBy<R>(pageSize: number, pageSelector: (page: number, offset: number, values: HierarchyQuery<TNode, T>) => R): AsyncQuery<R>; // pageBy<R>(pageSize: number, pageSelector?: (page: number, offset: number, values: HierarchyQuery<TNode, T>) => R): AsyncQuery<R> { // return super.pageBy(pageSize, pageSelector as (page: number, offset: number, values: Query<T>) => R); // } // /** // * Creates a subquery whose elements are the contiguous ranges of elements that share the same key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @category Subquery // */ // spanMap<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<Grouping<K, T> & Hierarchical<TNode>>; // /** // * Creates a subquery whose values are computed from each element of the contiguous ranges of elements that share the same key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @category Subquery // */ // spanMap<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): AsyncQuery<Grouping<K, V>>; // /** // * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @param spanSelector A callback used to select a result from a contiguous range. // * @param spanSelector.key The key for the span. // * @param spanSelector.elements The elements for the span. // * @category Subquery // */ // spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, spanSelector: (key: K, elements: Query<V>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; // /** // * Creates a subquery whose values are computed from the contiguous ranges of elements that share the same key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @param spanSelector A callback used to select a result from a contiguous range. // * @param spanSelector.key The key for the span. // * @param spanSelector.elements The elements for the span. // * @category Subquery // */ // spanMap<K, R>(keySelector: (element: T) => K, elementSelector: undefined, spanSelector: (key: K, elements: HierarchyQuery<TNode, T>) => PromiseLike<R> | R, keyEqualer?: Equaler<K>): AsyncQuery<R>; // spanMap<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K>, spanSelector?: ((key: K, elements: Query<T | V>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | ((key: K, elements: HierarchyQuery<TNode, T>) => PromiseLike<Grouping<K, T | V> | R> | Grouping<K, T | V> | R) | Equaler<K>, keyEqualer?: Equaler<K>) { // return super.spanMap(keySelector, elementSelector as (element: T) => PromiseLike<V> | V, spanSelector as (key: K, elements: Query<V>) => PromiseLike<R> | R, keyEqualer); // } // /** // * Groups each element of this `AsyncQuery` by its key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // groupBy<K>(keySelector: (element: T) => K, keyEqualer?: Equaler<K>): AsyncQuery<Grouping<K, T> & Hierarchical<TNode>>; // /** // * Groups each element by its key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // groupBy<K, V>(keySelector: (element: T) => K, elementSelector: (element: T) => V, keyEqualer?: Equaler<K>): AsyncQuery<Grouping<K, V>>; // /** // * Groups each element by its key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @param resultSelector A callback used to select a result from a group. // * @param resultSelector.key The key for the group. // * @param resultSelector.elements The elements for the group. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector: (element: T) => V, resultSelector: (key: K, elements: Query<V>) => R, keyEqualer?: Equaler<K>): AsyncQuery<R>; // /** // * Groups each element by its key. // * // * @param keySelector A callback used to select the key for an element. // * @param keySelector.element An element from which to select a key. // * @param elementSelector A callback used to select a value for an element. // * @param elementSelector.element An element from which to select a value. // * @param resultSelector A callback used to select a result from a group. // * @param resultSelector.key The key for the group. // * @param resultSelector.elements The elements for the group. // * @param keyEqualer An `Equaler` object used to compare key equality. // * @category Subquery // */ // groupBy<K, R>(keySelector: (element: T) => K, elementSelector: undefined, resultSelector: (key: K, elements: HierarchyQuery<TNode, T>) => R, keyEqualer?: Equaler<K>): AsyncQuery<R>; // groupBy<K, V, R>(keySelector: (element: T) => K, elementSelector?: ((element: T) => V) | Equaler<K>, resultSelector?: ((key: K, elements: Query<V>) => R) | ((key: K, elements: HierarchyQuery<TNode, T>) => R) | Equaler<K>, keyEqualer?: Equaler<K>) { // return super.groupBy(keySelector, elementSelector as (element: T) => V, resultSelector as (key: K, elements: Query<V>) => R, keyEqualer); // } // /** // * Eagerly evaluate the `AsyncQuery`, returning a new `AsyncQuery`. // * @category Subquery // */ // materialize(): AsyncHierarchyQuery<TNode, T> { // return super.materialize() as AsyncHierarchyQuery<TNode, T>; // } // // #endregion Subquery // // #region Order // /** // * Creates an ordered subquery whose elements are sorted in ascending order by the provided key. // * // * @param keySelector A callback used to select the key for an element. // * @param comparer An optional callback used to compare two keys. // * @category Order // */ // orderBy<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyQuery<TNode, T> { // return super.orderBy(keySelector, comparer) as AsyncOrderedHierarchyQuery<TNode, T>; // } // /** // * Creates an ordered subquery whose elements are sorted in descending order by the provided key. // * // * @param keySelector A callback used to select the key for an element. // * @param comparer An optional callback used to compare two keys. // * @category Order // */ // orderByDescending<K>(keySelector: (element: T) => K, comparer?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyQuery<TNode, T> { // return super.orderByDescending(keySelector, comparer) as AsyncOrderedHierarchyQuery<TNode, T>; // } // // #endregion Order // #region Hierarchy /** * Creates a subquery for the roots of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ root<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the roots of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ root(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; root(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.rootAsync(getSource(this), predicate)); } /** * Creates a subquery for the ancestors of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestors<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the ancestors of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestors(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; ancestors(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.ancestorsAsync(getSource(this), predicate)); } /** * Creates a subquery for the ancestors of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestorsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the ancestors of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ ancestorsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; ancestorsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.ancestorsAndSelfAsync(getSource(this), predicate)); } /** * Creates a subquery for the descendants of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendants<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the descendants of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendants(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; descendants(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.descendantsAsync(getSource(this), predicate)); } /** * Creates a subquery for the descendants of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendantsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the descendants of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ descendantsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; descendantsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.descendantsAndSelfAsync(getSource(this), predicate)); } /** * Creates a subquery for the parents of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ parents<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the parents of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ parents(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; parents(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.parentsAsync(getSource(this), predicate)); } /** * Creates a subquery for this `Asyncquery`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self<U extends T>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for this `Asyncquery`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for this `Asyncquery`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ self(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; self(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.selfAsync(getSource(this), predicate)); } /** * Creates a subquery for the siblings of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblings<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; siblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.siblingsAsync(getSource(this), predicate)); } /** * Creates a subquery for the siblings of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAndSelf<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings of each element as well as each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; siblingsAndSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.siblingsAndSelfAsync(getSource(this), predicate)); } /** * Creates a subquery for the children of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ children<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the children of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ children(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; children(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.childrenAsync(getSource(this), predicate)); } /** * Creates a subquery for the siblings before each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ precedingSiblings<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings before each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ precedingSiblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; precedingSiblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.precedingSiblingsAsync(getSource(this), predicate)); } /** * Creates a subquery for the siblings before each element in the hierarchy. * * NOTE: This is an alias for `precedingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsBeforeSelf<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings before each element in the hierarchy. * * NOTE: This is an alias for `precedingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsBeforeSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; siblingsBeforeSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this.precedingSiblings(predicate); } /** * Creates a subquery for the siblings after each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ followingSiblings<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings after each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ followingSiblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; followingSiblings(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.followingSiblingsAsync(getSource(this), predicate)); } /** * Creates a subquery for the siblings after each element in the hierarchy. * * NOTE: This is an alias for `followingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAfterSelf<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the siblings after each element in the hierarchy. * * NOTE: This is an alias for `followingSiblings`. * * @param predicate A callback used to filter the results. * @category Hierarchy */ siblingsAfterSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; siblingsAfterSelf(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this.followingSiblings(predicate); } /** * Creates a subquery for the nodes preceding each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ preceding<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the nodes preceding each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ preceding(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; preceding(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.precedingAsync(getSource(this), predicate)); } /** * Creates a subquery for the nodes following each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ following<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the nodes following each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ following(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; following(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.followingAsync(getSource(this), predicate)); } /** * Creates a subquery for the first child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ firstChild<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the first child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ firstChild(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; firstChild(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.firstChildAsync(getSource(this), predicate)); } /** * Creates a subquery for the last child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ lastChild<U extends TNode>(predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the last child of each element in the hierarchy. * * @param predicate A callback used to filter the results. * @category Hierarchy */ lastChild(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; lastChild(predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.lastChildAsync(getSource(this), predicate)); } /** * Creates a subquery for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param offset The offset for the child. * @category Hierarchy */ nthChild<U extends TNode>(offset: number | Index, predicate: (element: TNode) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the child of each element at the specified offset. A negative offset * starts from the last child. * * @param offset The offset for the child. * @category Hierarchy */ nthChild(offset: number | Index, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode>; nthChild(offset: number | Index, predicate?: (element: TNode) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode> { return this._fromAsync(fn.nthChildAsync(getSource(this), offset, predicate)); } /** * Creates a subquery for the top-most elements. Elements that are a descendant of any other * element are removed. * @category Hierarchy */ topMost<U extends T>(predicate: (element: T) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the top-most elements. Elements that are a descendant of any other * element are removed. * @category Hierarchy */ topMost(predicate?: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; topMost(predicate?: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { return this._fromAsync(fn.topMostAsync(getSource(this), predicate)); } /** * Creates a subquery for the bottom-most elements. Elements that are an ancestor of any other * element are removed. * @category Hierarchy */ bottomMost<U extends T>(predicate: (element: T) => element is U): AsyncHierarchyQuery<TNode, U>; /** * Creates a subquery for the bottom-most elements. Elements that are an ancestor of any other * element are removed. * @category Hierarchy */ bottomMost(predicate?: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T>; bottomMost(predicate?: (element: T) => PromiseLike<boolean> | boolean): AsyncHierarchyQuery<TNode, T> { return this._fromAsync(fn.bottomMostAsync(getSource(this), predicate)); } // #endregion Hierarchy [Hierarchical.hierarchy](): HierarchyProvider<TNode> { return getSource(this)[Hierarchical.hierarchy](); } } // Inline aliases to simplify call stacks AsyncHierarchyQuery.prototype.siblingsBeforeSelf = AsyncHierarchyQuery.prototype.precedingSiblings; AsyncHierarchyQuery.prototype.siblingsAfterSelf = AsyncHierarchyQuery.prototype.followingSiblings; /** * Represents an ordered sequence of hierarchically organized values. */ export class AsyncOrderedHierarchyQuery<TNode, T extends TNode = TNode> extends AsyncHierarchyQuery<TNode, T> implements AsyncOrderedHierarchyIterable<TNode, T> { constructor(source: AsyncOrderedHierarchyIterable<TNode, T> | OrderedHierarchyIterable<TNode, T>); constructor(source: AsyncOrderedIterable<T> | OrderedIterable<T>, provider: HierarchyProvider<TNode>); constructor(source: AsyncOrderedHierarchyIterable<TNode, T> | AsyncOrderedIterable<T> | OrderedHierarchyIterable<TNode, T> | OrderedIterable<T>, provider?: HierarchyProvider<TNode>) { if (provider !== undefined) { assert.assertType(AsyncOrderedIterable.hasInstance(source) || OrderedIterable.hasInstance(source), "source"); super(source, provider); } else { assert.assertType(AsyncOrderedHierarchyIterable.hasInstance(source) || OrderedHierarchyIterable.hasInstance(source), "source"); super(source); } } // #region Order /** * Creates a subsequent ordered subquery whose elements are sorted in ascending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparison An optional callback used to compare two keys. * @category Order */ thenBy<K>(keySelector: (element: T) => K, comparison?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyQuery<TNode, T> { return this._fromAsync(fn.thenByAsync(getSource(this), keySelector, comparison)); } /** * Creates a subsequent ordered subquery whose elements are sorted in descending order by the provided key. * * @param keySelector A callback used to select the key for an element. * @param comparison An optional callback used to compare two keys. * @category Order */ thenByDescending<K>(keySelector: (element: T) => K, comparison?: Comparison<K> | Comparer<K>): AsyncOrderedHierarchyQuery<TNode, T> { return this._fromAsync(fn.thenByDescendingAsync(getSource(this), keySelector, comparison)); } // #endregion Order [AsyncOrderedIterable.thenByAsync]<K>(keySelector: (element: T) => K, comparison: Comparison<K> | Comparer<K>, descending: boolean): AsyncOrderedHierarchyIterable<TNode, T> { return getSource(this)[AsyncOrderedIterable.thenByAsync](keySelector, comparison, descending); } }
the_stack
import { Trilogy } from '.' import { Hooks, Hook } from './hooks' import * as helpers from './helpers' import { Cast, normalizeSchema, createTrigger, TriggerEvent } from './schema-helpers' import { invariant, isEmpty, isString, isObject, isNil, toArray, firstOrValue } from './util' import * as types from './types' /** * Instances of `Model` manage the casting of values back and forth between the * SQLite backend and their corresponding JavaScript types as well as calling * hooks. * * Models are created using a trilogy instance's `model` method and are not * intended to be created directly. * * @internal */ export default class Model < D extends types.ReturnDict = types.LooseObject > extends Hooks<D> { cast: Cast<D> schema: types.Schema<D> /** * @param ctx trilogy instance used as a context for the model * @param name Name associated with this model and used in the backend * @param schema An object defining the fields & types of objects * @param options */ constructor ( public ctx: Trilogy, public name: string, schema: types.SchemaRaw<D>, public options: types.ModelOptions ) { super() this.schema = normalizeSchema<D>(schema, options) this.cast = new Cast<D>(this) } /** * Create an object on the given model. `object` should match the model's * defined schema but values will cast into types as needed. * * @param object Data to insert * @param options */ async create ( object: D, options: types.CreateOptions = {} ): Promise<D | undefined> { const { prevented } = await this._callHook(Hook.BeforeCreate, object, options) if (prevented) return const insertion = this.cast.toDefinition(object, options) const [returning, cleanup] = await createTrigger(this, TriggerEvent.Insert) const query = this.ctx.knex.raw( this.ctx.knex(this.name) .insert(insertion) .toString() .replace(/^insert/i, 'INSERT OR IGNORE') ) await helpers.runQuery(this.ctx, query, { model: this }) const result = await helpers.runQuery(this.ctx, returning, { model: this, needResponse: true, internal: true }) await cleanup() const created = !isEmpty(result) ? this.cast.fromDefinition( firstOrValue(result), options ) : undefined await this._callHook(Hook.AfterCreate, created, options) return created } /** * Find all objects matching a given criteria. * * @param criteria Criteria used to restrict selection * @param options */ async find ( criteria?: types.Criteria<D>, options: types.FindOptions = {} ): Promise<D[]> { types.FindOptions.check(options) const order = options.random ? 'random' : options.order let query = this.ctx.knex(this.name).select() query = helpers.buildWhere(query, this.cast.toDefinition( criteria || {}, { raw: true, ...options } )) if (order) query = helpers.buildOrder(query, order) if (options.limit) query = query.limit(options.limit) if (options.skip) query = query.offset(options.skip) const response = await helpers.runQuery(this.ctx, query, { model: this, needResponse: true }) if (!Array.isArray(response)) { return response ? [response] : [] } return response.map(object => { return this.cast.fromDefinition(object, options) }) } /** * Find all objects matching a given criteria and extract the values * at `column`. * * @param column Property name of objects to extract the value from * @param criteria Criteria used to restrict selection * @param options */ async findIn ( column: keyof D, criteria?: types.Criteria<D>, options?: types.FindOptions ): Promise<types.ValueOf<D>[]> { const response = await this.find(criteria, options) return response.map(object => { return this.cast.fromColumnDefinition( column as string, object[column], options ) }) } /** * Find a single object matching a given criteria. The first matching * object is returned. * * @param criteria Criteria used to restrict selection * @param options */ async findOne ( criteria?: types.Criteria<D>, options: types.FindOptions = {} ): Promise<D | undefined> { types.FindOptions.check(options) const order = options.random ? 'random' : options.order let query = this.ctx.knex(this.name).first() query = helpers.buildWhere(query, this.cast.toDefinition( criteria || {}, { raw: true, ...options } )) if (order) query = helpers.buildOrder(query, order) if (options.skip) query = query.offset(options.skip) const response = await helpers.runQuery(this.ctx, query, { model: this, needResponse: true }) const result = firstOrValue<D>(response) if (isNil(result)) return undefined return this.cast.fromDefinition(result, options) } /** * Find a single object matching a given criteria and extract the value * at `column`. The first matching object is returned. * * @param column Property name of the selected object to extract the value from * @param criteria Criteria used to restrict selection * @param options */ async findOneIn <K extends keyof D = keyof D, V = D[K]> ( column: K, criteria?: types.Criteria<D>, options: types.FindOptions = {} ): Promise<V | undefined> { return this.findOne(criteria, options) .then(object => object != null ? object[column] as V : undefined) } /** * Find a matching object based on the given criteria, or create it if it * doesn't exist. When creating the object, a merged object created from * `criteria` and `creation` will be used, with the properties from * `creation` taking precedence. * * @param criteria Criteria to search for * @param creation Data used to create the object if it doesn't exist * @param options */ async findOrCreate ( criteria: types.CriteriaObj<D>, creation: Partial<D> = {}, options?: types.FindOptions ): Promise<D | undefined> { return ( await this.findOne(criteria, options) || this.create({ ...criteria, ...creation } as D) ) } /** * Modify the properties of an existing object. While optional, if `data` * contains no properties no update queries will be run. * * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ async update ( criteria: types.Criteria<D> = {}, data: Partial<D> = {}, options: types.UpdateOptions = {} ): Promise<D[]> { types.UpdateOptions.check(options) if (Object.keys(data).length < 1) return [] const [returning, cleanup] = await createTrigger(this, TriggerEvent.Update) const { prevented } = await this._callHook(Hook.BeforeUpdate, [data, criteria], options) if (prevented) return [] const typedData = this.cast.toDefinition(data, options) const typedCriteria = this.cast.toDefinition(criteria, options) let query = this.ctx.knex(this.name).update(typedData) query = helpers.buildWhere(query, typedCriteria) await helpers.runQuery(this.ctx, query, { model: this }) const updatedRaw: D[] = await helpers.runQuery(this.ctx, returning, { model: this, needResponse: true, internal: true }) const updated = updatedRaw.map(object => { return this.cast.fromDefinition(object, options) }) await cleanup() await this._callHook(Hook.AfterUpdate, updated, options) return updated } /** * Update an existing object or create it if it doesn't exist. If creation * is necessary a merged object created from `criteria` and `data` will be * used, with the properties from `data` taking precedence. * * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ async updateOrCreate ( criteria: types.CriteriaObj<D>, data: Partial<D>, options: types.UpdateOptions & types.CreateOptions = {} ): Promise<D[]> { const found = await this.find(criteria, options) if (!found || !found.length) { return this.create({ ...criteria, ...data } as D, options) .then(res => toArray<D>(res as D)) } else { return this.update(criteria, data, options) } } /** * Works similarly to the `get` methods in lodash, underscore, etc. Returns * the value at `column` or, if it does not exist, the supplied `defaultValue`. * Essentially a useful shorthand for some `find` scenarios. * * @param column Property name of the object to extract the value from * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ get <K extends keyof D = keyof D, V extends D[K] = D[K]> ( column: K, criteria?: types.Criteria<D>, defaultValue?: V ) { return baseGet<D, K>(this, column, criteria, defaultValue) } /** * Works similarly to the `set` methods in lodash, underscore, etc. Updates * the value at `column` to be `value` where the given criteria is met. * * @param column Property name of the object at which to set the value * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ set <K extends keyof D = keyof D, V extends D[K] = D[K]> ( column: K, criteria: types.Criteria<D>, value: V ) { return baseSet<D, K>(this, column, criteria, value) } /** * Works exactly like `get` but bypasses getters and retrieves the raw database value. * * @param column Property name of the object to extract the value from * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ getRaw <K extends keyof D = keyof D, V extends D[K] = D[K]> ( column: K, criteria: types.Criteria<D>, defaultValue?: V ) { return baseGet<D, K>(this, column, criteria, defaultValue, { raw: true }) } /** * Works exactly like `set` but bypasses setters when updating the target value. * * @param column Property name of the object at which to set the value * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ setRaw <K extends keyof D = keyof D, V extends D[K] = D[K]> ( column: K, criteria: types.Criteria<D>, value: V ) { return baseSet<D, K>(this, column, criteria, value, { raw: true }) } /** * Increment the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param column Property at which to increment the value * @param criteria Criteria used to restrict selection * @param amount */ async increment ( column: keyof D, criteria?: types.Criteria<D>, amount?: number ): Promise<D[]> { const { prevented } = await this._callHook(Hook.BeforeUpdate, [{}, criteria as types.Criteria<D>]) if (prevented) return [] const cast = Number(amount) if (Number.isNaN(cast)) amount = 1 if (amount === 0) return [] const [returning, cleanup] = await createTrigger(this, TriggerEvent.Update) let query = this.ctx.knex(this.name).increment(column as string, amount) query = helpers.buildWhere(query, criteria) const affected = await helpers.runQuery(this.ctx, query, { model: this }) if (affected === 0) return [] const updatedRaw: D[] = await helpers.runQuery(this.ctx, returning, { model: this, needResponse: true, internal: true }) const updated = updatedRaw.map(object => { return this.cast.fromDefinition(object, {}) }) await cleanup() await this._callHook(Hook.AfterUpdate, updated) return updated } /** * Decrement the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param column Property at which to decrement the value * @param criteria Criteria used to restrict selection * @param amount */ async decrement ( column: keyof D, criteria?: types.Criteria<D>, amount?: number, allowNegative?: boolean ): Promise<D[]> { const { prevented } = await this._callHook(Hook.BeforeUpdate, [{}, criteria as types.Criteria<D>]) if (prevented) return [] const cast = Number(amount) if (Number.isNaN(cast)) amount = 1 if (amount === 0) return [] const [returning, cleanup] = await createTrigger(this, TriggerEvent.Update) const raw = allowNegative ? '?? - ?' : 'MAX(0, ?? - ?)' const query = helpers.buildWhere( this.ctx.knex(this.name).update({ [column]: this.ctx.knex.raw(raw, [column, amount] as [string, number]) }), criteria ) const affected = await helpers.runQuery(this.ctx, query, { model: this }) if (affected === 0) return [] const updatedRaw: D[] = await helpers.runQuery(this.ctx, returning, { model: this, needResponse: true, internal: true }) const updated = updatedRaw.map(object => { return this.cast.fromDefinition(object, {}) }) await cleanup() await this._callHook(Hook.AfterUpdate, updated) return updated } /** * Delete objects from this model that match `criteria`. * * @remarks * If `criteria` is empty or absent, nothing will be done. This is a safeguard * against unintentionally deleting everything in the model. Use `clear` if * you really want to remove all rows. * * @param criteria Criteria used to restrict selection */ async remove (criteria: types.Criteria<D>): Promise<D[]> { const { prevented } = await this._callHook(Hook.BeforeRemove, criteria) if (prevented) return [] if ( !helpers.isValidWhere(criteria) || (isObject(criteria) && !Object.keys(criteria).length) ) return [] const [returning, cleanup] = await createTrigger(this, TriggerEvent.Delete) let query = this.ctx.knex(this.name).del() query = helpers.buildWhere(query, criteria) const deleteCount = await helpers.runQuery(this.ctx, query, { model: this }) if (deleteCount === 0) return [] const deleted = await helpers.runQuery(this.ctx, returning, { model: this, needResponse: true, internal: true }) await cleanup() await this._callHook(Hook.AfterRemove, deleted) return deleted } /** * Delete all objects from this model. */ clear (): Promise<number> { const query = this.ctx.knex(this.name).truncate() return helpers.runQuery(this.ctx, query, { model: this }) } /** * Count the number of objects in this model. * * @param criteria Criteria used to restrict selection * @param options */ async count ( criteria?: types.Criteria<D>, options: types.AggregateOptions = {} ): Promise<number> { return baseCount<D>(this, '*', criteria, options) } /** * Count the number of objects in this model, selecting on column (meaning * `NULL` values are not counted). * * @param column Property name to select on * @param criteria Criteria used to restrict selection * @param options */ async countIn ( column: keyof D, criteria?: types.Criteria<D>, options: types.AggregateOptions = {} ): Promise<number> { return baseCount<D>(this, column, criteria, options) } /** * Find the minimum value contained in this model, comparing all values in * `column` that match the given criteria. * * @param column Property name to inspect * @param criteria Criteria used to restrict selection * @param options */ async min ( column: keyof D, criteria?: types.Criteria<D>, options: types.AggregateOptions = {} ): Promise<number | undefined> { return baseMinMax(this, 'min', column, criteria, options) } /** * Find the maximum value contained in this model, comparing all values in * `column` that match the given criteria. * * @param column Property name to inspect * @param criteria Criteria used to restrict selection * @param options */ async max ( column: keyof D, criteria?: types.Criteria<D>, options?: types.AggregateOptions ): Promise<number | undefined> { return baseMinMax(this, 'max', column, criteria, options) } } async function baseCount <D extends types.ReturnDict> ( model: Model<D>, column: keyof D, criteria?: types.Criteria<D>, options: types.AggregateOptions = {} ): Promise<number> { invariant( column && isString(column), `invalid column: expected string, got ${typeof column}` ) types.AggregateOptions.check(options) const val = `${column} as count` const builder = model.ctx.knex(model.name) let query = options.distinct ? builder.countDistinct(val) : builder.count(val) query = helpers.buildWhere(query, model.cast.toDefinition( criteria || {}, { raw: true, ...options } )) if (options.group) query = query.groupBy(toArray(options.group)) const res = await helpers.runQuery(model.ctx, query, { model, needResponse: true }) if (!Array.isArray(res)) return 0 return res[0].count } async function baseMinMax <D extends types.ReturnDict> ( model: Model<D>, method: 'min' | 'max', column: keyof D, criteria?: types.Criteria<D>, options: types.AggregateOptions = {} ) { types.AggregateOptions.check(options) const val = `${column} as ${method}` let query = model.ctx.knex(model.name)[method](val) query = helpers.buildWhere(query, model.cast.toDefinition( criteria || {}, { raw: true, ...options } )) if (options.group) query = query.groupBy(toArray(options.group)) const res = await helpers.runQuery(model.ctx, query, { model, needResponse: true }) if (!Array.isArray(res)) return undefined return res[0][method] } async function baseGet <D extends types.ReturnDict, K extends keyof D> ( model: Model<D>, column: K, criteria: types.Criteria<D> | undefined, defaultValue?: D[K], options?: types.LooseObject ): Promise<D[K] | undefined> { const data = await model.findOneIn(column, criteria, options) return data ?? defaultValue } async function baseSet <D extends types.ReturnDict, K extends keyof D> ( model: Model<D>, column: K, criteria: types.Criteria<D> | undefined, value?: D[K], options?: types.LooseObject ): Promise<D[]> { invariant( model.schema[column as string], `no column by the name '${column}' is defined in '${model.name}'` ) return model.update(criteria, { [column]: value } as Partial<D>, options) }
the_stack
import { EventEmitter } from 'events'; import { ChildProcess } from 'child_process'; import * as asap from 'asap'; import deprecated from 'deprecated-decorator'; import { BreakSignal, GoToSignal } from './signals'; import { Context } from './context'; import { TimeoutError } from './errors'; let EventEmitterConstructor: any; let ChildProcessConstructor: any; try { EventEmitterConstructor = require('events').EventEmitter; } catch (error) { } try { ChildProcessConstructor = require('child_process').ChildProcess; } catch (error) { } ///////////// // Promise // ///////////// export interface PromiseLike<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onfulfilled The callback to execute when the Promise is resolved. * @param onrejected The callback to execute when the Promise is rejected. * @return A Promise for the completion of which ever callback is executed. */ then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>; then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>; } export type Resolvable<T> = PromiseLike<T> | T; export type Resolver<T> = ( resolve: (value?: Resolvable<T>) => void, reject: (reason: any) => void ) => void; export type OnFulfilledHandler<T, TResult> = (value: T) => Resolvable<TResult>; export type OnFulfilledSpreadHandler<TResult> = (...values: any[]) => Resolvable<TResult>; export type OnRejectedHandler<TResult> = (reason: any) => Resolvable<TResult>; export type OnAnyHandler<TResult> = (valueOrReason: any) => Resolvable<TResult>; export type OnContextDisposedHandler = () => void; export type NodeStyleCallback<T> = (error?: any, value?: T) => void; export type MapCallback<T, TResult> = (value: T, index: number, array: T[]) => Resolvable<TResult>; export type ReduceCallback<T, TResult> = (previousValue: TResult, currentValue: T, index: number, array: T[]) => Resolvable<TResult>; export type EachCallback<T> = (value: T, index: number, array: T[]) => Resolvable<boolean | void>; export type WaterfallCallback<T, TResult> = (value: T, result: TResult, index: number, array: T[]) => Resolvable<TResult>; /** * Possible states of a promise. */ const enum State { pending, fulfilled, rejected, skipped } /** * ThenFail promise options. */ export let options = { disableUnrelayedRejectionWarning: false, logger: { log: console.log, warn: console.warn, error: console.error } }; // The core abstraction of this implementation is to imagine the behavior of promises // as relay runners. // 1. Grab the baton state (and value/reason). // 2. Run and get its own state. // 3. Relay the new state to next runners. export class Promise<T> implements PromiseLike<T> { /** To make sure type checking work with value. */ private __generic: T; /** Current state of this promise. */ private _state = State.pending; /** * Indicates whether `onfulfilled` or `onrejected` handler has been called * but the resolved value has not become fulfilled yet. */ private _running = false; /** Indicates whether this promise has been relayed or notified as unrelayed. */ private _handled = false; /** The fulfilled value or rejected reason associated with this promise. */ private _valueOrReason: any; /** Context of this promise. */ private _context: Context; /** Label of this promise. */ private _label: string; /** * Next promise in the chain. * Avoid using an array if not necessary due to performance issue, * the same way applies to `_handledPromise(s)`. * If `_chainedPromise` is not undefined, `_chainedPromises` must be undefined. * Vice versa. */ private _chainedPromise: Promise<any>; /** Next promises in the chain. */ private _chainedPromises: Promise<any>[]; /** * Promise that will share the same state (and value/reason). * * Example: * * ```ts * let promiseA = Promise.then(() => { * let promiseB = Promise.then(() => ...); * return promiseB; * }); * ``` * * The state of `promiseB` will determine the state of `promiseA`. * And `promiseA` will then be in here. */ private _handledPromise: Promise<T>; /** Promises that will share the same state (and value/reason). */ private _handledPromises: Promise<T>[]; private _onPreviousFulfilled: OnFulfilledHandler<any, T>; private _onPreviousRejected: OnRejectedHandler<T>; private _onContextDisposed: OnContextDisposedHandler; /** * Promise constructor. */ constructor(); constructor(resolver: Resolver<T>); constructor(context: Context); constructor(resolverOrContext?: Resolver<T> | Context) { if (resolverOrContext instanceof Context && !resolverOrContext._enclosed) { this._context = resolverOrContext; } else { this._context = new Context(); } if (typeof resolverOrContext === 'function') { try { (<Resolver<T>>resolverOrContext)( value => this.resolve(value), reason => this.reject(reason) ); } catch (error) { this.reject(error); } } } /** * Get the state from previous promise in chain. */ private _grab(previousState: State, previousValueOrReason?: any): void { if (this._state !== State.pending) { return; } let handler: OnAnyHandler<Resolvable<T>>; if (previousState === State.fulfilled) { handler = this._onPreviousFulfilled; } else if (previousState === State.rejected) { handler = this._onPreviousRejected; } if (handler) { this._run(handler, previousValueOrReason); } else { this._relay(previousState, previousValueOrReason); } } /** * Invoke `onfulfilled` or `onrejected` handlers. */ private _run(handler: OnAnyHandler<any>, previousValueOrReason: any): void { this._running = true; asap(() => { let resolvable: Resolvable<T>; try { resolvable = handler(previousValueOrReason); } catch (error) { this._decide(State.rejected, error); this._running = false; return; } this._unpack(resolvable, (state, valueOrReason) => { this._decide(state, valueOrReason); this._running = false; }); }); } /** * The resolve process defined in Promises/A+ specifications. */ private _unpack(value: Resolvable<T>, callback: (state: State, valueOrReason: any) => void): void { if (this === value) { callback(State.rejected, new TypeError('The promise should not return itself')); return; } if (value instanceof Promise) { if (value._state === State.pending) { if (value._handledPromise) { value._handledPromises = [value._handledPromise, this]; value._handledPromise = undefined; } else if (value._handledPromises) { value._handledPromises.push(this); } else { value._handledPromise = this; } let context = this._context; if (context._subContexts) { context._subContexts.push(value._context); } else { context._subContexts = [value._context]; } } else { callback(value._state, value._valueOrReason); value._handled = true; } return; } if (value && (typeof value === 'object' || typeof value === 'function')) { try { let then = (value as PromiseLike<any>).then; if (typeof then === 'function') { then.call( value, (value: any) => { if (callback) { this._unpack(value, callback); callback = undefined; } }, (reason: any) => { if (callback) { callback(State.rejected, reason); callback = undefined; } } ); return; } } catch (error) { if (callback) { callback(State.rejected, error); callback = undefined; } return; } } callback(State.fulfilled, value); } /** * Decide whether to call `_relay`, `_skip` or `_goto`. */ private _decide(state: State, valueOrReason?: any): void { if (valueOrReason instanceof BreakSignal) { this._skip(valueOrReason); } else if (valueOrReason instanceof GoToSignal) { this._goto(valueOrReason); } else { this._relay(state, valueOrReason); } } /** * Set the state of current promise and relay it to next promises. */ private _relay(state: State, valueOrReason?: any): void { if (this._state !== State.pending) { return; } if (this._context._disposed) { this._skip(); return; } this._state = state; this._valueOrReason = valueOrReason; if (this._chainedPromise) { this._chainedPromise._grab(state, valueOrReason); } else if (this._chainedPromises) { for (let promise of this._chainedPromises) { promise._grab(state, valueOrReason); } } if (this._handledPromise) { this._handledPromise._relay(state, valueOrReason); } else if (this._handledPromises) { for (let promise of this._handledPromises) { promise._relay(state, valueOrReason); } } asap(() => { if (state === State.rejected && !this._handled) { this._handled = true; let relayed = !!(this._chainedPromise || this._chainedPromises || this._handledPromise || this._handledPromises); if (!relayed && !options.disableUnrelayedRejectionWarning) { let error = valueOrReason && (valueOrReason.stack || valueOrReason.message) || valueOrReason; options.logger.warn(`An unrelayed rejection happens:\n${error}`); } } this._relax(); }); } /** * Skip some promises. */ private _skip(signal?: BreakSignal): void { if (this._state !== State.pending) { return; } if (this._running) { // if it's disposed. if (!signal) { if (this._onContextDisposed) { try { this._onContextDisposed.call(undefined); } catch (error) { asap(() => { throw error; }); } } } this._state = State.fulfilled; } else { this._state = State.skipped; } if (this._chainedPromise) { let promise = this._chainedPromise; if (promise._context === this._context) { promise._skip(signal); } else { promise._grab(State.fulfilled); } } else if (this._chainedPromises) { for (let promise of this._chainedPromises) { if (promise._context === this._context) { promise._skip(signal); } else { promise._grab(State.fulfilled); } } } if (signal && signal.preliminary) { signal.preliminary = false; if (this._handledPromise) { this._handledPromise._skip(signal); } else if (this._handledPromises) { for (let promise of this._handledPromises) { promise._skip(signal); } } } else { if (this._handledPromise) { this._handledPromise._relay(State.fulfilled); } else if (this._handledPromises) { for (let promise of this._handledPromises) { promise._relay(State.fulfilled); } } } this._relax(); } /** * Go to a specific promise that matches given label. */ private _goto(signal: GoToSignal): void { if (this._state !== State.pending) { return; } this._state = this._running ? State.fulfilled : State.skipped; if (this._chainedPromise) { let promise = this._chainedPromise; if (promise._label === signal.label) { promise._grab(State.fulfilled, signal.value); } else { promise._goto(signal); } } else if (this._chainedPromises) { for (let promise of this._chainedPromises) { if (promise._label === signal.label) { promise._grab(State.fulfilled, signal.value); } else { promise._goto(signal); } } } if (signal && signal.preliminary) { signal.preliminary = false; if (this._handledPromise) { this._handledPromise._goto(signal); } else if (this._handledPromises) { for (let promise of this._handledPromises) { promise._goto(signal); } } } else { if (this._handledPromise) { this._handledPromise._relay(State.fulfilled); } else if (this._handledPromises) { for (let promise of this._handledPromises) { promise._relay(State.fulfilled); } } } this._relax(); } /** * Set handlers to undefined. */ private _relax(): void { if (this._onPreviousFulfilled) { this._onPreviousFulfilled = undefined; } if (this._onPreviousRejected) { this._onPreviousRejected = undefined; } if (this._onContextDisposed) { this._onContextDisposed = undefined; } if (this._chainedPromise) { this._chainedPromise = undefined; } else { this._chainedPromises = undefined; } if (this._handledPromise) { this._handledPromise = undefined; } else { this._handledPromises = undefined; } } /** * The `then` method that follows * [Promises/A+ specifications](https://promisesaplus.com). * @param onfulfilled Fulfillment handler. * @param onrejected Rejection handler. * @return Created promise. */ then<TResult>(onfulfilled: OnFulfilledHandler<T, TResult>, onrejected?: OnRejectedHandler<TResult>): Promise<TResult> { let promise = new Promise<any>(this._context); if (typeof onfulfilled === 'function') { promise._onPreviousFulfilled = onfulfilled; } if (typeof onrejected === 'function') { promise._onPreviousRejected = onrejected; } if (this._state === State.pending) { if (this._chainedPromise) { this._chainedPromises = [this._chainedPromise, promise]; this._chainedPromise = undefined; } else if (this._chainedPromises) { this._chainedPromises.push(promise); } else { this._chainedPromise = promise; } } else { if (!this._handled) { this._handled = true; } promise._grab(this._state, this._valueOrReason); } return promise; } /** * Resolve the promise with a value or thenable. * @param resolvable The value to fulfill or thenable to resolve. */ resolve(resolvable?: Resolvable<T>): void { this._unpack(resolvable, (state, valueOrReason) => this._grab(state, valueOrReason)); } /** * Reject this promise with a reason. * @param reason Rejection reason. */ reject(reason: any): void { this._grab(State.rejected, reason); } /** * Like `then` but accepts the first extra parameter as the label of * current part. * @param label Part label. * @param onfulfilled Fulfillment handler. * @param onrejected Rejection handler. * @return Created promise. */ label<TResult>(label: string, onfulfilled: OnFulfilledHandler<T, TResult>, onrejected?: OnRejectedHandler<TResult>): Promise<TResult> { let promise = this.then(onfulfilled, onrejected); promise._label = label; return promise; } /** * Set up the interruption handler of the promise. * An interruption handler will be called if either the `onfulfilled` * or `onrejected` handler of the promise has been called but * interrupted due to context disposal. * (by break signal or the canceling of the context). * @param oninerrupted Interruption handler. * @return Current promise. */ interruption(oncontextdisposed: OnContextDisposedHandler): Promise<T> { if (this._state === State.pending) { if (this._onContextDisposed) { throw new Error('Interruption handler has already been set'); } this._onContextDisposed = oncontextdisposed; } else { // To unify error handling behavior, handler would not be invoked // if it's added after promise state being no longer pending. options.logger.warn('Handler added after promise state no longer being pending'); } return this; } /** * Enclose current promise context. * @return Current promise. */ enclose(): Promise<T> { this._context._enclosed = true; return this; } /** * Create a promise that will be fulfilled in given time after * its previous promise becomes fulfilled. * The fulfilled value will be relayed. * @param timeout Timeout in milliseconds. * @return Current promise. */ delay(timeout: number): Promise<T> { return this.then(value => { return new Promise<T>(resolve => { setTimeout(() => resolve(value), Math.floor(timeout) || 0); }); }); } /** * Reject the promise with `TimeoutError` if it's still pending after * timeout. The timer starts once this method is called * (usually before the fulfillment of previous promise). * @param timeout Timeout in milliseconds. * @return Current promise. */ timeout(timeout: number, message?: string): Promise<T> { this._context._enclosed = true; setTimeout(() => { if (this._state === State.pending) { this._relay(State.rejected, new TimeoutError(message)); this._context.disposeSubContexts(); } }, Math.floor(timeout) || 0); return this; } /** * Handle another promise or node style callback with the value or * reason of current promise. * @param promise A promise with the same type as current promise. * @return Current promise. */ handle(promise: Promise<T>): Promise<T>; /** * @param callback Node style callback. * @return Current promise. */ handle(callback: NodeStyleCallback<T>): Promise<T>; handle(promiseOrCallback: Promise<T> | NodeStyleCallback<T>): Promise<T> { if (promiseOrCallback instanceof Promise) { if (this._state === State.pending) { if (this._handledPromise) { this._handledPromises = [this._handledPromise, promiseOrCallback]; this._handledPromise = undefined; } else if (this._handledPromises) { this._handledPromises.push(promiseOrCallback); } else { this._handledPromise = promiseOrCallback; } } else { if (!this._handled) { this._handled = true; } promiseOrCallback._relay(this._state, this._valueOrReason); } } else if (typeof promiseOrCallback === 'function') { this.then( value => { (promiseOrCallback as NodeStyleCallback<T>)(undefined, value); }, reason => { (promiseOrCallback as NodeStyleCallback<T>)(reason, undefined) } ); } else { throw new TypeError('Unsupported type to handle'); } return this; } /** * Create a disposable resource promise. * @param disposor A synchronous function to handle resource disposing. * @return Created disposable resource promise. */ disposable(disposer: Disposer<T>): Promise<Disposable<T>> { return this.then(resource => { return { resource, dispose: disposer }; }); } /** * Like `then` with only an `onfulfilled` handler, but will relay the * previous fulfilled value instead of value returned by its own * `onfulfilled` handler. * @param onfulfilled Fulfillment handler. * @return Created promise. */ tap(onfulfilled: OnFulfilledHandler<T, void>): Promise<T> { let relayValue: T; return this .then(value => { relayValue = value; return onfulfilled(value); }) .then(() => relayValue); } /** * Spread a fulfilled array-like value as arguments of the given handler. * @param onfulfilled Handler that takes the spread arguments. * @return Created promise. */ spread<TResult>(onfulfilled: OnFulfilledSpreadHandler<TResult>): Promise<TResult> { return this.then(value => onfulfilled.apply(undefined, value)); } /** * A shortcut of `promise.then(undefined, onrejected)`. */ fail(onrejected: OnRejectedHandler<T>): Promise<T> { return this.then<T>(undefined, onrejected); } /** * Like `fail` but can specify type of reason to catch. * @param onrejected Rejection handler. * @return Created promise. */ catch(onrejected: OnRejectedHandler<T>): Promise<T>; /** * @param ReasonType Type of reasons to catch. * @param onrejected Rejection handler. * @return Created promise. */ catch(ReasonType: Function, onrejected: OnRejectedHandler<T>): Promise<T>; catch(ReasonType: Function | OnRejectedHandler<T>, onrejected?: OnRejectedHandler<T>): Promise<T> { if (typeof onrejected === 'function') { return this.then<T>(undefined, reason => { if (reason instanceof ReasonType) { return onrejected(reason); } else { throw reason; } }); } else { onrejected = ReasonType as OnRejectedHandler<T>; return this.then<T>(undefined, onrejected); } } /** * A shortcut of `Promise.map`, assuming the fulfilled value of * previous promise is a array. * @param callback Map callback. * @return Created promise. */ map<T>(callback: MapCallback<any, T>): Promise<T[]> { return this.then((values: any) => Promise.map(values, callback)); } /** * A shortcut of `Promise.map`, assuming the fulfilled value of * previous promise is a array. * @param callback Map callback. * @return Created promise. */ reduce<TResult>(callback: ReduceCallback<any, TResult>, initialValue?: TResult): Promise<TResult> { return this.then((values: any) => Promise.reduce(values, callback, initialValue)); } /** * A shortcut of `Promise.each`, assuming the fulfilled value of * previous promise is a array. * @param callback Each callback. * @return Created promise. */ each<T>(callback: EachCallback<T>): Promise<boolean> { return this.then((values: any) => Promise.each(values, callback)); } /** * A shortcut of `Promise.waterfall`, take the fulfilled value of * previous promise as initial result. */ waterfall<TValue>(values: TValue[], callback: WaterfallCallback<TValue, T>): Promise<T> { return this.then(initialResult => Promise.waterfall(values, initialResult, callback)); } /** * A shortcut of `Promise.retry`. */ retry<TResult>(callback: RetryCallback<TResult>): Promise<TResult>; retry<TResult>(options: RetryOptions, callback: RetryCallback<TResult>): Promise<TResult>; retry<TResult>(options: RetryOptions, callback?: RetryCallback<TResult>): Promise<TResult> { return this.then(() => Promise.retry(options, callback)); } /** * Log the value specified on fulfillment, or if not, the fulfilled value or * rejection reason of current promise after the previous promise becomes settled. * @param object Specified value to log. * @return Created promise. */ log(object?: any): Promise<T> { if (object === undefined) { return this.then(value => { if (value !== undefined) { options.logger.log(value); } return value; }, reason => { options.logger.error(reason && (reason.stack || reason.message) || reason); return undefined; }); } else { return this.tap(() => { options.logger.log(object); }); } } /** * Call `this.then` with `onrejected` handler only, and throw the * rejection reason if any. */ done(): void { this.then(undefined, reason => { asap(() => { throw reason; }); }); } /** * (get) A promise that will be rejected with a pre-break signal if previous * promise is fulfilled with a non-`false` value. */ get break(): Promise<any> { return this.then(value => { if (<any>value !== false) { throw new BreakSignal(true); } }); } /** * Create a promise that will be rejected with a goto signal if previous * promise is fulfilled with a non-`false` value. */ goto(label: string, value?: any): Promise<any> { return this.then(value => { if (<any>value !== false) { throw new GoToSignal(label, value, true); } }); } /** * (get) A promise that will eventually be fulfilled with `undefined`. */ get void(): Promise<void> { return this.then(() => undefined); } /** * (get) A promise that will eventually been fulfilled with `true`. */ get true(): Promise<boolean> { return this.then(() => true); } /** * (get) A promise that will eventually been fulfilled with `false`. */ get false(): Promise<boolean> { return this.then(() => false); } /** * (get) Get the context of current promise. */ get context(): Context { return this._context; } /** * (get) A boolean that indicates whether the promise is pending. */ get pending(): boolean { return this._state === State.pending; } /** * (get) A boolean that indicates whether the promise is fulfilled. */ get fulfilled(): boolean { return this._state === State.fulfilled; } /** * (get) A boolean that indicates whether the promise is rejected. */ get rejected(): boolean { return this._state === State.rejected; } /** * (get) A boolean that indicates whether the promise is interrupted. */ get skipped(): boolean { return this._state === State.skipped; } /** * @deperacated * (get) A boolean that indicates whether the promise is interrupted. */ @deprecated('skipped', '0.4') get interrupted(): boolean { return this._state === State.skipped; } // Static helpers /** * A shortcut of `Promise.void.then(onfulfilled)`. * @param onfulfilled Fulfillment handler. * @return Created promise. */ static then<TResult>(onfulfilled: OnFulfilledHandler<void, TResult>): Promise<TResult> { return Promise.void.then(onfulfilled); } /** * Resolve a value or thenable as a promise. * @return The value itself if it's a ThenFail Promise, * otherwise the created promise. */ static resolve(): Promise<void>; /** * @return The value itself if it's a ThenFail Promise, * otherwise the created promise. */ static resolve<T>(resolvable: Resolvable<T>): Promise<T>; static resolve<T>(resolvable?: Resolvable<T>): Promise<T> { if (resolvable instanceof Promise) { return resolvable; } else { let promise = new Promise<T>(); promise.resolve(resolvable); return promise; } } /** * Create a promise rejected by specified reason. * @param reason Rejection reason. * @return Created promise. */ static reject(reason: any): Promise<void>; /** * @param reason Rejection reason. * @return Created promise. */ static reject<T>(reason: any): Promise<T>; static reject<T>(reason: any): Promise<T> { let promise = new Promise<T>(); promise.reject(reason); return promise; } /** * Alias of `Promise.resolve`. */ static when<T>(value: Resolvable<T>): Promise<T> { return Promise.resolve(value); } /** * Create a promise with given context. * @param context Promise context. * @return Created promise. */ static context(context: Context): Promise<void> { let promise = new Promise<void>(context); promise.resolve(); return promise; } /** * Create a promise that will be fulfilled with `undefined` in given * time. * @param timeout Timeout in milliseconds. * @return Created promise. */ static delay(timeout: number): Promise<void> { return new Promise<void>(resolve => { setTimeout(() => resolve(), Math.floor(timeout) || 0); }); } /** * Create a promise that will be fulfilled: * * 1. when all values are fulfilled. * 2. with the value of an array of fulfilled values. * * And will be rejected: * * 1. if any of the values is rejected. * 2. with the reason of the first rejection as its reason. * 3. once the first rejection happens. * * @return Created promise. */ static all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>, Resolvable<T6>, Resolvable<T7>, Resolvable<T8>, Resolvable<T9>, Resolvable<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; static all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>, Resolvable<T6>, Resolvable<T7>, Resolvable<T8>, Resolvable<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; static all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>, Resolvable<T6>, Resolvable<T7>, Resolvable<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; static all<T1, T2, T3, T4, T5, T6, T7>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>, Resolvable<T6>, Resolvable<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; static all<T1, T2, T3, T4, T5, T6>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>, Resolvable<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>; static all<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Promise<[T1, T2, T3, T4, T5]>; static all<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Promise<[T1, T2, T3, T4]>; static all<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Promise<[T1, T2, T3]>; static all<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Promise<[T1, T2]>; static all<T1>(values: [Resolvable<T1>]): Promise<[T1]>; /** * @param resolvables Resolvables involved. * @return Created promise. */ static all<T>(resolvables: Resolvable<T>[]): Promise<T[]>; // TODO: change return type to Promise<T[]> after TypeDoc upgrades. static all<T>(resolvables: Resolvable<T>[]): Promise<any> { if (!resolvables.length) { return Promise.resolve([]); } let resultsPromise = new Promise<T[]>(); let results: T[] = []; let remaining = resolvables.length; let rejected = false; resolvables.forEach((resolvable, index) => { Promise .resolve(resolvable) .then(result => { if (rejected) { return; } results[index] = result; if (--remaining === 0) { resultsPromise.resolve(results); } }, reason => { if (rejected) { return; } rejected = true; resultsPromise.reject(reason); results = undefined; }); }); return resultsPromise; } /** * Create a promise that is settled the same way as the first passed promise to settle. * It resolves or rejects, whichever happens first. * @param resolvables Promises or values to race. * @return Created promise. */ static race<TResult>(resolvables: Resolvable<TResult>[]): Promise<TResult> { let promise = new Promise<TResult>(); for (let resolvable of resolvables) { Promise .resolve(resolvable) .handle(promise); } return promise; } /** * A promise version of `Array.prototype.map`. * @param values Values to map. * @param callback Map callback. * @return Created promise. */ static map<T, TResult>(values: T[], callback: MapCallback<T, TResult>): Promise<TResult[]> { let results: TResult[] = new Array<TResult>(values.length); return values .reduce((promise, value, index, values) => { return promise .then(() => callback(value, index, values)) .then(result => { results[index] = result; }); }, Promise.resolve()) .then(() => results); } /** * A promise version of `Array.prototype.reduce`. * @param values Values to reduce. * @param callback Reduce callback. * @return Created promise. */ static reduce<T, TResult>(values: T[], callback: ReduceCallback<T, TResult>, initialValue?: TResult): Promise<TResult> { return values.reduce((promise, value, index, values) => { return promise.then(previousValue => { return callback(previousValue, value, index, values); }); }, Promise.resolve(initialValue)); } /** * (breakable) Iterate elements in an array one by one. * TResult `false` or a promise that will eventually be fulfilled with * `false` to interrupt iteration. * @param values Values to iterate. * @param callback Each callback. * @return A promise that will be fulfiled with a boolean which * indicates whether the iteration completed without interruption. */ static each<T>(values: T[], callback: EachCallback<T>): Promise<boolean> { return values .reduce((promise, value, index, values) => { return promise.then(result => { if (result === false) { throw new BreakSignal(); } return callback(value, index, values); }); }, Promise.resolve<boolean | void>(undefined)) .then(() => true) .enclose() .then(completed => !!completed); } /** * (breakable) Pass the last result to the same callback with pre-set values. * @param values Pre-set values that will be passed to the callback one * by one. * @param initialResult The initial result for the very first call. * @param callback Waterfall callback. */ static waterfall<T, TResult>(values: T[], initialResult: TResult, callback: WaterfallCallback<T, TResult>): Promise<TResult> { let lastResult = initialResult; return Promise .each(values, (value, index, array) => { let callbackPromise = Promise .then(() => callback(value, lastResult, index, array)) .then(result => result); return callbackPromise .enclose() .then(result => { if (callbackPromise.interrupted) { return false; } else { lastResult = result; return undefined; } }); }) .then(() => lastResult); } /** * Retry the process in the callback for several times. * @param callback Retry callback. * @return Created promise. */ static retry<TResult>(callback: RetryCallback<TResult>): Promise<TResult>; /** * @param options Retry options. * @param callback Retry callback. * @return Created promise. */ static retry<TResult>(options: RetryOptions, callback: RetryCallback<TResult>): Promise<TResult>; static retry<TResult>(options: RetryOptions = {}, callback?: RetryCallback<TResult>): Promise<TResult> { if ( callback === undefined && typeof options === 'function' ) { callback = <any>options; options = {}; } let { limit = 3, interval = 0 } = options; let lastReason: any; let attemptIndex = 0; return process(); function process(): Promise<TResult> { return Promise .then(() => callback(lastReason, attemptIndex++)) .enclose() .fail(reason => { if (attemptIndex >= limit) { throw reason; } lastReason = reason; if (interval) { return Promise .delay(interval) .then(() => process()); } else { return process(); } }); } } /** * Use a disposable resource and dispose it after been used. * @param disposable The disposable resource or a thenable of * disposable resource. * @param handler Using handler. * @return Created promise. */ static using<T, TResult>(disposable: Resolvable<Disposable<T>>, handler: OnFulfilledHandler<T, TResult>): Promise<TResult> { let resolvedDisposable: Disposable<T>; let promise = Promise .resolve(disposable) .then(disposable => { resolvedDisposable = disposable; return handler(disposable.resource); }); let disposed = false; function dispose(): void { if (!disposed) { // Change the value of `disposed` first to avoid exception in // `resolvedDisposable.dispose()` causing `onrejected` handler been called // again. disposed = true; resolvedDisposable.dispose(resolvedDisposable.resource); } } promise .interruption(dispose) .then(dispose, dispose); return promise; } /** * Invoke a Node style asynchronous function that accepts the last * argument as callback. * @param fn Node style asynchronous function. * @param args Arguments. * @return Created promise. */ static invoke(fn: Function, ...args: any[]): Promise<void>; static invoke<TResult>(fn: Function, ...args: any[]): Promise<TResult>; static invoke<TResult>(fn: Function, ...args: any[]): Promise<TResult> { return new Promise<TResult>((resolve, reject) => { args = args.concat((error: any, value: TResult) => { if (error) { reject(error); } else { resolve(value); } }); fn.apply(undefined, args); }); } private static _forChildProcess(process: ChildProcess): Promise<void> { return new Promise<void>((resolve, reject) => { process.on('exit', onexit); process.on('error', onerror); function removeListeners() { process.removeListener('exit', onexit); process.removeListener('error', onerror); } function onexit(code: number) { removeListeners(); if (code === 0) { resolve(); } else { reject(new Error('Invalid exit code')); } } function onerror(error: any) { asap(removeListeners); reject(error); } }); } private static _forEventEmitter<T>(emitter: EventEmitter, types: string | string[], errorEmitters: EventEmitter[] = []): Promise<T> { errorEmitters.unshift(emitter); if (typeof types === 'string') { types = [types as string]; } return new Promise<T>((resolve, reject) => { for (let type of types) { emitter.on(type, onsuccess); } for (let emitter of errorEmitters) { emitter.on('error', onerror); } function removeListeners() { for (let type of types) { emitter.removeListener(type, onsuccess); } for (let emitter of errorEmitters) { emitter.removeListener('error', onerror); } } function onsuccess(value: T) { removeListeners(); resolve(value); } function onerror(error: any) { asap(removeListeners); reject(error); } }); } /** * Create a promise for a `ChildProcess` object. * @param process - The process to listen on 'exit' and 'error' events for fulfillment * or rejection. */ static for(process: ChildProcess): Promise<void>; /** * Create a promise for an event emitter. * @param emitter - The emitter to listen on 'error' event for rejection, * and given event types for fulfillment. * @param type - A string or an array of string of event types for * fulfillment. * @param errorEmitters - Other emitters to listen on 'error' event for rejection. */ static for(emitter: EventEmitter, types: string | string[], errorEmitters?: EventEmitter[]): Promise<void>; static for<T>(emitter: EventEmitter, types: string | string[], errorEmitters?: EventEmitter[]): Promise<T>; static for<T>(emitter: EventEmitter, types?: string | string[], errorEmitters?: EventEmitter[]): Promise<T | void> { if (ChildProcessConstructor && emitter instanceof ChildProcessConstructor && types === undefined) { return this._forChildProcess(emitter as ChildProcess); } if (EventEmitterConstructor && emitter instanceof EventEmitterConstructor) { return this._forEventEmitter<T>(emitter, types, errorEmitters); } throw new TypeError('Unsupported object'); } /** * (fake statement) This getter will always throw a break signal that interrupts the promises chain. * * Example: * * ```ts * promise * .then(() => { * if (toBreak) { * Promise.break; * } * * // Or not to break. * }) * .then(() => { * // If `toBreak` is true, it will never enter this handler. * }, () => { * // Nor this handler. * }); * ``` */ static get break(): void { throw new BreakSignal(); } /** (get) The break signal. */ static get breakSignal(): any { return new BreakSignal(); } /** (get) The pre-break signal. */ static get preBreakSignal(): any { return new BreakSignal(true); } /** (fake statement) This method will throw an `GoToSignal` with specified `label`. */ static goto(label: string, value?: any): void { throw new GoToSignal(label, value); } /** * (get) A promise that has already been fulfilled with `undefined`. */ static get void(): Promise<void> { let promise = new Promise<void>(); promise.resolve(undefined); return promise; } /** * (get) A promise that has already been fulfilled with `true`. */ static get true(): Promise<boolean> { let promise = new Promise<boolean>(); promise.resolve(true); return promise; } /** * (get) A promise that has already been fulfilled with `false`. */ static get false(): Promise<boolean> { let promise = new Promise<boolean>(); promise.resolve(false); return promise; } } /////////// // Retry // /////////// export type RetryCallback<TResult> = (lastReason: any, attemptIndex: number) => Resolvable<TResult>; export interface RetryOptions { /** Try limit times (defaults to 3). */ limit?: number; /** Interval between two tries (defaults to 0). */ interval?: number; } //////////////// // Disposable // //////////////// export type Disposer<TResource> = (resource: TResource) => void; export interface Disposable<TResource> { resource: TResource; dispose: Disposer<TResource>; } export const using: typeof Promise.using = Promise.using; export const invoke: typeof Promise.invoke = Promise.invoke;
the_stack
import assert from "assert"; import { malloc, free, freeAll, calloc, realloc, get__free, readBlockNext, get__used, readBlockSize, align, get_top, get_doCompact, get_doSplit, get_end, } from "./functional"; import { allocatorInit, stats as readStats } from "./functional"; import type { AllocatorState } from "./functionalInterfaces"; const POOL_OVERHEAD = 7 * 4; const BLOCK_OVERHEAD = 4 * 4; describe("malloc functional", () => { let allocatorState: AllocatorState; beforeEach(() => { // allocatorState = new MemPool({ size: 0x100 }); allocatorState = allocatorInit({ size: 0x100, align: 8, start: 0, end: 0x100, compact: true, split: true, minSplit: 24, }); }); it("allocatorInit", () => { assert.strictEqual(allocatorState.options.start, 0); assert.strictEqual(get_top(allocatorState.state), align(POOL_OVERHEAD, 8)); assert(get_doCompact(allocatorState.state)); assert(get_doSplit(allocatorState.state)); assert.strictEqual( get_end(allocatorState.state), allocatorState.u8.buffer.byteLength, "When end option not specified, end should be byteLength" ); // p = new MemPool({ size: 0x100, start: 0x0c, end: 0x80 }); allocatorState = allocatorInit({ size: 0x100, align: 8, start: 0x0c, end: 0x80, compact: true, split: true, minSplit: 24, }); assert.strictEqual(allocatorState.options.start, 0x0c); assert.strictEqual( get_top(allocatorState.state), align(0x0c + POOL_OVERHEAD, 8) ); assert.strictEqual(get_end(allocatorState.state), 0x80); assert.throws(() => { // assert.throws(() => new MemPool({ size: 0x100, start: 0x0, end: 0x0 })); allocatorState = allocatorInit({ size: 0x100, align: 8, start: 0x0, end: 0x0, compact: true, split: true, minSplit: 24, }); }); assert.throws(() => { // new MemPool({ size: 0x100, start: 0x100, end: 0x200 }) allocatorState = allocatorInit({ size: 0x100, align: 8, start: 0x100, end: 0x200, compact: true, split: true, minSplit: 24, }); }); assert.throws(() => { // () => new MemPool({ size: 0x100, start: 0x80, end: 0x0 }) allocatorState = allocatorInit({ size: 0x100, align: 8, start: 0x80, end: 0x0, compact: true, split: true, minSplit: 24, }); }); }); it("malloc / free", () => { assert(!malloc(allocatorState, 256), "insufficient mem"); assert(!malloc(allocatorState, -1), "neg size"); assert(!malloc(allocatorState, 0), "zero size"); const base = readStats(allocatorState).top; let a = malloc(allocatorState, 12); let b = malloc(allocatorState, 31); let c = malloc(allocatorState, 24); assert.strictEqual(a, base + BLOCK_OVERHEAD, "a"); assert.strictEqual(b, a + 16 + BLOCK_OVERHEAD, "b"); assert.strictEqual(c, b + 32 + BLOCK_OVERHEAD, "c"); // state check let stats = readStats(allocatorState); assert.strictEqual(stats.top, c + 24, "top"); assert.deepStrictEqual(stats.free, { count: 0, size: 0 }); assert.deepStrictEqual(stats.used, { count: 3, size: 16 + 32 + 24 + 3 * BLOCK_OVERHEAD, }); // free all assert(free(allocatorState, a), "free a"); assert(free(allocatorState, c), "free b"); assert(free(allocatorState, b), "free c"); // assert(!free(allocatorState, b), "free b (repeat)"); stats = readStats(allocatorState); assert.strictEqual(stats.top, base, "top2"); assert.deepStrictEqual(stats.free, { count: 0, size: 0 }); assert.deepStrictEqual(stats.used, { count: 0, size: 0 }); // alloc & split free block a = malloc(allocatorState, 32); assert.strictEqual(a, base + BLOCK_OVERHEAD, "a2"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 0, size: 0 }); assert.deepStrictEqual(stats.used, { count: 1, size: 32 + BLOCK_OVERHEAD }); assert.strictEqual(stats.top, base + 32 + BLOCK_OVERHEAD, "top3"); // alloc next block & free prev b = malloc(allocatorState, 12); assert.strictEqual(b, base + 32 + BLOCK_OVERHEAD * 2, "b2"); assert(free(allocatorState, a), "free a2"); // re-alloc from free & split a = malloc(allocatorState, 8); assert.strictEqual(a, base + BLOCK_OVERHEAD, "a3"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 1, size: 24 }); assert.deepStrictEqual(stats.used, { count: 2, size: 24 + 2 * BLOCK_OVERHEAD, }); assert.strictEqual(stats.top, base + 32 + 16 + 2 * BLOCK_OVERHEAD, "top4"); // join both free blocks assert(free(allocatorState, b), "free b2"); // extend free block + top b = malloc(allocatorState, 64); assert.strictEqual(b, base + 8 + 2 * BLOCK_OVERHEAD, "b3"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 0, size: 0 }); assert.deepStrictEqual(stats.used, { count: 2, size: 8 + 64 + 2 * BLOCK_OVERHEAD, }); assert.strictEqual(stats.top, base + 8 + 64 + 2 * BLOCK_OVERHEAD, "top5"); // alloc at top, below min size c = malloc(allocatorState, 1); // non-continous free chain assert(free(allocatorState, c), "free c2"); // top reset to before assert.strictEqual(stats.top, base + 8 + 64 + 2 * BLOCK_OVERHEAD, "top6"); assert(free(allocatorState, a), "free a3"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 1, size: 8 + BLOCK_OVERHEAD }); assert.deepStrictEqual(stats.used, { count: 1, size: 64 + BLOCK_OVERHEAD }); // top remains unchanged assert.strictEqual(stats.top, base + 8 + 64 + 2 * BLOCK_OVERHEAD, "top7"); // alloc larger size to force walking free chain // and then alloc @ top (reuse earlier block) a = malloc(allocatorState, 27); assert.strictEqual(a, base + 8 + 64 + 3 * BLOCK_OVERHEAD, "a4"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 1, size: 8 + BLOCK_OVERHEAD }); assert.deepStrictEqual(stats.used, { count: 2, size: 64 + 32 + 2 * BLOCK_OVERHEAD, }); assert.strictEqual( stats.top, base + 8 + 64 + 32 + 3 * BLOCK_OVERHEAD, "top8" ); assert(free(allocatorState, a), "free a4"); assert(free(allocatorState, b), "free b3"); stats = readStats(allocatorState); assert.deepStrictEqual(stats.free, { count: 0, size: 0 }); assert.deepStrictEqual(stats.used, { count: 0, size: 0 }); assert.strictEqual(stats.available, 256 - base); assert.strictEqual(stats.top, base, "top9"); freeAll(allocatorState); assert.deepStrictEqual(readStats(allocatorState), { free: { count: 0, size: 0 }, used: { count: 0, size: 0 }, available: allocatorState.u8.buffer.byteLength - base, total: allocatorState.u8.buffer.byteLength, top: base, }); // allocatorState.release(); }); it("calloc", () => { const u8: Uint8Array = (<any>allocatorState).u8; u8.fill(0xff, readStats(allocatorState).top); const a = calloc(allocatorState, 6); assert.deepStrictEqual( [...u8.subarray(a, a + 9)], [0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff] ); }); it("malloc top", () => { const a = malloc(allocatorState, 8); const b = malloc(allocatorState, 8); const c = malloc(allocatorState, 8); const d = malloc(allocatorState, 8); // cause non continuous free chain free(allocatorState, a); free(allocatorState, b); free(allocatorState, d); assert.strictEqual( malloc(allocatorState, allocatorState.u8.buffer.byteLength - d + 1), 0, "malloc top" ); // assert.strictEqual( // allocatorState.mallocAs(Type.U8, allocatorState.u8.buffer.byteLength - d + 1), // null, // "mallocAs top" // ); free(allocatorState, c); }); // We have tests in the other file it.skip("realloc", () => { const a = malloc(allocatorState, 8); allocatorState.u8.fill(0xff, a, a + 8); const block = get__used(allocatorState.state); const bsize = readBlockSize(allocatorState.u32, block); assert.strictEqual(bsize, align(8 + BLOCK_OVERHEAD, 8), "size a"); assert.strictEqual(realloc(allocatorState, a, 0), 0, "too small"); assert.strictEqual(realloc(allocatorState, a, 65), a, "enlarge a"); const usedBlockAfterRealloc = get__used(allocatorState.state); assert.strictEqual(usedBlockAfterRealloc, block); assert.strictEqual( readBlockSize(allocatorState.u32, usedBlockAfterRealloc), align(65 + BLOCK_OVERHEAD, 8) ); // shrink & update top assert.strictEqual(realloc(allocatorState, a, 31), a, "shrink a"); assert.strictEqual( readBlockSize(allocatorState.u32, usedBlockAfterRealloc), align(31 + BLOCK_OVERHEAD, 8) ); assert.strictEqual(get__free(allocatorState.state), 0); assert.strictEqual(get_top(allocatorState.state), a + 32); // add new top block const b = malloc(allocatorState, 8); assert.strictEqual(b, a + 48, "b"); // enlage a again, but need to move after b const a2 = realloc(allocatorState, a, 65); assert.strictEqual(a2, b + 16); assert.deepStrictEqual( [...allocatorState.u8.slice(a2, a2 + 9)], [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0] ); }); // it("reallocArray", () => { // const a = allocatorState.callocAs(Type.F32, 4, 1); // assert.deepStrictEqual( // [...allocatorState.reallocArray(a!, 8)!], // [1, 1, 1, 1, 0, 0, 0, 0] // ); // assert.strictEqual(allocatorState.reallocArray(a!, 10000), undefined); // assert.strictEqual(allocatorState.reallocArray(new Float32Array(4), 8), undefined); // }); // We now have merge on by default it.skip("no compact", () => { allocatorState = allocatorInit({ size: 0x100, split: true, start: 0, end: 0x100, align: 8, minSplit: 24, compact: false, }); const a = malloc(allocatorState, 8); const a1 = malloc(allocatorState, 8); const a2 = malloc(allocatorState, 8); free(allocatorState, a); free(allocatorState, a1); free(allocatorState, a2); assert.strictEqual(get__free(allocatorState.state) + BLOCK_OVERHEAD, a); assert.strictEqual( readBlockNext(allocatorState.u32, get__free(allocatorState.state)) + BLOCK_OVERHEAD, a1 ); assert.strictEqual( readBlockNext( allocatorState.u32, readBlockNext(allocatorState.u32, get__free(allocatorState.state)) ) + BLOCK_OVERHEAD, a2 ); assert.strictEqual( readBlockNext( allocatorState.u32, readBlockNext( allocatorState.u32, readBlockNext(allocatorState.u32, get__free(allocatorState.state)) ) ), 0 ); }); it("no split", () => { // allocatorState = new MemPool({ size: 0x100, split: true }); allocatorState = allocatorInit({ size: 0x100, split: true, start: 0, end: 0x100, align: 8, minSplit: 24, compact: true, }); const base = readStats(allocatorState).top; let a = malloc(allocatorState, 32); malloc(allocatorState, 8); free(allocatorState, a); malloc(allocatorState, 8); assert.strictEqual(get__used(allocatorState.state), base); assert.strictEqual( readBlockSize(allocatorState.u32, get__used(allocatorState.state)), 8 + BLOCK_OVERHEAD ); assert.strictEqual( get__free(allocatorState.state), base + 8 + BLOCK_OVERHEAD ); assert.strictEqual( readBlockSize(allocatorState.u32, get__free(allocatorState.state)), 24 ); allocatorState = allocatorInit({ size: 0x100, split: false, start: 0, end: 0x100, align: 8, minSplit: 24, compact: true, }); a = malloc(allocatorState, 32); malloc(allocatorState, 8); free(allocatorState, a); malloc(allocatorState, 8); assert.strictEqual(get__used(allocatorState.state), base); assert.strictEqual( readBlockSize(allocatorState.u32, get__used(allocatorState.state)), 32 + BLOCK_OVERHEAD ); assert.strictEqual(get__free(allocatorState.state), 0); }); // it("malloc (align 16)", () => { // allocatorState = new MemPool({ size: 0x100, align: 16 }); // let p: any = allocatorState; // const base = allocatorState.stats().top; // let a = allocatorState.callocAs(Type.U8, 15); // let b = allocatorState.callocAs(Type.U8, 11); // let c = allocatorState.callocAs(Type.U8, 7); // let d = allocatorState.callocAs(Type.U8, 3); // let e = allocatorState.callocAs(Type.U8, 1); // assert.strictEqual(a!.byteOffset, base + BLOCK_OVERHEAD, "a"); // assert.strictEqual( // b!.byteOffset, // align(a!.byteOffset + BLOCK_OVERHEAD + 15, 16), // "b" // ); // assert.strictEqual( // c!.byteOffset, // align(b!.byteOffset + BLOCK_OVERHEAD + 11, 16), // "c" // ); // assert.strictEqual( // d!.byteOffset, // align(c!.byteOffset + BLOCK_OVERHEAD + 7, 16), // "d" // ); // assert.strictEqual( // e!.byteOffset, // align(d!.byteOffset + BLOCK_OVERHEAD + 3, 16), // "e" // ); // let stats = readStats(allocatorState); // assert.strictEqual(stats.top, align(e!.byteOffset + 1, 16) - BLOCK_OVERHEAD); // free(allocatorState, d!); // assert.strictEqual(get__free(allocatorState.state), d!.byteOffset - BLOCK_OVERHEAD); // free(allocatorState, b!); // assert.strictEqual(get__free(allocatorState.state), b!.byteOffset - BLOCK_OVERHEAD); // assert.strictEqual(p.blockNext(get__free(allocatorState.state)), d!.byteOffset - BLOCK_OVERHEAD); // free(allocatorState, c!); // assert.strictEqual(get__free(allocatorState.state), b!.byteOffset - BLOCK_OVERHEAD); // assert.strictEqual(blockSize(allocatorState.u32, get__free(allocatorState.state)), e!.byteOffset - b!.byteOffset); // free(allocatorState, a!); // assert.strictEqual(get__free(allocatorState.state), a!.byteOffset - BLOCK_OVERHEAD); // assert.strictEqual(blockSize(allocatorState.u32, get__free(allocatorState.state)), e!.byteOffset - a!.byteOffset); // free(allocatorState, e!); // assert.strictEqual(get__free(allocatorState.state), 0); // assert.strictEqual(get__used(allocatorState.state), 0); // assert.strictEqual(p.top, base); // }); // it("freeAll (align 16)", () => { // pool = new MemPool({ size: 0x100, align: 16 }); // const base = readStats(allocatorState).top; // pool.callocAs(Type.U8, 15); // pool.callocAs(Type.U8, 11); // freeAll(allocatorState); // assert.strictEqual(readStats(allocatorState).top, base); // }); });
the_stack
import * as Cms from '../app/cms'; import {modelToSchema, schemaToModel, slugify} from '../app/cms'; import {Field, FieldType, Node, NodeType, normalizeModel, TreeModel} from "../app/model"; import {readdirSync} from "fs"; const fs = require("fs"); const Promise = require("bluebird"); const readFile = Promise.promisify(fs.readFile); let jsonTree; /** * Utility methods that loads model and data from disk and cache them in a global variable. * @returns {Promise} */ const loadTree = () => { const promise = jsonTree ? Promise.resolve(jsonTree) // reparse from cache : Promise.all([readFile('test/data/model.json', 'utf-8'), readFile('test/data/data.json', 'utf-8')]) .then(results => { jsonTree = { model: results[0], data: results[1] }; return jsonTree; }); return promise.then(json => { let normalizedModel = normalizeModel(JSON.parse(json.model)); return { model: normalizedModel, schema: modelToSchema(normalizedModel), data: JSON.parse(json.data) } }); }; test('testNormalizeModel', () => { const model = { name: 'Foo', children: [], fields: [ 'field1', { name: 'field2' }, { name: 'field3', type: 'boolean' } ] }; const normalized = normalizeModel(model); expect(normalized.getFieldNamed('field1').type).toBe(FieldType.String); expect(normalized.getFieldNamed('field2').type).toBe(FieldType.String); expect(normalized.getFieldNamed('field3').type).toBe(FieldType.Boolean); }); test('checkNormalize', () => { return loadTree().then(tree => { const pages = Cms.findNode(tree, "pages"); expect(pages.model.getFieldNamed('Search Enabled').type).toBe(FieldType.Boolean); expect(pages.model.getFieldNamed('Description').type).toBe(FieldType.TextArea); expect(pages.model.getFieldNamed('Description').className).toBe('short'); }); }); test(`findNode(messages)`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, "messages"); expect(Cms.getNodeType(node)).toBe(NodeType.TYPE_TREE); const treeModel : TreeModel = <TreeModel> node.model; expect(node.model.name).toBe("Messages"); expect(treeModel.children.length).toBe(2); expect(treeModel.children[0].name).toBe("Errors"); expect(node.data.errors).toBeDefined(); expect(node.path).toBe('messages'); }); }); test(`findNode(nav/header)`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, "nav/header"); expect(node.model.name).toBe("Header"); expect(node.data.length).toBe(3); expect(node.data[0].label).toBe('Home'); expect(node.path).toBe('nav/header'); }); }); test(`findNode(nav/header/2)`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, "nav/header/2"); expect(node.model.name).toBe("Header"); expect(node.data.label).toBe('Blog'); expect(node.path).toBe('nav/header/2'); }); }); test(`findNode(messages/errors)`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, "messages/errors"); expect(node.model.name).toBe("Errors"); expect(node.data.internalError).toBeDefined(); expect(node.path).toBe('messages/errors'); }); }); test(`findNode(messages/errors/internalError)`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, "messages/errors/internalError"); expect(node.model.name).toBe("Errors"); expect(node.data.title).toBe('Internal Error'); expect(node.path).toBe('messages/errors/internalError'); }); }); const testTreePathAndIndex = (path, expectedFullPath, expectedTreePath, expectedIndex) => { test(`treePathAndIndex(${path})`, () => { return loadTree().then(tree => { const res = Cms.treePathAndIndex(tree, path); expect(res.fullPath).toBe(expectedFullPath); expect(res.treePath).toBe(expectedTreePath); expect(res.dataIndex).toBe(expectedIndex); }); }); }; testTreePathAndIndex('messages/errors/internalError', 'messages/errors/internalError', 'messages/errors', 'internalError'); testTreePathAndIndex('site_info', 'site_info', 'site_info', -1); testTreePathAndIndex('nav/header', 'nav/header', 'nav/header', -1); testTreePathAndIndex('nav/header/2', 'nav/header/2', 'nav/header', 2); // The following cases are debatable (should we rather throw an error id a path does not / cannot exist ?... testTreePathAndIndex('nav/header/5', 'nav/header/5', 'nav/header', 5); testTreePathAndIndex('messages/errors/3', 'messages/errors/3', 'messages/errors', "3"); const testFindDeepest = (data, path, depth, extractor) => { test(`findDeepest(${path})`, () => { const result = Cms.findDeepest(data, path); expect(result.depth).toBe(depth); expect(result.node.name).toBe(extractor(data)); }); }; const data1 = { a: { name: 'hello' }, c: { name: 'world' } }; testFindDeepest(data1, "a/b", 1, d => d.a.name); testFindDeepest(data1, "a/b/c", 1, d => d.a.name); testFindDeepest(data1, "a/b/c", 1, d => d.a.name); testFindDeepest(data1, "a/b/c/1", 1, d => d.a.name); const data2 = { a: { b: { c: { name: 'abc' }, name: 'ab' } }, d: { name: 'd' }, name: 'root' }; testFindDeepest(data2, "a/b", 2, d => d.a.b.name); testFindDeepest(data2, "a/b/c", 3, d => d.a.b.c.name); testFindDeepest(data2, "a/b/c/d/e/f/g", 3, d => d.a.b.c.name); testFindDeepest(data2, "foo/bar/hux", 0, d => d.name); // const data3 = { a: { name: 'hello' }, c: { name: 'world' } }; // test("fillPath", () => { // expect(typeof data3.a.b).toBe('undefined'); // expect(data3.c).toBeDefined(); // Cms.fillPath(data3, "a/b"); // expect(data3.a.b).toBeDefined(); // Cms.fillPath(data3, "a/b/d/e/f"); // expect(data3.a.b.d.e.f).toBeDefined(); // expect(data3.c).toBeDefined(); // Cms.fillPath(data3, "c/foo/bar/3"); // expect(data3.c.foo.bar).toBeDefined(); // expect(typeof data3.c.foo.bar).toBe('object'); // }); const testAddListItem = (path, requestedName, expectedNewNames) => { test(`addListItem(${path},${requestedName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); if (!Array.isArray(expectedNewNames)) { expectedNewNames = [ expectedNewNames ]; } expectedNewNames.forEach(expectedNewName => { const newItem = Cms.addItem(node, requestedName).item; expect(newItem[Cms.defaultFieldName(node.model)]).toBe(expectedNewName); }); }); }); }; testAddListItem("nav/header", "New Item", [ "New Item", "New Item (2)", "New Item (3)" ]); testAddListItem("nav/header", "Blog", [ "Blog (2)", "Blog (3)" ]); testAddListItem("nav/header", "Blog (2)", [ "Blog (2)", "Blog (2) (2)", "Blog (2) (3)" ]); const testAddMapItem = (path, requestedName, expectedNewNames) => { test(`addMapItem(${path},${requestedName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); if (!Array.isArray(expectedNewNames)) { expectedNewNames = [ expectedNewNames ]; } expectedNewNames.forEach(expectedNewName => { const newKey = Cms.addItem(node, requestedName).dataIndex; expect(newKey).toBe(expectedNewName); }); }); }); }; testAddMapItem("messages/errors", "internalError", [ "internalError (2)", "internalError (3)" ]); testAddMapItem("messages/errors", "anotherError", [ "anotherError", "anotherError (2)" ]); testAddMapItem("messages/tooltips", "welcome", [ "welcome (2)", "welcome (3)" ]); testAddMapItem("messages/tooltips", "anotherTooltip", [ "anotherTooltip", "anotherTooltip (2)" ]); const testAddNode = (path, nodeType, requestedName, expectedNewNames) => { test(`addNode(${path}, ${nodeType})`, () => { return loadTree().then(tree => { const node : Node<TreeModel> = <Node<TreeModel>> Cms.findNode(tree, path); if (!Array.isArray(expectedNewNames)) { expectedNewNames = [ expectedNewNames ]; } expectedNewNames.forEach(expectedNewName => { const newNode = Cms.addNode(node, requestedName, nodeType); expect(newNode.model.name).toBe(expectedNewName); }); }); }); }; testAddNode("nav", NodeType.TYPE_TREE, "New Node", [ "New Node", "New Node (2)", "New Node (3)" ]); testAddNode("nav", NodeType.TYPE_MAP_OBJECT, "New Map", [ "New Map", "New Map (2)", "New Map (3)" ]); testAddNode("nav", NodeType.TYPE_LIST_OBJECT, "New List", [ "New List", "New List (2)", "New List (3)" ]); testAddNode("nav", NodeType.TYPE_LIST_OBJECT, "Header", [ "Header (2)", "Header (3)" ]); testAddNode("nav", NodeType.TYPE_MAP_OBJECT, "Header", [ "Header (2)", "Header (3)" ]); testAddNode("nav", NodeType.TYPE_TREE, "Header", [ "Header (2)", "Header (3)" ]); const testGetFieldNamed = (path, fieldName) => { test(`getFieldName(${path}, ${fieldName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); const field = Cms.getFieldNamed(node, fieldName); expect(field).toBeDefined(); expect(field.name).toBe(fieldName); }); }); }; testGetFieldNamed("nav/header", 'Url'); testGetFieldNamed("nav/footer", 'Target'); testGetFieldNamed("nav/footer/1", 'Target'); testGetFieldNamed("pages", 'Search Enabled'); const testDeleteField = (path, fieldName) => { test(`deleteField(${path}, ${fieldName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); const field = Cms.getFieldNamed(node, fieldName); const fieldIndex = Cms.getFieldIndex(node, field); Cms.getDataItems(node).forEach(item => { expect(item[Cms.slugify(field.name)]).toBeDefined(); }); Cms.deleteFieldAt(node, fieldIndex); Cms.getDataItems(node).forEach(item => { expect(item[Cms.slugify(field.name)]).toBeUndefined(); }); }); }); }; const testDeleteFieldError = (path, fieldName) => { test(`deleteFieldError(${path}, ${fieldName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); const field = Cms.getFieldNamed(node, fieldName); const fieldIndex = Cms.getFieldIndex(node, field); expect(() => Cms.deleteFieldAt(node, fieldIndex)).toThrow(Error); }); }); }; testDeleteField("nav/header", 'Url'); testDeleteField("nav/footer", 'Label'); testDeleteField("messages/errors", 'Title'); testDeleteFieldError("messages/errors", 'Identifier'); testDeleteFieldError("messages/tooltips", 'Identifier'); testDeleteFieldError("messages/tooltips", 'Message'); const testUpdateField = (path, fieldName, field, expectedData) => { test(`updateField(${path}, ${fieldName})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); const prevField = Cms.getFieldNamed(node, fieldName); const fieldIndex = Cms.getFieldIndex(node, prevField); if (typeof field === 'string') { field = new Field(field); } expect(node.model.fields).not.toContainEqual(field); Cms.updateFieldAt(node, fieldIndex, field); expect(node.model.fields).toContainEqual(field); expect(node.data).toEqual(expectedData); }); }); }; testUpdateField("nav/header", 'Url', "theUrl", [ { "label": "Home", "theurl": "/home" }, { "label": "Product", "theurl": "/product" }, { "label": "Blog", "theurl": "/blog" } ]); testUpdateField("nav/header", 'Url', { name: "Url", type: 'boolean' }, [ { "label": "Home", "url": true }, { "label": "Product", "url": true }, { "label": "Blog", "url": true } ]); testUpdateField("messages/errors", 'Identifier', "Id", { "internalError": { "title": "Internal Error", "message": "An internal error occurred" }, "connectionError": { "title": "Network Error", "message": "There seem to be network issues" } }); testUpdateField("messages/errors", 'Title', "theTitle", { "internalError": { "thetitle": "Internal Error", "message": "An internal error occurred" }, "connectionError": { "thetitle": "Network Error", "message": "There seem to be network issues" } }); testUpdateField("messages/tooltips", 'Identifier', "Id", { "welcome": "Welcome to my web site", "sendEmail": "click to send an email" }); testUpdateField("messages/tooltips", 'Message', "Msg", { "welcome": "Welcome to my web site", "sendEmail": "click to send an email" }); const testRenameNode = (path, name) => { test(`renameNode(${path}, ${name})`, () => { return loadTree().then(tree => { const node = Cms.findNode(tree, path); const previousName = node.model.name; const prev = node.parent!.data[Cms.slugify(node.model.name)]; Cms.renameNode(node, name); expect(node.model.name).toBe(name); expect(node.parent!.data[slugify(name)]).toEqual(prev); expect(node.parent!.data[slugify(previousName)]).toBeUndefined(); }); }); }; testRenameNode('nav/header', 'headers'); testRenameNode('nav', 'navigation'); testRenameNode('messages/errors', 'erreurs'); const testConvertModel2Schema = () => { test(`convertModel2Schema`, () => { return Promise.all([readFile('test/data/model.json', 'utf-8'), readFile('test/data/schema.json', 'utf-8')]) .then(results => { const model = normalizeModel(JSON.parse(results[0])); const modelStr = JSON.stringify(model, null, 2); let schemaStr = results[1]; const schema = JSON.parse(schemaStr); expect(JSON.stringify(modelToSchema(model), null, 2)).toBe(JSON.stringify(JSON.parse(schemaStr), null, 2)); expect(JSON.stringify(schemaToModel(modelToSchema(model)), null, 2)).toBe(modelStr.trim()); expect(JSON.stringify(schemaToModel(schema), null, 2)).toBe(modelStr.trim()); }); }); }; testConvertModel2Schema();
the_stack
import { CharCode } from 'vs/base/common/charCode'; import { KeyCode, KeyCodeUtils, IMMUTABLE_CODE_TO_KEY_CODE, ScanCode, ScanCodeUtils, NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE } from 'vs/base/common/keyCodes'; import { Keybinding, ResolvedKeybinding, SimpleKeybinding, KeybindingModifier, ScanCodeBinding } from 'vs/base/common/keybindings'; import { UILabelProvider } from 'vs/base/common/keybindingLabels'; import { OperatingSystem } from 'vs/base/common/platform'; import { IKeyboardEvent } from 'vs/platform/keybinding/common/keybinding'; import { IKeyboardMapper } from 'vs/platform/keyboardLayout/common/keyboardMapper'; import { BaseResolvedKeybinding } from 'vs/platform/keybinding/common/baseResolvedKeybinding'; import { removeElementsAfterNulls } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { IWindowsKeyboardMapping } from 'vs/platform/keyboardLayout/common/keyboardLayout'; const LOG = false; function log(str: string): void { if (LOG) { console.info(str); } } export interface IScanCodeMapping { scanCode: ScanCode; keyCode: KeyCode; value: string; withShift: string; withAltGr: string; withShiftAltGr: string; } export class WindowsNativeResolvedKeybinding extends BaseResolvedKeybinding<SimpleKeybinding> { private readonly _mapper: WindowsKeyboardMapper; constructor(mapper: WindowsKeyboardMapper, parts: SimpleKeybinding[]) { super(OperatingSystem.Windows, parts); this._mapper = mapper; } protected _getLabel(keybinding: SimpleKeybinding): string | null { if (keybinding.isDuplicateModifierCase()) { return ''; } return this._mapper.getUILabelForKeyCode(keybinding.keyCode); } private _getUSLabelForKeybinding(keybinding: SimpleKeybinding): string | null { if (keybinding.isDuplicateModifierCase()) { return ''; } return KeyCodeUtils.toString(keybinding.keyCode); } public getUSLabel(): string | null { return UILabelProvider.toLabel(this._os, this._parts, (keybinding) => this._getUSLabelForKeybinding(keybinding)); } protected _getAriaLabel(keybinding: SimpleKeybinding): string | null { if (keybinding.isDuplicateModifierCase()) { return ''; } return this._mapper.getAriaLabelForKeyCode(keybinding.keyCode); } protected _getElectronAccelerator(keybinding: SimpleKeybinding): string | null { return this._mapper.getElectronAcceleratorForKeyBinding(keybinding); } protected _getUserSettingsLabel(keybinding: SimpleKeybinding): string | null { if (keybinding.isDuplicateModifierCase()) { return ''; } const result = this._mapper.getUserSettingsLabelForKeyCode(keybinding.keyCode); return (result ? result.toLowerCase() : result); } protected _isWYSIWYG(keybinding: SimpleKeybinding): boolean { return this.__isWYSIWYG(keybinding.keyCode); } private __isWYSIWYG(keyCode: KeyCode): boolean { if ( keyCode === KeyCode.LeftArrow || keyCode === KeyCode.UpArrow || keyCode === KeyCode.RightArrow || keyCode === KeyCode.DownArrow ) { return true; } const ariaLabel = this._mapper.getAriaLabelForKeyCode(keyCode); const userSettingsLabel = this._mapper.getUserSettingsLabelForKeyCode(keyCode); return (ariaLabel === userSettingsLabel); } protected _getDispatchPart(keybinding: SimpleKeybinding): string | null { if (keybinding.isModifierKey()) { return null; } let result = ''; if (keybinding.ctrlKey) { result += 'ctrl+'; } if (keybinding.shiftKey) { result += 'shift+'; } if (keybinding.altKey) { result += 'alt+'; } if (keybinding.metaKey) { result += 'meta+'; } result += KeyCodeUtils.toString(keybinding.keyCode); return result; } protected _getSingleModifierDispatchPart(keybinding: SimpleKeybinding): KeybindingModifier | null { if (keybinding.keyCode === KeyCode.Ctrl && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) { return 'ctrl'; } if (keybinding.keyCode === KeyCode.Shift && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) { return 'shift'; } if (keybinding.keyCode === KeyCode.Alt && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) { return 'alt'; } if (keybinding.keyCode === KeyCode.Meta && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) { return 'meta'; } return null; } private static getProducedCharCode(kb: ScanCodeBinding, mapping: IScanCodeMapping): string | null { if (!mapping) { return null; } if (kb.ctrlKey && kb.shiftKey && kb.altKey) { return mapping.withShiftAltGr; } if (kb.ctrlKey && kb.altKey) { return mapping.withAltGr; } if (kb.shiftKey) { return mapping.withShift; } return mapping.value; } public static getProducedChar(kb: ScanCodeBinding, mapping: IScanCodeMapping): string { const char = this.getProducedCharCode(kb, mapping); if (char === null || char.length === 0) { return ' --- '; } return ' ' + char + ' '; } } export class WindowsKeyboardMapper implements IKeyboardMapper { public readonly isUSStandard: boolean; private readonly _codeInfo: IScanCodeMapping[]; private readonly _scanCodeToKeyCode: KeyCode[]; private readonly _keyCodeToLabel: Array<string | null> = []; private readonly _keyCodeExists: boolean[]; constructor(isUSStandard: boolean, rawMappings: IWindowsKeyboardMapping) { this.isUSStandard = isUSStandard; this._scanCodeToKeyCode = []; this._keyCodeToLabel = []; this._keyCodeExists = []; this._keyCodeToLabel[KeyCode.Unknown] = KeyCodeUtils.toString(KeyCode.Unknown); for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) { const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode]; if (immutableKeyCode !== KeyCode.DependsOnKbLayout) { this._scanCodeToKeyCode[scanCode] = immutableKeyCode; this._keyCodeToLabel[immutableKeyCode] = KeyCodeUtils.toString(immutableKeyCode); this._keyCodeExists[immutableKeyCode] = true; } } let producesLetter: boolean[] = []; let producesLetters = false; this._codeInfo = []; for (let strCode in rawMappings) { if (rawMappings.hasOwnProperty(strCode)) { const scanCode = ScanCodeUtils.toEnum(strCode); if (scanCode === ScanCode.None) { log(`Unknown scanCode ${strCode} in mapping.`); continue; } const rawMapping = rawMappings[strCode]; const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode]; if (immutableKeyCode !== KeyCode.DependsOnKbLayout) { const keyCode = NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE[rawMapping.vkey] || KeyCode.Unknown; if (keyCode === KeyCode.Unknown || immutableKeyCode === keyCode) { continue; } if (scanCode !== ScanCode.NumpadComma) { // Looks like ScanCode.NumpadComma doesn't always map to KeyCode.NUMPAD_SEPARATOR // e.g. on POR - PTB continue; } } const value = rawMapping.value; const withShift = rawMapping.withShift; const withAltGr = rawMapping.withAltGr; const withShiftAltGr = rawMapping.withShiftAltGr; const keyCode = NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE[rawMapping.vkey] || KeyCode.Unknown; const mapping: IScanCodeMapping = { scanCode: scanCode, keyCode: keyCode, value: value, withShift: withShift, withAltGr: withAltGr, withShiftAltGr: withShiftAltGr, }; this._codeInfo[scanCode] = mapping; this._scanCodeToKeyCode[scanCode] = keyCode; if (keyCode === KeyCode.Unknown) { continue; } this._keyCodeExists[keyCode] = true; if (value.length === 0) { // This key does not produce strings this._keyCodeToLabel[keyCode] = null; } else if (value.length > 1) { // This key produces a letter representable with multiple UTF-16 code units. this._keyCodeToLabel[keyCode] = value; } else { const charCode = value.charCodeAt(0); if (charCode >= CharCode.a && charCode <= CharCode.z) { const upperCaseValue = CharCode.A + (charCode - CharCode.a); producesLetter[upperCaseValue] = true; producesLetters = true; this._keyCodeToLabel[keyCode] = String.fromCharCode(CharCode.A + (charCode - CharCode.a)); } else if (charCode >= CharCode.A && charCode <= CharCode.Z) { producesLetter[charCode] = true; producesLetters = true; this._keyCodeToLabel[keyCode] = value; } else { this._keyCodeToLabel[keyCode] = value; } } } } // Handle keyboard layouts where latin characters are not produced e.g. Cyrillic const _registerLetterIfMissing = (charCode: CharCode, keyCode: KeyCode): void => { if (!producesLetter[charCode]) { this._keyCodeToLabel[keyCode] = String.fromCharCode(charCode); } }; _registerLetterIfMissing(CharCode.A, KeyCode.KeyA); _registerLetterIfMissing(CharCode.B, KeyCode.KeyB); _registerLetterIfMissing(CharCode.C, KeyCode.KeyC); _registerLetterIfMissing(CharCode.D, KeyCode.KeyD); _registerLetterIfMissing(CharCode.E, KeyCode.KeyE); _registerLetterIfMissing(CharCode.F, KeyCode.KeyF); _registerLetterIfMissing(CharCode.G, KeyCode.KeyG); _registerLetterIfMissing(CharCode.H, KeyCode.KeyH); _registerLetterIfMissing(CharCode.I, KeyCode.KeyI); _registerLetterIfMissing(CharCode.J, KeyCode.KeyJ); _registerLetterIfMissing(CharCode.K, KeyCode.KeyK); _registerLetterIfMissing(CharCode.L, KeyCode.KeyL); _registerLetterIfMissing(CharCode.M, KeyCode.KeyM); _registerLetterIfMissing(CharCode.N, KeyCode.KeyN); _registerLetterIfMissing(CharCode.O, KeyCode.KeyO); _registerLetterIfMissing(CharCode.P, KeyCode.KeyP); _registerLetterIfMissing(CharCode.Q, KeyCode.KeyQ); _registerLetterIfMissing(CharCode.R, KeyCode.KeyR); _registerLetterIfMissing(CharCode.S, KeyCode.KeyS); _registerLetterIfMissing(CharCode.T, KeyCode.KeyT); _registerLetterIfMissing(CharCode.U, KeyCode.KeyU); _registerLetterIfMissing(CharCode.V, KeyCode.KeyV); _registerLetterIfMissing(CharCode.W, KeyCode.KeyW); _registerLetterIfMissing(CharCode.X, KeyCode.KeyX); _registerLetterIfMissing(CharCode.Y, KeyCode.KeyY); _registerLetterIfMissing(CharCode.Z, KeyCode.KeyZ); if (!producesLetters) { // Since this keyboard layout produces no latin letters at all, most of the UI will use the // US kb layout equivalent for UI labels, so also try to render other keys with the US labels // for consistency... const _registerLabel = (keyCode: KeyCode, charCode: CharCode): void => { // const existingLabel = this._keyCodeToLabel[keyCode]; // const existingCharCode = (existingLabel ? existingLabel.charCodeAt(0) : CharCode.Null); // if (existingCharCode < 32 || existingCharCode > 126) { this._keyCodeToLabel[keyCode] = String.fromCharCode(charCode); // } }; _registerLabel(KeyCode.Semicolon, CharCode.Semicolon); _registerLabel(KeyCode.Equal, CharCode.Equals); _registerLabel(KeyCode.Comma, CharCode.Comma); _registerLabel(KeyCode.Minus, CharCode.Dash); _registerLabel(KeyCode.Period, CharCode.Period); _registerLabel(KeyCode.Slash, CharCode.Slash); _registerLabel(KeyCode.Backquote, CharCode.BackTick); _registerLabel(KeyCode.BracketLeft, CharCode.OpenSquareBracket); _registerLabel(KeyCode.Backslash, CharCode.Backslash); _registerLabel(KeyCode.BracketRight, CharCode.CloseSquareBracket); _registerLabel(KeyCode.Quote, CharCode.SingleQuote); } } public dumpDebugInfo(): string { let result: string[] = []; let immutableSamples = [ ScanCode.ArrowUp, ScanCode.Numpad0 ]; let cnt = 0; result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`); for (let scanCode = ScanCode.None; scanCode < ScanCode.MAX_VALUE; scanCode++) { if (IMMUTABLE_CODE_TO_KEY_CODE[scanCode] !== KeyCode.DependsOnKbLayout) { if (immutableSamples.indexOf(scanCode) === -1) { continue; } } if (cnt % 6 === 0) { result.push(`| HW Code combination | Key | KeyCode combination | UI label | User settings | WYSIWYG |`); result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`); } cnt++; const mapping = this._codeInfo[scanCode]; const strCode = ScanCodeUtils.toString(scanCode); const mods = [0b000, 0b010, 0b101, 0b111]; for (const mod of mods) { const ctrlKey = (mod & 0b001) ? true : false; const shiftKey = (mod & 0b010) ? true : false; const altKey = (mod & 0b100) ? true : false; const scanCodeBinding = new ScanCodeBinding(ctrlKey, shiftKey, altKey, false, scanCode); const kb = this._resolveSimpleUserBinding(scanCodeBinding); const strKeyCode = (kb ? KeyCodeUtils.toString(kb.keyCode) : null); const resolvedKb = (kb ? new WindowsNativeResolvedKeybinding(this, [kb]) : null); const outScanCode = `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${strCode}`; const ariaLabel = (resolvedKb ? resolvedKb.getAriaLabel() : null); const outUILabel = (ariaLabel ? ariaLabel.replace(/Control\+/, 'Ctrl+') : null); const outUserSettings = (resolvedKb ? resolvedKb.getUserSettingsLabel() : null); const outKey = WindowsNativeResolvedKeybinding.getProducedChar(scanCodeBinding, mapping); const outKb = (strKeyCode ? `${ctrlKey ? 'Ctrl+' : ''}${shiftKey ? 'Shift+' : ''}${altKey ? 'Alt+' : ''}${strKeyCode}` : null); const isWYSIWYG = (resolvedKb ? resolvedKb.isWYSIWYG() : false); const outWYSIWYG = (isWYSIWYG ? ' ' : ' NO '); result.push(`| ${this._leftPad(outScanCode, 30)} | ${outKey} | ${this._leftPad(outKb, 25)} | ${this._leftPad(outUILabel, 25)} | ${this._leftPad(outUserSettings, 25)} | ${outWYSIWYG} |`); } result.push(`-----------------------------------------------------------------------------------------------------------------------------------------`); } return result.join('\n'); } private _leftPad(str: string | null, cnt: number): string { if (str === null) { str = 'null'; } while (str.length < cnt) { str = ' ' + str; } return str; } public getUILabelForKeyCode(keyCode: KeyCode): string { return this._getLabelForKeyCode(keyCode); } public getAriaLabelForKeyCode(keyCode: KeyCode): string { return this._getLabelForKeyCode(keyCode); } public getUserSettingsLabelForKeyCode(keyCode: KeyCode): string { if (this.isUSStandard) { return KeyCodeUtils.toUserSettingsUS(keyCode); } return KeyCodeUtils.toUserSettingsGeneral(keyCode); } public getElectronAcceleratorForKeyBinding(keybinding: SimpleKeybinding): string | null { return KeyCodeUtils.toElectronAccelerator(keybinding.keyCode); } private _getLabelForKeyCode(keyCode: KeyCode): string { return this._keyCodeToLabel[keyCode] || KeyCodeUtils.toString(KeyCode.Unknown); } public resolveKeybinding(keybinding: Keybinding): WindowsNativeResolvedKeybinding[] { const parts = keybinding.parts; for (let i = 0, len = parts.length; i < len; i++) { const part = parts[i]; if (!this._keyCodeExists[part.keyCode]) { return []; } } return [new WindowsNativeResolvedKeybinding(this, parts)]; } public resolveKeyboardEvent(keyboardEvent: IKeyboardEvent): WindowsNativeResolvedKeybinding { const keybinding = new SimpleKeybinding(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode); return new WindowsNativeResolvedKeybinding(this, [keybinding]); } private _resolveSimpleUserBinding(binding: SimpleKeybinding | ScanCodeBinding | null): SimpleKeybinding | null { if (!binding) { return null; } if (binding instanceof SimpleKeybinding) { if (!this._keyCodeExists[binding.keyCode]) { return null; } return binding; } const keyCode = this._scanCodeToKeyCode[binding.scanCode] || KeyCode.Unknown; if (keyCode === KeyCode.Unknown || !this._keyCodeExists[keyCode]) { return null; } return new SimpleKeybinding(binding.ctrlKey, binding.shiftKey, binding.altKey, binding.metaKey, keyCode); } public resolveUserBinding(input: (SimpleKeybinding | ScanCodeBinding)[]): ResolvedKeybinding[] { const parts: SimpleKeybinding[] = removeElementsAfterNulls(input.map(keybinding => this._resolveSimpleUserBinding(keybinding))); if (parts.length > 0) { return [new WindowsNativeResolvedKeybinding(this, parts)]; } return []; } }
the_stack
import { TextDocument } from 'vscode-languageserver-textdocument'; import { AureliaView } from '../../../server/src/common/constants'; import { ViewRegionUtils } from '../../../server/src/common/documens/ViewRegionUtils'; import { RegionParser } from '../../../server/src/core/regions/RegionParser'; import { RepeatForRegion, ViewRegionSubType, ViewRegionType, } from '../../../server/src/core/regions/ViewRegions'; import { TestCasesMapFileBased, getEmptyShared, filterTestCaseMap, givenImInTheProject, whenIParseTheFile, andImOnTheLine, COLLECTION_SPLIT, GROUP_SPLIT, } from '../common/testTemplate'; const testCasesMapFileBased: TestCasesMapFileBased = {}; /* prettier-ignore */ testCasesMapFileBased['Offsets'] = [ // , CODE , PARAMETERS , Type , LINE , FILE [{} , '<div id.bind="bar"></div>' , {regVal:'bar' ,off:'45;48'} , 'Attribute' , 2 , 'custom-element.html' ] , [{} , '<div id="${foo}"></div>' , {regVal:'foo' ,off:'18;21'} , 'AttributeInterpolation' , 1 , 'custom-element.html' ] , [{} , '' , {} , 'CustomElement' , NaN , 'other-custom-element-user.html' ] , [{} , '' , {} , 'Import' , NaN , 'other-custom-element-user.html' ] , [{} , '<div repeat.for="fooElement of foo"></div>' , {regVal:'foo' ,off:'88;91'} , 'RepeatFor' , 3 , 'custom-element.html' ] , [{} , '${foo}' , {regVal:'foo' ,off:'2;6' } , 'TextInterpolation' , 0 , 'custom-element.html' ] , ]; /* prettier-ignore */ testCasesMapFileBased['Access scopes'] = [ // , CODE , PARAMETERS , Type , LINE , FILE [{} , '<p id.bind="foo"></p>' , {accSco:['foo'] ,nameLoc:['12;15'] } , 'Attribute' , NaN , '' ] , [{} , '<p repeat.for="person of people"></p>' , {accSco:['people']} , 'Attribute' , NaN , ''] , [{} , '<p repeat.for="p of people | foo:bar & qux:\'zed\'"></p>' , {accSco:['people;bar']} , 'Many' , NaN , ''] , // // , Html-only Custom Elements [{} , "<template bindable='foo'></template>" , {accSco:['foo'] ,nameLoc:['20;23'] } , 'Attribute' , NaN , '' ] , // // , Nested [{} , "<p>a ${zzz} mid ${foo ? `(${foo.bar})` : ''} Max</p>" , {accSco:['zzz','foo!foo'] ,nameLoc:['7;10','18;21!28;31'] } , 'Attribute' , NaN , '' ] , [{} , "<p>foo ${bar}</p>" , {accSco:['bar'] ,nameLoc:['9;12'] } , 'Attribute' , NaN , '' ] , [{} , '<p>${foo}<</p>' , {accSco:['foo'] ,nameLoc:['5;8'] } , 'TextInterpolation' , NaN , '' ] , [{} , '${foo.} ${bar}<p></p>' , {accSco:['foo'] ,nameLoc:['2;5','9;12'] } , 'TextInterpolation' , NaN , '' ] , [{} , '${foo} ${bar.}<p></p>' , {accSco:['foo','bar'] ,nameLoc:['2;5','9;12'] } , 'TextInterpolation' , NaN , '' ] , [{} , '<p>${foo} ${} bar ${qux} zed</p>' , {accSco:['foo','','qux'] ,nameLoc: ['5;8','12;12','20;23']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n..${foo}</p>' , {accSco:['foo'] ,nameLoc: ['8;11']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\r\n..${foo}</p>' , {accSco:['foo'] ,nameLoc: ['9;12']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo}</p>' , {accSco:['foo'] ,nameLoc: ['9;12']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo} ${bar}</p>' , {accSco:['foo','bar'] ,nameLoc: ['9;12','16;19']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo} ${}</p>' , {accSco:['foo',''] ,nameLoc: ['9;12','16;16']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo} ${} ${bar}</p>' , {accSco:['foo','','bar'] ,nameLoc: ['9;12','16;16','20;23']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${`${foo} bar`} ${} ${qux}</p>' , {accSco:['foo','','qux'] ,nameLoc: ['12;15','25;25','29;32']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${`${foo} ${bar} qux`} ${} ${zed}</p>' , {accSco:['foo!bar','','zed'] ,nameLoc: ['12;15!19;22','32;32','36;39']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n..${foo}\n..${bar}</p>' , {accSco:['foo','bar'] ,nameLoc: ['8;11','17;20']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo} ${bar}\n..${qux}</p>' , {accSco:['foo','bar','qux'] ,nameLoc: ['9;12','16;19','25;28']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\n\n..${foo[bar]} ${qux}</p>' , {accSco:['foo!bar','qux'] ,nameLoc: ['9;12!13;16','21;24']} , 'TextInterpolation' , NaN , ''] , [{} , '<p>\r\n\r\n..${foo} ${bar}\r\n..${qux}</p>' , {accSco:['foo','bar','qux'] ,nameLoc: ['11;14','18;21','28;31']} , 'TextInterpolation' , NaN , ''] , // // , File based // // , CODE , PARAMETERS , Type , LINE , FILE [{} , '<div id="${foo}"></div>' , {accSco:['foo'] ,nameLoc: ['18;21']} , 'AttributeInterpolation' , 1 , 'custom-element.html'], [{} , '<div id.bind="bar"></div>' , {accSco:['bar'] ,nameLoc: ['45;48']} , 'Attribute' , 2 , 'custom-element.html'], [{} , '<span id.bind="qux.attr">${qux.interpol}</span>' , {accSco:['qux','qux'] ,nameLoc: ['115;118','127;130']} , 'Many' , 4 , 'custom-element.html'], [{} , '<p class="${useFoo(qux)}">${arr[qux] |hello}</p>' , {accSco:['useFoo!qux','arr!qux'] ,nameLoc: ['160;166!167;170','176;179!180;183']} , 'Many' , 5 , 'custom-element.html'], ]; /* prettier-ignore */ testCasesMapFileBased['No parse result'] = [ // , CODE , PARAMETERS , Type , LINE , FILE [{} , '<a href=""></a>' , {} , 'ATag' , 0 , '' ] , ]; describe('RegionParser.', () => { let shared = getEmptyShared(); const filteredTestCaseMap = filterTestCaseMap(testCasesMapFileBased); Object.entries(filteredTestCaseMap).forEach(([testName, testCases]) => { testCases.forEach((testCase) => { const [, code, parameters, regionType, line, fileName] = testCase; // Actual suite describe(`${testName}.`, () => { describe(`${regionType}.`, () => { beforeEach(() => { if (fileName === '') return; givenImInTheProject('scoped-for-testing', shared); whenIParseTheFile(fileName, shared); andImOnTheLine(line, shared); }); afterEach(() => { shared = getEmptyShared(); }); // -- Region types // Custom Element if (regionType === ViewRegionType.CustomElement) { // Custom Element - BindableAttribute it('the result should include Custom element bindable attributes', () => { const target = ViewRegionUtils.getRegionsOfType( shared.parsedRegions, ViewRegionType.CustomElement ); expect(target.length).toBeGreaterThan(0); const result = target[0].data?.find( (attribute) => attribute.type === ViewRegionType.BindableAttribute ); expect(result?.regionValue).toBe('foo'); }); // Custom Element - Whole Tag it('the result should include Custom element - whole tag', () => { // shared.parsedRegions /* ? */ const target = ViewRegionUtils.getRegionsOfType( shared.parsedRegions, ViewRegionType.CustomElement ); const openingCustomElementTag = target[0]; const { startTagLocation } = openingCustomElementTag; expect(startTagLocation.startLine).toBe(5); expect(startTagLocation.startCol).toBe(2); expect(startTagLocation.startOffset).toBe(142); expect(startTagLocation.endLine).toBe(10); expect(startTagLocation.endCol).toBe(3); expect(startTagLocation.endOffset).toBe(238); }); // Custom Element - Start Tag it('the result should include Custom element - opening tag', () => { const target = ViewRegionUtils.getRegionsOfType( shared.parsedRegions, ViewRegionType.CustomElement ); const openingCustomElementTag = target[0]; expect(openingCustomElementTag.subType).toBe( ViewRegionSubType.StartTag ); const { sourceCodeLocation } = openingCustomElementTag; expect(sourceCodeLocation.startLine).toBe(5); expect(sourceCodeLocation.startCol).toBe(3); expect(sourceCodeLocation.startOffset).toBe(143); expect(sourceCodeLocation.endLine).toBe(5); expect(sourceCodeLocation.endCol).toBe(17); expect(sourceCodeLocation.endOffset).toBe(157); }); // Custom Element - End Tag it('the result should include Custom element - closing tag', () => { const target = ViewRegionUtils.getRegionsOfType( shared.parsedRegions, ViewRegionType.CustomElement ); expect(target.length).toBe(2); const closingCustomElementTag = target[1]; expect(closingCustomElementTag.subType).toBe( ViewRegionSubType.EndTag ); const { sourceCodeLocation } = closingCustomElementTag; expect(sourceCodeLocation.startCol).toBe(5); expect(sourceCodeLocation.startLine).toBe(10); expect(sourceCodeLocation.startOffset).toBe(240); expect(sourceCodeLocation.endCol).toBe(19); expect(sourceCodeLocation.endLine).toBe(10); expect(sourceCodeLocation.endOffset).toBe(254); }); } // Import else if (regionType === ViewRegionType.Import) { it('the result should include import tags.', () => { const target = ViewRegionUtils.getRegionsOfType( shared.parsedRegions, ViewRegionType[regionType] ); expect(target.length).toBeGreaterThan(0); expect(target[0].attributeName).toBe( AureliaView.IMPORT_FROM_ATTRIBUTE ); }); } // -- Parameters // Offset if (parameters.off != null) { // TODO: Do we need raw sourceCodeLocation at all? Now that we hav accessScopes? it.skip('Should have the correct offset for the region.', () => { const target = ViewRegionUtils.getTargetRegionByLine( shared.parsedRegions, String(shared.line) ); target; /* ? */ expect(target).toBeDefined(); if (!target) return; if (parameters.off == null) return; const [startOffset, endOffset] = parameters.off.split(GROUP_SPLIT); if (RepeatForRegion.is(target)) { const repeatForRegion = target; expect(repeatForRegion.data?.iterableStartOffset).toBe( Number(startOffset) ); expect(repeatForRegion.data?.iterableEndOffset).toBe( Number(endOffset) ); } else { expect(target.sourceCodeLocation.startOffset).toBe( Number(startOffset) ); expect(target.sourceCodeLocation.endOffset).toBe( Number(endOffset) ); } }); } if (parameters.accSco != null && parameters.nameLoc != null) { it(code, () => { if (parameters.accSco == null) return; if (parameters.nameLoc == null) return; let targetRegions = shared.parsedRegions; if (shared.parsedRegions.length === 0) { const document = TextDocument.create('', 'html', 0, code); // document.getText() /* ? */ targetRegions = RegionParser.parse(document, []); } if (!isNaN(shared.line)) { targetRegions = ViewRegionUtils.getManyTargetsRegionByLine( targetRegions, String(shared.line) ); } expect(targetRegions.length).toBeGreaterThan(0); // targetRegions; /* ? */ const rawExpectedAccessScopes = parameters.accSco; const rawExpectedNameLocation = parameters.nameLoc; // expect(true).toBeFalsy(); // targetRegions /* ? */ targetRegions.forEach((region, regionIndex) => { const resultNames = region.accessScopes?.map( (scope) => scope.name ); if (!resultNames) return; if (rawExpectedAccessScopes == null) return; const expectedAccessScopes = rawExpectedAccessScopes[regionIndex].split(COLLECTION_SPLIT); expect(resultNames).toEqual(expectedAccessScopes); if (rawExpectedNameLocation == null) return; if (rawExpectedNameLocation.length === 0) return; region.accessScopes?.forEach((scope, scopeIndex) => { const expectedNameLocation = rawExpectedNameLocation[regionIndex].split( COLLECTION_SPLIT ); const [expectedStart, expectedEnd] = expectedNameLocation[scopeIndex].split(GROUP_SPLIT); const { start, end } = scope.nameLocation; expect(start).toEqual(Number(expectedStart)); expect(end).toEqual(Number(expectedEnd)); }); }); // expect(true).toBeFalsy(); }); } // No parse result if (testName === 'No parse result') { it(testName, () => { const document = TextDocument.create('', '', 0, code); const parsedRegions = RegionParser.parse(document, []); expect(parsedRegions.length).toBe(0); }); } it('empty', () => expect(true).toBeTruthy()); }); }); }); }); });
the_stack
import Page = require('../../../base/Page'); import Response = require('../../../http/response'); import V1 = require('../V1'); import { SerializableClass } from '../../../interfaces'; /** * Initialize the ByocTrunkList * * @param version - Version of the resource */ declare function ByocTrunkList(version: V1): ByocTrunkListInstance; /** * Options to pass to update * * @property cnamLookupEnabled - Whether Caller ID Name (CNAM) lookup is enabled for the trunk * @property connectionPolicySid - Origination Connection Policy (to your Carrier) * @property friendlyName - A string to describe the resource * @property fromDomainSid - The SID of the SIP Domain that should be used in the `From` header of originating calls * @property statusCallbackMethod - The HTTP method we should use to call status_callback_url * @property statusCallbackUrl - The URL that we should call to pass status updates * @property voiceFallbackMethod - The HTTP method used with voice_fallback_url * @property voiceFallbackUrl - The URL we should call when an error occurs in executing TwiML * @property voiceMethod - The HTTP method we should use with voice_url * @property voiceUrl - The URL we should call when receiving a call */ interface ByocTrunkInstanceUpdateOptions { cnamLookupEnabled?: boolean; connectionPolicySid?: string; friendlyName?: string; fromDomainSid?: string; statusCallbackMethod?: string; statusCallbackUrl?: string; voiceFallbackMethod?: string; voiceFallbackUrl?: string; voiceMethod?: string; voiceUrl?: string; } interface ByocTrunkListInstance { /** * @param sid - sid of instance */ (sid: string): ByocTrunkContext; /** * create a ByocTrunkInstance * * @param callback - Callback to handle processed record */ create(callback?: (error: Error | null, item: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; /** * create a ByocTrunkInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ create(opts?: ByocTrunkListInstanceCreateOptions, callback?: (error: Error | null, item: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; /** * Streams ByocTrunkInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; /** * Streams ByocTrunkInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: ByocTrunkListInstanceEachOptions, callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void): void; /** * Constructs a byoc_trunk * * @param sid - The unique string that identifies the resource */ get(sid: string): ByocTrunkContext; /** * Retrieve a single target page of ByocTrunkInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; /** * Retrieve a single target page of ByocTrunkInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; /** * Lists ByocTrunkInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: ByocTrunkInstance[]) => any): Promise<ByocTrunkInstance[]>; /** * Lists ByocTrunkInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: ByocTrunkListInstanceOptions, callback?: (error: Error | null, items: ByocTrunkInstance[]) => any): Promise<ByocTrunkInstance[]>; /** * Retrieve a single page of ByocTrunkInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; /** * Retrieve a single page of ByocTrunkInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: ByocTrunkListInstancePageOptions, callback?: (error: Error | null, items: ByocTrunkPage) => any): Promise<ByocTrunkPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to create * * @property cnamLookupEnabled - Whether Caller ID Name (CNAM) lookup is enabled for the trunk * @property connectionPolicySid - Origination Connection Policy (to your Carrier) * @property friendlyName - A string to describe the resource * @property fromDomainSid - The SID of the SIP Domain that should be used in the `From` header of originating calls * @property statusCallbackMethod - The HTTP method we should use to call `status_callback_url` * @property statusCallbackUrl - The URL that we should call to pass status updates * @property voiceFallbackMethod - The HTTP method to use with voice_fallback_url * @property voiceFallbackUrl - The URL we should call when an error occurs in executing TwiML * @property voiceMethod - The HTTP method to use with voice_url * @property voiceUrl - The URL we should call when receiving a call */ interface ByocTrunkListInstanceCreateOptions { cnamLookupEnabled?: boolean; connectionPolicySid?: string; friendlyName?: string; fromDomainSid?: string; statusCallbackMethod?: string; statusCallbackUrl?: string; voiceFallbackMethod?: string; voiceFallbackUrl?: string; voiceMethod?: string; voiceUrl?: string; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface ByocTrunkListInstanceEachOptions { callback?: (item: ByocTrunkInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface ByocTrunkListInstanceOptions { limit?: number; pageSize?: number; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface ByocTrunkListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; } interface ByocTrunkPayload extends ByocTrunkResource, Page.TwilioResponsePayload { } interface ByocTrunkResource { account_sid: string; cnam_lookup_enabled: boolean; connection_policy_sid: string; date_created: Date; date_updated: Date; friendly_name: string; from_domain_sid: string; sid: string; status_callback_method: string; status_callback_url: string; url: string; voice_fallback_method: string; voice_fallback_url: string; voice_method: string; voice_url: string; } interface ByocTrunkSolution { } declare class ByocTrunkContext { /** * Initialize the ByocTrunkContext * * @param version - Version of the resource * @param sid - The unique string that identifies the resource */ constructor(version: V1, sid: string); /** * fetch a ByocTrunkInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; /** * remove a ByocTrunkInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<boolean>; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a ByocTrunkInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; /** * update a ByocTrunkInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: ByocTrunkInstanceUpdateOptions, callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; } declare class ByocTrunkInstance extends SerializableClass { /** * Initialize the ByocTrunkContext * * @param version - Version of the resource * @param payload - The instance payload * @param sid - The unique string that identifies the resource */ constructor(version: V1, payload: ByocTrunkPayload, sid: string); private _proxy: ByocTrunkContext; accountSid: string; cnamLookupEnabled: boolean; connectionPolicySid: string; dateCreated: Date; dateUpdated: Date; /** * fetch a ByocTrunkInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; friendlyName: string; fromDomainSid: string; /** * remove a ByocTrunkInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<boolean>; sid: string; statusCallbackMethod: string; statusCallbackUrl: string; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a ByocTrunkInstance * * @param callback - Callback to handle processed record */ update(callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; /** * update a ByocTrunkInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: ByocTrunkInstanceUpdateOptions, callback?: (error: Error | null, items: ByocTrunkInstance) => any): Promise<ByocTrunkInstance>; url: string; voiceFallbackMethod: string; voiceFallbackUrl: string; voiceMethod: string; voiceUrl: string; } declare class ByocTrunkPage extends Page<V1, ByocTrunkPayload, ByocTrunkResource, ByocTrunkInstance> { /** * Initialize the ByocTrunkPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: ByocTrunkSolution); /** * Build an instance of ByocTrunkInstance * * @param payload - Payload response from the API */ getInstance(payload: ByocTrunkPayload): ByocTrunkInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { ByocTrunkContext, ByocTrunkInstance, ByocTrunkInstanceUpdateOptions, ByocTrunkList, ByocTrunkListInstance, ByocTrunkListInstanceCreateOptions, ByocTrunkListInstanceEachOptions, ByocTrunkListInstanceOptions, ByocTrunkListInstancePageOptions, ByocTrunkPage, ByocTrunkPayload, ByocTrunkResource, ByocTrunkSolution }
the_stack
import {ClientInfo} from "../clientInfo"; import {ClientType} from "../clientType"; import {Constants} from "../constants"; import {PageInfo} from "../pageInfo"; import {UserInfo, AuthType} from "../userInfo"; import {ObjectUtils} from "../objectUtils"; import {Communicator} from "../communicator/communicator"; import {CommunicatorPassthrough} from "../communicator/communicatorPassthrough"; import {IFrameMessageHandler} from "../communicator/iframeMessageHandler"; import {MessageHandler} from "../communicator/messageHandler"; import {SmartValue} from "../communicator/smartValue"; import {DomUtils} from "../domParsers/domUtils"; import {Rtl} from "../localization/rtl"; import * as Log from "../logging/log"; import {Logger} from "../logging/logger"; import {CommunicatorLoggerPure} from "../logging/communicatorLoggerPure"; import {ClipperStorageKeys} from "../storage/clipperStorageKeys"; import {InitializableRangyStatic} from "../typingsExtends/initializableRangyStatic"; import {Frame, StyledFrameFactory} from "./styledFrameFactory"; import {FrameInjectBase} from "./frameInjectBase"; import {FrameInjectOptions} from "./injectOptions"; import {InvokeOptions, InvokeMode} from "./invokeOptions"; export interface ClipperInjectOptions extends FrameInjectOptions { enableAddANote: boolean; enableEditableTitle: boolean; enableRegionClipping: boolean; useInlineBackgroundWorker?: boolean; } declare let rangy: InitializableRangyStatic; /** * Loads up the Clipper iframe and manages it */ export class ClipperInject extends FrameInjectBase<ClipperInjectOptions> { private clientInfo: SmartValue<ClientInfo>; private pageInfo: SmartValue<PageInfo>; private isFullScreen: SmartValue<boolean>; private frameHeight = 100; private logger: Logger; /** * Called to toggle the clipper's visibility, or to invoke it if it does not exist */ public static main(oneNoteClipperOptions: ClipperInjectOptions): ClipperInject { // Rather than using a static field (i.e., traditional singleton pattern), we have to attach // the singleton to the window object because each time we inject a new inject script, they are // sandboxed from each other, so having a static field will not work. let oneNoteInjectBaseObject = (<any>window).oneNoteInjectBaseObject as ClipperInject; if (!!document.getElementById(Constants.Ids.clipperUiFrame) && oneNoteInjectBaseObject) { // The page could have changed between invokes e.g., single page apps if (window.getComputedStyle(oneNoteInjectBaseObject.frame).display === "none") { oneNoteInjectBaseObject.updatePageInfo(); } oneNoteInjectBaseObject.toggleClipper(); return oneNoteInjectBaseObject; } else if (!document.getElementById(Constants.Ids.clipperUiFrame)) { // The Web Clipper has not been invoked on this page yet let clipperInject = new ClipperInject(oneNoteClipperOptions); (<any>window).oneNoteInjectBaseObject = clipperInject; return clipperInject; } else { // The inject base object has been lost, likely due to an extension refresh or update while the Web Clipper is invoked, // so we prevent further action. It technically still exists but it has been orphaned (i.e., we lost a reference to it). return undefined; } } constructor(options: ClipperInjectOptions) { super(options); try { this.updateUiSizeAttributes(); this.overrideTransformStyles(document.documentElement); this.logger = new CommunicatorLoggerPure(this.uiCommunicator); this.updatePageInfo(); this.extCommunicator.callRemoteFunction(Constants.FunctionKeys.setStorageValue, { param: { key: ClipperStorageKeys.lastInvokedDate, value: Date.now().toString() } }); // We set up this call here as it requires both ui and ext communicators to be set up first this.extCommunicator.registerFunction(Constants.FunctionKeys.setInvokeOptions, (invokeOptions: InvokeOptions) => { // Some modes are gated here in the inject for extra processing switch (invokeOptions.invokeMode) { case InvokeMode.ContextTextSelection: // In the case of PDF, the selection is passed to us from the WebExtension API, so we use that instead as Rangy won't work if (invokeOptions.invokeDataForMode) { invokeOptions.invokeDataForMode = this.toScrubbedHtml(invokeOptions.invokeDataForMode); this.sendInvokeOptionsToUi(invokeOptions); break; } // Rangy initializes itself on the page load, so we need to initialize it if the user invoked before this happens if (!rangy.initialized && rangy.init) { rangy.init(); } // We get the selection here as the WebExtension API only allows us to get text // We assume there is rangeCount of 1: https://developer.mozilla.org/en-US/docs/Web/API/Selection/rangeCount let selection = rangy.getSelection() as RangySelection; let range = selection.getRangeAt(0) as RangyRange; let doc = (new DOMParser()).parseFromString(range.toHtml(), "text/html"); DomUtils.toOnml(doc).then(() => { // Selections are prone to not having an outer html element, which can lead to anomalies in preview invokeOptions.invokeDataForMode = this.toScrubbedHtml(doc.body.innerHTML); this.sendInvokeOptionsToUi(invokeOptions); }); break; default: this.sendInvokeOptionsToUi(invokeOptions); break; } }); document.onkeydown = (event) => { if (event.keyCode === Constants.KeyCodes.tab) { if (window.getComputedStyle(this.frame).display !== "none") { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.tabToLowestIndexedElement); } } }; } catch (e) { this.handleConstructorError(e); throw e; } } protected checkForNoOps() { // Ensure the frame was created and is visible let clipperFrame = document.getElementById(Constants.Ids.clipperUiFrame); let frameWasNotInjected = ObjectUtils.isNullOrUndefined(clipperFrame); let url = window.location.href; if (frameWasNotInjected) { Log.ErrorUtils.sendNoOpTrackerRequest({ label: Log.NoOp.Label.WebClipperUiFrameDidNotExist, channel: Constants.CommunicationChannels.injectedAndUi, clientInfo: this.clientInfo, url: url }); } else { let isFrameVisible = window.getComputedStyle(clipperFrame).display !== "none"; if (!isFrameVisible) { Log.ErrorUtils.sendNoOpTrackerRequest({ label: Log.NoOp.Label.WebClipperUiFrameIsNotVisible, channel: Constants.CommunicationChannels.injectedAndUi, clientInfo: this.clientInfo, url: url }, true); } } // No-op tracker for communication with the UI let noOpTrackerTimeout = Log.ErrorUtils.setNoOpTrackerRequestTimeout({ label: Log.NoOp.Label.InitializeCommunicator, channel: Constants.CommunicationChannels.injectedAndUi, clientInfo: this.clientInfo, url: window.location.href }); this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.noOpTracker, { param: new Date().getTime(), callback: () => { clearTimeout(noOpTrackerTimeout); } }); } protected createFrame() { this.frame = StyledFrameFactory.getStyledFrame(Frame.WebClipper); this.frame.id = Constants.Ids.clipperUiFrame; this.frame.src = this.options.frameUrl; } protected handleConstructorError(e: Error) { Log.ErrorUtils.sendFailureLogRequest({ label: Log.Failure.Label.UnhandledExceptionThrown, properties: { failureType: Log.Failure.Type.Unexpected, failureInfo: { error: JSON.stringify({ error: e.toString(), url: window.location.href }) }, failureId: "InjectBase", stackTrace: Log.Failure.getStackTrace(e) }, clientInfo: this.clientInfo }); } protected init() { this.clientInfo = new SmartValue<ClientInfo>(); this.pageInfo = new SmartValue<PageInfo>(); this.isFullScreen = new SmartValue<boolean>(false); } protected initializeExtCommunicator(extMessageHandlerThunk: () => MessageHandler) { this.extCommunicator = new Communicator(extMessageHandlerThunk(), Constants.CommunicationChannels.injectedAndExtension); // Clear the extension no-op tracker this.extCommunicator.registerFunction(Constants.FunctionKeys.noOpTracker, (trackerStartTime: number) => { let clearNoOpTrackerEvent = new Log.Event.BaseEvent(Log.Event.Label.ClearNoOpTracker); clearNoOpTrackerEvent.setCustomProperty(Log.PropertyName.Custom.TimeToClearNoOpTracker, new Date().getTime() - trackerStartTime); clearNoOpTrackerEvent.setCustomProperty(Log.PropertyName.Custom.Channel, Constants.CommunicationChannels.injectedAndExtension); this.logger.logEvent(clearNoOpTrackerEvent); return Promise.resolve(); }); this.extCommunicator.setErrorHandler((e: Error) => { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.showRefreshClipperMessage, { param: "Communicator " + Constants.CommunicationChannels.injectedAndExtension + " caught an error: " + e.message }); // Orphaned web clippers are a handled communicator error, so no further handling is needed here }); this.extCommunicator.subscribeAcrossCommunicator(this.clientInfo, Constants.SmartValueKeys.clientInfo); } protected initializeEventListeners() { // Preserve any onkeydown events the page might have set let oldOnKeyDown = document.onkeydown; document.onkeydown = (event) => { if (event.keyCode === Constants.KeyCodes.esc) { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.escHandler); } if (oldOnKeyDown) { oldOnKeyDown.call(document, event); } }; // Notify the background when we're unloading window.onbeforeunload = (event) => { this.extCommunicator.callRemoteFunction(Constants.FunctionKeys.unloadHandler); }; // On single-page-app 'navigates' we want to be able to toggle off the Clipper. We don't destroy it completely as it causes // the extension to be in a weird state. // See: http://stackoverflow.com/questions/4570093/how-to-get-notified-about-changes-of-the-history-via-history-pushstate let history: any = window.history; history.pushState = function (state) { if (typeof history.onpushstate === "function") { history.onpushstate({ state: state }); } return history.pushState.apply(history, arguments); }; window.onpopstate = history.onpushstate = (event) => { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.onSpaNavigate); }; // SPF is a SPA framework that some sites use, e.g., youtube. It sends an spfdone event when the page has 'navigated'. document.addEventListener("spfdone", () => { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.onSpaNavigate); }); } protected initializePassthroughCommunicator(extMessageHandlerThunk: () => MessageHandler) { if (!this.options.useInlineBackgroundWorker) { // Create a link for the extension to pass communication to the ui without having to re-register all the functions, smartValues, etc. let passthroughCommunicator = new CommunicatorPassthrough(extMessageHandlerThunk(), new IFrameMessageHandler(() => this.frame.contentWindow), Constants.CommunicationChannels.extensionAndUi, (e: Error) => { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.showRefreshClipperMessage, { param: "Communicator " + Constants.CommunicationChannels.extensionAndUi + " caught an error: " + e.message }); Log.ErrorUtils.handleCommunicatorError(Constants.CommunicationChannels.extensionAndUi, e, this.clientInfo); }); } } protected initializeUiCommunicator() { this.uiCommunicator = new Communicator(new IFrameMessageHandler(() => this.frame.contentWindow), Constants.CommunicationChannels.injectedAndUi); this.uiCommunicator.setErrorHandler((e: Error) => { Log.ErrorUtils.handleCommunicatorError(Constants.CommunicationChannels.injectedAndUi, e, this.clientInfo); }); this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.setInjectOptions, { param: this.options }); this.uiCommunicator.broadcastAcrossCommunicator(this.pageInfo, Constants.SmartValueKeys.pageInfo); this.uiCommunicator.subscribeAcrossCommunicator(this.isFullScreen, Constants.SmartValueKeys.isFullScreen, () => { this.updateUiSizeAttributes(); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.updateFrameHeight, (newHeight: number) => { this.frameHeight = newHeight + Constants.Styles.clipperUiTopRightOffset + (Constants.Styles.clipperUiDropShadowBuffer * 2); this.updateUiSizeAttributes(); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.updatePageInfoIfUrlChanged, () => { if (document.URL !== this.pageInfo.get().rawUrl) { this.updatePageInfo(); } return Promise.resolve(); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.hideUi, () => { this.frame.style.display = "none"; }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.refreshPage, () => { location.reload(); }); } /** * Creates a PageInfo object from the document data */ private createPageInfo(): PageInfo { let contentType: OneNoteApi.ContentType = DomUtils.getPageContentType(document); return { canonicalUrl: DomUtils.fetchCanonicalUrl(document), contentData: this.getTrimmedDomString(), contentLocale: DomUtils.getLocale(document), contentTitle: (contentType === OneNoteApi.ContentType.EnhancedUrl) ? DomUtils.getFileNameFromUrl(document) : document.title, contentType: contentType, rawUrl: document.URL } as PageInfo; } private getTrimmedDomString() { const maxPartLength = 2097152; let cleanDomEvent: Log.Event.BaseEvent = new Log.Event.BaseEvent(Log.Event.Label.GetCleanDom); let fullDomString = DomUtils.getCleanDomOfCurrentPage(document); let totalBytes = DomUtils.getByteSize(fullDomString); cleanDomEvent.setCustomProperty(Log.PropertyName.Custom.DomSizeInBytes, totalBytes); let trimmedString: string = DomUtils.truncateStringToByteSize(fullDomString, maxPartLength); let trimmedBytes = DomUtils.getByteSize(trimmedString); if (trimmedBytes !== totalBytes) { cleanDomEvent.setCustomProperty(Log.PropertyName.Custom.BytesTrimmed, totalBytes - trimmedBytes); } this.logger.logEvent(cleanDomEvent); return trimmedString; } private overrideTransformStyles(element: HTMLElement) { let parentStyles = window.getComputedStyle(element); if (parentStyles) { if (parentStyles.transform !== "none" || parentStyles.webkitTransform !== "none") { element.style.transform = element.style.webkitTransform = "none"; } } } private sendInvokeOptionsToUi(invokeOptions: InvokeOptions) { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.setInvokeOptions, { param: invokeOptions }); } private toggleClipper() { if (this.frame.style.display === "none") { this.frame.style.display = ""; } this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.toggleClipper); } private toScrubbedHtml(content: string): string { let divContainer = document.createElement("div"); divContainer.innerHTML = DomUtils.cleanHtml(content); return divContainer.outerHTML; } private updatePageInfo() { this.pageInfo.set(this.createPageInfo()); } private updateUiSizeAttributes() { if (this.isFullScreen.get()) { this.frame.style.width = "100%"; this.frame.style.height = "100%"; } else { this.frame.style.width = Constants.Styles.clipperUiWidth + Constants.Styles.clipperUiDropShadowBuffer + Constants.Styles.clipperUiTopRightOffset + "px"; this.frame.style.height = this.frameHeight + "px"; } } }
the_stack
import { userOwns } from '../../vulcan-users/permissions'; import { Utils, slugify, getDomain, getOutgoingUrl } from '../../vulcan-lib/utils'; import moment from 'moment'; import { foreignKeyField, resolverOnlyField, denormalizedField, denormalizedCountOfReferences, accessFilterMultiple, accessFilterSingle } from '../../utils/schemaUtils' import { schemaDefaultValue } from '../../collectionUtils'; import { PostRelations } from "../postRelations/collection" import { postGetPageUrl, postGetEmailShareUrl, postGetTwitterShareUrl, postGetFacebookShareUrl, postGetDefaultStatus, getSocialPreviewImage } from './helpers'; import { postStatuses, postStatusLabels } from './constants'; import { userGetDisplayNameById } from '../../vulcan-users/helpers'; import { TagRels } from "../tagRels/collection"; import { getWithLoader } from '../../loaders'; import { formGroups } from './formGroups'; import SimpleSchema from 'simpl-schema' import { DEFAULT_QUALITATIVE_VOTE } from '../reviewVotes/schema'; import { getVotingSystems } from '../../voting/votingSystems'; const STICKY_PRIORITIES = { 1: "Low", 2: "Normal", 3: "Elevated", 4: "Max", } export interface SettingsOption { label: string; tooltip?: string; } export const SORT_ORDER_OPTIONS: { [key: string]: SettingsOption; } = { magic: { label: 'Magic (New & Upvoted)', tooltip: 'Posts with the highest karma from the past few days' }, topAdjusted: { label: 'Top (Inflation Adjusted)', tooltip: 'Posts with the highest karma relative to those posted around the same time' }, recentComments: { label: 'Recent Comments' }, new: { label: 'New' }, old: { label: 'Old' }, top: { label: 'Top' }, } export interface RSVPType { name: string email: string nonPublic: boolean response: "yes" | "maybe" | "no" userId: string createdAt: Date } const rsvpType = new SimpleSchema({ name: { type: String, }, email: { type: String, optional: true, }, nonPublic: { type: Boolean, optional: true, }, response: { type: String, allowedValues: ["yes", "maybe", "no"], }, userId: { type: String, optional: true, }, createdAt: { type: Date, optional: true }, }) const schema: SchemaType<DbPost> = { // Timestamp of post creation createdAt: { type: Date, optional: true, viewableBy: ['admins'], onInsert: () => new Date(), }, // Timestamp of post first appearing on the site (i.e. being approved) postedAt: { type: Date, optional: true, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins'], control: 'datetime', group: formGroups.adminOptions, onInsert: (post, currentUser) => { // Set the post's postedAt if it's going to be approved if (!post.postedAt && postGetDefaultStatus(currentUser!) === postStatuses.STATUS_APPROVED) { return new Date(); } }, onEdit: (modifier, post) => { // Set the post's postedAt if it's going to be approved if (!post.postedAt && modifier.$set.status === postStatuses.STATUS_APPROVED) { return new Date(); } } }, // Timestamp of last post modification modifiedAt: { type: Date, optional: true, viewableBy: ['guests'], ...denormalizedField({ getValue: () => { return new Date() } }), }, // URL url: { type: String, optional: true, max: 500, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members', 'sunshineRegiment', 'admins'], control: 'EditUrl', order: 12, query: ` SiteData{ logoUrl title } `, inputProperties: { labels: { inactive: 'Link-post?', active: 'Add a linkpost URL', }, hintText: 'Please write what you liked about the post, and sample liberally. Or, if the author allows it, copy in the entire post text. If you know the author\'s username you can add them as a co-author of this post in the "Options" menu below.', }, group: formGroups.options, }, // Title title: { type: String, optional: false, max: 500, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members', 'sunshineRegiment', 'admins'], order: 10, placeholder: "Title", control: 'EditTitle', group: formGroups.default, }, // Slug slug: { type: String, optional: true, viewableBy: ['guests'], onInsert: async (post) => { return await Utils.getUnusedSlugByCollectionName("Posts", slugify(post.title)) }, onEdit: async (modifier, post) => { if (modifier.$set.title) { return await Utils.getUnusedSlugByCollectionName("Posts", slugify(modifier.$set.title), false, post._id) } } }, // Count of how many times the post's page was viewed viewCount: { type: Number, optional: true, viewableBy: ['admins'], defaultValue: 0 }, // Timestamp of the last comment lastCommentedAt: { type: Date, denormalized: true, optional: true, viewableBy: ['guests'], hidden: true, onInsert: (post: DbPost) => post.postedAt || new Date(), }, // Count of how many times the post's link was clicked clickCount: { type: Number, optional: true, viewableBy: ['admins'], defaultValue: 0 }, deletedDraft: { type: Boolean, optional: true, ...schemaDefaultValue(false), viewableBy: ['guests'], editableBy: ['members'], hidden: true, }, // The post's status. One of pending (`1`), approved (`2`), rejected (`3`), spam (`4`) or deleted (`5`) status: { type: Number, optional: true, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins', 'sunshineRegiment'], control: 'select', onInsert: (document, currentUser) => { if (!document.status) { return postGetDefaultStatus(currentUser!); } }, onEdit: (modifier, document, currentUser) => { // if for some reason post status has been removed, give it default status if (modifier.$unset && modifier.$unset.status) { return postGetDefaultStatus(currentUser!); } }, options: () => postStatusLabels, group: formGroups.adminOptions }, // Whether a post is scheduled in the future or not isFuture: { type: Boolean, optional: true, viewableBy: ['guests'], onInsert: (post) => { // Set the post's isFuture to true if necessary if (post.postedAt) { const postTime = new Date(post.postedAt).getTime(); const currentTime = new Date().getTime() + 1000; return postTime > currentTime; // round up to the second } else { return false; } }, onEdit: (modifier, post) => { // Set the post's isFuture to true if necessary if (modifier.$set.postedAt) { const postTime = new Date(modifier.$set.postedAt).getTime(); const currentTime = new Date().getTime() + 1000; if (postTime > currentTime) { // if a post's postedAt date is in the future, set isFuture to true return true; } else if (post.isFuture) { // else if a post has isFuture to true but its date is in the past, set isFuture to false return false; } } } }, // Whether the post is sticky (pinned to the top of posts lists) sticky: { type: Boolean, optional: true, ...schemaDefaultValue(false), viewableBy: ['guests'], insertableBy: ['sunshineRegiment', 'admins'], editableBy: ['sunshineRegiment', 'admins'], control: 'checkbox', order: 10, group: formGroups.adminOptions, onInsert: (post) => { if(!post.sticky) { return false; } }, onEdit: (modifier, post) => { if (!modifier.$set.sticky) { return false; } } }, // Priority of the stickied post. Higher priorities will be sorted before // lower priorities. stickyPriority: { type: SimpleSchema.Integer, ...schemaDefaultValue(2), viewableBy: ['guests'], insertableBy: ['sunshineRegiment', 'admins'], editableBy: ['sunshineRegiment', 'admins'], control: 'select', options: () => Object.entries(STICKY_PRIORITIES).map(([level, name]) => ({ value: parseInt(level), label: name })), group: formGroups.adminOptions, order: 11, optional: true, }, // Save info for later spam checking on a post. We will use this for the akismet package userIP: { type: String, optional: true, viewableBy: ['admins'], }, userAgent: { type: String, optional: true, viewableBy: ['admins'], }, referrer: { type: String, optional: true, viewableBy: ['admins'], }, // The post author's name author: { type: String, denormalized: true, optional: true, viewableBy: ['guests'], onEdit: async (modifier, document, currentUser) => { // if userId is changing, change the author name too if (modifier.$set && modifier.$set.userId) { return await userGetDisplayNameById(modifier.$set.userId) } } }, // The post author's `_id`. userId: { ...foreignKeyField({ idFieldName: "userId", resolverName: "user", collectionName: "Users", type: "User", nullable: true }), optional: true, control: 'text', viewableBy: ['guests'], editableBy: ['admins'], insertableBy: ['admins'], tooltip: 'The user id of the author', group: formGroups.adminOptions, }, // GraphQL-only fields domain: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => getDomain(post.url), }), pageUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => postGetPageUrl(post, true), }), pageUrlRelative: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => postGetPageUrl(post, false), }), linkUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => { return post.url ? getOutgoingUrl(post.url) : postGetPageUrl(post, true); }, }), postedAtFormatted: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => { return moment(post.postedAt).format('dddd, MMMM Do YYYY'); } }), emailShareUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => postGetEmailShareUrl(post), }), twitterShareUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => postGetTwitterShareUrl(post), }), facebookShareUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => postGetFacebookShareUrl(post), }), socialPreviewImageUrl: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, context: ResolverContext) => getSocialPreviewImage(post) }), question: { type: Boolean, optional: true, ...schemaDefaultValue(false), viewableBy: ['guests'], insertableBy: ['members'], hidden: true, }, authorIsUnreviewed: { type: Boolean, optional: true, denormalized: true, ...schemaDefaultValue(false), viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, }, // DEPRECATED field for GreaterWrong backwards compatibility wordCount: resolverOnlyField({ type: Number, viewableBy: ['guests'], resolver: (post: DbPost, args: void, { Posts }: ResolverContext) => { const contents = post.contents; if (!contents) return 0; return contents.wordCount; } }), // DEPRECATED field for GreaterWrong backwards compatibility htmlBody: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (post: DbPost, args: void, { Posts }: ResolverContext) => { const contents = post.contents; if (!contents) return ""; return contents.html; } }), submitToFrontpage: { type: Boolean, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members', 'admins', 'sunshineRegiment'], optional: true, hidden: true, ...schemaDefaultValue(true), onCreate: ({newDocument}: { newDocument: DbPost }) => { if (newDocument.isEvent) return false if ('submitToFrontpage' in newDocument) return newDocument.submitToFrontpage return true }, onUpdate: ({data, document}: { data: Partial<DbPost>, document: DbPost }) => { const updatedDocIsEvent = ('isEvent' in document) ? document.isEvent : false if (updatedDocIsEvent) return false return ('submitToFrontpage' in document) ? document.submitToFrontpage : true } }, hiddenRelatedQuestion: { type: Boolean, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members', 'admins', 'sunshineRegiment'], hidden: true, optional: true, ...schemaDefaultValue(false), }, originalPostRelationSourceId: { type: String, optional: true, viewableBy: ['guests'], insertableBy: ['members'], hidden: true, }, sourcePostRelations: resolverOnlyField({ type: Array, graphQLtype: '[PostRelation!]!', viewableBy: ['guests'], resolver: async (post: DbPost, args: void, context: ResolverContext) => { const result = await PostRelations.find({targetPostId: post._id}).fetch() return await accessFilterMultiple(context.currentUser, PostRelations, result, context); } }), 'sourcePostRelations.$': { type: String, optional: true, }, targetPostRelations: resolverOnlyField({ type: Array, graphQLtype: '[PostRelation!]!', viewableBy: ['guests'], resolver: async (post: DbPost, args: void, context: ResolverContext) => { const { Posts, currentUser } = context; const postRelations = await Posts.aggregate([ { $match: { _id: post._id }}, { $graphLookup: { from: "postrelations", as: "relatedQuestions", startWith: post._id, connectFromField: "targetPostId", connectToField: "sourcePostId", maxDepth: 3 } }, { $project: { relatedQuestions: 1 } }, { $unwind: "$relatedQuestions" }, { $replaceRoot: { newRoot: "$relatedQuestions" } } ]).toArray() if (!postRelations || postRelations.length < 1) return [] return await accessFilterMultiple(currentUser, PostRelations, postRelations, context); } }), 'targetPostRelations.$': { type: String, optional: true, }, // A post should have the shortform flag set iff its author's shortformFeedId // field is set to this post's ID. shortform: { type: Boolean, optional: true, hidden: true, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins'], denormalized: true, ...schemaDefaultValue(false), }, canonicalSource: { type: String, optional: true, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins'], group: formGroups.adminOptions, }, nominationCount2018: { ...denormalizedCountOfReferences({ fieldName: "nominationCount2018", collectionName: "Posts", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "postId", filterFn: comment => !comment.deleted && comment.nominatedForReview === "2018" }), canRead: ['guests'], }, nominationCount2019: { ...denormalizedCountOfReferences({ fieldName: "nominationCount2019", collectionName: "Posts", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "postId", filterFn: comment => !comment.deleted && comment.nominatedForReview === "2019" }), canRead: ['guests'], }, reviewCount2018: { ...denormalizedCountOfReferences({ fieldName: "reviewCount2018", collectionName: "Posts", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "postId", filterFn: comment => !comment.deleted && comment.reviewingForReview === "2018" }), canRead: ['guests'], }, reviewCount2019: { ...denormalizedCountOfReferences({ fieldName: "reviewCount2019", collectionName: "Posts", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "postId", filterFn: comment => !comment.deleted && comment.reviewingForReview === "2019" }), canRead: ['guests'], }, reviewCount: { ...denormalizedCountOfReferences({ fieldName: "reviewCount", collectionName: "Posts", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "postId", filterFn: comment => !comment.deleted && !!comment.reviewingForReview }), canRead: ['guests'], }, reviewVoteCount: { type: Number, optional: true, defaultValue: 0, ...denormalizedCountOfReferences({ fieldName: "reviewVoteCount", collectionName: "Posts", foreignCollectionName: "ReviewVotes", foreignTypeName: "reviewVote", foreignFieldName: "postId", }), canRead: ['guests'], }, positiveReviewVoteCount: { type: Number, optional: true, defaultValue: 0, ...denormalizedCountOfReferences({ fieldName: "positiveReviewVoteCount", collectionName: "Posts", foreignCollectionName: "ReviewVotes", foreignTypeName: "reviewVote", foreignFieldName: "postId", filterFn: vote => vote.qualitativeScore > DEFAULT_QUALITATIVE_VOTE || vote.quadraticScore > 0 }), canRead: ['guests'], }, // The various reviewVoteScore and reviewVotes fields are for caching the results of the updateQuadraticVotes migration (which calculates the score of posts during the LessWrong Review) reviewVoteScoreAF: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, reviewVotesAF: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'reviewVotesAF.$': { type: Number, optional: true, }, reviewVoteScoreHighKarma: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, reviewVotesHighKarma: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'reviewVotesHighKarma.$': { type: Number, optional: true, }, reviewVoteScoreAllKarma: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, reviewVotesAllKarma: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'reviewVotesAllKarma.$': { type: Number, optional: true, }, // the final review scores for each post, at the end of the review. finalReviewVoteScoreHighKarma: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, finalReviewVotesHighKarma: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'finalReviewVotesHighKarma.$': { type: Number, optional: true, }, finalReviewVoteScoreAllKarma: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, finalReviewVotesAllKarma: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'finalReviewVotesAllKarma.$': { type: Number, optional: true, }, finalReviewVoteScoreAF: { type: Number, optional: true, defaultValue: 0, canRead: ['guests'] }, finalReviewVotesAF: { type: Array, optional: true, defaultValue: [], canRead: ['guests'] }, 'finalReviewVotesAF.$': { type: Number, optional: true, }, lastCommentPromotedAt: { type: Date, optional: true, hidden: true, canRead: ['guests'] }, tagRel: resolverOnlyField({ type: "TagRel", graphQLtype: "TagRel", viewableBy: ['guests'], graphqlArguments: 'tagId: String', resolver: async (post: DbPost, args: {tagId: string}, context: ResolverContext) => { const { tagId } = args; const { currentUser } = context; const tagRels = await getWithLoader(context, TagRels, "tagRelByDocument", { tagId: tagId }, 'postId', post._id ); const filteredTagRels = await accessFilterMultiple(currentUser, TagRels, tagRels, context) if (filteredTagRels?.length) { return filteredTagRels[0] } } }), tags: resolverOnlyField({ type: "[Tag]", graphQLtype: "[Tag]", viewableBy: ['guests'], resolver: async (post: DbPost, args: void, context: ResolverContext) => { const { currentUser } = context; const tagRelevanceRecord:Record<string, number> = post.tagRelevance || {} const tagIds = Object.entries(tagRelevanceRecord).filter(([id, score]) => score && score > 0).map(([id]) => id) const tags = await context.loaders.Tags.loadMany(tagIds) return await accessFilterMultiple(currentUser, context.Tags, tags, context) } }), // Denormalized, with manual callbacks. Mapping from tag ID to baseScore, ie Record<string,number>. tagRelevance: { type: Object, optional: true, hidden: true, viewableBy: ['guests'], }, "tagRelevance.$": { type: Number, optional: true, hidden: true, }, lastPromotedComment: resolverOnlyField({ type: "Comment", graphQLtype: "Comment", viewableBy: ['guests'], resolver: async (post, args, context: ResolverContext) => { const { currentUser, Comments } = context; if (post.lastCommentPromotedAt) { const comment = await Comments.findOne({postId: post._id, promoted: true}, {sort:{promotedAt: -1}}) return await accessFilterSingle(currentUser, Comments, comment, context) } } }), bestAnswer: resolverOnlyField({ type: "Comment", graphQLtype: "Comment", viewableBy: ['guests'], resolver: async (post: DbPost, args: void, context: ResolverContext) => { const { currentUser, Comments } = context; if (post.question) { if (post.lastCommentPromotedAt) { const comment = await Comments.findOne({postId: post._id, answer: true, promoted: true}, {sort:{promotedAt: -1}}) return await accessFilterSingle(currentUser, Comments, comment, context) } else { const comment = await Comments.findOne({postId: post._id, answer: true, baseScore: {$gt: 15}}, {sort:{baseScore: -1}}) return await accessFilterSingle(currentUser, Comments, comment, context) } } } }), // Tell search engines not to index this post. Useful for old posts that were // from a time with different quality standards. Posts will still be findable // in algolia. See PostsPage and HeadTags for their use of this field and the // noIndexLowKarma migration for the setting of it. noIndex: { type: Boolean, optional: true, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins'], group: formGroups.adminOptions, ...schemaDefaultValue(false), }, // TODO: doc rsvps: { type: Array, viewableBy: ['guests'], optional: true, // TODO: how to remove people without db access? hidden: true, }, 'rsvps.$': { type: rsvpType, viewableBy: ['guests'], }, activateRSVPs: { type: Boolean, viewableBy: ['guests'], insertableBy: ['members'], editableBy: ['members', 'sunshineRegiment', 'admins'], hidden: (props) => !props.eventForm, group: formGroups.event, control: 'checkbox', label: "Enable RSVPs for this event", tooltip: "RSVPs are public, but the associated email addresses are only visible to organizers.", optional: true }, nextDayReminderSent: { type: Boolean, viewableBy: ['guests'], insertableBy: ['admins'], editableBy: ['admins'], optional: true, hidden: true, ...schemaDefaultValue(false), }, onlyVisibleToLoggedIn: { type: Boolean, viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], optional: true, group: formGroups.adminOptions, label: "Hide this post from users who are not logged in", ...schemaDefaultValue(false), }, onlyVisibleToEstablishedAccounts: { type: Boolean, viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], optional: true, group: formGroups.adminOptions, label: "Hide this post from logged out users and newly created accounts", ...schemaDefaultValue(false), }, currentUserReviewVote: resolverOnlyField({ type: "ReviewVote", graphQLtype: "ReviewVote", viewableBy: ['members'], resolver: async (post: DbPost, args: void, context: ResolverContext): Promise<DbReviewVote|null> => { const { ReviewVotes, currentUser } = context; if (!currentUser) return null; const votes = await getWithLoader(context, ReviewVotes, `reviewVotesByUser${currentUser._id}`, { userId: currentUser._id }, "postId", post._id ); if (!votes.length) return null; const vote = await accessFilterSingle(currentUser, ReviewVotes, votes[0], context); return vote; } }), votingSystem: { type: String, optional: true, viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], group: formGroups.adminOptions, control: "select", form: { options: () => { return getVotingSystems() .map(votingSystem => ({label: votingSystem.description, value: votingSystem.name})); } }, }, }; export default schema;
the_stack
import { createHookMsg } from '@anchor-protocol/anchor.js/dist/utils/cw20/create-hook-msg'; import { validateTxFee } from '@anchor-protocol/app-fns'; import { useAnchorWebapp, useBondBLunaExchangeRateQuery, useBondBurnTx, } from '@anchor-protocol/app-provider'; import { useAnchorBank } from '@anchor-protocol/app-provider/hooks/useAnchorBank'; import { formatLuna, formatLunaInput, formatUST, LUNA_INPUT_MAXIMUM_DECIMAL_POINTS, LUNA_INPUT_MAXIMUM_INTEGER_POINTS, } from '@anchor-protocol/notation'; import type { bLuna, Luna } from '@anchor-protocol/types'; import { Gas, u, UST } from '@anchor-protocol/types'; import { useEstimateFee, useFixedFee } from '@libs/app-provider'; import { floor } from '@libs/big-math'; import { demicrofy, MICRO } from '@libs/formatter'; import { ActionButton } from '@libs/neumorphism-ui/components/ActionButton'; import { IconSpan } from '@libs/neumorphism-ui/components/IconSpan'; import { NumberMuiInput } from '@libs/neumorphism-ui/components/NumberMuiInput'; import { SelectAndTextInputContainer } from '@libs/neumorphism-ui/components/SelectAndTextInputContainer'; import { useAlert } from '@libs/neumorphism-ui/components/useAlert'; import { NativeSelect as MuiNativeSelect } from '@material-ui/core'; import { StreamStatus } from '@rx-stream/react'; import { Msg, MsgExecuteContract } from '@terra-money/terra.js'; import { useConnectedWallet } from '@terra-money/wallet-provider'; import big, { Big } from 'big.js'; import { MessageBox } from 'components/MessageBox'; import { IconLineSeparator } from 'components/primitives/IconLineSeparator'; import { TxResultRenderer } from 'components/tx/TxResultRenderer'; import { SwapListItem, TxFeeList, TxFeeListItem } from 'components/TxFeeList'; import { ViewAddressWarning } from 'components/ViewAddressWarning'; import debounce from 'lodash.debounce'; import { pegRecovery } from 'pages/bond/logics/pegRecovery'; import { validateBurnAmount } from 'pages/bond/logics/validateBurnAmount'; import React, { ChangeEvent, useCallback, useEffect, useMemo, useState, } from 'react'; interface Item { label: string; value: string; } const assetCurrencies: Item[] = [{ label: 'LUNA', value: 'luna' }]; const bAssetCurrencies: Item[] = [{ label: 'bLUNA', value: 'bluna' }]; export function Burn() { // --------------------------------------------- // dependencies // --------------------------------------------- const connectedWallet = useConnectedWallet(); const { contractAddress, gasPrice, constants } = useAnchorWebapp(); const fixedFee = useFixedFee(); const estimateFee = useEstimateFee(connectedWallet?.walletAddress); const [burn, burnResult] = useBondBurnTx(); const [openAlert, alertElement] = useAlert(); // --------------------------------------------- // states // --------------------------------------------- const [burnAmount, setBurnAmount] = useState<bLuna>('' as bLuna); const [getAmount, setGetAmount] = useState<Luna>('' as Luna); const [estimatedGasWanted, setEstimatedGasWanted] = useState<Gas | null>( null, ); const [estimatedFee, setEstimatedFee] = useState<u<UST> | null>(null); const [burnCurrency, setBurnCurrency] = useState<Item>( () => bAssetCurrencies[0], ); const [getCurrency, setGetCurrency] = useState<Item>( () => assetCurrencies[0], ); // --------------------------------------------- // queries // --------------------------------------------- const bank = useAnchorBank(); const { data: { state: exchangeRate, parameters } = {} } = useBondBLunaExchangeRateQuery(); // --------------------------------------------- // logics // --------------------------------------------- const pegRecoveryFee = useMemo( () => pegRecovery(exchangeRate, parameters), [exchangeRate, parameters], ); const invalidTxFee = useMemo( () => !!connectedWallet && validateTxFee(bank.tokenBalances.uUST, fixedFee), [bank, fixedFee, connectedWallet], ); const invalidBurnAmount = useMemo( () => !!connectedWallet && validateBurnAmount(burnAmount, bank), [bank, burnAmount, connectedWallet], ); // --------------------------------------------- // effects // --------------------------------------------- const estimate = useMemo(() => { return debounce((msgs: Msg[] | null) => { if (!msgs) { setEstimatedGasWanted(null); setEstimatedFee(null); return; } estimateFee(msgs).then((estimated) => { if (estimated) { setEstimatedGasWanted(estimated.gasWanted); setEstimatedFee( big(estimated.txFee).mul(gasPrice.uusd).toFixed() as u<UST>, ); } else { setEstimatedGasWanted(null); setEstimatedFee(null); } }); }, 500); }, [estimateFee, gasPrice.uusd]); useEffect(() => { if (!connectedWallet || burnAmount.length === 0) { setEstimatedGasWanted(null); setEstimatedFee(null); estimate(null); return; } const amount = floor(big(burnAmount).mul(MICRO)); if (amount.lt(0) || amount.gt(bank.tokenBalances.ubLuna ?? 0)) { setEstimatedGasWanted(null); setEstimatedFee(null); estimate(null); return; } estimate([ new MsgExecuteContract( connectedWallet.terraAddress, contractAddress.cw20.bLuna, { send: { contract: contractAddress.bluna.hub, amount: amount.toFixed(), msg: createHookMsg({ unbond: {}, }), }, }, ), ]); }, [ bank.tokenBalances.ubLuna, burnAmount, connectedWallet, constants.bondGasWanted, contractAddress.bluna.hub, contractAddress.cw20.bLuna, estimate, estimateFee, fixedFee, gasPrice.uusd, ]); // --------------------------------------------- // callbacks // --------------------------------------------- const updateBurnCurrency = useCallback((nextBurnCurrencyValue: string) => { setBurnCurrency( bAssetCurrencies.find(({ value }) => nextBurnCurrencyValue === value) ?? bAssetCurrencies[0], ); }, []); const updateGetCurrency = useCallback((nextGetCurrencyValue: string) => { setGetCurrency( assetCurrencies.find(({ value }) => nextGetCurrencyValue === value) ?? assetCurrencies[0], ); }, []); const updateBurnAmount = useCallback( (nextBurnAmount: string) => { if (nextBurnAmount.trim().length === 0) { setGetAmount('' as Luna); setBurnAmount('' as bLuna); } else { const burnAmount: bLuna = nextBurnAmount as bLuna; const getAmount: Luna = formatLunaInput( big(burnAmount).mul(exchangeRate?.exchange_rate ?? 1) as Luna<Big>, ); setGetAmount(getAmount); setBurnAmount(burnAmount); } }, [exchangeRate?.exchange_rate], ); const updateGetAmount = useCallback( (nextGetAmount: string) => { if (nextGetAmount.trim().length === 0) { setBurnAmount('' as bLuna); setGetAmount('' as Luna); } else { const getAmount: Luna = nextGetAmount as Luna; const burnAmount: bLuna = formatLunaInput( big(getAmount).div(exchangeRate?.exchange_rate ?? 1) as bLuna<Big>, ); setBurnAmount(burnAmount); setGetAmount(getAmount); } }, [exchangeRate?.exchange_rate], ); const init = useCallback(() => { setGetAmount('' as Luna); setBurnAmount('' as bLuna); }, []); const proceed = useCallback( async (burnAmount: bLuna) => { if (!connectedWallet || !burn) { return; } const estimated = await estimateFee([ new MsgExecuteContract( connectedWallet.terraAddress, contractAddress.cw20.bLuna, { send: { contract: contractAddress.bluna.hub, amount: floor(big(burnAmount).mul(MICRO)).toFixed(), msg: createHookMsg({ unbond: {}, }), }, }, ), ]); if (estimated) { burn({ burnAmount, gasWanted: estimated.gasWanted, txFee: big(estimated.txFee).mul(gasPrice.uusd).toFixed() as u<UST>, onTxSucceed: () => { init(); }, }); } else { await openAlert({ description: ( <> Broadcasting failed, <br /> please retry after some time. </> ), agree: 'OK', }); } }, [ burn, connectedWallet, contractAddress.bluna.hub, contractAddress.cw20.bLuna, estimateFee, gasPrice.uusd, init, openAlert, ], ); // --------------------------------------------- // presentation // --------------------------------------------- if ( burnResult?.status === StreamStatus.IN_PROGRESS || burnResult?.status === StreamStatus.DONE ) { return ( <TxResultRenderer resultRendering={burnResult.value} onExit={() => { init(); switch (burnResult.status) { case StreamStatus.IN_PROGRESS: burnResult.abort(); break; case StreamStatus.DONE: burnResult.clear(); break; } }} /> ); } return ( <> {!!invalidTxFee && <MessageBox>{invalidTxFee}</MessageBox>} {pegRecoveryFee && ( <MessageBox level="info" hide={{ id: 'burn_peg', period: 1000 * 60 * 60 * 24 * 7 }} > When exchange rate is lower than threshold, <br /> protocol charges peg recovery fee for each Mint/Burn action. </MessageBox> )} <MessageBox level="info" hide={{ id: 'burn', period: 1000 * 60 * 60 * 24 * 7 }} > Default bLuna redemptions take at least 21 days to process. <br /> Slashing events during the 21 days may affect the final amount withdrawn. <br /> Redemptions are processed in 3-day batches and may take up to 24 days. </MessageBox> {/* Burn (bAsset) */} <div className="burn-description"> <p>I want to burn</p> <p /> </div> <SelectAndTextInputContainer className="burn" gridColumns={[120, '1fr']} error={!!invalidBurnAmount} leftHelperText={invalidBurnAmount} rightHelperText={ !!connectedWallet && ( <span> Balance:{' '} <span style={{ textDecoration: 'underline', cursor: 'pointer' }} onClick={() => updateBurnAmount( formatLunaInput(demicrofy(bank.tokenBalances.ubLuna)), ) } > {formatLuna(demicrofy(bank.tokenBalances.ubLuna))}{' '} {burnCurrency.label} </span> </span> ) } > <MuiNativeSelect value={burnCurrency} onChange={({ target }) => updateBurnCurrency(target.value)} IconComponent={ bAssetCurrencies.length < 2 ? BlankComponent : undefined } disabled={bAssetCurrencies.length < 2} > {bAssetCurrencies.map(({ label, value }) => ( <option key={value} value={value}> {label} </option> ))} </MuiNativeSelect> <NumberMuiInput placeholder="0.00" error={!!invalidBurnAmount} value={burnAmount} maxIntegerPoinsts={LUNA_INPUT_MAXIMUM_INTEGER_POINTS} maxDecimalPoints={LUNA_INPUT_MAXIMUM_DECIMAL_POINTS} onChange={({ target }: ChangeEvent<HTMLInputElement>) => updateBurnAmount(target.value) } /> </SelectAndTextInputContainer> <IconLineSeparator /> {/* Get (Asset) */} <div className="gett-description"> <p>and get</p> <p /> </div> <SelectAndTextInputContainer className="gett" gridColumns={[120, '1fr']} error={!!invalidBurnAmount} > <MuiNativeSelect value={getCurrency} onChange={({ target }) => updateGetCurrency(target.value)} IconComponent={ assetCurrencies.length < 2 ? BlankComponent : undefined } disabled={assetCurrencies.length < 2} > {assetCurrencies.map(({ label, value }) => ( <option key={value} value={value}> {label} </option> ))} </MuiNativeSelect> <NumberMuiInput placeholder="0.00" error={!!invalidBurnAmount} value={getAmount} maxIntegerPoinsts={LUNA_INPUT_MAXIMUM_INTEGER_POINTS} maxDecimalPoints={LUNA_INPUT_MAXIMUM_DECIMAL_POINTS} onChange={({ target }: ChangeEvent<HTMLInputElement>) => updateGetAmount(target.value) } /> </SelectAndTextInputContainer> <TxFeeList className="receipt"> {exchangeRate && ( <SwapListItem label="Price" currencyA={burnCurrency.label} currencyB={getCurrency.label} exchangeRateAB={exchangeRate.exchange_rate} formatExchangeRate={(ratio) => formatLuna(ratio as Luna<Big>)} /> )} {!!pegRecoveryFee && getAmount.length > 0 && ( <TxFeeListItem label={<IconSpan>Peg Recovery Fee</IconSpan>}> {formatLuna(demicrofy(pegRecoveryFee(getAmount)))} LUNA </TxFeeListItem> )} {burnAmount.length > 0 && estimatedFee && ( <TxFeeListItem label={<IconSpan>Estimated Tx Fee</IconSpan>}> ≈ {formatUST(demicrofy(estimatedFee))} UST </TxFeeListItem> )} </TxFeeList> {/* Submit */} <ViewAddressWarning> <ActionButton className="submit" disabled={ !connectedWallet || !connectedWallet.availablePost || !burn || burnAmount.length === 0 || big(burnAmount).lte(0) || !!invalidTxFee || !!invalidBurnAmount || estimatedGasWanted === null || estimatedFee === null } onClick={() => proceed(burnAmount)} > Burn </ActionButton> </ViewAddressWarning> {alertElement} </> ); } function BlankComponent() { return <div />; }
the_stack