text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { isDefined, isUndefined, max } from '@collectable/core'; import { COMMIT_MODE, CONST, OFFSET_ANCHOR, invertAnchor, invertOffset, normalizeIndex, verifyIndex } from './common'; import { View } from './view'; import { ExpansionParameters, Slot } from './slot'; import { ListStructure, createList, getOtherView, getView, setView } from './list'; /** * Checks whether a list ordinal position lies within the absolute range of a slot within the list * * @param {number} ordinal * @param {number} leftOffset * @param {number} slotSize * @returns {boolean} */ function isInRange (ordinal: number, leftOffset: number, slotSize: number): boolean { return ordinal >= leftOffset && ordinal < leftOffset + slotSize; } /** * Checks whether a list ordinal position lies within the specified view's absolute range within the list * * @template T The type of elements in the list * @param {View<T>} view A view to perform a range check against * @param {number} ordinal An ordinal position whose existence should be checked with respect to the specified view * @param {number} listSize The total number of elements in the list * @returns {boolean} true if the ordinal falls within the view's enclosed range, otherwise false */ export function isViewInRange<T> (view: View<T>, ordinal: number, listSize: number): boolean { return view.anchor === OFFSET_ANCHOR.LEFT ? isInRange(ordinal, view.offset, view.slot.size) : isInRange(ordinal, invertOffset(view.offset, view.slot.size, listSize), view.slot.size); } /** * Checks an upper view's offset and size to see if it is an ancestor of the lower view * * @template T The type of elements in the list * @param {View<T>} upperView An ancestral view * @param {View<T>} lowerView A descendant view * @param {number} listSize The total number of elements in the list * @returns {boolean} true if upperView is an ancestor of lowerView, otherwise false */ function isAncestor<T> (upperView: View<T>, lowerView: View<T>, listSize: number): boolean { if(upperView.isRoot()) return true; var upperOffset = lowerView.anchor === upperView.anchor ? upperView.offset : invertOffset(upperView.offset, upperView.slot.size + lowerView.sizeDelta, listSize); return upperOffset <= lowerView.offset && upperOffset + upperView.slot.size + lowerView.sizeDelta >= lowerView.offset + lowerView.slot.size; } /** * Selects and returns either the left or the right view for further operations at the specified ordinal position. The * view is selected with a preference for preserving the position of the last view that was written to, so that the * reading and writing of views will implicitly optimise itself according to the way the list is being used. * * @param {ListState<T>} state The list state to be queried * @param {number} ordinal A hint to indicate the next ordinal position to be queried * @returns {View<T>} One of either the left or the right view * * @memberOf ListState */ function selectView<T> (list: ListStructure<T>, ordinal: number, asWriteTarget: boolean): View<T> { var left = list._left, right = list._right, resolve = asWriteTarget; var anchor: OFFSET_ANCHOR; if(left.isNone()) { anchor = right.isRoot() || isInRange(ordinal, invertOffset(right.offset, right.slot.size, list._size), right.slot.size) ? OFFSET_ANCHOR.RIGHT : OFFSET_ANCHOR.LEFT; if(anchor === OFFSET_ANCHOR.LEFT) resolve = true; } else if(right.isNone()) { anchor = left.isRoot() || isInRange(ordinal, left.offset, left.slot.size) ? OFFSET_ANCHOR.LEFT : OFFSET_ANCHOR.RIGHT; if(anchor === OFFSET_ANCHOR.RIGHT) resolve = true; } else { var leftEnd = left.bound(); var rightStart = list._size - right.bound(); anchor = rightStart <= ordinal ? OFFSET_ANCHOR.RIGHT : leftEnd > ordinal ? OFFSET_ANCHOR.LEFT : invertAnchor(list._lastWrite); } return resolve ? getView(list, anchor, asWriteTarget, ordinal) : anchor === OFFSET_ANCHOR.LEFT ? left : right; } export class TreeWorker<T> { private static _defaults: { defaultPrimary: TreeWorker<any>; defaultSecondary: TreeWorker<any>; defaultOther: TreeWorker<any>; defaultTemporary: TreeWorker<any>; }; private static _getDefaults () { var defaults = TreeWorker._defaults; if(isUndefined(defaults)) { TreeWorker._defaults = defaults = { defaultPrimary: new TreeWorker<any>(), defaultSecondary: new TreeWorker<any>(), defaultOther: new TreeWorker<any>(), defaultTemporary: new TreeWorker<any>(), }; } return defaults; } static defaultPrimary<T> (): TreeWorker<T> { return TreeWorker._getDefaults().defaultPrimary; } static defaultSecondary<T> (): TreeWorker<T> { return TreeWorker._getDefaults().defaultSecondary; } static defaultOther<T> (): TreeWorker<T> { return TreeWorker._getDefaults().defaultOther; } static defaultTemporary<T> (): TreeWorker<T> { return TreeWorker._getDefaults().defaultTemporary; } static refocusView<T> (list: ListStructure<T>, view: View<T>, ordinal: number, asAltView: boolean, asWriteTarget: boolean) { var worker = TreeWorker.defaultTemporary<T>().reset(list, view, list._group); view = worker.refocusView(ordinal, asAltView, asWriteTarget); worker.dispose(); return view; } static focusOrdinal<T> (list: ListStructure<T>, ordinal: number, asWriteTarget: boolean): View<T>|undefined { ordinal = verifyIndex(list._size, ordinal); if(ordinal === -1) return void 0; var view = selectView(list, ordinal, asWriteTarget); return isViewInRange(view, ordinal, list._size) ? view : TreeWorker.refocusView<T>(list, view, ordinal, false, asWriteTarget); } static focusEdge<T> (list: ListStructure<T>, edge: OFFSET_ANCHOR, asWriteTarget: boolean): View<T> { var view = getView(list, edge, asWriteTarget); view = view.offset > 0 || (asWriteTarget && !view.slot.isReserved() && !view.isRoot()) ? TreeWorker.refocusView<T>(list, view, edge === OFFSET_ANCHOR.LEFT ? 0 : list._size - 1, false, asWriteTarget) : view; return view; } static focusHead<T> (list: ListStructure<T>, asWriteTarget: boolean): View<T> { return TreeWorker.focusEdge(list, OFFSET_ANCHOR.LEFT, asWriteTarget); } static focusTail<T> (list: ListStructure<T>, asWriteTarget: boolean): View<T> { return TreeWorker.focusEdge(list, OFFSET_ANCHOR.RIGHT, asWriteTarget); } static focusView<T> (list: ListStructure<T>, ordinal: number, anchor: OFFSET_ANCHOR, asWriteTarget: boolean): View<T> { var view = getView(list, anchor, true, ordinal); return isViewInRange(view, ordinal, list._size) ? view : TreeWorker.refocusView<T>(list, view, ordinal, false, true); } list = createList<T>(false); previous = View.none<T>(); current = View.none<T>(); other = View.none<T>(); otherCommittedChild = View.none<T>(); otherCommitMode: COMMIT_MODE = -1; committedOther = false; slotResult = { slot: Slot.empty<T>(), index: 0, offset: 0 }; group = 0; shift = 0; isRoot (): boolean { return this.current.isRoot(); } hasOtherView (): boolean { return !this.other.isNone(); } reset (list: ListStructure<T>, view: View<T>, group: number, otherCommitMode?: COMMIT_MODE): TreeWorker<T> { if (isUndefined(otherCommitMode)) { otherCommitMode = COMMIT_MODE.NO_CHANGE; } this.list = list; this.current = view; this.group = group; this.shift = 0; if(otherCommitMode === -1) { this.committedOther = true; } else { this.other = getOtherView(list, view.anchor); this.committedOther = this.other.isNone(); this.otherCommitMode = otherCommitMode; } return this; } dispose (): void { this.list = createList<T>(false); this.previous = View.none<T>(); this.current = View.none<T>(); this.other = View.none<T>(); this.otherCommittedChild = View.none<T>(); this.slotResult.slot = Slot.empty<T>(); } ensureEditable (persist: boolean): View<T> { var view = this.current; var group = this.list._group; if(!view.isEditable(group)) { this.current = view = view.cloneToGroup(group); if(this.shift === 0 && persist) { setView(this.list, view); } } return view; } ascend (mode: COMMIT_MODE, expandParent?: ExpansionParameters): View<T> { var childView = this.current; var childSlot = childView.slot; var group = this.group; var parentView: View<T>; var parentSlot: Slot<T>; var hasChanges: boolean; var prepend = 0, append = 0; if(this.committedOther && !this.otherCommittedChild.isNone()) { this.otherCommittedChild = View.none<T>(); } var persistChild = mode === COMMIT_MODE.RELEASE_DISCARD ? (mode = COMMIT_MODE.RELEASE, false/*this.hasOtherView() && this.other.parent === childView*/) : true; var slotIndex = childView.slotIndex; var childWasRoot = childView.isRoot(); if(childWasRoot) { if(this.shift >= CONST.BRANCH_INDEX_BITCOUNT*12) { throw new Error('Unterminated tree growth'); } // Ascending from the root slot causes the tree to grow by one level. Non-zero delta values for the child view can // be disregarded, as we're absorbing the child view's final computed values in advance. var slotCount = 1, slotSize = childSlot.size; var recompute = childSlot.isRelaxed() ? slotCount : -1; if(isDefined(expandParent)) { prepend = expandParent.padLeft; append = expandParent.padRight; if(childView.isAnchoredIncorrectly(prepend) && (childView = this.ensureEditable(persistChild))) { childView.flipAnchor(this.list._size); } slotCount += prepend + append; slotIndex += prepend; slotSize += expandParent.sizeDelta; if(recompute !== -1) { recompute += max(append, -1); } this.list._size += expandParent.sizeDelta; } var slots = new Array<Slot<T>>(slotCount); slots[slotIndex] = mode === COMMIT_MODE.RESERVE ? childSlot.cloneAsPlaceholder(group) : childSlot; parentSlot = new Slot<T>(group, slotSize, 0, recompute, childSlot.slots.length, slots); parentView = View.create<T>(group, childView.offset, prepend ? OFFSET_ANCHOR.RIGHT : OFFSET_ANCHOR.LEFT, 0, 0, 0, View.none<T>(), parentSlot); hasChanges = false; } else { parentView = childView.parent.ensureEditable(group); parentSlot = parentView.slot; hasChanges = childView.hasUncommittedChanges(); // If the child wasn't already reserved with a placeholder slot, and no reservation has been requested, then there is // nothing further that we need to do. if(hasChanges || mode === COMMIT_MODE.RESERVE || isDefined(expandParent)) { // Optional expansion parameters can add slots to the start or end of the parent slot. if(isDefined(expandParent)) { append = expandParent.padRight; prepend = expandParent.padLeft; slotIndex += prepend; } // Prepare the parent view and slot for modifications, and optionally append or prepend additional slots as needed. if(!parentSlot.isEditable(group)) { // Note that it is impossible for a slot to be a member of the current group if the view referencing it is not. parentView.slot = parentSlot = isDefined(expandParent) ? parentSlot.cloneWithAdjustedRange(group, prepend, append, false, true) : parentSlot.cloneToGroup(group, true); } else if(isDefined(expandParent)) { parentSlot.adjustRange(prepend, append, false); } if(isDefined(expandParent)) { this.list._size += expandParent.sizeDelta; } if(!this.committedOther && isAncestor(parentView, this.other, this.list._size)) { this.commitOther(parentView, prepend); } // If the direction of expansion is the same as the current offset anchor, the offset anchor must be flipped so that // the relative offset is not invalidated by the expanded size of the slot. If expanding both sides, offset // adjustments will need to be calculated externally. if(isDefined(expandParent)) { parentSlot.size += expandParent.sizeDelta; if(!parentView.isRoot()) { parentView.sizeDelta += expandParent.sizeDelta; } } // Pending changes to the list size and parent slot subcount need to be propagated upwards. Before any further // operations are performed, the calling function should also commit changes from the other (left/right) view if // they descend from this branch, or the returned slot/view may not reflect the true state of the list. if(hasChanges) { if(!parentView.isRoot()) { parentView.sizeDelta += childView.sizeDelta; } parentSlot.subcount += childView.slotsDelta; parentSlot.size += childView.sizeDelta; if(parentSlot.isRelaxed() || childSlot.isRelaxed() || (childView.slotsDelta < 0 && slotIndex < parentSlot.slots.length - 1 && parentSlot.recompute === -1)) { parentSlot.recompute = max(parentSlot.recompute, parentSlot.slots.length - slotIndex); } else { parentSlot.recompute = -1; } } } // Avoid dragging around extraneous references to old state that will be invalidated by any subsequent writes to // descendant nodes. if(mode === COMMIT_MODE.RESERVE || (hasChanges && mode === COMMIT_MODE.NO_CHANGE && childSlot.isReserved())) { var childSlotRef = <Slot<T>>parentSlot.slots[slotIndex]; if(childSlotRef.isReservedFor(group)) { if(hasChanges) { childSlotRef.size = childSlot.size; childSlotRef.slots.length = childSlot.slots.length; } } else { var sum = childSlotRef.sum; parentSlot.slots[slotIndex] = childSlotRef = childSlot.cloneAsPlaceholder(group); childSlotRef.sum = sum; } if(childSlotRef.isReservedFor(group)) { if(hasChanges) { childSlotRef.updatePlaceholder(childSlot); } } else { parentSlot.slots[slotIndex] = childSlot.cloneAsPlaceholder(group); } } else if(mode === COMMIT_MODE.RELEASE) { if(childSlot.isReserved()) { if(!parentSlot.isEditable(group)) { parentView.slot = parentSlot = parentSlot.cloneToGroup(group, true); } if(childSlot.isEditable(group)) { childSlot.group = group; } else { childSlot = childSlot.cloneToGroup(group); } childSlot.sum = (<Slot<T>>parentSlot.slots[slotIndex]).sum; parentSlot.slots[slotIndex] = childSlot; } } } // If the slot is flagged as relaxed, but it is now full, change it back to a regular node. if(parentSlot.recompute !== -1 && parentSlot.size === CONST.BRANCH_FACTOR << (this.shift + CONST.BRANCH_INDEX_BITCOUNT)) { parentSlot.recompute = -1; } if(!this.committedOther && isAncestor(parentView, this.other, this.list._size)) { this.commitOther(parentView, isDefined(expandParent) ? expandParent.padLeft : 0); } if(persistChild) { if(mode === COMMIT_MODE.RESERVE && !childSlot.isReserved()) { if(childSlot.isEditable(group)) { childSlot.group = -group; } else { childSlot = childSlot.cloneToGroup(-group); } } if(!childView.isEditable(group)) { childView = childView.cloneToGroup(group); if(this.shift === 0) { setView(this.list, childView); } } if(hasChanges || childSlot !== childView.slot || childView.parent !== parentView || this.otherCommitMode === -1) { childView.slot = childSlot; childView.parent = parentView; childView.slotsDelta = 0; childView.sizeDelta = 0; } childView.slotIndex = slotIndex; this.previous = childView; } else if(childView.isEditable(group)) { View.pushReusableView(childView); } this.current = parentView; this.shift += CONST.BRANCH_INDEX_BITCOUNT; return parentView; } commitOther (replacementParent: View<T>, slotIndexOffset: number): void { var otherView = this.other; if(slotIndexOffset === 0 && this.shift === 0 && !otherView.hasUncommittedChanges() && otherView.parent === replacementParent && (this.otherCommitMode === COMMIT_MODE.NO_CHANGE || (this.otherCommitMode === COMMIT_MODE.RESERVE) === otherView.slot.isReserved())) { this.committedOther = true; this.otherCommittedChild = otherView; return; } if(!otherView.isEditable(this.group)) { otherView = otherView.cloneToGroup(this.group); } var anchor = otherView.anchor; setView(this.list, this.other = this.otherCommitMode === COMMIT_MODE.RELEASE_DISCARD ? View.empty<T>(anchor) : otherView); var worker = TreeWorker.defaultOther<T>().reset(this.list, otherView, this.group, -1); while(worker.shift < this.shift) { otherView = worker.ascend(this.otherCommitMode); } otherView.parent = replacementParent; otherView.slotIndex += slotIndexOffset; worker.ascend(this.otherCommitMode); this.committedOther = true; this.otherCommittedChild = worker.previous; worker.dispose(); } ascendToOrdinal (ordinal: number, mode: COMMIT_MODE, ensureBranchReserved: boolean): View<T> { var view = this.current, target = view, branchFound = false; var shift = this.shift; do { view = this.ascend(!this.hasOtherView() || (this.hasOtherView() && !this.committedOther) || mode === COMMIT_MODE.RESERVE ? mode : COMMIT_MODE.NO_CHANGE); if(!branchFound) { branchFound = isViewInRange(view, ordinal, this.list._size); if(branchFound) { shift = this.shift; target = view; if(ensureBranchReserved) { mode = COMMIT_MODE.RESERVE; } } } } while(!branchFound || (mode === COMMIT_MODE.RESERVE && !view.isRoot() && !view.slot.isReserved())); this.shift = shift; this.current = target; return target; } descendToOrdinal (ordinal: number, asWriteTarget: boolean): View<T>|undefined { var view = this.current, shift = this.shift, out = this.slotResult; var offset = view.anchor === OFFSET_ANCHOR.RIGHT ? invertOffset(view.offset, view.slot.size, this.list._size) : view.offset; var flip = this.hasOtherView() && this.other.anchor === OFFSET_ANCHOR.LEFT; do { view.slot.resolveChild(ordinal - offset, shift, out); if(out.slot.isReserved()) { while(view !== this.current) { var discarded = view; view = discarded.parent; View.pushReusableView(discarded); } return void 0; } shift -= CONST.BRANCH_INDEX_BITCOUNT; offset += out.offset; if(asWriteTarget) { view.ensureSlotEditable().slots[out.index] = out.slot.cloneAsPlaceholder(this.group); out.slot = out.slot.toReservedNode(this.group); } view = View.create<T>(this.group, offset, OFFSET_ANCHOR.LEFT, out.index, 0, 0, view, <Slot<T>>out.slot); if(flip) view.flipAnchor(this.list._size); } while(shift > 0); this.previous = this.current; this.current = view; this.shift = 0; return view; } refocusView (ordinal: number, asAltView: boolean, asWriteTarget: boolean): View<T> { ordinal = verifyIndex(this.list._size, ordinal); var anchor = asAltView ? invertAnchor(this.current.anchor) : this.current.anchor; this.ascendToOrdinal(ordinal, asAltView ? COMMIT_MODE.NO_CHANGE : COMMIT_MODE.RELEASE_DISCARD, asWriteTarget); var view = this.descendToOrdinal(ordinal, asWriteTarget); if(isUndefined(view)) { this.reset(this.list, getOtherView(this.list, anchor), this.group, -1); this.ascendToOrdinal(ordinal, COMMIT_MODE.NO_CHANGE, false); view = <View<T>>this.descendToOrdinal(ordinal, asWriteTarget); } if(view.anchor !== anchor) { view.flipAnchor(this.list._size); } setView(this.list, view); return view; } } export function getAtOrdinal<T> (list: ListStructure<T>, ordinal: number): T|undefined { ordinal = normalizeIndex(list._size, ordinal); var view = TreeWorker.focusOrdinal<T>(list, ordinal, false); if(view === void 0) return void 0; return <T>view.slot.slots[getLeafIndex(view, ordinal, list._size)]; } export function getLeafIndex<T> (view: View<T>, ordinal: number, listSize: number): number { return ordinal - (view.anchor === OFFSET_ANCHOR.LEFT ? view.offset : invertOffset(view.offset, view.slot.size, listSize)); }
the_stack
import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnDestroy, Output, ViewChild, } from '@angular/core'; import { AbstractControl, FormBuilder, FormControl, FormGroup, FormGroupDirective, NgForm, Validators, } from '@angular/forms'; import { TranslateService } from '@ngx-translate/core'; import { ErrorStateMatcher } from '@angular/material'; import { Subscription } from 'rxjs'; import { distinctUntilChanged, filter, map } from 'rxjs/operators'; import { IPVersion, NetworkRuleType } from '../../sg.model'; import { NetworkProtocol } from '../../network-rule.model'; import { cidrValidator, endPortValidator, icmpCodeValidator, icmpTypeValidator, startPortValidator, } from '../../shared/validators'; import { getICMPCodeTranslationToken, getICMPTypeTranslationToken, getICMPV6CodeTranslationToken, getICMPV6TypeTranslationToken, IcmpType, icmpV4Types, icmpV6Types, } from '../../../shared/icmp/icmp-types'; import { FirewallRule } from '../../shared/models'; import { CidrUtils } from '../../../shared/utils/cidr-utils'; export class PortsErrorStateMatcher implements ErrorStateMatcher { isErrorState(control: FormControl, form: FormGroupDirective | NgForm): boolean { return control.invalid && control.dirty; } } @Component({ selector: 'cs-sg-rule-addition-form', templateUrl: './sg-rule-addition-form.component.html', styleUrls: ['./sg-rule-addition-form.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SGRuleAdditionFormComponent implements OnDestroy { // Workaround for resetting form state. https://github.com/angular/material2/issues/4190 // We need manually reset FormGroupDirective via resetForm() method otherwise, // the form will be invalid and errors are shown @ViewChild('mainForm') mainForm; @Input() isAdding = false; @Output() addRule = new EventEmitter<FirewallRule>(); public isIcmpProtocol = false; public filteredIcmpTypes: IcmpType[]; public filteredIcmpCodes: number[]; public portMatcher = new PortsErrorStateMatcher(); public readonly maxPortNumber = 65535; public readonly minPortNumber = 0; public types = [ { value: NetworkRuleType.Ingress, text: 'SECURITY_GROUP_PAGE.RULES.INGRESS' }, { value: NetworkRuleType.Egress, text: 'SECURITY_GROUP_PAGE.RULES.EGRESS' }, ]; public protocols = [ { value: NetworkProtocol.TCP, text: 'SECURITY_GROUP_PAGE.RULES.TCP' }, { value: NetworkProtocol.UDP, text: 'SECURITY_GROUP_PAGE.RULES.UDP' }, { value: NetworkProtocol.ICMP, text: 'SECURITY_GROUP_PAGE.RULES.ICMP' }, ]; public ruleForm: FormGroup; private portsForm: FormGroup; private icmpForm: FormGroup; private protocolChanges: Subscription; private cidrChanges: Subscription; private icmpTypeChanges: Subscription; private icmpCodeChanges: Subscription; private startPortChanges: Subscription; private endPortChanges: Subscription; constructor(private fb: FormBuilder, private translateService: TranslateService) { this.createForm(); this.onProtocolChange(); this.onCidrChange(); this.onIcmpTypeChange(); this.onIcmpCodeChange(); this.onPortsChanges(); } public ngOnDestroy() { this.protocolChanges.unsubscribe(); this.cidrChanges.unsubscribe(); this.icmpTypeChanges.unsubscribe(); this.icmpCodeChanges.unsubscribe(); this.startPortChanges.unsubscribe(); this.endPortChanges.unsubscribe(); } public createForm() { this.portsForm = this.fb.group({ startPort: [null, [Validators.required]], endPort: [null, [Validators.required]], }); this.icmpForm = this.fb.group({ icmpType: [{ value: null, disabled: true }, [Validators.required]], icmpCode: [{ value: null, disabled: true }, [Validators.required]], }); this.ruleForm = this.fb.group({ type: [this.types[0].value, Validators.required], protocol: [this.protocols[0].value, Validators.required], cidr: ['', [Validators.required, cidrValidator()]], params: this.portsForm, // Depends on initial value of protocol }); // Some validators required form controls and we can set them after they were created this.setPortFormValidators(); this.setIcmpFormValidators(); } public onSubmit() { const rule = this.getFormData(); this.addRule.emit(rule); this.resetForm(); } public getStartPortErrorMessage() { const port = this.portsForm.get('startPort'); let translateToken: string; let param: { value?: string } = {}; if (port.hasError('min')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.START_PORT_SHOULD_BE_GREATER_THAN'; param = { value: port.errors.min.min }; } else if (port.hasError('max')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.START_PORT_SHOULD_BE_LESS_THAN'; param = { value: port.errors.max.max }; } else if (port.hasError('startPortValidator')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.START_PORT_SHOULD_BE_LESS_THAN_END_PORT'; } if (translateToken) { return this.translateService.instant(translateToken, param); } return null; } public getEndPortErrorMessage() { const port = this.portsForm.get('endPort'); let translateToken: string; let param: { value?: string } = {}; if (port.hasError('min')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.END_PORT_SHOULD_BE_GREATER_THAN'; param = { value: port.errors.min.min }; } else if (port.hasError('max')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.END_PORT_SHOULD_BE_LESS_THAN'; param = { value: port.errors.max.max }; } else if (port.hasError('endPortValidator')) { translateToken = 'SECURITY_GROUP_PAGE.RULES.END_PORT_SHOULD_BE_GREATER_THAN_START_PORT'; } if (translateToken) { return this.translateService.instant(translateToken, param); } return null; } private setPortFormValidators() { const portCommonValidators = [ Validators.required, Validators.min(this.minPortNumber), Validators.max(this.maxPortNumber), ]; this.startPort.setValidators([...portCommonValidators, startPortValidator(this.endPort)]); this.endPort.setValidators([...portCommonValidators, endPortValidator(this.startPort)]); } private setIcmpFormValidators() { this.icmpType.setValidators([Validators.required, icmpTypeValidator(this.cidr)]); this.icmpCode.setValidators([Validators.required, icmpCodeValidator(this.cidr, this.icmpType)]); } private getFormData(): FirewallRule { const formModel = this.ruleForm.value; const commonProperties: FirewallRule = { type: formModel.type, protocol: formModel.protocol, cidr: formModel.cidr, }; if (commonProperties.protocol === NetworkProtocol.ICMP) { const icmpModel = this.icmpForm.value; return { ...commonProperties, icmpType: icmpModel.icmpType, icmpCode: icmpModel.icmpCode, }; } const portsModel = this.portsForm.value; return { ...commonProperties, startPort: portsModel.startPort, endPort: portsModel.endPort, }; } private resetForm() { const paramsForm = this.protocol.value === NetworkProtocol.ICMP ? this.icmpForm : this.portsForm; const formState = { type: this.type.value, protocol: this.protocol.value, cidr: this.cidr.value, params: paramsForm, }; this.mainForm.resetForm(); this.ruleForm.reset(formState); } private onProtocolChange() { this.protocolChanges = this.protocol.valueChanges .pipe( filter(Boolean), map((protocol: NetworkProtocol) => protocol === NetworkProtocol.ICMP), distinctUntilChanged(), filter((isIcmp: boolean) => this.isIcmpProtocol !== isIcmp), ) .subscribe((isIcmp: boolean) => { // invokes only if isIcmpProtocol flag changes const paramsForm = isIcmp ? this.icmpForm : this.portsForm; this.ruleForm.setControl('params', paramsForm); this.isIcmpProtocol = isIcmp; if (isIcmp) { this.updateIcmpFormState(); } }); } private onCidrChange() { this.cidrChanges = this.cidr.valueChanges .pipe( map(CidrUtils.getCidrIpVersion), distinctUntilChanged(), filter(() => this.isIcmpProtocol), ) .subscribe(() => { // invokes only when cidr change IP version and protocol equals ICMP this.updateIcmpFormState(); }); } private updateIcmpFormState() { this.updateIcmpFormFieldsValidity(); this.updateDisabledStatusOnIcmpTypeField(); this.updateDisabledStatusOnIcmpCodeField(); this.updateFilteredIcmpTypes(this.icmpType.value); this.updateFilteredIcmpCodes(this.icmpCode.value); } private updateIcmpFormFieldsValidity() { this.icmpType.updateValueAndValidity(); this.icmpCode.updateValueAndValidity(); } private onPortsChanges() { this.startPortChanges = this.startPort.valueChanges .pipe(distinctUntilChanged()) .subscribe((value: number) => { this.duplicatePortForFirstFilling(this.endPort, value); this.endPort.updateValueAndValidity(); }); this.endPortChanges = this.endPort.valueChanges .pipe(distinctUntilChanged()) .subscribe((value: number) => { this.duplicatePortForFirstFilling(this.startPort, value); this.startPort.updateValueAndValidity(); }); } private duplicatePortForFirstFilling(port: AbstractControl, portNumber: number) { const isChangedByUser = port.untouched; if (isChangedByUser) { port.setValue(portNumber); port.markAsDirty(); } } private onIcmpTypeChange() { this.icmpTypeChanges = this.icmpType.valueChanges.subscribe(value => { this.updateFilteredIcmpTypes(value); this.updateFilteredIcmpCodes(this.icmpCode.value); this.updateDisabledStatusOnIcmpCodeField(); }); } private updateFilteredIcmpTypes(value: number | string) { this.filteredIcmpTypes = this.filterIcmpTypes(value); } private filterIcmpTypes(val: number | string | null): IcmpType[] { if (val === null || val === '') { return this.getIcmpTypes(); } const filterValue = val.toString().toLowerCase(); return this.getIcmpTypes().filter(el => { return ( el.type.toString() === filterValue || this.translateService .instant(this.getIcmpTypeTranslationToken(el.type)) .toLowerCase() .indexOf(filterValue) !== -1 ); }); } private onIcmpCodeChange() { this.icmpCodeChanges = this.icmpCode.valueChanges.subscribe(value => { this.updateFilteredIcmpCodes(value); }); } private updateFilteredIcmpCodes(value: number | string) { this.filteredIcmpCodes = this.filterIcmpCodes(value); } private filterIcmpCodes(val: number | string | null) { if (val === null || val === '') { return this.getIcmpCodes(); } const filterValue = val.toString().toLowerCase(); const icmpType = this.icmpType.value; return this.getIcmpCodes().filter(code => { return ( code.toString().indexOf(filterValue) !== -1 || this.translateService .instant(this.getIcmpCodeTranslationToken(icmpType, code)) .toLowerCase() .indexOf(filterValue) !== -1 ); }); } private updateDisabledStatusOnIcmpTypeField() { if (this.cidr.valid) { this.icmpType.enable(); } else { this.icmpType.disable(); } } private updateDisabledStatusOnIcmpCodeField() { if (this.icmpType.valid) { this.icmpCode.enable(); } else { this.icmpCode.disable(); } } private getIcmpTypes(): IcmpType[] { const cidrIpVersion = CidrUtils.getCidrIpVersion(this.cidr.value); if (!cidrIpVersion) { return []; } return cidrIpVersion === IPVersion.ipv6 ? icmpV6Types : icmpV4Types; } private getIcmpCodes(): number[] { const type: string | number = this.icmpType.value; // type === 0 is valid value so we can't use !type if (type === null || type === '') { return []; } const numType = +type; const typeObj = this.getIcmpTypes().find(el => { return el.type === numType; }); return typeObj ? typeObj.codes : []; } private getIcmpTypeTranslationToken(type: number) { const cidrIpVersion = CidrUtils.getCidrIpVersion(this.cidr.value); if (!cidrIpVersion) { return; } return cidrIpVersion === IPVersion.ipv6 ? getICMPV6TypeTranslationToken(type) : getICMPTypeTranslationToken(type); } private getIcmpCodeTranslationToken(type: number, code: number) { const cidrIpVersion = CidrUtils.getCidrIpVersion(this.cidr.value); if (!cidrIpVersion) { return; } return cidrIpVersion === IPVersion.ipv6 ? getICMPV6CodeTranslationToken(type, code) : getICMPCodeTranslationToken(type, code); } private get type(): AbstractControl | null { return this.ruleForm.get('type'); } private get protocol(): AbstractControl | null { return this.ruleForm.get('protocol'); } private get cidr(): AbstractControl | null { return this.ruleForm.get('cidr'); } public get startPort(): AbstractControl | null { return this.portsForm.get('startPort'); } private get endPort(): AbstractControl | null { return this.portsForm.get('endPort'); } private get icmpType(): AbstractControl | null { return this.icmpForm.get('icmpType'); } private get icmpCode(): AbstractControl | null { return this.icmpForm.get('icmpCode'); } }
the_stack
import type { ActionMap } from "@interactjs/core/scope"; import type { Modifier } from "@interactjs/modifiers/base"; import type { Interactable, InteractEvent, Interaction, ResizeEvent } from "@interactjs/types"; import interact from "@nothingislost/interactjs"; import { around } from "monkey-around"; import { Component, EphemeralState, HoverPopover, MarkdownEditView, OpenViewState, parseLinktext, PopoverState, MousePos, requireApiVersion, resolveSubpath, setIcon, TFile, View, Workspace, WorkspaceLeaf, WorkspaceSplit, EmptyView, } from "obsidian"; import HoverEditorPlugin, { genId } from "./main"; import { restorePopover, calculateOffsets, storeDimensions, snapToEdge, expandContract, dragMoveListener, } from "./utils/measure"; const popovers = new WeakMap<Element, HoverEditor>(); export interface HoverEditorParent { hoverPopover: HoverEditor | null; containerEl?: HTMLElement; view?: View; dom?: HTMLElement; } type ConstructableWorkspaceSplit = new (ws: Workspace, dir: string) => WorkspaceSplit; let mouseCoords: MousePos = { x: 0, y: 0 }; function nosuper<T>(base: new (...args: unknown[]) => T): new () => T { const derived = function () { return Component.call(this); }; derived.prototype = base.prototype; return Object.setPrototypeOf(derived, base); } export class HoverEditor extends nosuper(HoverPopover) { onTarget: boolean; onHover: boolean; shownPos: MousePos | null; isPinned: boolean = this.plugin.settings.autoPin === "always" ? true : false; isDragging: boolean; isResizing: boolean; interact?: Interactable; lockedOut: boolean; abortController? = this.addChild(new Component()); detaching = false; opening = false; rootSplit: WorkspaceSplit = new (WorkspaceSplit as ConstructableWorkspaceSplit)(window.app.workspace, "vertical"); targetRect = this.targetEl?.getBoundingClientRect(); pinEl: HTMLElement; titleEl: HTMLElement; containerEl: HTMLElement; hideNavBarEl: HTMLElement; viewHeaderHeight: number; oldPopover = this.parent?.hoverPopover; constrainAspectRatio: boolean; id = genId(8); resizeModifiers: Modifier[]; dragElementRect: { top: number; left: number; bottom: number; right: number }; onMouseIn: (event: MouseEvent) => void; onMouseOut: (event: MouseEvent) => void; xspeed: number; yspeed: number; bounce?: NodeJS.Timeout; boundOnZoomOut: () => void; originalPath: string; // these are kept to avoid adopting targets w/a different link originalLinkText: string; static activePopovers() { return document.body .findAll(".hover-popover") .map(el => popovers.get(el)!) .filter(he => he); } static forLeaf(leaf: WorkspaceLeaf | undefined) { // leaf can be null such as when right clicking on an internal link const el = leaf?.containerEl.matchParent(".hover-popover"); return el ? popovers.get(el) : undefined; } static iteratePopoverLeaves(ws: Workspace, cb: (leaf: WorkspaceLeaf) => unknown) { for (const popover of this.activePopovers()) { if (popover.rootSplit && ws.iterateLeaves(cb, popover.rootSplit)) return true; } return false; } constructor( parent: HoverEditorParent, public targetEl: HTMLElement, public plugin: HoverEditorPlugin, waitTime?: number, public onShowCallback?: () => unknown, ) { // super(); if (waitTime === undefined) { waitTime = 300; } this.onTarget = true; this.onHover = false; this.shownPos = null; this.parent = parent; this.waitTime = waitTime; this.state = PopoverState.Showing; const hoverEl = (this.hoverEl = createDiv({ cls: "popover hover-popover", attr: { id: "he" + this.id } })); this.onMouseIn = this._onMouseIn.bind(this); this.onMouseOut = this._onMouseOut.bind(this); this.abortController!.load(); if (targetEl) { targetEl.addEventListener("mouseover", this.onMouseIn); targetEl.addEventListener("mouseout", this.onMouseOut); } hoverEl.addEventListener("mouseover", event => { if (mouseIsOffTarget(event, hoverEl)) { this.onHover = true; this.onTarget = false; this.transition(); } }); hoverEl.addEventListener("mouseout", event => { if (mouseIsOffTarget(event, hoverEl)) { this.onHover = false; this.onTarget = false; this.transition(); } }); this.timer = window.setTimeout(this.show.bind(this), waitTime); document.addEventListener("mousemove", setMouseCoords); // custom logic begin popovers.set(this.hoverEl, this); this.hoverEl.addClass("hover-editor"); this.containerEl = this.hoverEl.createDiv("popover-content"); this.buildWindowControls(); this.setInitialDimensions(); const pinEl = (this.pinEl = createEl("a", "popover-header-icon mod-pin-popover")); this.titleEl.prepend(this.pinEl); pinEl.onclick = () => { this.togglePin(); }; if (requireApiVersion && requireApiVersion("0.13.27")) { setIcon(pinEl, "lucide-pin", 17); } else { setIcon(pinEl, "pin", 17); } this.createResizeHandles(); if (this.plugin.settings.imageZoom) this.registerZoomImageHandlers(); } adopt(targetEl: HTMLElement) { if (this.targetEl === targetEl) return true; const bounds = targetEl?.getBoundingClientRect(); if (overlaps(this.targetRect, bounds)) { this.targetEl.removeEventListener("mouseover", this.onMouseIn); this.targetEl.removeEventListener("mouseout", this.onMouseOut); targetEl.addEventListener("mouseover", this.onMouseIn); targetEl.addEventListener("mouseout", this.onMouseOut); this.targetEl = targetEl; this.targetRect = bounds; const { x, y } = mouseCoords; this.onTarget = overlaps(bounds, { left: x, right: x, top: y, bottom: y } as DOMRect); this.transition(); return true; } else { this.onTarget = false; this.transition(); } return false; } onZoomOut() { document.body.removeEventListener("mouseup", this.boundOnZoomOut); document.body.removeEventListener("dragend", this.boundOnZoomOut); if (this.hoverEl.hasClass("do-not-restore")) { this.hoverEl.removeClass("do-not-restore"); } else { restorePopover(this.hoverEl); } } onZoomIn(event: MouseEvent) { if (event.button !== 0) { return; } if (this.hoverEl.hasClass("snap-to-viewport")) { this.hoverEl.addClass("do-not-restore"); } document.body.addEventListener("mouseup", this.boundOnZoomOut, { once: true, }); document.body.addEventListener("dragend", this.boundOnZoomOut, { once: true, }); const offset = calculateOffsets(); storeDimensions(this.hoverEl); snapToEdge(this.hoverEl, "viewport", offset); return false; } registerZoomImageHandlers() { this.hoverEl.addClass("image-zoom"); this.boundOnZoomOut = this.onZoomOut.bind(this); this.hoverEl.on("mousedown", "img", this.onZoomIn.bind(this)); } togglePin(value?: boolean) { if (value === undefined) { value = !this.isPinned; } if (value) this.abortController?.unload(); this.hoverEl.toggleClass("is-pinned", value); this.pinEl.toggleClass("is-active", value); this.isPinned = value; } getDefaultMode() { return this.parent?.view?.getMode ? this.parent.view.getMode() : "preview"; } updateLeaves() { if (this.onTarget && this.targetEl && !document.contains(this.targetEl)) { this.onTarget = false; this.transition(); } let leafCount = 0; this.plugin.app.workspace.iterateLeaves(leaf => { leafCount++; }, this.rootSplit); if (leafCount === 0) { this.hide(); // close if we have no leaves } else if (leafCount > 1) { this.toggleConstrainAspectRatio(false); } this.hoverEl.setAttribute("data-leaf-count", leafCount.toString()); } get headerHeight() { const hoverEl = this.hoverEl; return this.titleEl.getBoundingClientRect().bottom - hoverEl.getBoundingClientRect().top; } toggleMinimized(value?: boolean) { const hoverEl = this.hoverEl; const headerHeight = this.headerHeight; if (!hoverEl.hasAttribute("data-restore-height")) { if (this.plugin.settings.rollDown) expandContract(hoverEl, false); hoverEl.setAttribute("data-restore-height", String(hoverEl.offsetHeight)); hoverEl.style.minHeight = headerHeight + "px"; hoverEl.style.maxHeight = headerHeight + "px"; hoverEl.toggleClass("is-minimized", true); } else { const restoreHeight = hoverEl.getAttribute("data-restore-height"); if (restoreHeight) { hoverEl.removeAttribute("data-restore-height"); hoverEl.style.height = restoreHeight + "px"; } hoverEl.style.removeProperty("max-height"); hoverEl.toggleClass("is-minimized", false); if (this.plugin.settings.rollDown) expandContract(hoverEl, true); } this.interact?.reflow({ name: "drag", axis: "xy" }); } attachLeaf(): WorkspaceLeaf { this.rootSplit.getRoot = () => this.plugin.app.workspace.rootSplit; this.titleEl.insertAdjacentElement("afterend", this.rootSplit.containerEl); const leaf = this.plugin.app.workspace.createLeafInParent(this.rootSplit, 0); this.updateLeaves(); return leaf; } onload(): void { super.onload(); this.registerEvent(this.plugin.app.workspace.on("layout-change", this.updateLeaves, this)); } leaves() { const leaves: WorkspaceLeaf[] = []; this.plugin.app.workspace.iterateLeaves(leaf => { leaves.push(leaf); }, this.rootSplit); return leaves; } setInitialDimensions() { this.hoverEl.style.height = this.plugin.settings.initialHeight; this.hoverEl.style.width = this.plugin.settings.initialWidth; } toggleViewHeader(value?: boolean) { if (value === undefined) value = !this.hoverEl.hasClass("show-navbar"); this.hideNavBarEl?.toggleClass("is-active", value); this.hoverEl.toggleClass("show-navbar", value); const viewHeaderEl = this.hoverEl.querySelector(".view-header"); if (!viewHeaderEl) return; const calculatedViewHeaderHeight = parseFloat( getComputedStyle(viewHeaderEl).getPropertyValue("--he-view-header-height"), ); this.hoverEl.style.transition = "height 0.2s"; if (value) { this.hoverEl.style.height = parseFloat(this.hoverEl.style.height) + calculatedViewHeaderHeight + "px"; } else { this.hoverEl.style.height = parseFloat(this.hoverEl.style.height) - calculatedViewHeaderHeight + "px"; } setTimeout(() => { this.hoverEl.style.removeProperty("transition"); }, 200); this.requestLeafMeasure(); } buildWindowControls() { this.titleEl = createDiv("popover-titlebar"); this.titleEl.createDiv("popover-title"); const popoverActions = this.titleEl.createDiv("popover-actions"); const hideNavBarEl = (this.hideNavBarEl = popoverActions.createEl("a", "popover-action mod-show-navbar")); setIcon(hideNavBarEl, "sidebar-open", 14); hideNavBarEl.addEventListener("click", event => { this.toggleViewHeader(); }); if (this.plugin.settings.showViewHeader) { this.toggleViewHeader(true); } const minEl = popoverActions.createEl("a", "popover-action mod-minimize"); setIcon(minEl, "minus"); minEl.addEventListener("click", event => { restorePopover(this.hoverEl); this.toggleMinimized(); }); const maxEl = popoverActions.createEl("a", "popover-action mod-maximize"); setIcon(maxEl, "maximize", 14); maxEl.addEventListener("click", event => { if (this.hoverEl.hasClass("snap-to-viewport")) { setIcon(maxEl, "maximize", 14); restorePopover(this.hoverEl); return; } setIcon(maxEl, "minimize", 14); const offset = calculateOffsets(); storeDimensions(this.hoverEl); snapToEdge(this.hoverEl, "viewport", offset); }); const closeEl = popoverActions.createEl("a", "popover-action mod-close"); setIcon(closeEl, "x"); closeEl.addEventListener("click", event => { this.hide(); }); this.containerEl.prepend(this.titleEl); } requestLeafMeasure() { // address view height measurement issues triggered by css transitions // we wait a bit for the transition to finish and remeasure const leaves = this.leaves(); if (leaves.length) { setTimeout(() => { leaves.forEach(leaf => leaf.onResize()); }, 200); } } onShow() { // Once we've been open for closeDelay, use the closeDelay as a hiding timeout const { closeDelay } = this.plugin.settings; setTimeout(() => (this.waitTime = closeDelay), closeDelay); this.oldPopover?.hide(); this.oldPopover = null; this.hoverEl.toggleClass("is-new", true); document.body.addEventListener( "click", () => { this.hoverEl.toggleClass("is-new", false); }, { once: true, capture: true }, ); if (this.parent) { this.parent.hoverPopover = this; } this.togglePin(this.isPinned); this.onShowCallback?.(); this.onShowCallback = undefined; // only call it once } startBounce() { this.bounce = setTimeout(() => { this.hoverEl.style.left = parseFloat(this.hoverEl.style.left) + this.xspeed + "px"; this.hoverEl.style.top = parseFloat(this.hoverEl.style.top) + this.yspeed + "px"; this.checkHitBox(); this.startBounce(); }, 20); } toggleBounce() { this.xspeed = 7; this.yspeed = 7; if (this.bounce) { clearTimeout(this.bounce); this.bounce = undefined; const el = this.hoverEl.querySelector(".view-content") as HTMLElement; if (el?.style) { el.style.removeProperty("backgroundColor"); } } else { this.startBounce(); } } checkHitBox() { const x = parseFloat(this.hoverEl.style.left); const y = parseFloat(this.hoverEl.style.top); const width = parseFloat(this.hoverEl.style.width); const height = parseFloat(this.hoverEl.style.height); if (x <= 0 || x + width >= document.body.offsetWidth) { this.xspeed *= -1; this.pickColor(); } if (y <= 0 || y + height >= document.body.offsetHeight) { this.yspeed *= -1; this.pickColor(); } } pickColor() { const r = Math.random() * (254 - 0) + 0; const g = Math.random() * (254 - 0) + 0; const b = Math.random() * (254 - 0) + 0; const el = this.hoverEl.querySelector(".view-content") as HTMLElement; if (el?.style) { el.style.backgroundColor = "rgb(" + r + "," + g + ", " + b + ")"; } } transition() { if (this.shouldShow()) { if (this.state === PopoverState.Hiding) { this.state = PopoverState.Shown; clearTimeout(this.timer); } } else { if (this.state === PopoverState.Showing) { this.hide(); } else { if (this.state === PopoverState.Shown) { this.state = PopoverState.Hiding; this.timer = window.setTimeout(() => { if (this.shouldShow()) { this.transition(); } else { this.hide(); } }, this.waitTime); } } } } detect(el: HTMLElement) { // TODO: may not be needed? the mouseover/out handers handle most detection use cases const { targetEl, hoverEl } = this; if (targetEl) { this.onTarget = el === targetEl || targetEl.contains(el); } this.onHover = el === hoverEl || hoverEl.contains(el); } _onMouseIn(event: MouseEvent) { if (!(this.targetEl && !mouseIsOffTarget(event, this.targetEl))) { this.onTarget = true; this.transition(); } } _onMouseOut(event: MouseEvent) { if (!(this.targetEl && !mouseIsOffTarget(event, this.targetEl))) { this.onTarget = false; this.transition(); } } position(pos?: MousePos | null): void { // without this adjustment, the x dimension keeps sliding over to the left as you progressively mouse over files // disabling this for now since messing with pos.x like this breaks the detect() logic // if (pos && pos.x !== undefined) { // pos.x = pos.x + 20; // } // native obsidian logic if (pos === undefined) { pos = this.shownPos; } let rect; if (pos) { rect = { top: pos.y - 10, bottom: pos.y + 10, left: pos.x, right: pos.x, }; } else if (this.targetEl) { const relativePos = getRelativePos(this.targetEl, document.body); rect = { top: relativePos.top, bottom: relativePos.top + this.targetEl.offsetHeight, left: relativePos.left, right: relativePos.left + this.targetEl.offsetWidth, }; } else { rect = { top: 0, bottom: 0, left: 0, right: 0, }; } document.body.appendChild(this.hoverEl); positionEl(rect, this.hoverEl, { gap: 10, }); // custom hover editor logic if (pos) { // give positionEl a chance to adjust the position before we read the coords setTimeout(() => { const left = parseFloat(this.hoverEl.style.left); const top = parseFloat(this.hoverEl.style.top); this.hoverEl.setAttribute("data-x", String(left)); this.hoverEl.setAttribute("data-y", String(top)); }, 0); } } shouldShow() { return this.shouldShowSelf() || this.shouldShowChild(); } shouldShowChild(): boolean { return HoverEditor.activePopovers().some(popover => { if (popover !== this && popover.targetEl && this.hoverEl.contains(popover.targetEl)) { return popover.shouldShow(); } return false; }); } shouldShowSelf() { // Don't let obsidian show() us if we've already started closing // return !this.detaching && (this.onTarget || this.onHover); return ( !this.detaching && !!( this.onTarget || this.onHover || (this.state == PopoverState.Shown && this.isPinned) || document.querySelector(`body>.modal-container, body > #he${this.id} ~ .menu`) ) ); } calculateMinSize() { return { width: 40, height: this.headerHeight }; } calculateMaxSize(x: number, y: number, interaction: Interaction<keyof ActionMap>) { const width = interaction.pointerType === "reflow" ? document.body.offsetWidth / 1.5 : document.body.offsetWidth; const height = interaction.pointerType === "reflow" ? document.body.offsetHeight / 1.5 : document.body.offsetHeight; return { width: width, height: height }; } toggleConstrainAspectRatio(value?: boolean, ratio?: number) { const aspectRatioMod = this.resizeModifiers.find(mod => mod.name == "aspectRatio"); if (!aspectRatioMod) return; if (value === undefined) value = !aspectRatioMod.options.enabled; if (value) { aspectRatioMod.enable(); this.constrainAspectRatio = true; if (ratio !== undefined && aspectRatioMod.options.ratio !== ratio) { aspectRatioMod.options.ratio = ratio; } } else { aspectRatioMod.disable(); this.constrainAspectRatio = false; } } registerInteract() { const viewPortBounds = this.plugin.app.dom.appContainerEl; const self = this; const calculateBoundaryRestriction = function ( eventX: number, eventY: number, interaction: Interaction<keyof ActionMap>, ) { const { top, right, bottom, left, x, y, width, height } = viewPortBounds.getBoundingClientRect(); const boundingRect = { top, right, bottom, left, x, y, width, height }; if (interaction.pointerType === "reflow") { // if we're reflowing, we want to keep the window fully inside the viewport self.dragElementRect.bottom = 1; } else { self.dragElementRect.bottom = 0; } if (self.plugin.settings.snapToEdges) { boundingRect.top = top - 30; boundingRect.bottom = bottom - self.headerHeight; } else { boundingRect.bottom = bottom - self.headerHeight; } return boundingRect; }; let firstMovement = true; let windowChromeHeight: number; const imgRatio = this.hoverEl.dataset?.imgRatio ? parseFloat(this.hoverEl.dataset?.imgRatio) : undefined; this.resizeModifiers = [ interact.modifiers.restrictEdges({ outer: viewPortBounds, }), interact.modifiers.restrictSize({ min: self.calculateMinSize.bind(this), max: self.calculateMaxSize.bind(this), }), interact.modifiers.aspectRatio({ ratio: imgRatio || "preserve", enabled: false, }), ]; this.dragElementRect = { top: 0, left: 1, bottom: 0, right: 0 }; const dragModifiers = [ interact.modifiers.restrict({ restriction: calculateBoundaryRestriction, offset: { top: 0, left: 40, bottom: 0, right: 40 }, elementRect: this.dragElementRect, endOnly: false, }), ]; if (this.constrainAspectRatio && imgRatio !== undefined) { this.toggleConstrainAspectRatio(true, imgRatio); } const i = interact(this.hoverEl) .preventDefault("always") .on("doubletap", this.onDoubleTap.bind(this)) .draggable({ // inertiajs has a core lib memory leak currently. leave disabled // inertia: false, modifiers: dragModifiers, allowFrom: ".popover-titlebar", listeners: { start(event: DragEvent) { // only auto pin if the drag with user initiated // this avoids a reflow causing an auto pin if (event.buttons) self.togglePin(true); if (event.buttons && event.target instanceof HTMLElement) { event.target.addClass("is-dragging"); } }, end(event: DragEvent) { if (event.target instanceof HTMLElement) { event.target.removeClass("is-dragging"); } }, move: dragMoveListener.bind(self), }, }) .resizable({ edges: { top: ".top-left, .top-right, .top", left: ".top-left, .bottom-left, .left", bottom: ".bottom-left, .bottom-right, .bottom", right: ".top-right, .bottom-right, .right", }, modifiers: this.resizeModifiers, listeners: { start(event: ResizeEvent) { const viewEl = event.target as HTMLElement; viewEl.style.removeProperty("max-height"); const viewHeaderHeight = (self.hoverEl.querySelector(".view-header") as HTMLElement)?.offsetHeight; const titlebarHeight = self.titleEl.offsetHeight; windowChromeHeight = titlebarHeight + viewHeaderHeight; firstMovement = true; // only auto pin if the drag with user initiated // this avoids a reflow causing an auto pin if (event.buttons) self.togglePin(true); }, move: function (event: ResizeEvent) { if (!event?.deltaRect || !event.edges) return; const { target } = event; let { x, y } = target.dataset; let height = event.rect.height; let width = event.rect.width; x = x ? x : target.style.left; y = y ? y : target.style.top; x = String((parseFloat(x) || 0) + event.deltaRect?.left); y = String((parseFloat(y) || 0) + event.deltaRect?.top); if (self.constrainAspectRatio && imgRatio && event.buttons !== undefined) { // don't run if this was an automated resize (ie. reflow) if (firstMovement) { // adjustments to compensate for the titlebar height if (event.edges.top && (event.edges.right || event.edges.left)) { y = String(parseFloat(y) - windowChromeHeight); } else if (event.edges.top) { x = String(parseFloat(x) + windowChromeHeight * imgRatio); } else if (event.edges.left && !(event.edges.top || event.edges.bottom)) { y = String(parseFloat(y) - windowChromeHeight); } } firstMovement = false; if (event.edges.top && !(event.edges.right || event.edges.left)) { height = height - windowChromeHeight; width = width - windowChromeHeight * imgRatio; } else if (event.edges.bottom && !(event.edges.right || event.edges.left)) { height = height - windowChromeHeight; width = width - windowChromeHeight * imgRatio; } height = height + windowChromeHeight; if (target.hasClass("snap-to-left") || target.hasClass("snap-to-right")) { y = String(parseFloat(target.style.top)); x = String(parseFloat(target.style.left)); } } else { if (imgRatio && height > document.body.offsetHeight) { height = height / 1.5; width = height * imgRatio; } } Object.assign(target.style, { width: `${width}px`, height: `${height}px`, top: `${y}px`, left: x === "NaN" ? "unset" : `${x}px`, }); Object.assign(target.dataset, { x, y }); }, end: function (event: ResizeEvent) { if (event.buttons === undefined) { const height = parseFloat(event.target.style.height) + windowChromeHeight; event.target.style.height = height + "px"; } if (event.rect.height > self.headerHeight) { event.target.removeAttribute("data-restore-height"); } i.reflow({ name: "drag", axis: "xy" }); }, }, }); this.interact = i; } createResizeHandles() { this.hoverEl.createDiv("resize-handle bottom-left"); this.hoverEl.createDiv("resize-handle bottom-right"); this.hoverEl.createDiv("resize-handle top-left"); this.hoverEl.createDiv("resize-handle top-right"); this.hoverEl.createDiv("resize-handle right"); this.hoverEl.createDiv("resize-handle left"); this.hoverEl.createDiv("resize-handle bottom"); this.hoverEl.createDiv("resize-handle top"); } onDoubleTap(event: InteractEvent) { if (event.target.tagName === "DIV" && event.target.closest(".popover-titlebar")) { event.preventDefault(); this.togglePin(true); this.toggleMinimized(); } } show() { // native obsidian logic start if (!this.targetEl || document.body.contains(this.targetEl)) { this.state = PopoverState.Shown; this.timer = 0; this.shownPos = mouseCoords; this.position(mouseCoords); document.removeEventListener("mousemove", setMouseCoords); this.onShow(); // initializingHoverPopovers.remove(this); // activeHoverPopovers.push(this); // initializePopoverChecker(); this.load(); } else { this.hide(); } // native obsidian logic end // if this is an image view, set the dimensions to the natural dimensions of the image // an interactjs reflow will be triggered to constrain the image to the viewport if it's // too large if (this.hoverEl.dataset.imgHeight && this.hoverEl.dataset.imgWidth) { this.hoverEl.style.height = parseFloat(this.hoverEl.dataset.imgHeight) + this.titleEl.offsetHeight + "px"; this.hoverEl.style.width = parseFloat(this.hoverEl.dataset.imgWidth) + "px"; } this.registerInteract(); this.interact?.reflow({ name: "resize", edges: { right: true, bottom: true }, }); this.interact?.reflow({ name: "drag", axis: "xy" }); } onHide() { this.oldPopover = null; if (this.parent?.hoverPopover === this) { this.parent.hoverPopover = null; } } hide() { this.onTarget = this.onHover = false; this.isPinned = false; this.detaching = true; // Once we reach this point, we're committed to closing // in case we didn't ever call show() document.removeEventListener("mousemove", setMouseCoords); // A timer might be pending to call show() for the first time, make sure // it doesn't bring us back up after we close if (this.timer) { clearTimeout(this.timer); this.timer = 0; } // Hide our HTML element immediately, even if our leaves might not be // detachable yet. This makes things more responsive and improves the // odds of not showing an empty popup that's just going to disappear // momentarily. this.hoverEl.hide(); // If a file load is in progress, we need to wait until it's finished before // detaching leaves. Because we set .detaching, The in-progress openFile() // will call us again when it finishes. if (this.opening) return; const leaves = this.leaves(); if (leaves.length) { // Detach all leaves before we unload the popover and remove it from the DOM. // Each leaf.detach() will trigger layout-changed and the updateLeaves() // method will then call hide() again when the last one is gone. leaves.forEach(leaf => leaf.detach()); } else { this.parent = null; if (this.interact?.unset) this.interact.unset(); this.abortController?.unload(); this.abortController = undefined; this.interact = undefined; return this.nativeHide(); } } nativeHide() { const { hoverEl, targetEl } = this; this.state = PopoverState.Hidden; hoverEl.detach(); if (targetEl) { const parent = targetEl.matchParent(".hover-popover"); if (parent) popovers.get(parent)?.transition(); targetEl.removeEventListener("mouseover", this.onMouseIn); targetEl.removeEventListener("mouseout", this.onMouseOut); } this.onHide(); this.unload(); } resolveLink(linkText: string, sourcePath: string): TFile | null { const link = parseLinktext(linkText); const tFile = link ? this.plugin.app.metadataCache.getFirstLinkpathDest(link.path, sourcePath) : null; return tFile; } async openLink(linkText: string, sourcePath: string, eState?: EphemeralState, createInLeaf?: WorkspaceLeaf) { let file = this.resolveLink(linkText, sourcePath); const link = parseLinktext(linkText); if (!file && createInLeaf) { const folder = this.plugin.app.fileManager.getNewFileParent(sourcePath); file = await this.plugin.app.fileManager.createNewMarkdownFile(folder, link.path); } if (!file) { this.displayCreateFileAction(linkText, sourcePath, eState); return; } const { viewRegistry } = this.plugin.app; const viewType = viewRegistry.typeByExtension[file.extension]; if (!viewType || !viewRegistry.viewByType[viewType]) { this.displayOpenFileAction(file); return; } eState = Object.assign(this.buildEphemeralState(file, link), eState); const parentMode = this.getDefaultMode(); const state = this.buildState(parentMode, eState); const leaf = await this.openFile(file, state, createInLeaf); const leafViewType = leaf?.view?.getViewType(); if (leafViewType === "image") { // TODO: temporary workaround to prevent image popover from disappearing immediately when using live preview if ( this.plugin.settings.autoFocus && this.parent?.hasOwnProperty("editorEl") && (this.parent as unknown as MarkdownEditView).editorEl!.hasClass("is-live-preview") ) { this.waitTime = 3000; } this.constrainAspectRatio = true; const img = leaf!.view.contentEl.querySelector("img")!; this.hoverEl.dataset.imgHeight = String(img.naturalHeight); this.hoverEl.dataset.imgWidth = String(img.naturalWidth); this.hoverEl.dataset.imgRatio = String(img.naturalWidth / img.naturalHeight); } else if (leafViewType === "pdf") { this.hoverEl.style.height = "800px"; this.hoverEl.style.width = "600px"; } if (state.state?.mode === "source") { setTimeout(() => { if (this.detaching) return; leaf?.view?.setEphemeralState(state.eState); }, this.plugin.settings.triggerDelay); } } displayOpenFileAction(file: TFile) { const leaf = this.attachLeaf(); const view = leaf.view! as EmptyView; view.emptyTitleEl.hide(); view.actionListEl.empty(); const { actionListEl } = view; actionListEl.createDiv({ cls: "file-embed-title" }, div => { div.createSpan({ cls: "file-embed-icon" }, span => setIcon(span, "document", 22)); div.appendText(" " + file.name); }); actionListEl.addEventListener("click", () => this.plugin.app.openWithDefaultApp(file.path)); actionListEl.setAttribute("aria-label", i18next.t("interface.embed-open-in-default-app-tooltip")); } displayCreateFileAction(linkText: string, sourcePath: string, eState?: EphemeralState) { const leaf = this.attachLeaf(); const view = leaf.view as EmptyView; if (view) { view.emptyTitleEl?.hide(); view.actionListEl?.empty(); const createEl = view.actionListEl?.createEl("button", "empty-state-action"); if (!createEl) return; createEl.textContent = `${linkText} is not yet created. Click to create.`; if (this.plugin.settings.autoFocus) { setTimeout(() => { createEl?.focus(); }, 200); } createEl.addEventListener( "click", async () => { this.togglePin(true); await this.openLink(linkText, sourcePath, eState, leaf); }, { once: true }, ); } } async openFile(file: TFile, openState?: OpenViewState, useLeaf?: WorkspaceLeaf) { if (this.detaching) return; const leaf = useLeaf ?? this.attachLeaf(); this.opening = true; try { await leaf.openFile(file, openState); if (this.plugin.settings.autoFocus && !this.detaching) { const existingCallback = this.onShowCallback; this.onShowCallback = () => { this.plugin.app.workspace.setActiveLeaf(leaf, false, true); // Prevent this leaf's file from registering as a recent file // (for the quick switcher or Recent Files plugin) for the next // 1ms. (They're both triggered by a file-open event that happens // in a timeout 0ms after setActiveLeaf, so we register now and // uninstall later to ensure our uninstalls happen after the event.) setTimeout( around(Workspace.prototype, { recordMostRecentOpenedFile(old) { return function (_file: TFile) { // Don't update the quick switcher's recent list if (_file !== file) { return old.call(this, _file); } }; }, }), 1, ); const recentFiles = this.plugin.app.plugins.plugins["recent-files-obsidian"]; if (recentFiles) setTimeout( around(recentFiles, { shouldAddFile(old) { return function (_file: TFile) { // Don't update the Recent Files plugin return _file !== file && old.call(this, _file); }; }, }), 1, ); if (existingCallback instanceof Function) existingCallback(); }; if (this.state === PopoverState.Shown) { this.onShowCallback(); this.onShowCallback = undefined; } } else if (!this.plugin.settings.autoFocus && !this.detaching) { const titleEl = this.hoverEl.querySelector(".popover-title"); if (!titleEl) return; titleEl.textContent = leaf.view?.getDisplayText(); titleEl.setAttribute("data-path", leaf.view?.file?.path); } } catch (e) { console.error(e); } finally { this.opening = false; if (this.detaching) this.hide(); } return leaf; } buildState(parentMode: string, eState?: EphemeralState) { const defaultMode = this.plugin.settings.defaultMode; const mode = defaultMode === "match" ? parentMode : this.plugin.settings.defaultMode; return { state: { mode: mode }, eState: eState, }; } buildEphemeralState( file: TFile, link?: { path: string; subpath: string; }, ) { const cache = this.plugin.app.metadataCache.getFileCache(file); const subpath = cache ? resolveSubpath(cache, link?.subpath || "") : undefined; const eState: EphemeralState = { subpath: link?.subpath }; if (subpath) { eState.line = subpath.start.line; eState.startLoc = subpath.start; eState.endLoc = subpath.end || undefined; } return eState; } } export function isHoverLeaf(leaf: WorkspaceLeaf) { return !!HoverEditor.forLeaf(leaf); } /** * It positions an element relative to a rectangle, taking into account the boundaries of the element's * offset parent * @param rect - The rectangle of the element you want to position the popup relative to. * @param {HTMLElement} el - The element to position * @param [options] - { * @returns An object with the top, left, and vresult properties. */ export function positionEl( rect: { top: number; bottom: number; left: number; right: number }, el: HTMLElement, options?: { gap?: number; preference?: string; offsetParent?: HTMLElement; horizontalAlignment?: string }, ) { options = options || {}; el.show(); const gap = options.gap || 0; const verticalPref = options.preference || "bottom"; const parentEl = options.offsetParent || el.offsetParent || document.documentElement; const horizontalAlignment = options.horizontalAlignment || "left"; const parentTop = parentEl.scrollTop + 10; const parentBottom = parentEl.scrollTop + parentEl.clientHeight - 10; const top = Math.min(rect.top, parentBottom); const bottom = Math.max(rect.bottom, parentTop); const elHeight = el.offsetHeight; const fitsAbove = rect.top - parentTop >= elHeight + gap; const fitsBelow = parentBottom - rect.bottom >= elHeight + gap; let topResult = 0; let vresult = ""; // vertical result if (!fitsAbove || ("top" !== verticalPref && fitsBelow)) { if (!fitsBelow || ("bottom" !== verticalPref && fitsAbove)) { if (parentEl.clientHeight < elHeight + gap) { topResult = parentTop; vresult = "overlap"; } else { if ("top" === verticalPref) { topResult = parentTop + gap; vresult = "overlap"; } else { topResult = parentBottom - elHeight; vresult = "overlap"; } } } else { topResult = bottom + gap; vresult = "bottom"; } } else { topResult = top - gap - elHeight; vresult = "top"; } const leftBoundary = parentEl.scrollLeft + 10; const rightBoundary = parentEl.scrollLeft + parentEl.clientWidth - 10; const elWidth = el.offsetWidth; let leftResult = "left" === horizontalAlignment ? rect.left : rect.right - elWidth; if (leftResult < leftBoundary) { leftResult = leftBoundary; } else { if (leftResult > rightBoundary - elWidth) { leftResult = rightBoundary - elWidth; } } el.style.top = "".concat(topResult.toString(), "px"); el.style.left = "".concat(leftResult.toString(), "px"); return { top: topResult, left: leftResult, vresult: vresult, }; } /** * "Get the position of an element relative to a parent element." * * The function takes two arguments: * * el: The element whose position we want to get. * parentEl: The parent element to which we want to get the relative position. * The function returns an object with two properties: * * top: The top position of the element relative to the parent element. * left: The left position of the element relative to the parent element. * * The function works by looping through the offsetParent chain of the element and subtracting the * scrollTop and scrollLeft values of the parent elements * @param {HTMLElement | null} el - The element you want to get the relative position of. * @param {HTMLElement | null} parentEl - The parent element that you want to get the relative position * of. * @returns An object with two properties, top and left. */ function getRelativePos(el: HTMLElement | null, parentEl: HTMLElement | null) { let top = 0, left = 0; for (let nextParentEl = parentEl ? parentEl.offsetParent : null; el && el !== parentEl && el !== nextParentEl; ) { top += el.offsetTop; left += el.offsetLeft; const offsetParent = el.offsetParent as HTMLElement | null; for (let parent = el.parentElement; parent && parent !== offsetParent; ) { top -= parent.scrollTop; left -= parent.scrollLeft; parent = parent.parentElement; } if (offsetParent && offsetParent !== parentEl && offsetParent !== nextParentEl) { top -= offsetParent.scrollTop; left -= offsetParent.scrollLeft; } el = offsetParent; } return { top, left, }; } export function setMouseCoords(event: MouseEvent) { mouseCoords = { x: event.clientX, y: event.clientY, }; } function mouseIsOffTarget(event: MouseEvent, el: Element) { const relatedTarget = event.relatedTarget; return !(relatedTarget instanceof Node && el.contains(relatedTarget)); } function overlaps(rect1?: DOMRect, rect2?: DOMRect) { return !!( rect1 && rect2 && rect1.right > rect2.left && rect1.left < rect2.right && rect1.bottom > rect2.top && rect1.top < rect2.bottom ); }
the_stack
import {PluginBase} from "../plugin-base"; import {Workflow} from "../../"; import {GraphNode} from "../../graph/graph-node"; import {Geometry} from "../../utils/geometry"; import {Edge} from "../../graph/edge"; import {EdgePanner} from "../../behaviors/edge-panning"; export class SVGPortDragPlugin extends PluginBase { /** Stored on drag start to detect collision with viewport edges */ private boundingClientRect: ClientRect; private portOrigins: Map<SVGGElement, SVGMatrix>; /** Group of edges (compound element) leading from origin port to ghost node */ private edgeGroup: SVGGElement; /** Coordinates of the node from which dragged port originates, stored so we can measure the distance from it */ private nodeCoords: { x: number; y: number }; /** Reference to a node that marks a new input/output creation */ private ghostNode: SVGGElement; /** How far away from the port you need to drag in order to create a new input/output instead of snapping */ private snapRadius = 120; /** Tells if the port is on the left or on the right side of a node */ private portType: "input" | "output"; /** Stores a port to which a connection would snap if user stops the drag */ private snapPort: SVGGElement; /** Map of CSS classes attached by this plugin */ private css = { /** Added to svgRoot as a sign that this plugin is active */ plugin: "__plugin-port-drag", /** Suggests that an element that contains it will be the one to snap to */ snap: "__port-drag-snap", /** Added to svgRoot while dragging is in progress */ dragging: "__port-drag-dragging", /** Will be added to suggested ports and their parent nodes */ suggestion: "__port-drag-suggestion", }; /** Port from which we initiated the drag */ private originPort: SVGGElement; private detachDragListenerFn = undefined; private wheelPrevent = ev => ev.stopPropagation(); private panner: EdgePanner; private ghostX = 0; private ghostY = 0; private portOnCanvas: { x: number; y: number }; private lastMouseMove: { x: number; y: number }; registerWorkflow(workflow: Workflow): void { super.registerWorkflow(workflow); this.panner = new EdgePanner(this.workflow); this.workflow.svgRoot.classList.add(this.css.plugin); } afterRender(): void { if(this.workflow.editingEnabled){ this.attachPortDrag(); } } onEditableStateChange(enabled: boolean): void { if (enabled) { this.attachPortDrag(); } else { this.detachPortDrag(); } } destroy(): void { this.detachPortDrag(); } detachPortDrag() { if (typeof this.detachDragListenerFn === "function") { this.detachDragListenerFn(); } this.detachDragListenerFn = undefined; } attachPortDrag() { this.detachPortDrag(); this.detachDragListenerFn = this.workflow.domEvents.drag( ".port", this.onMove.bind(this), this.onMoveStart.bind(this), this.onMoveEnd.bind(this) ); } onMove(dx: number, dy: number, ev: MouseEvent, portElement: SVGGElement): void { document.addEventListener("mousewheel", this.wheelPrevent, true); const mouseOnSVG = this.workflow.transformScreenCTMtoCanvas(ev.clientX, ev.clientY); const scale = this.workflow.scale; const sdx = (dx - this.lastMouseMove.x) / scale; const sdy = (dy - this.lastMouseMove.y) / scale; /** We might have hit the boundary and need to start panning */ this.panner.triggerCollisionDetection(ev.clientX, ev.clientY, (sdx, sdy) => { this.ghostX += sdx; this.ghostY += sdy; this.translateGhostNode(this.ghostX, this.ghostY); this.updateEdge(this.portOnCanvas.x, this.portOnCanvas.y, this.ghostX, this.ghostY); }); const nodeToMouseDistance = Geometry.distance( this.nodeCoords.x, this.nodeCoords.y, mouseOnSVG.x, mouseOnSVG.y ); const closestPort = this.findClosestPort(mouseOnSVG.x, mouseOnSVG.y); this.updateSnapPort(closestPort.portEl, closestPort.distance); this.ghostX += sdx; this.ghostY += sdy; this.translateGhostNode(this.ghostX, this.ghostY); this.updateGhostNodeVisibility(nodeToMouseDistance, closestPort.distance); this.updateEdge(this.portOnCanvas.x, this.portOnCanvas.y, this.ghostX, this.ghostY); this.lastMouseMove = {x: dx, y: dy}; } /** * @FIXME: Add panning * @param {MouseEvent} ev * @param {SVGGElement} portEl */ onMoveStart(ev: MouseEvent, portEl: SVGGElement): void { this.lastMouseMove = {x: 0, y: 0}; this.originPort = portEl; const portCTM = portEl.getScreenCTM(); this.portOnCanvas = this.workflow.transformScreenCTMtoCanvas(portCTM.e, portCTM.f); this.ghostX = this.portOnCanvas.x; this.ghostY = this.portOnCanvas.y; // Needed for collision detection this.boundingClientRect = this.workflow.svgRoot.getBoundingClientRect(); const nodeMatrix = this.workflow.findParent(portEl).transform.baseVal.getItem(0).matrix; this.nodeCoords = { x: nodeMatrix.e, y: nodeMatrix.f }; const workflowGroup = this.workflow.workflow; this.portType = portEl.classList.contains("input-port") ? "input" : "output"; this.ghostNode = this.createGhostNode(this.portType); workflowGroup.appendChild(this.ghostNode); /** @FIXME: this should come from workflow */ this.edgeGroup = Edge.spawn(); this.edgeGroup.classList.add(this.css.dragging); workflowGroup.appendChild(this.edgeGroup); this.workflow.svgRoot.classList.add(this.css.dragging); this.portOrigins = this.getPortCandidateTransformations(portEl); this.highlightSuggestedPorts(portEl.getAttribute("data-connection-id")); } onMoveEnd(ev: MouseEvent): void { document.removeEventListener("mousewheel", this.wheelPrevent, true); this.panner.stop(); const ghostType = this.ghostNode.getAttribute("data-type"); const ghostIsVisible = !this.ghostNode.classList.contains("hidden"); const shouldSnap = this.snapPort !== undefined; const shouldCreateInput = ghostIsVisible && ghostType === "input"; const shouldCreateOutput = ghostIsVisible && ghostType === "output"; const portID = this.originPort.getAttribute("data-connection-id"); if (shouldSnap) { this.createEdgeBetweenPorts(this.originPort, this.snapPort); } else if (shouldCreateInput || shouldCreateOutput) { const svgCoordsUnderMouse = this.workflow.transformScreenCTMtoCanvas(ev.clientX, ev.clientY); const customProps = { "sbg:x": svgCoordsUnderMouse.x, "sbg:y": svgCoordsUnderMouse.y }; if (shouldCreateInput) { this.workflow.model.createInputFromPort(portID, {customProps}); } else { this.workflow.model.createOutputFromPort(portID, {customProps}); } } this.cleanMemory(); this.cleanStyles(); } private updateSnapPort(closestPort: SVGGElement, closestPortDistance: number) { const closestPortChanged = closestPort !== this.snapPort; const closestPortIsOutOfRange = closestPortDistance > this.snapRadius; // We might need to remove old class for snapping if we are closer to some other port now if (this.snapPort && (closestPortChanged || closestPortIsOutOfRange)) { const node = this.workflow.findParent(this.snapPort); this.snapPort.classList.remove(this.css.snap); node.classList.remove(this.css.snap); delete this.snapPort; } // If closest port is further away than our snapRadius, no highlighting should be done if (closestPortDistance > this.snapRadius) { return; } const originID = this.originPort.getAttribute("data-connection-id"); const targetID = closestPort.getAttribute("data-connection-id"); if (this.findEdge(originID, targetID)) { delete this.snapPort; return; } this.snapPort = closestPort; const node = this.workflow.findParent(closestPort); const oppositePortType = this.portType === "input" ? "output" : "input"; closestPort.classList.add(this.css.snap); node.classList.add(this.css.snap); node.classList.add(`${this.css.snap}-${oppositePortType}`); } private updateEdge(fromX: number, fromY: number, toX: number, toY: number): void { const subEdges = this.edgeGroup.children as HTMLCollectionOf<SVGPathElement>; for (let subEdge of <any>subEdges) { const path = Workflow.makeConnectionPath( fromX, fromY, toX, toY, this.portType === "input" ? "left" : "right" ); subEdge.setAttribute("d", path); } } private updateGhostNodeVisibility(distanceToMouse: number, distanceToClosestPort) { const isHidden = this.ghostNode.classList.contains("hidden"); const shouldBeVisible = distanceToMouse > this.snapRadius && distanceToClosestPort > this.snapRadius; if (shouldBeVisible && isHidden) { this.ghostNode.classList.remove("hidden"); } else if (!shouldBeVisible && !isHidden) { this.ghostNode.classList.add("hidden"); } } private translateGhostNode(x: number, y: number) { this.ghostNode.transform.baseVal.getItem(0).setTranslate(x, y); } private getPortCandidateTransformations(portEl: SVGGElement): Map<SVGGElement, SVGMatrix> { const nodeEl = this.workflow.findParent(portEl); const nodeConnectionID = nodeEl.getAttribute("data-connection-id"); const otherPortType = this.portType === "input" ? "output" : "input"; const portQuery = `.node:not([data-connection-id="${nodeConnectionID}"]) .port.${otherPortType}-port`; const candidates = this.workflow.workflow.querySelectorAll(portQuery) as NodeListOf<SVGGElement>; const matrices = new Map<SVGGElement, SVGMatrix>(); for (let port of candidates) { matrices.set(port, Geometry.getTransformToElement(port, this.workflow.workflow)); } return matrices; } /** * Highlights ports that are model says are suggested. * Also marks their parent nodes as highlighted. * * @param {string} targetConnectionID ConnectionID of the origin port */ private highlightSuggestedPorts(targetConnectionID: string): void { // Find all ports that we can validly connect to // Note that we can connect to any port, but some of them are suggested based on hypothetical validity. const portModels = this.workflow.model.gatherValidConnectionPoints(targetConnectionID); for (let i = 0; i < portModels.length; i++) { const portModel = portModels[i]; if (!portModel.isVisible) continue; // Find port element by this connectionID and it's parent node element const portQuery = `.port[data-connection-id="${portModel.connectionId}"]`; const portElement = this.workflow.workflow.querySelector(portQuery); const parentNode = this.workflow.findParent(portElement); // Add highlighting classes to port and it's parent node parentNode.classList.add(this.css.suggestion); portElement.classList.add(this.css.suggestion); } } /** * @FIXME: GraphNode.radius should somehow come through Workflow, */ private createGhostNode(type: "input" | "output"): SVGGElement { const namespace = "http://www.w3.org/2000/svg"; const node = document.createElementNS(namespace, "g"); node.setAttribute("transform", "matrix(1,0,0,1,0,0)"); node.setAttribute("data-type", type); node.classList.add("ghost"); node.classList.add("node"); node.innerHTML = `<circle class="ghost-circle" cx="0" cy="0" r="${GraphNode.radius / 1.5}"></circle>`; return node; } /** * Finds a port closest to given SVG coordinates. */ private findClosestPort(x: number, y: number): { portEl: SVGGElement | undefined, distance: number } { let closestPort = undefined; let closestDistance = Infinity; this.portOrigins.forEach((matrix, port) => { const distance = Geometry.distance(x, y, matrix.e, matrix.f); if (distance < closestDistance) { closestPort = port; closestDistance = distance; } }); return { portEl: closestPort, distance: closestDistance }; } /** * Removes all dom elements and objects cached in-memory during dragging that are no longer needed. */ private cleanMemory() { this.edgeGroup.remove(); this.ghostNode.remove(); this.snapPort = undefined; this.edgeGroup = undefined; this.nodeCoords = undefined; this.originPort = undefined; this.portOrigins = undefined; this.boundingClientRect = undefined; } /** * Removes all css classes attached by this plugin */ private cleanStyles(): void { this.workflow.svgRoot.classList.remove(this.css.dragging); for (let cls in this.css) { const query = this.workflow.svgRoot.querySelectorAll("." + this.css[cls]); for (let el of query) { el.classList.remove(this.css[cls]); } } } /** * Creates an edge (connection) between two elements determined by their connection IDs * This edge is created on the model, and not rendered directly on graph, as main workflow * is supposed to catch the creation event and draw it. */ private createEdgeBetweenPorts(source: SVGGElement, destination: SVGGElement): void { // Find the connection ids of origin port and the highlighted port let sourceID = source.getAttribute("data-connection-id"); let destinationID = destination.getAttribute("data-connection-id"); // Swap their places in case you dragged out from input to output, since they have to be ordered output->input if (sourceID.startsWith("in")) { const tmp = sourceID; sourceID = destinationID; destinationID = tmp; } this.workflow.model.connect(sourceID, destinationID); } private findEdge(sourceID: string, destinationID: string): SVGGElement | undefined { const ltrQuery = `[data-source-connection="${sourceID}"][data-destination-connection="${destinationID}"]`; const rtlQuery = `[data-source-connection="${destinationID}"][data-destination-connection="${sourceID}"]`; return this.workflow.workflow.querySelector(`${ltrQuery},${rtlQuery}`) as SVGGElement; } }
the_stack
import { Store } from 'redux'; import ReduxThunk, { ThunkDispatch } from 'redux-thunk'; import configureMockStore from 'redux-mock-store'; import GetEntity from '../../src/thunk'; import { EntityAction, EntityActionType, ProcessorType, ReduxEntityOptions, ReduxEntityState } from '../types'; type DispatchExts = ThunkDispatch<ReduxEntityState, undefined, EntityAction>; const middlewares = [ReduxThunk]; const mockStore = configureMockStore<ReduxEntityState, DispatchExts>(middlewares); describe('Thunk Action Creators', () => { const entity = 'mockEntity'; let store: Store; beforeEach(() => { store = mockStore({}); }); describe('GetEntity()', () => { describe('Valid Params', () => { it('should not throw any errors', (done) => { expect(() => { store.dispatch<any>(GetEntity(entity, Promise.resolve())).then(done); }).not.toThrow(Error); }); }); describe('Bad Arguments', () => { it('should throw an error when no arguments are passed', () => { expect(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore store.dispatch(GetEntity()); }).toThrow('Missing required entityName'); }); it('should throw an error when "entityName" is null/undefined', () => { [null, undefined].forEach((val) => { expect(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore store.dispatch(GetEntity(val)); }).toThrow('Missing required entityName'); }); }); it('should throw an error when "entityName" not passed a string"', () => { [123, {}, new Date(), []].forEach((val) => { expect(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore store.dispatch(GetEntity(val)); }).toThrow('Missing required entityName'); }); }); it('should throw an error with an undefined data promise', () => { expect(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore store.dispatch(GetEntity(entity)); }).toThrow('Missing required entity promise'); }); it('should throw an error when a promise is not passed', () => { expect(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore store.dispatch(GetEntity(entity, {})); }).toThrow('Missing required entity promise'); }); }); describe('Promise Resolution', () => { const data = { foo: 'bar' }; const expectedFetch = { entity, type: EntityActionType.Request }; const expectedSuccess = { entity, type: EntityActionType.Success, payload: { data, lastUpdated: undefined, append: false, }, }; const expectedActions = [expectedFetch, expectedSuccess]; it('should dispatch FETCH_REQUEST and FETCH_SUCCESS actions', (done) => { const thunk = GetEntity(entity, Promise.resolve(data)); store.dispatch<any>(thunk).then(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(2); expectedSuccess.payload.lastUpdated = actions[1].payload.lastUpdated; expect(expectedActions).toEqual(actions); done(); }); }); }); describe('Promise Rejection', () => { const error = new Error('API Failure'); const expectedRequest = { entity, type: EntityActionType.Request }; const expectedFailure = { entity, type: EntityActionType.Failure, payload: { lastUpdated: undefined, error, }, }; const expectedActions = [expectedRequest, expectedFailure]; it('should dispatch FETCH_REQUEST and FETCH_FAILURE actions', (done) => { const thunk = GetEntity(entity, Promise.reject(error)); store.dispatch<any>(thunk).catch(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(2); expectedFailure.payload.lastUpdated = actions[1].payload.lastUpdated; expect(expectedActions).toEqual(actions); done(); }); }); }); describe('Silent Option', () => { const data = { foo: 'bar' }; const expectedSuccess = { entity, type: EntityActionType.Success, payload: { lastUpdated: undefined, data, append: false, }, }; const configOptions: ReduxEntityOptions = { silent: true }; it('should not dispatch a FETCH_REQUEST action', (done) => { const thunk = GetEntity(entity, Promise.resolve(data), configOptions); store.dispatch<any>(thunk).then(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(1); const successAction = actions[0]; // Force timestamps to match for easier assertion expectedSuccess.payload.lastUpdated = successAction.payload.lastUpdated; // Assert FETCH_SUCCESS was well-formed expect(successAction).toEqual(expectedSuccess); done(); }); }); }); describe('Processor Types', () => { describe('Processor Invocation', () => { it('should invoke the Success processor types', (done) => { const beforeSpy = jest.fn().mockImplementation(() => ({})); const afterSpy = jest.fn().mockImplementation(() => ({})); const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeSuccess]: beforeSpy, [ProcessorType.AfterSuccess]: afterSpy, }, }; const thunk = GetEntity(entity, Promise.resolve({}), options); store.dispatch<any>(thunk).then(() => { expect(beforeSpy).toHaveBeenCalledTimes(1); expect(afterSpy).toHaveBeenCalledTimes(1); done(); }); }); it('should invoke the Failure processor types', (done) => { const beforeSpy = jest.fn().mockImplementation(() => ({})); const afterSpy = jest.fn().mockImplementation(() => ({})); const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeFailure]: beforeSpy, [ProcessorType.AfterFailure]: afterSpy, }, }; const thunk = GetEntity(entity, Promise.reject({}), options); store.dispatch<any>(thunk).catch(() => { expect(beforeSpy).toHaveBeenCalledTimes(1); expect(afterSpy).toHaveBeenCalledTimes(1); done(); }); }); it('should invoke the Success processor types with data, dispatch, and getState', (done) => { const promiseData = { foo: 'bar' }; const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeSuccess]: (data: any, dispatch, getState) => { expect(data).toEqual(promiseData); expect(typeof dispatch).toEqual('function'); expect(typeof getState).toEqual('function'); dispatch({ type: 'In_Before_Success' }); return data; }, [ProcessorType.AfterSuccess]: (data: any, dispatch, getState) => { expect(data).toEqual(promiseData); expect(typeof dispatch).toEqual('function'); expect(typeof getState).toEqual('function'); dispatch({ type: 'In_After_Success' }); }, }, }; const thunk = GetEntity(entity, Promise.resolve(promiseData), options); store.dispatch<any>(thunk).then(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(4); done(); }); }); it('should invoke the Failure processor types with data, dispatch, and getState', (done) => { const promiseError = new Error('API Error'); const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeFailure]: (error: any, dispatch, getState) => { expect(error).toEqual(promiseError); expect(typeof dispatch).toEqual('function'); expect(typeof getState).toEqual('function'); dispatch({ type: 'In_Before_Failure' }); return error; }, [ProcessorType.AfterFailure]: (error: any, dispatch, getState) => { expect(error).toEqual(promiseError); expect(typeof dispatch).toEqual('function'); expect(typeof getState).toEqual('function'); dispatch({ type: 'In_After_Failure' }); }, }, }; const thunk = GetEntity(entity, Promise.reject(promiseError), options); store.dispatch<any>(thunk).catch(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(4); done(); }); }); }); describe('BEFORE_SUCCESS', () => { it('should return the data as modified in the processor', (done) => { const data = { foo: 'bar', baz: 'qux' }; const expectedArray = Object.keys(data); const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeSuccess]: (data: any) => Object.keys(data), }, }; const thunk = GetEntity(entity, Promise.resolve(data), options); store.dispatch<any>(thunk).then(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(2); const success = actions[1]; expect(success.payload.data).toEqual(expectedArray); done(); }); }); it('should return the mutated data as modified in the processor', (done) => { const data = { foo: 'bar' }; const mutatedData = { foo: 'foo', baz: 'qux', }; const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeSuccess]: (data: any) => ({ ...data, foo: 'foo', baz: 'qux', }), }, }; const thunk = GetEntity(entity, Promise.resolve(data), options); store.dispatch<any>(thunk).then(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(2); const success = actions[1]; expect(success.payload.data).toEqual(mutatedData); done(); }); }); }); describe('BEFORE_FAILURE', () => { const apiError = new Error('Fake error 1'); const newError = new Error('Fake error 2'); it('should return a new error', (done) => { const options: ReduxEntityOptions = { processors: { [ProcessorType.BeforeFailure]: () => newError, }, }; const thunk = GetEntity(entity, Promise.reject(apiError), options); store.dispatch<any>(thunk).catch(() => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const actions = store.getActions(); expect(actions).toHaveLength(2); const failure = actions[1]; expect(failure.payload.error).toEqual(newError); done(); }); }); }); }); }); });
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * ManagementGroups * __NOTE__: An instance of this class is automatically created for an * instance of the ManagementGroupsClient. */ export interface ManagementGroups { /** * List management groups for the authenticated user. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.skiptoken] Page continuation token is only used if * a previous operation returned a partial result. * If a previous response contains a nextLink element, the value of the * nextLink element will include a token parameter that specifies a starting * point to use for subsequent calls. * * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupListResult>>; /** * List management groups for the authenticated user. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.skiptoken] Page continuation token is only used if * a previous operation returned a partial result. * If a previous response contains a nextLink element, the value of the * nextLink element will include a token parameter that specifies a starting * point to use for subsequent calls. * * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupListResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupListResult>; list(callback: ServiceCallback<models.ManagementGroupListResult>): void; list(options: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupListResult>): void; /** * Get the details of the management group. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] The $expand=children query string parameter * allows clients to request inclusion of children in the response payload. * Possible values include: 'children' * * @param {boolean} [options.recurse] The $recurse=true query string parameter * allows clients to request inclusion of entire hierarchy in the response * payload. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupWithHierarchy>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(options?: { expand? : string, recurse? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupWithHierarchy>>; /** * Get the details of the management group. * * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] The $expand=children query string parameter * allows clients to request inclusion of children in the response payload. * Possible values include: 'children' * * @param {boolean} [options.recurse] The $recurse=true query string parameter * allows clients to request inclusion of entire hierarchy in the response * payload. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupWithHierarchy} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupWithHierarchy} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupWithHierarchy} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(options?: { expand? : string, recurse? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupWithHierarchy>; get(callback: ServiceCallback<models.ManagementGroupWithHierarchy>): void; get(options: { expand? : string, recurse? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupWithHierarchy>): void; /** * List management groups for the authenticated user. * * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupListResult>>; /** * List management groups for the authenticated user. * * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupListResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ManagementGroupListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupListResult>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ManagementGroupsClient. */ export interface Operations { /** * Lists all of the available management REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available management REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available management REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available management REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; }
the_stack
import assert = require("assert") import { Direction, JoinParam, JoinType, LOGIC_COMMANDS, Order, Params, QUERY_COMMANDS, UPDATE_COMMANDS } from "../types" /** * SqlBuilder: Mongo 操作语法生成 SQL 语句 */ export class SqlBuilder { readonly params: Params private _values: any[] = [] constructor(params: Params) { this._values = [] this.params = params } static from(params: Params): SqlBuilder { return new SqlBuilder(params) } get table(): string { return this.params.collection } get query(): any { return this.params.query || {} } get projection(): any { return this.params.projection || {} } get orders(): Order[] { return this.params.order || [] } get data(): any { return this.params.data || {} } get joins(): JoinParam[] { return this.params.joins || [] } select() { const fields = this.buildProjection() const joins = this.buildJoins() const query = this.buildQuery() const orderBy = this.buildOrder() const limit = this.buildLimit() const sql = `select ${fields} from ${this.table} ${joins}${query} ${orderBy} ${limit}` const values = this.values() return { sql, values } } update() { this.checkData() const data = this.buildUpdateData() const joins = this.buildJoins() const query = this.buildQuery() // 当 multi 为 true 时允许多条更新,反之则只允许更新一条数据 // multi 默认为 false const multi = this.params.multi const limit = multi ? '' : `limit 1` const orderBy = this.buildOrder() const sql = `update ${this.table} ${data} ${joins}${query} ${orderBy} ${limit}` const values = this.values() return { sql, values } } delete() { const joins = this.buildJoins() const query = this.buildQuery() // 当 multi 为 true 时允许多条更新,反之则只允许更新一条数据 const multi = this.params.multi const limit = multi ? '' : `limit 1` const orderBy = this.buildOrder() const sql = `delete from ${this.table} ${joins}${query} ${orderBy} ${limit} ` const values = this.values() return { sql, values } } insert() { this.checkData() const data = this.buildInsertData() const sql = `insert into ${this.table} ${data}` const values = this.values() return { sql, values } } count() { const joins = this.buildJoins() const query = this.buildQuery() const sql = `select count(*) as total from ${this.table} ${joins}${query}` const values = this.values() return { sql, values } } protected addValues(values: any[]) { this._values.push(...values) } // 构建联表语句(join) protected buildJoins(): string { const joins = this.joins const leftTable = this.params.collection if (joins.length === 0) return '' const strs = [] for (const join of joins) { const { collection, leftKey, rightKey, type } = join assert(this.checkJoinType(type), `invalid join type: ${type}`) this.checkField(collection) this.checkField(leftKey) this.checkField(rightKey) const rightTable = collection const str = `${type} join ${rightTable} on ${leftTable}.${leftKey} = ${rightTable}.${rightKey}` strs.push(str) } const ret = strs.join(' ') /** * 因为 join 功能是后加的, 空 joins 拼入 sql 后,会增加两 * 这样会导致,原来的单元测试用例都无法通过的问题 * 如果 joins 为空,那么就只插入空串,无空格即可 */ const wrapped_joins = ret == '' ? '' : ` ${ret} ` return wrapped_joins } protected checkJoinType(joinType: string): boolean { const types: string[] = [JoinType.FULL, JoinType.INNER, JoinType.LEFT, JoinType.RIGHT] return types.includes(joinType) } // build query string protected buildQuery(): string { const builder = SqlQueryBuilder.from(this.query) const sql = builder.build() const values = builder.values() this.addValues(values) return sql } // build update data string: set x=a, y=b ... /** * * ```js * { * action: 'database.updateDocument', * collection: 'categories', * query: { _id: '6024f815acbf480fbb9648ce' }, * data: { * '$set': { title: 'updated-title' }, * '$inc': { age: 1 }, * '$unset': { content: '' } * }, * merge: true * } * ``` */ protected buildUpdateData(): string { let strs = [] // sql 不支持 merge 为 false 的情况(合并更新,即替换) assert(this.params.merge, 'invalid params: {merge} should be true in sql') // $set if (this.data[UPDATE_COMMANDS.SET]) { const _data = this.data[UPDATE_COMMANDS.SET] assert(typeof _data === 'object', 'invalid data: value of $set must be object') for (const key in _data) { const _val = _data[key] assert(this.isBasicValue(_val), `invalid data: value of data only support BASIC VALUE(number|boolean|string|undefined|null), {${key}:${_val}} given`) this.addValues([_val]) strs.push(`${key}=?`) } } // $inc if (this.data[UPDATE_COMMANDS.INC]) { const _data = this.data[UPDATE_COMMANDS.INC] assert(typeof _data === 'object', 'invalid data: value of $inc must be object') for (const key in _data) { const _val = _data[key] assert(typeof _val === 'number', `invalid data: value of $inc property only support number, {${key}:${_val}} given`) this.addValues([_val]) strs.push(`${key}= ${key} + ?`) } } // $mul if (this.data[UPDATE_COMMANDS.MUL]) { const _data = this.data[UPDATE_COMMANDS.MUL] assert(typeof _data === 'object', 'invalid data: value of $mul must be object') for (const key in _data) { const _val = _data[key] assert(typeof _val === 'number', `invalid data: value of $mul property only support number, {${key}:${_val}} given`) this.addValues([_val]) strs.push(`${key}= ${key} * ?`) } } // $unset if (this.data[UPDATE_COMMANDS.REMOVE]) { const _data = this.data[UPDATE_COMMANDS.REMOVE] assert(typeof _data === 'object', 'invalid data: value of $unset must be object') for (const key in _data) { strs.push(`${key}= null`) } } assert(strs.length, 'invalid data: set statement in sql is empty') return 'set ' + strs.join(',') } // build insert data string: (field1, field2) values (a, b, c) ... protected buildInsertData(): string { const fields = Object.keys(this.data) const values = fields.map(key => { const _val = this.data[key] assert(this.isBasicValue(_val), `invalid data: value of data only support BASIC VALUE(number|boolean|string|undefined|null), {${key}:${_val}} given`) this.addValues([_val]) return '?' }) const s_fields = fields.join(',') const s_values = values.join(',') return `(${s_fields}) values (${s_values})` } protected _buildData(): { fields: string[], values: any[] } { const fields = Object.keys(this.data) const values = fields.map(key => { const _val = this.data[key] assert(this.isBasicValue(_val), `invalid data: value of data only support BASIC VALUE(number|boolean|string|undefined|null), {${key}:${_val}} given`) return _val }) return { fields, values } } protected buildOrder(): string { if (this.orders.length === 0) { return '' } const strs = this.orders.map(ord => { assert([Direction.ASC, Direction.DESC].includes(ord.direction), `invalid query: order value of {${ord.field}:${ord.direction}} MUST be 'desc' or 'asc'`) return `${ord.field} ${ord.direction}` }) return 'order by ' + strs.join(',') } protected buildLimit(_limit?: number): string { const offset = this.params.offset || 0 const limit = this.params.limit || _limit || 100 assert(typeof offset === 'number', 'invalid query: offset must be number') assert(typeof limit === 'number', 'invalid query: limit must be number') return `limit ${offset},${limit}` } /** * 指定返回的字段 * @tip 在 mongo 中可以指定只显示哪些字段 或者 不显示哪些字段,而在 SQL 中我们只支持[只显示哪些字段] * 示例数据: `projection: { age: 1, f1: 1}` */ protected buildProjection(): string { let fields = [] for (const key in this.projection) { this.checkProjection(key) const value = this.projection[key] assert(value, `invalid query: value of projection MUST be {true} or {1}, {false} or {0} is not supported in sql`) fields.push(key) } if (fields.length === 0) { return '*' } return fields.join(',') } protected values(): any[] { return this._values || [] } // 是否为值属性(number, string, boolean, undefine, null) protected isBasicValue(value) { if (value === null) { return true } const type = typeof value return ['number', 'string', 'boolean', 'undefined'].includes(type) } // data 不可为空 protected checkData() { assert(this.data, `invalid data: data can NOT be ${this.data}`) assert(typeof this.data === 'object', `invalid data: data must be an object`) assert(!(this.data instanceof Array), `invalid data: data cannot be Array while using SQL`) const keys = Object.keys(this.data) keys.forEach(this.checkField) assert(keys.length, `invalid data: data can NOT be empty object`) } protected checkField(field_name: string) { if (SecurityCheck.checkField(field_name) === false) throw new Error(`invalid field : '${field_name}'`) } protected checkProjection(name: string) { if (SecurityCheck.checkProjection(name) === false) { throw new Error(`invalid projection field : '${name}'`) } } } /** * Mongo 查询转换为 SQL 查询 */ export class SqlQueryBuilder { readonly query: any private _values: any[] = [] // SQL 参数化使用,收集SQL参数值 constructor(query: any) { this.query = query } static from(query: any) { return new SqlQueryBuilder(query) } // build(): string | null { assert(this.hasNestedFieldInQuery() === false, 'invalid query: nested property in query') let strs = ['where 1=1'] // 遍历查询属性 for (const key in this.query) { const v = this.buildOne(key, this.query[key]) strs.push(v) } strs = strs.filter(s => s != '' && s != undefined) if (strs.length === 1) { return strs[0] } return strs.join(' and ') } values(): any[] { return this._values } // 处理一条查询属性(逻辑操作符属性、值属性、查询操作符属性) protected buildOne(key: string, value: any) { this.checkField(key) // 若是逻辑操作符 if (this.isLogicOperator(key)) { return this.processLogicOperator(key, value) } // 若是值属性(number, string, boolean) if (this.isBasicValue(value)) { return this.processBasicValue(key, value, QUERY_COMMANDS.EQ) } // 若是查询操作符(QUERY_COMMANDS) if (typeof value === 'object') { return this.processQueryOperator(key, value) } throw new Error(`unknow query property found: {${key}: ${value}}`) } // 递归处理逻辑操作符的查询($and $or) /** ```js query = { f1: 0, '$or': [ { f2: 1}, { f6: { '$lt': 4000 } }, { '$and': [ { f6: { '$gt': 6000 } }, { f6: { '$lt': 8000 } } ] } ] } // where 1=1 and f1 = 0 and (f2 = 1 and f6 < 4000 or (f6 > 6000 and f6 < 8000)) ``` */ protected processLogicOperator(operator: string, value: any[]) { const that = this function _process(key: string, _value: any[] | any): string { // 如果是逻辑符,则 value 为数组遍历子元素 if (that.isLogicOperator(key)) { assert(_value instanceof Array, `invalid query: value of logic operator must be array, but ${_value} given`) let result = [] for (const item of _value) { // 逻辑符子项遍历 for (const k in item) { // 操作 const r = _process(k, item[k]) result.push(r) } } // 将逻辑符中每个子项的结果用 逻辑符 连接起来 const op = that.mapLogicOperator(key) const _v = result.join(` ${op} `) // keep spaces in both ends return `(${_v})` // } // 若是值属性(number, string, boolean) if (that.isBasicValue(_value)) { return that.processBasicValue(key, _value, QUERY_COMMANDS.EQ) } // 若是查询操作符(QUERY_COMMANDS) if (typeof _value === 'object') { return that.processQueryOperator(key, _value) } } return _process(operator, value) } // 处理值属性 protected processBasicValue(field: string, value: string | number | boolean | [], operator: string) { this.checkField(field) const op = this.mapQueryOperator(operator) let _v = null // $in $nin 值是数组, 需单独处理 const { IN, NIN } = QUERY_COMMANDS if ([IN, NIN].includes(operator)) { (value as any[]).forEach(v => this.addValue(v)) const arr = (value as any[]).map(_ => '?') const vals = arr.join(',') _v = `(${vals})` } else { assert(this.isBasicValue(value), `invalid query: typeof '${field}' must be number|string|boolean|undefined|null, but ${typeof value} given`) this.addValue(value) _v = '?' } return `${field} ${op} ${_v}` } // 处理查询操作符属性 protected processQueryOperator(field: string, value: any) { let strs = [] // key 就是查询操作符 for (let key in value) { this.checkField(key) // @todo 暂且跳过[非]查询操作符,这种情况应该报错? if (!this.isQueryOperator(key)) { continue } const sub_value = value[key] const result = this.processBasicValue(field, sub_value, key) strs.push(result) } strs = strs.filter(s => s != '' && s != undefined) if (strs.length === 0) { return '' } return strs.join(' and ') } protected addValue(value: any) { this._values.push(value) } // 是否为值属性(number, string, boolean) protected isBasicValue(value) { const type = typeof value return ['number', 'string', 'boolean'].includes(type) } // 是否为逻辑操作符 protected isLogicOperator(key: string) { const keys = Object.keys(LOGIC_COMMANDS) .map(k => LOGIC_COMMANDS[k]) return keys.includes(key) } // 是否为查询操作符(QUERY_COMMANDS) protected isQueryOperator(key: string) { const keys = Object.keys(QUERY_COMMANDS) .map(k => QUERY_COMMANDS[k]) return keys.includes(key) } // 是否为操作符 protected isOperator(key: string) { return this.isLogicOperator(key) || this.isQueryOperator(key) } // 获取所有的查询操作符 // @TODO not used protected getQueryOperators(): string[] { const logics = Object.keys(LOGIC_COMMANDS) .map(key => LOGIC_COMMANDS[key]) const queries = Object.keys(QUERY_COMMANDS) .map(key => QUERY_COMMANDS[key]) return [...logics, ...queries] } // 判断 Query 中是否有属性嵌套 public hasNestedFieldInQuery() { for (let key in this.query) { // 忽略对象顶层属性操作符 if (this.isOperator(key)) { continue } // 子属性是否有对象 const obj = this.query[key] if (typeof obj !== 'object') { continue } if (this.hasObjectIn(obj)) { return true } } return false } // 判断给定对象(Object)中是否存在某个属性为非操作符对象 protected hasObjectIn(object: any) { for (let key in object) { // 检测到非操作符对象,即判定存在 if (!this.isOperator(key)) { return true } } return false } // 转换 mongo 查询操作符到 sql protected mapQueryOperator(operator: string) { assert(this.isQueryOperator(operator), `invalid query: operator ${operator} must be query operator`) let op = '' switch (operator) { case QUERY_COMMANDS.EQ: op = '=' break case QUERY_COMMANDS.NEQ: op = '<>' break case QUERY_COMMANDS.GT: op = '>' break case QUERY_COMMANDS.GTE: op = '>=' break case QUERY_COMMANDS.LT: op = '<' break case QUERY_COMMANDS.LTE: op = '<=' break case QUERY_COMMANDS.IN: op = 'in' break case QUERY_COMMANDS.NIN: op = 'not in' break case QUERY_COMMANDS.LIKE: op = 'like' break } assert(op != '', `invalid query: unsupperted query operator ${operator}`) return op } // 转换 mongo 逻辑操作符到 sql protected mapLogicOperator(operator: string) { assert(this.isLogicOperator(operator), `invalid query: operator ${operator} must be logic operator`) let op = '' switch (operator) { case LOGIC_COMMANDS.AND: op = 'and' break case LOGIC_COMMANDS.OR: op = 'or' break } assert(op != '', `invalid query: unsupperted logic operator ${operator}`) return op } protected checkField(field_name) { if (SecurityCheck.checkField(field_name) === false) throw new Error(`invalid field : '${field_name}'`) } } /** * 安全检测工具: SQL注入,字段合法性 */ class SecurityCheck { // 检查字段名是否合法:data field, query field static checkField(name: string): boolean { if (this.isOperator(name)) { return true } const black_list = [ ' ', '#', // ' or ', ';', `'`, `"`, '`', '-', '/', '*', '\\', '+', '%' ] if (this.containStrs(name, black_list)) { return false } return true } // 检查字段名是否合法:data field, query field static checkProjection(name: string): boolean { const black_list = [ '#', ' or ', ';', `'`, `"`, '`', '+', '-', '/', '\\', '%', ] if (this.containStrs(name, black_list)) { return false } return true } static containStrs(source: string, str_list: string[]): boolean { for (const ch of str_list) { if (source.indexOf(ch) >= 0) return true } return false } // 是否为逻辑操作符 static isLogicOperator(key: string): boolean { const keys = Object.keys(LOGIC_COMMANDS) .map(k => LOGIC_COMMANDS[k]) return keys.includes(key) } // 是否为查询操作符(QUERY_COMMANDS) static isQueryOperator(key: string): boolean { const keys = Object.keys(QUERY_COMMANDS) .map(k => QUERY_COMMANDS[k]) return keys.includes(key) } // 是否为操作符 static isOperator(key: string): boolean { return this.isLogicOperator(key) || this.isQueryOperator(key) } }
the_stack
import DocPage from '../../components/DocPage' import DocSection from '../../components/DocSection' import Code from '../../components/Code' import wdill from '../../public/images/What does it look like.png' import wdill1 from '../../public/images/What does it look like1.png' import wdill2 from '../../public/images/What does it look like2.png' import mixpanel from '../../public/images/mixpanel.png' import opsgenie from '../../public/images/OpsGenie.png' import elmah_io from '../../public/images/elmah.io.png' import wdill3 from '../../public/images/What does it look like3.png' import sumologic from '../../public/images/SumoLogic.png' import { Targets } from '../../components/samples' export default function TargetsPage() { return ( <DocPage name="all-target" title="Targets / Sinks" colour="pink"> <DocSection title='InfluxDB' id='influxdb'> <p>Suppose you're measuring values coming from a car. This is what that could look like:</p> <ul> <li>Events will be logged to InfluxDb like such:<span className="_code"> "pointName, event=template, ctx1=ctxval1, ctx2=ctxval2 field1=fieldval1, field2=fieldval2 value=1i 14566666xxxx"</span></li> <br></br> <li>In other words, fields will be influx values and context fields will be influx tags.</li> <br></br> <li>The timestamp of the Message will be at the end as the timestamp of the sent line</li> <br></br> <li> Events will be logged in these influx measure names, so that you could e.g. put <span className="_code"> "event_fatal" </span>as an annotation in Grafana: <ul> <li><span className="_code"> event_verbose </span></li> <li><span className="_code"> event_debug </span></li> <li><span className="_code"> event_info</span></li> <li><span className="_code"> event_warn </span></li> <li><span className="_code"> event_error </span></li> <li><span className="_code"> event_fatal </span></li> </ul> </li> </ul> </DocSection> <DocSection title='File target' id='file'> <p> Logary's file target is primarily geared towards systems that are running on single machines as it prints a human-readable format, rather than a machine- readable one. </p> <h3>Configuration</h3> <p> The default configuration of the file target rotates log files greater than 200 MiB and deletes log files when the configured folder size is larger than 3 GiB. </p> <p> Folders that don't exist when the target starts are automatically created on target start-up in the current service's security context. Should the calls to create the folder fail, the target is never started, but will restart continuously like any ther Logary target. </p> <Code language="fsharp" value={Targets['Doc1.fs']} /> <p> Or in C#: </p> <Code language="fsharp" value={Targets['Doc2.cs']} /> <h3>Policies &amp; specifications</h3> <p>You can specify a number of deletion and rotation policies when configuring the file target. The deletion policies dictate when the oldest logs should be deleted, whilst the rotation policies dictates when the files should be rotated (thereby the previous file archived).</p> <p>Furthermore, you can specify a naming specification that dictates how the files should be named on disk.</p> <ul> <li>Deletion of files happen directly when at least one deletion policy has triggered.</li> <li>Rotation of files happen directly when at least one rotation policy has triggered.</li> <li>Naming specifications should automatically be amended with sequence number, should that be required.</li> </ul> <h3>Performance</h3> <p>The <span className="_code"> File </span> target is a performance-optimised target. Logging always happens on a separate thread from the caller, so we try to reach a balance between throughput and latency on ACKs.</p> <p>On Windows, overlapped IO is not used, because the files are opened in Append mode, should have equivalent performance. This means we should have similar performance on Linux and Windows.</p> <p>The formatters used for the <span className="_code">File</span> target should be writing to<span className="_code"> TextWriter</span> instances to avoid creating extra string copies in memory.</p> <h3>Handling of errors</h3> <p>The file target is thought as a last-chance target, because by default, logs should be shipped from your nodes/machines to a central logging service. It can also be nicely put to use for local console apps that need to log to disk.</p> <ul> <li>Non-target-fatal <span className="_code">IOExceptions</span>, for example when NTFS ACKs file deletes but still keeps the file listable and available for some duration afterwards are retried on a case-by-case basis. Internal Warn-level messages are logged.</li><br></br> <li>Fatal <span className="_code">IOExceptions</span> – more other cases; directory not found, file not found, etc. are not retried. The target should crash and restart. Its current batch is then retried forever, while logging internal Fatal-level exceptions.</li> </ul> <h3>Invariants</h3> <ul> <li>The File target is modelled as a transaction log and trades speed against safety that the contents have been written to disk, but does not do the bookkeeping required to use FILE_FLAG_NO_BUFFER.</li> <li>Fatal level events are automatically flushed/fsync-ed.</li> <li>Only a single writer to a file is allowed at any given time. This invariant exists because atomic flushes to files are only possible on Linux up to the page size used in the page cache.</li> <li>Only asynchronous IO is done, i.e. the Logary worker thread is not blocked by calls into the operating system. Because of the overhead of translating callbacks into Job/Alt structures, we try to write as much data as possible on every call into the operating system. This means that Messages to be logged can be ACKed in batches rather than individually.</li> <li>If your disk collapses while writing log messages (which happens once in a while and happens frequently when you have thousands of servers), the target should save its last will and then retry a configurable number of times after waiting an exponentially growing duration between each try. It does this by crashing and letting the supervisor handle the failure. After exhausting the tries, the batch of log messages is discarded.</li> <li>If there are IO errors on writing the log messages to disk, there's no guarantee that there won't be duplicate log lines written; however, they're normally timestamped, so downstream log ingestion systems can do de-duplication. This is from the batched nature of the File target.</li> </ul> <h3>Overview of buffers</h3> <ol type="1"> <li> You write a Message from your call-site, this message is synchronised upon between the sending thread and the receiving thread using Hopac. <ol type="I"> <li>If you use one of the logWithAck functions, placing the message in the RingBuffer can be awaited (or NACKed)</li> <li> If you use the logSimple function, the synchronisation is hoisted onto the concurrency scheduler's pending queue and raced with a timeout to be discarded if the logging subsystem is overwhelmed.</li> </ol> </li> <br></br> <li>Once the Message is in the RingBuffer of the File target, it's either removed by itself, or as part of a batch, to be serialised to string.</li> <br></br> <li>The serialisation function reads through the values of the message and uses the formatter function to write those values into a TextWriter. The TextWriter is normally a StreamWriter writing to a FileStream. This means no extra strings need be created through concatenation.</li> <br></br> <li>Depending on the inProcBuffer configuration flag, the TextWriter either supports buffering, which buffers the string inside the CLR process, or writes directly to the underlying file handle, which transitions the data to the kernel's ioctl subsystem. By default we don't buffer here.</li> <br></br> <li>Depending on the flushToDisk configuration flag, the FileStream is or is not called with Flush(true), which forces a disk synchronisation. By default we let the page cache buffer these writes, to trade safety against throughput. This is similar to how most other targets work.</li> <br></br> Depending on the writeThrough flag; Messages written with the File target is only ACKed when they are durably on disk. Defaults to true. <br></br> </ol> <p>Note that disposing Logary, e.g. during application exit flushes all buffers.</p> <h3>Notes on FILE_FLAG_NO_BUFFERING</h3> <p>I've been considering supporting <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/file-buffering"> NO_BUFFERING </a>but this would require callers to possibly wait for the 4096 bytes buffer to fill up before ACKing messages. However, for low-throughput logging, where each log line may be around, say, 240 bytes of text, having the NO_BUFFERING flag set may end up losing us more than it gains us.</p> <h5>References</h5> <ul> <li><a href="https://support.microsoft.com/en-us/kb/99794">https://support.microsoft.com/en-us/kb/99794</a></li> <br></br> <li><a href="https://stackoverflow.com/questions/317801/win32-write-to-file-without-buffering">https://stackoverflow.com/questions/317801/win32-write-to-file-without-buffering</a></li> <br></br> <li><a href="https://winntfs.com/2012/11/29/windows-write-caching-part-2-an-overview-for-application-developers/">https://winntfs.com/2012/11/29/windows-write-caching-part-2-an-overview-for-application-developers/</a></li> <br></br> <li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/cc644950(v=vs.85).aspx">https://msdn.microsoft.com/en-us/library/windows/desktop/cc644950(v=vs.85).aspx</a></li> <br></br> <li><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363772(v=vs.85).aspx">https://msdn.microsoft.com/en-us/library/windows/desktop/aa363772(v=vs.85).aspx</a></li> <br></br> <li><a href="https://stackoverflow.com/questions/8692635/how-do-disable-disk-cache-in-c-sharp-invoke-win32-createfile-api-with-file-flag">https://stackoverflow.com/questions/8692635/how-do-disable-disk-cache-in-c-sharp-invoke-win32-createfile-api-with-file-flag</a></li> <br></br> <li><a href="https://stackoverflow.com/questions/122362/how-to-empty-flush-windows-read-disk-cache-in-c">https://stackoverflow.com/questions/122362/how-to-empty-flush-windows-read-disk-cache-in-c</a></li> <br></br> <li><a href="https://ayende.com/blog/174785/fast-transaction-log-windows">https://ayende.com/blog/174785/fast-transaction-log-windows</a></li> <br></br> </ul> <h5>Example runs</h5> <p>These runs illustrate the above points in a more direct manner. In all of these cases we're writing 10K events to disk.</p> <pre>inProcBuffer = false, flushToDisk = true, caller awaits all acks at the end</pre> <p>This is the safest option and takes 1.3 seconds to log, format and write 10K messages.</p> <pre> <code> I 2016-11-08T11:04:00.6125063+00:00: Event 1 [Logary.Samples.main] <br></br> number =&gt; 1 <br></br> ... <br></br> [12:04:02 DBG] Flushing to disk. <br></br> ... <br></br> I 2016-11-08T11:04:02.0201345+00:00: Event 9402 [Logary.Samples.main] <br></br> number =&gt; 9402 <br></br> [12:04:02 DBG] Flushing to disk. <br></br> I 2016-11-08T11:04:02.0201345+00:00: Event 9403 [Logary.Samples.main] <br></br> number =&gt; 9403 <br></br> I 2016-11-08T11:04:02.0201345+00:00: Event 9404 [Logary.Samples.main] <br></br> number =&gt; 9404 <br></br> ... <br></br> I 2016-11-08T11:04:02.0891350+00:00: Event 10000 [Logary.Samples.main] <br></br> number =&gt; 10000 <br></br> [12:04:02 DBG] Flushing to disk. <br></br> ... <br></br> </code> </pre> <p>The interleaved flushes shows the batching functionality of the File target in action.</p> <pre>inProcBuffer = false, flushToDisk = true, caller awaits all ack after each</pre> <p>This example represents the worst-case usage of the safest configuration.</p> <pre> <code> I 2016-11-08T11:14:42.9071732+00:00: Event 1 [Logary.Samples.main] <br></br> number =&gt; 1 <br></br> <br></br> [12:14:42 DBG] Flushing to disk. <br></br> I 2016-11-08T11:14:42.9711735+00:00: Event 2 [Logary.Samples.main] <br></br> number =&gt; 2 <br></br> [12:14:42 DBG] Flushing to disk. <br></br> I 2016-11-08T11:04:02.0201345+00:00: Event 9403 [Logary.Samples.main] <br></br> number =&gt; 3 <br></br> [12:14:42 DBG] Flushing to disk. <br></br> I 2016-11-08T11:04:02.0201345+00:00: Event 9404 [Logary.Samples.main] <br></br> number =&gt; 4 <br></br> [12:14:42 DBG] Flushing to disk. <br></br> ... <br></br> I 2016-11-08T11:15:04.7635448+00:00: Event 10000 [Logary.Samples.main] <br></br> number =&gt; 10000 <br></br> [12:15:04 DBG] Flushing to disk. <br></br> </code> </pre> <p>With this configuration, the File target would still batch other threads' Messages but since this example has a single thread producer, there's only a single Message available for the target every loop.</p> <pre>inProcBuffer = true, flushToDisk = false, writeThrough=false caller awaits all acks at the end</pre> <p>This is the least safe and most speedy option. Useful when you're shipping logs away from the node and configure those shippers in a safer manner. In this case, .Net and the operating system and the device drivers decide when to flush.</p> <p>On exit/dispose of Logary, all targets are always flushed.</p> <pre> <code> [12:32:05 INF] Event 1 <br></br> ... <br></br> [12:32:06 INF] Event 10000 <br></br> [12:32:48 DBG] Shutting down Logary. <br></br> ... <br></br> [12:32:48 DBG] Flushing to disk. <br></br> </code> </pre> <p>In this example, the actual time taken is dominated by the time to generate the messages.</p> <h3>Work to be done</h3> <ul> <li>Unit test rotation code</li> <li>Then enable rotation</li> <li>Harden against exceptions during writes – mock FileSystem</li> </ul> </DocSection> <DocSection title='Stackdriver target' id='stackdriver'> <p> Development has been sponsored by <a href="https://www.tradera.com/?utm_source=logary"> Tradera.com. </a> </p> <p> Logary also includes a logging target for <a href="https://cloud.google.com/stackdriver"> Google Cloud Stackdriver. </a> </p> <h3>Configuration</h3> <p>The target can be configured like so:</p> <Code language="fsharp" value={Targets['Doc3.fs']} /> <p>Then, within withTargets:</p> <pre>Stackdriver.create conf "target-name"</pre> <h3>Further work</h3> <ul> <li>batching</li> <li> flushing <ul> <li>the underlying library doesn't provide a flush mechanism yet</li> </ul> </li> </ul> </DocSection> <DocSection title='Jaeger tracing target' id='jaeger'> <ul> <br></br> <li><a href="https://www.jaegertracing.io/"></a> https://www.jaegertracing.io/</li> </ul> <h3>Install jaeger tracing</h3> <ul> <br></br> <li><a href="https://www.jaegertracing.io/download/"></a> https://www.jaegertracing.io/download/</li> </ul> <h3>Usage</h3> <p>add ambientSpanId middleware to the target, if you want to use ambient span</p> <pre>jaegerTargetConf |&gt; TargetConf.middleware Middleware.ambientSpanId</pre> <p>then create span for some tracing, log message as usual:</p> <Code language="fsharp" value={Targets['Doc4.fs']} /> <p>if not using ambient span, you can use Message.setSpanId for log message and Span.setParentSpanInfo for childSpan creation.</p> <Code language="fsharp" value={Targets['Doc5.fs']} /> <h3>What does it look like?</h3> <img className="wdill" src={wdill} alt="What does it look like" /> </DocSection> <DocSection title='AliYun Log Service target' id='aliyun'> <h3>Usage</h3> <Code language="fsharp" value={Targets['Doc6.fs']} /> <h3>What does it look like?</h3> <img className="wdill" src={wdill2} alt="What does it look like" /> <img className="wdill" src={wdill1} alt="What does it look like" /> </DocSection> <DocSection title='Azure AppInsights target' id='azure-appinsights'> <p> Target for <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/overview"> Microsoft Azure AppInsights </a> logs the events as TRACE-messages (or Events/Metrics with a different MappingConfiguration). You need to set the API-key first. Then when you go to Azure Portal Application Insights and <span className="_code"> Overview -&gt; Search </span> you should be able to find the targets from there. Metrics goes to <span className="_code"> Metrics Explorer -&gt; Add Chart -&gt; Custom. </span> <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/create-new-resource">More info...</a> </p> </DocSection> <DocSection title='Commercial targets' id='commercial-targets'> <p>Logary is a production-grade logging and metrics library. We've also built targets that integrate with external paid services. These are listed here.</p> <h3>Mixpanel</h3> <img src={mixpanel} alt="" /> <p>Learn how people use your app with the world's most advanced mobile &amp; web analytics.</p> <p>[Purchase today](mailto:henrik@haf.se?subject=Logary Mixpanel Target)</p> <h5>Features</h5> <ul> <li>Ship logs from your iOS, Android app</li> <br></br> <li>Ship logs and handle user identification and unique-id tracking from web</li> <br></br> <li>Use your own domain and server (over HTTPS)</li> <br></br> <li>Logary listens on your server and forwards your events into Mixpanel</li> <br></br> <li>Add granular server-side event filtering/enriching/correlation for better insights before shipping them onwards.</li> <br></br> <li>Log web app usage even when Mixpanel is blocked client-side</li> <br></br> </ul> <h5>What's included?</h5> <p>We like open source – so in the purchase the reference source is provided so that it can be debugged like the rest of Logary.</p> <p>Send an e-mail to purchase</p> <p>This assumes you have an account at <a href="https://mixpanel.com/">Mixpanel.</a> </p> <h3>OpsGenie</h3> <img src={opsgenie} alt="" /> <p>You can't rely on any one notification method for critical alerts. Get alert notifications via iOS &amp; Android push, SMS, and phone calls; escalate automatically to team members if the alert is not acknowledged.</p> <p>The Logary target for OpsGenie ensures that you can bring in your Logging and Metrics into your daily operations.</p> <h5>Features</h5> <ul> <li>Connect using your own API key</li> <br></br> <li>Make Logary events into new alerts</li> <br></br> <li>Supports custom 'enrichers' to let you specify e.g. user, teams, recipients, tags, entity and notes, to name a few.</li> <br></br> <li>Ready to use from both F# and C#</li> <br></br> <li>Use derived metrics to create load-level alerts</li> <br></br> <li>Stay on top of your infrastructure</li> <br></br> <li>Avoid blacklisting your transactional e-mail service</li> <br></br> </ul> <p>This assumes you have an account at <a href="https://www.opsgenie.com/"> OpsGenie.</a></p> <h3>elmah.io</h3> <a href="https://elmah.io/"><img src={elmah_io} ></img></a> <p></p> <p><span className="_code"> source https://www.nuget.org/api/v2 </span></p> <p><span className="_code"> nuget Logary.Targets.Elmah.Io </span></p> <p>OR:</p> <p><span className="_code"> Install-Package Logary.Targets.Elmah.Io </span></p> <h5>Usage</h5> <p>Configure elmah.io just like you would any normal target.</p> <Code language="fsharp" value={Targets['Doc7.fs']} /> <p>Or from C#:</p> <Code language="fsharp" value={Targets['Doc8.cs']} /> <img src={wdill3}></img> <p>You'll get the same view by logging this Message:</p> <Code language="fsharp" value={Targets['Doc9.fs']} /> <p>This assumes you have an account at <a href="https://elmah.io/"> elmah.io.</a></p> <h3>SumoLogic (community-contributed)</h3> <a href="https://www.sumologic.com/"><img src={sumologic}></img></a> <p></p> <p>SumoLogic is a hosted service (at about 99 USD per month) that unifies logging, metrics, analytics and dashboards in a single service. As such it's a perfect Target for Logary, since Logary supports both logs and metrics.</p> <p>Have a look at @neoeinstein's <a href="https://neoeinstein.github.io/Logary.Targets.SumoLogic/"> Logary.Targets.SumoLogic </a> for the official docs and a sample of how to use it.</p> <span className="_code"> source https://www.nuget.org/api/v2 </span> <br></br> <span className="_code"> nuget Logary.Targets.SumoLogic </span> <p></p> <h3>Want your SaaS-logging service as a Target?</h3> <p>Absolutely! You have two options;</p> <ol type="1"> <p><li>Send a PR with your target that is of equivalent quality as the rest of the code-base, including documentation, code-doc, the C# builder API and a sample in this file. Then keep that code up-to-date when Logary evolves and your SaaS service changes its APIs.</li></p> <p><li>Send me an e-mail and I'll target the target for you. Pricing: a small initial fee and then a monthly maintenance fee, you'll have a beautiful way of getting logs and metrics to your servers!.</li></p> <p>This is by far the easiest option and ensures that your Target is stable and easy to use for your customers. I'll even write some Markdown/HTML-formatted docs for your site about how to use Logary with your target.</p> </ol> </DocSection> </DocPage> ) }
the_stack
import AVLTreeNode from './avl-tree-node' import Stack from '../../sequences/stack' import * as utils from '../../utils' class AVLTree<T> { root: AVLTreeNode<T> | null private sz: number private compare: utils.CompareFunction<T> constructor(compareFunction?: utils.CompareFunction<T>) { this.root = null this.sz = 0 this.compare = compareFunction || utils.defaultCompare } /***************************************************************************** INSPECTION *****************************************************************************/ size(): number { return this.sz } isEmpty(): boolean { return this.size() === 0 } // O(1) height(): number { if (this.root === null) return 0 return this.root.height } /***************************************************************************** SEARCHING *****************************************************************************/ // All search operations can be implemented iteratively and in O(logn) time. // O(logn) because we're just tracing a path down the tree find(value: T): AVLTreeNode<T> | null { let cur = this.root while (cur !== null && cur.value !== value) { if (this.compare(value, cur.value) < 0) cur = cur.left else cur = cur.right } return cur } contains(value: T): boolean { return this.find(value) !== null } // finds the min node in the subtree rooted at given root, or top-most parent by default // O(logn) because we're just tracing a path down the tree findMin(root?: AVLTreeNode<T> | null): AVLTreeNode<T> | null { let cur = root || this.root while (cur && cur.left !== null) { cur = cur.left } return cur } // finds the max node in the subtree rooted at given root, or top-most parent by default // O(logn) because we're just tracing a path down the tree findMax(root?: AVLTreeNode<T> | null): AVLTreeNode<T> | null { let cur = root || this.root while (cur && cur.right !== null) { cur = cur.right } return cur } // O(logn) since we follow a path down the tree or up the tree findSucessor(root: AVLTreeNode<T>): AVLTreeNode<T> | null { // if the right child exists, the successor is the left-most node of the right-child const rightChildExists = root.right !== null if (rightChildExists) return this.findMin(root.right) // otherwise, the successor is the lowest ancestor of the current node whose // left child is also an ancestor of the current node let cur = root let parent = root.parent // Go up the tree from cur until we find a node that is the left child of the parent. // If the node is the right child of the parent that means we haven't crossed // "up and over" to the successor side of the binary tree while (parent !== null && cur === parent.right) { cur = parent parent = parent.parent } return parent } // O(logn) since we follow a path down the tree or up the tree findPredecessor(root: AVLTreeNode<T>): AVLTreeNode<T> | null { // if the left child exists, the successor is the right-most node of the left-child const leftChildExists = root.left !== null if (leftChildExists) return this.findMax(root.left) // otherwise, the successor is the lowest ancestor of the current node whose // right child is also an ancestor of the current node let cur = root let parent = root.parent // Go up the tree from cur until we find a node that is the right child of the parent // If the node is the left child of the parent that means we haven't crossed // "up and over" to the predecessor side of the binary tree while (parent !== null && cur === parent.left) { cur = parent parent = parent.parent } return parent } /***************************************************************************** INSERTION/DELETION *****************************************************************************/ // O(logn) time since we follow a path down the tree insert(value: T): AVLTreeNode<T> | null { if (this.contains(value)) return null this.root = this.insertHelper(this.root, value, null) this.sz += 1 return this.root } private insertHelper( root: AVLTreeNode<T> | null, value: T, parent: AVLTreeNode<T> | null ): AVLTreeNode<T> { if (root === null) return new AVLTreeNode(value, parent) // regular BST insert first const cmp = this.compare(value, root.value) if (cmp < 0) { root.left = this.insertHelper(root.left, value, root) } else { root.right = this.insertHelper(root.right, value, root) } // update balance factor and height values in subtree rooted at node this.update(root) // re-balance tree to satisfy AVL invariant return this.balance(root) } // update node's height and balance factor private update(node: AVLTreeNode<T> | null): void { if (node === null) return const leftNodeHeight = node.left ? node.left.height : 0 const rightNodeHeight = node.right ? node.right.height : 0 node.height = Math.max(leftNodeHeight, rightNodeHeight) + 1 node.balanceFactor = leftNodeHeight - rightNodeHeight this.update(node.parent) } // re-balance a node if balance factor is +2 or -2 private balance(node: AVLTreeNode<T>): AVLTreeNode<T> { // left heavy since balanceFactor = leftChildHeight - rightChildHeight if (node.balanceFactor === 2) { // if left child has left child, we have three nodes forming a line so // perform a right rotation // node.left should be not null bc this method gets called only when node is left heavy ==> node.left is not null if (node.left === null) throw new Error() if (node.left.balanceFactor >= 0) { return this.leftLeftCase(node) } else { // o/w left child has a right child so // 1. left rotate left child so we now have three nodes forming a line // 2. right rotate the root return this.leftRightCase(node) } } else if (node.balanceFactor === -2) { // if right child has right child, we have three nodes forming a line so // perform a left rotation // node.right should be not null bc this method gets called only when node is right heavy ==> node.right is not null if (node.right === null) throw new Error() if (node.right.balanceFactor <= 0) { return this.rightRightCase(node) } else { // o/w right child has left child so // 1. right rotate right child so we now have three nodes forming a line // 2. left rotate the root return this.rightLeftCase(node) } } // o/w, node.balanceFactor is -1, 0, or 1. This is ok. return node } private leftLeftCase(node: AVLTreeNode<T>): AVLTreeNode<T> { return this.rightRotation(node) } private leftRightCase(node: AVLTreeNode<T>): AVLTreeNode<T> { // node.left should be not null bc this method gets called only when node is left heavy ==> node.left is not null if (node.left === null) throw new Error() this.leftRotation(node.left) return this.leftLeftCase(node) } private rightRightCase(node: AVLTreeNode<T>): AVLTreeNode<T> { return this.leftRotation(node) } private rightLeftCase(node: AVLTreeNode<T>): AVLTreeNode<T> { // node.right should be not null bc this method gets called only when node is right heavy ==> node.right is not null if (node.right === null) throw new Error() this.rightRotation(node.right) return this.rightRightCase(node) } private leftRotation(A: AVLTreeNode<T>): AVLTreeNode<T> { const P = A.parent // save A's parent for later const B = A.right if (B === null) throw new Error() A.right = B.left // swing B's predecessors to A since B.left will now be A // set B's predecessors parent to A now if (B.left !== null) B.left.parent = A // set BPredecessor.Parent = A B.left = A // rotate A left // link up parents A.parent = B B.parent = P if (P !== null) { if (P.left === A) P.left = B else P.right = B } // re-update height and balance factor this.update(A) this.update(B) return B } private rightRotation(A: AVLTreeNode<T>): AVLTreeNode<T> { const P = A.parent const B = A.left if (B === null) throw new Error() A.left = B.right // swing B's successors to A since B.right will now be A // if B has a sucessor, set it's new parent to A now if (B.right !== null) B.right.parent = A // set BSuccessor.parent = A B.right = A // rotate A right // link up parents A.parent = B B.parent = P if (P !== null) { if (P.left === A) P.left = B else P.right = B } // re-update height and balance factor this.update(A) this.update(B) return B } // O(logn) because in the worst case we have to find the successor of node. // This means calling this.findMin() which takes O(logn) time remove(node: AVLTreeNode<T>): boolean { if (!this.contains(node.value)) return false this.removeHelper(node) this.sz -= 1 return true } // O(logn) because in the worst case we have to find the successor of node. // This means calling this.findMin() which takes O(logn) time private removeHelper(node: AVLTreeNode<T>): void { // cases: // if node has no children, we simply remove it by modifying node.parent's pointer // if node has one child, we promote the child to take node's place // if node has two chldren, we replace node with node's successor to maintain BST invariant if (node.left === null) { // is node has just a right child, we replace node with it's right child which may // or may not be null this.transplant(node, node.right) } else if (node.right === null) { // if node has just a left child then we replace node with the left child this.transplant(node, node.left) } else { // otherwise node has two children const sucessor = this.findSucessor(node) // O(h) if (node.right === sucessor) { // if node's sucessor is the right child of node, then we replace node with // the sucessor this.transplant(node, sucessor) // link nodes left subtree with sucessor sucessor.left = node.left sucessor.left.parent = sucessor } else { // otherwise, the sucessor lies within node's right subtree but is not // node's immediate right child. then, replace the successor with it's own // right child, and then replace node with the sucessor // note: sucessor can't be null here. node has two children, so it // definitely does have a sucessor if (sucessor === null) throw new Error() // before we transplant node with sucessor, transplant sucessor with IT's // right subtree (sucessor subtree) this.transplant(sucessor, sucessor.right) this.transplant(node, sucessor) // link node's right subtree with sucessor sucessor.right = node.right sucessor.right.parent = sucessor // link node's left subtree with sucessor sucessor.left = node.left sucessor.left.parent = sucessor } } this.update(node) this.balance(node) } // Replaces the subtree rooted at u with the subtree rooted at v. Node u's // parent now becomes node v's parent. Note that transplant does not update // v.left or v.right private transplant(u: AVLTreeNode<T>, v: AVLTreeNode<T> | null) { if (u.parent === null) { // then u is the root of the tree so set root pointer to point to v this.root = v } else if (u === u.parent.left) { u.parent.left = v } else { u.parent.right = v } // set v's parent pointer to point to u's parent if (v) v.parent = u.parent } /***************************************************************************** READING *****************************************************************************/ inorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack = new Stack<AVLTreeNode<T>>() return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { // dig left while (root !== null) { stack.push(root) root = root.left } // we're done exploring the left branch if (stack.isEmpty()) { // if stack is empty, we have no more nodes to process return { value: null, done: true } } root = stack.pop()! // root is not null bc stack is not empty const value = root.value root = root.right return { value, done: false, } }, }), } } preorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack = new Stack<AVLTreeNode<T>>() if (root !== null) stack.push(root) return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { if (stack.isEmpty()) return { value: null, done: true } root = stack.pop()! // root is non-null bc stack is not empty const value = root.value if (root.right !== null) stack.push(root.right) if (root.left !== null) stack.push(root.left) return { value, done: false, } }, }), } } postorderTraversal(): { [Symbol.iterator](): Iterator<T> } { let root = this.root const stack1 = new Stack<AVLTreeNode<T>>() const stack2 = new Stack<AVLTreeNode<T>>() if (root !== null) stack1.push(root) while (!stack1.isEmpty()) { root = stack1.pop()! // non-null bc stack1 is not empty stack2.push(root) if (root.left !== null) stack1.push(root.left) if (root.right !== null) stack1.push(root.right) } return { [Symbol.iterator]: (): Iterator<T> => ({ next(): IteratorResult<T> { if (stack2.isEmpty()) return { value: null, done: true } const { value } = stack2.pop()! // non-null bc stack2 is not empty return { value, done: false, } }, }), } } } export default AVLTree
the_stack
import { Container } from '../../src/dependecy-injection/di.container'; import { DiService } from '../../src/dependecy-injection/di.service'; import { BeforeTests, Test, TestService } from '../../src/test/test.decorators'; import { AsserterService } from '../../src/test/test.shared'; import { Di1Example } from './examples/di1.example'; import { Di10Example } from './examples/di10.example'; import { Di11Example } from './examples/di11.example'; import { Di12Example } from './examples/di12.example'; import { Di13Example } from './examples/di13.example'; import { Di14Example } from './examples/di14.example'; import { Di15Example } from './examples/di15.example'; import { Di16Example } from './examples/di16.example'; import { Di17Example } from './examples/di17.example'; import { Di18Example } from './examples/di18.example'; import { Di19Example } from './examples/di19.example'; import { Di2Example } from './examples/di2.example'; import { Di3Example } from './examples/di3.example'; import { Di4Example } from './examples/di4.example'; import { Di5Example } from './examples/di5.example'; import { Di6Example } from './examples/di6.example'; import { Di7Example } from './examples/di7.example.ctx'; import { Di8Example } from './examples/di8.example.ctx'; import { Di9Example } from './examples/di9.example.ctx'; import { Di20Example } from './examples/di20.example'; import { Di21Example } from './examples/di21.example'; import { Di22Example } from './examples/di22.example'; @TestService() export class DiContainerTest extends AsserterService { private example1: Di1Example; private example2: Di2Example; private example3: Di3Example; private example4: Di4Example; private example5: Di5Example; private example6: Di6Example; private example7: Di7Example; private example8: Di8Example; private example9: Di9Example; private example10: Di10Example; private example11: Di11Example; private example12: Di12Example; private example13: Di13Example; private example14: Di14Example; private example15: Di15Example; private example16: Di16Example; private example17: Di17Example; private example18: Di18Example; private example19: Di19Example; private example20: Di20Example; private example21: Di21Example; private example22: Di22Example; @BeforeTests() public async beforeStart() { this.example6 = new Di6Example(); Container.set(Di6Example, this.example6, 'service6'); // Primitive dependencies Container.set(String, 'stringExample', 'stringExample'); Container.set(Number, 123, 'numberExample'); Container.set(Boolean, true, 'booleanExample'); const values1: any[] = await Promise.all([ // Typescript 1.7 bug with array types Container.get(Di1Example), Container.get(Di2Example), Container.get(Di3Example), Container.get(Di4Example), Container.get(Di5Example), Container.get(Di7Example, undefined, 'exampleCtx'), Container.getFromContext(Di8Example, 'exampleCtx'), Container.getFromContext(Di9Example, 'exampleCtx'), Container.get(Di10Example, { variationVar: '3' }), Container.get(Di11Example), ]); // Too many antries for just 1 Promise.all() const values2 = await Promise.all([ Container.get(Di12Example, { connection: 'testConnection' }), Container.get(Di13Example, { connection: 'testConnection' }), Container.get(Di14Example), Container.get(Di15Example), Container.get(Di16Example), Container.get(Di17Example), Container.get(Di18Example), Container.get(Di19Example) ]); // Too many antries for just 1 Promise.all() const values3 = await Promise.all([ Container.get(Di20Example), Container.get(Di21Example), Container.get(Di22Example) ]); this.example1 = values1[0]; this.example2 = values1[1]; this.example3 = values1[2]; this.example4 = values1[3]; this.example5 = values1[4]; this.example7 = values1[5]; this.example8 = values1[6]; this.example9 = values1[7]; this.example10 = values1[8]; this.example11 = values1[9]; this.example12 = values2[0]; this.example13 = values2[1]; this.example14 = values2[2]; this.example15 = values2[3]; this.example16 = values2[4]; this.example17 = values2[5]; this.example18 = values2[6]; this.example19 = values2[7]; this.example20 = values3[0]; this.example21 = values3[1]; this.example22 = values3[2]; } @Test() public serviceWithInject() { this.assert.ok(this.example1.getExample2()); this.assert.equal(this.example1.timesOnInitCalled, 1); } @Test() public serviceWithIDiOnInit() { this.assert.equal(this.example2.timesOnInitCalled, 1); } @Test() public serviceWith2Injects() { this.assert.ok(this.example3.getExample1()); this.assert.ok(this.example3.getExample2()); this.assert.equal(this.example3.timesOnInitCalled, 1); } @Test() public serviceWithConstructorDependencies() { this.assert.equal(this.example4.timesConstructorCalled, 1); } @Test() public serviceWithCustomSId() { this.assert.ok(this.example5.getExample1()); this.assert.ok(this.example5.getExample2()); this.assert.ok(this.example5.getExample6()); this.assert.equal(this.example5.timesConstructorCalled, 1); this.assert.equal(this.example5.timesOnInitCalled, 1); } @Test() public serviceForCustomCtx() { this.assert.equal(this.example7.timesOnInitCalled, 1); } @Test() public serviceForCustomCtxInjectinAnotherServiceFromSameCtx() { this.assert.equal(this.example8.timesConstructorCalled, 1); this.assert.ok(this.example8.di7Example); } @Test() public serviceForCustomCtxWithReferencesOtherCtxs() { this.assert.equal(this.example9.timesConstructorCalled, 1); this.assert.ok(this.example9.di1Example); this.assert.ok(this.example9.di1Example); this.assert.ok(this.example9.di8Example); this.assert.ok(!DiService.getMetadata(Di9Example)); DiService.updateMetadata(Di9Example, { test: 'test' }); DiService.updateMetadata(Di9Example, { test2: 'test2' }, true); this.assert.equal(DiService.getMetadata(Di9Example).test, 'test'); this.assert.equal(DiService.getMetadata(Di9Example).test2, 'test2'); } @Test() public serviceWithVariationVar() { this.assert.equal(this.example10.timesConstructorCalled, 1); this.assert.ok(this.example10.getExample1()); this.assert.ok(this.example10.getExample3()); this.assert.equal(this.example10.getVariationVar(), '3'); } @Test() public serviceWithVariation() { this.assert.equal(this.example11.timesConstructorCalled, 1); this.assert.ok(this.example11.getD10example1()); this.assert.ok(this.example11.getD10example2()); this.assert.equal(this.example11.getD10example1().getVariationVar(), '1'); this.assert.equal(this.example11.getD10example2().getVariationVar(), '2'); this.assert.ok(this.example11.getD10example1().getExample1()); this.assert.ok(this.example11.getD10example1().getExample3()); this.assert.ok(this.example11.getD10example2().getExample1()); this.assert.ok(this.example11.getD10example2().getExample3()); } @Test() public servicesWithInjectedConnections() { this.assert.equal(this.example12.timesConstructorCalled, 1); this.assert.equal(this.example13.timesConstructorCalled, 1); this.assert.equal(this.example14.timesConstructorCalled, 1); this.assert.equal(this.example12.getConnection(), 'testConnection'); this.assert.ok(this.example12.getDi1Example()); this.assert.equal(this.example13.getConnection(), 'testConnection'); this.assert.ok(this.example14.getDi12Example()); this.assert.ok(this.example14.getDi13Example()); } @Test() public servicesWithOptionalConnections() { // Without value this.assert.equal(this.example18.getDi15Example().getConnection(), undefined); this.assert.equal(this.example18.getDi16Example().getConnection(), undefined); // With value this.assert.equal(this.example19.getDi15Example().getConnection(), 'testConnection'); this.assert.equal(this.example19.getDi16Example().getConnection(), 'testConnection'); } @Test() public servicesWithOptionalVariations() { // Without value this.assert.equal(this.example18.getDi17Example().getOptionalVariationNumber(), undefined); this.assert.equal(this.example18.getDi17Example().getOptionalVariationString(), undefined); // With value this.assert.equal(this.example19.getDi17Example1().getOptionalVariationNumber(), 11); this.assert.equal(this.example19.getDi17Example1().getOptionalVariationString(), 'stringtest1'); this.assert.equal(this.example19.getDi17Example2().getOptionalVariationNumber(), 22); this.assert.equal(this.example19.getDi17Example2().getOptionalVariationString(), 'stringtest2'); } @Test() public servicesWithPartialOptionalVariations() { this.assert.equal(this.example19.getDi17Example3().getOptionalVariationNumber(), undefined); this.assert.equal(this.example19.getDi17Example3().getOptionalVariationString(), 'stringtest3'); this.assert.equal(this.example19.getDi17Example4().getOptionalVariationNumber(), 44); this.assert.equal(this.example19.getDi17Example4().getOptionalVariationString(), undefined); } @Test() public servicesWithPrimitiveTypeDependencies() { this.assert.equal(this.example15.getStringExample(), 'stringExample'); this.assert.equal(this.example18.getDi15Example().getStringExample(), 'stringExample'); this.assert.equal(this.example19.getDi15Example().getStringExample(), 'stringExample'); this.assert.equal(this.example16.getNumberExample(), 123); this.assert.equal(this.example18.getDi16Example().getNumberExample(), 123); this.assert.equal(this.example19.getDi16Example().getNumberExample(), 123); this.assert.equal(this.example17.getBooleanExample(), true); this.assert.equal(this.example18.getDi17Example().getBooleanExample(), true); this.assert.equal(this.example19.getDi17Example1().getBooleanExample(), true); this.assert.equal(this.example19.getDi17Example2().getBooleanExample(), true); this.assert.equal(this.example19.getDi17Example3().getBooleanExample(), true); this.assert.equal(this.example19.getDi17Example4().getBooleanExample(), true); } @Test() public mixBetweenConnectionAndOptionalVariationVars() { this.assert.equal(this.example20.getVarProp(), undefined); this.assert.equal(this.example20.getVarConstructor(), undefined); this.assert.equal(this.example20.getVarConstructorConnection(), undefined); this.assert.equal(this.example21.getDi20Example1().getVarProp(), 'varProp'); this.assert.equal(this.example21.getDi20Example1().getVarConstructor(), 'varConstructor'); this.assert.equal(this.example21.getDi20Example1().getVarConstructorConnection(), 'testConnection'); this.assert.equal(this.example21.getDi20Example2().getVarProp(), undefined); this.assert.equal(this.example21.getDi20Example2().getVarConstructor(), 'varConstructor'); this.assert.equal(this.example21.getDi20Example2().getVarConstructorConnection(), 'testConnection'); this.assert.equal(this.example21.getDi20Example3().getVarProp(), 'varProp'); this.assert.equal(this.example21.getDi20Example3().getVarConstructor(), undefined); this.assert.equal(this.example21.getDi20Example3().getVarConstructorConnection(), 'testConnection'); this.assert.equal(this.example21.getDi20Example4().getVarProp(), undefined); this.assert.equal(this.example21.getDi20Example4().getVarConstructor(), undefined); this.assert.equal(this.example21.getDi20Example4().getVarConstructorConnection(), 'testConnection'); this.assert.equal(this.example22.getDi20Example1().getVarProp(), 'varProp'); this.assert.equal(this.example22.getDi20Example1().getVarConstructor(), 'varConstructor'); this.assert.equal(this.example22.getDi20Example1().getVarConstructorConnection(), undefined); this.assert.equal(this.example22.getDi20Example2().getVarProp(), undefined); this.assert.equal(this.example22.getDi20Example2().getVarConstructor(), 'varConstructor'); this.assert.equal(this.example22.getDi20Example2().getVarConstructorConnection(), undefined); this.assert.equal(this.example22.getDi20Example3().getVarProp(), 'varProp'); this.assert.equal(this.example22.getDi20Example3().getVarConstructor(), undefined); this.assert.equal(this.example22.getDi20Example3().getVarConstructorConnection(), undefined); this.assert.equal(this.example22.getDi20Example4().getVarProp(), undefined); this.assert.equal(this.example22.getDi20Example4().getVarConstructor(), undefined); this.assert.equal(this.example22.getDi20Example4().getVarConstructorConnection(), undefined); } }
the_stack
import LRU from 'lru-cache' import superagent from 'superagent' import { UserBuyMenu } from 'user/userbuymenu' import { UserCosmetics } from 'user/usercosmetics' import { UserInventoryItem } from 'user/userinventoryitem' import { UserLoadout } from 'user/userloadout' import { userSvcAuthority, UserSvcPing } from 'authorities' export class UserInventory { /** * creates a new inventory, including cosmetics, loadouts and a buy menu * @param userId the new inventory owner's user ID * @returns true if successful, false if not */ public static async create(userId: number): Promise<boolean> { if (UserSvcPing.isAlive() === false) { return false } const invPromises: Promise<boolean>[] = [ UserInventory.createInventory(userId), UserInventory.createCosmetics(userId), UserInventory.createBuyMenu(userId), UserInventory.createLoadouts(userId) ] const results: boolean[] = await Promise.all(invPromises) // if results.includes returns false, then results doesn't have any false value return results.includes(false) !== false } /** * create inventory items for the owner user * @param ownerId the future inventory owner's user ID * @returns true if successful, false if not */ public static async createInventory(ownerId: number): Promise<boolean> { try { const res: superagent.Response = await superagent .post(`${userSvcAuthority()}/inventory/${ownerId}`) .accept('json') return res.status === 201 } catch (error) { console.error(error) await UserSvcPing.checkNow() return false } } /** * create cosmetic slots for the owner user * @param ownerId the future cosmetics owner's user ID * @returns true if successful, false if not */ public static async createCosmetics(ownerId: number): Promise<boolean> { try { const res: superagent.Response = await superagent .post(`${userSvcAuthority()}/inventory/${ownerId}/cosmetics`) .accept('json') return res.status === 201 } catch (error) { console.error(error) await UserSvcPing.checkNow() return false } } /** * create loadouts for the owner user * @param ownerId the future loadouts owner's user ID * @returns true if successful, false if not */ public static async createLoadouts(ownerId: number): Promise<boolean> { try { const res: superagent.Response = await superagent .post(`${userSvcAuthority()}/inventory/${ownerId}/loadout`) .accept('json') return res.status === 201 } catch (error) { console.error(error) await UserSvcPing.checkNow() return false } } /** * create buy menu for the owner user * @param ownerId the future buy menu owner's user ID * @returns true if successful, false if not */ public static async createBuyMenu(ownerId: number): Promise<boolean> { try { const res: superagent.Response = await superagent .post(`${userSvcAuthority()}/inventory/${ownerId}/buymenu`) .accept('json') return res.status === 201 } catch (error) { console.error(error) await UserSvcPing.checkNow() return null } } /** * get the inventory owner's items * @param ownerId the inventory owner's user ID */ public static async getInventory(ownerId: number): Promise<UserInventory> { try { const inventory: UserInventory = inventoryCache.get(ownerId) if (inventory != null) { return inventory } if (UserSvcPing.isAlive() === false) { return null } const res: superagent.Response = await superagent .get(`${userSvcAuthority()}/inventory/${ownerId}`) .accept('json') if (res.status === 200) { inventoryCache.set(ownerId, res.body) return res.body as UserInventory } return null } catch (error) { console.error(error) await UserSvcPing.checkNow() return null } } /** * get an user's cosmetic items * @param ownerId the cosmetics owner's user ID */ public static async getCosmetics(ownerId: number): Promise<UserCosmetics> { try { const cosmetics: UserCosmetics = cosmeticsCache.get(ownerId) if (cosmetics != null) { return cosmetics } if (UserSvcPing.isAlive() === false) { return null } const res: superagent.Response = await superagent .get(`${userSvcAuthority()}/inventory/${ownerId}/cosmetics`) .accept('json') if (res.status === 200) { cosmeticsCache.set(ownerId, res.body) return res.body as UserCosmetics } return null } catch (error) { console.error(error) await UserSvcPing.checkNow() return null } } /** * get an user's loadout * @param ownerId the loadout owner's user ID * @param loadoutNum the loadout's index number */ public static async getLoadout( ownerId: number, loadoutNum: number ): Promise<UserLoadout> { try { const res: superagent.Response = await superagent .get( userSvcAuthority() + `/inventory/${ownerId}/loadout/${loadoutNum}` ) .send() .accept('json') if (res.ok !== true) { return null } return res.body as UserLoadout } catch (error) { console.error(error) await UserSvcPing.checkNow() return null } } /** * get every loadout from an user * @param ownerId the loadouts owner's user ID */ public static async getAllLoadouts( ownerId: number ): Promise<UserLoadout[]> { let loadouts: UserLoadout[] = loadoutsCache.get(ownerId) if (loadouts != null) { return loadouts } if (UserSvcPing.isAlive() === false) { return null } const loadoutPromises: Promise<UserLoadout>[] = [] for (let i = 0; i < 3; i++) { loadoutPromises.push(UserInventory.getLoadout(ownerId, i)) } loadouts = await Promise.all(loadoutPromises) loadoutsCache.set(ownerId, loadouts) return loadouts } /** * get an user's buy menu * @param ownerId the buy menu owner's user ID */ public static async getBuyMenu(ownerId: number): Promise<UserBuyMenu> { try { const buymenu: UserBuyMenu = buymenuCache.get(ownerId) if (buymenu != null) { return buymenu } if (UserSvcPing.isAlive() === false) { return null } const res: superagent.Response = await superagent .get(`${userSvcAuthority()}/inventory/${ownerId}/buymenu`) .accept('json') if (res.status === 200) { buymenuCache.set(ownerId, res.body) return res.body as UserBuyMenu } return null } catch (error) { console.error(error) await UserSvcPing.checkNow() return null } } /** * sets an user's cosmetic slot with a new item * @param ownerId the cosmetics owner's user ID * @param slot the cosmetic slot * @param itemId the new cosmetic's item ID */ public static async setCosmeticSlot( ownerId: number, slot: number, itemId: number ): Promise<void> { const params = UserInventory.buildSetCosmeticParams(slot, itemId) try { const res: superagent.Response = await superagent .put(`${userSvcAuthority()}/inventory/${ownerId}/cosmetics`) .send(params) .accept('json') if (res.status === 200) { cosmeticsCache.del(ownerId) console.log('Set cosmetic item successfully') } } catch (error) { console.error(error) await UserSvcPing.checkNow() } } /** * sets a loadout's weapon slot with a different we * @param ownerId the loadout owner's user ID * @param loadout the loadout number * @param slot the weapon slot * @param itemId the new weapon's item id */ public static async setLoadoutWeapon( ownerId: number, loadout: number, slot: number, itemId: number ): Promise<void> { const params = UserInventory.buildSetLoadoutParams(slot, itemId) try { const res: superagent.Response = await superagent .put( `${userSvcAuthority()}/inventory/${ownerId}/loadout/${loadout}` ) .send(params) .accept('json') if (res.status === 200) { loadoutsCache.del(ownerId) console.log('Set loadout weapon successfully') } } catch (error) { console.error(error) await UserSvcPing.checkNow() } } /** * sets an user's whole buy menu * @param ownerId the buy menu owner's user ID * @param column the buy menu's column index * @param items the new buy menu's column items */ public static async setBuyMenu( ownerId: number, newBuyMenu: UserBuyMenu ): Promise<void> { try { const res: superagent.Response = await superagent .put(`${userSvcAuthority()}/inventory/${ownerId}/buymenu`) .send(newBuyMenu) .accept('json') if (res.status === 200) { buymenuCache.del(ownerId) console.log('Set buy menu successfully') } } catch (error) { console.error(error) await UserSvcPing.checkNow() } } /** * sets an user's buy menu column (such as the pistols column) * @param ownerId the buy menu owner's user ID * @param column the buy menu's column index * @param items the new buy menu's column items */ public static async setBuyMenuColumn( ownerId: number, column: number, items: number[] ): Promise<void> { const params = UserInventory.buildSetBuyMenuParams(column, items) try { const res: superagent.Response = await superagent .put(`${userSvcAuthority()}/inventory/${ownerId}/buymenu`) .send(params) .accept('json') if (res.status === 200) { buymenuCache.del(ownerId) console.log('Set buy menu column successfully') } } catch (error) { console.error(error) await UserSvcPing.checkNow() } } private static buildSetCosmeticParams(slot: number, itemId: number) { switch (slot) { case 0: return { ct_item: itemId } case 1: return { ter_item: itemId } case 2: return { head_item: itemId } case 3: return { glove_item: itemId } case 4: return { back_item: itemId } case 5: return { steps_item: itemId } case 6: return { card_item: itemId } case 7: return { spray_item: itemId } } console.error('Bad item slot for cosmetics') return null } private static buildSetLoadoutParams(slot: number, itemId: number) { switch (slot) { case 0: return { primary_weapon: itemId } case 1: return { secondary_weapon: itemId } case 2: return { melee: itemId } case 3: return { hegrenade: itemId } case 4: return { smoke: itemId } case 5: return { flash: itemId } } console.error('Bad item slot for loadout') return null } private static buildSetBuyMenuParams(slot: number, items: number[]) { switch (slot) { case 0: return { pistols: items } case 1: return { shotguns: items } case 2: return { smgs: items } case 3: return { rifles: items } case 4: return { snipers: items } case 5: return { machineguns: items } case 6: return { melees: items } case 7: return { equipment: items } } console.error('Bad column for buy menu') return null } public owner_id: number public items: UserInventoryItem[] } const inventoryCache = new LRU<number, UserInventory>({ max: 15, maxAge: 1000 * 15 }) const cosmeticsCache = new LRU<number, UserCosmetics>({ max: 30, maxAge: 1000 * 15 }) const loadoutsCache = new LRU<number, UserLoadout[]>({ max: 30, maxAge: 1000 * 15 }) const buymenuCache = new LRU<number, UserBuyMenu>({ max: 30, maxAge: 1000 * 15 })
the_stack
(function style_init() { "use strict"; const sparser:sparser = global.sparser, style = function lexer_style(source:string):data { let a:number = 0, ltype:string = "", ltoke:string = ""; const parse:parse = sparser.parse, data:data = parse.data, options:any = sparser.options, colors:string[] = [], colorNames = { aliceblue : 0.9288006825347457, antiquewhite : 0.8464695170775405, aqua : 0.7874, aquamarine : 0.8078549208338043, azure : 0.9726526495416643, beige : 0.8988459998705021, bisque : 0.8073232737297876, black : 0, blanchedalmond : 0.8508443960815607, blue : 0.0722, blueviolet : 0.12622014321946043, brown : 0.09822428787651079, burlywood : 0.5155984453389335, cadetblue : 0.29424681085422044, chartreuse : 0.7603202590262282, chocolate : 0.23898526114557292, coral : 0.3701793087292368, cornflowerblue : 0.30318641994179363, cornsilk : 0.9356211037296492, crimson : 0.16042199953025577, cyan : 0.7874, darkblue : 0.018640801980939217, darkcyan : 0.2032931783904645, darkgoldenrod : 0.27264703559992554, darkgray : 0.39675523072562674, darkgreen : 0.09114342904757505, darkgrey : 0.39675523072562674, darkkhaki : 0.45747326349994155, darkmagenta : 0.07353047651207048, darkolivegreen : 0.12651920884889156, darkorange : 0.40016167026523863, darkorchid : 0.1341314217485677, darkred : 0.05488967453113126, darksalmon : 0.4054147156338075, darkseagreen : 0.43789249325969054, darkslateblue : 0.06579284622798763, darkslategray : 0.06760815192804355, darkslategrey : 0.06760815192804355, darkturquoise : 0.4874606277449034, darkviolet : 0.10999048339343433, deeppink : 0.2386689582827583, deepskyblue : 0.444816033955754, dimgray : 0.14126329114027164, dimgrey : 0.14126329114027164, dodgerblue : 0.2744253699145608, firebrick : 0.10724525535015225, floralwhite : 0.9592248482500424, forestgreen : 0.18920812076002244, fuchsia : 0.2848, gainsboro : 0.7156935005064806, ghostwhite : 0.9431126188632283, gold : 0.6986087742815887, goldenrod : 0.41919977809568404, gray : 0.21586050011389915, green : 0.15438342968146068, greenyellow : 0.8060947261145331, grey : 0.21586050011389915, honeydew : 0.9633653555478173, hotpink : 0.3465843816971475, indianred : 0.21406134963884, indigo : 0.031075614863369846, ivory : 0.9907127060061531, khaki : 0.7701234339412052, lavendar : 0.8031875051452125, lavendarblush : 0.9017274863104644, lawngreen : 0.7390589312496334, lemonchiffon : 0.9403899224562171, lightblue : 0.6370914128080659, lightcoral : 0.35522120733134843, lightcyan : 0.9458729349482863, lightgoldenrodyellow: 0.9334835101829635, lightgray : 0.651405637419824, lightgreen : 0.6909197995686475, lightgrey : 0.651405637419824, lightpink : 0.5856615273489745, lightsalmon : 0.47806752252059587, lightseagreen : 0.3505014511704197, lightskyblue : 0.5619563761833096, lightslategray : 0.23830165007286924, lightslategrey : 0.23830165007286924, lightyellow : 0.9816181839288161, lime : 0.7152, limegreen : 0.44571042246097864, linen : 0.8835734098437936, magenta : 0.2848, maroon : 0.04589194232421496, mediumaquamarine : 0.4938970331080111, mediumblue : 0.04407778021232784, mediumorchid : 0.21639251153773428, mediumpurple : 0.22905858091648004, mediumseagreen : 0.34393112338131226, mediumslateblue : 0.20284629471622434, mediumspringgreen : 0.7070430819418444, mediumturquois : 0.5133827926447991, mediumvioletred : 0.14371899849357186, midnightblue : 0.020717866350860484, mintcream : 0.9783460494758793, mistyrose : 0.8218304785918541, moccasin : 0.8008300099156694, navajowhite : 0.7651968234278562, navy : 0.015585128108223519, oldlace : 0.9190063340554899, olive : 0.20027537200567563, olivedrab : 0.2259315095192918, orange : 0.48170267036309605, orangered : 0.2551624375341641, orchid : 0.3134880676143873, palegoldenrod : 0.7879264788761452, palegreen : 0.7793675900635259, paleturquoise : 0.764360779217138, palevioletred : 0.2875499411788909, papayawhip : 0.8779710019983541, peachpuff : 0.7490558987825108, peru : 0.3011307487793569, pink : 0.6327107070246611, plum : 0.4573422158796909, powderblue : 0.6825458650060524, purple : 0.061477070432438476, red : 0.2126, rosyblue : 0.3231945764940708, royalblue : 0.16663210743188323, saddlebrown : 0.09792228502052071, salmon : 0.3697724152759545, sandybrown : 0.46628543696283414, seagreen : 0.1973419970627483, seashell : 0.927378622069223, sienna : 0.13697631337097677, silver : 0.527115125705813, skyblue : 0.5529166851818412, slateblue : 0.14784278062136097, slategray : 0.20896704076536138, slategrey : 0.20896704076536138, slightsteelblue : 0.5398388828466575, snow : 0.9653334183484877, springgreen : 0.7305230606852947, steelblue : 0.20562642207624846, tan : 0.48237604163921527, teal : 0.1699685577896842, thistle : 0.5681840109373312, tomato : 0.3063861271941505, turquoise : 0.5895536427577983, violet : 0.40315452986676303, wheat : 0.7490970282048214, white : 1, whitesmoke : 0.913098651793419, yellow : 0.9278, yellowgreen : 0.5076295720870697 }, b:string[] = source.split(""), len:number = source.length, mapper:number[] = [], nosort:boolean[] = [], recordPush = function lexer_style_recordPush(structure:string):void { const record = { begin: parse.structure[parse.structure.length - 1][1], ender: -1, lexer: "style", lines: parse.linesSpace, stack: parse.structure[parse.structure.length - 1][0], token: ltoke, types: ltype }; parse.push(data, record, structure); }, esctest = function lexer_style_esctest(index:number):boolean { const slashy:number = index; do { index = index - 1; } while (b[index] === "\\" && index > 0); if ((slashy - index) % 2 === 1) { return true; } return false; }, // Since I am already identifying value types this is a good place to do some // quick analysis and clean up on certain value conditions. These things are // being corrected: // * fractional values missing a leading 0 are provided a leading 0 // * 0 values with a dimension indicator (px, em) have the dimension // indicator removed // * eliminate unnecessary leading 0s // * url values that are not quoted are wrapped in double quote characters // * color values are set to lowercase and reduced from 6 to 3 digits if // appropriate value = function lexer_style_value(val:string):string { const x:string[] = val.replace(/\s*!important/, " !important").split(""), values:string[] = [], transition:boolean = (/-?transition$/).test(data.token[parse.count - 2]), colorPush = function lexer_style_value_colorPush(value:string):string { const vl = value.toLowerCase(); if ((/^(#[0-9a-f]{3,6})$/).test(vl) === true) { colors.push(value); } else if ((/^(rgba?\()/).test(vl) === true) { colors.push(value); } else if (colorNames[vl] !== undefined) { colors.push(value); } return value; }, valueSpace = function lexer_style_value_valueSpace(find:string) { find = find.replace(/\s*/g, ""); if ((/\/\d/).test(find) === true && val.indexOf("url(") === 0) { return find; } return ` ${find.charAt(0)} ${find.charAt(1)}`; }, zerofix = function lexer_style_value_zerofix(find:string):string { if (options.lexer_options.style.no_lead_zero === true) { const scrub = function lexer_style_value_zerofix_scrub(search:string) { return search.replace(/0+/, ""); }; return find.replace(/^-?\D0+(\.|\d)/, scrub); } if ((/0*\./).test(find) === true) { return find.replace(/0*\./, "0."); } if ((/0+/).test((/\d+/).exec(find)[0]) === true) { if ((/^\D*0+\D*$/).test(find) === true) { return find.replace(/0+/, "0"); } return find.replace((/\d+/).exec(find)[0], (/\d+/).exec(find)[0].replace(/^0+/, "")); } return find; }, commaspace = function lexer_style_value_commaspace(find:string):string { return find.replace(",", ", "); }, diFix = function lexer_style_value_diFix(di:string):string { return `${di} `; }, slash = function lexer_style_value_slash():boolean { const start:number = cc - 1; let xx:number = start; if (start < 1) { return true; } do { xx = xx - 1; } while (xx > 0 && x[xx] === "\\"); // report true for odd numbers (escaped) if ((start - xx) % 2 === 1) { return true; } return false; }, zerodotstart:RegExp = (/^-?0+\.\d+[a-z]/), dotstart:RegExp = (/^-?\.\d+[a-z]/), zerodot:RegExp = (/(\s|\(|,)-?0+\.?\d+([a-z]|\)|,|\s)/g), dot:RegExp = (/(\s|\(|,)-?\.?\d+([a-z]|\)|,|\s)/g), dimensions:string = "%|cap|ch|cm|deg|dpcm|dpi|dppx|em|ex|fr|grad|Hz|ic|in|kHz|lh|mm|ms|mS|pc|pt|px|Q|rad|rem|rlh|s|turn|vb|vh|vi|vmax|vmin|vw"; let cc:number = 0, dd:number = 0, block:string = "", leng:number = x.length, items:string[] = []; // this loop identifies containment so that tokens/sub-tokens are correctly // taken if (cc < leng) { do { items.push(x[cc]); if (x[cc - 1] !== "\\" || slash() === false) { if (block === "") { if (x[cc] === "\"") { block = "\""; dd = dd + 1; } else if (x[cc] === "'") { block = "'"; dd = dd + 1; } else if (x[cc] === "(") { block = ")"; dd = dd + 1; } else if (x[cc] === "[") { block = "]"; dd = dd + 1; } } else if ((x[cc] === "(" && block === ")") || (x[cc] === "[" && block === "]")) { dd = dd + 1; } else if (x[cc] === block) { dd = dd - 1; if (dd === 0) { block = ""; } } } if (block === "" && x[cc] === " ") { items.pop(); values.push(colorPush(items.join(""))); items = []; } cc = cc + 1; } while (cc < leng); } values.push(colorPush(items.join(""))); leng = values.length; //This is where the rules mentioned above are applied cc = 0; if (cc < leng) { do { if (options.lexer_options.style.no_lead_zero === true && zerodotstart.test(values[cc]) === true) { values[cc] = values[cc].replace(/0+\./, "."); } else if ((options.lexer_options.style.no_lead_zero === false || options.lexer_options.style.no_lead_zero === undefined) && dotstart.test(values[cc]) === true) { values[cc] = values[cc].replace(".", "0."); } else if (zerodot.test(values[cc]) === true || dot.test(values[cc]) === true) { values[cc] = values[cc].replace(zerodot, zerofix).replace(dot, zerofix); } else if ((/^(0+([a-z]{2,3}|%))$/).test(values[cc]) === true && transition === false) { values[cc] = "0"; } else if ((/^(0+)/).test(values[cc]) === true) { values[cc] = values[cc].replace(/0+/, "0"); if ((/\d/).test(values[cc].charAt(1)) === true) { values[cc] = values[cc].substr(1); } } else if ((/^url\((?!('|"))/).test(values[cc]) === true && values[cc].charAt(values[cc].length - 1) === ")") { block = values[cc].charAt(values[cc].indexOf("url(") + 4); if (block !== "@" && block !== "{" && block !== "<") { if (options.lexer_options.style.quote_convert === "double") { values[cc] = values[cc] .replace(/url\(/, "url(\"") .replace(/\)$/, "\")"); } else { values[cc] = values[cc] .replace(/url\(/, "url('") .replace(/\)$/, "')"); } } } if ((/^(\+|-)?\d+(\.\d+)?(e-?\d+)?\D+$/).test(values[cc]) === true) { if (dimensions.indexOf(values[cc].replace(/(\+|-)?\d+(\.\d+)?(e-?\d+)?/, "")) < 0) { values[cc] = values[cc].replace(/(\+|-)?\d+(\.\d+)?(e-?\d+)?/, diFix); } } if ( (/^\w+\(/).test(values[cc]) === true && values[cc].charAt(values[cc].length - 1) === ")" && (values[cc].indexOf("url(") !== 0 || (values[cc].indexOf("url(") === 0 && values[cc].indexOf(" ") > 0)) ) { values[cc] = values[cc].replace(/,\S/g, commaspace); } cc = cc + 1; } while (cc < leng); } block = values.join(" "); return block.charAt(0) + block.slice(1) .replace(/\s*(\/|\+|\*)\s*(\d|\$)/, valueSpace); }, //the generic token builder buildtoken = function lexer_style_build():void { let aa:number = a, bb:number = 0, out:string[] = [], outy:string = "", funk:boolean = null, mappy:number = 0; const block:string[] = [], qc:"none"|"double"|"single" = (options.lexer_options.style.quote_convert === undefined) ? "none" : options.lexer_options.style.quote_convert, spacestart = function lexer_style_build_spacestart():void { out.push(b[aa]); if ((/\s/).test(b[aa + 1]) === true) { do { aa = aa + 1; } while (aa < len && (/\s/).test(b[aa + 1]) === true); } }; if (aa < len) { //this loop accounts for grouping mechanisms do { if (b[aa] === "\"" || b[aa] === "'") { if (funk === null) { funk = false; } if (block[block.length - 1] === b[aa] && (b[aa - 1] !== "\\" || esctest(aa - 1) === false)) { block.pop(); if (qc === "double") { b[aa] = "\""; } else if (qc === "single") { b[aa] = "'"; } } else if (block[block.length - 1] !== "\"" && block[block.length - 1] !== "'" && (b[aa - 1] !== "\\" || esctest(aa - 1) === false)) { block.push(b[aa]); if (qc === "double") { b[aa] = "\""; } else if (qc === "single") { b[aa] = "'"; } } else if (b[aa - 1] === "\\" && qc !== "none") { if (esctest(aa - 1) === true) { if (qc === "double" && b[aa] === "'") { out.pop(); } else if (qc === "single" && b[aa] === "\"") { out.pop(); } } } else if (qc === "double" && b[aa] === "\"") { b[aa] = "\\\""; } else if (qc === "single" && b[aa] === "'") { b[aa] = "\\'"; } out.push(b[aa]); } else if (b[aa - 1] !== "\\" || esctest(aa - 1) === false) { if (b[aa] === "(") { if (funk === null) { funk = true; } mappy = mappy + 1; block.push(")"); spacestart(); } else if (b[aa] === "[") { funk = false; block.push("]"); spacestart(); } else if ((b[aa] === "#" || b[aa] === "@") && b[aa + 1] === "{") { funk = false; out.push(b[aa]); aa = aa + 1; block.push("}"); spacestart(); } else if (b[aa] === block[block.length - 1]) { out.push(b[aa]); block.pop(); } else { out.push(b[aa]); } } else { out.push(b[aa]); } if (parse.structure[parse.structure.length - 1][0] === "map" && block.length === 0 && ( b[aa + 1] === "," || b[aa + 1] === ")" )) { if (b[aa + 1] === ")" && data.token[parse.count] === "(") { parse.pop(data); parse.structure.pop(); out.splice(0, 0, "("); } else { break; } } if (b[aa + 1] === ":") { bb = aa; if ((/\s/).test(b[bb]) === true) { do { bb = bb - 1; } while ((/\s/).test(b[bb]) === true); } outy = b .slice(bb - 6, bb + 1) .join(""); if (outy.indexOf("filter") === outy.length - 6 || outy.indexOf("progid") === outy.length - 6) { outy = "filter"; } } if (block.length === 0) { if ( (b[aa + 1] === ";" && esctest(aa + 1) === true) || ( b[aa + 1] === ":" && b[aa] !== ":" && b[aa + 2] !== ":" && outy !== "filter" && outy !== "progid" ) || b[aa + 1] === "}" || b[aa + 1] === "{" || (b[aa + 1] === "/" && (b[aa + 2] === "*" || b[aa + 2] === "/")) ) { bb = out.length - 1; if ((/\s/).test(out[bb]) === true) { do { bb = bb - 1; aa = aa - 1; out.pop(); } while ((/\s/).test(out[bb]) === true); } break; } if (b[aa + 1] === ",") { break; } } aa = aa + 1; } while (aa < len); } a = aa; if (parse.structure[parse.structure.length - 1][0] === "map" && out[0] === "(") { mapper[mapper.length - 1] = mapper[mapper.length - 1] - 1; } ltoke = out .join("") .replace(/\s+/g, " ") .replace(/^\s/, "") .replace(/\s$/, ""); if (funk === true) { ltoke = ltoke.replace(/\s+\(/g, "(").replace(/\s+\)/g, ")").replace(/,\(/g, ", ("); } if (parse.count > -1 && data.token[parse.count].indexOf("extend(") === 0) { ltype = "pseudo"; } else if ( funk === true && (/\d/).test(ltoke.charAt(0)) === false && (/^rgba?\(/).test(ltoke) === false && ltoke.indexOf("url(") !== 0 && (ltoke.indexOf(" ") < 0 || ltoke.indexOf(" ") > ltoke.indexOf("(")) && ltoke.charAt(ltoke.length - 1) === ")" ) { if (data.token[parse.count] === ":") { ltype = "value"; } else { ltoke = ltoke.replace(/,\u0020?/g, ", "); ltype = "function"; } ltoke = value(ltoke); } else if (parse.count > -1 && "\"'".indexOf(data.token[parse.count].charAt(0)) > -1 && data.types[parse.count] === "variable") { ltype = "item"; } else if (out[0] === "@" || out[0] === "$") { if (data.types[parse.count] === "colon" && options.language === "css" && (data.types[parse.count - 1] === "property" || data.types[parse.count - 1] === "variable")) { ltype = "value"; } else if (parse.count > -1) { ltype = "item"; outy = data.token[parse.count]; aa = outy.indexOf("("); if (outy.charAt(outy.length - 1) === ")" && aa > 0) { outy = outy.slice(aa + 1, outy.length - 1); data.token[parse.count] = data .token[parse.count] .slice(0, aa + 1) + value(outy) + ")"; } } ltoke = value(ltoke); } else { ltype = "item"; } recordPush(""); }, // Some tokens receive a generic type named 'item' because their type is unknown // until we know the following syntax. This function replaces the type 'item' // with something more specific. item = function lexer_style_item(type:string):void { let aa:number = parse.count, bb:number = 0, first:string = ""; const comsa:string[] = [], priors = function lexer_style_item_priors() { //backtrack through immediately prior comments to find the correct token if (data.types[aa] === "comment" || data.types[aa] === "ignore") { do { aa = aa - 1; comsa.push(data.token[aa]); } while (aa > 0 && data.lexer[aa] === "style" && (data.types[aa] === "comment" || data.types[aa] === "ignore")); } bb = aa - 1; if (data.types[bb] === "comment" || data.types[bb] === "ignore") { do { bb = bb - 1; } while (bb > 0 && data.lexer[aa] === "style" && (data.types[bb] === "comment" || data.types[bb] === "ignore")); } first = data.token[aa].charAt(0); }, selectorPretty = function lexer_style_item_selectorPretty(index:number):void { let cc:number = index, dd:number = data.begin[cc]; data.token[index] = data.token[index] .replace(/\s*&/, " &") .replace(/(\s*>\s*)/g, " > ") .replace(/:\s+/g, ": ") .replace(/^(\s+)/, "") .replace(/(\s+)$/, "") .replace(/\s+::\s+/, "::"); if (data.token[cc - 1] === "," || data.token[cc - 1] === ":" || data.types[cc - 1] === "comment") { do { cc = cc - 1; if (data.begin[cc] === dd) { if (data.token[cc] === ";") { break; } if (data.token[cc] !== "," && data.types[cc] !== "comment") { data.types[cc] = "selector"; } if (data.token[cc] === ":") { data.token[cc - 1] = `${data.token[cc - 1]}:${data.token[cc + 1]}`; parse.splice({ data: data, howmany: 2, index: cc }); } } else { break; } } while (cc > 0); } // sorts comma separated lists of selectors cc = parse.count; if (options.lexer_options.style.object_sort === true && data.token[cc - 1] === ",") { const store:string[] = [data.token[cc]]; do { cc = cc - 1; if (data.types[cc] === "comment" || data.types[cc] === "ignore") { do { cc = cc - 1; } while (cc > 0 && (data.types[cc] === "comment" || data.types[cc] === "ignore")); } if (data.token[cc] === ",") { cc = cc - 1; } store.push(data.token[cc]); } while (cc > 0 && (data.token[cc - 1] === "," || data.types[cc - 1] === "selector" || data.types[cc - 1] === "comment" || data.types[cc - 1] === "ignore")); store.sort(); cc = parse.count; data.token[cc] = store.pop(); do { cc = cc - 1; if (data.types[cc] === "comment" || data.types[cc] === "ignore") { do { cc = cc - 1; } while (cc > 0 && (data.types[cc] === "comment" || data.types[cc] === "ignore")); } if (data.token[cc] === ",") { cc = cc - 1; } data.token[cc] = store.pop(); } while (cc > 0 && (data.token[cc - 1] === "," || data.token[cc - 1] === "selector" || data.types[cc - 1] === "comment" || data.types[cc - 1] === "ignore")); } aa = parse.count; priors(); }; priors(); //if the last non-comment type is 'item' then id it if (type === "start" && (data.types[aa] === "value" || data.types[aa] === "variable")) { data.types[aa] = "item"; } if (data.lexer[parse.count - 1] !== "style" || bb < 0) { if (type === "colon") { if (first === "$" || first === "@") { data.types[aa] = "variable"; } else { data.types[aa] = "property"; } } else if (data.lexer[aa] === "style") { data.types[aa] = "selector"; selectorPretty(aa); } } else if (type === "start" && data.types[aa] === "function" && data.lexer[aa] === "style") { data.types[aa] = "selector"; selectorPretty(aa); } else if (data.types[aa] === "item" && data.lexer[aa] === "style") { if (type === "start") { selectorPretty(aa); data.types[aa] = "selector"; if (data.token[aa] === ":") { data.types[bb] = "selector"; } if (data.token[aa].indexOf("=\u201c") > 0) { sparser.parseerror = `Quote looking character (\u201c, \\201c) used instead of actual quotes on line number ${parse.lineNumber}`; } else if (data.token[aa].indexOf("=\u201d") > 0) { sparser.parseerror = `Quote looking character (\u201d, \\201d) used instead of actual quotes on line number ${parse.lineNumber}`; } } else if (type === "end") { if (first === "$" || first === "@") { data.types[aa] = "variable"; } else { data.types[aa] = "value"; } data.token[aa] = value(data.token[aa]); } else if (type === "separator") { if (data.types[bb] === "colon" || data.token[bb] === "," || data.token[bb] === "{") { if (b[a] !== ";" && (data.types[bb] === "selector" || data.token[bb] === "{")) { data.types[aa] = "selector"; selectorPretty(aa); } else if (data.token[aa].charAt(0) === "$" || data.token[aa].charAt(0) === "@") { data.types[aa] = "variable"; } else { data.types[aa] = "value"; } data.token[aa] = value(data.token[aa]); if (data.token[aa].charAt(0) === "\u201c") { sparser.parseerror = `Quote looking character (\u201c, \\201c) used instead of actual quotes on line number ${parse.lineNumber}`; } else if (data.token[aa].charAt(0) === "\u201d") { sparser.parseerror = `Quote looking character (\u201d, \\201d) used instead of actual quotes on line number ${parse.lineNumber}`; } } else { if (first === "$" || first === "@") { data.types[aa] = "variable"; } else if (data.types[bb] === "value" || data.types[bb] === "variable") { data.token[bb] = data.token[bb] + data.token[aa]; parse.pop(data); } else { data.types[aa] = "value"; } } } else if (type === "colon") { if (first === "$" || first === "@") { data.types[aa] = "variable"; } else { data.types[aa] = "property"; } } else if (data.token[bb].charAt(0) === "@" && ((data.types[bb - 2] !== "variable" && data.types[bb - 2] !== "property") || data.types[bb - 1] === "separator")) { data.types[bb] = "variable"; ltype = "variable"; data.token[bb] = value(data.token[bb]); } } }, semiComment = function lexer_style_separatorComment():void { let x:number = parse.count; do { x = x - 1; } while (x > 0 && (data.types[x] === "comment")); if (data.token[x] === ";") { return; } parse.splice({ data: data, howmany: 0, index: x + 1, record: { begin: parse.structure[parse.structure.length - 1][1], ender: -1, lexer: "style", lines: parse.linesSpace, stack: parse.structure[parse.structure.length - 1][0], token: ";", types: "separator" } }); }, template = function lexer_style_template(open:string, end:string):void { let quote:string = "", name:string = "", start:number = open.length, endlen:number = 0; const store:string[] = [], exit = function lexer_style_template_exit(typename:string):void { const endtype:string = data.types[parse.count - 1]; if (ltype === "item") { if (endtype === "colon") { data.types[parse.count] = "value"; } else { item(endtype); } } ltype = typename; if (ltype.indexOf("start") > -1 || ltype.indexOf("else") > -1) { recordPush(ltoke); } else { recordPush(""); } }; nosort[nosort.length - 1] = true; if (a < len) { do { store.push(b[a]); if (quote === "") { if (b[a] === "\"") { quote = "\""; } else if (b[a] === "'") { quote = "'"; } else if (b[a] === "/") { if (b[a + 1] === "/") { quote = "/"; } else if (b[a + 1] === "*") { quote = "*"; } } else if (b[a + 1] === end.charAt(0)) { do { endlen = endlen + 1; a = a + 1; store.push(b[a]); } while (a < len && endlen < end.length && b[a + 1] === end.charAt(endlen)); if (endlen === end.length) { quote = store.join(""); if ((/\s/).test(quote.charAt(start)) === true) { do { start = start + 1; } while ((/\s/).test(quote.charAt(start)) === true); } endlen = start; do { endlen = endlen + 1; } while (endlen < end.length && (/\s/).test(quote.charAt(endlen)) === false); if (endlen === quote.length) { endlen = endlen - end.length; } if (open === "{%") { if (quote.indexOf("{%-") === 0) { quote = quote .replace(/^(\{%-\s*)/, "{%- ") .replace(/(\s*-%\})$/, " -%}"); name = quote.slice(4); } else { quote = quote .replace(/^(\{%\s*)/, "{% ") .replace(/(\s*%\})$/, " %}"); name = quote.slice(3); } } if (open === "{{") { quote = quote .replace(/^(\{\{\s+)/, "{{") .replace(/(\s+\}\})$/, "}}"); } if (ltype === "item" && data.types[parse.count - 1] === "colon" && (data.types[parse.count - 2] === "property" || data.types[parse.count - 2] === "variable")) { ltype = "value"; data.types[parse.count] = "value"; if (Number.isNaN(Number(data.token[parse.count])) === true && data.token[parse.count].charAt(data.token[parse.count].length - 1) !== ")") { data.token[parse.count] = data.token[parse.count] + quote; } else { data.token[parse.count] = data.token[parse.count] + " " + quote; } return; } ltoke = quote; if (open === "{%") { const templateNames:string[] = [ "autoescape", "block", "capture", "case", "comment", "embed", "filter", "for", "form", "if", "macro", "paginate", "raw", "sandbox", "spaceless", "tablerow", "unless", "verbatim" ]; let namesLen:number = templateNames.length - 1; name = name.slice(0, name.indexOf(" ")); if (name.indexOf("(") > 0) { name = name.slice(0, name.indexOf("(")); } if (name === "else" || name === "elseif" || name === "when" || name === "elif") { exit("template_else"); return; } namesLen = templateNames.length - 1; if (namesLen > -1) { do { if (name === templateNames[namesLen]) { exit("template_start"); return; } if (name === "end" + templateNames[namesLen]) { exit("template_end"); return; } namesLen = namesLen - 1; } while (namesLen > -1); } } else if (open === "{{") { let group:string = quote.slice(2), ending:number = group.length, begin:number = 0; do { begin = begin + 1; } while ( begin < ending && (/\s/).test(group.charAt(begin)) === false && group.charAt(start) !== "(" ); group = group.slice(0, begin); if (group.charAt(group.length - 2) === "}") { group = group.slice(0, group.length - 2); } if (group === "end") { exit("template_end"); return; } if (group === "block" || group === "define" || group === "form" || group === "if" || group === "range" || group === "with") { exit("template_start"); return; } } if ((/\{\s*\?>$/).test(ltoke) === true) { if ((/^<\?(=|(php))\s*\}\s*else/).test(ltoke) === true) { exit("template_else"); return; } exit("template_start"); return; } if ((/^<\?(=|(php))\s*\}/).test(ltoke) === true) { if ((/^<\?(=|(php))\s*\}\s*else/).test(ltoke) === true) { exit("template_else"); return; } exit("template_end"); return; } exit("template"); return; } endlen = 0; } } else if (quote === b[a]) { if (quote === "\"" || quote === "'") { quote = ""; } else if (quote === "/" && (b[a] === "\r" || b[a] === "\n")) { quote = ""; } else if (quote === "*" && b[a + 1] === "/") { quote = ""; } } a = a + 1; } while (a < len); } }, //finds comments including those JS looking '//' comments comment = function lexer_style_comment(line:boolean):void { let comm:[string, number] = (line === true) ? parse.wrapCommentLine({ chars: b, end: len, lexer: "style", opening: "//", start: a, terminator: "\n" }) : parse.wrapCommentBlock({ chars: b, end: len, lexer: "style", opening: "/*", start: a, terminator: "\u002a/" }); ltoke = comm[0]; ltype = ((/^(\/\*\s*parse-ignore-start)/).test(ltoke) === true) ? "ignore" : "comment"; recordPush(""); a = comm[1]; }, //consolidate margin and padding values margin_padding = function lexer_style_marginPadding():void { const lines:number = parse.linesSpace, props:style_properties = { data: { margin: ["", "", "", "", false], padding: ["", "", "", "", false] }, last: { margin: 0, padding: 0 }, removes: [] }, begin:number = parse.structure[parse.structure.length - 1][1], populate = function lexer_style_marginPadding_populate(prop:"margin"|"padding"):void { if (data.token[aa - 2] === prop) { const values:string[] = data.token[aa].replace(/\s*!important\s*/g, "").split(" "), vlen:number = values.length; if (data.token[aa].indexOf("!important") > -1) { props.data[prop[4]] = true; } if (vlen > 3) { if (props.data[prop][0] === "") { props.data[prop][0] = values[0]; } if (props.data[prop][1] === "") { props.data[prop][1] = values[1]; } if (props.data[prop][2] === "") { props.data[prop][2] = values[2]; } if (props.data[prop][3] === "") { props.data[prop][3] = values[3]; } } else if (vlen > 2) { if (props.data[prop][0] === "") { props.data[prop][0] = values[0]; } if (props.data[prop][1] === "") { props.data[prop][1] = values[1]; } if (props.data[prop][2] === "") { props.data[prop][2] = values[2]; } if (props.data[prop][3] === "") { props.data[prop][3] = values[1]; } } else if (vlen > 1) { if (props.data[prop][0] === "") { props.data[prop][0] = values[0]; } if (props.data[prop][1] === "") { props.data[prop][1] = values[1]; } if (props.data[prop][2] === "") { props.data[prop][2] = values[0]; } if (props.data[prop][3] === "") { props.data[prop][3] = values[1]; } } else { if (props.data[prop][0] === "") { props.data[prop][0] = values[0]; } if (props.data[prop][1] === "") { props.data[prop][1] = values[0]; } if (props.data[prop][2] === "") { props.data[prop][2] = values[0]; } if (props.data[prop][3] === "") { props.data[prop][3] = values[0]; } } } else if (data.token[aa - 2] === `${prop}-bottom`) { if (props.data[prop][2] === "") { props.data[prop][2] = data.token[aa]; } } else if (data.token[aa - 2] === `${prop}-left`) { if (props.data[prop][3] === "") { props.data[prop][3] = data.token[aa]; } } else if (data.token[aa - 2] === `${prop}-right`) { if (props.data[prop][1] === "") { props.data[prop][1] = data.token[aa]; } } else if (data.token[aa - 2] === `${prop}-top`) { if (props.data[prop][0] === "") { props.data[prop][0] = data.token[aa]; } } else { return; } props.removes.push([aa, prop]); props.last[prop] = aa; }, removes = function lexer_style_marginPadding_removes():void { let cc:number = 0, values:string = ""; const zero:RegExp = (/^(0+([a-z]+|%))/), bb:number = props.removes.length, tmargin:boolean = (props.data.margin[0] !== "" && props.data.margin[1] !== "" && props.data.margin[2] !== "" && props.data.margin[3] !== ""), tpadding:boolean = (props.data.padding[0] !== "" && props.data.padding[1] !== "" && props.data.padding[2] !== "" && props.data.padding[3] !== ""), applyValues = function lexer_style_marginPadding_removes_applyValues(prop:"margin"|"padding") { if (zero.test(props.data[prop][0]) === true) { props.data[prop][0] = "0"; } if (zero.test(props.data[prop][1]) === true) { props.data[prop][1] = "0"; } if (zero.test(props.data[prop][2]) === true) { props.data[prop][2] = "0"; } if (zero.test(props.data[prop][3]) === true) { props.data[prop][3] = "0"; } if (props.data[prop][0] === props.data[prop][1] && props.data[prop][0] === props.data[prop][2] && props.data[prop][0] === props.data[prop][3]) { values = props.data[prop][0]; } else if (props.data[prop][0] === props.data[prop][2] && props.data[prop][1] === props.data[prop][3] && props.data[prop][0] !== props.data[prop][1]) { values = `${props.data[prop][0]} ${props.data[prop][1]}`; } else if (props.data[prop][1] === props.data[prop][3] && props.data[prop][0] !== props.data[prop][2]) { values = `${props.data[prop][0]} ${props.data[prop][1]} ${props.data[prop][2]}`; } else { values = `${props.data[prop][0]} ${props.data[prop][1]} ${props.data[prop][2]} ${props.data[prop][3]}`; } if (props.data[prop[4]] === true) { values = `${values.replace(" !important", "")} !important`; } if (props.last[prop] > parse.count) { cc = (begin < 1) ? 1 : begin + 1; do { if (data.begin[cc] === begin && data.types[cc] === "value" && data.token[cc - 2].indexOf(prop) === 0) { props.last[prop] = cc; break; } cc = cc + 1; } while (cc < parse.count) } data.token[props.last[prop]] = values; data.token[props.last[prop] - 2] = prop; }; if (bb > 1 && (tmargin === true || tpadding === true)) { do { if (props.removes[cc][0] !== props.last.margin && props.removes[cc][0] !== props.last.padding && ((tmargin === true && props.removes[cc][1] === "margin") || (tpadding === true && props.removes[cc][1] === "padding"))) { parse.splice({ data: data, howmany: (data.types[props.removes[cc][0] + 1] === "separator") ? 4 : 3, index: props.removes[cc][0] - 2 }); } cc = cc + 1; } while (cc < bb - 1); } if (tmargin === true) { applyValues("margin"); } if (tpadding === true) { applyValues("padding"); } // this is necessary to fix the "begin" values of descendent blocks if (endtest === true) { if (begin < 0) { sparser.parseerror = "Brace mismatch. There appears to be more closing braces than starting braces."; } else { parse.sortCorrection(begin, parse.count + 1); } } }; let aa:number = parse.count, endtest:boolean = false; do { aa = aa - 1; if (data.begin[aa] === begin) { if (data.types[aa] === "value" && data.types[aa - 2] === "property") { if (data.token[aa - 2].indexOf("margin") === 0) { populate("margin"); } else if (data.token[aa - 2].indexOf("padding") === 0) { populate("padding"); } } } else { endtest = true; aa = data.begin[aa]; } } while (aa > begin); removes(); parse.linesSpace = lines; }; //token building loop do { if ((/\s/).test(b[a]) === true) { a = parse.spacer({array: b, end: len, index: a}); } else if (b[a] === "/" && b[a + 1] === "*") { comment(false); } else if (b[a] === "/" && b[a + 1] === "/") { comment(true); } else if (b[a] === "<" && b[a + 1] === "?" && b[a + 2] === "p" && b[a + 3] === "h" && b[a + 4] === "p") { //php template("<?php", "?>"); } else if (b[a] === "<" && b[a + 1] === "?" && b[a + 2] === "=") { //php template("<?=", "?>"); } else if (b[a] === "<" && b[a + 1] === "%") { //asp template("<%", "%>"); } else if (b[a] === "{" && b[a + 1] === "%") { //asp template("{%", "%}"); } else if (b[a] === "{" && b[a + 1] === "{" && b[a + 2] === "{") { //mustache template("{{{", "}}}"); } else if (b[a] === "{" && b[a + 1] === "{") { //handlebars template("{{", "}}"); } else if (b[a] === "<" && b[a + 1] === "!" && b[a + 2] === "-" && b[a + 3] === "-" && b[a + 4] === "#") { //ssi template("<!--#", "-->"); } else if (b[a] === "@" && b[a + 1] === "e" && b[a + 2] === "l" && b[a + 3] === "s" && b[a + 4] === "e" && (b[a + 5] === "{" || (/\s/).test(b[a + 5]) === true)) { ltoke = "@else"; ltype = "template_else"; recordPush(""); a = a + 4; } else if (b[a] === "{" || (b[a] === "(" && data.token[parse.count] === ":" && data.types[parse.count - 1] === "variable")) { item("start"); ltype = "start"; ltoke = b[a]; if (b[a] === "(") { recordPush("map"); mapper.push(0); } else if (data.types[parse.count] === "selector" || data.types[parse.count] === "variable") { recordPush(data.token[parse.count]); } else if (data.types[parse.count] === "colon") { recordPush(data.token[parse.count - 1]); } else { recordPush("block"); } nosort.push(false); } else if (b[a] === "}" || (b[a] === ")" && parse.structure[parse.structure.length - 1][0] === "map" && mapper[mapper.length - 1] === 0)) { if (b[a] === "}" && data.types[parse.count] === "item" && data.token[parse.count - 1] === "{" && data.token[parse.count - 2] !== undefined && data.token[parse.count - 2].charAt(data.token[parse.count - 2].length - 1) === "@") { data.token[parse.count - 2] = data.token[parse.count - 2] + "{" + data.token[parse.count] + "}"; parse.pop(data); parse.pop(data); parse.structure.pop(); } else { if (b[a] === ")") { mapper.pop(); } item("end"); if (b[a] === "}" && data.token[parse.count] !== ";") { if (data.types[parse.count] === "value" || data.types[parse.count] === "function" || ( data.types[parse.count] === "variable" && ( data.token[parse.count - 1] === ":" || data.token[parse.count - 1] === ";" ) )) { if (options.correct === true) { ltoke = ";"; } else { ltoke = "x;"; } ltype = "separator"; recordPush(""); } else if (data.types[parse.count] === "comment") { semiComment(); } } ltype = "end"; nosort.pop(); ltoke = b[a]; ltype = "end"; if (b[a] === "}") { margin_padding(); } if (options.lexer_options.style.object_sort === true && b[a] === "}") { parse.object_sort(data); } recordPush(""); } } else if (b[a] === ";" || b[a] === ",") { if (data.types[parse.count - 1] === "selector" || (data.token[parse.count - 1] === "}" && data.types[parse.count] !== "function")) { item("start"); } else { item("separator"); } if (data.types[parse.count] !== "separator" && esctest(a) === true) { ltoke = b[a]; ltype = "separator"; recordPush(""); } } else if (b[a] === ":" && data.types[parse.count] !== "end") { item("colon"); ltoke = ":"; ltype = "colon"; recordPush(""); } else { if (parse.structure[parse.structure.length - 1][0] === "map" && b[a] === "(") { mapper[mapper.length - 1] = mapper[mapper.length - 1] + 1; } buildtoken(); } a = a + 1; } while (a < len); if (options.lexer_options.style.object_sort === true) { parse.object_sort(data); } return data; }; sparser.lexers.style = style; }());
the_stack
import { Modal, Notice, Plugin, Setting, addIcon, setIcon, FileSystemAdapter, } from "obsidian"; import cloneDeep from "lodash/cloneDeep"; import { createElement, RotateCcw, RefreshCcw, FileText } from "lucide"; import type { FileOrFolderMixedState, RemotelySavePluginSettings, SyncTriggerSourceType, } from "./baseTypes"; import { COMMAND_CALLBACK, COMMAND_CALLBACK_ONEDRIVE, COMMAND_CALLBACK_DROPBOX, COMMAND_URI, } from "./baseTypes"; import { importQrCodeUri } from "./importExport"; import { insertDeleteRecordByVault, insertRenameRecordByVault, insertSyncPlanRecordByVault, loadFileHistoryTableByVault, prepareDBs, InternalDBs, insertLoggerOutputByVault, clearExpiredLoggerOutputRecords, clearExpiredSyncPlanRecords, } from "./localdb"; import { RemoteClient } from "./remote"; import { DEFAULT_DROPBOX_CONFIG, getAuthUrlAndVerifier as getAuthUrlAndVerifierDropbox, sendAuthReq as sendAuthReqDropbox, setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceDropbox, } from "./remoteForDropbox"; import { AccessCodeResponseSuccessfulType, DEFAULT_ONEDRIVE_CONFIG, sendAuthReq as sendAuthReqOnedrive, setConfigBySuccessfullAuthInplace as setConfigBySuccessfullAuthInplaceOnedrive, } from "./remoteForOnedrive"; import { DEFAULT_S3_CONFIG } from "./remoteForS3"; import { DEFAULT_WEBDAV_CONFIG } from "./remoteForWebdav"; import { RemotelySaveSettingTab } from "./settings"; import { fetchMetadataFile, parseRemoteItems, SyncStatusType } from "./sync"; import { doActualSync, getSyncPlan, isPasswordOk } from "./sync"; import { messyConfigToNormal, normalConfigToMessy } from "./configPersist"; import { ObsConfigDirFileType, listFilesInObsFolder } from "./obsFolderLister"; import { I18n } from "./i18n"; import type { LangType, LangTypeAndAuto, TransItemType } from "./i18n"; import { DeletionOnRemote, MetadataOnRemote } from "./metadataOnRemote"; import { SyncAlgoV2Modal } from "./syncAlgoV2Notice"; import { applyPresetRulesInplace } from "./presetRules"; import { applyLogWriterInplace, log } from "./moreOnLog"; import AggregateError from "aggregate-error"; import { exportVaultLoggerOutputToFiles, exportVaultSyncPlansToFiles, } from "./debugMode"; import { SizesConflictModal } from "./syncSizesConflictNotice"; const DEFAULT_SETTINGS: RemotelySavePluginSettings = { s3: DEFAULT_S3_CONFIG, webdav: DEFAULT_WEBDAV_CONFIG, dropbox: DEFAULT_DROPBOX_CONFIG, onedrive: DEFAULT_ONEDRIVE_CONFIG, password: "", serviceType: "s3", currLogLevel: "info", // vaultRandomID: "", // deprecated autoRunEveryMilliseconds: -1, initRunAfterMilliseconds: -1, agreeToUploadExtraMetadata: false, concurrency: 5, syncConfigDir: false, syncUnderscoreItems: false, lang: "auto", logToDB: false, skipSizeLargerThan: -1, }; interface OAuth2Info { verifier?: string; helperModal?: Modal; authDiv?: HTMLElement; revokeDiv?: HTMLElement; revokeAuthSetting?: Setting; } const iconNameSyncWait = `remotely-save-sync-wait`; const iconNameSyncRunning = `remotely-save-sync-running`; const iconNameLogs = `remotely-save-logs`; const getIconSvg = () => { const iconSvgSyncWait = createElement(RotateCcw); iconSvgSyncWait.setAttribute("width", "100"); iconSvgSyncWait.setAttribute("height", "100"); const iconSvgSyncRunning = createElement(RefreshCcw); iconSvgSyncRunning.setAttribute("width", "100"); iconSvgSyncRunning.setAttribute("height", "100"); const iconSvgLogs = createElement(FileText); iconSvgLogs.setAttribute("width", "100"); iconSvgLogs.setAttribute("height", "100"); const res = { iconSvgSyncWait: iconSvgSyncWait.outerHTML, iconSvgSyncRunning: iconSvgSyncRunning.outerHTML, iconSvgLogs: iconSvgLogs.outerHTML, }; iconSvgSyncWait.empty(); iconSvgSyncRunning.empty(); iconSvgLogs.empty(); return res; }; export default class RemotelySavePlugin extends Plugin { settings: RemotelySavePluginSettings; db: InternalDBs; syncStatus: SyncStatusType; oauth2Info: OAuth2Info; currLogLevel: string; currSyncMsg?: string; syncRibbon?: HTMLElement; autoRunIntervalID?: number; i18n: I18n; vaultRandomID: string; async syncRun(triggerSource: SyncTriggerSourceType = "manual") { const t = (x: TransItemType, vars?: any) => { return this.i18n.t(x, vars); }; const getNotice = (x: string, timeout?: number) => { // only show notices in manual mode // no notice in auto mode if (triggerSource === "manual" || triggerSource === "dry") { new Notice(x, timeout); } }; if (this.syncStatus !== "idle") { // here the notice is shown regardless of triggerSource new Notice( t("syncrun_alreadyrunning", { pluginName: this.manifest.name, syncStatus: this.syncStatus, }) ); if (this.currSyncMsg !== undefined && this.currSyncMsg !== "") { new Notice(this.currSyncMsg); } return; } let originLabel = `${this.manifest.name}`; if (this.syncRibbon !== undefined) { originLabel = this.syncRibbon.getAttribute("aria-label"); } try { log.info( `${ this.manifest.id }-${Date.now()}: start sync, triggerSource=${triggerSource}` ); if (this.syncRibbon !== undefined) { setIcon(this.syncRibbon, iconNameSyncRunning); this.syncRibbon.setAttribute( "aria-label", t("syncrun_syncingribbon", { pluginName: this.manifest.name, triggerSource: triggerSource, }) ); } const MAX_STEPS = 8; if (triggerSource === "dry") { getNotice( t("syncrun_step0", { maxSteps: `${MAX_STEPS}`, }) ); } //log.info(`huh ${this.settings.password}`) getNotice( t("syncrun_step1", { maxSteps: `${MAX_STEPS}`, serviceType: this.settings.serviceType, }) ); this.syncStatus = "preparing"; getNotice( t("syncrun_step2", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "getting_remote_files_list"; const self = this; const client = new RemoteClient( this.settings.serviceType, this.settings.s3, this.settings.webdav, this.settings.dropbox, this.settings.onedrive, this.app.vault.getName(), () => self.saveSettings() ); const remoteRsp = await client.listFromRemote(); // log.debug(remoteRsp); getNotice( t("syncrun_step3", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "checking_password"; const passwordCheckResult = await isPasswordOk( remoteRsp.Contents, this.settings.password ); if (!passwordCheckResult.ok) { getNotice(t("syncrun_passworderr")); throw Error(passwordCheckResult.reason); } getNotice( t("syncrun_step4", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "getting_remote_extra_meta"; const { remoteStates, metadataFile } = await parseRemoteItems( remoteRsp.Contents, this.db, this.vaultRandomID, client.serviceType, this.settings.password ); const origMetadataOnRemote = await fetchMetadataFile( metadataFile, client, this.app.vault, this.settings.password ); getNotice( t("syncrun_step5", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "getting_local_meta"; const local = this.app.vault.getAllLoadedFiles(); const localHistory = await loadFileHistoryTableByVault( this.db, this.vaultRandomID ); let localConfigDirContents: ObsConfigDirFileType[] = undefined; if (this.settings.syncConfigDir) { localConfigDirContents = await listFilesInObsFolder( this.app.vault.configDir, this.app.vault, this.manifest.id ); } // log.info(local); // log.info(localHistory); getNotice( t("syncrun_step6", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "generating_plan"; const { plan, sortedKeys, deletions, sizesGoWrong } = await getSyncPlan( remoteStates, local, localConfigDirContents, origMetadataOnRemote.deletions, localHistory, client.serviceType, triggerSource, this.app.vault, this.settings.syncConfigDir, this.app.vault.configDir, this.settings.syncUnderscoreItems, this.settings.skipSizeLargerThan, this.settings.password ); log.info(plan.mixedStates); // for debugging await insertSyncPlanRecordByVault(this.db, plan, this.vaultRandomID); // The operations above are almost read only and kind of safe. // The operations below begins to write or delete (!!!) something. if (triggerSource !== "dry") { getNotice( t("syncrun_step7", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "syncing"; await doActualSync( client, this.db, this.vaultRandomID, this.app.vault, plan, sortedKeys, metadataFile, origMetadataOnRemote, sizesGoWrong, deletions, (key: string) => self.trash(key), this.settings.password, this.settings.concurrency, (ss: FileOrFolderMixedState[]) => { new SizesConflictModal( self.app, self, this.settings.skipSizeLargerThan, ss, this.settings.password !== "" ).open(); }, (i: number, totalCount: number, pathName: string, decision: string) => self.setCurrSyncMsg(i, totalCount, pathName, decision) ); } else { this.syncStatus = "syncing"; getNotice( t("syncrun_step7skip", { maxSteps: `${MAX_STEPS}`, }) ); } getNotice( t("syncrun_step8", { maxSteps: `${MAX_STEPS}`, }) ); this.syncStatus = "finish"; this.syncStatus = "idle"; if (this.syncRibbon !== undefined) { setIcon(this.syncRibbon, iconNameSyncWait); this.syncRibbon.setAttribute("aria-label", originLabel); } log.info( `${ this.manifest.id }-${Date.now()}: finish sync, triggerSource=${triggerSource}` ); } catch (error) { const msg = t("syncrun_abort", { manifestID: this.manifest.id, theDate: `${Date.now()}`, triggerSource: triggerSource, syncStatus: this.syncStatus, }); log.error(msg); log.error(error); getNotice(msg, 10 * 1000); if (error instanceof AggregateError) { for (const e of error.errors) { getNotice(e.message, 10 * 1000); } } else { getNotice(error.message, 10 * 1000); } this.syncStatus = "idle"; if (this.syncRibbon !== undefined) { setIcon(this.syncRibbon, iconNameSyncWait); this.syncRibbon.setAttribute("aria-label", originLabel); } } } async onload() { log.info(`loading plugin ${this.manifest.id}`); const { iconSvgSyncWait, iconSvgSyncRunning, iconSvgLogs } = getIconSvg(); addIcon(iconNameSyncWait, iconSvgSyncWait); addIcon(iconNameSyncRunning, iconSvgSyncRunning); addIcon(iconNameLogs, iconSvgLogs); this.oauth2Info = { verifier: "", helperModal: undefined, authDiv: undefined, revokeDiv: undefined, revokeAuthSetting: undefined, }; // init this.currSyncMsg = ""; await this.loadSettings(); await this.checkIfPresetRulesFollowed(); // lang should be load early, but after settings this.i18n = new I18n(this.settings.lang, async (lang: LangTypeAndAuto) => { this.settings.lang = lang; await this.saveSettings(); }); const t = (x: TransItemType, vars?: any) => { return this.i18n.t(x, vars); }; if (this.settings.currLogLevel !== undefined) { log.setLevel(this.settings.currLogLevel as any); } await this.checkIfOauthExpires(); // MUST before prepareDB() // And, it's also possible to be an empty string, // which means the vaultRandomID is read from db later! const vaultRandomIDFromOldConfigFile = await this.getVaultRandomIDFromOldConfigFile(); // no need to await this this.tryToAddIgnoreFile(); const vaultBasePath = this.getVaultBasePath(); try { await this.prepareDBAndVaultRandomID( vaultBasePath, vaultRandomIDFromOldConfigFile ); } catch (err) { new Notice(err.message, 10 * 1000); throw err; } // must AFTER preparing DB this.addOutputToDBIfSet(); this.enableAutoClearOutputToDBHistIfSet(); // must AFTER preparing DB this.enableAutoClearSyncPlanHist(); this.syncStatus = "idle"; this.registerEvent( this.app.vault.on("delete", async (fileOrFolder) => { await insertDeleteRecordByVault( this.db, fileOrFolder, this.vaultRandomID ); }) ); this.registerEvent( this.app.vault.on("rename", async (fileOrFolder, oldPath) => { await insertRenameRecordByVault( this.db, fileOrFolder, oldPath, this.vaultRandomID ); }) ); this.registerObsidianProtocolHandler(COMMAND_URI, async (inputParams) => { const parsed = importQrCodeUri(inputParams, this.app.vault.getName()); if (parsed.status === "error") { new Notice(parsed.message); } else { const copied = cloneDeep(parsed.result); // new Notice(JSON.stringify(copied)) this.settings = Object.assign({}, this.settings, copied); this.saveSettings(); new Notice( t("protocol_saveqr", { manifestName: this.manifest.name, }) ); } }); this.registerObsidianProtocolHandler( COMMAND_CALLBACK, async (inputParams) => { new Notice( t("protocol_callbacknotsupported", { params: JSON.stringify(inputParams), }) ); } ); this.registerObsidianProtocolHandler( COMMAND_CALLBACK_DROPBOX, async (inputParams) => { if (inputParams.code !== undefined) { if (this.oauth2Info.helperModal !== undefined) { this.oauth2Info.helperModal.contentEl.empty(); t("protocol_dropbox_connecting") .split("\n") .forEach((val) => { this.oauth2Info.helperModal.contentEl.createEl("p", { text: val, }); }); } let authRes = await sendAuthReqDropbox( this.settings.dropbox.clientID, this.oauth2Info.verifier, inputParams.code ); const self = this; setConfigBySuccessfullAuthInplaceDropbox( this.settings.dropbox, authRes, () => self.saveSettings() ); const client = new RemoteClient( "dropbox", undefined, undefined, this.settings.dropbox, undefined, this.app.vault.getName(), () => self.saveSettings() ); const username = await client.getUser(); this.settings.dropbox.username = username; await this.saveSettings(); new Notice( t("protocol_dropbox_connect_succ", { username: username, }) ); this.oauth2Info.verifier = ""; // reset it this.oauth2Info.helperModal?.close(); // close it this.oauth2Info.helperModal = undefined; this.oauth2Info.authDiv?.toggleClass( "dropbox-auth-button-hide", this.settings.dropbox.username !== "" ); this.oauth2Info.authDiv = undefined; this.oauth2Info.revokeAuthSetting?.setDesc( t("protocol_dropbox_connect_succ_revoke", { username: this.settings.dropbox.username, }) ); this.oauth2Info.revokeAuthSetting = undefined; this.oauth2Info.revokeDiv?.toggleClass( "dropbox-revoke-auth-button-hide", this.settings.dropbox.username === "" ); this.oauth2Info.revokeDiv = undefined; } else { new Notice(t("protocol_dropbox_connect_fail")); throw Error( t("protocol_dropbox_connect_unknown", { params: JSON.stringify(inputParams), }) ); } } ); this.registerObsidianProtocolHandler( COMMAND_CALLBACK_ONEDRIVE, async (inputParams) => { if (inputParams.code !== undefined) { if (this.oauth2Info.helperModal !== undefined) { this.oauth2Info.helperModal.contentEl.empty(); t("protocol_onedrive_connecting") .split("\n") .forEach((val) => { this.oauth2Info.helperModal.contentEl.createEl("p", { text: val, }); }); } let rsp = await sendAuthReqOnedrive( this.settings.onedrive.clientID, this.settings.onedrive.authority, inputParams.code, this.oauth2Info.verifier ); if ((rsp as any).error !== undefined) { throw Error(`${JSON.stringify(rsp)}`); } const self = this; setConfigBySuccessfullAuthInplaceOnedrive( this.settings.onedrive, rsp as AccessCodeResponseSuccessfulType, () => self.saveSettings() ); const client = new RemoteClient( "onedrive", undefined, undefined, undefined, this.settings.onedrive, this.app.vault.getName(), () => self.saveSettings() ); this.settings.onedrive.username = await client.getUser(); await this.saveSettings(); this.oauth2Info.verifier = ""; // reset it this.oauth2Info.helperModal?.close(); // close it this.oauth2Info.helperModal = undefined; this.oauth2Info.authDiv?.toggleClass( "onedrive-auth-button-hide", this.settings.onedrive.username !== "" ); this.oauth2Info.authDiv = undefined; this.oauth2Info.revokeAuthSetting?.setDesc( t("protocol_onedrive_connect_succ_revoke", { username: this.settings.onedrive.username, }) ); this.oauth2Info.revokeAuthSetting = undefined; this.oauth2Info.revokeDiv?.toggleClass( "onedrive-revoke-auth-button-hide", this.settings.onedrive.username === "" ); this.oauth2Info.revokeDiv = undefined; } else { new Notice(t("protocol_onedrive_connect_fail")); throw Error( t("protocol_onedrive_connect_unknown", { params: JSON.stringify(inputParams), }) ); } } ); this.syncRibbon = this.addRibbonIcon( iconNameSyncWait, `${this.manifest.name}`, async () => this.syncRun("manual") ); this.addCommand({ id: "start-sync", name: t("command_startsync"), icon: iconNameSyncWait, callback: async () => { this.syncRun("manual"); }, }); this.addCommand({ id: "start-sync-dry-run", name: t("command_drynrun"), icon: iconNameSyncWait, callback: async () => { this.syncRun("dry"); }, }); this.addCommand({ id: "export-sync-plans-json", name: t("command_exportsyncplans_json"), icon: iconNameLogs, callback: async () => { await exportVaultSyncPlansToFiles( this.db, this.app.vault, this.vaultRandomID, "json" ); new Notice(t("settings_syncplans_notice")); }, }); this.addCommand({ id: "export-sync-plans-table", name: t("command_exportsyncplans_table"), icon: iconNameLogs, callback: async () => { await exportVaultSyncPlansToFiles( this.db, this.app.vault, this.vaultRandomID, "table" ); new Notice(t("settings_syncplans_notice")); }, }); this.addCommand({ id: "export-logs-in-db", name: t("command_exportlogsindb"), icon: iconNameLogs, callback: async () => { await exportVaultLoggerOutputToFiles( this.db, this.app.vault, this.vaultRandomID ); new Notice(t("settings_logtodbexport_notice")); }, }); this.addSettingTab(new RemotelySaveSettingTab(this.app, this)); // this.registerDomEvent(document, "click", (evt: MouseEvent) => { // log.info("click", evt); // }); if (!this.settings.agreeToUploadExtraMetadata) { const syncAlgoV2Modal = new SyncAlgoV2Modal(this.app, this); syncAlgoV2Modal.open(); } else { this.enableAutoSyncIfSet(); this.enableInitSyncIfSet(); } } async onunload() { log.info(`unloading plugin ${this.manifest.id}`); this.syncRibbon = undefined; if (this.oauth2Info !== undefined) { this.oauth2Info.helperModal = undefined; this.oauth2Info = undefined; } } async loadSettings() { this.settings = Object.assign( {}, cloneDeep(DEFAULT_SETTINGS), messyConfigToNormal(await this.loadData()) ); if (this.settings.dropbox.clientID === "") { this.settings.dropbox.clientID = DEFAULT_SETTINGS.dropbox.clientID; } if (this.settings.dropbox.remoteBaseDir === undefined) { this.settings.dropbox.remoteBaseDir = ""; } if (this.settings.onedrive.clientID === "") { this.settings.onedrive.clientID = DEFAULT_SETTINGS.onedrive.clientID; } if (this.settings.onedrive.authority === "") { this.settings.onedrive.authority = DEFAULT_SETTINGS.onedrive.authority; } if (this.settings.onedrive.remoteBaseDir === undefined) { this.settings.onedrive.remoteBaseDir = ""; } if (this.settings.webdav.manualRecursive === undefined) { this.settings.webdav.manualRecursive = false; } if (this.settings.webdav.depth === undefined) { this.settings.webdav.depth = "auto_unknown"; } if (this.settings.webdav.remoteBaseDir === undefined) { this.settings.webdav.remoteBaseDir = ""; } if (this.settings.s3.partsConcurrency === undefined) { this.settings.s3.partsConcurrency = 20; } if (this.settings.s3.forcePathStyle === undefined) { this.settings.s3.forcePathStyle = false; } } async checkIfPresetRulesFollowed() { const res = applyPresetRulesInplace(this.settings); if (res.changed) { await this.saveSettings(); } } async saveSettings() { await this.saveData(normalConfigToMessy(this.settings)); } async checkIfOauthExpires() { let needSave: boolean = false; const current = Date.now(); // fullfill old version settings if ( this.settings.dropbox.refreshToken !== "" && this.settings.dropbox.credentialsShouldBeDeletedAtTime === undefined ) { // It has a refreshToken, but not expire time. // Likely to be a setting from old version. // we set it to a month. this.settings.dropbox.credentialsShouldBeDeletedAtTime = current + 1000 * 60 * 60 * 24 * 30; needSave = true; } if ( this.settings.onedrive.refreshToken !== "" && this.settings.onedrive.credentialsShouldBeDeletedAtTime === undefined ) { this.settings.onedrive.credentialsShouldBeDeletedAtTime = current + 1000 * 60 * 60 * 24 * 30; needSave = true; } // check expired or not let dropboxExpired = false; if ( this.settings.dropbox.refreshToken !== "" && current >= this.settings.dropbox.credentialsShouldBeDeletedAtTime ) { dropboxExpired = true; this.settings.dropbox = cloneDeep(DEFAULT_DROPBOX_CONFIG); needSave = true; } let onedriveExpired = false; if ( this.settings.onedrive.refreshToken !== "" && current >= this.settings.onedrive.credentialsShouldBeDeletedAtTime ) { onedriveExpired = true; this.settings.onedrive = cloneDeep(DEFAULT_ONEDRIVE_CONFIG); needSave = true; } // save back if (needSave) { await this.saveSettings(); } // send notice if (dropboxExpired && onedriveExpired) { new Notice( `${this.manifest.name}: You haven't manually auth Dropbox and OneDrive for a while, you need to re-auth them again.`, 6000 ); } else if (dropboxExpired) { new Notice( `${this.manifest.name}: You haven't manually auth Dropbox for a while, you need to re-auth it again.`, 6000 ); } else if (onedriveExpired) { new Notice( `${this.manifest.name}: You haven't manually auth OneDrive for a while, you need to re-auth it again.`, 6000 ); } } async getVaultRandomIDFromOldConfigFile() { let vaultRandomID = ""; if (this.settings.vaultRandomID !== undefined) { // In old version, the vault id is saved in data.json // But we want to store it in localForage later if (this.settings.vaultRandomID !== "") { // a real string was assigned before vaultRandomID = this.settings.vaultRandomID; } log.debug("vaultRandomID is no longer saved in data.json"); delete this.settings.vaultRandomID; await this.saveSettings(); } return vaultRandomID; } async trash(x: string) { if (!(await this.app.vault.adapter.trashSystem(x))) { await this.app.vault.adapter.trashLocal(x); } } getVaultBasePath() { if (this.app.vault.adapter instanceof FileSystemAdapter) { // in desktop return this.app.vault.adapter.getBasePath().split("?")[0]; } else { // in mobile return this.app.vault.adapter.getResourcePath("").split("?")[0]; } } async prepareDBAndVaultRandomID( vaultBasePath: string, vaultRandomIDFromOldConfigFile: string ) { const { db, vaultRandomID } = await prepareDBs( vaultBasePath, vaultRandomIDFromOldConfigFile ); this.db = db; this.vaultRandomID = vaultRandomID; } enableAutoSyncIfSet() { if ( this.settings.autoRunEveryMilliseconds !== undefined && this.settings.autoRunEveryMilliseconds !== null && this.settings.autoRunEveryMilliseconds > 0 ) { this.app.workspace.onLayoutReady(() => { const intervalID = window.setInterval(() => { this.syncRun("auto"); }, this.settings.autoRunEveryMilliseconds); this.autoRunIntervalID = intervalID; this.registerInterval(intervalID); }); } } enableInitSyncIfSet() { if ( this.settings.initRunAfterMilliseconds !== undefined && this.settings.initRunAfterMilliseconds !== null && this.settings.initRunAfterMilliseconds > 0 ) { this.app.workspace.onLayoutReady(() => { window.setTimeout(() => { this.syncRun("autoOnceInit"); }, this.settings.initRunAfterMilliseconds); }); } } async saveAgreeToUseNewSyncAlgorithm() { this.settings.agreeToUploadExtraMetadata = true; await this.saveSettings(); } async setCurrSyncMsg( i: number, totalCount: number, pathName: string, decision: string ) { const msg = `syncing progress=${i}/${totalCount},decision=${decision},path=${pathName}`; this.currSyncMsg = msg; } /** * Because data.json contains sensitive information, * We usually want to ignore it in the version control. * However, if there's already a an ignore file (even empty), * we respect the existing configure and not add any modifications. * @returns */ async tryToAddIgnoreFile() { const pluginConfigDir = this.manifest.dir || `${this.app.vault.configDir}/plugins/${this.manifest.dir}`; const pluginConfigDirExists = await this.app.vault.adapter.exists( pluginConfigDir ); if (!pluginConfigDirExists) { // what happened? return; } const ignoreFile = `${pluginConfigDir}/.gitignore`; const ignoreFileExists = await this.app.vault.adapter.exists(ignoreFile); const contentText = "data.json\n"; try { if (!ignoreFileExists) { // not exists, directly create // no need to await this.app.vault.adapter.write(ignoreFile, contentText); } } catch (error) { // just skip } } addOutputToDBIfSet() { if (this.settings.logToDB) { applyLogWriterInplace((...msg: any[]) => { insertLoggerOutputByVault(this.db, this.vaultRandomID, ...msg); }); } } enableAutoClearOutputToDBHistIfSet() { const initClearOutputToDBHistAfterMilliseconds = 1000 * 45; const autoClearOutputToDBHistAfterMilliseconds = 1000 * 60 * 5; this.app.workspace.onLayoutReady(() => { // init run window.setTimeout(() => { if (this.settings.logToDB) { clearExpiredLoggerOutputRecords(this.db); } }, initClearOutputToDBHistAfterMilliseconds); // scheduled run const intervalID = window.setInterval(() => { if (this.settings.logToDB) { clearExpiredLoggerOutputRecords(this.db); } }, autoClearOutputToDBHistAfterMilliseconds); this.registerInterval(intervalID); }); } enableAutoClearSyncPlanHist() { const initClearSyncPlanHistAfterMilliseconds = 1000 * 45; const autoClearSyncPlanHistAfterMilliseconds = 1000 * 60 * 5; this.app.workspace.onLayoutReady(() => { // init run window.setTimeout(() => { clearExpiredSyncPlanRecords(this.db); }, initClearSyncPlanHistAfterMilliseconds); // scheduled run const intervalID = window.setInterval(() => { clearExpiredSyncPlanRecords(this.db); }, autoClearSyncPlanHistAfterMilliseconds); this.registerInterval(intervalID); }); } }
the_stack
import { Component, Watch } from 'vue-property-decorator'; import { forceSimulation, Simulation, forceLink, forceManyBody, forceCenter } from 'd3-force'; import { event as d3Event, select } from 'd3-selection'; import { line, curveBasis, curveLinearClosed } from 'd3-shape'; import { zoom, ZoomBehavior, zoomIdentity } from 'd3-zoom'; import Victor from 'victor'; import _ from 'lodash'; import $ from 'jquery'; import template from './network.html'; import { drawBrushBox, getBrushBox, injectVisualizationTemplate, isPointInBox, multiplyVisuals, Visualization, } from '@/components/visualization'; import ColumnSelect from '@/components/column-select/column-select'; import FormInput from '@/components/form-input/form-input'; import { VisualProperties } from '@/data/visuals'; import { SELECTED_COLOR } from '@/common/constants'; import { SubsetInputPort, SubsetOutputPort } from '@/components/port'; import { SubsetSelection } from '@/data/package'; import { getTransform, fadeOut, areSegmentsIntersected } from '@/common/util'; import TabularDataset from '@/data/tabular-dataset'; import { mirrorPoint } from '@/common/vector'; import { getColumnSelectOptions } from '@/data/util'; import * as history from './history'; // A mouse must move at least this distance to be considered a zoom. const ZOOM_DISTANCE_THRESHOLD = 5; const NODE_LABEL_SIZE_PX = 12; const NODE_LABEL_X_OFFSET_PX = 10; const NODE_LABEL_Y_OFFSET_PX = NODE_LABEL_SIZE_PX / 2; const NODE_SIZE_PX = 5; const EDGE_ARROW_LENGTH = 10; const EDGE_CURVE_SHIFT = .1; const FORCE_FRICTION = .25; const ZOOM_EXTENT: [number, number] = [.01, 8]; const DEFAULT_NODE_VISUALS: VisualProperties = { color: '#555', border: 'black', width: 2, size: 5, }; const DEFAULT_EDGE_VISUALS: VisualProperties = { width: 1.5, color: '#333', }; const SELECTED_NODE_VISUALS: VisualProperties = { color: 'white', border: SELECTED_COLOR, }; const SELECTED_EDGE_VISUALS: VisualProperties = { color: SELECTED_COLOR, }; export interface NetworkSelection { nodeSelection: SubsetSelection; edgeSelection: SubsetSelection; } interface NetworkSave { nodeIdColumn: number | null; edgeSourceColumn: number | null; edgeTargetColumn: number | null; nodeLabelColumn: number | null; linkDistance: number; isNavigating: boolean; nodeSelection: number[]; edgeSelection: number[]; zoomScale: number; zoomTranslate: [number, number]; lastNodeDatasetHash: string; lastEdgeDatasetHash: string; } interface NetworkNodeProps { index: number; label: string; visuals: VisualProperties; hasVisuals: boolean; selected: boolean; node: NetworkNode; } interface NetworkEdgeProps { index: number; visuals: VisualProperties; hasVisuals: boolean; selected: boolean; source: NetworkNode; target: NetworkNode; } interface NetworkNode { nodeIndex: number; // Note that "index" is reserved by d3.forceSimulation label: string; x: number; y: number; size: number; } interface NetworkEdge { edgeIndex: number; // Note that "index" is reserved by d3.forceLink source: NetworkNode; target: NetworkNode; } @Component({ template: injectVisualizationTemplate(template), components: { ColumnSelect, FormInput, }, }) export default class Network extends Visualization { protected NODE_TYPE = 'network'; private nodeIdColumn: number | null = null; private edgeSourceColumn: number | null = null; private edgeTargetColumn: number | null = null; private nodeLabelColumn: number | null = null; private linkDistance = 30; private isNavigating = true; private nodeSelection: SubsetSelection = new SubsetSelection(); private edgeSelection: SubsetSelection = new SubsetSelection(); private prevNodeSelection: SubsetSelection = new SubsetSelection(); private prevEdgeSelection: SubsetSelection = new SubsetSelection(); // References to rendered node objects. private nodes: { [index: number]: NetworkNode } = {}; // References to rendered edge objects. private edges: { [index: number]: NetworkEdge } = {}; private nodeProps: NetworkNodeProps[] = []; private edgeProps: NetworkEdgeProps[] = []; private zoomScale: number = 1.; private zoomTranslate: [number, number] = [0, 0]; private zoomBahavior: ZoomBehavior<Element, {}> | null = null; private nodeDataset: TabularDataset | null = null; private edgeDataset: TabularDataset | null = null; private lastNodeDatasetHash: string = ''; private lastEdgeDatasetHash: string = ''; private zoomStartPosition: Point = { x: 0, y: 0}; private force: Simulation<NetworkNode, undefined> | null = null; get nodeColumnSelectOptions(): SelectOption[] { return getColumnSelectOptions(this.nodeDataset); } get edgeColumnSelectOptions(): SelectOption[] { return getColumnSelectOptions(this.edgeDataset); } public onKeys(keys: string): boolean { if (keys === 'n') { this.toggleNavigating(); return true; } return this.onKeysVisualization(keys); } public setNetworkSelection({ nodeSelection, edgeSelection }: { nodeSelection: number[], edgeSelection: number[] }) { this.nodeSelection.setItems(nodeSelection); this.edgeSelection.setItems(edgeSelection); this.onSelectionUpdate(); } public setNodeIdColumn(column: number) { this.nodeIdColumn = column; this.draw(); } public setEdgeSourceColumn(column: number) { this.edgeSourceColumn = column; this.draw(); } public setEdgeTargetColumn(column: number) { this.edgeTargetColumn = column; this.draw(); } public setNodeLabelColumn(column: number) { this.nodeLabelColumn = column; this.draw(); } public setLinkDistance(value: number) { this.linkDistance = value; this.draw(); } public setNavigating(value: boolean) { this.isNavigating = value; this.draw(); } /** * As a network node has two heterogeneous node and edge tables. We must check them separately. */ protected checkDataset(): boolean { if (this.hasNoDataset()) { this.coverText = 'No Node/Edge Dataset'; this.updateNoDatasetOutput(); return false; } this.nodeDataset = this.inputPortMap.node.getSubsetPackage().getDataset() as TabularDataset; this.edgeDataset = this.inputPortMap.edge.getSubsetPackage().getDataset() as TabularDataset; // See subset-node-base.ts for a description of how to use dataset hashes. if (this.nodeDataset.getHash() !== this.lastNodeDatasetHash || this.edgeDataset.getHash() !== this.lastEdgeDatasetHash) { this.lastNodeDatasetHash = this.nodeDataset.getHash(); this.lastEdgeDatasetHash = this.edgeDataset.getHash(); this.onDatasetChange(); } this.coverText = ''; return true; } protected hasNoDataset(): boolean { return !this.inputPortMap.node.isConnected() || !this.inputPortMap.node.getSubsetPackage().hasDataset() || !this.inputPortMap.edge.isConnected() || !this.inputPortMap.edge.getSubsetPackage().hasDataset(); } protected findDefaultColumns() { // TODO: auto fill? } protected created() { this.serializationChain.push((): NetworkSave => ({ nodeIdColumn: this.nodeIdColumn, edgeSourceColumn: this.edgeSourceColumn, edgeTargetColumn: this.edgeTargetColumn, nodeLabelColumn: this.nodeLabelColumn, linkDistance: this.linkDistance, isNavigating: this.isNavigating, nodeSelection: this.nodeSelection.serialize(), edgeSelection: this.edgeSelection.serialize(), zoomScale: this.zoomScale, zoomTranslate: this.zoomTranslate, lastNodeDatasetHash: this.lastNodeDatasetHash, lastEdgeDatasetHash: this.lastEdgeDatasetHash, })); this.deserializationChain.push(nodeSave => { const save = nodeSave as NetworkSave; this.nodeSelection = new SubsetSelection(save.nodeSelection); this.edgeSelection = new SubsetSelection(save.edgeSelection); this.applyZoomTransform(); }); } /** * Creates zoom handler on mounted. */ protected onMounted() { const svg = select<Element, {}>(this.$refs.svg as SVGSVGElement); const z = zoom() .scaleExtent(ZOOM_EXTENT) .on('start', this.onZoomStart) // Zoom will block mouse event. This avoids option panel getting stuck. .on('zoom', this.onZoom) .on('end', this.onZoomEnd) .filter(this.isZoomable); this.zoomBahavior = z; svg.call(z); this.setZoomTransform(); // Set the saved zoom transform to zoomBehavior } protected createInputPorts() { this.inputPorts = [ new SubsetInputPort({ data: { id: 'node', node: this, }, store: this.$store, }), new SubsetInputPort({ data: { id: 'edge', node: this, }, store: this.$store, }), ]; } protected createOutputPorts() { this.outputPorts = [ new SubsetOutputPort({ data: { id: 'nodeSelection', node: this, isSelection: true, }, store: this.$store, }), new SubsetOutputPort({ data: { id: 'node', node: this, }, store: this.$store, }), new SubsetOutputPort({ data: { id: 'edgeSelection', node: this, isSelection: true, }, store: this.$store, }), new SubsetOutputPort({ data: { id: 'edge', node: this, }, store: this.$store, }), ]; } protected draw() { if (this.nodeIdColumn === null || this.edgeSourceColumn === null || this.edgeTargetColumn === null) { this.coverText = 'Please select node/edge columns'; return; } this.coverText = ''; this.processNetwork(); this.computeProps(); this.drawNetwork(); this.startForce(); this.moveSelectedNodesAndEdgesToFront(); } protected brushed(brushPoints: Point[], isBrushStop?: boolean) { if (isBrushStop) { this.computeBrushedItems(brushPoints); this.onSelectionUpdate(); } drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []); } protected updateNoDatasetOutput() { this.outputPortMap.node.clear(); this.outputPortMap.nodeSelection.clear(); this.outputPortMap.edge.clear(); this.outputPortMap.edgeSelection.clear(); } protected computeForwarding() { this.forwardSubset(this.inputPortMap.node, this.outputPortMap.node); this.forwardSubset(this.inputPortMap.edge, this.outputPortMap.edge); } protected propagateSelection() { this.portUpdated(this.outputPortMap.nodeSelection); this.portUpdated(this.outputPortMap.edgeSelection); } protected computeSelection() { const nodePkg = this.inputPortMap.node.getSubsetPackage(); this.outputPortMap.nodeSelection.updatePackage(nodePkg.subset(this.nodeSelection.getItems())); const edgePkg = this.inputPortMap.edge.getSubsetPackage(); this.outputPortMap.edgeSelection.updatePackage(edgePkg.subset(this.edgeSelection.getItems())); } protected executeSelectAll() { const nodes = this.inputPortMap.node.getSubsetPackage().getItemIndices(); this.nodeSelection.addItems(nodes); const edges = this.inputPortMap.edge.getSubsetPackage().getItemIndices(); this.edgeSelection.addItems(edges); } protected executeDeselectAll() { this.nodeSelection.clear(); this.edgeSelection.clear(); } protected onSelectionUpdate() { this.computeProps(); this.drawNetwork(); this.computeSelection(); this.propagateSelection(); } protected recordPrevSelection() { this.prevNodeSelection = this.nodeSelection.clone(); this.prevEdgeSelection = this.edgeSelection.clone(); } protected commitSelectionHistory(message?: string) { this.commitHistory(history.interactiveSelectionEvent(this, { nodeSelection: this.nodeSelection, edgeSelection: this.edgeSelection }, { nodeSelection: this.prevNodeSelection, edgeSelection: this.prevEdgeSelection }, message, )); } protected isSelectionEmpty(): boolean { return !this.nodeSelection.numItems() && !this.edgeSelection.numItems(); } protected isDraggable(evt: MouseEvent, ui?: JQueryUI.DraggableEventUIParams) { if (this.isContentVisible && this.isNavigating) { return false; // If the network is in navigation mode, then node drag is disabled. } return this.isDraggableBase(evt); } protected isBrushable(): boolean { return !this.isNavigating; } protected onResize() { if (!this.hasNoDataset() && !this.isAnimating && this.isExpanded) { console.log('render', this.NODE_TYPE); // Do not call draw() which would restart force and reset transform. this.drawNetwork(); } } protected onEnlargeClose() { this.draw(); } private processNetwork() { this.validateNetwork(); this.processNodes(); this.processEdges(); } private validateNetwork() { const newNodes: Set<number> = new Set(this.inputPortMap.node.getSubsetPackage().getItemIndices()); const deletedNodes: Set<number> = new Set(); for (const index in this.nodes) { if (!newNodes.has(+index)) { deletedNodes.add(+index); delete this.nodes[index]; } } const newEdges: Set<number> = new Set(this.inputPortMap.edge.getSubsetPackage().getItemIndices()); for (const index in this.edges) { if (!newEdges.has(+index) || deletedNodes.has(this.edges[index].source.nodeIndex) || deletedNodes.has(this.edges[index].target.nodeIndex)) { delete this.edges[index]; } } } private processNodes() { // Eliminate randomness in initial layout. function* rand(): IterableIterator<number> { let randValue = 3; while (true) { randValue = randValue * 997 + 317; randValue %= 1003; yield randValue; } } const coordinate = rand(); const nodeDataset = this.getNodeDataset(); const pkg = this.inputPortMap.node.getSubsetPackage(); pkg.getItems().forEach(node => { const nodeIndex = node.index; const hasNode = nodeIndex in this.nodes; this.nodes[nodeIndex] = { nodeIndex, label: this.nodeLabelColumn !== null ? nodeDataset.getCell(nodeIndex, this.nodeLabelColumn).toString() : '', x: !hasNode ? coordinate.next().value % this.svgWidth : this.nodes[nodeIndex].x, y: !hasNode ? coordinate.next().value % this.svgHeight : this.nodes[nodeIndex].y, size: node.visuals.size || NODE_SIZE_PX, }; }); } private processEdges() { const nodeIdToIndex: { [id: string]: number } = {}; const nodeDataset = this.getNodeDataset(); _.each(this.nodes, node => { const id = nodeDataset.getCell(node.nodeIndex, this.nodeIdColumn as number).toString(); nodeIdToIndex[id] = node.nodeIndex; }); const pkg = this.inputPortMap.edge.getSubsetPackage(); const edgeDataset = this.getEdgeDataset(); pkg.getItemIndices().forEach(edgeIndex => { const sourceId = edgeDataset.getCell(edgeIndex, this.edgeSourceColumn as number); const targetId = edgeDataset.getCell(edgeIndex, this.edgeTargetColumn as number); const sourceIndex = nodeIdToIndex[sourceId]; const targetIndex = nodeIdToIndex[targetId]; if (sourceIndex === undefined || targetIndex === undefined || sourceIndex === targetIndex) { // The edge has undefined nodes, or it is self-loop, ignore. // TODO: display a warning in the option panel. delete this.edges[edgeIndex]; return; } this.edges[edgeIndex] = { edgeIndex, source: this.nodes[sourceIndex], target: this.nodes[targetIndex], }; }); } private computeProps() { this.computeNodeProps(); this.computeEdgeProps(); } private computeNodeProps() { const pkg = this.inputPortMap.node.getSubsetPackage(); const dataset = this.getNodeDataset(); this.nodeProps = _.toArray(this.nodes).map(node => { const index = node.nodeIndex; const visuals = pkg.getItem(index).visuals; const props: NetworkNodeProps = { index, label: this.nodeLabelColumn !== null ? dataset.getCell(index, this.nodeLabelColumn).toString() : '', hasVisuals: !_.isEmpty(visuals), visuals: _.extend({}, DEFAULT_NODE_VISUALS, visuals), selected: this.nodeSelection.hasItem(index), node, }; if (props.selected) { _.extend(props.visuals, SELECTED_NODE_VISUALS); multiplyVisuals(props.visuals); } return props; }); } private computeEdgeProps() { const pkg = this.inputPortMap.edge.getSubsetPackage(); this.edgeProps = _.toArray(this.edges).map(edge => { const index = edge.edgeIndex; const visuals = pkg.getItem(index).visuals; const props: NetworkEdgeProps = { index, hasVisuals: !_.isEmpty(visuals), visuals: _.extend({}, DEFAULT_EDGE_VISUALS, visuals), selected: this.edgeSelection.hasItem(index), source: edge.source, target: edge.target, }; if (props.selected) { _.extend(props.visuals, SELECTED_EDGE_VISUALS); multiplyVisuals(props.visuals); } return props; }); } /** * Network uses two-stage drawing. First stage is "append" that creates the elements on the canvas. The second stage * is "update" that sets the elements' properties. When forced, we call "update" methods. */ private drawNetwork() { this.appendNodes(); this.appendEdges(); this.appendNodeLabels(); this.updateNetwork(); } private appendNodes() { const nodes = select(this.$refs.nodes as SVGGElement).selectAll<SVGCircleElement, NetworkNodeProps>('circle') .data(this.nodeProps, d => d.index.toString()); nodes.enter().append('circle'); fadeOut(nodes.exit()); } private appendEdges() { const edges = select(this.$refs.edges as SVGGElement).selectAll<SVGGElement, NetworkEdgeProps>('g') .data(this.edgeProps, d => d.index.toString()); const enteredEdges = edges.enter().append('g'); enteredEdges.append('path').classed('edge', true); enteredEdges.append('path').classed('arrow', true); fadeOut(edges.exit()); } private appendNodeLabels() { if (this.nodeLabelColumn === null) { fadeOut(select(this.$refs.nodeLabels as SVGGElement).selectAll('*')); return; } const labels = select(this.$refs.nodeLabels as SVGGElement).selectAll<SVGTextElement, NetworkNodeProps>('text') .data(this.nodeProps, d => d.index.toString()); labels.enter().append('text'); fadeOut(labels.exit()); } private updateNetwork() { this.updateNodes(); this.updateEdges(); this.updateNodeLabels(); } private updateNodes() { const nodes = select(this.$refs.nodes as SVGGElement).selectAll<SVGCircleElement, NetworkNodeProps>('circle'); nodes .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected) .attr('transform', d => getTransform([d.node.x, d.node.y])) .attr('r', d => (d.visuals.size as number / 2) / this.zoomScale) .style('stroke', d => d.visuals.border as string) .style('stroke-width', d => (d.visuals.width as number) / this.zoomScale + 'px') .style('fill', d => d.visuals.color as string) .style('opacity', d => d.visuals.opacity as number); } /** * Creates a shifted point around the middle of the edge to be the control * point of the edge's curve. */ private getShiftPoint(p: Victor, q: Victor): Victor { const m = p.clone().add(q).multiplyScalar(.5); let d = p.clone().subtract(q); d = new Victor(-d.y, d.x).normalize().multiplyScalar(d.length() * EDGE_CURVE_SHIFT); return m.add(d); } private updateEdges() { const edges = select(this.$refs.edges as SVGGElement).selectAll<SVGGElement, NetworkEdgeProps>('g') .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); // Creates a stroke that looks like an arrow. const getArrowPoints = (p: Victor, q: Victor): Victor[] => { const m = this.getShiftPoint(p, q); const ds = p.clone().subtract(q).normalize(); const dm = m.clone().subtract(q).normalize(); const p1 = q.clone().add(dm.multiplyScalar(NODE_SIZE_PX / this.zoomScale)); const p2 = p1.clone().add(ds.multiplyScalar(EDGE_ARROW_LENGTH / this.zoomScale)); const p3 = mirrorPoint(p2, p1, m); return [p1, p2, p3]; }; const dCurve = line<Victor>().curve(curveBasis).x(d => d.x).y(d => d.y); edges.select<SVGPathElement>('path.edge') .style('stroke', d => d.visuals.color as string) .style('stroke-width', d => (d.visuals.width as number) / this.zoomScale + 'px') .style('opacity', d => d.visuals.opacity as number) .attr('d', d => { const s = new Victor(d.source.x, d.source.y); const t = new Victor(d.target.x, d.target.y); return dCurve([s, this.getShiftPoint(s, t), t]); }); const dLine = line<Victor>().curve(curveLinearClosed).x(d => d.x).y(d => d.y); edges.select<SVGPathElement>('path.arrow') .style('stroke', d => d.visuals.color as string) .style('stroke-width', d => (d.visuals.width as number) / this.zoomScale + 'px') .style('fill', d => d.visuals.color as string) .style('opacity', d => d.visuals.opacity as number) .attr('d', d => dLine(getArrowPoints(new Victor(d.source.x, d.source.y), new Victor(d.target.x, d.target.y)))); } private updateNodeLabels() { if (this.nodeLabelColumn === null) { return; } const labels = select(this.$refs.nodeLabels as SVGGElement).selectAll<SVGTextElement, NetworkNodeProps>('text'); labels .text(d => d.label) .style('font-size', () => NODE_LABEL_SIZE_PX / this.zoomScale) .attr('transform', d => getTransform([ d.node.x + (d.visuals.size as number / 2 || 0) + NODE_LABEL_X_OFFSET_PX / this.zoomScale, d.node.y + (d.visuals.size as number / 2 || 0) + NODE_LABEL_Y_OFFSET_PX / this.zoomScale, ])); } private startForce() { if (this.force) { this.force.stop(); } this.force = forceSimulation(_.toArray(this.nodes)) .force('link', forceLink(_.toArray(this.edges)).distance(this.linkDistance)) .force('charge', forceManyBody()) .force('center', forceCenter(this.svgWidth / 2, this.svgHeight / 2)) .velocityDecay(FORCE_FRICTION) .on('tick', this.updateNetwork) .restart(); } private isZoomable() { if (d3Event.type === 'wheel') { return true; } return this.isNavigating; } private onZoomStart() { if (!d3Event.sourceEvent) { return; } this.zoomStartPosition = { x: d3Event.sourceEvent.pageX, y: d3Event.sourceEvent.pageY, }; } private onZoom() { const transform: { x: number, y: number, k: number } = d3Event.transform; const translate: [number, number] = [transform.x, transform.y]; const scale = transform.k; this.zoomScale = scale; this.zoomTranslate = translate; this.applyZoomTransform(); // Update the network the scale stroke width and text size proportionally. this.updateNetwork(); } private onZoomEnd() { if (!d3Event.sourceEvent) { return; } const [x, y] = [ d3Event.sourceEvent.pageX, d3Event.sourceEvent.pageY, ]; const distance = Math.abs(x - this.zoomStartPosition.x) + Math.abs(y - this.zoomStartPosition.y); if (distance < ZOOM_DISTANCE_THRESHOLD) { // If the user clicks the node, it is not a valid zoom and we call the click handler to respond to // node selection correctly. this.onClick(d3Event.sourceEvent); } else { this.select(); // Regardless, zooming always selects the node. } } private computeBrushedItems(brushPoints: Point[]) { if (!this.isShiftPressed || !brushPoints.length) { this.nodeSelection.clear(); this.edgeSelection.clear(); if (!brushPoints.length) { return; } } // Applies the current zoom transform to a cooridnate. const applyTransform = (x: number, y: number): Point => { return { x: x * this.zoomScale + this.zoomTranslate[0], y: y * this.zoomScale + this.zoomTranslate[1], }; }; const box = getBrushBox(brushPoints); _.each(this.nodes, node => { const point = applyTransform(node.x, node.y); const clickToNodeDistance = new Victor(point.x, point.y).subtract(new Victor(box.x, box.y)).length(); if (isPointInBox(point, box) || clickToNodeDistance <= node.size / 2 * this.zoomScale) { this.nodeSelection.addItem(node.nodeIndex); } }); const boxPoints = [ { x: box.x, y: box.y }, { x: box.x + box.width, y: box.y }, { x: box.x + box.width, y: box.y + box.height}, { x: box.x, y: box.y + box.height}, ]; // Check box intersecting with straight line segment. // Note: curve is drawn slightly curved but intersection check does not consider curves. _.each(this.edges, edge => { const p = applyTransform(edge.source.x, edge.source.y); const q = applyTransform(edge.target.x, edge.target.y); const m = new Victor(p.x + q.x, p.y + q.y).multiplyScalar(.5); for (let i = 0; i < 4; i++) { if (areSegmentsIntersected(p, m, boxPoints[i], boxPoints[(i + 1) % 4]) || areSegmentsIntersected(m, q, boxPoints[i], boxPoints[(i + 1) % 4])) { this.edgeSelection.addItem(edge.edgeIndex); return; } } }); } private moveSelectedNodesAndEdgesToFront() { const $nodes = $(this.$refs.nodes as SVGGElement); $nodes.children('circle[has-visuals=true]').appendTo(this.$refs.nodes as SVGGElement); $nodes.children('circle[is-selected=true]').appendTo(this.$refs.nodes as SVGGElement); const $edges = $(this.$refs.edges as SVGGElement); $edges.children('g[has-visuals=true]').appendTo(this.$refs.edges as SVGGElement); $edges.children('g[is-selected=true]').appendTo(this.$refs.edges as SVGGElement); } private getNodeDataset(): TabularDataset { return this.nodeDataset as TabularDataset; } private getEdgeDataset(): TabularDataset { return this.edgeDataset as TabularDataset; } private toggleNavigating() { this.isNavigating = !this.isNavigating; } /** * Applies the current zoom transform. */ private setZoomTransform() { if (!this.zoomBahavior) { return; } select<Element, {}>(this.$refs.svg as SVGSVGElement) .call(this.zoomBahavior.transform, zoomIdentity.translate(this.zoomTranslate[0], this.zoomTranslate[1]).scale(this.zoomScale)); } /** * Applies the zoom transform on all child render groups (nodes, edges, node labels). */ private applyZoomTransform() { select(this.$refs.svg as SVGSVGElement).selectAll('.zoom-group') .attr('transform', getTransform(this.zoomTranslate, this.zoomScale)); } private resetTransform() { this.zoomScale = 1; this.zoomTranslate = [0, 0]; this.setZoomTransform(); this.applyZoomTransform(); } @Watch('isNavigating') private onNavigatingChange() { if (this.isNavigating) { this.setZoomTransform(); } } private onInputNodeIdColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectNodeIdColumnEvent(this, column, prevColumn)); this.draw(); } private onInputEdgeSourceColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectEdgeSourceColumnEvent(this, column, prevColumn)); this.draw(); } private onInputEdgeTargetColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectEdgeTargetColumnEvent(this, column, prevColumn)); this.draw(); } private onInputNodeLabelColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectNodeLabelColumnEvent(this, column, prevColumn)); this.computeProps(); this.drawNetwork(); } private onInputLinkDistance(value: number, prevValue: number) { this.commitHistory(history.inputLinkDistanceEvent(this, value, prevValue)); this.drawNetwork(); } private onChangeLinkDistance(value: number, prevValue: number) { this.linkDistance = value; if (this.force) { this.startForce(); } } private onToggleNavigating(value: boolean) { this.commitHistory(history.toggleNavigatingEvent(this, value)); } }
the_stack
import { Injectable } from '@angular/core'; import { Cordova, AwesomeCordovaNativePlugin, Plugin } from '@awesome-cordova-plugins/core'; import { Observable } from 'rxjs'; export enum BackgroundGeolocationLocationCode { PERMISSION_DENIED = 1, LOCATION_UNAVAILABLE = 2, TIMEOUT = 3, } export enum BackgroundGeolocationNativeProvider { gps = 'gps', network = 'network', passive = 'passive', fused = 'fused', } export enum BackgroundGeolocationLocationProvider { DISTANCE_FILTER_PROVIDER = 0, ACTIVITY_PROVIDER = 1, RAW_PROVIDER = 2, } export enum BackgroundGeolocationEvents { http_authorization = 'http_authorization', // Triggered when server responded with "<code>401 Unauthorized</code>" to post/sync request. abort_requested = 'abort_requested', // Triggered when server responded with "<code>285 Updates Not Required</code>" to post/sync request. background = 'background', // Triggered when app entered background state and (not visible to the user). foreground = 'foreground', // Triggered when app entered foreground state and (visible to the user). authorization = 'authorization', // Triggered when user changes authorization/permissions for the app or toggles location services. error = 'error', // Register error listener. stop = 'stop', // Triggered when background service has been stopped succesfully. start = 'start', // Event is triggered when background service has been started succesfully. activity = 'activity', // Register activity monitoring listener. stationary = 'stationary', // Register stationary location event listener. location = 'location', // Register location event listener. } export enum BackgroundGeolocationAuthorizationStatus { NOT_AUTHORIZED = 0, AUTHORIZED = 1, AUTHORIZED_FOREGROUND = 2, } export enum BackgroundGeolocationLogLevel { TRACE = 'TRACE', DEBUG = 'DEBUG', INFO = 'INFO', WARN = 'WARN', ERROR = 'ERROR', } export interface BackgroundGeolocationLogEntry { /** ID of log entry as stored in db. */ id: number; /** Timestamp in milliseconds since beginning of UNIX epoch. */ timestamp: number; /** Log level */ level: BackgroundGeolocationLogLevel; /** Log message */ message: string; /** Recorded stacktrace. (Android only, on iOS part of message) */ stackTrace: string; } export interface ServiceStatus { /** TRUE if service is running. */ isRunning: boolean; /** TRUE if location services are enabled */ locationServicesEnabled: boolean; /** * Authorization status. * * Posible values: * NOT_AUTHORIZED, AUTHORIZED, AUTHORIZED_FOREGROUND * * @example * if (authorization == BackgroundGeolocation.NOT_AUTHORIZED) {...} */ authorization: BackgroundGeolocationAuthorizationStatus; } export interface BackgroundGeolocation { code: BackgroundGeolocationLocationCode; message: string; } export interface BackgroundGeolocationCurrentPositionConfig { timeout: number; maximumAge: number; enableHighAccuracy: boolean; } export interface BackgroundGeolocationResponse { /** ID of location as stored in DB (or null) */ id: number; /** * Native provider reponsible for location. * * Possible values: * "gps", "network", "passive" or "fused" */ provider: BackgroundGeolocationNativeProvider; /** Configured location provider. */ locationProvider: BackgroundGeolocationLocationProvider; /** UTC time of this fix, in milliseconds since January 1, 1970. */ time: number; /** Latitude, in degrees. */ latitude: number; /** Longitude, in degrees. */ longitude: number; /** Estimated accuracy of this location, in meters. */ accuracy: number; /** * Speed if it is available, in meters/second over ground. * * Note: Not all providers are capable of providing speed. * Typically network providers are not able to do so. */ speed: number; /** Altitude if available, in meters above the WGS 84 reference ellipsoid. */ altitude: number; /** Bearing, in degrees. */ bearing: number; /** * True if location was recorded by mock provider. (ANDROID ONLY) * * Note: this property is not enabled by default! * You can enable it "postTemplate" configure option. */ isFromMockProvider?: boolean; /** * True if device has mock locations enabled. (ANDROID ONLY) * * Note: this property is not enabled by default! * You can enable it "postTemplate" configure option. */ mockLocationsEnabled?: boolean; } export interface BackgroundGeolocationConfig { /** * Set location provider * * Platform: all * Available providers: * DISTANCE_FILTER_PROVIDER, * ACTIVITY_PROVIDER * RAW_PROVIDER * * @default DISTANCE_FILTER_PROVIDER * @example * { locationProvider: LocationProvider.RAW_PROVIDER } */ locationProvider?: number; /** * Desired accuracy in meters. * * Platform: all * Provider: all * Possible values: * HIGH_ACCURACY, * MEDIUM_ACCURACY, * LOW_ACCURACY, * PASSIVE_ACCURACY * Note: Accuracy has direct effect on power drain. Lower accuracy = lower power drain. * * @default MEDIUM_ACCURACY * @example * { desiredAccuracy: BackgroundGeolocationAccuracy.LOW } */ desiredAccuracy?: number; /** * Stationary radius in meters. * * When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage. * Platform: all * Provider: DISTANCE_FILTER * * @default 50 */ stationaryRadius?: number; /** * When enabled, the plugin will emit sounds for life-cycle events of background-geolocation! See debugging sounds table. * * Platform: all * Provider: all * * @default false */ debug?: boolean; /** * The minimum distance (measured in meters) a device must move horizontally before an update event is generated. * * Platform: all * Provider: DISTANCE_FILTER, RAW * * @default 500 * @see {@link https://apple.co/2oHo2CV|Apple docs} */ distanceFilter?: number; /** * Enable this in order to force a stop() when the application terminated. * E.g. on iOS, double-tap home button, swipe away the app. * * Platform: all * Provider: all * * @default true */ stopOnTerminate?: boolean; /** * Start background service on device boot. * * Platform: Android * Provider: all * * @default false */ startOnBoot?: boolean; /** * The minimum time interval between location updates in milliseconds. * * Platform: Android * Provider: all * * @default 60000 * @see {@link https://bit.ly/1x00RUu|Android docs} */ interval?: number; /** * Fastest rate in milliseconds at which your app can handle location updates. * * Platform: Android * Provider: ACTIVITY * * @default 120000 * @see {@link https://bit.ly/1x00RUu|Android docs} */ fastestInterval?: number; /** * Rate in milliseconds at which activity recognition occurs. * Larger values will result in fewer activity detections while improving battery life. * * Platform: Android * Provider: ACTIVITY * * @default 10000 */ activitiesInterval?: number; /** * @deprecated Stop location updates, when the STILL activity is detected. */ stopOnStillActivity?: boolean; /** * Enable/disable local notifications when tracking and syncing locations. * * Platform: Android * Provider: all * * @default true */ notificationsEnabled?: boolean; /** * Allow location sync service to run in foreground state. * Foreground state also requires a notification to be presented to the user. * * Platform: Android * Provider: all * * @default false */ startForeground?: boolean; /** * Custom notification title in the drawer. * * Platform: Android * Provider: all * * @default "Background tracking" */ notificationTitle?: string; /** * Custom notification text in the drawer. * * Platform: Android * Provider: all * * @default "ENABLED" */ notificationText?: string; /** * The accent color (hex triplet) to use for notification. * Eg. <code>#4CAF50</code>. * * Platform: Android * Provider: all */ notificationIconColor?: string; /** * The filename of a custom notification icon. * * Platform: Android * Provider: all */ notificationIconLarge?: string; /** * The filename of a custom notification icon. * * Platform: Android * Provider: all */ notificationIconSmall?: string; /** * Activity type. * Presumably, this affects iOS GPS algorithm. * * Possible values: * "AutomotiveNavigation", "OtherNavigation", "Fitness", "Other" * * Platform: iOS * Provider: all * * @default "OtherNavigation" * @see {@link https://apple.co/2oHofpH|Apple docs} */ activityType?: string; /** * Pauses location updates when app is paused. * * Platform: iOS * Provider: all * * @default false * @see {@link https://apple.co/2CbjEW2|Apple docs} */ pauseLocationUpdates?: boolean; /** * Switch to less accurate significant changes and region monitory when in background. * * Platform: iOS * Provider: all * * @default false */ saveBatteryOnBackground?: boolean; /** * Server url where to send HTTP POST with recorded locations * * Platform: all * Provider: all */ url?: string; /** * Server url where to send fail to post locations * * Platform: all * Provider: all */ syncUrl?: string; /** * Specifies how many previously failed locations will be sent to server at once. * * Platform: all * Provider: all * * @default 100 */ syncThreshold?: number; /** * Optional HTTP headers sent along in HTTP request. * * Platform: all * Provider: all */ httpHeaders?: any; /** * Limit maximum number of locations stored into db. * * Platform: all * Provider: all * * @default 10000 */ maxLocations?: number; /** * Customization post template. * * Platform: all * Provider: all */ postTemplate?: any; } /** * Set location service provider @see https://github.com/mauron85/cordova-plugin-background-geolocation/wiki/Android-providers * * Possible values: * ANDROID_DISTANCE_FILTER_PROVIDER: 0, * ANDROID_ACTIVITY_PROVIDER: 1 * * @enum {number} */ export declare enum BackgroundGeolocationProvider { ANDROID_DISTANCE_FILTER_PROVIDER = 0, ANDROID_ACTIVITY_PROVIDER = 1, } /** * Desired accuracy in meters. Possible values [0, 10, 100, 1000]. * The lower the number, the more power devoted to GeoLocation resulting in higher accuracy readings. * 1000 results in lowest power drain and least accurate readings. * * Possible values: * HIGH: 0 * MEDIUM: 10 * LOW: 100 * PASSIVE: 1000 * * enum {number} */ export declare enum BackgroundGeolocationAccuracy { HIGH = 0, MEDIUM = 10, LOW = 100, PASSIVE = 1000, } /** * Used in the switchMode function * * Possible values: * BACKGROUND: 0 * FOREGROUND: 1 * * @enum {number} */ export declare enum BackgroundGeolocationMode { BACKGROUND = 0, FOREGROUND = 1, } export declare enum BackgroundGeolocationIOSActivity { AutomotiveNavigation = 'AutomotiveNavigation', OtherNavigation = 'OtherNavigation', Fitness = 'Fitness', Other = 'Other', } /** * @name Background Geolocation * @description * This plugin provides foreground and background geolocation with battery-saving "circular region monitoring" and "stop detection". For * more detail, please see https://github.com/mauron85/cordova-plugin-background-geolocation * @usage * * BackgroundGeolocation must be called within app.ts and or before Geolocation. Otherwise the platform will not ask you for background tracking permission. * * ```typescript * import { BackgroundGeolocation, BackgroundGeolocationConfig, BackgroundGeolocationEvents, BackgroundGeolocationResponse } from '@awesome-cordova-plugins/background-geolocation/ngx'; * * constructor(private backgroundGeolocation: BackgroundGeolocation) { } * * ... * * const config: BackgroundGeolocationConfig = { * desiredAccuracy: 10, * stationaryRadius: 20, * distanceFilter: 30, * debug: true, // enable this hear sounds for background-geolocation life-cycle. * stopOnTerminate: false, // enable this to clear background location settings when the app terminates * }; * * this.backgroundGeolocation.configure(config) * .then(() => { * * this.backgroundGeolocation.on(BackgroundGeolocationEvents.location).subscribe((location: BackgroundGeolocationResponse) => { * console.log(location); * * // IMPORTANT: You must execute the finish method here to inform the native plugin that you're finished, * // and the background-task may be completed. You must do this regardless if your operations are successful or not. * // IF YOU DON'T, ios will CRASH YOUR APP for spending too much time in the background. * this.backgroundGeolocation.finish(); // FOR IOS ONLY * }); * * }); * * // start recording location * this.backgroundGeolocation.start(); * * // If you wish to turn OFF background-tracking, call the #stop method. * this.backgroundGeolocation.stop(); * * ``` * @interfaces * BackgroundGeolocationResponse * BackgroundGeolocationConfig */ @Plugin({ pluginName: 'BackgroundGeolocation', plugin: '@mauron85/cordova-plugin-background-geolocation', pluginRef: 'BackgroundGeolocation', repo: 'https://github.com/mauron85/cordova-plugin-background-geolocation', platforms: ['Android', 'iOS'], }) @Injectable() export class BackgroundGeolocation extends AwesomeCordovaNativePlugin { /** * Configure the plugin. * * @param options {BackgroundGeolocationConfig} options An object of type Config * @returns {Promise<any>} */ @Cordova() configure(options: BackgroundGeolocationConfig): Promise<any> { return; } /** * Turn ON the background-geolocation system. * The user will be tracked whenever they suspend the app. * * @returns {Promise<any>} */ @Cordova() start(): Promise<any> { return; } /** * Turn OFF background-tracking * * @returns {Promise<any>} */ @Cordova() stop(): Promise<any> { return; } /** * Inform the native plugin that you're finished, the background-task may be completed * * @returns {Promise<any>} */ @Cordova({ platforms: ['iOS'], }) finish(): Promise<any> { return; } /** * Force the plugin to enter "moving" or "stationary" state * * @param isMoving {boolean} * @returns {Promise<any>} */ @Cordova({ platforms: ['iOS'], }) changePace(isMoving: boolean): Promise<any> { return; } /** * Setup configuration * * @param options {BackgroundGeolocationConfig} * @returns {Promise<any>} */ @Cordova({ callbackOrder: 'reverse', }) setConfig(options: BackgroundGeolocationConfig): Promise<any> { return; } /** * Returns current stationaryLocation if available. null if not * * @returns {Promise<Location>} */ @Cordova({ platforms: ['iOS'], }) getStationaryLocation(): Promise<BackgroundGeolocationResponse> { return; } /** * Add a stationary-region listener. Whenever the devices enters "stationary-mode", * your #success callback will be executed with #location param containing #radius of region * * @returns {Promise<any>} */ @Cordova({ platforms: ['iOS'], }) onStationary(): Promise<any> { return; } /** * Check if location is enabled on the device * * @returns {Promise<number>} Returns a promise with int argument that takes values 0, 1 (true). */ @Cordova({ platforms: ['Android'], }) isLocationEnabled(): Promise<number> { return; } /** * Display app settings to change permissions */ @Cordova({ sync: true }) showAppSettings(): void {} /** * Display device location settings */ @Cordova({ sync: true }) showLocationSettings(): void {} /** * Method can be used to detect user changes in location services settings. * If user enable or disable location services then success callback will be executed. * In case or (SettingNotFoundException) fail callback will be executed. * * @returns {Observable<number>} */ @Cordova({ platforms: ['Android'], observable: true, }) watchLocationMode(): Observable<number> { return; } /** * Stop watching for location mode changes. * * @returns {Promise<any>} */ @Cordova({ platforms: ['Android'], }) stopWatchingLocationMode(): Promise<any> { return; } /** * Method will return all stored locations. * Locations are stored when: * - config.stopOnTerminate is false and main activity was killed * by the system * or * - option.debug is true * * @returns {Promise<any>} */ @Cordova({ platforms: ['Android'], }) getLocations(): Promise<any> { return; } /** * Method will return locations, which has not been yet posted to server. NOTE: Locations does contain locationId. * * @returns {Promise<any>} */ @Cordova() getValidLocations(): Promise<any> { return; } /** * Delete stored location by given locationId. * * @param locationId {number} * @returns {Promise<any>} */ @Cordova({ platforms: ['Android'], }) deleteLocation(locationId: number): Promise<any> { return; } /** * Delete all stored locations. * * @returns {Promise<any>} */ @Cordova({ platforms: ['Android'], }) deleteAllLocations(): Promise<any> { return; } /** * Normally plugin will handle switching between BACKGROUND and FOREGROUND mode itself. * Calling switchMode you can override plugin behavior and force plugin to switch into other mode. * * In FOREGROUND mode plugin uses iOS local manager to receive locations and behavior is affected by option.desiredAccuracy and option.distanceFilter. * In BACKGROUND mode plugin uses significant changes and region monitoring to receive locations and uses option.stationaryRadius only. * * BackgroundGeolocation.Mode.FOREGROUND * BackgroundGeolocation.Mode.BACKGROUND * * @param modeId {number} * @returns {Promise<any>} */ @Cordova({ platforms: ['iOS'], }) switchMode(modeId: number): Promise<any> { return; } /** * Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries. * * @see https://github.com/mauron85/cordova-plugin-background-geolocation/tree/v2.2.1#debugging for more information. * @param fromId * @param minLevel * @param limit {number} Limits the number of entries * @returns {Promise<any>} */ @Cordova() getLogEntries( limit: number, fromId: number, minLevel: BackgroundGeolocationLogLevel ): Promise<BackgroundGeolocationLogEntry[]> { return; } /** * Return all logged events. Useful for plugin debugging. Parameter limit limits number of returned entries. * * @see https://github.com/mauron85/cordova-plugin-background-geolocation/tree/v2.2.1#debugging for more information. * @returns {Promise<any>} */ @Cordova() getConfig(): Promise<any> { return; } /** * One time location check to get current location of the device. * {timeout: Maximum time in milliseconds device will wait for location, * maximumAge: Maximum age in milliseconds of a possible cached location that is acceptable to return; * enableHighAccuracy: if true and if the device is able to provide a more accurate position, it will do so} * * @param {BackgroundGeolocationCurrentPositionConfig} options * @returns {Promise<any>} */ @Cordova({ callbackOrder: 'reverse', }) getCurrentLocation(options?: BackgroundGeolocationCurrentPositionConfig): Promise<BackgroundGeolocationResponse> { return; } /** * Check status of the service */ @Cordova() checkStatus(): Promise<ServiceStatus> { return; } /** * Start background task (iOS only) * * To perform any long running operation on iOS * you need to create background task * IMPORTANT: task has to be ended by endTask * * @returns {Promise<number>} taskKey */ @Cordova({ platforms: ['IOS'], }) startTask(): Promise<number> { return; } /** * End background task indentified by taskKey (iOS only) * * @param taskKey */ @Cordova({ platforms: ['IOS'], }) endTask(taskKey: number): Promise<any> { return; } /** * A special task that gets executed when the app is terminated, but * the plugin was configured to continue running in the background * (option <code>stopOnTerminate: false</code>). * * In this scenario the Activity was killed by the system and all registered * event listeners will not be triggered until the app is relaunched. * * @example * BackgroundGeolocation.headlessTask(function(event) { * * if (event.name === 'location' || event.name === 'stationary') { * var xhr = new XMLHttpRequest(); * xhr.open('POST', 'http://192.168.81.14:3000/headless'); * xhr.setRequestHeader('Content-Type', 'application/json'); * xhr.send(JSON.stringify(event.params)); * } * * return 'Processing event: ' + event.name; // will be logged * }); * @param func */ @Cordova() headlessTask(func: any): Promise<any> { return; } /** * Force sync of pending locations. * Option <code>syncThreshold</code> will be ignored and all pending locations will be immediately posted to <code>syncUrl</code> in single batch. * * Platform: Android, iOS */ @Cordova() forceSync(): Promise<any> { return; } /** * Register event listener. * * Triggered when server responded with "<code>285 Updates Not Required</code>" to post/sync request. * * @param event * @param callbackFn */ @Cordova({ observable: true, }) on(event: BackgroundGeolocationEvents): Observable<BackgroundGeolocationResponse> { return; } /** * Unregister all event listeners for given event. * * If parameter <code>event</code> is not provided then all event listeners will be removed. * * @param event */ @Cordova() removeAllListeners(event?: BackgroundGeolocationEvents): Promise<any> { return; } }
the_stack
import LRUCache from 'lru-cache'; import * as vscode from 'vscode'; import { Repository } from '../api/api'; import { GitApiImpl } from '../api/api1'; import { parseRepositoryRemotes } from '../common/remote'; import { AuthProvider } from '../github/credentials'; import { FolderRepositoryManager, NO_MILESTONE, PullRequestDefaults, ReposManagerState, } from '../github/folderRepositoryManager'; import { IAccount } from '../github/interface'; import { IssueModel } from '../github/issueModel'; import { MilestoneModel } from '../github/milestoneModel'; import { RepositoriesManager } from '../github/repositoriesManager'; import { CurrentIssue } from './currentIssue'; import { BRANCH_CONFIGURATION, DEFAULT_QUERY_CONFIGURATION, getIssueNumberLabel, ISSUES_CONFIGURATION, QUERIES_CONFIGURATION, variableSubstitution, } from './util'; // TODO: make exclude from date words configurable const excludeFromDate: string[] = ['Recovery']; const CURRENT_ISSUE_KEY = 'currentIssue'; const ISSUES_KEY = 'issues'; const IGNORE_MILESTONES_CONFIGURATION = 'ignoreMilestones'; export interface IssueState { branch?: string; hasDraftPR?: boolean; } interface TimeStampedIssueState extends IssueState { stateModifiedTime: number; } interface IssuesState { issues: Record<string, TimeStampedIssueState>; branches: Record<string, { owner: string; repositoryName: string; number: number }>; } const DEFAULT_QUERY_CONFIGURATION_VALUE = [{ label: 'My Issues', query: 'default' }]; export interface MilestoneItem extends MilestoneModel { uri: vscode.Uri; } export class IssueItem extends IssueModel { uri: vscode.Uri; } interface SingleRepoState { lastHead?: string; lastBranch?: string; currentIssue?: CurrentIssue; issueCollection: Map<string, Promise<MilestoneItem[] | IssueItem[]>>; maxIssueNumber: number; userMap?: Promise<Map<string, IAccount>>; folderManager: FolderRepositoryManager; } export class StateManager { public readonly resolvedIssues: Map<string, LRUCache<string, IssueModel>> = new Map(); private _singleRepoStates: Map<string, SingleRepoState | undefined> = new Map(); private _onRefreshCacheNeeded: vscode.EventEmitter<void> = new vscode.EventEmitter(); public onRefreshCacheNeeded: vscode.Event<void> = this._onRefreshCacheNeeded.event; private _onDidChangeIssueData: vscode.EventEmitter<void> = new vscode.EventEmitter(); public onDidChangeIssueData: vscode.Event<void> = this._onDidChangeIssueData.event; private _queries: { label: string; query: string }[] = []; private _onDidChangeCurrentIssue: vscode.EventEmitter<void> = new vscode.EventEmitter(); public readonly onDidChangeCurrentIssue: vscode.Event<void> = this._onDidChangeCurrentIssue.event; private initializePromise: Promise<void> | undefined; private statusBarItem?: vscode.StatusBarItem; getIssueCollection(uri: vscode.Uri): Map<string, Promise<MilestoneItem[] | IssueItem[]>> { let collection = this._singleRepoStates.get(uri.path)?.issueCollection; if (collection) { return collection; } else { collection = new Map(); return collection; } } constructor( readonly gitAPI: GitApiImpl, private manager: RepositoriesManager, private context: vscode.ExtensionContext, ) { manager.folderManagers.forEach(folderManager => { this.context.subscriptions.push(folderManager.onDidChangeRepositories(() => this.refresh())); }); } private getOrCreateSingleRepoState(uri: vscode.Uri, folderManager?: FolderRepositoryManager): SingleRepoState { let state = this._singleRepoStates.get(uri.path); if (state) { return state; } if (!folderManager) { folderManager = this.manager.getManagerForFile(uri)!; } state = { issueCollection: new Map(), maxIssueNumber: 0, folderManager, }; this._singleRepoStates.set(uri.path, state); return state; } async tryInitializeAndWait() { if (!this.initializePromise) { this.initializePromise = new Promise(resolve => { if (this.manager.state === ReposManagerState.RepositoriesLoaded) { this.doInitialize(); resolve(); } else { const disposable = this.manager.onDidChangeState(() => { if (this.manager.state === ReposManagerState.RepositoriesLoaded) { this.doInitialize(); disposable.dispose(); resolve(); } }); this.context.subscriptions.push(disposable); } }); } return this.initializePromise; } private registerRepositoryChangeEvent() { async function updateRepository(that: StateManager, repository: Repository) { const state = that.getOrCreateSingleRepoState(repository.rootUri); // setIssueData can cause the last head and branch state to change. Capture them before that can happen. const oldHead = state.lastHead; const oldBranch = state.lastBranch; const newHead = repository.state.HEAD ? repository.state.HEAD.commit : undefined; if ((repository.state.HEAD ? repository.state.HEAD.commit : undefined) !== oldHead) { await that.setIssueData(state.folderManager); } const newBranch = repository.state.HEAD?.name; if ( (oldHead !== newHead || oldBranch !== newBranch) && (!state.currentIssue || newBranch !== state.currentIssue.branchName) ) { if (newBranch) { if (state.folderManager) { await that.setCurrentIssueFromBranch(state, newBranch); } } else { await that.setCurrentIssue(state, undefined); } } state.lastHead = repository.state.HEAD ? repository.state.HEAD.commit : undefined; state.lastBranch = repository.state.HEAD ? repository.state.HEAD.name : undefined; } function addChangeEvent(that: StateManager, repository: Repository) { that.context.subscriptions.push( repository.state.onDidChange(async () => { updateRepository(that, repository); }), ); } this.context.subscriptions.push(this.gitAPI.onDidOpenRepository(repository => { updateRepository(this, repository); addChangeEvent(this, repository); })); this.gitAPI.repositories.forEach(repository => { addChangeEvent(this, repository); }); } refreshCacheNeeded() { this._onRefreshCacheNeeded.fire(); } async refresh() { return this.setAllIssueData(); } private async doInitialize() { this.cleanIssueState(); this._queries = vscode.workspace .getConfiguration(ISSUES_CONFIGURATION) .get(QUERIES_CONFIGURATION, DEFAULT_QUERY_CONFIGURATION_VALUE); if (this._queries.length === 0) { this._queries = DEFAULT_QUERY_CONFIGURATION_VALUE; } this.context.subscriptions.push( vscode.workspace.onDidChangeConfiguration(change => { if (change.affectsConfiguration(`${ISSUES_CONFIGURATION}.${QUERIES_CONFIGURATION}`)) { this._queries = vscode.workspace .getConfiguration(ISSUES_CONFIGURATION) .get(QUERIES_CONFIGURATION, DEFAULT_QUERY_CONFIGURATION_VALUE); this._onRefreshCacheNeeded.fire(); } else if (change.affectsConfiguration(`${ISSUES_CONFIGURATION}.${IGNORE_MILESTONES_CONFIGURATION}`)) { this._onRefreshCacheNeeded.fire(); } }), ); this.registerRepositoryChangeEvent(); await this.setAllIssueData(); this.context.subscriptions.push( this.onRefreshCacheNeeded(async () => { await this.refresh(); }), ); for (const folderManager of this.manager.folderManagers) { const singleRepoState: SingleRepoState = this.getOrCreateSingleRepoState( folderManager.repository.rootUri, folderManager, ); singleRepoState.lastHead = folderManager.repository.state.HEAD ? folderManager.repository.state.HEAD.commit : undefined; this._singleRepoStates.set(folderManager.repository.rootUri.path, singleRepoState); const branch = folderManager.repository.state.HEAD?.name; if (!singleRepoState.currentIssue && branch) { await this.setCurrentIssueFromBranch(singleRepoState, branch); } } } private cleanIssueState() { const stateString: string | undefined = this.context.workspaceState.get(ISSUES_KEY); const state: IssuesState = stateString ? JSON.parse(stateString) : { issues: [], branches: [] }; const deleteDate: number = new Date().valueOf() - 30 /*days*/ * 86400000 /*milliseconds in a day*/; for (const issueState in state.issues) { if (state.issues[issueState].stateModifiedTime < deleteDate) { if (state.branches && state.branches[issueState]) { delete state.branches[issueState]; } delete state.issues[issueState]; } } } private async getUsers(uri: vscode.Uri): Promise<Map<string, IAccount>> { await this.initializePromise; const assignableUsers = await this.manager.getManagerForFile(uri)?.getAssignableUsers(); const userMap: Map<string, IAccount> = new Map(); for (const remote in assignableUsers) { assignableUsers[remote].forEach(account => { userMap.set(account.login, account); }); } return userMap; } getUserMap(uri: vscode.Uri): Promise<Map<string, IAccount>> { if (!this.initializePromise) { return Promise.resolve(new Map()); } const state = this.getOrCreateSingleRepoState(uri); if (!state.userMap) { state.userMap = this.getUsers(uri); } return state.userMap; } private async getCurrentUser(authProviderId: AuthProvider): Promise<string | undefined> { return this.manager.credentialStore.getCurrentUser(authProviderId)?.login; } private async setAllIssueData() { return Promise.all(this.manager.folderManagers.map(folderManager => this.setIssueData(folderManager))); } private async setIssueData(folderManager: FolderRepositoryManager) { const singleRepoState = this.getOrCreateSingleRepoState(folderManager.repository.rootUri, folderManager); singleRepoState.issueCollection.clear(); let defaults: PullRequestDefaults | undefined; let user: string | undefined; for (const query of this._queries) { let items: Promise<IssueItem[] | MilestoneItem[]>; if (query.query === DEFAULT_QUERY_CONFIGURATION) { items = this.setMilestones(folderManager); } else { if (!defaults) { try { defaults = await folderManager.getPullRequestDefaults(); } catch (e) { // leave defaults undefined } } if (!user) { const enterpriseRemotes = parseRepositoryRemotes(folderManager.repository).filter( remote => remote.authProviderId === AuthProvider['github-enterprise'] ); user = await this.getCurrentUser(enterpriseRemotes.length ? AuthProvider['github-enterprise'] : AuthProvider.github); } items = this.setIssues( folderManager, await variableSubstitution(query.query, undefined, defaults, user), ); } singleRepoState.issueCollection.set(query.label, items); } singleRepoState.maxIssueNumber = await folderManager.getMaxIssue(); singleRepoState.lastHead = folderManager.repository.state.HEAD?.commit; singleRepoState.lastBranch = folderManager.repository.state.HEAD?.name; } private setIssues(folderManager: FolderRepositoryManager, query: string): Promise<IssueItem[]> { return new Promise(async resolve => { const issues = await folderManager.getIssues({ fetchNextPage: false }, query); this._onDidChangeIssueData.fire(); resolve( issues.items.map(item => { const issueItem: IssueItem = item as IssueItem; issueItem.uri = folderManager.repository.rootUri; return issueItem; }), ); }); } private async setCurrentIssueFromBranch(singleRepoState: SingleRepoState, branchName: string) { const createBranchConfig = vscode.workspace .getConfiguration(ISSUES_CONFIGURATION) .get<string>(BRANCH_CONFIGURATION); if (createBranchConfig === 'off') { return; } let defaults: PullRequestDefaults | undefined; try { defaults = await singleRepoState.folderManager.getPullRequestDefaults(); } catch (e) { // No remote, don't try to set the current issue return; } if (branchName === defaults.base) { await this.setCurrentIssue(singleRepoState, undefined); return; } if (singleRepoState.currentIssue && singleRepoState.currentIssue.branchName === branchName) { return; } const state: IssuesState = this.getSavedState(); for (const branch in state.branches) { if (branch === branchName) { const issueModel = await singleRepoState.folderManager.resolveIssue( state.branches[branch].owner, state.branches[branch].repositoryName, state.branches[branch].number, ); if (issueModel) { await this.setCurrentIssue( singleRepoState, new CurrentIssue(issueModel, singleRepoState.folderManager, this), ); } return; } } } private setMilestones(folderManager: FolderRepositoryManager): Promise<MilestoneItem[]> { return new Promise(async resolve => { const now = new Date(); const skipMilestones: string[] = vscode.workspace .getConfiguration(ISSUES_CONFIGURATION) .get(IGNORE_MILESTONES_CONFIGURATION, []); const milestones = await folderManager.getMilestones( { fetchNextPage: false }, skipMilestones.indexOf(NO_MILESTONE) < 0, ); let mostRecentPastTitleTime: Date | undefined = undefined; const milestoneDateMap: Map<string, Date> = new Map(); const milestonesToUse: MilestoneItem[] = []; // The number of milestones is expected to be very low, so two passes through is negligible for (let i = 0; i < milestones.items.length; i++) { const item: MilestoneItem = milestones.items[i] as MilestoneItem; item.uri = folderManager.repository.rootUri; const milestone = milestones.items[i].milestone; if ((item.issues && item.issues.length <= 0) || skipMilestones.indexOf(milestone.title) >= 0) { continue; } milestonesToUse.push(item); let milestoneDate = milestone.dueOn ? new Date(milestone.dueOn) : undefined; if (!milestoneDate) { milestoneDate = new Date(this.removeDateExcludeStrings(milestone.title)); if (isNaN(milestoneDate.getTime())) { milestoneDate = new Date(milestone.createdAt!); } } if ( milestoneDate < now && (mostRecentPastTitleTime === undefined || milestoneDate > mostRecentPastTitleTime) ) { mostRecentPastTitleTime = milestoneDate; } milestoneDateMap.set(milestone.id ? milestone.id : milestone.title, milestoneDate); } milestonesToUse.sort((a: MilestoneModel, b: MilestoneModel): number => { const dateA = milestoneDateMap.get(a.milestone.id ? a.milestone.id : a.milestone.title)!; const dateB = milestoneDateMap.get(b.milestone.id ? b.milestone.id : b.milestone.title)!; if (mostRecentPastTitleTime && dateA >= mostRecentPastTitleTime && dateB >= mostRecentPastTitleTime) { return dateA <= dateB ? -1 : 1; } else { return dateA >= dateB ? -1 : 1; } }); this._onDidChangeIssueData.fire(); resolve(milestonesToUse); }); } private removeDateExcludeStrings(possibleDate: string): string { excludeFromDate.forEach(exclude => (possibleDate = possibleDate.replace(exclude, ''))); return possibleDate; } currentIssue(uri: vscode.Uri): CurrentIssue | undefined { return this._singleRepoStates.get(uri.path)?.currentIssue; } currentIssues(): CurrentIssue[] { return Array.from(this._singleRepoStates.values()) .filter(state => state?.currentIssue) .map(state => state!.currentIssue!); } maxIssueNumber(uri: vscode.Uri): number { return this._singleRepoStates.get(uri.path)?.maxIssueNumber ?? 0; } private isSettingIssue: boolean = false; async setCurrentIssue(repoState: SingleRepoState | FolderRepositoryManager, issue: CurrentIssue | undefined) { if (this.isSettingIssue && issue === undefined) { return; } this.isSettingIssue = true; if (repoState instanceof FolderRepositoryManager) { const state = this._singleRepoStates.get(repoState.repository.rootUri.path); if (!state) { return; } repoState = state; } try { if (repoState.currentIssue && issue?.issue.number === repoState.currentIssue.issue.number) { return; } if (repoState.currentIssue) { await repoState.currentIssue.stopWorking(); } if (issue) { this.context.subscriptions.push(issue.onDidChangeCurrentIssueState(() => this.updateStatusBar())); } this.context.workspaceState.update(CURRENT_ISSUE_KEY, issue?.issue.number); if (!issue || (await issue.startWorking())) { repoState.currentIssue = issue; this.updateStatusBar(); } this._onDidChangeCurrentIssue.fire(); } catch (e) { // Error has already been surfaced } finally { this.isSettingIssue = false; } } private updateStatusBar() { const currentIssues = this.currentIssues(); const shouldShowStatusBarItem = currentIssues.length > 0; if (!shouldShowStatusBarItem) { if (this.statusBarItem) { this.statusBarItem.hide(); this.statusBarItem.dispose(); this.statusBarItem = undefined; } return; } if (shouldShowStatusBarItem && !this.statusBarItem) { this.statusBarItem = vscode.window.createStatusBarItem('github.issues.status', vscode.StatusBarAlignment.Left, 0); this.statusBarItem.name = 'GitHub Active Issue'; } const statusBarItem = this.statusBarItem!; statusBarItem.text = `$(issues) Issue ${currentIssues .map(issue => getIssueNumberLabel(issue.issue, issue.repoDefaults)) .join(', ')}`; statusBarItem.tooltip = currentIssues.map(issue => issue.issue.title).join(', '); statusBarItem.command = 'issue.statusBar'; statusBarItem.show(); } private getSavedState(): IssuesState { const stateString: string | undefined = this.context.workspaceState.get(ISSUES_KEY); return stateString ? JSON.parse(stateString) : { issues: Object.create(null), branches: Object.create(null) }; } getSavedIssueState(issueNumber: number): IssueState { const state: IssuesState = this.getSavedState(); return state.issues[`${issueNumber}`] ?? {}; } async setSavedIssueState(issue: IssueModel, issueState: IssueState) { const state: IssuesState = this.getSavedState(); state.issues[`${issue.number}`] = { ...issueState, stateModifiedTime: new Date().valueOf() }; if (issueState.branch) { if (!state.branches) { state.branches = Object.create(null); } state.branches[issueState.branch] = { number: issue.number, owner: issue.remote.owner, repositoryName: issue.remote.repositoryName, }; } return this.context.workspaceState.update(ISSUES_KEY, JSON.stringify(state)); } }
the_stack
import * as Protocol from '../../../../../../front_end/generated/protocol.js'; import * as ApplicationComponents from '../../../../../../front_end/panels/application/components/components.js'; import * as Coordinator from '../../../../../../front_end/ui/components/render_coordinator/render_coordinator.js'; import * as TreeOutline from '../../../../../../front_end/ui/components/tree_outline/tree_outline.js'; import {assertElement, assertShadowRoot, getElementWithinComponent, renderElementIntoDOM, stripLitHtmlCommentNodes} from '../../../helpers/DOMHelpers.js'; const coordinator = Coordinator.RenderCoordinator.RenderCoordinator.instance(); const {assert} = chai; async function renderOriginTrialTreeView( data: ApplicationComponents.OriginTrialTreeView.OriginTrialTreeViewData, ): Promise<{ component: ApplicationComponents.OriginTrialTreeView.OriginTrialTreeView, shadowRoot: ShadowRoot, }> { const component = new ApplicationComponents.OriginTrialTreeView.OriginTrialTreeView(); component.data = data; renderElementIntoDOM(component); assertShadowRoot(component.shadowRoot); await coordinator.done(); return { component, shadowRoot: component.shadowRoot, }; } type OriginTrialTreeOutline = TreeOutline.TreeOutline.TreeOutline<ApplicationComponents.OriginTrialTreeView.OriginTrialTreeNodeData>; /** * Extract `TreeOutline` component from `OriginTrialTreeView` for inspection. */ async function renderOriginTrialTreeViewTreeOutline( data: ApplicationComponents.OriginTrialTreeView.OriginTrialTreeViewData, ): Promise<{ component: OriginTrialTreeOutline, shadowRoot: ShadowRoot, }> { const {component} = await renderOriginTrialTreeView(data); const treeOutline: OriginTrialTreeOutline = getElementWithinComponent<ApplicationComponents.OriginTrialTreeView.OriginTrialTreeView, OriginTrialTreeOutline>( component, 'devtools-tree-outline', TreeOutline.TreeOutline.TreeOutline); assertShadowRoot(treeOutline.shadowRoot); return { component: treeOutline, shadowRoot: treeOutline.shadowRoot, }; } const tokenPlaceHolder = 'Origin Trial Token Placeholder'; const trialWithMultipleTokens: Protocol.Page.OriginTrial = { trialName: 'AppCache', status: Protocol.Page.OriginTrialStatus.Enabled, tokensWithStatus: [ { status: Protocol.Page.OriginTrialTokenStatus.Success, rawTokenText: tokenPlaceHolder, parsedToken: { trialName: 'AppCache', origin: 'https://foo.com', expiryTime: 1000, usageRestriction: Protocol.Page.OriginTrialUsageRestriction.None, isThirdParty: false, matchSubDomains: false, }, }, { status: Protocol.Page.OriginTrialTokenStatus.Expired, rawTokenText: tokenPlaceHolder, parsedToken: { trialName: 'AppCache', origin: 'https://foo.com', expiryTime: 1000, usageRestriction: Protocol.Page.OriginTrialUsageRestriction.None, isThirdParty: false, matchSubDomains: false, }, }, { status: Protocol.Page.OriginTrialTokenStatus.WrongOrigin, rawTokenText: tokenPlaceHolder, parsedToken: { trialName: 'AppCache', origin: 'https://bar.com', expiryTime: 1000, usageRestriction: Protocol.Page.OriginTrialUsageRestriction.None, isThirdParty: false, matchSubDomains: false, }, }, ], }; const trialWithSingleToken: Protocol.Page.OriginTrial = { trialName: 'AutoPictureInPicture', status: Protocol.Page.OriginTrialStatus.ValidTokenNotProvided, tokensWithStatus: [ { status: Protocol.Page.OriginTrialTokenStatus.NotSupported, rawTokenText: tokenPlaceHolder, parsedToken: { trialName: 'AutoPictureInPicture', origin: 'https://foo.com', expiryTime: 1000, usageRestriction: Protocol.Page.OriginTrialUsageRestriction.None, isThirdParty: false, matchSubDomains: false, }, }, ], }; const trialWithUnparsableToken: Protocol.Page.OriginTrial = { trialName: 'UNKNOWN', status: Protocol.Page.OriginTrialStatus.ValidTokenNotProvided, tokensWithStatus: [ { status: Protocol.Page.OriginTrialTokenStatus.InvalidSignature, rawTokenText: tokenPlaceHolder, }, ], }; function extractBadgeTextFromTreeNode(node: HTMLLIElement): string[] { return [...node.querySelectorAll('devtools-resources-origin-trial-tree-view-badge')].map(badgeElement => { assertShadowRoot(badgeElement.shadowRoot); const adornerElement = badgeElement.shadowRoot.querySelector('devtools-adorner'); assert.isNotNull(adornerElement); if (adornerElement === null) { return ''; } assertShadowRoot(adornerElement.shadowRoot); const contentElement = adornerElement.querySelector('[slot="content"]'); assert.isNotNull(contentElement); if (contentElement === null) { return ''; } return contentElement.innerHTML; }); } function nodeKeyInnerHTML(node: HTMLLIElement|ShadowRoot) { const keyNode = node.querySelector('[data-node-key]'); if (!keyNode) { throw new Error('Found tree node without a key within it.'); } return stripLitHtmlCommentNodes(keyNode.innerHTML); } interface VisibleTreeNodeFromDOM { nodeElement: HTMLLIElement; children?: VisibleTreeNodeFromDOM[]; } /** * Converts the nodes into a tree structure that we can assert against. */ function visibleNodesToTree(shadowRoot: ShadowRoot): VisibleTreeNodeFromDOM[] { const tree: VisibleTreeNodeFromDOM[] = []; function buildTreeNode(node: HTMLLIElement): VisibleTreeNodeFromDOM { const item: VisibleTreeNodeFromDOM = { nodeElement: node, }; if (node.getAttribute('aria-expanded') && node.getAttribute('aria-expanded') === 'true') { item.children = []; const childNodes = node.querySelectorAll<HTMLLIElement>(':scope > ul[role="group"]>li'); for (const child of childNodes) { item.children.push(buildTreeNode(child)); } } return item; } const rootNodes = shadowRoot.querySelectorAll<HTMLLIElement>('ul[role="tree"]>li'); for (const root of rootNodes) { tree.push(buildTreeNode(root)); } return tree; } /** * Wait until a certain number of children are rendered. We need this as the * component uses LitHtml's until directive, which is async and not within the * render coordinator's control. */ async function waitForRenderedTreeNodeCount(shadowRoot: ShadowRoot, expectedNodeCount: number): Promise<void> { const actualNodeCount = shadowRoot.querySelectorAll('li[role="treeitem"]').length; if (actualNodeCount === expectedNodeCount) { return; } await new Promise<void>(resolve => { requestAnimationFrame(async () => { await waitForRenderedTreeNodeCount(shadowRoot, expectedNodeCount); resolve(); }); }); } describe('OriginTrialTreeView', () => { it('renders trial names as root tree nodes', async () => { const {shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, trialWithSingleToken, trialWithUnparsableToken, ], }); const visibleItems = shadowRoot.querySelectorAll<HTMLLIElement>('li[role="treeitem"]'); assert.lengthOf(visibleItems, 3); assert.include(nodeKeyInnerHTML(visibleItems[0]), trialWithMultipleTokens.trialName); assert.include(nodeKeyInnerHTML(visibleItems[1]), trialWithSingleToken.trialName); assert.include(nodeKeyInnerHTML(visibleItems[2]), trialWithUnparsableToken.trialName); }); it('renders token with status when there are more than 1 tokens', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, // Node counts by level: 1/3/6/3 ], }); await component.expandRecursively(/* maxDepth= */ 0); await waitForRenderedTreeNodeCount(shadowRoot, 4); const visibleTree = visibleNodesToTree(shadowRoot); // When there are more than 1 tokens in a trial, second level nodes // should show token status. const tokenWithStatusNodes = visibleTree[0].children; assert.isDefined(tokenWithStatusNodes); if (tokenWithStatusNodes === undefined) { return; } assert.lengthOf(tokenWithStatusNodes, 3); for (let i = 0; i < tokenWithStatusNodes.length; i++) { assert.include( extractBadgeTextFromTreeNode(tokenWithStatusNodes[i].nodeElement), trialWithMultipleTokens.tokensWithStatus[i].status, ); } }); it('skips token with status when there is only 1 token', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithSingleToken, // Node counts by level: 1/2/1 ], }); await component.expandRecursively(/* maxDepth= */ 1); await waitForRenderedTreeNodeCount(shadowRoot, 3); const visibleTree = visibleNodesToTree(shadowRoot); // When there is only 1 token, token with status level should be skipped. const tokenDetailNodes = visibleTree[0].children; assert.isDefined(tokenDetailNodes); if (tokenDetailNodes === undefined) { return; } assert.lengthOf(tokenDetailNodes, 2); }); it('renders token fields', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithSingleToken, // Node counts by level: 1/2/1 ], }); await component.expandRecursively(/* maxDepth= */ 1); await waitForRenderedTreeNodeCount(shadowRoot, 3); const visibleTree = visibleNodesToTree(shadowRoot); const tokenDetailNodes = visibleTree[0].children; assert.isDefined(tokenDetailNodes); if (tokenDetailNodes === undefined) { return; } assert.lengthOf(tokenDetailNodes, 2); const tokenFieldsNode = tokenDetailNodes[0]; const rowsComponent = tokenFieldsNode.nodeElement.querySelector('devtools-resources-origin-trial-token-rows'); assertElement(rowsComponent, ApplicationComponents.OriginTrialTreeView.OriginTrialTokenRows); assertShadowRoot(rowsComponent.shadowRoot); const innerHTML = rowsComponent.shadowRoot.innerHTML; const parsedToken = trialWithSingleToken.tokensWithStatus[0].parsedToken; assert.isDefined(parsedToken); if (parsedToken === undefined) { return; } // Note: only origin and usageRestriction field are tested, as other fields // are not directly rendered: // - expiryTime: rendered as time format // - isThirdParty, MatchesSubDomain: boolean flags assert.include(innerHTML, parsedToken.origin); assert.include(innerHTML, parsedToken.usageRestriction); }); it('renders raw token text', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithSingleToken, // Node counts by level: 1/2/1 ], }); await component.expandRecursively(/* maxDepth= */ 2); await waitForRenderedTreeNodeCount(shadowRoot, 4); const visibleTree = visibleNodesToTree(shadowRoot); const tokenDetailNodes = visibleTree[0].children; assert.isDefined(tokenDetailNodes); if (tokenDetailNodes === undefined) { return; } assert.lengthOf(tokenDetailNodes, 2); const rawTokenNode = tokenDetailNodes[1]; assert.isDefined(rawTokenNode.children); if (rawTokenNode.children === undefined) { return; } assert.lengthOf(rawTokenNode.children, 1); const innerHTML = nodeKeyInnerHTML(rawTokenNode.children[0].nodeElement); assert.include(innerHTML, trialWithSingleToken.tokensWithStatus[0].rawTokenText); }); it('shows token count when there are more than 1 tokens in a trial', async () => { const {shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, ], }); await waitForRenderedTreeNodeCount(shadowRoot, 1); const visibleTree = visibleNodesToTree(shadowRoot); const trialNameNode = visibleTree[0]; const badges = extractBadgeTextFromTreeNode(trialNameNode.nodeElement); assert.lengthOf(badges, 2); assert.include(badges, `${trialWithMultipleTokens.tokensWithStatus.length} tokens`); }); it('shows trial status', async () => { const {shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, ], }); await waitForRenderedTreeNodeCount(shadowRoot, 1); const visibleTree = visibleNodesToTree(shadowRoot); const trialNameNode = visibleTree[0]; const badges = extractBadgeTextFromTreeNode(trialNameNode.nodeElement); assert.lengthOf(badges, 2); assert.include(badges, trialWithMultipleTokens.status); }); it('shows token status, when token with status node not expanded', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, // Node counts by level: 1/3/6/3 ], }); await component.expandRecursively(/* maxDepth= */ 0); await waitForRenderedTreeNodeCount(shadowRoot, 4); const visibleTree = visibleNodesToTree(shadowRoot); const trialNameNode = visibleTree[0]; assert.isDefined(trialNameNode.children); if (trialNameNode.children === undefined) { return; } assert.lengthOf(trialNameNode.children, 3); for (let i = 0; i < trialNameNode.children.length; i++) { const tokenWithStatusNode = trialNameNode.children[i]; assert.isUndefined(tokenWithStatusNode.children); const badges = extractBadgeTextFromTreeNode(tokenWithStatusNode.nodeElement); assert.lengthOf(badges, 1); assert.strictEqual(badges[0], trialWithMultipleTokens.tokensWithStatus[i].status); } }); it('hide token status, when token with status node is expanded', async () => { const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ trialWithMultipleTokens, // Node counts by level: 1/3/6/3 ], }); await component.expandRecursively(/* maxDepth= */ 1); await waitForRenderedTreeNodeCount(shadowRoot, 4); const visibleTree = visibleNodesToTree(shadowRoot); const trialNameNode = visibleTree[0]; assert.isDefined(trialNameNode.children); if (trialNameNode.children === undefined) { return; } for (let i = 0; i < trialNameNode.children.length; i++) { const tokenWithStatusNode = trialNameNode.children[i]; assert.isDefined(tokenWithStatusNode.children); const badges = extractBadgeTextFromTreeNode(tokenWithStatusNode.nodeElement); assert.lengthOf(badges, 0); } }); it('shows trial name for token with status UnknownTrial', async () => { const unknownTrialName = 'UnkownTrialName'; const {component, shadowRoot} = await renderOriginTrialTreeViewTreeOutline({ trials: [ { trialName: 'UNKNOWN', status: Protocol.Page.OriginTrialStatus.ValidTokenNotProvided, tokensWithStatus: [ { status: Protocol.Page.OriginTrialTokenStatus.UnknownTrial, parsedToken: { trialName: unknownTrialName, origin: 'https://foo.com', expiryTime: 1000, usageRestriction: Protocol.Page.OriginTrialUsageRestriction.None, isThirdParty: false, matchSubDomains: false, }, rawTokenText: tokenPlaceHolder, }, ], }, ], }); // Node counts by level: 1/2/1 await component.expandRecursively(/* maxDepth= */ 1); await waitForRenderedTreeNodeCount(shadowRoot, 3); const visibleTree = visibleNodesToTree(shadowRoot); const tokenDetailNodes = visibleTree[0].children; assert.isDefined(tokenDetailNodes); if (tokenDetailNodes === undefined) { return; } assert.lengthOf(tokenDetailNodes, 2); const tokenFieldsNode = tokenDetailNodes[0]; const rowsComponent = tokenFieldsNode.nodeElement.querySelector('devtools-resources-origin-trial-token-rows'); assertElement(rowsComponent, ApplicationComponents.OriginTrialTreeView.OriginTrialTokenRows); assertShadowRoot(rowsComponent.shadowRoot); const innerHTML = rowsComponent.shadowRoot.innerHTML; assert.include(innerHTML, unknownTrialName); }); });
the_stack
import { TabStopRequirementState } from 'common/types/store-data/visualization-scan-result-data'; import { AutomatedTabStopRequirementResult } from 'injected/tab-stop-requirement-result'; import * as React from 'react'; import { ReportExportServiceKey } from 'report-export/types/report-export-service'; import { TabStopRequirementId } from 'types/tab-stop-requirement-info'; import { DictionaryStringTo } from '../types/common-types'; import { AssessmentRequirementScanTelemetryData, AssessmentTelemetryData, AutoDetectedFailuresDialogStateTelemetryData, BaseTelemetryData, DetailsViewOpenedTelemetryData, DetailsViewOpenTelemetryData, DetailsViewPivotSelectedTelemetryData, ExportFastPassResultsTelemetryData, ExportResultsTelemetryData, FeatureFlagToggleTelemetryData, FileIssueClickTelemetryData, InspectTelemetryData, IssuesAnalyzerScanTelemetryData, NeedsReviewAnalyzerScanTelemetryData, ReportExportFormat, RequirementActionTelemetryData, RequirementSelectTelemetryData, RequirementStatusTelemetryData, RuleAnalyzerScanTelemetryData, ScopingTelemetryData, SelectGettingStartedTelemetryData, SetAllUrlsPermissionTelemetryData, SettingsOpenSourceItem, SettingsOpenTelemetryData, TabStopAutomatedFailuresInstanceCount, TabStopRequirementInstanceCount, TabStopsAutomatedResultsTelemetryData, TelemetryEventSource, ToggleTelemetryData, TriggeredBy, TriggeredByNotApplicable, } from './extension-telemetry-events'; import { ForIssuesAnalyzerScanCallback, ForNeedsReviewAnalyzerScanCallback, ForRuleAnalyzerScanCallback, } from './types/analyzer-telemetry-callbacks'; import { DetailsViewPivotType } from './types/details-view-pivot-type'; import { VisualizationType } from './types/visualization-type'; export type SupportedMouseEvent = | React.SyntheticEvent<MouseEvent> | React.MouseEvent<any> | MouseEvent | React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement> | React.SyntheticEvent<Element, Event> | undefined; export class TelemetryDataFactory { public forVisualizationToggleByCommand(enabled: boolean): ToggleTelemetryData { return { triggeredBy: 'shortcut', enabled, source: TelemetryEventSource.ShortcutCommand, }; } public forToggle( event: SupportedMouseEvent, enabled: boolean, source: TelemetryEventSource, ): ToggleTelemetryData { return { ...this.withTriggeredByAndSource(event, source), enabled, }; } public forFeatureFlagToggle( event: SupportedMouseEvent, enabled: boolean, source: TelemetryEventSource, featureFlagId: string, ): FeatureFlagToggleTelemetryData { return { ...this.withTriggeredByAndSource(event, source), enabled, featureFlagId, }; } public forExportedResults( reportExportFormat: ReportExportFormat, selectedServiceKey: ReportExportServiceKey, event: SupportedMouseEvent, source: TelemetryEventSource, ): ExportResultsTelemetryData { return { ...this.withTriggeredByAndSource(event, source), exportResultsType: reportExportFormat, exportResultsService: selectedServiceKey, }; } public forExportedResultsWithFastPassData( tabStopRequirementData: TabStopRequirementState, wereAutomatedChecksRun: boolean, reportExportFormat: ReportExportFormat, selectedServiceKey: ReportExportServiceKey, event: React.MouseEvent<HTMLElement>, source: TelemetryEventSource, ): ExportFastPassResultsTelemetryData { const tabStopRequirementInstanceCount: TabStopRequirementInstanceCount = { pass: {}, fail: {}, unknown: {}, }; Object.entries(tabStopRequirementData).forEach(([requirementId, data]) => { if (data.status === 'fail') { tabStopRequirementInstanceCount[data.status][requirementId] = data.instances.length; } else { tabStopRequirementInstanceCount[data.status][requirementId] = 1; } }); return { ...this.withTriggeredByAndSource(event, source), exportResultsType: reportExportFormat, exportResultsService: selectedServiceKey, wereAutomatedChecksRun, tabStopRequirementInstanceCount, }; } public forAddSelector( event: SupportedMouseEvent, inputType: string, source: TelemetryEventSource, ): ScopingTelemetryData { return { ...this.withTriggeredByAndSource(event, source), inputType, }; } public forDeleteSelector( event: SupportedMouseEvent, inputType: string, source: TelemetryEventSource, ): ScopingTelemetryData { return { ...this.withTriggeredByAndSource(event, source), inputType, }; } public forSelectDetailsView( event: SupportedMouseEvent, visualizationType: VisualizationType, ): DetailsViewOpenTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView), selectedTest: VisualizationType[visualizationType], }; } public forSelectRequirement( event: SupportedMouseEvent, visualizationType: VisualizationType, requirement: string, ): RequirementSelectTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView), selectedTest: VisualizationType[visualizationType], selectedRequirement: requirement, }; } public forSelectGettingStarted( event: SupportedMouseEvent, visualizationType: VisualizationType, ): SelectGettingStartedTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView), selectedTest: VisualizationType[visualizationType], }; } public forRequirementStatus( visualizationType: VisualizationType, requirement: string, passed: boolean, numInstances: number, ): RequirementStatusTelemetryData { return { triggeredBy: TriggeredByNotApplicable, source: TelemetryEventSource.DetailsView, selectedTest: VisualizationType[visualizationType], selectedRequirement: requirement, passed: passed, numInstances: numInstances, }; } public forOpenDetailsView( event: SupportedMouseEvent, visualizationType: VisualizationType, source: TelemetryEventSource, ): DetailsViewOpenTelemetryData { return { ...this.withTriggeredByAndSource(event, source), selectedTest: VisualizationType[visualizationType], }; } public forDetailsViewOpened( selectedPivot: DetailsViewPivotType, ): DetailsViewOpenedTelemetryData { return { ...this.fromDetailsViewNoTriggeredBy(), selectedDetailsViewPivot: DetailsViewPivotType[selectedPivot], }; } public forSettingsPanelOpen( event: SupportedMouseEvent, source: TelemetryEventSource, sourceItem: SettingsOpenSourceItem, ): SettingsOpenTelemetryData { return { ...this.withTriggeredByAndSource(event, source), sourceItem, }; } public forFileIssueClick( event: SupportedMouseEvent, source: TelemetryEventSource, service: string, ): FileIssueClickTelemetryData { return { ...this.withTriggeredByAndSource(event, source), service, }; } public forInspectElement(event: SupportedMouseEvent, target: string[]): InspectTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.IssueDetailsDialog), target: target, }; } public forDetailsViewNavPivotActivated( event: SupportedMouseEvent, pivotKey: string, ): DetailsViewPivotSelectedTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView), pivotKey, }; } public forAssessmentActionFromDetailsViewNoTriggeredBy( visualizationType: VisualizationType, ): AssessmentTelemetryData { return { triggeredBy: TriggeredByNotApplicable, source: TelemetryEventSource.DetailsView, selectedTest: VisualizationType[visualizationType], }; } public forAssessmentActionFromDetailsView( visualizationType: VisualizationType, event: SupportedMouseEvent, ): AssessmentTelemetryData { return { ...this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView), selectedTest: VisualizationType[visualizationType], }; } public forRequirementFromDetailsView( test: VisualizationType, requirement: string, ): RequirementActionTelemetryData { return { triggeredBy: TriggeredByNotApplicable, source: TelemetryEventSource.DetailsView, selectedRequirement: requirement, selectedTest: VisualizationType[test], }; } public forTabStopRequirement( requirementId: TabStopRequirementId, source: TelemetryEventSource, ) { return { triggeredBy: TriggeredByNotApplicable, source, requirementId: requirementId, }; } public forCancelStartOver( event: SupportedMouseEvent, test: VisualizationType, requirement: string, ): RequirementSelectTelemetryData { return { ...this.fromDetailsView(event), selectedTest: VisualizationType[test], selectedRequirement: requirement, }; } public fromDetailsViewNoTriggeredBy(): BaseTelemetryData { return { triggeredBy: TriggeredByNotApplicable, source: TelemetryEventSource.DetailsView, }; } public fromDetailsView(event: SupportedMouseEvent): BaseTelemetryData { return this.withTriggeredByAndSource(event, TelemetryEventSource.DetailsView); } public fromHamburgerMenu(event: SupportedMouseEvent): BaseTelemetryData { return this.withTriggeredByAndSource(event, TelemetryEventSource.HamburgerMenu); } public fromLaunchPad(event: SupportedMouseEvent): BaseTelemetryData { return this.withTriggeredByAndSource(event, TelemetryEventSource.LaunchPad); } public withTriggeredByAndSource( event: SupportedMouseEvent, source: TelemetryEventSource, ): BaseTelemetryData { return { triggeredBy: this.getTriggeredBy(event), source: source, }; } public forAssessmentRequirementScan: ForRuleAnalyzerScanCallback = ( analyzerResult, scanDuration, elementsScanned, testVisualizationType, requirementName, ) => { const telemetry: AssessmentRequirementScanTelemetryData = { ...this.forTestScan( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ), requirementName, }; return telemetry; }; public forTestScan: ForRuleAnalyzerScanCallback = ( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ) => { const telemetry: RuleAnalyzerScanTelemetryData = { scanDuration: scanDuration, NumberOfElementsScanned: elementsScanned, include: analyzerResult.include, exclude: analyzerResult.exclude, testName: VisualizationType[testVisualizationType], }; return telemetry; }; public forIssuesAnalyzerScan: ForIssuesAnalyzerScanCallback = ( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ) => { const passedRuleResults: DictionaryStringTo<number> = this.generateTelemetryRuleResult( analyzerResult.originalResult.passes, ); const failedRuleResults: DictionaryStringTo<number> = this.generateTelemetryRuleResult( analyzerResult.originalResult.violations, ); const telemetry: IssuesAnalyzerScanTelemetryData = { ...this.forTestScan( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ), passedRuleResults: JSON.stringify(passedRuleResults), failedRuleResults: JSON.stringify(failedRuleResults), }; return telemetry; }; public forNeedsReviewAnalyzerScan: ForNeedsReviewAnalyzerScanCallback = ( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ) => { const passedRuleResults: DictionaryStringTo<number> = this.generateTelemetryRuleResult( analyzerResult.originalResult.passes, ); const failedRuleResults: DictionaryStringTo<number> = this.generateTelemetryRuleResult( analyzerResult.originalResult.violations, ); const incompleteRuleResults: DictionaryStringTo<number> = this.generateTelemetryRuleResult( analyzerResult.originalResult.incomplete, ); const telemetry: NeedsReviewAnalyzerScanTelemetryData = { ...this.forTestScan( analyzerResult, scanDuration, elementsScanned, testVisualizationType, ), passedRuleResults: JSON.stringify(passedRuleResults), failedRuleResults: JSON.stringify(failedRuleResults), incompleteRuleResults: JSON.stringify(incompleteRuleResults), }; return telemetry; }; public forLeftNavPanelExpanded(event: SupportedMouseEvent): BaseTelemetryData { return { source: TelemetryEventSource.DetailsView, triggeredBy: this.getTriggeredBy(event), }; } private getTriggeredBy(event: SupportedMouseEvent): TriggeredBy { // MouseEvent => event.detail === 0 ? "keypress" : "mouseclick" // React.SyntheticEvent<MouseEvent> event.nativeEvent can be cast to MouseEvent // React.MouseEvent<any> event.nativeEvent can be cast to MouseEvent if (!event) { return TriggeredByNotApplicable; } const reactEvent = event as React.MouseEvent<any>; const mouseEvent = (reactEvent.nativeEvent || event) as MouseEvent; return mouseEvent.detail === 0 ? 'keypress' : 'mouseclick'; } private generateTelemetryRuleResult(axeRule: AxeRule[]): DictionaryStringTo<number> { const ruleResults: DictionaryStringTo<number> = {}; axeRule.forEach(element => { const key: string = element.id; if (key != null) { ruleResults[key] = element.nodes.length; } }); return ruleResults; } public forSetAllUrlPermissionState( event: SupportedMouseEvent, source: TelemetryEventSource, permissionState: boolean, ): SetAllUrlsPermissionTelemetryData { return { ...this.withTriggeredByAndSource(event, source), permissionState, }; } public forAutomatedTabStopsResults( results: AutomatedTabStopRequirementResult[], source: TelemetryEventSource, ): TabStopsAutomatedResultsTelemetryData | undefined { if (!results || results.length === 0) { return undefined; } const tabStopAutomatedFailuresInstanceCount: TabStopAutomatedFailuresInstanceCount = {}; results.forEach(({ requirementId }) => { const count = tabStopAutomatedFailuresInstanceCount[requirementId] ?? 0; tabStopAutomatedFailuresInstanceCount[requirementId] = count + 1; }); return { triggeredBy: TriggeredByNotApplicable, source, tabStopAutomatedFailuresInstanceCount, }; } public forSetAutoDetectedFailuresDialogState( enabled: boolean, ): AutoDetectedFailuresDialogStateTelemetryData | undefined { if (enabled === undefined) { return undefined; } return { enabled, }; } }
the_stack
import { IExecuteFunctions, } from 'n8n-core'; import { IBinaryData, ICredentialsDecrypted, ICredentialTestFunctions, IDataObject, INodeExecutionData, INodeType, INodeTypeDescription, NodeCredentialTestResult, NodeOperationError, } from 'n8n-workflow'; import { addAdditionalFields, apiRequest, getPropertyName, } from './GenericFunctions'; export class Telegram implements INodeType { description: INodeTypeDescription = { displayName: 'Telegram', name: 'telegram', icon: 'file:telegram.svg', group: ['output'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Sends data to Telegram', defaults: { name: 'Telegram', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'telegramApi', required: true, testedBy: 'telegramBotTest', }, ], properties: [ { displayName: 'Resource', name: 'resource', type: 'options', options: [ // { // name: 'Bot', // value: 'bot', // }, { name: 'Chat', value: 'chat', }, { name: 'Callback', value: 'callback', }, { name: 'File', value: 'file', }, { name: 'Message', value: 'message', }, ], default: 'message', description: 'The resource to operate on.', }, // ---------------------------------- // operation // ---------------------------------- // { // displayName: 'Operation', // name: 'operation', // type: 'options', // displayOptions: { // show: { // resource: [ // 'bot', // ], // }, // }, // options: [ // { // name: 'Info', // value: 'info', // description: 'Get information about the bot associated with the access token.', // }, // ], // default: 'info', // description: 'The operation to perform.', // }, // ---------------------------------- // operation // ---------------------------------- { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'chat', ], }, }, options: [ { name: 'Get', value: 'get', description: 'Get up to date information about a chat.', }, { name: 'Leave', value: 'leave', description: 'Leave a group, supergroup or channel.', }, { name: 'Member', value: 'member', description: 'Get the member of a chat.', }, { name: 'Set Description', value: 'setDescription', description: 'Set the description of a chat.', }, { name: 'Set Title', value: 'setTitle', description: 'Set the title of a chat.', }, ], default: 'get', description: 'The operation to perform.', }, { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'callback', ], }, }, options: [ { name: 'Answer Query', value: 'answerQuery', description: 'Send answer to callback query sent from inline keyboard.', }, { name: 'Answer Inline Query', value: 'answerInlineQuery', description: 'Send answer to callback query sent from inline bot.', }, ], default: 'answerQuery', description: 'The operation to perform.', }, { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'file', ], }, }, options: [ { name: 'Get', value: 'get', description: 'Get a file.', }, ], default: 'get', description: 'The operation to perform.', }, { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'message', ], }, }, options: [ { name: 'Delete Chat Message', value: 'deleteMessage', description: 'Delete a chat message', }, { name: 'Edit Message Text', value: 'editMessageText', description: 'Edit a text message', }, { name: 'Pin Chat Message', value: 'pinChatMessage', description: 'Pin a chat message', }, { name: 'Send Animation', value: 'sendAnimation', description: 'Send an animated file', }, { name: 'Send Audio', value: 'sendAudio', description: 'Send a audio file', }, { name: 'Send Chat Action', value: 'sendChatAction', description: 'Send a chat action', }, { name: 'Send Document', value: 'sendDocument', description: 'Send a document', }, { name: 'Send Location', value: 'sendLocation', description: 'Send a location', }, { name: 'Send Media Group', value: 'sendMediaGroup', description: 'Send group of photos or videos to album', }, { name: 'Send Message', value: 'sendMessage', description: 'Send a text message', }, { name: 'Send Photo', value: 'sendPhoto', description: 'Send a photo', }, { name: 'Send Sticker', value: 'sendSticker', description: 'Send a sticker', }, { name: 'Send Video', value: 'sendVideo', description: 'Send a video', }, { name: 'Unpin Chat Message', value: 'unpinChatMessage', description: 'Unpin a chat message', }, ], default: 'sendMessage', description: 'The operation to perform.', }, // ---------------------------------- // chat / message // ---------------------------------- { displayName: 'Chat ID', name: 'chatId', type: 'string', default: '', displayOptions: { show: { operation: [ 'deleteMessage', 'get', 'leave', 'member', 'pinChatMessage', 'setDescription', 'setTitle', 'sendAnimation', 'sendAudio', 'sendChatAction', 'sendDocument', 'sendLocation', 'sendMessage', 'sendMediaGroup', 'sendPhoto', 'sendSticker', 'sendVideo', 'unpinChatMessage', ], resource: [ 'chat', 'message', ], }, }, required: true, description: 'Unique identifier for the target chat or username of the target channel (in the format @channelusername).', }, // ---------------------------------- // message:deleteMessage // ---------------------------------- { displayName: 'Message ID', name: 'messageId', type: 'string', default: '', displayOptions: { show: { operation: [ 'deleteMessage', ], resource: [ 'message', ], }, }, required: true, description: 'Unique identifier of the message to delete.', }, // ---------------------------------- // message:pinChatMessage // ---------------------------------- { displayName: 'Message ID', name: 'messageId', type: 'string', default: '', displayOptions: { show: { operation: [ 'pinChatMessage', 'unpinChatMessage', ], resource: [ 'message', ], }, }, required: true, description: 'Unique identifier of the message to pin or unpin.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'pinChatMessage', ], resource: [ 'message', ], }, }, default: {}, options: [ { displayName: 'Disable Notification', name: 'disable_notification', type: 'boolean', default: false, description: 'Do not send a notification to all chat members about the new pinned message.', }, ], }, // ---------------------------------- // chat // ---------------------------------- // ---------------------------------- // chat:member // ---------------------------------- { displayName: 'User ID', name: 'userId', type: 'string', default: '', displayOptions: { show: { operation: [ 'member', ], resource: [ 'chat', ], }, }, required: true, description: 'Unique identifier of the target user.', }, // ---------------------------------- // chat:setDescription // ---------------------------------- { displayName: 'Description', name: 'description', type: 'string', default: '', displayOptions: { show: { operation: [ 'setDescription', ], resource: [ 'chat', ], }, }, required: true, description: 'New chat description, 0-255 characters.', }, // ---------------------------------- // chat:setTitle // ---------------------------------- { displayName: 'Title', name: 'title', type: 'string', default: '', displayOptions: { show: { operation: [ 'setTitle', ], resource: [ 'chat', ], }, }, required: true, description: 'New chat title, 1-255 characters.', }, // ---------------------------------- // callback // ---------------------------------- // ---------------------------------- // callback:answerQuery // ---------------------------------- { displayName: 'Query ID', name: 'queryId', type: 'string', default: '', displayOptions: { show: { operation: [ 'answerQuery', ], resource: [ 'callback', ], }, }, required: true, description: 'Unique identifier for the query to be answered.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'answerQuery', ], resource: [ 'callback', ], }, }, default: {}, options: [ { displayName: 'Cache Time', name: 'cache_time', type: 'number', typeOptions: { minValue: 0, }, default: 0, description: 'The maximum amount of time in seconds that the result of the callback query may be cached client-side.', }, { displayName: 'Show Alert', name: 'show_alert', type: 'boolean', default: false, description: 'If true, an alert will be shown by the client instead of a notification at the top of the chat screen.', }, { displayName: 'Text', name: 'text', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: 'Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.', }, { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'URL that will be opened by the user\'s client.', }, ], }, // ----------------------------------------------- // callback:answerInlineQuery // ----------------------------------------------- { displayName: 'Query ID', name: 'queryId', type: 'string', default: '', displayOptions: { show: { operation: [ 'answerInlineQuery', ], resource: [ 'callback', ], }, }, required: true, description: 'Unique identifier for the answered query.', }, { displayName: 'Results', name: 'results', type: 'string', default: '', displayOptions: { show: { operation: [ 'answerInlineQuery', ], resource: [ 'callback', ], }, }, required: true, description: 'A JSON-serialized array of results for the inline query.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'answerInlineQuery', ], resource: [ 'callback', ], }, }, default: {}, options: [ { displayName: 'Cache Time', name: 'cache_time', type: 'number', typeOptions: { minValue: 0, }, default: 0, description: 'The maximum amount of time in seconds that the result of the callback query may be cached client-side.', }, { displayName: 'Show Alert', name: 'show_alert', type: 'boolean', default: false, description: 'If true, an alert will be shown by the client instead of a notification at the top of the chat screen.', }, { displayName: 'Text', name: 'text', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: 'Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.', }, { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'URL that will be opened by the user\'s client.', }, ], }, // ---------------------------------- // file // ---------------------------------- // ---------------------------------- // file:get/download // ---------------------------------- { displayName: 'File ID', name: 'fileId', type: 'string', default: '', displayOptions: { show: { operation: [ 'get', ], resource: [ 'file', ], }, }, required: true, description: 'The ID of the file.', }, { displayName: 'Download', name: 'download', type: 'boolean', displayOptions: { show: { operation: [ 'get', ], resource: [ 'file', ], }, }, default: true, description: 'Download the file.', }, // ---------------------------------- // message // ---------------------------------- // ---------------------------------- // message:editMessageText // ---------------------------------- { displayName: 'Message Type', name: 'messageType', type: 'options', displayOptions: { show: { operation: [ 'editMessageText', ], resource: [ 'message', ], }, }, options: [ { name: 'Inline Message', value: 'inlineMessage', }, { name: 'Message', value: 'message', }, ], default: 'message', description: 'The type of the message to edit.', }, { displayName: 'Chat ID', name: 'chatId', type: 'string', default: '', displayOptions: { show: { messageType: [ 'message', ], operation: [ 'editMessageText', ], resource: [ 'message', ], }, }, required: true, description: 'Unique identifier for the target chat or username of the target channel (in the format @channelusername). To find your chat id ask @get_id_bot.', }, // ---------------------------------- // message:sendAnimation/sendAudio/sendDocument/sendPhoto/sendSticker/sendVideo // ---------------------------------- { displayName: 'Binary Data', name: 'binaryData', type: 'boolean', default: false, required: true, displayOptions: { show: { operation: [ 'sendAnimation', 'sendAudio', 'sendDocument', 'sendPhoto', 'sendVideo', 'sendSticker', ], resource: [ 'message', ], }, }, description: 'If the data to upload should be taken from binary field.', }, { displayName: 'Binary Property', name: 'binaryPropertyName', type: 'string', default: 'data', required: true, displayOptions: { show: { operation: [ 'sendAnimation', 'sendAudio', 'sendDocument', 'sendPhoto', 'sendVideo', 'sendSticker', ], resource: [ 'message', ], binaryData: [ true, ], }, }, placeholder: '', description: 'Name of the binary property that contains the data to upload', }, { displayName: 'Message ID', name: 'messageId', type: 'string', default: '', displayOptions: { show: { messageType: [ 'message', ], operation: [ 'editMessageText', ], resource: [ 'message', ], }, }, required: true, description: 'Unique identifier of the message to edit.', }, { displayName: 'Inline Message ID', name: 'inlineMessageId', type: 'string', default: '', displayOptions: { show: { messageType: [ 'inlineMessage', ], operation: [ 'editMessageText', ], resource: [ 'message', ], }, }, required: true, description: 'Unique identifier of the inline message to edit.', }, { displayName: 'Reply Markup', name: 'replyMarkup', displayOptions: { show: { operation: [ 'editMessageText', ], resource: [ 'message', ], }, }, type: 'options', options: [ { name: 'None', value: 'none', }, { name: 'Inline Keyboard', value: 'inlineKeyboard', }, ], default: 'none', description: 'Additional interface options.', }, // ---------------------------------- // message:sendAnimation // ---------------------------------- { displayName: 'Animation', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendAnimation', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Animation to send. Pass a file_id to send an animation that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get an animation from the Internet', }, // ---------------------------------- // message:sendAudio // ---------------------------------- { displayName: 'Audio', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendAudio', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Audio file to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get a file from the Internet', }, // ---------------------------------- // message:sendChatAction // ---------------------------------- { displayName: 'Action', name: 'action', type: 'options', displayOptions: { show: { operation: [ 'sendChatAction', ], resource: [ 'message', ], }, }, options: [ { name: 'Find Location', value: 'find_location', }, { name: 'Record Audio', value: 'record_audio', }, { name: 'Record Video', value: 'record_video', }, { name: 'Record Video Note', value: 'record_video_note', }, { name: 'Typing', value: 'typing', }, { name: 'Upload Audio', value: 'upload_audio', }, { name: 'Upload Document', value: 'upload_document', }, { name: 'Upload Photo', value: 'upload_photo', }, { name: 'Upload Video', value: 'upload_video', }, { name: 'Upload Video Note', value: 'upload_video_note', }, ], default: 'typing', description: 'Type of action to broadcast. Choose one, depending on what the user is about to receive. The status is set for 5 seconds or less (when a message arrives from your bot).', }, // ---------------------------------- // message:sendDocument // ---------------------------------- { displayName: 'Document', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendDocument', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Document to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get a file from the Internet', }, // ---------------------------------- // message:sendLocation // ---------------------------------- { displayName: 'Latitude', name: 'latitude', type: 'number', default: 0.0, typeOptions: { numberPrecision: 10, minValue: -90, maxValue: 90, }, displayOptions: { show: { operation: [ 'sendLocation', ], resource: [ 'message', ], }, }, description: 'Location latitude', }, { displayName: 'Longitude', name: 'longitude', type: 'number', typeOptions: { numberPrecision: 10, minValue: -180, maxValue: 180, }, default: 0.0, displayOptions: { show: { operation: [ 'sendLocation', ], resource: [ 'message', ], }, }, description: 'Location longitude', }, // ---------------------------------- // message:sendMediaGroup // ---------------------------------- { displayName: 'Media', name: 'media', type: 'fixedCollection', displayOptions: { show: { operation: [ 'sendMediaGroup', ], resource: [ 'message', ], }, }, description: 'The media to add.', placeholder: 'Add Media', typeOptions: { multipleValues: true, }, default: {}, options: [ { displayName: 'Media', name: 'media', values: [ { displayName: 'Type', name: 'type', type: 'options', options: [ { name: 'Photo', value: 'photo', }, { name: 'Video', value: 'video', }, ], default: 'photo', description: 'The type of the media to add.', }, { displayName: 'Media File', name: 'media', type: 'string', default: '', description: 'Media to send. Pass a file_id to send a file that exists on the Telegram servers (recommended) or pass an HTTP URL for Telegram to get a file from the Internet.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, options: [ { displayName: 'Caption', name: 'caption', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: 'Caption text to set, 0-1024 characters.', }, { displayName: 'Parse Mode', name: 'parse_mode', type: 'options', options: [ { name: 'Markdown', value: 'Markdown', }, { name: 'HTML', value: 'HTML', }, ], default: 'HTML', description: 'How to parse the text.', }, ], }, ], }, ], }, // ---------------------------------- // message:sendMessage // ---------------------------------- { displayName: 'Text', name: 'text', type: 'string', required: true, typeOptions: { alwaysOpenEditWindow: true, }, default: '', displayOptions: { show: { operation: [ 'editMessageText', 'sendMessage', ], resource: [ 'message', ], }, }, description: 'Text of the message to be sent.', }, // ---------------------------------- // message:sendPhoto // ---------------------------------- { displayName: 'Photo', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendPhoto', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Photo to send. Pass a file_id to send a photo that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get a photo from the Internet', }, // ---------------------------------- // message:sendSticker // ---------------------------------- { displayName: 'Sticker', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendSticker', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Sticker to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get a .webp file from the Internet', }, // ---------------------------------- // message:sendVideo // ---------------------------------- { displayName: 'Video', name: 'file', type: 'string', default: '', displayOptions: { show: { operation: [ 'sendVideo', ], resource: [ 'message', ], binaryData: [ false, ], }, }, description: 'Video file to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), an HTTP URL for Telegram to get a file from the Internet', }, // ---------------------------------- // message:editMessageText/sendAnimation/sendAudio/sendLocation/sendMessage/sendPhoto/sendSticker/sendVideo // ---------------------------------- { displayName: 'Reply Markup', name: 'replyMarkup', displayOptions: { show: { operation: [ 'sendAnimation', 'sendDocument', 'sendMessage', 'sendPhoto', 'sendSticker', 'sendVideo', 'sendAudio', 'sendLocation', ], resource: [ 'message', ], }, }, type: 'options', options: [ { name: 'None', value: 'none', }, { name: 'Force Reply', value: 'forceReply', }, { name: 'Inline Keyboard', value: 'inlineKeyboard', }, { name: 'Reply Keyboard', value: 'replyKeyboard', }, { name: 'Reply Keyboard Remove', value: 'replyKeyboardRemove', }, ], default: 'none', description: 'Additional interface options.', }, { displayName: 'Force Reply', name: 'forceReply', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { replyMarkup: [ 'forceReply', ], resource: [ 'message', ], }, }, default: {}, options: [ { displayName: 'Force Reply', name: 'force_reply', type: 'boolean', default: false, description: 'Shows reply interface to the user, as if they manually selected the bot‘s message and tapped ’Reply.', }, { displayName: 'Selective', name: 'selective', type: 'boolean', default: false, description: ' Use this parameter if you want to force reply from specific users only.', }, ], }, { displayName: 'Inline Keyboard', name: 'inlineKeyboard', placeholder: 'Add Keyboard Row', description: 'Adds an inline keyboard that appears right next to the message it belongs to.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, displayOptions: { show: { replyMarkup: [ 'inlineKeyboard', ], resource: [ 'message', ], }, }, default: {}, options: [ { displayName: 'Rows', name: 'rows', values: [ { displayName: 'Row', name: 'row', type: 'fixedCollection', description: 'The value to set.', placeholder: 'Add Button', typeOptions: { multipleValues: true, }, default: {}, options: [ { displayName: 'Buttons', name: 'buttons', values: [ { displayName: 'Text', name: 'text', type: 'string', default: '', description: 'Label text on the button.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, options: [ { displayName: 'Callback Data', name: 'callback_data', type: 'string', default: '', description: 'Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes.', }, { displayName: 'Pay', name: 'pay', type: 'boolean', default: false, description: 'Specify True, to send a Pay button.', }, { displayName: 'Switch Inline Query Current Chat', name: 'switch_inline_query_current_chat', type: 'string', default: '', description: 'If set, pressing the button will insert the bot‘s username and the specified inline query in the current chat\'s input field.Can be empty, in which case only the bot’s username will be inserted.', }, { displayName: 'Switch Inline Query', name: 'switch_inline_query', type: 'string', default: '', description: 'If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot‘s username and the specified inline query in the input field. Can be empty, in which case just the bot’s username will be inserted.', }, { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'HTTP or tg:// url to be opened when button is pressed.', }, ], }, ], }, ], }, ], }, ], }, { displayName: 'Reply Keyboard', name: 'replyKeyboard', placeholder: 'Add Reply Keyboard Row', description: 'Adds a custom keyboard with reply options.', type: 'fixedCollection', typeOptions: { multipleValues: true, }, displayOptions: { show: { replyMarkup: [ 'replyKeyboard', ], }, }, default: {}, options: [ { displayName: 'Rows', name: 'rows', values: [ { displayName: 'Row', name: 'row', type: 'fixedCollection', description: 'The value to set.', placeholder: 'Add Button', typeOptions: { multipleValues: true, }, default: {}, options: [ { displayName: 'Buttons', name: 'buttons', values: [ { displayName: 'Text', name: 'text', type: 'string', default: '', description: 'Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, options: [ { displayName: 'Request Contact', name: 'request_contact', type: 'boolean', default: false, description: 'If True, the user\'s phone number will be sent as a contact when the button is pressed.Available in private chats only.', }, { displayName: 'Request Location', name: 'request_location', type: 'boolean', default: false, description: 'If True, the user\'s request_location.', }, ], }, ], }, ], }, ], }, ], }, { displayName: 'Reply Keyboard Options', name: 'replyKeyboardOptions', type: 'collection', placeholder: 'Add Option', displayOptions: { show: { replyMarkup: [ 'replyKeyboard', ], }, }, default: {}, options: [ { displayName: 'Resize Keyboard', name: 'resize_keyboard', type: 'boolean', default: false, description: 'Requests clients to resize the keyboard vertically for optimal fit.', }, { displayName: 'One Time Keyboard', name: 'one_time_keyboard', type: 'boolean', default: false, description: 'Requests clients to hide the keyboard as soon as it\'s been used.', }, { displayName: 'Selective', name: 'selective', type: 'boolean', default: false, description: 'Use this parameter if you want to show the keyboard to specific users only.', }, ], }, { displayName: 'Reply Keyboard Remove', name: 'replyKeyboardRemove', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { replyMarkup: [ 'replyKeyboardRemove', ], }, }, default: {}, options: [ { displayName: 'Remove Keyboard', name: 'remove_keyboard', type: 'boolean', default: false, description: 'Requests clients to remove the custom keyboard.', }, { displayName: 'Selective', name: 'selective', type: 'boolean', default: false, description: ' Use this parameter if you want to force reply from specific users only.', }, ], }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', displayOptions: { show: { operation: [ 'editMessageText', 'sendAnimation', 'sendAudio', 'sendDocument', 'sendLocation', 'sendMessage', 'sendMediaGroup', 'sendPhoto', 'sendSticker', 'sendVideo', ], resource: [ 'message', ], }, }, default: {}, options: [ { displayName: 'Caption', name: 'caption', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, displayOptions: { show: { '/operation': [ 'sendAnimation', 'sendAudio', 'sendDocument', 'sendPhoto', 'sendVideo', ], }, }, default: '', description: 'Caption text to set, 0-1024 characters.', }, { displayName: 'Disable Notification', name: 'disable_notification', type: 'boolean', default: false, displayOptions: { hide: { '/operation': [ 'editMessageText', ], }, }, description: 'Sends the message silently. Users will receive a notification with no sound.', }, { displayName: 'Disable WebPage Preview', name: 'disable_web_page_preview', type: 'boolean', displayOptions: { show: { '/operation': [ 'editMessageText', 'sendMessage', ], }, }, default: false, description: 'Disables link previews for links in this message.', }, { displayName: 'Duration', name: 'duration', type: 'number', typeOptions: { minValue: 0, }, displayOptions: { show: { '/operation': [ 'sendAnimation', 'sendAudio', 'sendVideo', ], }, }, default: 0, description: 'Duration of clip in seconds.', }, { displayName: 'Height', name: 'height', type: 'number', typeOptions: { minValue: 0, }, displayOptions: { show: { '/operation': [ 'sendAnimation', 'sendVideo', ], }, }, default: 0, description: 'Height of the video.', }, { displayName: 'Parse Mode', name: 'parse_mode', type: 'options', options: [ { name: 'Markdown', value: 'Markdown', }, { name: 'HTML', value: 'HTML', }, ], displayOptions: { show: { '/operation': [ 'editMessageText', 'sendAnimation', 'sendAudio', 'sendMessage', 'sendPhoto', 'sendVideo', ], }, }, default: 'HTML', description: 'How to parse the text.', }, { displayName: 'Performer', name: 'performer', type: 'string', displayOptions: { show: { '/operation': [ 'sendAudio', ], }, }, default: '', description: 'Name of the performer.', }, { displayName: 'Reply To Message ID', name: 'reply_to_message_id', type: 'number', displayOptions: { hide: { '/operation': [ 'editMessageText', ], }, }, default: 0, description: 'If the message is a reply, ID of the original message.', }, { displayName: 'Title', name: 'title', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, displayOptions: { show: { '/operation': [ 'sendAudio', ], }, }, default: '', description: 'Title of the track.', }, { displayName: 'Thumbnail', name: 'thumb', type: 'string', displayOptions: { show: { '/operation': [ 'sendAnimation', 'sendAudio', 'sendDocument', 'sendVideo', ], }, }, default: '', description: 'Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail‘s width and height should not exceed 320.', }, { displayName: 'Width', name: 'width', type: 'number', typeOptions: { minValue: 0, }, displayOptions: { show: { '/operation': [ 'sendAnimation', 'sendVideo', ], }, }, default: 0, description: 'Width of the video.', }, ], }, ], }; methods = { credentialTest: { async telegramBotTest(this: ICredentialTestFunctions, credential: ICredentialsDecrypted): Promise<NodeCredentialTestResult> { const credentials = credential.data; const options = { uri: `https://api.telegram.org/bot${credentials!.accessToken}/getMe`, json: true, }; try { const response = await this.helpers.request(options); if (!response.ok) { return { status: 'Error', message: 'Token is not valid.', }; } } catch (err) { return { status: 'Error', message: `Token is not valid; ${err.message}`, }; } return { status: 'OK', message: 'Authentication successful!', }; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: INodeExecutionData[] = []; // For Post let body: IDataObject; // For Query string let qs: IDataObject; let requestMethod: string; let endpoint: string; const operation = this.getNodeParameter('operation', 0) as string; const resource = this.getNodeParameter('resource', 0) as string; const binaryData = this.getNodeParameter('binaryData', 0, false) as boolean; for (let i = 0; i < items.length; i++) { try { // Reset all values requestMethod = 'POST'; endpoint = ''; body = {}; qs = {}; if (resource === 'callback') { if (operation === 'answerQuery') { // ---------------------------------- // callback:answerQuery // ---------------------------------- endpoint = 'answerCallbackQuery'; body.callback_query_id = this.getNodeParameter('queryId', i) as string; // Add additional fields const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); } else if (operation === 'answerInlineQuery') { // ----------------------------------------------- // callback:answerInlineQuery // ----------------------------------------------- endpoint = 'answerInlineQuery'; body.inline_query_id = this.getNodeParameter('queryId', i) as string; body.results = this.getNodeParameter('results', i) as string; // Add additional fields const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); } } else if (resource === 'chat') { if (operation === 'get') { // ---------------------------------- // chat:get // ---------------------------------- endpoint = 'getChat'; body.chat_id = this.getNodeParameter('chatId', i) as string; } else if (operation === 'leave') { // ---------------------------------- // chat:leave // ---------------------------------- endpoint = 'leaveChat'; body.chat_id = this.getNodeParameter('chatId', i) as string; } else if (operation === 'member') { // ---------------------------------- // chat:member // ---------------------------------- endpoint = 'getChatMember'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.user_id = this.getNodeParameter('userId', i) as string; } else if (operation === 'setDescription') { // ---------------------------------- // chat:setDescription // ---------------------------------- endpoint = 'setChatDescription'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.description = this.getNodeParameter('description', i) as string; } else if (operation === 'setTitle') { // ---------------------------------- // chat:setTitle // ---------------------------------- endpoint = 'setChatTitle'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.title = this.getNodeParameter('title', i) as string; } // } else if (resource === 'bot') { // if (operation === 'info') { // endpoint = 'getUpdates'; // } } else if (resource === 'file') { if (operation === 'get') { // ---------------------------------- // file:get // ---------------------------------- endpoint = 'getFile'; body.file_id = this.getNodeParameter('fileId', i) as string; } } else if (resource === 'message') { if (operation === 'editMessageText') { // ---------------------------------- // message:editMessageText // ---------------------------------- endpoint = 'editMessageText'; const messageType = this.getNodeParameter('messageType', i) as string; if (messageType === 'inlineMessage') { body.inline_message_id = this.getNodeParameter('inlineMessageId', i) as string; } else { body.chat_id = this.getNodeParameter('chatId', i) as string; body.message_id = this.getNodeParameter('messageId', i) as string; } body.text = this.getNodeParameter('text', i) as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'deleteMessage') { // ---------------------------------- // message:deleteMessage // ---------------------------------- endpoint = 'deleteMessage'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.message_id = this.getNodeParameter('messageId', i) as string; } else if (operation === 'pinChatMessage') { // ---------------------------------- // message:pinChatMessage // ---------------------------------- endpoint = 'pinChatMessage'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.message_id = this.getNodeParameter('messageId', i) as string; const { disable_notification } = this.getNodeParameter('additionalFields', i) as IDataObject; if (disable_notification) { body.disable_notification = true; } } else if (operation === 'unpinChatMessage') { // ---------------------------------- // message:unpinChatMessage // ---------------------------------- endpoint = 'unpinChatMessage'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.message_id = this.getNodeParameter('messageId', i) as string; } else if (operation === 'sendAnimation') { // ---------------------------------- // message:sendAnimation // ---------------------------------- endpoint = 'sendAnimation'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.animation = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendAudio') { // ---------------------------------- // message:sendAudio // ---------------------------------- endpoint = 'sendAudio'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.audio = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendChatAction') { // ---------------------------------- // message:sendChatAction // ---------------------------------- endpoint = 'sendChatAction'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.action = this.getNodeParameter('action', i) as string; } else if (operation === 'sendDocument') { // ---------------------------------- // message:sendDocument // ---------------------------------- endpoint = 'sendDocument'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.document = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendLocation') { // ---------------------------------- // message:sendLocation // ---------------------------------- endpoint = 'sendLocation'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.latitude = this.getNodeParameter('latitude', i) as string; body.longitude = this.getNodeParameter('longitude', i) as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendMessage') { // ---------------------------------- // message:sendMessage // ---------------------------------- endpoint = 'sendMessage'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.text = this.getNodeParameter('text', i) as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendMediaGroup') { // ---------------------------------- // message:sendMediaGroup // ---------------------------------- endpoint = 'sendMediaGroup'; body.chat_id = this.getNodeParameter('chatId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const mediaItems = this.getNodeParameter('media', i) as IDataObject; body.media = []; for (const mediaItem of mediaItems.media as IDataObject[]) { if (mediaItem.additionalFields !== undefined) { Object.assign(mediaItem, mediaItem.additionalFields); delete mediaItem.additionalFields; } (body.media as IDataObject[]).push(mediaItem); } } else if (operation === 'sendPhoto') { // ---------------------------------- // message:sendPhoto // ---------------------------------- endpoint = 'sendPhoto'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.photo = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendSticker') { // ---------------------------------- // message:sendSticker // ---------------------------------- endpoint = 'sendSticker'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.sticker = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } else if (operation === 'sendVideo') { // ---------------------------------- // message:sendVideo // ---------------------------------- endpoint = 'sendVideo'; body.chat_id = this.getNodeParameter('chatId', i) as string; body.video = this.getNodeParameter('file', i, '') as string; // Add additional fields and replyMarkup addAdditionalFields.call(this, body, i); } } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } let responseData; if (binaryData === true) { const binaryPropertyName = this.getNodeParameter('binaryPropertyName', 0) as string; const binaryData = items[i].binary![binaryPropertyName] as IBinaryData; const dataBuffer = await this.helpers.getBinaryDataBuffer(i, binaryPropertyName); const propertyName = getPropertyName(operation); const formData = { ...body, [propertyName]: { value: dataBuffer, options: { filename: binaryData.fileName, contentType: binaryData.mimeType, }, }, }; responseData = await apiRequest.call(this, requestMethod, endpoint, {}, qs, { formData }); } else { responseData = await apiRequest.call(this, requestMethod, endpoint, body, qs); } if (resource === 'file' && operation === 'get') { if (this.getNodeParameter('download', i, false) as boolean === true) { const filePath = responseData.result.file_path; const credentials = await this.getCredentials('telegramApi'); if (credentials === undefined) { throw new NodeOperationError(this.getNode(), 'No credentials got returned!'); } const file = await apiRequest.call(this, 'GET', '', {}, {}, { json: false, encoding: null, uri: `https://api.telegram.org/file/bot${credentials.accessToken}/${filePath}`, resolveWithFullResponse: true }); const fileName = filePath.split('/').pop(); const binaryData = await this.helpers.prepareBinaryData(Buffer.from(file.body as string), fileName); returnData.push({ json: responseData, binary: { data: binaryData, }, }); continue; } } // if (resource === 'bot' && operation === 'info') { // responseData = { // user: responseData.result[0].message.from, // chat: responseData.result[0].message.chat, // }; // } returnData.push({ json: responseData }); } catch (error) { if (this.continueOnFail()) { returnData.push({ json: { error: error.message } }); continue; } throw error; } } return this.prepareOutputData(returnData); } }
the_stack
'use strict'; import * as os from 'os'; import * as TypeMoq from 'typemoq'; import { DiagnosticSeverity, TextDocument, Uri, WorkspaceFolder } from 'vscode'; import { LanguageServerType } from '../../client/activation/types'; import { IApplicationShell, IWorkspaceService } from '../../client/common/application/types'; import { Product } from '../../client/common/installer/productInstaller'; import { ProductNames } from '../../client/common/installer/productNames'; import { IFileSystem, IPlatformService } from '../../client/common/platform/types'; import { IPythonExecutionFactory, IPythonToolExecutionService } from '../../client/common/process/types'; import { Flake8CategorySeverity, IConfigurationService, IInstaller, IMypyCategorySeverity, IOutputChannel, IPycodestyleCategorySeverity, IPylintCategorySeverity, IPythonSettings, } from '../../client/common/types'; import { IServiceContainer } from '../../client/ioc/types'; import { LINTERID_BY_PRODUCT } from '../../client/linters/constants'; import { LinterManager } from '../../client/linters/linterManager'; import { ILinter, ILinterManager, ILintMessage, LinterId } from '../../client/linters/types'; export function newMockDocument(filename: string): TypeMoq.IMock<TextDocument> { const uri = Uri.file(filename); const doc = TypeMoq.Mock.ofType<TextDocument>(undefined, TypeMoq.MockBehavior.Strict); doc.setup((s) => s.uri).returns(() => uri); return doc; } export function linterMessageAsLine(msg: ILintMessage): string { switch (msg.provider) { case 'pydocstyle': { return `<filename>:${msg.line} spam:${os.EOL}\t${msg.code}: ${msg.message}`; } default: { return `${msg.line},${msg.column},${msg.type},${msg.code}:${msg.message}`; } } } export function getLinterID(product: Product): LinterId { const linterID = LINTERID_BY_PRODUCT.get(product); if (!linterID) { throwUnknownProduct(product); } return linterID!; } export function getProductName(product: Product, capitalize = true): string { let prodName = ProductNames.get(product); if (!prodName) { prodName = Product[product]; } if (capitalize) { return prodName.charAt(0).toUpperCase() + prodName.slice(1); } else { return prodName; } } export function throwUnknownProduct(product: Product) { throw Error(`unsupported product ${Product[product]} (${product})`); } export class LintingSettings { public enabled: boolean; public cwd?: string; public ignorePatterns: string[]; public prospectorEnabled: boolean; public prospectorArgs: string[]; public pylintEnabled: boolean; public pylintArgs: string[]; public pycodestyleEnabled: boolean; public pycodestyleArgs: string[]; public pylamaEnabled: boolean; public pylamaArgs: string[]; public flake8Enabled: boolean; public flake8Args: string[]; public pydocstyleEnabled: boolean; public pydocstyleArgs: string[]; public lintOnSave: boolean; public maxNumberOfProblems: number; public pylintCategorySeverity: IPylintCategorySeverity; public pycodestyleCategorySeverity: IPycodestyleCategorySeverity; public flake8CategorySeverity: Flake8CategorySeverity; public mypyCategorySeverity: IMypyCategorySeverity; public prospectorPath: string; public pylintPath: string; public pycodestylePath: string; public pylamaPath: string; public flake8Path: string; public pydocstylePath: string; public mypyEnabled: boolean; public mypyArgs: string[]; public mypyPath: string; public banditEnabled: boolean; public banditArgs: string[]; public banditPath: string; constructor() { // mostly from configSettings.ts this.enabled = true; this.cwd = undefined; this.ignorePatterns = []; this.lintOnSave = false; this.maxNumberOfProblems = 100; this.flake8Enabled = false; this.flake8Path = 'flake8'; this.flake8Args = []; this.flake8CategorySeverity = { E: DiagnosticSeverity.Error, W: DiagnosticSeverity.Warning, F: DiagnosticSeverity.Warning, }; this.mypyEnabled = false; this.mypyPath = 'mypy'; this.mypyArgs = []; this.mypyCategorySeverity = { error: DiagnosticSeverity.Error, note: DiagnosticSeverity.Hint, }; this.banditEnabled = false; this.banditPath = 'bandit'; this.banditArgs = []; this.pycodestyleEnabled = false; this.pycodestylePath = 'pycodestyle'; this.pycodestyleArgs = []; this.pycodestyleCategorySeverity = { E: DiagnosticSeverity.Error, W: DiagnosticSeverity.Warning, }; this.pylamaEnabled = false; this.pylamaPath = 'pylama'; this.pylamaArgs = []; this.prospectorEnabled = false; this.prospectorPath = 'prospector'; this.prospectorArgs = []; this.pydocstyleEnabled = false; this.pydocstylePath = 'pydocstyle'; this.pydocstyleArgs = []; this.pylintEnabled = false; this.pylintPath = 'pylint'; this.pylintArgs = []; this.pylintCategorySeverity = { convention: DiagnosticSeverity.Hint, error: DiagnosticSeverity.Error, fatal: DiagnosticSeverity.Error, refactor: DiagnosticSeverity.Hint, warning: DiagnosticSeverity.Warning, }; } } export class BaseTestFixture { public serviceContainer: TypeMoq.IMock<IServiceContainer>; public linterManager: LinterManager; // services public workspaceService: TypeMoq.IMock<IWorkspaceService>; public installer: TypeMoq.IMock<IInstaller>; public appShell: TypeMoq.IMock<IApplicationShell>; // config public configService: TypeMoq.IMock<IConfigurationService>; public pythonSettings: TypeMoq.IMock<IPythonSettings>; public lintingSettings: LintingSettings; // data public outputChannel: TypeMoq.IMock<IOutputChannel>; // artifacts public output: string; public logged: string[]; constructor( platformService: IPlatformService, filesystem: IFileSystem, pythonToolExecService: IPythonToolExecutionService, pythonExecFactory: IPythonExecutionFactory, configService?: TypeMoq.IMock<IConfigurationService>, serviceContainer?: TypeMoq.IMock<IServiceContainer>, ignoreConfigUpdates = false, public readonly workspaceDir = '.', protected readonly printLogs = false, ) { this.serviceContainer = serviceContainer ? serviceContainer : TypeMoq.Mock.ofType<IServiceContainer>(undefined, TypeMoq.MockBehavior.Strict); // services this.workspaceService = TypeMoq.Mock.ofType<IWorkspaceService>(undefined, TypeMoq.MockBehavior.Strict); this.installer = TypeMoq.Mock.ofType<IInstaller>(undefined, TypeMoq.MockBehavior.Strict); this.appShell = TypeMoq.Mock.ofType<IApplicationShell>(undefined, TypeMoq.MockBehavior.Strict); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IFileSystem), TypeMoq.It.isAny())) .returns(() => filesystem); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IWorkspaceService), TypeMoq.It.isAny())) .returns(() => this.workspaceService.object); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IInstaller), TypeMoq.It.isAny())) .returns(() => this.installer.object); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IPlatformService), TypeMoq.It.isAny())) .returns(() => platformService); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IPythonToolExecutionService), TypeMoq.It.isAny())) .returns(() => pythonToolExecService); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IPythonExecutionFactory), TypeMoq.It.isAny())) .returns(() => pythonExecFactory); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IApplicationShell), TypeMoq.It.isAny())) .returns(() => this.appShell.object); this.initServices(); // config this.configService = configService ? configService : TypeMoq.Mock.ofType<IConfigurationService>(undefined, TypeMoq.MockBehavior.Strict); this.pythonSettings = TypeMoq.Mock.ofType<IPythonSettings>(undefined, TypeMoq.MockBehavior.Strict); this.lintingSettings = new LintingSettings(); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IConfigurationService), TypeMoq.It.isAny())) .returns(() => this.configService.object); this.configService.setup((c) => c.getSettings(TypeMoq.It.isAny())).returns(() => this.pythonSettings.object); this.pythonSettings.setup((s) => s.linting).returns(() => this.lintingSettings); this.initConfig(ignoreConfigUpdates); // data this.outputChannel = TypeMoq.Mock.ofType<IOutputChannel>(undefined, TypeMoq.MockBehavior.Strict); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IOutputChannel), TypeMoq.It.isAny())) .returns(() => this.outputChannel.object); this.initData(); // artifacts this.output = ''; this.logged = []; // linting this.linterManager = new LinterManager(this.configService.object); this.serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(ILinterManager), TypeMoq.It.isAny())) .returns(() => this.linterManager); } public async getLinter(product: Product, enabled = true): Promise<ILinter> { const info = this.linterManager.getLinterInfo(product); (this.lintingSettings as any)[info.enabledSettingName] = enabled; await this.linterManager.setActiveLintersAsync([product]); await this.linterManager.enableLintingAsync(enabled); return this.linterManager.createLinter(product, this.outputChannel.object, this.serviceContainer.object); } public async getEnabledLinter(product: Product): Promise<ILinter> { return this.getLinter(product, true); } public async getDisabledLinter(product: Product): Promise<ILinter> { return this.getLinter(product, false); } protected newMockDocument(filename: string): TypeMoq.IMock<TextDocument> { return newMockDocument(filename); } private initServices(): void { const workspaceFolder = TypeMoq.Mock.ofType<WorkspaceFolder>(undefined, TypeMoq.MockBehavior.Strict); workspaceFolder.setup((f) => f.uri).returns(() => Uri.file(this.workspaceDir)); this.workspaceService .setup((s) => s.getWorkspaceFolder(TypeMoq.It.isAny())) .returns(() => workspaceFolder.object); this.appShell .setup((a) => a.showErrorMessage(TypeMoq.It.isAny(), TypeMoq.It.isAny())) .returns(() => Promise.resolve(undefined)); } private initConfig(ignoreUpdates = false): void { this.configService .setup((c) => c.updateSetting(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), ) .callback((setting, value) => { if (ignoreUpdates) { return; } const prefix = 'linting.'; if (setting.startsWith(prefix)) { (this.lintingSettings as any)[setting.substring(prefix.length)] = value; } }) .returns(() => Promise.resolve(undefined)); this.pythonSettings.setup((s) => s.languageServer).returns(() => LanguageServerType.Jedi); } private initData(): void { this.outputChannel .setup((o) => o.appendLine(TypeMoq.It.isAny())) .callback((line) => { if (this.output === '') { this.output = line; } else { this.output = `${this.output}${os.EOL}${line}`; } }); this.outputChannel .setup((o) => o.append(TypeMoq.It.isAny())) .callback((data) => { this.output += data; }); this.outputChannel.setup((o) => o.show()); } }
the_stack
import React from 'react'; import cx from 'classnames'; import omit from 'lodash/omit'; import isFunction from 'lodash/isFunction'; import assign from 'lodash/assign'; import { Steps, Result, Spin } from 'antd'; import Memorize from './memorize'; import { Form, FieldGroup, FormProps, FieldGroupProps, FormAction, FormInstance } from '../form'; import { RequestConfig } from '../types/request'; import LocaleReceiver from '../localereceiver'; import { transformSubmit } from '../template-create-form/CreateForm'; import './style/step-form.less'; import { ActionPlugin } from '../types/plugin'; const { Step } = Steps; const MemorizeItem = Memorize.Item; export interface StepProps extends Omit<FieldGroupProps, 'name'> { title: string; subTitle?: string; description?: string; } export type StepType = 'first' | 'middle' | 'submit' | 'result'; export interface StepFormProps extends FormProps { result?: { title: string; subTitle: string; }; steps: StepProps[]; back?: ActionPlugin; submit: RequestConfig; save?: RequestConfig; direction?: 'vertical' | 'horizontal'; stepsStyle?: React.CSSProperties; formStyle?: React.CSSProperties; } type StepStatus = 'success' | 'error'; interface StepFormState { current: number; loading: boolean; stepsStatus: Array<StepStatus>; } export default class StepForm extends React.Component<StepFormProps, StepFormState> { static defaultProps = { direction: 'horizontal', mode: 'create', }; state = { current: 0, loading: false, stepsStatus: [] as Array<StepStatus>, }; validateStep = ( form: FormInstance, stepIndex: number, stepsStatus: Array<StepStatus>, ): Promise<any> => { return form .validateGroupFields(this.getStepName(stepIndex)) .then( () => { stepsStatus.push('success'); }, () => { stepsStatus.push('error'); }, ) .then(() => { if (stepIndex === this.props.steps.length - 1) { return; } else { return this.validateStep(form, stepIndex + 1, stepsStatus); } }); }; validateSteps = (form: FormInstance) => { const stepsStatus = [] as Array<StepStatus>; return new Promise((resolve, reject) => { this.validateStep(form, 0, stepsStatus).then(() => { if (stepsStatus.indexOf('error') > -1) { /** 如果存在校验错误,不再执行后续action */ reject(); } else { resolve(stepsStatus); } this.setState({ stepsStatus, }); }); }); }; getStepName = (stepIndex: number) => { return `@@step${stepIndex}`; }; nextStep = () => { this.setState({ current: this.state.current + 1, }); this.clearStepErrorStatus(this.state.current + 1); }; previousStep = () => { this.setState({ current: this.state.current - 1, }); this.clearStepErrorStatus(this.state.current - 1); }; /** save 才会开启 */ handleChange = (current: number) => { this.setState({ current }); this.clearStepErrorStatus(current); }; clearStepErrorStatus = (stepIndex: number) => { const { save } = this.props; const { stepsStatus } = this.state; if (save && stepsStatus[stepIndex] === 'error') { const newStepsStatus = [...stepsStatus]; newStepsStatus[stepIndex] = 'success' as StepStatus; this.setState({ stepsStatus: newStepsStatus, }); } }; renderStepActions = (stepType, locale) => { const { mode, submit, back = 'back', result, save } = this.props; const isView = mode === 'view'; const { current } = this.state; // 取消或者返回 const cancelAction = { type: 'button', props: { children: mode === 'create' ? locale.cancelText : locale.backText, }, action: 'back', }; const okAction = { type: 'button', props: { children: locale.backText, }, action: back, }; // 上一步 const previousAction = { type: 'button', props: { children: locale.previousText, }, action: [this.previousStep], }; // 下一步 const nextAction = { type: 'button', props: { type: save && !isView ? 'default' : 'primary', children: locale.nextText, }, action: [this.nextStep], }; // 校验且下一步 const validateFieldsAndNextAction = { type: 'button', props: { type: 'primary', children: locale.nextText, }, action: [ { type: 'validateGroupFields', args: [this.getStepName(current)], }, this.nextStep, ], }; /** * 仅提交不校验 */ const saveAction = save && { type: 'button', props: { type: stepType === 'submit' ? 'default' : 'primary', children: locale.stageText, }, action: [ { type: 'getFieldsValue', resultPropName: '$fieldsValue', }, ...transformSubmit( isFunction(save) ? save : assign({ successMessage: locale.stageText }, save), ), ], }; /** * 校验并提交 */ const submitAction = { type: 'button', props: { type: 'primary', children: mode === 'create' ? locale.submitText : locale.updateText, }, action: [ /** 如果是暂存模式,先对各step做校验,如果有校验不过的就不走后面的action */ ...(save ? [ { type: (ctx: {form: FormInstance}) => { return this.validateSteps(ctx.form); }, }, ] : []), { type: 'validateFields', resultPropName: '$fieldsValue', }, ...transformSubmit(submit, result ? this.nextStep : 'back'), ], }; if (stepType === 'first') { return [ ...(isView ? [nextAction] : save ? [saveAction, nextAction] : [validateFieldsAndNextAction]), cancelAction, ]; } else if (stepType === 'middle') { return [ ...(isView ? [nextAction] : save ? [saveAction, nextAction] : [validateFieldsAndNextAction]), previousAction, cancelAction, ]; } else if (stepType === 'submit') { return [ ...(isView ? [] : [submitAction, ...(save ? [saveAction] : [])]), previousAction, cancelAction, ]; } else { // result return [okAction]; } }; renderStepForm = (locale) => { const { steps, result, direction, stepsStyle, formStyle, save, ...restFormProps } = this.props; const { loading, stepsStatus } = this.state; const formProps = omit(restFormProps, ['submit', 'back']); const { current } = this.state; const isView = restFormProps.mode === 'view'; const containerCls = cx('sula-template-step-form', `sula-template-step-form-${direction}`); return ( <div className={containerCls}> <div className={`sula-template-step-form-${direction}-steps`} style={stepsStyle}> <Steps direction={direction} size={direction === 'vertical' ? 'small' : 'default'} current={current} {...(save ? { onChange: this.handleChange } : {})} > {steps.map((step, stepIndex) => { const { title, subTitle, description } = step; return ( <Step title={title} subTitle={subTitle} description={description} {...(save ? { status: stepsStatus[stepIndex] !== 'error' ? undefined : 'error' } : {})} key={stepIndex} /> ); })} </Steps> </div> <div className={`sula-template-step-form-${direction}-form`} style={formStyle}> <Spin spinning={loading}> <Form {...formProps} onRemoteValuesStart={() => { this.setState({ loading: true, }); }} onRemoteValuesEnd={() => { this.setState({ loading: false, }); }} > <Memorize> {steps.map((step, stepIndex) => { const isFirstStep = stepIndex === 0; const isSubmitStep = stepIndex === steps.length - 1; let stepType: StepType; if (isFirstStep) { stepType = 'first'; } else if (isSubmitStep) { stepType = 'submit'; } else { stepType = 'middle'; } const actionsRender = this.renderStepActions(stepType, locale); const fieldGroupProps = omit(step, ['name', 'title', 'subTitle', 'description']); return ( <MemorizeItem visible={current === stepIndex} key={stepIndex} memoId={stepIndex} > <FieldGroup name={this.getStepName(stepIndex)} actionsRender={actionsRender} {...fieldGroupProps} /> </MemorizeItem> ); })} {result && !isView ? ( <MemorizeItem visible={current === steps.length} memoId={steps.length}> <Result className={`sula-template-step-form-${direction}-result`} status="success" title={result.title || locale.successText} subTitle={result.subTitle} extra={ <FormAction actionsPosition="center" actionsRender={this.renderStepActions('result', locale)} /> } /> </MemorizeItem> ) : null} </Memorize> </Form> </Spin> </div> </div> ); }; render() { return <LocaleReceiver>{this.renderStepForm}</LocaleReceiver>; } }
the_stack
* Unit tests for core.ts. */ import {cast, ones, serialization, Tensor, tensor1d, Tensor2D, tensor2d, tensor3d} from '@tensorflow/tfjs-core'; import {SymbolicTensor} from '../engine/topology'; import * as tfl from '../index'; import {Shape} from '../keras_format/common'; import {deserialize} from '../layers/serialization'; import {convertPythonicToTs, convertTsToPythonic} from '../utils/serialization_utils'; import {describeMathCPU, describeMathCPUAndGPU, describeMathCPUAndWebGL2, expectTensorsClose} from '../utils/test_utils'; import {Add, Average, Concatenate, Maximum, Minimum, Multiply} from './merge'; describeMathCPU('Merge Layers Except Concatenate: Symbolic', () => { const layers = [Add, Average, Multiply, Maximum, Minimum]; const symbolicInputShapes: Shape[] = [ [10, 3], [10, 2, 2], ]; const numInputsArray: number[] = [2, 4]; for (const layer of layers) { for (const inputShape of symbolicInputShapes) { for (const numInputs of numInputsArray) { const testTitle = `layer=${layer.name}; inputShape=${JSON.stringify(inputShape)}; ` + `numInputs=${numInputs}`; it(testTitle, () => { const addLayer = new layer({name: layer.name}); const symbolicInputs: tfl.SymbolicTensor[] = []; for (let i = 0; i < numInputs; ++i) { symbolicInputs.push( new tfl.SymbolicTensor('float32', inputShape, null, [], null)); } const output = addLayer.apply(symbolicInputs) as tfl.SymbolicTensor; expect(output.dtype).toEqual(symbolicInputs[0].dtype); expect(output.shape).toEqual(inputShape); }); } } } it('Single input leads to exception', () => { const x = new tfl.SymbolicTensor('float32', [2, 2], null, [], null); const addLayer = tfl.layers.add({name: 'Add'}); expect(() => { addLayer.apply([x]); }).toThrowError(/.*at least 2 inputs\. Got 1 input.*/); }); it('Non-unique batch sizes to exception', () => { const x1 = new tfl.SymbolicTensor('float32', [1, 2], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [2, 2], null, [], null); const addLayer = tfl.layers.add({name: 'Add'}); expect(() => { addLayer.apply([x1, x2]); }).toThrowError(/Can not merge tensors with different batch sizes/); }); }); describeMathCPUAndGPU('Add-Functional', () => { it('Calling without arg returns Layer', () => { expect((tfl.layers.add()).getClassName()).toEqual('Add'); }); it('Calling with config arg returns Layer', () => { expect((tfl.layers.add({name: 'addLayer'})).name.indexOf('addLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 2]}); const input2 = tfl.layers.input({shape: [2, 2]}); const output = tfl.layers.add().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 2]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([1, 2, 3, 4], [2, 2]); const input2 = tensor2d([10, 20, 30, 40], [2, 2]); const output = tfl.layers.add().apply([input1, input2]) as Tensor; expectTensorsClose(output, tensor2d([11, 22, 33, 44], [2, 2])); }); it('predict() with functional model with Add layer works', () => { const input = tfl.layers.input({shape: [24, 24, 3]}); const conv1 = tfl.layers.conv2d({filters: 4, kernelSize: [3, 3]}).apply(input) as tfl.SymbolicTensor; const conv2 = tfl.layers.conv2d({filters: 4, kernelSize: [3, 3]}).apply(input) as tfl.SymbolicTensor; const sum = tfl.layers.add().apply([conv1, conv2]) as tfl.SymbolicTensor; const model = tfl.model({inputs: [input], outputs: sum}); const x = ones([1, 24, 24, 3]); const y = model.predict(x) as Tensor; expect(y.shape).toEqual([1, 22, 22, 4]); }); }); describeMathCPUAndGPU('Multiply-Functional', () => { it('Calling without arg returns Layer', () => { expect(tfl.layers.multiply().getClassName()).toEqual('Multiply'); }); it('Calling with config arg returns Layer', () => { expect(tfl.layers.multiply({name: 'multiplyLayer'}) .name.indexOf('multiplyLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 2]}); const input2 = tfl.layers.input({shape: [2, 2]}); const output = tfl.layers.multiply().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 2]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([1, 2, 3, 4], [2, 2]); const input2 = tensor2d([10, 20, 30, 40], [2, 2]); const output = tfl.layers.multiply().apply([input1, input2]) as Tensor; expectTensorsClose(output, tensor2d([10, 40, 90, 160], [2, 2])); }); }); describeMathCPUAndGPU('Average-Functional', () => { it('Calling without arg returns Layer', () => { expect(tfl.layers.average().getClassName()).toEqual('Average'); }); it('Calling with config arg returns Layer', () => { expect( tfl.layers.average({name: 'averageLayer'}).name.indexOf('averageLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 2]}); const input2 = tfl.layers.input({shape: [2, 2]}); const output = tfl.layers.average().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 2]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([1, 2, 3, 4], [2, 2]); const input2 = tensor2d([10, 20, 30, 40], [2, 2]); const output = tfl.layers.average().apply([input1, input2]) as Tensor; expectTensorsClose(output, tensor2d([5.5, 11, 16.5, 22], [2, 2])); }); }); describeMathCPUAndGPU('Maximum-Functional', () => { it('Calling without arg returns Layer', () => { expect(tfl.layers.maximum().getClassName()).toEqual('Maximum'); }); it('Calling with config arg returns Layer', () => { expect( tfl.layers.maximum({name: 'maximumLayer'}).name.indexOf('maximumLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 2]}); const input2 = tfl.layers.input({shape: [2, 2]}); const output = tfl.layers.maximum().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 2]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([1, 20, 3, 40], [2, 2]); const input2 = tensor2d([10, 2, 30, 4], [2, 2]); const output = tfl.layers.maximum().apply([input1, input2]) as Tensor; expectTensorsClose(output, tensor2d([10, 20, 30, 40], [2, 2])); }); }); describeMathCPUAndGPU('Minimum-Functional', () => { it('Calling without arg returns Layer', () => { expect(tfl.layers.minimum().getClassName()).toEqual('Minimum'); }); it('Calling with config arg returns Layer', () => { expect( tfl.layers.minimum({name: 'minimumLayer'}).name.indexOf('minimumLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 2]}); const input2 = tfl.layers.input({shape: [2, 2]}); const output = tfl.layers.minimum().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 2]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([1, 20, 3, 40], [2, 2]); const input2 = tensor2d([10, 2, 30, 4], [2, 2]); const output = tfl.layers.minimum().apply([input1, input2]) as Tensor; expectTensorsClose(output, tensor2d([1, 2, 3, 4], [2, 2])); }); }); describeMathCPUAndGPU('Concatenate-Functional', () => { it('Calling without arg returns Layer', () => { expect(tfl.layers.concatenate().getClassName()).toEqual('Concatenate'); }); it('Calling with config arg returns Layer', () => { expect(tfl.layers.concatenate({name: 'concatenateLayer'}) .name.indexOf('concatenateLayer')) .toEqual(0); }); it('Calling with symbolic tensors returns symbolic tensor', () => { const input1 = tfl.layers.input({shape: [2, 3]}); const input2 = tfl.layers.input({shape: [2, 4]}); const output = tfl.layers.concatenate().apply([input1, input2]) as tfl.SymbolicTensor; expect(output.shape).toEqual([null, 2, 7]); }); it('Calling with tensors returns tensor', () => { const input1 = tensor2d([[1, 2], [3, 4]], [2, 2]); const input2 = tensor2d([[10, 20], [30, 40]], [2, 2]); const output = tfl.layers.concatenate().apply([input1, input2]) as Tensor; expectTensorsClose( output, tensor2d([[1, 2, 10, 20], [3, 4, 30, 40]], [2, 4])); }); }); describeMathCPU('Concatenate Layer: Symbolic', () => { it('All known shapes', () => { const x1 = new tfl.SymbolicTensor('float32', [2, 3, 4], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [2, 3, 4], null, [], null); const layer0 = tfl.layers.concatenate({}); expect((layer0.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ 2, 3, 8 ]); const layer1 = tfl.layers.concatenate({axis: -1}); expect((layer1.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ 2, 3, 8 ]); const layer2 = tfl.layers.concatenate({axis: 0}); expect((layer2.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ 4, 3, 4 ]); const layer3 = tfl.layers.concatenate({axis: 1}); expect((layer3.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ 2, 6, 4 ]); }); it('Concat axis has unknown shape', () => { const x1 = new tfl.SymbolicTensor('float32', [2, null, 4], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [2, null, 4], null, [], null); const layer = tfl.layers.concatenate({axis: 1}); expect((layer.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ 2, null, 4 ]); }); it('Non-concat axis has unknown shape', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 3, 4], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 5, 4], null, [], null); const layer = tfl.layers.concatenate({axis: 1}); expect((layer.apply([x1, x2]) as tfl.SymbolicTensor).shape).toEqual([ null, 8, 4 ]); }); it('Incompatible shape leads to error', () => { const x1 = new tfl.SymbolicTensor('float32', [2, 3, 5], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [2, 4, 5], null, [], null); const layer = tfl.layers.concatenate({}); expect(() => layer.apply([ x1, x2 ])).toThrowError(/requires inputs with matching shapes except/); }); it('Single shape leads to error', () => { const x1 = new tfl.SymbolicTensor('float32', [2, 3, 5], null, [], null); const layer = tfl.layers.concatenate({}); expect(() => layer.apply([x1])) .toThrowError(/should be called on a list of at least 2 inputs/); }); it('Serialization round trip', () => { const layer = tfl.layers.concatenate({axis: 2}); const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.concatenate(tsConfig); expect(layerPrime.getConfig().axis).toEqual(2); }); }); describeMathCPUAndGPU('Add Layer: Tensor', () => { it('2D plus 2D', () => { const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); const x2 = tensor2d([[-1, -2], [-3, -4]], [2, 2]); const addLayer = tfl.layers.add({}); const y = addLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[9, 18], [27, 36]], [2, 2])); }); it('2D plus 2D, with broadcast', () => { const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); const x2 = tensor2d([[-2], [-4]], [2, 1]); const addLayer = tfl.layers.add({}); const y = addLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[8, 18], [26, 36]], [2, 2])); }); it('2D plus 2D, with dimension expansion', () => { const x1 = tensor3d([[[10, 20], [30, 40]], [[50, 60], [70, 80]]], [2, 2, 2]); const x2 = tensor2d([[-2], [-4]], [2, 1]); const addLayer = tfl.layers.add({}); const y = addLayer.apply([x1, x2]) as Tensor; expectTensorsClose( y, tensor3d([[[8, 18], [28, 38]], [[46, 56], [66, 76]]], [2, 2, 2])); }); it('computeMask', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-2, -1], [-4, -3]]); const addLayer = tfl.layers.add({}); const m1 = tensor1d([true, false], 'bool'); const m2 = tensor1d([true, true], 'bool'); const mask = addLayer.computeMask([x1, x2], [m1, m2]); expectTensorsClose(mask, tensor2d([[true, false]], [1, 2], 'bool')); }); it('computeMask error condition: non-array input', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-2, -1], [-4, -3]]); const addLayer = tfl.layers.add({}); const m1 = tensor1d([true, false], 'bool'); const m2 = tensor1d([true, true], 'bool'); expect(() => addLayer.computeMask(x1, [ m1, m2 ])).toThrowError(/inputs.*should be an Array/); expect(() => addLayer.computeMask([x1, x2], m1)) .toThrowError(/mask.*should be an Array/); }); it('computeMask error condition: incorrect number of masks', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-2, -1], [-4, -3]]); const addLayer = tfl.layers.add({}); const m1 = tensor1d([true, false], 'bool'); expect(() => addLayer.computeMask([x1, x2], [m1])) .toThrowError(/ are expected to have the same/); }); }); describeMathCPUAndGPU('Multiply Layer: Tensor', () => { it('2D times 2D', () => { const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); const x2 = tensor2d([[-1, -2], [-3, -4]], [2, 2]); const multipyLayer = tfl.layers.multiply({}); const y = multipyLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-10, -40], [-90, -160]], [2, 2])); }); // TODO(cais): Reinstate when this issue is fixed: // https://github.com/PAIR-code/deeplearnjs/issues/457 // it('2D times 2D, with broadcast', () => { // const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); // const x2 = tensor2d([[-2], [-4]], [2, 1]); // const multiplyLayer = new Multiply({}); // const y = multiplyLayer.apply([x1, x2]) as Tensor; // expectTensorsClose(y, tensor2d([[-20, -40], [-120, -160]], [2, 2])); // }); }); describeMathCPUAndGPU('Average Layer: Tensor', () => { it('2D and 2D', () => { const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); const x2 = tensor2d([[-2, -4], [-6, -8]], [2, 2]); const averageLayer = tfl.layers.average({}); const y = averageLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[4, 8], [12, 16]], [2, 2])); }); it('2D and 2D, with broadcast', () => { const x1 = tensor2d([[10, 20], [30, 40]], [2, 2]); const x2 = tensor2d([[-2], [-4]], [2, 1]); const averageLayer = tfl.layers.average({}); const y = averageLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[4, 9], [13, 18]], [2, 2])); }); }); describeMathCPUAndGPU('Maximum Layer: Tensor', () => { it('2D and 2D', () => { const x1 = tensor2d([[10, 20], [-6, -8]], [2, 2]); const x2 = tensor2d([[-2, -4], [30, 40]], [2, 2]); const averageLayer = tfl.layers.maximum({}); const y = averageLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[10, 20], [30, 40]], [2, 2])); }); }); describeMathCPUAndGPU('Minimum Layer: Tensor', () => { it('2D and 2D', () => { const x1 = tensor2d([[10, 20], [-6, -8]], [2, 2]); const x2 = tensor2d([[-2, -4], [30, 40]], [2, 2]); const averageLayer = tfl.layers.minimum({}); const y = averageLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-2, -4], [-6, -8]], [2, 2])); }); }); describeMathCPUAndWebGL2('Concatenate Layer: Tensor', () => { let x1: Tensor2D; let x2: Tensor2D; function createData() { x1 = tensor2d([1, 2, 3, 4], [2, 2]); x2 = tensor2d([-1, -2, -3, -4], [2, 2]); } const axisValues: number[] = [null, undefined, 0, 1, -1]; for (const axis of axisValues) { it(`axis=${axis}`, () => { createData(); const layer = tfl.layers.concatenate({axis}); const expected = axis === 0 ? tensor2d([1, 2, 3, 4, -1, -2, -3, -4], [4, 2]) : tensor2d([1, 2, -1, -2, 3, 4, -3, -4], [2, 4]); expectTensorsClose(layer.apply([x1, x2]) as Tensor, expected); }); } it('computeMask', () => { const layer = tfl.layers.concatenate(); const x1 = tensor2d([[1], [0], [1]]); const x2 = tensor2d([[1], [0], [0]]); const mask = layer.computeMask([x1, x2], [cast(x1, 'bool'), cast(x2, 'bool')]); expectTensorsClose(mask, tensor1d([true, false, false], 'bool')); }); // Reference Python code: // ```py // import keras // import numpy as np // // input1 = keras.Input(shape=[4]) // input2 = keras.Input(shape=[4]) // y1 = keras.layers.Embedding(10, // 3, // input_length=4, // mask_zero=True, // embeddings_initializer='ones')(input1) // y1 = keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(y1) // y2 = keras.layers.Embedding(10, // 3, // input_length=4, // mask_zero=True, // embeddings_initializer='ones')(input2) // y2 = keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(y2) // // y = keras.layers.Concatenate()([y1, y2]) // y = keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zeros')(y) // // model = keras.Model(inputs=[input1, input2], outputs=y) // model.summary() // // xs1 = np.array([[0, 0, 0, 0], // [1, 0, 0, 0], // [1, 2, 0, 0], // [1, 2, 3, 0]]) // xs2 = np.array([[0, 0, 0, 0], // [0, 0, 0, 0], // [1, 0, 0, 0], // [1, 2, 0, 0]]) // // ys = model.predict([xs1, xs2]) // print(ys) // ``` it('With masking', () => { const input1 = tfl.input({shape: [4]}); const input2 = tfl.input({shape: [4]}); let y1 = tfl.layers .embedding({ inputDim: 10, outputDim: 3, inputLength: 4, maskZero: true, embeddingsInitializer: 'ones' }) .apply(input1) as SymbolicTensor; y1 = tfl.layers .lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }) .apply(y1) as SymbolicTensor; let y2 = tfl.layers .embedding({ inputDim: 10, outputDim: 3, inputLength: 4, maskZero: true, embeddingsInitializer: 'ones' }) .apply(input2) as SymbolicTensor; y2 = tfl.layers .lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }) .apply(y2) as SymbolicTensor; let y = tfl.layers.concatenate().apply([y1, y2]) as SymbolicTensor; y = tfl.layers .dense( {units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'}) .apply(y) as SymbolicTensor; const model = tfl.model({inputs: [input1, input2], outputs: y}); const xs1 = tensor2d([[0, 0, 0, 0], [1, 0, 0, 0], [1, 2, 0, 0], [1, 2, 3, 0]]); // Notice the mask of xs2 is different from that of xs1. const xs2 = tensor2d([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 2, 0, 0]]); const ys = model.predict([xs1, xs2]) as Tensor; expectTensorsClose( ys, tensor2d([[0], [2.2785282], [5.169547], [5.8760333]])); }); }); describeMathCPU('Deserialize Merge Layers', () => { it('LayersModel with Add Layer', () => { // The following model config JSON can be obtained with Python code: // ```python // import keras // // input1 = keras.Input(shape=[4]) // input2 = keras.Input(shape=[4]) // // output = keras.layers.add([input1, input2]) // model = keras.Model([input1, input2], output) // // model_json = model.to_json() // print(model_json) const modelWithMergeJSON: {} = { 'class_name': 'Model', 'keras_version': '2.1.5', 'config': { 'layers': [ { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, 4], 'name': 'input_1', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_1' }, { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, 4], 'name': 'input_2', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_2' }, { 'class_name': 'Add', 'config': {'trainable': true, 'name': 'add_1'}, 'inbound_nodes': [[['input_1', 0, 0, {}], ['input_2', 0, 0, {}]]], 'name': 'add_1' } ], 'input_layers': [['input_1', 0, 0], ['input_2', 0, 0]], 'output_layers': [['add_1', 0, 0]], 'name': 'model_1' }, 'backend': 'tensorflow' }; const tsConfig = convertPythonicToTs(modelWithMergeJSON) as serialization.ConfigDict; const model = deserialize(tsConfig) as tfl.LayersModel; expect(model.inputs.length).toEqual(2); expect(model.inputs[0].shape).toEqual([null, 4]); expect(model.inputs[1].shape).toEqual([null, 4]); expect(model.layers.length).toEqual(3); expect(model.layers[2] instanceof Add); expect(model.outputs.length).toEqual(1); expect(model.outputs[0].shape).toEqual([null, 4]); }); it('LayersModel with Concatenate Layer', () => { // The following model config JSON can be obtained with Python code: // ```python // import keras // // input1 = keras.Input(shape=[4]) // input2 = keras.Input(shape=[4]) // // output = keras.layers.concatenate([input1, input2]) // model = keras.Model([input1, input2], output) // // model_json = model.to_json() // print(model_json) const modelWithMergeJSON: {} = { 'class_name': 'Model', 'keras_version': '2.1.5', 'config': { 'layers': [ { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, 4], 'name': 'input_1', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_1' }, { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, 4], 'name': 'input_2', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_2' }, { 'class_name': 'Concatenate', 'config': {'trainable': true, 'name': 'concatenate_1', 'axis': -1}, 'inbound_nodes': [[['input_1', 0, 0, {}], ['input_2', 0, 0, {}]]], 'name': 'concatenate_1' } ], 'input_layers': [['input_1', 0, 0], ['input_2', 0, 0]], 'output_layers': [['concatenate_1', 0, 0]], 'name': 'model_1' }, 'backend': 'tensorflow' }; const tsConfig = convertPythonicToTs(modelWithMergeJSON) as serialization.ConfigDict; const model = deserialize(tsConfig) as tfl.LayersModel; expect(model.inputs.length).toEqual(2); expect(model.inputs[0].shape).toEqual([null, 4]); expect(model.inputs[1].shape).toEqual([null, 4]); expect(model.layers.length).toEqual(3); expect(model.layers[2] instanceof Concatenate); expect(model.outputs.length).toEqual(1); expect(model.outputs[0].shape).toEqual([null, 8]); }); }); describeMathCPU('Dot-Layer: Symbolic', () => { // Example refernce Python Keras code: // // ```py // import keras // // x1 = keras.Input(shape=[3, 4]) // x2 = keras.Input(shape=[3]) // dot_layer = keras.layers.Dot(1) // y = dot_layer([x1, x2]) // // print(x1.shape) // print(x2.shape) // print(y.shape) // ``` it('2D x 2D', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 8], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 8], null, [], null); const y1 = tfl.layers.dot({axes: -1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y1.shape).toEqual([null, 1]); const y2 = tfl.layers.dot({axes: 1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 1]); }); it('3D x 3D, axes = -1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const y = tfl.layers.dot({axes: -1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y.shape).toEqual([null, 2, 2]); }); it('3D x 3D, axes = 1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const y2 = tfl.layers.dot({axes: 1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 3, 3]); }); it('3D x 3D, axes = 2', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const y2 = tfl.layers.dot({axes: 2}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 2, 2]); }); it('2D x 3D, axes = -1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const y2 = tfl.layers.dot({axes: -1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 2]); }); it('2D x 3D, axes = 1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 3, 4], null, [], null); const y2 = tfl.layers.dot({axes: 1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 4]); }); it('3D x 2D, axes = -1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 3], null, [], null); const y2 = tfl.layers.dot({axes: -1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 2]); }); it('3D x 2D, axes = -1', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 3, 4], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 3], null, [], null); const y2 = tfl.layers.dot({axes: 1}).apply([x1, x2]) as tfl.SymbolicTensor; expect(y2.shape).toEqual([null, 4]); }); it('computeOutputShape() does not alter input shape', () => { const dotLayer = tfl.layers.dot({axes: 1}); const inputShape1: Shape = [null, 3, 4]; const inputShape2: Shape = [null, 3]; const outputShape = dotLayer.computeOutputShape([inputShape1, inputShape2]); expect(outputShape).toEqual([null, 4]); expect(inputShape1).toEqual([null, 3, 4]); expect(inputShape2).toEqual([null, 3]); }); // TODO(cais): Uncomment the follow test case when 4D and higher is supported // by the Dot layer. // it('4D x 4D, axes = -1', () => { // const x1 = new tfl.SymbolicTensor( // 'float32', [null, 2, 3, 4], null, [], null); // const x2 = new tfl.SymbolicTensor( // 'float32', [null, 2, 3, 4], null, [], null); // const y = tfl.layers.dot({axes: -1}).apply([x1, x2]) as // tfl.SymbolicTensor; // expect(y.shape).toEqual([null, 2, 3, 2, 3]); // }); it('Dimension mismatch leads to error', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 4], null, [], null); expect(() => tfl.layers.dot({axes: -1}).apply([ x1, x2 ])).toThrowError('Dimension incompatibility: 3 !== 4'); }); it('Incorrect number of inputs leads to error', () => { const x1 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x2 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); const x3 = new tfl.SymbolicTensor('float32', [null, 2, 3], null, [], null); expect(() => tfl.layers.dot({axes: -1}).apply([x1])) .toThrowError(/should be called on a list of exactly 2 inputs/); expect(() => tfl.layers.dot({axes: -1}).apply(x1)) .toThrowError(/should be called on a list of exactly 2 inputs/); expect(() => tfl.layers.dot({axes: -1}).apply([ x1, x2, x3 ])).toThrowError(/should be called on a list of exactly 2 inputs/); }); it('Serialization round trip', () => { const layer = tfl.layers.dot({axes: -1, normalize: true}); const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.dot(tsConfig); expect(layerPrime.getConfig().axes).toEqual(-1); expect(layerPrime.getConfig().normalize).toEqual(true); }); }); describeMathCPUAndWebGL2('Dot-Layer: Tensor', () => { // Example reference Python Keras code: // // ```py // import keras // import numpy as np // // x1 = keras.Input(shape=[2]) // x2 = keras.Input(shape=[2]) // dot_layer = keras.layers.Dot(-11) // y = dot_layer([x1, x2]) // // model = keras.Model([x1, x2], y) // model.summary() // // xs1 = np.array([[10, 20], [30, 40]], dtype=np.float32) // xs2 = np.array([[-1, -2], [-3, -4]], dtype=np.float32) // print(model.predict([xs1, xs2])) // ``` it('2D x 2D, axis = -1', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-1, -2], [-3, -4]]); const dotLayer = tfl.layers.dot({axes: -1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-50], [-250]])); }); it('2D x 2D, axis = -1, normalize = true', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-1, -2], [-4, -3]]); const dotLayer = tfl.layers.dot({axes: -1, normalize: true}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-1], [-0.96]])); }); it('2D x 2D, axis = 1', () => { const x1 = tensor2d([[10, 20], [30, 40]]); const x2 = tensor2d([[-1, -2], [-3, -4]]); const dotLayer = tfl.layers.dot({axes: 1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-50], [-250]])); }); it('3D x 2D, axis = -1', () => { const x1 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const x2 = tensor2d([[-1, -2], [-3, -4]]); const dotLayer = tfl.layers.dot({axes: -1}); const y1 = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y1, tensor2d([[-50, -110], [-24, -10]])); const x3 = tensor2d([[1, 2], [3, 4]]); const y2 = dotLayer.apply([x1, x3]) as Tensor; expectTensorsClose(y2, tensor2d([[50, 110], [24, 10]])); }); it('2D x 3D, axis = -1', () => { const x1 = tensor2d([[-1, -2], [-3, -4]]); const x2 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const dotLayer = tfl.layers.dot({axes: -1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-50, -110], [-24, -10]])); }); it('2D x 3D, axis = 1', () => { const x1 = tensor2d([[-1, -2], [-3, -4]]); const x2 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const dotLayer = tfl.layers.dot({axes: 1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose(y, tensor2d([[-70, -100], [-20, -13]])); }); it('3D x 3D, axis = -1', () => { const x1 = tensor3d([[[-1, -2], [-3, -4]], [[5, 6], [7, 8]]]); const x2 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const dotLayer = tfl.layers.dot({axes: -1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose( y, tensor3d([[[-50, -110], [-110, -250]], [[38, 16], [52, 22]]])); }); it('3D x 3D, axis = 1', () => { const x1 = tensor3d([[[-1, -2], [-3, -4]], [[5, 6], [7, 8]]]); const x2 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const dotLayer = tfl.layers.dot({axes: 1}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose( y, tensor3d([[[-100, -140], [-140, -200]], [[34, 22], [40, 26]]])); }); it('3D x 3D, axis = [1, 2]', () => { const x1 = tensor3d([[[-1, -2], [-3, -4]], [[5, 6], [7, 8]]]); const x2 = tensor3d([[[10, 20], [30, 40]], [[4, 3], [2, 1]]]); const dotLayer = tfl.layers.dot({axes: [1, 2]}); const y = dotLayer.apply([x1, x2]) as Tensor; expectTensorsClose( y, tensor3d([[[-70, -150], [-100, -220]], [[41, 17], [48, 20]]])); }); // Reference Python code: // ```py // import keras // import numpy as np // // input1 = keras.Input(shape=[4]) // input2 = keras.Input(shape=[4]) // y1 = keras.layers.Embedding(10, // 3, // input_length=4, // mask_zero=True, // embeddings_initializer='ones')(input1) // y1 = keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(y1) // y2 = keras.layers.Embedding(10, // 3, // input_length=4, // mask_zero=True, // embeddings_initializer='ones')(input2) // y2 = keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(y2) // // y = keras.layers.Dot(axes=[-1, -1])([y1, y2]) // y = keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zeros')(y) // // model = keras.Model(inputs=[input1, input2], outputs=y) // // xs1 = np.array([[0, 0, 0, 0], // [1, 0, 0, 0], // [1, 2, 0, 0], // [1, 2, 3, 0]]) // xs2 = np.array([[0, 0, 0, 0], // [0, 0, 0, 0], // [1, 0, 0, 0], // [1, 2, 0, 0]]) // ys = model.predict([xs1, xs2]) // print(ys) // ``` it('With masking', () => { const input1 = tfl.input({shape: [4]}); const input2 = tfl.input({shape: [4]}); let y1 = tfl.layers .embedding({ inputDim: 10, outputDim: 3, inputLength: 4, maskZero: true, embeddingsInitializer: 'ones' }) .apply(input1) as SymbolicTensor; y1 = tfl.layers .lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }) .apply(y1) as SymbolicTensor; let y2 = tfl.layers .embedding({ inputDim: 10, outputDim: 3, inputLength: 4, maskZero: true, embeddingsInitializer: 'ones' }) .apply(input2) as SymbolicTensor; y2 = tfl.layers .lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }) .apply(y2) as SymbolicTensor; let y = tfl.layers.dot({axes: [-1, -1]}).apply([y1, y2]) as SymbolicTensor; y = tfl.layers .dense( {units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'}) .apply(y) as SymbolicTensor; const model = tfl.model({inputs: [input1, input2], outputs: y}); const xs1 = tensor2d([[0, 0, 0, 0], [1, 0, 0, 0], [1, 2, 0, 0], [1, 2, 3, 0]]); // Notice the mask of xs2 is different from that of xs1. const xs2 = tensor2d([[0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 2, 0, 0]]); const ys = model.predict([xs1, xs2]) as Tensor; expectTensorsClose(ys, tensor2d([[0], [0], [2.195756], [2.8765779]])); }); });
the_stack
declare var App: AppleTVJS.App; declare var Device: AppleTVJS.Device; declare var navigationDocument: AppleTVJS.NavigationDocument; declare var Settings: AppleTVJS.Settings; declare function evaluateScripts(scripts: string[], complete: (success: boolean) => void): void; declare namespace AppleTVJS { interface App { /** * The onError attribute is used to handle any errors sent from the device. * This attribute must be set to a function that accepts an “options” argument. * For example App.onError = function (options) {}. * */ onError: (options: any) => void; /** * The onExit attribute is used to complete any actions that need to be cleaned * up when the app has been exited. This attribute must be set to a function that * accepts an “options” argument. For example App.onExit = function (options) {}. * */ onExit: (options: any) => void; /** * The onLaunch attribute is used to start any required actions when the app * launches. This attribute must be set to a function that accepts an “options” * argument. For example App.onLaunch = function (options) {}. * */ onLaunch: (options: any) => void; /** * This function reloads the initial JavaScript file without quitting the app. * The optional reloadData parameter provides developers with a way to capture * and restart the app in it’s current state. If the reloadData parameter is not * present, the app is restarted in its initial state. This attribute must be set * to a function that accepts an “options” argument. * For example App.onError = function (options) {}. * */ reload(options?: any, reloadData?: any): void; } interface Device { /** The unique identifier for the app. */ appIdentifier: string; /** The current app version. */ appVersion: string; /** A string that identifies the device model. */ model: string; /** The version of the product installed on the device. */ productType: string; /** The operating system on the device. */ systemVersion: string; /** The UUID of the device. */ vendorIdentifier: string; } interface FeatureElement extends Element { /** Gets a feature for a given element. */ getFeature(feature: string): any; } class Highlight { /** The name of the highlight. */ name: string; /** The description of the highlight. */ description: string; /** The starttime of the highlight. */ starttime: number; /** The duration of the highlight. */ duration: number; /** The imageURL of the highlight. */ imageURL: string; } class HighlightGroup { /** The name of the highlight group. */ name: string; /** The hightlights in the highlight group. */ hightlights: Highlight[]; } class Interstitial { /** The starttime of the interstitial. */ starttime: number; /** The duration of the interstitial. */ duration: number; } interface Keyboard { /** The text inside of a searchField or textField element. */ text: string; /** * A callback function that is called when the text inside * of searchField or textField element changes. * */ onTextChange: () => void; } class MediaItem { /** * Creates a new MediaItem object from the information stored in the URL location. * @type: Valid values are: audio, video. Defaults to video. * @url: The URL pointing to the media item information. * */ constructor(type: string, url?: string); /** * The domain that the rating applies to. * There are three valid values for this property: movie, music, and tvshow. * */ contentRatingDomain: string; /** * The rating for a video item. * The rating is a value from 0-1000. This value corresponds to a specific rating * used by different countries. For example, a rating value can represent a PG-13 * rating in the United State and a MA15+ in Australia. * */ contentRatingRanking: number; /** * A value indicating whether the item has explicit lyrics. * This property is ignored if the MediaItem object type is video. * */ isExplicit: boolean; /** The URL path to the artwork that accompanies the media item. */ artworkImageURL: string; /** The description for a media item. */ description: string; /** The subtitle for a the media item. */ subtitle: string; /** The title of the media item. */ title: string; /** * The type of media item. * The valid values for this attribute are audio and video. * */ type: string; /** The URL path to the media item. */ url: string; /** An array of highlightGroup objects. */ highlightGroups: HighlightGroup[]; /** An array of interstitial objects. */ interstitials: Interstitial[]; /** * The number, in seconds, that a media item starts playing at. * Use this to begin playing a MediaItem object at a time other than * at the beginning of the object. If this property contains anything * other than 0, the player displays “Resume” instead of * “Play from beginning” on playback. * */ resumeTime: number; /** A callback function used to load the asset identifier for an item. */ loadAssetID: (url: string, callback: (assetID: string, error: string) => void) => void; /** A callback function used to load the security certificate for an item. */ loadCertificate: (url: string, callback: (certificate: string, error: string) => void) => void; /** A callback function used to load the security key for an item. */ loadKey: (url: string, requestData: any, callback: (key: string, renewalDate: string, error: string) => void) => void; } interface MenuBarDocument { /** * Retrieves the document associated with the specified menu item. * */ getDocument(menuItem: Element): Document; /** * Associates a document with a menu item. * */ setDocument(document: Document, menuItem: Element): void; /** * Sets the focus in a menu bar to the specified menu item. * */ setSelectedItem(menuItem: Element): void; } interface NavigationDocument { /** * Inserts a new document directly before a document currently on the stack. * */ insertBeforeDocument(document: Document, beforeDocument?: Document): void; /** * This function searches the stack for the first instance of the document * contained in the beforeDocument parameter and inserts the document contained * in the document parameter on top of it. * */ pushDocument(document: Document): void; /** * Replaces a document on the stack with a new document. * */ replaceDocument(document: Document, beforeDocument?: Document): void; /** Dismisses the document displayed in modal view. */ dismissModal(): void; /** * Displays the passed document on top of the current document. * */ presentModal(document: Document): void; /** The documents currently on the stack. */ documents: Document[]; /** * Removes all documents currently on the stack. * */ clear(): void; /** * Removes the top most document from the stack. * */ popDocument(): void; /** * Removes all of the documents on the stack that are above the passed document. * */ popToDocument(document: Document): void; /** * Removes all documents from the stack except for the bottom most document. * */ popToRootDocument(): void; /** * Removes the specified document from the stack. * */ removeDocument(document: Document): void; } class Player { /** The annotations for a video created by placing a DOM document over the video. */ overlayDocument: Document; /** The play list for a player. */ playlist: Playlist; /** Shows the player UI if it is not currently visible. */ present(): void; /** Pauses the currently playing media item. */ pause(): void; /** Plays the currently selected media item. */ play(): void; /** * The current state of the player. * * This property can contain the following valid values: * begin * end * loading * playing * paused * scanning * */ playbackState: string; /** Sets the playback point to a specified time. */ seekToTime(time: number): void; /** Sets the playback speed. */ setPlaybackRate(playbackRate: number): void; /** Stops the currently playing item and dismisses the player UI. */ stop(): void; /** The currently selected media item in the playlist. */ currentMediaItem: MediaItem; /** The next media item in the playlist. */ nextMediaItem: MediaItem; /** The previous MediaItem object in the playlist. */ previousMediaItem: MediaItem; /** * An event notifying the listener that the player is about to change media items. * * Valid values are: * errorDidOccur * fastForwardedToEndOfMediaItem * mannuallyChanged * newPlaylist * playerInvalidated * playedToEndOfMediaItem * */ mediaItemDidChange: (reason: string) => void; /** * An event that indicates if a seek to time request was accomplished. * * The values for this attribute can be one of the following: * true — The seek performed as requested. * false or null— The seek was not performed. * An integer value — The seek will be performed to the stated value and not the initial requested value. * */ requestSeekToTime: (result?: any) => void; /** An event that indicates a state change request has occurred. */ shouldHandleStateChange: (result: boolean) => void; /** An event that indicates the state has changed. */ stateDidChange: () => void; /** An event that indicates the state is about to change. */ stateWillChange: () => void; /** An event that indicates a particular playback time has been crossed. */ timeBoundaryDidCross: () => void; /** An event that happens at a specified interval. */ timeDidChange: () => void; /** An event that happens whenever a specified piece of metadata occurs. */ timedMetadata: () => void; } class Playlist { /** Returns the MediaItem located in the indicated array index. */ item(index: number): MediaItem; /** The number of items in the playlist. */ length: number; /** Removes a media item from the end of a playlist. */ pop(): MediaItem; /** Adds a media item to the end of a playlist. */ push(object: MediaItem): void; /** Deletes the indicated array elements and replaces them with the specified elements. */ splice(index: number, howManu: number, object: MediaItem): MediaItem[]; } interface Restrictions { /** A boolean value that indicates if explicit media is allowed. */ allowsExplicit: boolean; /** The maximum movie ranking allowed. */ maxMovieRank: number; /** The maximum movie rating allowed for the specified country. */ maxMovieRatingForCountry(countryCode: string): string; /** The maximum television show ranking allowed. */ maxTVShowRank: number /** Sets the maximum television show rating allowed for the specified country. */ maxTVShowRatingForCountry(countryCode: string): string; } interface Settings { /** Contains the restriction information on the device. */ restrictions: Restrictions; /** Contains the language the device displays information in. */ language: string; /** Contains the country code used by the store on this device. */ storefrontCountryCode: string; /** * Called when changes to a device’s restriction information changes. */ onRestrictionsChange: () => void; } class TVError { /** The error code. */ code: string; /** A string containing the description of the error. */ description: string; /** * A string containing the error domain. * * The predefined error domains: * NSPOSIXErrorDomain - POSIX/BSD errors * NSOSStatusErrorDomain - OS X/Carbon errors * NSMachErrorDomain - Mach errors * */ domain: string; /** * The user info dictionary. * * These keys may exist in the user info dictionary: * NSLocalizedDesciptionKey * NSFilePathErrorKey * NSStringEncodingErrorKey * NSUnderlyingErrorKey * NSURLErrorKey * NSLocalizedFailureReasonErrorKey * NSLocalizedRecoverySuggestionErrorKey * NSLocalizedRecoveryOptionsErrorKey * NSRecoveryAttempterErrorKey * NSHelpAnchorErrorKey * NSURLErrorFailingURLErrorKey * NSURLErrorFailingURLStringErrorKey * NSURLErrorFailingURLPeerTrustErrorKey * */ userInfo: any; } }
the_stack
import { assertNotNull } from "common"; import { ShaderAttributes, SizingData, Texture, Uniform, UniformType, } from "types"; import { ZerdeParser } from "zerde"; type UniformLocation = { name: string; offset: number; ty: string; loc: WebGLUniformLocation | null; fn: WebGLRenderer["uniformFnTable"][number]; }; export class WebGLRenderer { private canvas: HTMLCanvasElement | OffscreenCanvas; private memory: WebAssembly.Memory; private sizingData: SizingData; private shaders: { geomAttribs: ReturnType<WebGLRenderer["getAttribLocations"]>; instAttribs: ReturnType<WebGLRenderer["getAttribLocations"]>; passUniforms: ReturnType<WebGLRenderer["getUniformLocations"]>; viewUniforms: ReturnType<WebGLRenderer["getUniformLocations"]>; drawUniforms: ReturnType<WebGLRenderer["getUniformLocations"]>; userUniforms: ReturnType<WebGLRenderer["getUniformLocations"]>; textureSlots: ReturnType<WebGLRenderer["getUniformLocations"]>; instanceSlots: number; program: WebGLProgram; ash: ShaderAttributes; }[]; private indexBuffers: { glBuf: WebGLBuffer; length: number }[]; private arrayBuffers: { glBuf: WebGLBuffer; length: number }[]; private vaos: { glVao: WebGLVertexArrayObjectOES; geomIbId: number; geomVbId: number; instVbId: number; }[]; private textures: Texture[]; private framebuffers: WebGLFramebuffer[]; private gl: WebGLRenderingContext; // eslint-disable-next-line camelcase private OESVertexArrayObject!: OES_vertex_array_object; // eslint-disable-next-line camelcase private ANGLEInstancedArrays!: ANGLE_instanced_arrays; private targetWidth: number; private targetHeight: number; private clearFlags: number; private clearR: number; private clearG: number; private clearB: number; private clearA: number; private clearDepth: number; private zerdeParser!: ZerdeParser; private basef32!: Float32Array; private baseu32!: Uint32Array; constructor( canvas: HTMLCanvasElement | OffscreenCanvas, memory: WebAssembly.Memory, sizingData: SizingData, incompatibleBrowserCallback: () => void ) { this.canvas = canvas; this.memory = memory; this.sizingData = sizingData; this.shaders = []; this.indexBuffers = []; this.arrayBuffers = []; this.vaos = []; this.textures = []; this.framebuffers = []; this.targetWidth = 0; this.targetHeight = 0; this.clearFlags = 0; this.clearR = 0; this.clearG = 0; this.clearB = 0; this.clearA = 0; this.clearDepth = 0; // this.isMainCanvas = false; const options = { preferLowPowerToHighPerformance: true, // xrCompatible: true // TODO(JP): Bring back some day? }; // @ts-ignore - TODO(Paras): Get proper support for OffscreenCanvas this.gl = // @ts-ignore canvas.getContext("webgl", options) || // @ts-ignore canvas.getContext("webgl-experimental", options) || // @ts-ignore canvas.getContext("experimental-webgl", options); if (!this.gl) { incompatibleBrowserCallback(); return; } this.OESVertexArrayObject = assertNotNull( this.gl.getExtension("OES_vertex_array_object") ); this.ANGLEInstancedArrays = assertNotNull( this.gl.getExtension("ANGLE_instanced_arrays") ); this.gl.getExtension("OES_standard_derivatives"); this.gl.getExtension("OES_element_index_uint"); this.resize(sizingData); } processMessages(zerdeParserPtr: number): void { this.zerdeParser = new ZerdeParser(this.memory, zerdeParserPtr); this.basef32 = new Float32Array(this.memory.buffer); this.baseu32 = new Uint32Array(this.memory.buffer); // eslint-disable-next-line no-constant-condition while (true) { const msgType = this.zerdeParser.parseU32(); if (this.sendFnTable[msgType](this)) { break; } } } resize(sizingData: SizingData): void { this.sizingData = sizingData; this.canvas.width = sizingData.width * sizingData.dpiFactor; this.canvas.height = sizingData.height * sizingData.dpiFactor; } private getAttribLocations( program: WebGLProgram, base: string, slots: number ): { loc: number; offset: number; size: number; stride: number; }[] { const gl = this.gl; const attribLocs = []; let attribs = slots >> 2; if ((slots & 3) != 0) attribs++; for (let i = 0; i < attribs; i++) { let size = slots - i * 4; if (size > 4) size = 4; attribLocs.push({ loc: gl.getAttribLocation(program, base + i), offset: i * 16, size: size, stride: slots * 4, }); } return attribLocs; } private getUniformLocations( program: WebGLProgram, uniforms: Uniform[] ): UniformLocation[] { const gl = this.gl; const uniformLocs: UniformLocation[] = []; let offset = 0; for (let i = 0; i < uniforms.length; i++) { const uniform = uniforms[i]; // lets align the uniform const slots = uniformSizeTable[uniform.ty]; if ((offset & 3) != 0 && (offset & 3) + slots > 4) { // goes over the boundary offset += 4 - (offset & 3); // make jump to new slot } uniformLocs.push({ name: uniform.name, offset: offset << 2, ty: uniform.ty, loc: gl.getUniformLocation(program, uniform.name), fn: this.uniformFnTable[uniform.ty], }); offset += slots; } return uniformLocs; } private compileWebGLShader(ash: ShaderAttributes): void { const gl = this.gl; const vsh = assertNotNull(gl.createShader(gl.VERTEX_SHADER)); gl.shaderSource(vsh, ash.vertex); gl.compileShader(vsh); if (!gl.getShaderParameter(vsh, gl.COMPILE_STATUS)) { console.log(gl.getShaderInfoLog(vsh), addLineNumbersToString(ash.vertex)); } // compile pixelshader const fsh = assertNotNull(gl.createShader(gl.FRAGMENT_SHADER)); gl.shaderSource(fsh, ash.fragment); gl.compileShader(fsh); if (!gl.getShaderParameter(fsh, gl.COMPILE_STATUS)) { console.log( gl.getShaderInfoLog(fsh), addLineNumbersToString(ash.fragment) ); } const program = assertNotNull(gl.createProgram()); gl.attachShader(program, vsh); gl.attachShader(program, fsh); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { console.log( gl.getProgramInfoLog(program), addLineNumbersToString(ash.vertex), addLineNumbersToString(ash.fragment) ); } // fetch all attribs and uniforms this.shaders[ash.shaderId] = { geomAttribs: this.getAttribLocations( program, "mpsc_packed_geometry_", ash.geometrySlots ), instAttribs: this.getAttribLocations( program, "mpsc_packed_instance_", ash.instanceSlots ), passUniforms: this.getUniformLocations(program, ash.passUniforms), viewUniforms: this.getUniformLocations(program, ash.viewUniforms), drawUniforms: this.getUniformLocations(program, ash.drawUniforms), userUniforms: this.getUniformLocations(program, ash.userUniforms), textureSlots: this.getUniformLocations(program, ash.textureSlots), instanceSlots: ash.instanceSlots, program: program, ash: ash, }; } private allocArrayBuffer(arrayBufferId: number, array: Float32Array): void { const gl = this.gl; let buf = this.arrayBuffers[arrayBufferId]; if (buf === undefined) { buf = this.arrayBuffers[arrayBufferId] = { glBuf: assertNotNull(gl.createBuffer()), length: array.length, }; } else { buf.length = array.length; } gl.bindBuffer(gl.ARRAY_BUFFER, buf.glBuf); gl.bufferData(gl.ARRAY_BUFFER, array, gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER, null); } private allocIndexBuffer(indexBufferId: number, array: Uint32Array): void { const gl = this.gl; let buf = this.indexBuffers[indexBufferId]; if (buf === undefined) { buf = this.indexBuffers[indexBufferId] = { glBuf: assertNotNull(gl.createBuffer()), length: array.length, }; } else { buf.length = array.length; } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf.glBuf); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array, gl.STATIC_DRAW); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); } private allocVao( vaoId: number, shaderId: number, geomIbId: number, geomVbId: number, instVbId: number ): void { const gl = this.gl; const oldVao = this.vaos[vaoId]; if (oldVao) { this.OESVertexArrayObject.deleteVertexArrayOES(oldVao.glVao); } const glVao = assertNotNull( this.OESVertexArrayObject.createVertexArrayOES() ); const vao = (this.vaos[vaoId] = { glVao, geomIbId, geomVbId, instVbId }); this.OESVertexArrayObject.bindVertexArrayOES(vao.glVao); gl.bindBuffer(gl.ARRAY_BUFFER, this.arrayBuffers[geomVbId].glBuf); const shader = this.shaders[shaderId]; for (let i = 0; i < shader.geomAttribs.length; i++) { const attr = shader.geomAttribs[i]; if (attr.loc < 0) { continue; } gl.vertexAttribPointer( attr.loc, attr.size, gl.FLOAT, false, attr.stride, attr.offset ); gl.enableVertexAttribArray(attr.loc); this.ANGLEInstancedArrays.vertexAttribDivisorANGLE(attr.loc, 0); } gl.bindBuffer(gl.ARRAY_BUFFER, this.arrayBuffers[instVbId].glBuf); for (let i = 0; i < shader.instAttribs.length; i++) { const attr = shader.instAttribs[i]; if (attr.loc < 0) { continue; } gl.vertexAttribPointer( attr.loc, attr.size, gl.FLOAT, false, attr.stride, attr.offset ); gl.enableVertexAttribArray(attr.loc); this.ANGLEInstancedArrays.vertexAttribDivisorANGLE(attr.loc, 1); } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffers[geomIbId].glBuf); this.OESVertexArrayObject.bindVertexArrayOES(null); } private drawCall( shaderId: number, vaoId: number, passUniformsPtr: number, viewUniformsPtr: number, drawUniformsPtr: number, userUniformsPtr: number, texturesPtr: number ): void { const gl = this.gl; const shader = this.shaders[shaderId]; gl.useProgram(shader.program); const vao = this.vaos[vaoId]; this.OESVertexArrayObject.bindVertexArrayOES(vao.glVao); const indexBuffer = this.indexBuffers[vao.geomIbId]; const instanceBuffer = this.arrayBuffers[vao.instVbId]; // set up uniforms TODO do this a bit more incremental based on uniform layer // also possibly use webGL2 uniform buffers. For now this will suffice for webGL 1 compat const passUniforms = shader.passUniforms; // if vr_presenting const viewUniforms = shader.viewUniforms; for (let i = 0; i < viewUniforms.length; i++) { const uni = viewUniforms[i]; uni.fn(this, uni.loc, uni.offset + viewUniformsPtr); } const drawUniforms = shader.drawUniforms; for (let i = 0; i < drawUniforms.length; i++) { const uni = drawUniforms[i]; uni.fn(this, uni.loc, uni.offset + drawUniformsPtr); } const userUniforms = shader.userUniforms; for (let i = 0; i < userUniforms.length; i++) { const uni = userUniforms[i]; uni.fn(this, uni.loc, uni.offset + userUniformsPtr); } const textureSlots = shader.textureSlots; for (let i = 0; i < textureSlots.length; i++) { const texSlot = textureSlots[i]; const texId = this.baseu32[(texturesPtr >> 2) + i]; const texObj = this.textures[texId]; gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(gl.TEXTURE_2D, texObj); gl.uniform1i(texSlot.loc, i); } const indices = indexBuffer.length; const instances = instanceBuffer.length / shader.instanceSlots; // if (this.isMainCanvas && xrIsPresenting) { // for (let i = 3; i < pass_uniforms.length; i ++) { // let uni = pass_uniforms[i]; // uni.fn(this, uni.loc, uni.offset + pass_uniforms_ptr); // } // // the first 2 matrices are project and view // let left_viewport = this.xr_left_viewport; // gl.viewport(left_viewport.x, left_viewport.y, left_viewport.width, left_viewport.height); // gl.uniformMatrix4fv(pass_uniforms[0].loc, false, this.xr_left_projection_matrix); // gl.uniformMatrix4fv(pass_uniforms[1].loc, false, this.xr_left_transform_matrix); // gl.uniformMatrix4fv(pass_uniforms[2].loc, false, this.xr_left_invtransform_matrix); // this.ANGLE_instanced_arrays.drawElementsInstancedANGLE(gl.TRIANGLES, indices, gl.UNSIGNED_INT, 0, instances); // let right_viewport = this.xr_right_viewport; // gl.viewport(right_viewport.x, right_viewport.y, right_viewport.width, right_viewport.height); // gl.uniformMatrix4fv(pass_uniforms[0].loc, false, this.xr_right_projection_matrix); // gl.uniformMatrix4fv(pass_uniforms[1].loc, false, this.xr_right_transform_matrix); // gl.uniformMatrix4fv(pass_uniforms[2].loc, false, this.xr_right_invtransform_matrix); // this.ANGLE_instanced_arrays.drawElementsInstancedANGLE(gl.TRIANGLES, indices, gl.UNSIGNED_INT, 0, instances); // } else { for (let i = 0; i < passUniforms.length; i++) { const uni = passUniforms[i]; uni.fn(this, uni.loc, uni.offset + passUniformsPtr); } this.ANGLEInstancedArrays.drawElementsInstancedANGLE( gl.TRIANGLES, indices, gl.UNSIGNED_INT, 0, instances ); // } this.OESVertexArrayObject.bindVertexArrayOES(null); } private allocTexture( textureId: number, width: number, height: number, dataPtr: number ): void { const gl = this.gl; const glTex = this.textures[textureId] || gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, glTex); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); const data = new Uint8Array( this.memory.buffer, dataPtr, width * height * 4 ); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data ); this.textures[textureId] = glTex as Texture; } private beginRenderTargets( passId: number, width: number, height: number ): void { const gl = this.gl; this.targetWidth = width; this.targetHeight = height; this.clearFlags = 0; // this.isMainCanvas = false; const glFramebuffer = this.framebuffers[passId] || (this.framebuffers[passId] = assertNotNull(gl.createFramebuffer())); gl.bindFramebuffer(gl.FRAMEBUFFER, glFramebuffer); } private addColorTarget( textureId: number, initOnly: number, r: number, g: number, b: number, a: number ): void { // if use_default this.clearR = r; this.clearG = g; this.clearB = b; this.clearA = a; const gl = this.gl; const glTex = this.textures[textureId] || (this.textures[textureId] = gl.createTexture() as Texture); // resize or create texture if ( glTex.mpWidth != this.targetWidth || glTex.mpHeight != this.targetHeight ) { gl.bindTexture(gl.TEXTURE_2D, glTex); this.clearFlags |= gl.COLOR_BUFFER_BIT; glTex.mpWidth = this.targetWidth; glTex.mpHeight = this.targetHeight; gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, glTex.mpWidth, glTex.mpHeight, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); } else if (!initOnly) { this.clearFlags |= gl.COLOR_BUFFER_BIT; } gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTex, 0 ); } private setDepthTarget( textureId: number, initOnly: number, depth: number ): void { const gl = this.gl; this.clearDepth = depth; const glRenderBuffer = this.textures[textureId] || (this.textures[textureId] = gl.createRenderbuffer() as Texture); if ( glRenderBuffer.mpWidth != this.targetWidth || glRenderBuffer.mpHeight != this.targetHeight ) { // Borrowed concept from https://webglfundamentals.org/webgl/lessons/webgl-render-to-texture.html gl.bindRenderbuffer(gl.RENDERBUFFER, glRenderBuffer); this.clearFlags |= gl.DEPTH_BUFFER_BIT; glRenderBuffer.mpWidth = this.targetWidth; glRenderBuffer.mpHeight = this.targetHeight; gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.targetWidth, this.targetHeight ); } else if (!initOnly) { this.clearFlags |= gl.DEPTH_BUFFER_BIT; } gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, glRenderBuffer ); } private endRenderTargets(): void { const gl = this.gl; // process the actual 'clear' gl.viewport(0, 0, this.targetWidth, this.targetHeight); // check if we need to clear color, and depth // clear it if (this.clearFlags) { gl.clearColor(this.clearR, this.clearG, this.clearB, this.clearA); gl.clearDepth(this.clearDepth); gl.clear(this.clearFlags); } } private setDefaultDepthAndBlendMode(): void { const gl = this.gl; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); gl.enable(gl.BLEND); } private beginMainCanvas( r: number, g: number, b: number, a: number, depth: number ): void { const gl = this.gl; // this.isMainCanvas = true; // if (this.xrIsPresenting) { // let xr_webgllayer = this.xr_session.renderState.baseLayer; // this.gl.bindFramebuffer(gl.FRAMEBUFFER, xr_webgllayer.framebuffer); // gl.viewport(0, 0, xr_webgllayer.framebufferWidth, xr_webgllayer.framebufferHeight); // // quest 1 is 3648 // // quest 2 is 4096 // let left_view = this.xr_pose.views[0]; // let right_view = this.xr_pose.views[1]; // this.xr_left_viewport = xr_webgllayer.getViewport(left_view); // this.xr_right_viewport = xr_webgllayer.getViewport(right_view); // this.xr_left_projection_matrix = left_view.projectionMatrix; // this.xr_left_transform_matrix = left_view.transform.inverse.matrix; // this.xr_left_invtransform_matrix = left_view.transform.matrix; // this.xr_right_projection_matrix = right_view.projectionMatrix; // this.xr_right_transform_matrix = right_view.transform.inverse.matrix; // this.xr_right_camera_pos = right_view.transform.inverse.position; // this.xr_right_invtransform_matrix = right_view.transform.matrix; // } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.viewport( 0, 0, this.sizingData.width * this.sizingData.dpiFactor, this.sizingData.height * this.sizingData.dpiFactor ); // } gl.clearColor(r, g, b, a); gl.clearDepth(depth); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } private uniformFnTable: Record< string, (zelf: WebGLRenderer, loc: WebGLUniformLocation | null, off: number) => void > = { float: function setFloat(zelf, loc, off) { const slot = off >> 2; zelf.gl.uniform1f(loc, zelf.basef32[slot]); }, vec2: function setVec2(zelf, loc, off) { const slot = off >> 2; const basef32 = zelf.basef32; zelf.gl.uniform2f(loc, basef32[slot], basef32[slot + 1]); }, vec3: function setVec3(zelf, loc, off) { const slot = off >> 2; const basef32 = zelf.basef32; zelf.gl.uniform3f( loc, basef32[slot], basef32[slot + 1], basef32[slot + 2] ); }, vec4: function setVec4(zelf, loc, off) { const slot = off >> 2; const basef32 = zelf.basef32; zelf.gl.uniform4f( loc, basef32[slot], basef32[slot + 1], basef32[slot + 2], basef32[slot + 3] ); }, mat2: function setMat2(zelf, loc, off) { zelf.gl.uniformMatrix2fv( loc, false, new Float32Array(zelf.memory.buffer, off, 4) ); }, mat3: function setMat3(zelf, loc, off) { zelf.gl.uniformMatrix3fv( loc, false, new Float32Array(zelf.memory.buffer, off, 9) ); }, mat4: function setMat4(zelf, loc, off) { const mat4 = new Float32Array(zelf.memory.buffer, off, 16); zelf.gl.uniformMatrix4fv(loc, false, mat4); }, }; // Array of function id's wasm can call on us; `zelf` is pointer to WebGLRenderer. // (It's not called `self` as to not overload https://developer.mozilla.org/en-US/docs/Web/API/Window/self) // Function names are suffixed with the index in the array, and annotated with // their name in cx_webgl.rs, for easier matching. private sendFnTable: ((zelf: this) => void | boolean)[] = [ // end function end0(_zelf) { return true; }, // compile_webgl_shader function compileWebGLShader1(zelf) { function parseShvarvec(): Uniform[] { const len = zelf.zerdeParser.parseU32(); const vars: Uniform[] = []; for (let i = 0; i < len; i++) { vars.push({ ty: zelf.zerdeParser.parseString() as UniformType, name: zelf.zerdeParser.parseString(), }); } return vars; } const ash = { shaderId: zelf.zerdeParser.parseU32(), fragment: zelf.zerdeParser.parseString(), vertex: zelf.zerdeParser.parseString(), geometrySlots: zelf.zerdeParser.parseU32(), instanceSlots: zelf.zerdeParser.parseU32(), passUniforms: parseShvarvec(), viewUniforms: parseShvarvec(), drawUniforms: parseShvarvec(), userUniforms: parseShvarvec(), textureSlots: parseShvarvec(), }; zelf.compileWebGLShader(ash); }, // alloc_array_buffer function allocArrayBuffer2(zelf) { const arrayBufferId = zelf.zerdeParser.parseU32(); const len = zelf.zerdeParser.parseU32(); const pointer = zelf.zerdeParser.parseU32(); const array = new Float32Array(zelf.memory.buffer, pointer, len); zelf.allocArrayBuffer(arrayBufferId, array); }, // alloc_index_buffer function allocIndexBuffer3(zelf) { const indexBufferId = zelf.zerdeParser.parseU32(); const len = zelf.zerdeParser.parseU32(); const pointer = zelf.zerdeParser.parseU32(); const array = new Uint32Array(zelf.memory.buffer, pointer, len); zelf.allocIndexBuffer(indexBufferId, array); }, // alloc_vao function allocVao4(zelf) { const vaoId = zelf.zerdeParser.parseU32(); const shaderId = zelf.zerdeParser.parseU32(); const geomIbId = zelf.zerdeParser.parseU32(); const geomVbId = zelf.zerdeParser.parseU32(); const instVbId = zelf.zerdeParser.parseU32(); zelf.allocVao(vaoId, shaderId, geomIbId, geomVbId, instVbId); }, // draw_call function drawCall5(zelf) { const shaderId = zelf.zerdeParser.parseU32(); const vaoId = zelf.zerdeParser.parseU32(); const uniformsPassPtr = zelf.zerdeParser.parseU32(); const uniformsViewPtr = zelf.zerdeParser.parseU32(); const uniformsDrawPtr = zelf.zerdeParser.parseU32(); const uniformsUserPtr = zelf.zerdeParser.parseU32(); const textures = zelf.zerdeParser.parseU32(); zelf.drawCall( shaderId, vaoId, uniformsPassPtr, uniformsViewPtr, uniformsDrawPtr, uniformsUserPtr, textures ); }, // update_texture_image2d function allocTexture6(zelf) { const textureId = zelf.zerdeParser.parseU32(); const width = zelf.zerdeParser.parseU32(); const height = zelf.zerdeParser.parseU32(); const dataPtr = zelf.zerdeParser.parseU32(); zelf.allocTexture(textureId, width, height, dataPtr); }, // begin_render_targets function beginRenderTargets7(zelf) { const passId = zelf.zerdeParser.parseU32(); const width = zelf.zerdeParser.parseU32(); const height = zelf.zerdeParser.parseU32(); zelf.beginRenderTargets(passId, width, height); }, // add_color_target function addColorTarget8(zelf) { const textureId = zelf.zerdeParser.parseU32(); const initOnly = zelf.zerdeParser.parseU32(); const r = zelf.zerdeParser.parseF32(); const g = zelf.zerdeParser.parseF32(); const b = zelf.zerdeParser.parseF32(); const a = zelf.zerdeParser.parseF32(); zelf.addColorTarget(textureId, initOnly, r, g, b, a); }, // set_depth_target function setDepthTarget9(zelf) { const textureId = zelf.zerdeParser.parseU32(); const initOnly = zelf.zerdeParser.parseU32(); const depth = zelf.zerdeParser.parseF32(); zelf.setDepthTarget(textureId, initOnly, depth); }, // end_render_targets function endRenderTargets10(zelf) { zelf.endRenderTargets(); }, // set_default_depth_and_blend_mode function setDefaultDepthAndBlendMode11(zelf) { zelf.setDefaultDepthAndBlendMode(); }, // begin_main_canvas function beginMainCanvas12(zelf) { const r = zelf.zerdeParser.parseF32(); const g = zelf.zerdeParser.parseF32(); const b = zelf.zerdeParser.parseF32(); const a = zelf.zerdeParser.parseF32(); const depth = zelf.zerdeParser.parseF32(); zelf.beginMainCanvas(r, g, b, a, depth); }, ]; } const uniformSizeTable = { float: 1, vec2: 2, vec3: 3, vec4: 4, mat2: 4, mat3: 9, mat4: 16, }; function addLineNumbersToString(code: string) { const lines = code.split("\n"); let out = ""; for (let i = 0; i < lines.length; i++) { out += i + 1 + ": " + lines[i] + "\n"; } return out; }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [appmesh-preview](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsappmeshpreview.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class AppmeshPreview extends PolicyStatement { public servicePrefix = 'appmesh-preview'; /** * Statement provider for service [appmesh-preview](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsappmeshpreview.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 create a gateway route that is associated with a virtual gateway * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateGatewayRoute.html */ public toCreateGatewayRoute() { return this.to('CreateGatewayRoute'); } /** * Grants permission to create a service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateMesh.html */ public toCreateMesh() { return this.to('CreateMesh'); } /** * Grants permission to create a route that is associated with a virtual router * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateRoute.html */ public toCreateRoute() { return this.to('CreateRoute'); } /** * Grants permission to create a virtual gateway within a service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateVirtualGateway.html */ public toCreateVirtualGateway() { return this.to('CreateVirtualGateway'); } /** * Grants permission to create a virtual node within a service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateVirtualNode.html */ public toCreateVirtualNode() { return this.to('CreateVirtualNode'); } /** * Grants permission to create a virtual router within a service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateVirtualRouter.html */ public toCreateVirtualRouter() { return this.to('CreateVirtualRouter'); } /** * Grants permission to create a virtual service within a service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_CreateVirtualService.html */ public toCreateVirtualService() { return this.to('CreateVirtualService'); } /** * Grants permission to delete an existing gateway route * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteGatewayRoute.html */ public toDeleteGatewayRoute() { return this.to('DeleteGatewayRoute'); } /** * Grants permission to delete an existing service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteMesh.html */ public toDeleteMesh() { return this.to('DeleteMesh'); } /** * Grants permission to delete an existing route * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteRoute.html */ public toDeleteRoute() { return this.to('DeleteRoute'); } /** * Grants permission to delete an existing virtual gateway * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteVirtualGateway.html */ public toDeleteVirtualGateway() { return this.to('DeleteVirtualGateway'); } /** * Grants permission to delete an existing virtual node * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteVirtualNode.html */ public toDeleteVirtualNode() { return this.to('DeleteVirtualNode'); } /** * Grants permission to delete an existing virtual router * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteVirtualRouter.html */ public toDeleteVirtualRouter() { return this.to('DeleteVirtualRouter'); } /** * Grants permission to delete an existing virtual service * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DeleteVirtualService.html */ public toDeleteVirtualService() { return this.to('DeleteVirtualService'); } /** * Grants permission to describe an existing gateway route * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeGatewayRoute.html */ public toDescribeGatewayRoute() { return this.to('DescribeGatewayRoute'); } /** * Grants permission to describe an existing service mesh * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeMesh.html */ public toDescribeMesh() { return this.to('DescribeMesh'); } /** * Grants permission to describe an existing route * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeRoute.html */ public toDescribeRoute() { return this.to('DescribeRoute'); } /** * Grants permission to describe an existing virtual gateway * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeVirtualGateway.html */ public toDescribeVirtualGateway() { return this.to('DescribeVirtualGateway'); } /** * Grants permission to describe an existing virtual node * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeVirtualNode.html */ public toDescribeVirtualNode() { return this.to('DescribeVirtualNode'); } /** * Grants permission to describe an existing virtual router * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeVirtualRouter.html */ public toDescribeVirtualRouter() { return this.to('DescribeVirtualRouter'); } /** * Grants permission to describe an existing virtual service * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_DescribeVirtualService.html */ public toDescribeVirtualService() { return this.to('DescribeVirtualService'); } /** * Grants permission to list existing gateway routes in a service mesh * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListGatewayRoutes.html */ public toListGatewayRoutes() { return this.to('ListGatewayRoutes'); } /** * Grants permission to list existing service meshes * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListMeshes.html */ public toListMeshes() { return this.to('ListMeshes'); } /** * Grants permission to list existing routes in a service mesh * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListRoutes.html */ public toListRoutes() { return this.to('ListRoutes'); } /** * Grants permission to list existing virtual gateways in a service mesh * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListVirtualGateways.html */ public toListVirtualGateways() { return this.to('ListVirtualGateways'); } /** * Grants permission to list existing virtual nodes * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListVirtualNodes.html */ public toListVirtualNodes() { return this.to('ListVirtualNodes'); } /** * Grants permission to list existing virtual routers in a service mesh * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListVirtualRouters.html */ public toListVirtualRouters() { return this.to('ListVirtualRouters'); } /** * Grants permission to list existing virtual services in a service mesh * * Access Level: List * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_ListVirtualServices.html */ public toListVirtualServices() { return this.to('ListVirtualServices'); } /** * Grants permission to receive streamed resources for an App Mesh endpoint (VirtualNode/VirtualGateway) * * Access Level: Read * * https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html */ public toStreamAggregatedResources() { return this.to('StreamAggregatedResources'); } /** * Grants permission to update an existing gateway route for a specified service mesh and virtual gateway * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateGatewayRoute.html */ public toUpdateGatewayRoute() { return this.to('UpdateGatewayRoute'); } /** * Grants permission to update an existing service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateMesh.html */ public toUpdateMesh() { return this.to('UpdateMesh'); } /** * Grants permission to update an existing route for a specified service mesh and virtual router * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateRoute.html */ public toUpdateRoute() { return this.to('UpdateRoute'); } /** * Grants permission to update an existing virtual gateway in a specified service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateVirtualGateway.html */ public toUpdateVirtualGateway() { return this.to('UpdateVirtualGateway'); } /** * Grants permission to update an existing virtual node in a specified service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateVirtualNode.html */ public toUpdateVirtualNode() { return this.to('UpdateVirtualNode'); } /** * Grants permission to update an existing virtual router in a specified service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateVirtualRouter.html */ public toUpdateVirtualRouter() { return this.to('UpdateVirtualRouter'); } /** * Grants permission to update an existing virtual service in a specified service mesh * * Access Level: Write * * https://docs.aws.amazon.com/app-mesh/latest/APIReference/API_UpdateVirtualService.html */ public toUpdateVirtualService() { return this.to('UpdateVirtualService'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateGatewayRoute", "CreateMesh", "CreateRoute", "CreateVirtualGateway", "CreateVirtualNode", "CreateVirtualRouter", "CreateVirtualService", "DeleteGatewayRoute", "DeleteMesh", "DeleteRoute", "DeleteVirtualGateway", "DeleteVirtualNode", "DeleteVirtualRouter", "DeleteVirtualService", "UpdateGatewayRoute", "UpdateMesh", "UpdateRoute", "UpdateVirtualGateway", "UpdateVirtualNode", "UpdateVirtualRouter", "UpdateVirtualService" ], "Read": [ "DescribeGatewayRoute", "DescribeMesh", "DescribeRoute", "DescribeVirtualGateway", "DescribeVirtualNode", "DescribeVirtualRouter", "DescribeVirtualService", "StreamAggregatedResources" ], "List": [ "ListGatewayRoutes", "ListMeshes", "ListRoutes", "ListVirtualGateways", "ListVirtualNodes", "ListVirtualRouters", "ListVirtualServices" ] }; /** * Adds a resource of type mesh to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html * * @param meshName - Identifier for the meshName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onMesh(meshName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}'; arn = arn.replace('${MeshName}', meshName); 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 virtualService to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html * * @param meshName - Identifier for the meshName. * @param virtualServiceName - Identifier for the virtualServiceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onVirtualService(meshName: string, virtualServiceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualService/${VirtualServiceName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualServiceName}', virtualServiceName); 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 virtualNode to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html * * @param meshName - Identifier for the meshName. * @param virtualNodeName - Identifier for the virtualNodeName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onVirtualNode(meshName: string, virtualNodeName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualNode/${VirtualNodeName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualNodeName}', virtualNodeName); 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 virtualRouter to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html * * @param meshName - Identifier for the meshName. * @param virtualRouterName - Identifier for the virtualRouterName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onVirtualRouter(meshName: string, virtualRouterName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualRouter/${VirtualRouterName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualRouterName}', virtualRouterName); 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 route to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html * * @param meshName - Identifier for the meshName. * @param virtualRouterName - Identifier for the virtualRouterName. * @param routeName - Identifier for the routeName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onRoute(meshName: string, virtualRouterName: string, routeName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualRouter/${VirtualRouterName}/route/${RouteName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualRouterName}', virtualRouterName); arn = arn.replace('${RouteName}', routeName); 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 virtualGateway to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_gateways.html * * @param meshName - Identifier for the meshName. * @param virtualGatewayName - Identifier for the virtualGatewayName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onVirtualGateway(meshName: string, virtualGatewayName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualGateway/${VirtualGatewayName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualGatewayName}', virtualGatewayName); 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 gatewayRoute to the statement * * https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_gateways.html * * @param meshName - Identifier for the meshName. * @param virtualGatewayName - Identifier for the virtualGatewayName. * @param gatewayRouteName - Identifier for the gatewayRouteName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onGatewayRoute(meshName: string, virtualGatewayName: string, gatewayRouteName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:appmesh-preview:${Region}:${Account}:mesh/${MeshName}/virtualGateway/${VirtualGatewayName}/gatewayRoute/${GatewayRouteName}'; arn = arn.replace('${MeshName}', meshName); arn = arn.replace('${VirtualGatewayName}', virtualGatewayName); arn = arn.replace('${GatewayRouteName}', gatewayRouteName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
declare namespace ast { /** * Base type for all nodes that represent grammar AST. * * @template {T} Type of the node */ interface Node<T> { /** Defines type of each node */ type: T; /** * Location in the source grammar where node is located. Locations of all * child nodes always inside location of their parent node. */ location: LocationRange; } enum MatchResult { ALWAYS = 1, SOMETIMES = 0, NEVER = -1, } /** * Base interface for all nodes that forming a rule expression. * * @template {T} Type of the node */ interface Expr<T> extends Node<T> { /** * The estimated result of matching this node against any input: * * - `-1`: negative result, matching of that node always fails * - `0`: neutral result, may be fail, may be match * - `1`: positive result, always match * * This property is created by the `inferenceMatchResult` pass. */ match?: MatchResult; } /** The main Peggy AST class returned by the parser. */ interface Grammar extends Node<"grammar"> { /** Initializer that run once when importing generated parser module. */ topLevelInitializer?: TopLevelInitializer; /** Initializer that run each time when `parser.parse()` method in invoked. */ initializer?: Initializer; /** List of all rules in that grammar. */ rules: Rule[]; /** Added by the `generateJs` pass and contains the JS code. */ code?: string; } /** * Base interface for all initializer nodes with the code. * * @template {T} Type of the node */ interface CodeBlock<T> extends Node<T> { /** The code from the grammar. */ code: string; /** Span that covers all code between `{` and `}`. */ codeLocation: LocationRange; } /** * Base interface for all expression nodes with the code. * * @template {T} Type of the node */ interface CodeBlockExpr<T> extends Expr<T> { /** The code from the grammar. */ code: string; /** Span that covers all code between `{` and `}`. */ codeLocation: LocationRange; } /** * Code that runs one-time on import generated parser or right after * `generate(..., { output: "parser" })` returns. */ interface TopLevelInitializer extends CodeBlock<"top_level_initializer"> {} /** Code that runs on each `parse()` call of the generated parser. */ interface Initializer extends CodeBlock<"initializer"> {} interface Rule extends Expr<"rule"> { /** Identifier of the rule. Should be unique in the grammar. */ name: string; /** * Span of the identifier of the rule. Used for pointing to the rule * in error messages. */ nameLocation: LocationRange; /** Parsing expression of this rule. */ expression: Named | Expression; /** Added by the `generateBytecode` pass. */ bytecode?: number[]; } /** Represents rule body if it has a name. */ interface Named extends Expr<"named"> { /** Name of the rule that will appear in the error messages. */ name: string; expression: Expression; } /** Arbitrary expression of the grammar. */ type Expression = Choice | Action | Sequence | Labeled | Prefixed | Suffixed | Primary; /** One element of the choice node. */ type Alternative = Action | Sequence | Labeled | Prefixed | Suffixed | Primary; interface Choice extends Expr<"choice"> { /** * List of expressions to match. Only one of them could match the input, * the first one that matched is used as a result of the `choice` node. */ alternatives: Alternative[]; } interface Action extends CodeBlockExpr<"action"> { expression: ( Sequence | Labeled | Prefixed | Suffixed | Primary ); } /** One element of the sequence node. */ type Element = Labeled | Prefixed | Suffixed | Primary; interface Sequence extends Expr<"sequence"> { /** List of expressions each of them should match in order to match the sequence. */ elements: Element[]; } interface Labeled extends Expr<"labeled"> { /** If `true`, labeled expression is one of automatically returned. */ pick?: true; /** * Name of the variable under that result of `expression` will be available * in the user code. */ label: string | null; /** * Span of the identifier of the label. Used for pointing to the label * in error messages. If `label` is `null` then this location pointed * to the `@` symbol (pick symbol). */ labelLocation: LocationRange; /** Expression which result will be available in the user code under name `label`. */ expression: Prefixed | Suffixed | Primary; } /** Expression with a preceding operator. */ interface Prefixed extends Expr<"text" | "simple_and" | "simple_not"> { expression: Suffixed | Primary; } /** Expression with a following operator. */ interface Suffixed extends Expr<"optional" | "zero_or_more" | "one_or_more"> { expression: Primary; } type Primary = RuleReference | SemanticPredicate | Group | Literal | CharacterClass | Any; interface RuleReference extends Expr<"rule_ref"> { /** Name of the rule to refer. */ name: string; } interface SemanticPredicate extends CodeBlockExpr<"semantic_and" | "semantic_not"> {} /** Group node introduces new scope for labels. */ interface Group extends Expr<"group"> { expression: Labeled | Sequence; } /** Matches continuous sequence of symbols. */ interface Literal extends Expr<"literal"> { /** Sequence of symbols to match. */ value: string; /** If `true`, symbols matches even if they case do not match case in the `value`. */ ignoreCase: boolean; } /** Matches single UTF-16 character. */ interface CharacterClass extends Expr<"class"> { /** * Each part represents either symbol range or single symbol. * If empty, such character class never matches anything, even end-of-stream marker. */ parts: (string[] | string)[]; /** * If `true`, matcher will match, if symbol from input doesn't contains * in the `parts`. */ inverted: boolean; /** * If `true`, symbol matches even if it case do not match case of `string` parts, * or it case-paired symbol in the one of ranges of `string[]` parts. */ ignoreCase: boolean; } /** Matches any UTF-16 code unit in the input, but doesn't match the empty string. */ interface Any extends Expr<"any"> {} } /** Current Peggy version in semver format. */ export const VERSION: string; /** Default list of reserved words. Contains list of JavaScript reserved words */ export const RESERVED_WORDS: string[]; /** * The entry that maps object in the `source` property of error locations * to the actual source text of a grammar. That entries is necessary for * formatting errors. */ export interface SourceText { /** * Identifier of a grammar that stored in the `location().source` property * of error and diagnostic messages. * * This one should be the same object that used in the `location().source`, * because their compared using `===`. */ source: any; /** Source text of a grammar. */ text: string; } export interface DiagnosticNote { message: string; location: LocationRange; } /** Thrown if the grammar contains a semantic error. */ export class GrammarError extends Error { /** Location of the error in the source. */ location?: LocationRange; /** Additional messages with context information. */ diagnostics: DiagnosticNote[]; constructor( message: string, location?: LocationRange, diagnostics?: DiagnosticNote[] ); /** * Format the error with associated sources. The `location.source` should have * a `toString()` representation in order the result to look nice. If source * is `null` or `undefined`, it is skipped from the output * * Sample output: * ``` * Error: Label "head" is already defined * --> examples/arithmetics.pegjs:15:17 * | * 15 | = head:Factor head:(_ ("*" / "/") _ Factor)* { * | ^^^^ * note: Original label location * --> examples/arithmetics.pegjs:15:5 * | * 15 | = head:Factor head:(_ ("*" / "/") _ Factor)* { * | ^^^^ * ``` * * @param sources mapping from location source to source text * * @returns the formatted error */ format(sources: SourceText[]): string; toString(): string; } export namespace parser { /** * Parses grammar and returns the grammar AST. * * @param grammar Source text of the grammar * @param options Parser options * * @throws {SyntaxError} If `grammar` has an incorrect format */ function parse(grammar: string, options?: Options): ast.Grammar; /** Options, accepted by the parser of PEG grammar. */ interface Options { /** * Object that will be attached to the each `LocationRange` object created by * the parser. For example, this can be path to the parsed file or even the * File object. */ grammarSource?: any; /** * List of words that won't be allowed as label names. Using such word will * produce a syntax error. */ reservedWords: string[]; /** The only acceptable rule is `"Grammar"`, all other values leads to the exception */ startRule?: "Grammar"; } /** Specific sequence of symbols is expected in the parsed source. */ interface LiteralExpectation { type: "literal"; /** Expected sequence of symbols. */ text: string; /** If `true`, symbols of any case is expected. `text` in that case in lower case */ ignoreCase: boolean; } /** One of the specified symbols is expected in the parse position. */ interface ClassExpectation { type: "class"; /** List of symbols and symbol ranges expected in the parse position. */ parts: (string[] | string)[]; /** * If `true`, meaning of `parts` is inverted: symbols that NOT expected in * the parse position. */ inverted: boolean; /** If `true`, symbols of any case is expected. `text` in that case in lower case */ ignoreCase: boolean; } /** Any symbol is expected in the parse position. */ interface AnyExpectation { type: "any"; } /** EOF is expected in the parse position. */ interface EndExpectation { type: "end"; } /** * Something other is expected in the parse position. That expectation is * generated by call of the `expected()` function in the parser code, as * well as rules with human-readable names. */ interface OtherExpectation { type: "other"; /** * Depending on the origin of this expectation, can be: * - text, supplied to the `expected()` function * - human-readable name of the rule */ description: string; } type Expectation = LiteralExpectation | ClassExpectation | AnyExpectation | EndExpectation | OtherExpectation; /** Thrown if the grammar contains a syntax error. */ class SyntaxError extends Error { /** Location where error was originated. */ location: LocationRange; /** * List of possible tokens in the parse position, or `null` if error was * created by the `error()` call. */ expected: Expectation[] | null; /** * Character in the current parse position, or `null` if error was created * by the `error()` call. */ found: string | null; /** * Format the error with associated sources. The `location.source` should have * a `toString()` representation in order the result to look nice. If source * is `null` or `undefined`, it is skipped from the output * * Sample output: * ``` * Error: Expected "!", "$", "&", "(", ".", "@", character class, comment, end of line, identifier, literal, or whitespace but "#" found. * --> my grammar:3:9 * | * 3 | start = # 'a'; * | ^ * ``` * * @param sources mapping from location source to source text * * @returns the formatted error */ format(sources: SourceText[]): string; /** * Constructs the human-readable message from the machine representation. * * @param expected Array of expected items, generated by the parser * @param found Any text that will appear as found in the input instead of expected */ static buildMessage(expected: Expectation[], found: string): string; } } export namespace compiler { namespace visitor { /** List of possible visitors of AST nodes. */ interface NodeTypes { /** * Default behavior: run visitor: * - on the top level initializer, if it is defined * - on the initializer, if it is defined * - on each element in `rules` * * At the end return `undefined` * * @param node Reference to the whole AST * @param args Any arguments passed to the `Visitor` */ grammar?(node: ast.Grammar, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Node, representing user-defined code that executed only once * when initializing the generated parser (during importing generated * code) * @param args Any arguments passed to the `Visitor` */ top_level_initializer?( node: ast.TopLevelInitializer, ...args: any[] ): any; /** * Default behavior: do nothing * * @param node Node, representing user-defined code that executed on each * run of the `parse()` method of the generated parser * @param args Any arguments passed to the `Visitor` */ initializer?(node: ast.Initializer, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing one structural element of the grammar * @param args Any arguments passed to the `Visitor` */ rule?(node: ast.Rule, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing assigning a human-readable name to * the rule * @param args Any arguments passed to the `Visitor` */ named?(node: ast.Named, ...args: any[]): any; /** * Default behavior: run visitor on each element in `alternatives`, * return `undefined` * * @param node Node, representing ordered choice of the one expression * to match * @param args Any arguments passed to the `Visitor` */ choice?(node: ast.Choice, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing execution of the user-defined action * in the grammar * @param args Any arguments passed to the `Visitor` */ action?(node: ast.Action, ...args: any[]): any; /** * Default behavior: run visitor on each element in `elements`, * return `undefined` * * @param node Node, representing ordered sequence of expressions to match * @param args Any arguments passed to the `Visitor` */ sequence?(node: ast.Sequence, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing labeling of the `expression` result * @param args Any arguments passed to the `Visitor` */ labeled?(node: ast.Labeled, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing usage of part of matched input * @param args Any arguments passed to the `Visitor` */ text?(node: ast.Prefixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing positive lookahead check * @param args Any arguments passed to the `Visitor` */ simple_and?(node: ast.Prefixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing negative lookahead check * @param args Any arguments passed to the `Visitor` */ simple_not?(node: ast.Prefixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing optional presenting of the `expression` * @param args Any arguments passed to the `Visitor` */ optional?(node: ast.Suffixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing repetition of the `expression` any number of times * @param args Any arguments passed to the `Visitor` */ zero_or_more?(node: ast.Suffixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, representing repetition of the `expression` at least once * @param args Any arguments passed to the `Visitor` */ one_or_more?(node: ast.Suffixed, ...args: any[]): any; /** * Default behavior: run visitor on `expression` and return it result * * @param node Node, introducing new scope for the labels * @param args Any arguments passed to the `Visitor` */ group?(node: ast.Group, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing positive lookahead check * @param args Any arguments passed to the `Visitor` */ semantic_and?(node: ast.SemanticPredicate, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing negative lookahead check * @param args Any arguments passed to the `Visitor` */ semantic_not?(node: ast.SemanticPredicate, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing using of the another rule * @param args Any arguments passed to the `Visitor` */ rule_ref?(node: ast.RuleReference, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing match of a continuous sequence of symbols * @param args Any arguments passed to the `Visitor` */ literal?(node: ast.Literal, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing match of a characters range * @param args Any arguments passed to the `Visitor` */ class?(node: ast.CharacterClass, ...args: any[]): any; /** * Default behavior: do nothing * * @param node Leaf node, representing match of an any character * @param args Any arguments passed to the `Visitor` */ any?(node: ast.Any, ...args: any[]): any; } type AnyFunction = (...args: any[]) => any; /** * Callable object that runs traversal of the AST starting from the node * `node` by calling corresponding visitor function. All additional * arguments of the call will be forwarded to the visitor function. * * Visitors are created by calling `build()` with object, containing all * necessary visit functions. All functions, not defined explicitly, will * receive appropriate default. See the function definitions in the type * `Nodes` for description of the default behavior. * * @template {F} Object with visitors of AST nodes */ interface Visitor<F extends NodeTypes> { /** * Runs visitor function registered for the specified node type. * Returns value from the visitor function for the node. * * @param node Reference to the AST node * @param args Extra arguments that will be forwarded to the corresponding * visitor function, associated with `T` * * @template {T} Type of the AST node */ <T extends keyof NodeTypes>( node: ast.Node<T>, ...args: any[] ): ReturnType<F[T] & AnyFunction>; } /** * Creates visitor object for traversing the AST. * * @param functions Object with visitor functions */ function build<F extends NodeTypes>(functions: F): Visitor<F>; } /** * Mapping from the stage name to the default pass suite. * Plugins can extend or replace the list of passes during configuration. */ interface Stages { /** * Pack of passes that performing checks on the AST. This bunch of passes * executed in the very beginning of the compilation stage. */ check: Pass[]; /** * Pack of passes that performing transformation of the AST. * Various types of optimizations are performed here. */ transform: Pass[]; /** Pack of passes that generates the code. */ generate: Pass[]; /** Any additional stages that can be added in the future. */ [key: string]: Pass[]; } /** List of the compilation stages. */ let passes: Stages; /** * Generates a parser from a specified grammar AST. * * Note that not all errors are detected during the generation and some may * protrude to the generated parser and cause its malfunction. * * @param ast Abstract syntax tree of the grammar from a parser * @param stages List of compilation stages * @param options Compilation options * * @return A parser object * * @throws {GrammarError} If the AST contains a semantic error, for example, * duplicated labels */ function compile( ast: ast.Grammar, stages: Stages, options?: ParserBuildOptions ): Parser; /** * Generates a parser source from a specified grammar AST. * * Note that not all errors are detected during the generation and some may * protrude to the generated parser and cause its malfunction. * * @param ast Abstract syntax tree of the grammar from a parser * @param stages List of compilation stages * @param options Compilation options * * @return A parser source code * * @throws {GrammarError} If the AST contains a semantic error, for example, * duplicated labels */ function compile( ast: ast.Grammar, stages: Stages, options: SourceBuildOptions ): string; } /** Provides information pointing to a location within a source. */ export interface Location { /** Line in the parsed source (1-based). */ line: number; /** Column in the parsed source (1-based). */ column: number; /** Offset in the parsed source (0-based). */ offset: number; } /** The `start` and `end` position's of an object within the source. */ export interface LocationRange { /** Any object that was supplied to the `parse()` call as the `grammarSource` option. */ source: any; /** Position at the beginning of the expression. */ start: Location; /** Position after the end of the expression. */ end: Location; } export interface ParserOptions { /** * Object that will be attached to the each `LocationRange` object created by * the parser. For example, this can be path to the parsed file or even the * File object. */ grammarSource?: any; startRule?: string; tracer?: ParserTracer; [key: string]: any; } export interface Parser { parse(input: string, options?: ParserOptions): any; SyntaxError: parser.SyntaxError; } export interface ParserTracer { trace(event: ParserTracerEvent): void; } export type ParserTracerEvent = | { type: "rule.enter"; rule: string; location: LocationRange } | { type: "rule.match"; rule: string; result: any; location: LocationRange } | { type: "rule.fail"; rule: string; location: LocationRange }; /** * Function that performs checking, transformation or analysis of the AST. * * @param ast Reference to the parsed grammar. Pass can change it * @param options Options that was supplied to the `PEG.generate()` call. * All passes shared the same options object */ export type Pass = (ast: ast.Grammar, options: ParserBuildOptions) => void; /** * List of possible compilation stages. Each stage consist of the one or * several passes. Three default stage are defined, but plugins can insert * as many new stages as they want. But keep in mind, that order of stages * execution is defined by the insertion order (or declaration order in case * of the object literal) properties with stage names. */ export interface Stages { /** * Passes that should check correctness of the parser AST. Passes in that * stage shouldn't modify the ast, if modification is required, use the * `transform` stage. This is the first stage executed. */ check: Pass[]; /** * Passes that should transform initial AST. They could add or remove some * nodes from the AST, or calculate some properties on nodes. That stage is * executed after the `check` stage but before the `generate` stage. */ transform: Pass[]; /** * Passes that should generate the final code. This is the last stage executed */ generate: Pass[]; } /** * Object that will be passed to the each plugin during their setup. * Plugins can replace `parser` and add new pass(es) to the `passes` array. */ export interface Config { /** * Parser object that will be used to parse grammar source. Plugin can replace it. */ parser: Parser; /** * List of stages with compilation passes that plugin usually should modify * to add their own pass. */ passes: Stages; /** * List of words that won't be allowed as label names. Using such word will * produce a syntax error. This property can be replaced by the plugin if * it want to change list of reserved words. By default this list is equals * to `RESERVED_WORDS`. */ reservedWords: string[]; } /** Interface for the Peggy extenders. */ export interface Plugin { /** * This method is called at start of the `generate()` call, before even parser * of the supplied grammar will be invoked. All plugins invoked in the order in * which their registered in the `options.plugins` array. * * @param config Object that can be modified by plugin to enhance generated parser * @param options Options that was supplied to the `generate()` call. Plugin * can find their own parameters there. It is recommended to store all * options in the object with name of plugin to reduce possible clashes */ use(config: Config, options: ParserBuildOptions): void; } /** * Parser dependencies, is an object which maps variables used to access the * dependencies in the parser to module IDs used to load them */ export interface Dependencies { [variable: string]: string; } export interface BuildOptionsBase { /** Rules the parser will be allowed to start parsing from (default: the first rule in the grammar) */ allowedStartRules?: string[]; /** If `true`, makes the parser cache results, avoiding exponential parsing time in pathological cases but making the parser slower (default: `false`) */ cache?: boolean; /** * Object that will be attached to the each `LocationRange` object created by * the parser. For example, this can be path to the parsed file or even the * File object. */ grammarSource?: any; /** * Selects between optimizing the generated parser for parsing speed (`"speed"`) * or code size (`"size"`) (default: `"speed"`) * * @deprecated This feature was deleted in 1.2.0 release and has no effect anymore. * It will be deleted in 2.0. * Parser is always generated in the former `"speed"` mode */ optimize?: "speed" | "size"; /** Plugins to use */ plugins?: Plugin[]; /** Makes the parser trace its progress (default: `false`) */ trace?: boolean; } export interface ParserBuildOptions extends BuildOptionsBase { /** If set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ output?: "parser"; } export interface OutputFormatAmdCommonjsEs extends BuildOptionsBase { /** If set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ output: "source"; /** Format of the generated parser (`"amd"`, `"bare"`, `"commonjs"`, `"es"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ format: "amd" | "commonjs" | "es"; /** * Parser dependencies, the value is an object which maps variables used to * access the dependencies in the parser to module IDs used to load them; * valid only when `format` is set to `"amd"`, `"commonjs"`, `"es"`, or `"umd"` * (default: `{}`) */ dependencies?: Dependencies; } export interface OutputFormatUmd extends BuildOptionsBase { /** If set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ output: "source"; /** Format of the generated parser (`"amd"`, `"bare"`, `"commonjs"`, `"es"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ format: "umd"; /** * Parser dependencies, the value is an object which maps variables used to * access the dependencies in the parser to module IDs used to load them; * valid only when `format` is set to `"amd"`, `"commonjs"`, `"es"`, or `"umd"` * (default: `{}`) */ dependencies?: Dependencies; /** * Name of a global variable into which the parser object is assigned to when * no module loader is detected; valid only when `format` is set to `"globals"` * (and in that case it should be defined) or `"umd"` (default: `null`) */ exportVar?: string; } export interface OutputFormatGlobals extends BuildOptionsBase { /** If set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ output: "source"; /** Format of the generated parser (`"amd"`, `"bare"`, `"commonjs"`, `"es"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ format: "globals"; /** * Name of a global variable into which the parser object is assigned to when * no module loader is detected; valid only when `format` is set to `"globals"` * (and in that case it should be defined) or `"umd"` (default: `null`) */ exportVar: string; } export interface OutputFormatBare extends BuildOptionsBase { /** If set to `"parser"`, the method will return generated parser object; if set to `"source"`, it will return parser source code as a string (default: `"parser"`) */ output: "source"; /** Format of the generated parser (`"amd"`, `"bare"`, `"commonjs"`, `"es"`, `"globals"`, or `"umd"`); valid only when `output` is set to `"source"` (default: `"bare"`) */ format?: "bare"; } /** Options for generating source code of the parser. */ export type SourceBuildOptions = OutputFormatUmd | OutputFormatBare | OutputFormatGlobals | OutputFormatAmdCommonjsEs; /** * Returns a generated parser object. * * @param grammar String in the format described by the meta-grammar in the * `parser.pegjs` file * @param options Options that allow you to customize returned parser object * * @throws {SyntaxError} If the grammar contains a syntax error, for example, * an unclosed brace * @throws {GrammarError} If the grammar contains a semantic error, for example, * duplicated labels */ export function generate(grammar: string, options?: ParserBuildOptions): Parser; /** * Returns the generated source code as a `string` in the specified module format. * * @param grammar String in the format described by the meta-grammar in the * `parser.pegjs` file * @param options Options that allow you to customize returned parser object * * @throws {SyntaxError} If the grammar contains a syntax error, for example, * an unclosed brace * @throws {GrammarError} If the grammar contains a semantic error, for example, * duplicated labels */ export function generate(grammar: string, options: SourceBuildOptions): string; // Export all exported stuff under a global variable PEG in non-module environments export as namespace PEG;
the_stack
const teamTypes = ['read', 'write', 'admin']; const defaultLargeAdminTeamSize = 250; import { WebhookProcessor } from '../organizationProcessor'; import { Operations } from '../../business'; import { Organization } from '../../business'; import RenderHtmlMail from '../../lib/emailRender'; import { IMailProvider } from '../../lib/mailProvider'; import getCompanySpecificDeployment from '../../middleware/companySpecificDeployment'; interface IAutomaticTeamsMail { to: string; cc?: string; subject: string; category?: string[]; content?: string; } interface ICustomDataEventName { content?: string; receipt: string; eventName?: string; } export default class AutomaticTeamsWebhookProcessor implements WebhookProcessor { processOrgSpecialTeams(organization: Organization) { const specialTeams = organization.specialRepositoryPermissionTeams; let specials = []; let specialTeamIds = new Set<number>(); let specialTeamLevels = new Map<number, string>(); teamTypes.forEach(specialTeam => { if (specialTeams[specialTeam] && specialTeams[specialTeam].length) { specials.push(specialTeam); for (let i = 0; i < specialTeams[specialTeam].length; i++) { const teamId = specialTeams[specialTeam][i]; specialTeamIds.add(teamId); specialTeamLevels.set(teamId, translateSpecialToGitHub(specialTeam)); } } }); return { specialTeams, specials, specialTeamIds, specialTeamLevels }; } filter(data: any) { const eventType = data.properties.event; const eventAction = data.body.action; // Someone added a team to the repo if (eventType === 'team' && ['add_repository', 'added_to_repository'].includes(eventAction)) { return true; } // Someone removed a team from the repo if (eventType === 'team' && eventAction === 'removed_from_repository') { return true; } // Team permission level changed if (eventType === 'team' && eventAction === 'edited') { return true; } // A new repo may need the teams if (eventType === 'repository' && eventAction === 'created') { return true; } return false; } async run(operations: Operations, organization: Organization, data: any): Promise<boolean> { const eventType = data.properties.event; const eventAction = data.body.action; const { specialTeamIds, specialTeamLevels } = this.processOrgSpecialTeams(organization); const preventLargeTeamPermissions = organization.preventLargeTeamPermissions; const repositoryBody = data.body.repository; const newPermissions = repositoryBody ? repositoryBody.permissions : null; const whoChangedIt = (data.body && data.body.sender ? data.body.sender.login : null) as string; const whoChangedItId = whoChangedIt ? data.body.sender.id : null; // New repository if (eventType === 'repository' && eventAction === 'created') { for (const teamId of specialTeamIds) { const necessaryPermission = specialTeamLevels.get(teamId); await setTeamPermission(operations, organization, repositoryBody, teamId, necessaryPermission, `a new repository was created by username ${whoChangedIt}, setting automatic permissions`); } } else if (eventType === 'team') { const teamBody = data.body.team; const teamId = teamBody.id; const teamName = teamBody.name; // Enforce required special team permissions if (specialTeamIds.has(teamId)) { const necessaryPermission = specialTeamLevels.get(teamId); if (!necessaryPermission) { throw new Error(`No ideal permission level found for the team ${teamId}.`); } if (eventAction === 'removed_from_repository') { // Someone removed the entire team await setTeamPermission(operations, organization, repositoryBody, teamId, necessaryPermission, `the team and its permission were removed by the username ${whoChangedIt}`); } else if (eventAction === 'edited') { // The team no longer has the appropriate permission level if (newPermissions[necessaryPermission] !== true) { await setTeamPermission(operations, organization, repositoryBody, teamId, necessaryPermission, `the permission was downgraded by the username ${whoChangedIt}`); } } return true; } // Prevent granting large teams access if (preventLargeTeamPermissions) { const teamSize = await getTeamSize(organization, teamId); // Special thanks to the GitHub API team. The added_to_repository event did not // include the 'permissions' information. Fixed and deployed by GitHub on // 6/13/17. Thank you for helping us simplify our code! if (['added_to_repository', 'edited'].includes(eventAction) && newPermissions) { const specificReason = teamTooLargeForPurpose(teamId, newPermissions.admin, newPermissions.push, organization, teamSize, preventLargeTeamPermissions); if (specificReason && !operations.isSystemAccountByUsername(whoChangedIt)) { await revertLargePermissionChange(operations, organization, repositoryBody, teamId, teamName, whoChangedIt, whoChangedItId, specificReason); } } return true; } } return true; } } function teamTooLargeForPurpose(teamId, isAdmin, isPush, organization, teamSize, preventLargeTeamPermissions) { const broadAccessTeams = organization.broadAccessTeams; let isBroadAccessTeam = broadAccessTeams && broadAccessTeams.includes(teamId); if (isBroadAccessTeam && (isAdmin || isPush)) { return 'The team is a very broad access team and does not allow push (write) or admin access to prevent widespread escalation of privileges and spamming thousands of people'; } let teamSizeLimitAdmin = defaultLargeAdminTeamSize; let teamSizeLimitType = 'default limit'; if (preventLargeTeamPermissions && preventLargeTeamPermissions.maximumAdministrators) { teamSizeLimitAdmin = preventLargeTeamPermissions.maximumAdministrators; teamSizeLimitType = `administrator team limit in the ${organization.name} organization`; } if (isAdmin && teamSize >= teamSizeLimitAdmin) { return `The team has ${teamSize} members which surpasses the ${teamSizeLimitAdmin} ${teamSizeLimitType}`; } return false; } function translateSpecialToGitHub(ourTerm) { switch (ourTerm) { case 'admin': return 'admin'; case 'write': return 'push'; case 'read': return 'pull'; } throw new Error(`Unknown team type ${ourTerm}`); } export async function getTeamSize(organization: Organization, teamId): Promise<number> { const team = organization.team(teamId); await team.getDetails(); return team.members_count || 0; } async function revertLargePermissionChange(operations: Operations, organization: Organization, repositoryBody, teamId, teamName: string, whoChangedIt, whoChangedItId: string, specificReason?: string) { specificReason = specificReason ? ': ' + specificReason : ''; const blockReason = `the permission was upgraded by ${whoChangedIt} but a large team permission prevention feature has reverted the change${specificReason}`; console.log(blockReason); const insights = operations.insights; insights.trackMetric({ name: 'JobAutomaticTeamsLargeTeamPermissionBlock', value: 1 }); insights.trackEvent({ name: 'JobAutomaticTeamsLargeTeamPermissionBlocked', properties: { specificReason: specificReason, teamId: teamId, organization: organization.name, repository: repositoryBody.name, whoChangedIt: whoChangedIt, whoChangedItId: whoChangedItId, }, }); const successfulAndOk = await setTeamPermission(operations, organization, repositoryBody, teamId, 'pull', blockReason); if (successfulAndOk) { const owner = repositoryBody.owner.login.toLowerCase(); // We do not want to notify for each fork, if the permissions bubble to the fork if (owner === organization.name.toLowerCase()) { await largeTeamPermissionPreventionWarningMail(operations, organization, repositoryBody, teamId, teamName, blockReason, whoChangedIt, whoChangedItId); } } } async function largeTeamPermissionPreventionWarningMail(operations: Operations, organization: Organization, repositoryBody, teamId, teamName, reason, whoChangedIt, whoChangedItId): Promise<void> { // System accounts should not need notifications const mailProvider = operations.providers.mailProvider; const insights = operations.providers.insights; if (!mailProvider || operations.isSystemAccountByUsername(whoChangedIt)) { return; } const senderMember = organization.member(whoChangedItId); const mailAddress = await senderMember.getMailAddress(); if (!mailAddress) { return; } const basedir = operations.config.typescript.appDirectory; const operationsMail = operations.getOperationsMailAddress(); const companySpecific = getCompanySpecificDeployment(); const largeTeamProtectionDetailsLink = companySpecific?.strings?.largeTeamProtectionDetailsLink; const config = operations.config; await sendEmail(config, insights, basedir, mailProvider, mailAddress, operationsMail, { repository: repositoryBody, whoChangedIt, teamName, reason, companyName: config.brand.companyName, largeTeamProtectionDetailsLink, }); } async function sendEmail(config, insights, basedir, mailProvider: IMailProvider, to, operationsMail: string, body) { body.reason = `You are receiving this e-mail because you changed the permissions on the ${body.teamName} GitHub team, triggering this action.`; body.headline = 'Team permission change reverted'; body.notification = 'warning'; body.app = `${config.brand.companyName} GitHub`; const mail: IAutomaticTeamsMail = { to, cc: operationsMail, subject: `Team permission change for ${body.repository.full_name} repository reverted`, category: ['error', 'repos'], }; let mailContent = null; try { mailContent = await RenderHtmlMail(basedir, 'largeTeamProtected', body); } catch (renderError) { insights.trackException({ exception: renderError, properties: { content: body, eventName: 'JobAutomaticTeamsLargeTeamPermissionBlockMailRenderFailure', }, }); throw renderError; } mail.content = mailContent; let customData: ICustomDataEventName = { content: body, receipt: '', }; try { const mailResult = await mailProvider.sendMail(mail); customData.receipt = mailResult; } catch (mailError) { customData.eventName = 'JobAutomaticTeamsLargeTeamPermissionBlockMailFailure'; insights.trackException({ exception: mailError, properties: customData }); throw mailError; } insights.trackEvent({ name: 'JobAutomaticTeamsLargeTeamPermissionBlockMailSuccess', properties: customData }); } async function setTeamPermission(operations: Operations, organization: Organization, repositoryBody: any, teamId, necessaryPermission, reason): Promise<boolean> { const { customizedTeamPermissionsWebhookLogic } = operations.providers; const repoName = repositoryBody.name; const repoId = repositoryBody?.id; const orgName = organization.name; const repository = organization.repository(repoName, { id: repoId }); if (customizedTeamPermissionsWebhookLogic) { const shouldSkipEnforcement = await customizedTeamPermissionsWebhookLogic.shouldSkipEnforcement(repository); if (shouldSkipEnforcement) { console.log(`Customized logic for team permissions: skipping enforcement for repository ${repository.id}`); return false; } } const description = `setting permission level ${necessaryPermission} for the team with ID ${teamId} on the repository ${repoName} inside the ${orgName} GitHub org because ${reason}`; const insights = operations.insights; let error = null; try { await repository.setTeamPermission(teamId, necessaryPermission); } catch (setError) { error = setError; } const eventRoot = 'AutomaticRepoPermissionSet'; const eventName = eventRoot + error ? 'Success' : 'Failure'; if (error) { error.description = description; console.warn(`${eventName} ${description}`); } else { console.log(`${eventName} ${description}`); } if (insights) { insights.trackEvent({ name: eventName, properties: { success: !!error, reason: reason, description: description, }, }); } if (error) { throw error; } return true; }
the_stack
import {defaultTransformPseudoClasses, getTransformedPseudoClass, transformPseudoClasses} from './transform-pseudo-classes'; declare global { interface DocumentOrShadowRoot { adoptedStyleSheets?: CSSStyleSheet[]; } } /** * Retrieves the element type from a `Harness` type. * * @template H The harness type. */ export type HarnessElement<H extends Harness> = H extends Harness<infer E>? E : never; /** * A test harness class that can be used to simulate interaction with an * element. * * @template E The harness's element type. */ export class Harness<E extends HTMLElement = HTMLElement> { /** * The pseudo classes that should be transformed for simulation. Component * subclasses may override this to add additional pseudo classes. */ protected transformPseudoClasses = defaultTransformPseudoClasses; /** * Creates a new harness for the given element. * * @param element The element that this harness controls. */ constructor(readonly element: E) {} /** * Resets the element's simulated classes to the default state. */ async reset() { await this.release(); await this.blur(); } /** * Hovers, clicks, and leaves the element with a simulated mouse click. */ async click() { await this.hoverEnter(); this.simulateClick(await this.getInteractiveElement()); await this.hoverLeave(); } /** * Taps once on the element with a simulated touch. */ async tap() { this.simulateTap(await this.getInteractiveElement()); } /** * Hovers over the element with a simulated mouse. */ async hoverEnter() { this.simulateHoverEnter(await this.getInteractiveElement()); } /** * Moves the simulated mouse cursor off of the element. */ async hoverLeave() { this.simulateHoverLeave(await this.getInteractiveElement()); } /** * Simulates focusing an element with the keyboard. */ async focusWithKeyboard() { this.simulateKeyboardFocus(await this.getInteractiveElement()); } /** * Simulates focusing an element with a pointer (mouse/touch). */ async focusWithPointer() { await this.hoverEnter(); this.simulatePointerFocus(await this.getInteractiveElement()); } /** * Simulates unfocusing an element. */ async blur() { await this.hoverLeave(); this.simulateBlur(await this.getInteractiveElement()); } /** * Simulates pressing and holding a mouse cursor over an element. */ async press() { await this.hoverEnter(); this.simulateMousePress(await this.getInteractiveElement()); } /** * Simulates releasing a pressed mouse cursor over an element. */ async release() { this.simulateMouseRelease(await this.getInteractiveElement()); await this.hoverLeave(); } /** * Returns the element that should be used for interaction simulation. * Defaults to the host element itself. * * Subclasses should override this if the interactive element is not the host. * * @return The element to use in simulation. */ protected async getInteractiveElement(): Promise<HTMLElement> { return this.element; } /** * Adds a pseudo class to an element. The element's shadow root styles (or * document if not in a shadow root) will be transformed to support * simulated pseudo classes. * * @param element The element to add a pseudo class to. * @param pseudoClass The pseudo class to add. */ protected addPseudoClass(element: HTMLElement, pseudoClass: string) { if (!this.transformPseudoClasses.includes(pseudoClass)) { return; } const root = element.getRootNode() as Document | ShadowRoot; transformPseudoClasses(root.styleSheets, this.transformPseudoClasses); transformPseudoClasses( root.adoptedStyleSheets || [], this.transformPseudoClasses); element.classList.add(getTransformedPseudoClass(pseudoClass)); } /** * Removes a pseudo class from an element. * * @param element The element to remove a pseudo class from. * @param pseudoClass The pseudo class to remove. */ protected removePseudoClass(element: HTMLElement, pseudoClass: string) { element.classList.remove(getTransformedPseudoClass(pseudoClass)); } /** * Simulates a mouse press and release. * * @param element The element to click. */ protected simulateClick(element: HTMLElement) { this.simulateMousePress(element); this.simulateMouseRelease(element); } /** * Simulates a touch press and release. * * @param element The element to tap. */ protected simulateTap(element: HTMLElement) { this.simulateTouchPress(element); this.simulateTouchRelease(element); } /** * Simulates focusing with a keyboard. The difference between this and * `simulatePointerFocus` is that keyboard focus will include the * `:focus-visible` pseudo class. * * @param element The element to focus with a keyboard. */ protected simulateKeyboardFocus(element: HTMLElement) { this.simulateKeydown(element.ownerDocument, 'Tab'); this.addPseudoClass(element, ':focus-visible'); this.simulatePointerFocus(element); this.simulateKeyup(element, 'Tab'); } /** * Simulates focusing with a pointer. * * @param element The element to focus with a pointer. */ protected simulatePointerFocus(element: HTMLElement) { this.addPseudoClass(element, ':focus'); this.addPseudoClass(this.element, ':focus-within'); element.dispatchEvent(new FocusEvent('focus', {composed: true})); element.dispatchEvent( new FocusEvent('focusin', {bubbles: true, composed: true})); } /** * Simulates unfocusing an element. * * @param element The element to blur. */ protected simulateBlur(element: HTMLElement) { this.removePseudoClass(element, ':focus'); this.removePseudoClass(element, ':focus-visible'); this.removePseudoClass(this.element, ':focus-within'); element.dispatchEvent(new FocusEvent('blur', {composed: true})); element.dispatchEvent( new FocusEvent('focusout', {bubbles: true, composed: true})); element.blur(); } /** * Simulates a mouse pointer hovering over an element. * * @param element The element to hover over. */ protected simulateHoverEnter(element: HTMLElement) { this.addPseudoClass(element, ':hover'); const rect = element.getBoundingClientRect(); const mouseInit = this.createMouseEventInit(element); const mouseEnterInit = { ...mouseInit, bubbles: false, clientX: rect.left, clientY: rect.top, screenX: rect.left, screenY: rect.top, }; const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'mouse', }; const pointerEnterInit: PointerEventInit = { ...pointerInit, ...mouseEnterInit, }; element.dispatchEvent(new PointerEvent('pointerover', pointerInit)); element.dispatchEvent(new PointerEvent('pointerenter', pointerEnterInit)); element.dispatchEvent(new MouseEvent('mouseover', mouseInit)); element.dispatchEvent(new MouseEvent('mouseenter', mouseEnterInit)); } /** * Simulates a mouse pointer leaving the element. * * @param element The element to stop hovering over. */ protected simulateHoverLeave(element: HTMLElement) { this.removePseudoClass(element, ':hover'); const rect = element.getBoundingClientRect(); const mouseInit = this.createMouseEventInit(element); const mouseLeaveInit = { ...mouseInit, bubbles: false, clientX: rect.left - 1, clientY: rect.top - 1, screenX: rect.left - 1, screenY: rect.top - 1, }; const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'mouse', }; const pointerLeaveInit: PointerEventInit = { ...pointerInit, ...mouseLeaveInit, }; element.dispatchEvent(new PointerEvent('pointerout', pointerInit)); element.dispatchEvent(new PointerEvent('pointerleave', pointerLeaveInit)); element.dispatchEvent(new MouseEvent('pointerout', mouseInit)); element.dispatchEvent(new MouseEvent('mouseleave', mouseLeaveInit)); } /** * Simulates a mouse press and hold on an element. * * @param element The element to press with a mouse. */ protected simulateMousePress(element: HTMLElement) { this.addPseudoClass(element, ':active'); const mouseInit = this.createMouseEventInit(element); const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'mouse', }; element.dispatchEvent(new PointerEvent('pointerdown', pointerInit)); element.dispatchEvent(new MouseEvent('mousedown', mouseInit)); this.simulatePointerFocus(element); } /** * Simulates a mouse press release from an element. * * @param element The element to release pressing from. */ protected simulateMouseRelease(element: HTMLElement) { this.removePseudoClass(element, ':active'); const mouseInit = this.createMouseEventInit(element); const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'mouse', }; element.dispatchEvent(new PointerEvent('pointerup', pointerInit)); element.dispatchEvent(new MouseEvent('mouseup', mouseInit)); element.click(); } /** * Simulates a touch press and hold on an element. * * @param element The element to press with a touch pointer. */ protected simulateTouchPress(element: HTMLElement) { this.addPseudoClass(element, ':active'); const mouseInit = this.createMouseEventInit(element); const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'touch', }; const touch = this.createTouch(element); element.dispatchEvent(new PointerEvent('pointerdown', pointerInit)); element.dispatchEvent(new TouchEvent('touchstart', { touches: [touch], targetTouches: [touch], changedTouches: [touch], })); this.simulatePointerFocus(element); } /** * Simulates a touch press release from an element. * * @param element The element to release pressing from. */ protected simulateTouchRelease(element: HTMLElement) { this.removePseudoClass(element, ':active'); const mouseInit = this.createMouseEventInit(element); const pointerInit: PointerEventInit = { ...mouseInit, isPrimary: true, pointerType: 'touch', }; const touch = this.createTouch(element); element.dispatchEvent(new PointerEvent('pointerup', pointerInit)); element.dispatchEvent( new TouchEvent('touchend', {changedTouches: [touch]})); element.dispatchEvent(new MouseEvent('mousedown', mouseInit)); element.dispatchEvent(new MouseEvent('mouseup', mouseInit)); element.click(); } /** * Simulates a keypress on an element. * * @param element The element to press a key on. * @param key The key to press. * @param init Additional keyboard options. */ protected simulateKeypress( element: EventTarget, key: string, init?: Partial<KeyboardEventInit>) { this.simulateKeydown(element, key, init); this.simulateKeyup(element, key, init); } /** * Simulates a keydown press on an element. * * @param element The element to press a key on. * @param key The key to press. * @param init Additional keyboard options. */ protected simulateKeydown( element: EventTarget, key: string, init: Partial<KeyboardEventInit> = {}) { element.dispatchEvent(new KeyboardEvent('keydown', { ...init, key, bubbles: true, composed: true, cancelable: true, })); } /** * Simulates a keyup release from an element. * * @param element The element to release a key from. * @param key The key to release. * @param init Additional keyboard options. */ protected simulateKeyup( element: EventTarget, key: string, init: Partial<KeyboardEventInit> = {}) { element.dispatchEvent(new KeyboardEvent('keyup', { ...init, key, bubbles: true, composed: true, cancelable: true, })); } /** * Creates a MouseEventInit for an element. The default x/y coordinates of the * event init will be in the center of the element. * * @param element The element to create a `MouseEventInit` for. * @return The init object for a `MouseEvent`. */ protected createMouseEventInit(element: HTMLElement): MouseEventInit { const rect = element.getBoundingClientRect(); return { bubbles: true, cancelable: true, composed: true, clientX: (rect.left + rect.right) / 2, clientY: (rect.top + rect.bottom) / 2, screenX: (rect.left + rect.right) / 2, screenY: (rect.top + rect.bottom) / 2, }; } /** * Creates a Touch instance for an element. The default x/y coordinates of the * touch will be in the center of the element. This can be used in the * `TouchEvent` constructor. * * @param element The element to create a touch for. * @param identifier Optional identifier for the touch. Defaults to 0 for * every touch instance. * @return The `Touch` instance. */ protected createTouch(element: HTMLElement, identifier = 0): Touch { const rect = element.getBoundingClientRect(); return new Touch({ identifier, target: element, clientX: (rect.left + rect.right) / 2, clientY: (rect.top + rect.bottom) / 2, screenX: (rect.left + rect.right) / 2, screenY: (rect.top + rect.bottom) / 2, pageX: (rect.left + rect.right) / 2, pageY: (rect.top + rect.bottom) / 2, }); } }
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const taskOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'task', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a task', }, { name: 'Delete', value: 'delete', description: 'Delete a task', }, { name: 'Get', value: 'get', description: 'Get a task', }, { name: 'Get All', value: 'getAll', description: 'Get all tasks', }, { name: 'Get Summary', value: 'getSummary', description: `Returns an overview of task's metadata`, }, { name: 'Update', value: 'update', description: 'Update a task', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const taskFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* task:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Status', name: 'status', type: 'options', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'create', ], }, }, typeOptions: { loadOptionsMethod: 'getTaskStatuses', }, description: 'The current status of the task, such as In Progress or Completed.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'task', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Activity Date', name: 'activityDate', type: 'dateTime', default: '', description: `Represents the due date of the task. This field has a timestamp that is always set to midnight in the Coordinated Universal Time (UTC) time zone.`, }, { displayName: 'Call Disposition', name: 'callDisposition', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: `Represents the result of a given call, for example, “we'll call back,” or “call unsuccessful.” Limit is 255 characters. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center.`, }, { displayName: 'Call Duration In Seconds', name: 'callDurationInSeconds', type: 'number', default: '', description: `Duration of the call in seconds. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center`, }, { displayName: 'Call Object', name: 'callObject', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: `Name of a call center. Limit is 255 characters. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center.`, }, { displayName: 'Call Type', name: 'callType', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskCallTypes', }, description: 'The type of call being answered: Inbound, Internal, or Outbound.', }, { displayName: 'Custom Fields', name: 'customFieldsUi', placeholder: 'Add Custom Field', type: 'fixedCollection', typeOptions: { multipleValues: true, }, description: 'Filter by custom fields ', default: {}, options: [ { name: 'customFieldsValues', displayName: 'Custom Field', values: [ { displayName: 'Field ID', name: 'fieldId', type: 'options', typeOptions: { loadOptionsMethod: 'getCustomFields', }, default: '', description: 'The ID of the field to add custom field to.', }, { displayName: 'Value', name: 'value', type: 'string', default: '', description: 'The value to set on custom field.', }, ], }, ], }, { displayName: 'Description', name: 'description', type: 'string', default: '', typeOptions: { alwaysOpenEditWindow: true, }, description: 'Contains a text description of the task.', }, { displayName: 'Is ReminderSet', name: 'isReminderSet', type: 'boolean', default: false, description: 'Indicates whether a popup reminder has been set for the task (true) or not (false).', }, { displayName: 'Owner', name: 'owner', type: 'options', typeOptions: { loadOptionsMethod: 'getUsers', }, default: '', description: 'ID of the User who owns the record.', }, { displayName: 'Priority', name: 'priority', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskPriorities', }, description: `Indicates the importance or urgency of a task, such as high or low.`, }, { displayName: 'Recurrence Type', name: 'recurrenceType', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskRecurrenceTypes', }, description: 'Recurrence Type of the task.', }, { displayName: 'Recurrence Instance', name: 'recurrenceInstance', type: 'options', typeOptions: { loadOptionsMethod: 'getTaskRecurrenceInstances', }, default: '', description: `The frequency of the recurring task. For example, “2nd” or “3rd.”`, }, { displayName: 'Recurrence Interval', name: 'recurrenceInterval', type: 'number', default: '', description: 'The interval between recurring tasks.', }, { displayName: 'Recurrence Day Of Month', name: 'recurrenceDayOfMonth', type: 'number', default: '', description: 'The day of the month in which the task repeats.', }, { displayName: 'Recurrence Day Of Week Mask', name: 'recurrenceDayOfWeekMask', type: 'number', default: '', description: `The day or days of the week on which the task repeats. This field contains a bitmask. The values are as follows: Sunday = 1 Monday = 2 Tuesday = 4 Wednesday = 8 Thursday = 16 Friday = 32 Saturday = 64 Multiple days are represented as the sum of their numerical values. For example, Tuesday and Thursday = 4 + 16 = 20.`, }, { displayName: 'Recurrence End Date Only', name: 'recurrenceEndDateOnly', type: 'dateTime', default: '', description: `The last date on which the task repeats. This field has a timestamp that is always set to midnight in the Coordinated Universal Time (UTC) time zone.`, }, { displayName: 'Recurrence Month Of Year', name: 'recurrenceMonthOfYear', type: 'options', options: [ { name: 'January', value: 'January', }, { name: 'February', value: 'February', }, { name: 'March', value: 'March', }, { name: 'April', value: 'April', }, { name: 'May', value: 'May', }, { name: 'June', value: 'June', }, { name: 'July', value: 'July', }, { name: 'August', value: 'August', }, { name: 'September', value: 'September', }, { name: 'October', value: 'October', }, { name: 'November', value: 'November', }, { name: 'December', value: 'December', }, ], default: '', description: 'The month of the year in which the task repeats.', }, { displayName: 'Recurrence Regenerated Type', name: 'recurrenceRegeneratedType', type: 'options', default: '', options: [ { name: 'After due date', value: 'RecurrenceRegenerateAfterDueDate', }, { name: 'After date completed', value: 'RecurrenceRegenerateAfterToday', }, { name: '(Task Closed)', value: 'RecurrenceRegenerated', }, ], description: `Represents what triggers a repeating task to repeat. Add this field to a page layout together with the RecurrenceInterval field, which determines the number of days between the triggering date (due date or close date) and the due date of the next repeating task in the series. Label is Repeat This Task.`, }, { displayName: 'Recurrence Start Date Only', name: 'recurrenceEndDateOnly', type: 'dateTime', default: '', description: `The date when the recurring task begins. Must be a date and time before RecurrenceEndDateOnly.`, }, { displayName: 'Recurrence TimeZone SidKey', name: 'recurrenceTimeZoneSidKey', type: 'string', default: '', description: `The time zone associated with the recurring task. For example, “UTC-8:00” for Pacific Standard Time.`, }, { displayName: 'Reminder Date Time', name: 'reminderDateTime', type: 'dateTime', default: '', description: `Represents the time when the reminder is scheduled to fire, if IsReminderSet is set to true. If IsReminderSet is set to false, then the user may have deselected the reminder checkbox in the Salesforce user interface, or the reminder has already fired at the time indicated by the value.`, }, { displayName: 'Subject', name: 'subject', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskSubjects', }, description: 'The subject line of the task, such as “Call” or “Send Quote.” Limit: 255 characters.', }, { displayName: 'Type', name: 'type', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskTypes', }, description: `Represents Type of the task, such as Call or Meeting.`, }, { displayName: 'What Id', name: 'whatId', type: 'string', default: '', description: `The WhatId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. WhatIds are polymorphic. Polymorphic means a WhatId is equivalent to the ID of a related object.`, }, { displayName: 'Who Id', name: 'whoId', type: 'string', default: '', description: `The WhoId represents a human such as a lead or a contact. WhoIds are polymorphic. Polymorphic means a WhoId is equivalent to a contact’s ID or a lead’s ID.`, }, ], }, /* -------------------------------------------------------------------------- */ /* task:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Task ID', name: 'taskId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'update', ], }, }, description: 'ID of task that needs to be fetched.', }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'task', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Activity Date', name: 'activityDate', type: 'dateTime', default: '', description: `Represents the due date of the task. This field has a timestamp that is always set to midnight in the Coordinated Universal Time (UTC) time zone.`, }, { displayName: 'Call Disposition', name: 'callDisposition', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: `Represents the result of a given call, for example, “we'll call back,” or “call unsuccessful.” Limit is 255 characters. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center.`, }, { displayName: 'Call Duration In Seconds', name: 'callDurationInSeconds', type: 'number', default: '', description: `Duration of the call in seconds. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center`, }, { displayName: 'Call Object', name: 'callObject', type: 'string', typeOptions: { alwaysOpenEditWindow: true, }, default: '', description: `Name of a call center. Limit is 255 characters. Not subject to field-level security, available for any user in an organization with Salesforce CRM Call Center.`, }, { displayName: 'Call Type', name: 'callType', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskCallTypes', }, description: 'The type of call being answered: Inbound, Internal, or Outbound.', }, { displayName: 'Custom Fields', name: 'customFieldsUi', placeholder: 'Add Custom Field', type: 'fixedCollection', typeOptions: { multipleValues: true, }, description: 'Filter by custom fields ', default: {}, options: [ { name: 'customFieldsValues', displayName: 'Custom Field', values: [ { displayName: 'Field ID', name: 'fieldId', type: 'options', typeOptions: { loadOptionsMethod: 'getCustomFields', }, default: '', description: 'The ID of the field to add custom field to.', }, { displayName: 'Value', name: 'value', type: 'string', default: '', description: 'The value to set on custom field.', }, ], }, ], }, { displayName: 'Description', name: 'description', type: 'string', default: '', typeOptions: { alwaysOpenEditWindow: true, }, description: 'Contains a text description of the task.', }, { displayName: 'Is ReminderSet', name: 'isReminderSet', type: 'boolean', default: false, description: 'Indicates whether a popup reminder has been set for the task (true) or not (false).', }, { displayName: 'Owner', name: 'owner', type: 'options', typeOptions: { loadOptionsMethod: 'getUsers', }, default: '', description: 'ID of the User who owns the record.', }, { displayName: 'Priority', name: 'priority', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskPriorities', }, description: `Indicates the importance or urgency of a task, such as high or low.`, }, { displayName: 'Status', name: 'status', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskStatuses', }, description: 'The current status of the task, such as In Progress or Completed.', }, { displayName: 'Subject', name: 'subject', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskSubjects', }, description: 'The subject line of the task, such as “Call” or “Send Quote.” Limit: 255 characters.', }, { displayName: 'Recurrence Day Of Month', name: 'recurrenceDayOfMonth', type: 'number', default: '', description: 'The day of the month in which the task repeats.', }, { displayName: 'Recurrence Day Of Week Mask', name: 'recurrenceDayOfWeekMask', type: 'number', default: '', description: `The day or days of the week on which the task repeats. This field contains a bitmask. The values are as follows: Sunday = 1 Monday = 2 Tuesday = 4 Wednesday = 8 Thursday = 16 Friday = 32 Saturday = 64. Multiple days are represented as the sum of their numerical values. For example, Tuesday and Thursday = 4 + 16 = 20.`, }, { displayName: 'Recurrence End Date Only', name: 'recurrenceEndDateOnly', type: 'dateTime', default: '', description: `The last date on which the task repeats. This field has a timestamp that is always set to midnight in the Coordinated Universal Time (UTC) time zone.`, }, { displayName: 'Recurrence Instance', name: 'recurrenceInstance', type: 'options', typeOptions: { loadOptionsMethod: 'getTaskRecurrenceInstances', }, default: '', description: `The frequency of the recurring task. For example, “2nd” or “3rd.”`, }, { displayName: 'Recurrence Interval', name: 'recurrenceInterval', type: 'number', default: '', description: 'The interval between recurring tasks.', }, { displayName: 'Recurrence Month Of Year', name: 'recurrenceMonthOfYear', type: 'options', options: [ { name: 'January', value: 'January', }, { name: 'February', value: 'February', }, { name: 'March', value: 'March', }, { name: 'April', value: 'April', }, { name: 'May', value: 'May', }, { name: 'June', value: 'June', }, { name: 'July', value: 'July', }, { name: 'August', value: 'August', }, { name: 'September', value: 'September', }, { name: 'October', value: 'October', }, { name: 'November', value: 'November', }, { name: 'December', value: 'December', }, ], default: '', description: 'The month of the year in which the task repeats.', }, { displayName: 'Recurrence Start Date Only', name: 'recurrenceEndDateOnly', type: 'dateTime', default: '', description: `The date when the recurring task begins. Must be a date and time before RecurrenceEndDateOnly.`, }, { displayName: 'Recurrence Regenerated Type', name: 'recurrenceRegeneratedType', type: 'options', default: '', options: [ { name: 'After due date', value: 'RecurrenceRegenerateAfterDueDate', }, { name: 'After date completed', value: 'RecurrenceRegenerateAfterToday', }, { name: '(Task Closed)', value: 'RecurrenceRegenerated', }, ], description: `Represents what triggers a repeating task to repeat. Add this field to a page layout together with the RecurrenceInterval field, which determines the number of days between the triggering date (due date or close date) and the due date of the next repeating task in the series. Label is Repeat This Task.`, }, { displayName: 'Recurrence Type', name: 'recurrenceType', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskRecurrenceTypes', }, description: 'Website for the task.', }, { displayName: 'Recurrence TimeZone SidKey', name: 'recurrenceTimeZoneSidKey', type: 'string', default: '', description: `The time zone associated with the recurring task. For example, “UTC-8:00” for Pacific Standard Time.`, }, { displayName: 'Reminder Date Time', name: 'reminderDateTime', type: 'dateTime', default: '', description: `Represents the time when the reminder is scheduled to fire, if IsReminderSet is set to true. If IsReminderSet is set to false, then the user may have deselected the reminder checkbox in the Salesforce user interface, or the reminder has already fired at the time indicated by the value.`, }, { displayName: 'Type', name: 'type', type: 'options', default: '', typeOptions: { loadOptionsMethod: 'getTaskTypes', }, description: `Represents Type of the task, such as Call or Meeting.`, }, { displayName: 'What Id', name: 'whatId', type: 'string', default: '', description: `The WhatId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. WhatIds are polymorphic. Polymorphic means a WhatId is equivalent to the ID of a related object.`, }, { displayName: 'Who Id', name: 'whoId', type: 'string', default: '', description: `The WhoId represents a human such as a lead or a contact. WhoIds are polymorphic. Polymorphic means a WhoId is equivalent to a contact’s ID or a lead’s ID.`, }, ], }, /* -------------------------------------------------------------------------- */ /* task:get */ /* -------------------------------------------------------------------------- */ { displayName: 'Task ID', name: 'taskId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'get', ], }, }, description: 'ID of task that needs to be fetched.', }, /* -------------------------------------------------------------------------- */ /* task:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Task ID', name: 'taskId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'task', ], operation: [ 'delete', ], }, }, description: 'ID of task that needs to be fetched.', }, /* -------------------------------------------------------------------------- */ /* task:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 100, }, default: 50, description: 'How many results to return.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'task', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Conditions', name: 'conditionsUi', placeholder: 'Add Condition', type: 'fixedCollection', typeOptions: { multipleValues: true, }, description: 'The condition to set.', default: {}, options: [ { name: 'conditionValues', displayName: 'Condition', values: [ { displayName: 'Field', name: 'field', type: 'options', typeOptions: { loadOptionsMethod: 'getTaskFields', }, default: '', description: 'For date, number, or boolean, please use expressions.', }, { displayName: 'Operation', name: 'operation', type: 'options', options: [ { name: '=', value: 'equal', }, { name: '>', value: '>', }, { name: '<', value: '<', }, { name: '>=', value: '>=', }, { name: '<=', value: '<=', }, ], default: 'equal', }, { displayName: 'Value', name: 'value', type: 'string', default: '', }, ], }, ], }, { displayName: 'Fields', name: 'fields', type: 'string', default: '', description: 'Fields to include separated by ,', }, ], }, ];
the_stack
import * as chrome from "selenium-webdriver/chrome"; import { By, until, Builder, Capabilities, WebDriver, Locator, promise, logging, WebElement, Condition, } from "selenium-webdriver"; import { config, BenchmarkDriverOptions } from "./common"; interface PathPart { tagName: string; index: number; } let useShadowRoot = false; let useRowShadowRoot = false; let shadowRootName = ""; let buttonsInShadowRoot = false; export function setUseShadowRoot(val: boolean) { useShadowRoot = val; } export function setUseRowShadowRoot(val: boolean) { useRowShadowRoot = val; } export function setShadowRootName(val: string) { shadowRootName = val; } export function setButtonsInShadowRoot(val: boolean) { buttonsInShadowRoot = val; } function convertPath(path: string): Array<PathPart> { let parts = path.split(/\//).filter((v) => !!v); let res: Array<PathPart> = []; for (let part of parts) { let components = part.split(/\[|]/).filter((v) => !!v); let tagName = components[0]; let index: number = 0; if (components.length == 2) { index = Number(components[1]); if (!index) { console.log("Index can't be parsed", components[1]); throw "Index can't be parsed " + components[1]; } } else { index = 1; } res.push({ tagName, index }); } return res; } async function shadowRoot( driver: WebDriver, selector: string ): Promise<WebElement> { const el = await driver.findElement(By.css(selector)); return driver.executeScript(`return arguments[0].shadowRoot`, el); } // Fake findByXPath for simple XPath expressions to allow usage with shadow dom export async function findByXPath( driver: WebDriver, path: string, isInButtonArea: boolean ): Promise<WebElement> { let root = await mainRoot(driver, isInButtonArea); let paths = convertPath(path); let n = root; try { for (let p of paths) { let elem; if (useRowShadowRoot && p.tagName === "tr") { try { const shadowHost = await shadowRoot( driver, `benchmark-row:nth-of-type(${p.index})` ); elem = await shadowHost.findElement(By.tagName("tr")); if (elem === null) { return null; } } catch (err) { return null; } } else { let elems = await n.findElements( By.css(p.tagName + ":nth-of-type(" + p.index + ")") ); if (elems == null || elems.length == 0) { return null; } elem = elems[0]; } n = elem; } } catch (e) { //can happen for StaleElementReferenceError return null; } return n; } function elemNull(v: any) { console.log("*** ELEMENT WAS NULL"); return false; } function waitForCondition(driver: WebDriver) { return async function ( text: string, fn: (driver: WebDriver) => Promise<boolean>, timeout: number ): Promise<boolean> { return await driver.wait( new Condition<Promise<boolean>>(text, fn), timeout ); }; } // driver.findElement(By.xpath("//tbody/tr[1]/td[1]")).getText().then(...) can throw a stale element error: // thus we're using a safer way here: export async function testTextContains( driver: WebDriver, xpath: string, text: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testTextContains ${xpath} ${text}`, async function (driver) { try { let elem = await findByXPath(driver, xpath, isInButtonArea); if (elem == null) return false; let v = await elem.getText(); return v && v.indexOf(text) > -1; } catch (err) { console.log( "ignoring error in testTextContains for xpath = " + xpath + " text = " + text, err.toString().split("\n")[0] ); } }, timeout ); } export function testTextNotContained( driver: WebDriver, xpath: string, text: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testTextNotContained ${xpath} ${text}`, async function (driver) { try { let elem = await findByXPath(driver, xpath, isInButtonArea); if (elem == null) return false; let v = await elem.getText(); return v && v.indexOf(text) == -1; } catch (err) { console.log( "ignoring error in testTextNotContained for xpath = " + xpath + " text = " + text, err.toString().split("\n")[0] ); } }, timeout ); } export function testClassContains( driver: WebDriver, xpath: string, text: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testClassContains ${xpath} ${text}`, async function (driver) { try { let elem = await findByXPath(driver, xpath, isInButtonArea); if (elem == null) return false; let v = await elem.getAttribute("class"); return v && v.indexOf(text) > -1; } catch (err) { console.log( "ignoring error in testClassContains for xpath = " + xpath + " text = " + text, err.toString().split("\n")[0] ); } }, timeout ); } export function testElementLocatedByXpath( driver: WebDriver, xpath: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testElementLocatedByXpath ${xpath}`, async function (driver) { try { let elem = await findByXPath(driver, xpath, isInButtonArea); return elem ? true : false; } catch (err) { console.log( "ignoring error in testElementLocatedByXpath for xpath = " + xpath, err.toString() ); } }, timeout ); } export function testElementNotLocatedByXPath( driver: WebDriver, xpath: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testElementNotLocatedByXPath ${xpath}`, async function (driver) { try { let elem = await findByXPath(driver, xpath, isInButtonArea); return elem ? false : true; } catch (err) { console.log( "ignoring error in testElementNotLocatedByXPath for xpath = " + xpath, err.toString().split("\n")[0] ); } }, timeout ); } export function testElementLocatedById( driver: WebDriver, id: string, timeout = config.TIMEOUT, isInButtonArea: boolean ) { return waitForCondition(driver)( `testElementLocatedById ${id}`, async function (driver) { try { let elem = await mainRoot(driver, isInButtonArea); elem = await elem.findElement(By.id(id)); return true; } catch (err) { // console.log("ignoring error in testElementLocatedById for id = "+id,err.toString().split("\n")[0]); } }, timeout ); } async function retry<T>( retryCount: number, driver: WebDriver, fun: (driver: WebDriver, retryCount: number) => Promise<T> ): Promise<T> { for (let i = 0; i < retryCount; i++) { try { return await fun(driver, i); } catch (err) { console.log("comand failed. Retry #", i + 1); await driver.sleep(200); } } } // Stale element prevention. For aurelia even after a testElementLocatedById clickElementById for the same id can fail // No idea how that can be explained export function clickElementById( driver: WebDriver, id: string, isInButtonArea: boolean ) { return retry(5, driver, async function (driver) { let elem = await mainRoot(driver, isInButtonArea); elem = await elem.findElement(By.id(id)); await elem.click(); }); } export function clickElementByXPath( driver: WebDriver, xpath: string, isInButtonArea: boolean ) { return retry(5, driver, async function (driver, count) { if (count > 1 && config.LOG_DETAILS) console.log("clickElementByXPath ", xpath, " attempt #", count); let elem = await findByXPath(driver, xpath, isInButtonArea); await elem.click(); }); // Stale element possible: // return to(driver.findElement(By.xpath(xpath)).click()); } export async function getTextByXPath( driver: WebDriver, xpath: string, isInButtonArea: boolean ): Promise<string> { return await retry(5, driver, async function (driver, count) { if (count > 1 && config.LOG_DETAILS) console.log("getTextByXPath ", xpath, " attempt #", count); let elem = await findByXPath(driver, xpath, isInButtonArea); return await elem.getText(); }); } export async function mainRoot( driver: WebDriver, isInButtonArea: boolean ): Promise<WebElement> { if (useShadowRoot) { if (!buttonsInShadowRoot && isInButtonArea) { return driver.findElement(By.tagName("body")); } else { return shadowRoot(driver, shadowRootName); } } else { return driver.findElement(By.tagName("body")); } } // node_modules\.bin\chromedriver.cmd --verbose --port=9998 --log-path=chromedriver.log // SELENIUM_REMOTE_URL=http://localhost:9998 export function buildDriver( benchmarkOptions: BenchmarkDriverOptions ): WebDriver { let args = [ "--js-flags=--expose-gc", "--enable-precise-memory-info", "--no-first-run", "--disable-background-networking", "--disable-background-timer-throttling", "--disable-cache", "--disable-translate", "--disable-sync", "--disable-extensions", "--disable-default-apps", "--remote-debugging-port=" + benchmarkOptions.remoteDebuggingPort.toFixed(), "--window-size=2400,1600", ]; if (process.platform == "darwin" && process.arch == "arm64") { console.log("INFO: Disabling site isolation as a workaround for Mac M1"); args.push("--disable-features=IsolateOrigins,site-per-process"); } if (benchmarkOptions.headless) { args.push("--headless"); args.push("--disable-gpu"); // https://bugs.chromium.org/p/chromium/issues/detail?id=737678 args.push("--no-sandbox"); } let caps = new Capabilities({ browserName: "chrome", platform: "ANY", version: "stable", "goog:chromeOptions": { binary: benchmarkOptions.chromeBinaryPath, args: args, perfLoggingPrefs: { enableNetwork: true, enablePage: true, traceCategories: "devtools.timeline,blink.user_timing", }, excludeSwitches: ["enable-automation"], }, "goog:loggingPrefs": { browser: "ALL", performance: "ALL", }, }); // port probing fails sometimes on windows, the following driver construction avoids probing: let service = new chrome.ServiceBuilder() .setPort(benchmarkOptions.chromePort) .build(); var driver = chrome.Driver.createSession(caps, service); return driver; }
the_stack
import * as React from "react" import * as ReactDOM from "react-dom" import * as Immutable from "immutable" import * as Moment from 'moment' import {C, Mode, Cont, CmdCommon, make_C, unit, bind} from './core' function format_int(num:number, length:number) : string { return (num / Math.pow(10, length)).toFixed(length).substr(2); } export type OptionalParameters = { disabled?: boolean, size?: number } export type NumberProps = { kind:"number", value:number, mode:Mode } & CmdCommon<number> export type StringType = "email"|"tel"|"text"|"url"|"password" export type StringProps = { kind:"string", value:string, type:StringType, mode:Mode, optional_parameters: OptionalParameters } & CmdCommon<string> export type BooleanStyle = "checkbox"|"fancy toggle"|"plus/minus"|"radio" export type BoolProps = { kind:"bool", value:boolean, mode:Mode, style:BooleanStyle } & CmdCommon<boolean> export type DateProps = { kind:"date", value:Moment.Moment, mode:Mode } & CmdCommon<Moment.Moment> export type DateTimeProps = { kind:"date time", value:Moment.Moment, mode:Mode } & CmdCommon<Moment.Moment> export type TimeProps = { kind:"time", value:Moment.Moment, mode:Mode } & CmdCommon<Moment.Moment> type NumberState = { value:number } class Number extends React.Component<NumberProps,NumberState> { constructor(props:NumberProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:NumberProps) { if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(this.state.value)) } componentWillMount() { this.call_cont(this.state.value) } call_cont(value:number) { this.props.cont(()=>null)(value) } render() { return this.props.mode == "edit" ? <input type="number" value={this.state.value} onChange={e => { let new_value = isNaN(e.currentTarget.valueAsNumber) ? 0 : e.currentTarget.valueAsNumber if (new_value == this.state.value) return this.props.cont(()=>null)(new_value)} }/> : <span>{this.state.value}</span> } } export let number = (mode:Mode, key?:string, dbg?:() => string) => function(value:number) : C<number> { return make_C<number>(ctxt => cont => React.createElement<NumberProps>(Number, { kind:"number", debug_info:dbg, mode:mode, value:value, context:ctxt, cont:cont, key:key })) } type StringState = { value:string } class String extends React.Component<StringProps,StringState> { constructor(props:StringProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:StringProps) { if (this.props.debug_info != undefined) console.log(`receiving props`, this.props.debug_info()) if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(new_props.value)) } componentWillMount() { if (this.props.debug_info != undefined) console.log(`mounting`, this.props.debug_info()) this.call_cont(this.state.value) } call_cont(value:string) { if (this.props.debug_info != undefined) console.log(`calling continuation`, this.props.debug_info()) this.props.cont(()=>null)(value) } render() { if (this.props.debug_info != undefined) console.log(`render`, this.props.debug_info()) return this.props.mode == "edit" ? <input type={this.props.type} value={this.state.value} onChange={e => { if (this.state.value == e.currentTarget.value) return this.call_cont(e.currentTarget.value)} } size={this.props.optional_parameters.size != undefined ? this.props.optional_parameters.size : undefined} disabled={this.props.optional_parameters.disabled != undefined && this.props.optional_parameters.disabled} /> : this.props.type == "text" ? <span>{this.state.value}</span> : this.props.type == "tel" ? <a href={`tel:${this.state.value}`}>{this.state.value}</a> : this.props.type == "email" ? <a href={`mailto:${this.state.value}`}>{this.state.value}</a> : this.props.type == "url" ? <a href={this.state.value}>{this.state.value}</a> : this.props.type == "password" ? <span>{Immutable.Repeat("*", this.state.value.length).join("")}</span> : <span>{this.state.value}</span> } } export let string = (mode:Mode, type?:StringType, key?:string, dbg?:() => string, optional_parameters?: OptionalParameters) => function(value:string) : C<string> { return make_C<string>(ctxt => cont => React.createElement<StringProps>(String, { kind:"string", debug_info:dbg, type:type || "text", mode:mode, value:value, context:ctxt, cont:cont, key:key , optional_parameters: optional_parameters == undefined || optional_parameters == null ? {} : optional_parameters })) } type BoolState = { value:boolean } class Bool extends React.Component<BoolProps,BoolState> { constructor(props:BoolProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:BoolProps) { if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(this.state.value)) } componentWillMount() { this.call_cont(this.state.value) } call_cont(value:boolean) { this.props.cont(()=>null)(value) } render() { return this.props.style == "fancy toggle" ? <input type="checkbox" className="monadic-input-choices monadic-input-choices--switch" disabled={this.props.mode == "view"} checked={this.state.value} onChange={e => this.props.cont(()=>null)(e.currentTarget.checked)} /> : this.props.style == "plus/minus" ? <input type="checkbox" className="monadic-input-choices monadic-input-choices--toggle" disabled={this.props.mode == "view"} checked={this.state.value} onChange={e => this.props.cont(()=>null)(e.currentTarget.checked)} /> : <input type={this.props.style} className="monadic-input-choices monadic-input-choices--checkbox" disabled={this.props.mode == "view"} checked={this.state.value} onChange={e => this.props.cont(()=>null)(e.currentTarget.checked)} /> } } export let bool = (mode:Mode, style:BooleanStyle, key?:string, dbg?:() => string) => function(value:boolean) : C<boolean> { return make_C<boolean>(ctxt => cont => React.createElement<BoolProps>(Bool, { kind:"bool", debug_info:dbg, style:style, mode:mode, value:value, context:ctxt, cont:cont, key:key })) } type DateTimeState = { value:Moment.Moment } class DateTime extends React.Component<DateTimeProps,DateTimeState> { constructor(props:DateTimeProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:DateTimeProps) { if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(this.state.value)) } componentWillMount() { this.call_cont(this.state.value) } call_cont(value:Moment.Moment) { this.props.cont(()=>null)(value) } render() { let item = this.state.value let default_value = `${format_int(item.year(), 4)}-${format_int(item.month()+1, 2)}-${format_int(item.date(), 2)}T${format_int(item.hours(), 2)}:${format_int(item.minutes(), 2)}` return this.props.mode == "view" ? <div>{ `${format_int(item.date(), 2)}/${format_int(item.month()+1, 2)}/${format_int(item.year(), 4)} ${format_int(item.hours(), 2)}:${format_int(item.minutes(), 2)}` }</div> : <input type="datetime-local" value={default_value} onChange={(e) => this.call_cont(Moment.utc(e.currentTarget.value)) } /> } } export let date_time = (mode:Mode, key?:string, dbg?:() => string) => function(value:Moment.Moment) : C<Moment.Moment> { return make_C<Moment.Moment>(ctxt => cont => React.createElement<DateTimeProps>(DateTime, { kind:"date time", debug_info:dbg, mode:mode, value:value, context:ctxt, cont:cont, key:key })) } type DateState = { value:Moment.Moment } class DateOnly extends React.Component<DateProps,DateState> { constructor(props:DateProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:DateProps) { if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(this.state.value)) } componentWillMount() { this.call_cont(this.state.value) } call_cont(value:Moment.Moment) { this.props.cont(()=>null)(value) } render() { let item = this.state.value let default_value = `${format_int(item.year(), 4)}-${format_int(item.month()+1, 2)}-${format_int(item.date(), 2)}` return this.props.mode == "view" ? <div>{ `${format_int(item.date(), 2)}/${format_int(item.month()+1, 2)}/${format_int(item.year(), 4)}` }</div> : <input type="date" value={default_value} onChange={(e) => this.call_cont(Moment.utc(new Date(e.currentTarget.value)).startOf('d').add(12, 'h')) } /> } } export let date = (mode:Mode, key?:string, dbg?:() => string) => function(value:Moment.Moment) : C<Moment.Moment> { return make_C<Moment.Moment>(ctxt => cont => React.createElement<DateProps>(DateOnly, { kind:"date", debug_info:dbg, mode:mode, value:value, context:ctxt, cont:cont, key:key })) } type TimeState = { value:Moment.Moment } class Time extends React.Component<TimeProps,TimeState> { constructor(props:TimeProps,context:any) { super(props, context) this.state = { value:props.value } } componentWillReceiveProps(new_props:TimeProps) { if (new_props.value != this.state.value) this.setState({...this.state, value: new_props.value}) //, () => this.call_cont(this.state.value)) } componentWillMount() { this.call_cont(this.state.value) } call_cont(value:Moment.Moment) { this.props.cont(()=>null)(value) } render() { let item = this.state.value let default_value = `${format_int(item.hours(), 2)}:${format_int(item.minutes(), 2)}` return this.props.mode == "view" ? <div>{ default_value }</div> : <input type="time" value={default_value} onChange={(e) => this.call_cont(Moment.utc(e.currentTarget.valueAsDate)) } /> } } export let time = (mode:Mode, key?:string, dbg?:() => string) => function(value:Moment.Moment) : C<Moment.Moment> { return make_C<Moment.Moment>(ctxt => cont => React.createElement<TimeProps>(Time, { kind:"time", debug_info:dbg, mode:mode, value:value, context:ctxt, cont:cont, key:key })) }
the_stack
import {Easing} from "@swim/util"; import {Affinity} from "@swim/component"; import {Spec, Test, Exam} from "@swim/unit"; import {Color} from "@swim/style"; import {Look, Mood, Theme, ThemeAnimator} from "@swim/theme"; import {TestThemeComponent} from "./TestThemeComponent"; export class ThemeAnimatorSpec extends Spec { @Test testThemeAnimator(exam: Exam): void { const animator = ThemeAnimator.create(null); exam.equal(animator.name, ""); exam.equal(animator.look, null); exam.equal(animator.state, void 0); exam.equal(animator.value, void 0); animator.setState("bar"); exam.equal(animator.look, null); exam.equal(animator.state, "bar"); exam.equal(animator.value, "bar"); exam.identical(animator("baz"), null, "accessor set"); exam.equal(animator(), "baz", "accessor get"); } @Test testThemeAnimatorDefine(exam: Exam): void { const testAnimator = ThemeAnimator.define("foo", {type: Number, value: 0}); const animator = testAnimator.create(null); exam.equal(animator.name, "foo"); exam.equal(animator.state, 0); exam.equal(animator.value, 0); animator.setState(1); exam.equal(animator.state, 1); exam.equal(animator.value, 1); exam.identical(animator(0.5), null, "accessor set"); exam.equal(animator(), 0.5, "accessor get"); } @Test testThemeAnimatorDecorator(exam: Exam): void { class TestComponent extends TestThemeComponent { @ThemeAnimator({type: Number, value: 0}) readonly foo!: ThemeAnimator<this, number>; } const component = new TestComponent(); component.mount(); exam.equal(component.foo.name, "foo"); exam.equal(component.foo.state, 0); exam.equal(component.foo.value, 0); component.foo.setState(1); exam.equal(component.foo.state, 1); exam.equal(component.foo.value, 1); exam.identical(component.foo(0.5), component, "accessor set"); exam.equal(component.foo(), 0.5, "accessor get"); } @Test testThemeAnimatorLook(exam: Exam): void { const theme = Theme.dark; const mood = Mood.default; const color = theme.get(Look.color, mood)!; class TestComponent extends TestThemeComponent { @ThemeAnimator({type: Color, value: null}) readonly foo!: ThemeAnimator<this, Color | null>; } const component = new TestComponent(); component.theme.setValue(theme); component.mood.setValue(mood); component.mount(); exam.equal(component.foo.name, "foo"); exam.equal(component.foo.look, null); exam.equal(component.foo.state, null); exam.equal(component.foo.value, null); component.foo.setLook(Look.color); exam.equal(component.foo.look, Look.color); exam.equal(component.foo.state, color); exam.equal(component.foo.value, color); } @Test testThemeAnimatorLookInheritance(exam: Exam): void { const theme = Theme.dark; const mood = Mood.default; const color = theme.get(Look.color, mood)!; const backgroundColor = theme.get(Look.backgroundColor, mood)!; class TestComponent extends TestThemeComponent { @ThemeAnimator({type: Color, value: null, inherits: true}) readonly foo!: ThemeAnimator<this, Color | null>; } const parent = new TestComponent(); parent.theme.setValue(theme); parent.mood.setValue(mood); const child = new TestComponent(); parent.appendChild(child); parent.mount(); exam.equal(child.foo.superFastener, parent.foo); exam.equal(parent.foo.look, null); exam.equal(parent.foo.state, null); exam.equal(parent.foo.value, null); exam.false(parent.foo.inherited); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.look, null); exam.equal(child.foo.state, null); exam.equal(child.foo.value, null); exam.true(child.foo.inherited); exam.true(child.foo.coherent); exam.false(child.foo.tweening); parent.foo.setLook(Look.color, false); exam.equal(parent.foo.look, Look.color); exam.equal(parent.foo.state, color); exam.equal(parent.foo.value, color); exam.false(parent.foo.inherited); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.look, null); exam.equal(child.foo.state, null); exam.equal(child.foo.value, null); exam.true(child.foo.inherited); exam.false(child.foo.coherent); exam.false(child.foo.tweening); child.recohereFasteners(); exam.equal(child.foo.look, Look.color); exam.equal(child.foo.state, color); exam.equal(child.foo.value, color); exam.true(child.foo.inherited); exam.true(child.foo.coherent); exam.false(child.foo.tweening); child.foo.setLook(Look.backgroundColor, false); exam.equal(parent.foo.look, Look.color); exam.equal(parent.foo.state, color); exam.equal(parent.foo.value, color); exam.false(parent.foo.inherited); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.look, Look.backgroundColor); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, backgroundColor); exam.false(child.foo.inherited); exam.true(child.foo.coherent); exam.false(child.foo.tweening); child.foo.setAffinity(Affinity.Inherited); exam.equal(parent.foo.look, Look.color); exam.equal(parent.foo.state, color); exam.equal(parent.foo.value, color); exam.false(parent.foo.inherited); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.look, Look.color); exam.equal(child.foo.state, color); exam.equal(child.foo.value, color); exam.true(child.foo.inherited); exam.true(child.foo.coherent); exam.false(child.foo.tweening); } @Test testThemeAnimatorLookTweening(exam: Exam): void { const theme = Theme.dark; const mood = Mood.default; const color = theme.get(Look.color, mood)!; const backgroundColor = theme.get(Look.backgroundColor, mood)!; const colorInterpolator = color.interpolateTo(backgroundColor); class TestComponent extends TestThemeComponent { @ThemeAnimator({type: Color, look: Look.color}) readonly foo!: ThemeAnimator<this, Color | null>; } const component = new TestComponent(); component.theme.setValue(theme); component.mood.setValue(mood); component.mount(); exam.equal(component.foo.look, Look.color); exam.equal(component.foo.state, color); exam.equal(component.foo.value, color); exam.false(component.foo.tweening); component.foo.setLook(Look.backgroundColor, Easing.linear.withDuration(1000)); exam.equal(component.foo.look, Look.backgroundColor); exam.equal(component.foo.state, backgroundColor); exam.equal(component.foo.value, color); exam.true(component.foo.tweening); component.recohereFasteners(0); exam.equal(component.foo.look, Look.backgroundColor); exam.equal(component.foo.state, backgroundColor); exam.equal(component.foo.value, color); exam.true(component.foo.tweening); component.recohereFasteners(500); exam.equal(component.foo.look, Look.backgroundColor); exam.equal(component.foo.state, backgroundColor); exam.equal(component.foo.value, colorInterpolator(0.5)); exam.true(component.foo.tweening); component.recohereFasteners(1000); exam.equal(component.foo.look, Look.backgroundColor); exam.equal(component.foo.state, backgroundColor); exam.equal(component.foo.value, backgroundColor); exam.false(component.foo.tweening); } @Test testThemeAnimatorLookTweeningInheritance(exam: Exam): void { const theme = Theme.dark; const mood = Mood.default; const color = theme.get(Look.color, mood)!; const backgroundColor = theme.get(Look.backgroundColor, mood)!; const colorInterpolator = color.interpolateTo(backgroundColor); class TestComponent extends TestThemeComponent { @ThemeAnimator({type: Color, look: Look.color, inherits: true}) readonly foo!: ThemeAnimator<this, Color | null>; } const parent = new TestComponent(); parent.theme.setValue(theme); parent.mood.setValue(mood); const child = new TestComponent(); parent.appendChild(child); parent.mount(); exam.equal(child.foo.superFastener, parent.foo); exam.equal(parent.foo.state, color); exam.equal(parent.foo.value, color); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.state, color); exam.equal(child.foo.value, color); exam.true(child.foo.coherent); exam.false(child.foo.tweening); parent.foo.setLook(Look.backgroundColor, Easing.linear.withDuration(1000)); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, color); exam.false(parent.foo.coherent); exam.true(parent.foo.tweening); exam.equal(child.foo.state, color); exam.equal(child.foo.value, color); exam.false(parent.foo.coherent); exam.true(child.foo.tweening); parent.recohereFasteners(0); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, color); exam.false(parent.foo.coherent); exam.true(parent.foo.tweening); exam.equal(child.foo.state, color); exam.equal(child.foo.value, color); exam.false(child.foo.coherent); exam.true(child.foo.tweening); child.recohereFasteners(0); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, color); exam.false(parent.foo.coherent); exam.true(parent.foo.tweening); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, color); exam.false(child.foo.coherent); exam.true(child.foo.tweening); parent.recohereFasteners(500); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, colorInterpolator(0.5)); exam.false(parent.foo.coherent); exam.true(parent.foo.tweening); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, color); exam.false(child.foo.coherent); exam.true(child.foo.tweening); child.recohereFasteners(500); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, colorInterpolator(0.5)); exam.false(parent.foo.coherent); exam.true(parent.foo.tweening); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, colorInterpolator(0.5)); exam.false(child.foo.coherent); exam.true(child.foo.tweening); parent.recohereFasteners(1000); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, backgroundColor); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, colorInterpolator(0.5)); exam.false(child.foo.coherent); exam.true(child.foo.tweening); child.recohereFasteners(1000); exam.equal(parent.foo.state, backgroundColor); exam.equal(parent.foo.value, backgroundColor); exam.true(parent.foo.coherent); exam.false(parent.foo.tweening); exam.equal(child.foo.state, backgroundColor); exam.equal(child.foo.value, backgroundColor); exam.true(child.foo.coherent); exam.false(child.foo.tweening); } }
the_stack
import 'jest-extended' import { request } from '@test/server' import fs from 'fs' import { promisify } from 'util' import { end } from '@test/supertest-shared-utils' import { Response } from 'superagent' import { getClaims } from '@shared/jwt' import { registerAndLoginAccount } from '@test/utils' import { SuperTest, Test } from 'supertest' const getUserId = (token: string): string => getClaims(token)['x-hasura-user-id'] const registerAndLoginAccountUserId = async (agent: SuperTest<Test>) => { return getUserId((await registerAndLoginAccount(agent)).token) } const readFile = promisify(fs.readFile) const filePath = 'package.json' function bodyArray(length: number) { return (res: Response) => { expect(res.body).toBeArrayOfSize(length) } } function text() { return (res: Response) => { expect(res.text).toBeTruthy() } } function textIsFileData(fileData: string) { return (res: Response) => { expect(res.text).toEqual(fileData) } } function token(saver: (t: string) => any) { return (res: Response) => { saver(res.body.Metadata.token) } } function tokenIsFileToken(fileToken: string) { return (res: Response) => { expect(res.body.Metadata.token).toEqual(fileToken) } } function setFileToken(saver: (f: string) => any) { return (res: Response) => { saver(res.body.Metadata.token) } } it('new user should not have any files', (done) => { registerAndLoginAccountUserId(request).then(id => { request.get(`/storage/m/user/${id}/`) .expect(200) .expect(bodyArray(0)) .end(end(done)) }) }) it('should be able to upload a new file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end(end(done)) }) }) it('should be able to revoke and generate new token', (done) => { let fileToken = '' registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .expect(setFileToken(f => fileToken = f)) .end((err) => { if(err) return done(err) request .post(`/storage/m/user/${id}/${filePath}`) .set({ 'x-admin-secret': process.env.HASURA_GRAPHQL_ADMIN_SECRET }) .send({ action: 'revoke-token' }) .expect(200) .expect(token( t => expect(t).not.toEqual(fileToken) )) .end(end(done)) }) }) }) it('should fail to revoke token on incorrect admin secret', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/m/user/${id}/${filePath}`) .set({ 'x-admin-secret': 'incorrect-admin-secret' }) .send({ action: 'revoke-token' }) .expect(403) .end(end(done)) }) }) }) it('should fail with non existing action with correct admin secret', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/m/user/${id}/${filePath}`) .set({ 'x-admin-secret': process.env.HASURA_GRAPHQL_ADMIN_SECRET }) .send({ action: 'non-existing' }) .expect(400) .end(end(done)) }) }) }) it('should fail to with incorrect action and incorrect admin secret', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/m/user/${id}/${filePath}`) .set({ 'x-admin-secret': 'incorrect-admin-secret' }) .send({ action: 'non-existing' }) .expect(400) .end(end(done)) }) }) }) it('should get the correct amount of files', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .get(`/storage/m/user/${id}/`) .expect(200) .expect(bodyArray(1)) .end(end(done)) }) }) }) it('should fail if trying to upload, without a file attached', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/o/user/${id}/${filePath}`) .expect(400) .end(end(done)) }) }) }) it('should update an existing file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end(end(done)) }) }) }) it('should not upload file on missing file name in correct path', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/`) .attach('file', filePath) .expect(404) .end(end(done)) }) }) it('should not upload file on incorrect file path', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/123/`) .attach('file', filePath) .expect(403) .end(end(done)) }) }) it('should only include one file when updating the same file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .expect( token( t => expect(t).toBeString() ) ) .end((err) => { if(err) return done(err) request .get(`/storage/m/user/${id}/`) .expect(200) .expect(bodyArray(1)) .end(end(done)) }) }) }) }) it('should not update an hypothetical file of another hypothetical user', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/another-user/another-file`) .attach('file', filePath) .expect(403) .end(end(done)) }) }) it('should get file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) readFile(filePath, 'utf8').then(fileData => { request .get(`/storage/o/user/${id}/${filePath}`) .expect(200) .expect(textIsFileData(fileData)) .end(end(done)) }) }) }) }) describe('Tests as an unauthenticated user', () => { it('should get file from the token stored in the file metadata while unauthenticated', (done) => { let fileToken = '' registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .expect( token( t => expect(t).toBeString() ) ) .expect(setFileToken(f => fileToken = f)) .end((err) => { if(err) return done(err) request .post(`/auth/logout`) .end((err) => { if(err) return done(err) readFile(filePath, 'utf8').then(fileData => { request .get(`/storage/o/user/${id}/${filePath}`) .query({ token: fileToken }) .expect(200) .expect(textIsFileData(fileData)) .end(end(done)) }); }) }) }) }) it('should not get file from incorrect token while unauthenticated', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/auth/logout`) .end((err) => { if(err) return done(err) readFile(filePath, 'utf8').then(() => { request .get(`/storage/o/user/${id}/${filePath}`) .query({ token: 'incorrect' }) .expect(403) .end(end(done)) }); }) }) }) }) it('should not get file without authentication nor token', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .post(`/auth/logout`) .end((err) => { if(err) return done(err) request .get(`/storage/o/user/${id}/${filePath}`) .expect(403) .end(end(done)) }) }) }) }) // TODO attempt to get the file from another authenticated user }) // it(`should update an existing file's metadata`, (done) => { // const { status } = await request // .post(`/storage/m/user/${id}/${filePath}`) // .query({ description: newDescription }) // expect(status).toEqual(200) // }) it('should get file metadata', (done) => { let fileToken = '' registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .expect( token( t => expect(t).toBeString() ) ) .expect(setFileToken(f => fileToken = f)) .end((err) => { if(err) return done(err) request .get(`/storage/m/user/${id}/${filePath}`) .expect(200) .expect(tokenIsFileToken(fileToken)) .end(end(done)) }) }) }) it('should get the headers of all the user files', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .get(`/storage/m/user/${id}/`) .expect(200) .expect(bodyArray(1)) .end(end(done)) }) }) }) it('should get a zip that contains all user files', (done) => { registerAndLoginAccountUserId(request).then(id => { request .get(`/storage/o/user/${id}/`) .expect(200) .expect(text()) .end(end(done)) }) // TODO unzip and compare the file(s) }) it('should delete file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .post(`/storage/o/user/${id}/${filePath}`) .attach('file', filePath) .expect(200) .end((err) => { if(err) return done(err) request .delete(`/storage/o/user/${id}/${filePath}`) .expect(204) .end(end(done)) }) }) }) it('should not be able to get deleted file', (done) => { registerAndLoginAccountUserId(request).then(id => { request .get(`/storage/o/user/${id}/${filePath}`) .expect(404) .end(end(done)) }) }) it('should get the headers of no files', (done) => { registerAndLoginAccountUserId(request).then(id => { request .get(`/storage/m/user/${id}/`) .expect(200) .expect(bodyArray(0)) .end(end(done)) }) }) it('should upload a new imae', (done) => { request .post(`/storage/o/public/example.jpg`) .attach('file', 'test-mocks/example.jpg') .expect(200) .end(end(done)) }) it('should get image', (done) => { request .get(`/storage/o/public/example.jpg`) .expect(200) .end(end(done)) }) it('should get image with width and height parameter', (done) => { request .get(`/storage/o/public/example.jpg?w=100&h=200`) .expect(200) .end(end(done)) }) it('should get image with width, height and quality parameter', (done) => { request .get(`/storage/o/public/example.jpg?w=100&h=200&q=50`) .expect(200) .end(end(done)) }) it('should fail to get image with width parameter of -1', (done) => { request .get(`/storage/o/public/example.jpg?w=-1`) .expect(400) .end(end(done)) }) it('should fail to get image with width parameter of 10000', (done) => { request .get(`/storage/o/public/example.jpg?w=10000`) .expect(400) .end(end(done)) }) it('should fail to get image with height parameter of -1', (done) => { request .get(`/storage/o/public/example.jpg?h=-1`) .expect(400) .end(end(done)) }) it('should fail to get image with height parameter of 10000', (done) => { request .get(`/storage/o/public/example.jpg?h=10000`) .expect(400) .end(end(done)) }) it('should fail to get image with quality parameter of -1', (done) => { request .get(`/storage/o/public/example.jpg?q=-1`) .expect(400) .end(end(done)) }) it('should fail to get image with quality parameter of 101', (done) => { request .get(`/storage/o/public/example.jpg?q=101`) .expect(400) .end(end(done)) })
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Key Vault. * * ## Disclaimers * * > **Note:** It's possible to define Key Vault Access Policies both within the `azure.keyvault.KeyVault` resource via the `accessPolicy` block and by using the `azure.keyvault.AccessPolicy` resource. However it's not possible to use both methods to manage Access Policies within a KeyVault, since there'll be conflicts. * * > **Note:** This provider will automatically recover a soft-deleted Key Vault during Creation if one is found - you can opt out of this using the `features` configuration within the Provider configuration block. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const current = azure.core.getClientConfig({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleKeyVault = new azure.keyvault.KeyVault("exampleKeyVault", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * enabledForDiskEncryption: true, * tenantId: current.then(current => current.tenantId), * softDeleteRetentionDays: 7, * purgeProtectionEnabled: false, * skuName: "standard", * accessPolicies: [{ * tenantId: current.then(current => current.tenantId), * objectId: current.then(current => current.objectId), * keyPermissions: ["Get"], * secretPermissions: ["Get"], * storagePermissions: ["Get"], * }], * }); * ``` * * ## Import * * Key Vault's can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:keyvault/keyVault:KeyVault example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.KeyVault/vaults/vault1 * ``` */ export class KeyVault extends pulumi.CustomResource { /** * Get an existing KeyVault 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?: KeyVaultState, opts?: pulumi.CustomResourceOptions): KeyVault { return new KeyVault(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:keyvault/keyVault:KeyVault'; /** * Returns true if the given object is an instance of KeyVault. 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 KeyVault { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === KeyVault.__pulumiType; } /** * A list of up to 16 objects describing access policies, as described below. */ public readonly accessPolicies!: pulumi.Output<outputs.keyvault.KeyVaultAccessPolicy[]>; /** * One or more `contact` block as defined below. */ public readonly contacts!: pulumi.Output<outputs.keyvault.KeyVaultContact[] | undefined>; /** * Boolean flag to specify whether Azure Key Vault uses Role Based Access Control (RBAC) for authorization of data actions. Defaults to `false`. */ public readonly enableRbacAuthorization!: pulumi.Output<boolean | undefined>; /** * Boolean flag to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault. Defaults to `false`. */ public readonly enabledForDeployment!: pulumi.Output<boolean | undefined>; /** * Boolean flag to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. Defaults to `false`. */ public readonly enabledForDiskEncryption!: pulumi.Output<boolean | undefined>; /** * Boolean flag to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. Defaults to `false`. */ public readonly enabledForTemplateDeployment!: pulumi.Output<boolean | undefined>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ public readonly location!: pulumi.Output<string>; /** * Specifies the name of the Key Vault. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * A `networkAcls` block as defined below. */ public readonly networkAcls!: pulumi.Output<outputs.keyvault.KeyVaultNetworkAcls>; /** * Is Purge Protection enabled for this Key Vault? Defaults to `false`. */ public readonly purgeProtectionEnabled!: pulumi.Output<boolean | undefined>; /** * The name of the resource group in which to create the Key Vault. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The Name of the SKU used for this Key Vault. Possible values are `standard` and `premium`. */ public readonly skuName!: pulumi.Output<string>; /** * @deprecated Azure has removed support for disabling Soft Delete as of 2020-12-15, as such this field is no longer configurable and can be safely removed. This field will be removed in version 3.0 of the Azure Provider. */ public readonly softDeleteEnabled!: pulumi.Output<boolean>; /** * The number of days that items should be retained for once soft-deleted. This value can be between `7` and `90` (the default) days. */ public readonly softDeleteRetentionDays!: pulumi.Output<number | undefined>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. */ public readonly tenantId!: pulumi.Output<string>; /** * The URI of the Key Vault, used for performing operations on keys and secrets. */ public /*out*/ readonly vaultUri!: pulumi.Output<string>; /** * Create a KeyVault 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: KeyVaultArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: KeyVaultArgs | KeyVaultState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as KeyVaultState | undefined; inputs["accessPolicies"] = state ? state.accessPolicies : undefined; inputs["contacts"] = state ? state.contacts : undefined; inputs["enableRbacAuthorization"] = state ? state.enableRbacAuthorization : undefined; inputs["enabledForDeployment"] = state ? state.enabledForDeployment : undefined; inputs["enabledForDiskEncryption"] = state ? state.enabledForDiskEncryption : undefined; inputs["enabledForTemplateDeployment"] = state ? state.enabledForTemplateDeployment : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["networkAcls"] = state ? state.networkAcls : undefined; inputs["purgeProtectionEnabled"] = state ? state.purgeProtectionEnabled : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["skuName"] = state ? state.skuName : undefined; inputs["softDeleteEnabled"] = state ? state.softDeleteEnabled : undefined; inputs["softDeleteRetentionDays"] = state ? state.softDeleteRetentionDays : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tenantId"] = state ? state.tenantId : undefined; inputs["vaultUri"] = state ? state.vaultUri : undefined; } else { const args = argsOrState as KeyVaultArgs | undefined; if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.skuName === undefined) && !opts.urn) { throw new Error("Missing required property 'skuName'"); } if ((!args || args.tenantId === undefined) && !opts.urn) { throw new Error("Missing required property 'tenantId'"); } inputs["accessPolicies"] = args ? args.accessPolicies : undefined; inputs["contacts"] = args ? args.contacts : undefined; inputs["enableRbacAuthorization"] = args ? args.enableRbacAuthorization : undefined; inputs["enabledForDeployment"] = args ? args.enabledForDeployment : undefined; inputs["enabledForDiskEncryption"] = args ? args.enabledForDiskEncryption : undefined; inputs["enabledForTemplateDeployment"] = args ? args.enabledForTemplateDeployment : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["networkAcls"] = args ? args.networkAcls : undefined; inputs["purgeProtectionEnabled"] = args ? args.purgeProtectionEnabled : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["skuName"] = args ? args.skuName : undefined; inputs["softDeleteEnabled"] = args ? args.softDeleteEnabled : undefined; inputs["softDeleteRetentionDays"] = args ? args.softDeleteRetentionDays : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["tenantId"] = args ? args.tenantId : undefined; inputs["vaultUri"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(KeyVault.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering KeyVault resources. */ export interface KeyVaultState { /** * A list of up to 16 objects describing access policies, as described below. */ accessPolicies?: pulumi.Input<pulumi.Input<inputs.keyvault.KeyVaultAccessPolicy>[]>; /** * One or more `contact` block as defined below. */ contacts?: pulumi.Input<pulumi.Input<inputs.keyvault.KeyVaultContact>[]>; /** * Boolean flag to specify whether Azure Key Vault uses Role Based Access Control (RBAC) for authorization of data actions. Defaults to `false`. */ enableRbacAuthorization?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault. Defaults to `false`. */ enabledForDeployment?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. Defaults to `false`. */ enabledForDiskEncryption?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. Defaults to `false`. */ enabledForTemplateDeployment?: pulumi.Input<boolean>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * Specifies the name of the Key Vault. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A `networkAcls` block as defined below. */ networkAcls?: pulumi.Input<inputs.keyvault.KeyVaultNetworkAcls>; /** * Is Purge Protection enabled for this Key Vault? Defaults to `false`. */ purgeProtectionEnabled?: pulumi.Input<boolean>; /** * The name of the resource group in which to create the Key Vault. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The Name of the SKU used for this Key Vault. Possible values are `standard` and `premium`. */ skuName?: pulumi.Input<string>; /** * @deprecated Azure has removed support for disabling Soft Delete as of 2020-12-15, as such this field is no longer configurable and can be safely removed. This field will be removed in version 3.0 of the Azure Provider. */ softDeleteEnabled?: pulumi.Input<boolean>; /** * The number of days that items should be retained for once soft-deleted. This value can be between `7` and `90` (the default) days. */ softDeleteRetentionDays?: pulumi.Input<number>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. */ tenantId?: pulumi.Input<string>; /** * The URI of the Key Vault, used for performing operations on keys and secrets. */ vaultUri?: pulumi.Input<string>; } /** * The set of arguments for constructing a KeyVault resource. */ export interface KeyVaultArgs { /** * A list of up to 16 objects describing access policies, as described below. */ accessPolicies?: pulumi.Input<pulumi.Input<inputs.keyvault.KeyVaultAccessPolicy>[]>; /** * One or more `contact` block as defined below. */ contacts?: pulumi.Input<pulumi.Input<inputs.keyvault.KeyVaultContact>[]>; /** * Boolean flag to specify whether Azure Key Vault uses Role Based Access Control (RBAC) for authorization of data actions. Defaults to `false`. */ enableRbacAuthorization?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Virtual Machines are permitted to retrieve certificates stored as secrets from the key vault. Defaults to `false`. */ enabledForDeployment?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Disk Encryption is permitted to retrieve secrets from the vault and unwrap keys. Defaults to `false`. */ enabledForDiskEncryption?: pulumi.Input<boolean>; /** * Boolean flag to specify whether Azure Resource Manager is permitted to retrieve secrets from the key vault. Defaults to `false`. */ enabledForTemplateDeployment?: pulumi.Input<boolean>; /** * Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created. */ location?: pulumi.Input<string>; /** * Specifies the name of the Key Vault. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A `networkAcls` block as defined below. */ networkAcls?: pulumi.Input<inputs.keyvault.KeyVaultNetworkAcls>; /** * Is Purge Protection enabled for this Key Vault? Defaults to `false`. */ purgeProtectionEnabled?: pulumi.Input<boolean>; /** * The name of the resource group in which to create the Key Vault. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * The Name of the SKU used for this Key Vault. Possible values are `standard` and `premium`. */ skuName: pulumi.Input<string>; /** * @deprecated Azure has removed support for disabling Soft Delete as of 2020-12-15, as such this field is no longer configurable and can be safely removed. This field will be removed in version 3.0 of the Azure Provider. */ softDeleteEnabled?: pulumi.Input<boolean>; /** * The number of days that items should be retained for once soft-deleted. This value can be between `7` and `90` (the default) days. */ softDeleteRetentionDays?: pulumi.Input<number>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The Azure Active Directory tenant ID that should be used for authenticating requests to the key vault. */ tenantId: pulumi.Input<string>; }
the_stack
import Sandbox, { SandboxConstructor, SandboxProps } from '@ice/sandbox'; import isEmpty from 'lodash.isempty'; import { NOT_LOADED, NOT_MOUNTED, LOADING_ASSETS, UNMOUNTED, LOAD_ERROR, MOUNTED } from './util/constant'; import checkUrlActive, { ActivePath, PathOption, formatPath } from './util/checkActive'; import { createSandbox, getUrlAssets, getEntryAssets, loadAndAppendCssAssets, loadAndAppendJsAssets, emptyAssets, filterRemovedAssets, Assets, } from './util/handleAssets'; import { setCache } from './util/cache'; import { loadScriptByFetch, loadScriptByImport } from './util/loaders'; import { getLifecyleByLibrary, getLifecyleByRegister } from './util/getLifecycle'; import { mergeFrameworkBaseToPath, getAppBasename, shouldSetBasename } from './util/helpers'; import globalConfiguration from './util/globalConfiguration'; import type { StartConfiguration } from './util/globalConfiguration'; export type ScriptAttributes = string[] | ((url: string) => string[]); const importCachedAssets: { [index: string]: HTMLElement[]; } = {}; interface LifecycleProps { container: HTMLElement | string; customProps?: object; } export interface ModuleLifeCycle { mount?: (props: LifecycleProps) => Promise<void> | void; unmount?: (props: LifecycleProps) => Promise<void> | void; update?: (props: LifecycleProps) => Promise<void> | void; bootstrap?: (props: LifecycleProps) => Promise<void> | void; } export interface BaseConfig extends PathOption { name?: string; url?: string | string[]; activePath?: ActivePath; container?: HTMLElement; status?: string; sandbox?: boolean | SandboxProps | SandboxConstructor; entry?: string; entryContent?: string; /** * basename is used for setting custom basename for child's basename. */ basename?: string; /** * will be deprecated in future version, use `loadScriptMode` instead. * @see loadScriptMode * @deprecated */ umd?: boolean; loadScriptMode?: 'fetch' | 'script' | 'import'; checkActive?: (url: string) => boolean; appAssets?: Assets; props?: object; cached?: boolean; title?: string; /** * custom script attributes,only effective when scripts load by `<scrpit />` */ scriptAttributes?: ScriptAttributes; } interface LifeCycleFn { (app: AppConfig): void; } interface AppLifecylceOptions { beforeMount?: LifeCycleFn; afterMount?: LifeCycleFn; beforeUnmount?: LifeCycleFn; afterUnmount?: LifeCycleFn; beforeUpdate?: LifeCycleFn; afterUpdate?: LifeCycleFn; } export interface AppConfig extends BaseConfig { appLifecycle?: AppLifecylceOptions; appSandbox?: Sandbox; } export interface MicroApp extends AppConfig, ModuleLifeCycle { configuration?: StartConfiguration; } // cache all microApp let microApps: MicroApp[] = []; (window as any).microApps = microApps; function getAppNames() { return microApps.map((app) => app.name); } export function getMicroApps() { return microApps; } export function getAppStatus(appName: string) { const app = microApps.find((microApp) => appName === microApp.name); return app ? app.status : ''; } export function registerMicroApp(appConfig: AppConfig, appLifecyle?: AppLifecylceOptions) { // check appConfig.name if (getAppNames().includes(appConfig.name)) { throw Error(`name ${appConfig.name} already been regsitered`); } const { activePath, hashType = false, exact = false, sensitive = false, strict = false } = appConfig; /** * Format activePath in advance */ const activePathArray = formatPath(activePath, { hashType, exact, sensitive, strict, }); const { basename: frameworkBasename } = globalConfiguration; const checkActive = checkUrlActive(mergeFrameworkBaseToPath(activePathArray, frameworkBasename)); const microApp = { status: NOT_LOADED, ...appConfig, appLifecycle: appLifecyle, checkActive, }; microApps.push(microApp); } export function registerMicroApps(appConfigs: AppConfig[], appLifecyle?: AppLifecylceOptions) { appConfigs.forEach((appConfig) => { registerMicroApp(appConfig, appLifecyle); }); } export function getAppConfig(appName: string) { return microApps.find((microApp) => microApp.name === appName); } export function updateAppConfig(appName: string, config) { microApps = microApps.map((microApp) => { if (microApp.name === appName) { return { ...microApp, ...config, }; } return microApp; }); } // load app js assets export async function loadAppModule(appConfig: AppConfig) { const { onLoadingApp, onFinishLoading, fetch } = getAppConfig(appConfig.name)?.configuration || globalConfiguration; let lifecycle: ModuleLifeCycle = {}; onLoadingApp(appConfig); const appSandbox = createSandbox(appConfig.sandbox) as Sandbox; const { url, container, entry, entryContent, name, scriptAttributes = [], umd } = appConfig; const appAssets = url ? getUrlAssets(url) : await getEntryAssets({ root: container, entry, href: location.href, entryContent, assetsCacheKey: name, fetch, }); updateAppConfig(appConfig.name, { appAssets, appSandbox }); /** * LoadScriptMode has the first priority */ const loadScriptMode = appConfig.loadScriptMode ?? (umd ? 'fetch' : 'script'); switch (loadScriptMode) { case 'import': await loadAndAppendCssAssets([ ...appAssets.cssList, ...filterRemovedAssets(importCachedAssets[name] || [], ['LINK', 'STYLE']), ]); lifecycle = await loadScriptByImport(appAssets.jsList); // Not to handle script element temporarily. break; case 'fetch': await loadAndAppendCssAssets(appAssets.cssList); lifecycle = await loadScriptByFetch(appAssets.jsList, appSandbox); break; default: await Promise.all([ loadAndAppendCssAssets(appAssets.cssList), loadAndAppendJsAssets(appAssets, { sandbox: appSandbox, fetch, scriptAttributes }), ]); lifecycle = getLifecyleByLibrary() || getLifecyleByRegister() || {}; } if (isEmpty(lifecycle)) { console.error('[@ice/stark] microapp should export mount/unmout or register registerAppEnter/registerAppLeave.'); } onFinishLoading(appConfig); return combineLifecyle(lifecycle, appConfig); } function capitalize(str: string) { if (typeof str !== 'string') return ''; return `${str.charAt(0).toUpperCase()}${str.slice(1)}`; } async function callAppLifecycle(primaryKey: string, lifecycleKey: string, appConfig: AppConfig) { if (appConfig.appLifecycle && appConfig.appLifecycle[`${primaryKey}${capitalize(lifecycleKey)}`]) { await appConfig.appLifecycle[`${primaryKey}${capitalize(lifecycleKey)}`](appConfig); } } function combineLifecyle(lifecycle: ModuleLifeCycle, appConfig: AppConfig) { const combinedLifecyle = { ...lifecycle }; ['mount', 'unmount', 'update'].forEach((lifecycleKey) => { if (lifecycle[lifecycleKey]) { combinedLifecyle[lifecycleKey] = async (props) => { await callAppLifecycle('before', lifecycleKey, appConfig); await lifecycle[lifecycleKey](props); await callAppLifecycle('after', lifecycleKey, appConfig); }; } }); return combinedLifecyle; } export function getAppConfigForLoad(app: string | AppConfig, options?: AppLifecylceOptions) { if (typeof app === 'string') { return getAppConfig(app); } const { name } = app; const appIndex = getAppNames().indexOf(name); if (appIndex === -1) { registerMicroApp(app, options); } else { updateAppConfig(name, app); } return getAppConfig(name); } export async function createMicroApp(app: string | AppConfig, appLifecyle?: AppLifecylceOptions, configuration?: StartConfiguration) { const appConfig = getAppConfigForLoad(app, appLifecyle); const appName = appConfig && appConfig.name; if (appConfig && appName) { // add configuration to every micro app const userConfiguration = globalConfiguration; Object.keys(configuration || {}).forEach((key) => { userConfiguration[key] = configuration[key]; }); updateAppConfig(appName, { configuration: userConfiguration }); const { container, basename, activePath } = appConfig; if (container) { setCache('root', container); } const { basename: frameworkBasename } = userConfiguration; if (shouldSetBasename(activePath, basename)) { setCache('basename', getAppBasename(activePath, frameworkBasename, basename)); } // check status of app if (appConfig.status === NOT_LOADED || appConfig.status === LOAD_ERROR) { if (appConfig.title) document.title = appConfig.title; updateAppConfig(appName, { status: LOADING_ASSETS }); let lifeCycle: ModuleLifeCycle = {}; try { lifeCycle = await loadAppModule(appConfig); // in case of app status modified by unload event if (getAppStatus(appName) === LOADING_ASSETS) { updateAppConfig(appName, { ...lifeCycle, status: NOT_MOUNTED }); } } catch (err) { userConfiguration.onError(err); updateAppConfig(appName, { status: LOAD_ERROR }); } if (lifeCycle.mount) { await mountMicroApp(appConfig.name); } } else if (appConfig.status === UNMOUNTED) { if (!appConfig.cached) { await loadAndAppendCssAssets(appConfig?.appAssets?.cssList || []); } await mountMicroApp(appConfig.name); } else if (appConfig.status === NOT_MOUNTED) { await mountMicroApp(appConfig.name); } else { console.info(`[icestark] current status of app ${appName} is ${appConfig.status}`); } return getAppConfig(appName); } else { console.error(`[icestark] fail to get app config of ${appName}`); } return null; } export async function mountMicroApp(appName: string) { const appConfig = getAppConfig(appName); // check current url before mount if (appConfig && appConfig.checkActive(window.location.href) && appConfig.status !== MOUNTED) { if (appConfig.mount) { await appConfig.mount({ container: appConfig.container, customProps: appConfig.props }); } updateAppConfig(appName, { status: MOUNTED }); } } export async function unmountMicroApp(appName: string) { const appConfig = getAppConfig(appName); if (appConfig && (appConfig.status === MOUNTED || appConfig.status === LOADING_ASSETS || appConfig.status === NOT_MOUNTED)) { // remove assets if app is not cached const { shouldAssetsRemove } = getAppConfig(appName)?.configuration || globalConfiguration; const removedAssets = emptyAssets(shouldAssetsRemove, !appConfig.cached && appConfig.name); /** * Since es module natively imported twice may never excute twice. https://dmitripavlutin.com/javascript-module-import-twice/ * Cache all child's removed assets, then append them when app is mounted for the second time. * Only cache removed assets when app's loadScriptMode is import which may not cause break change. */ if (appConfig.loadScriptMode === 'import') { importCachedAssets[appName] = removedAssets; } updateAppConfig(appName, { status: UNMOUNTED }); if (!appConfig.cached && appConfig.appSandbox) { appConfig.appSandbox.clear(); appConfig.appSandbox = null; } if (appConfig.unmount) { await appConfig.unmount({ container: appConfig.container, customProps: appConfig.props }); } } } // unload micro app, load app bundles when create micro app export async function unloadMicroApp(appName: string) { const appConfig = getAppConfig(appName); if (appConfig) { unmountMicroApp(appName); delete appConfig.mount; delete appConfig.unmount; delete appConfig.appAssets; updateAppConfig(appName, { status: NOT_LOADED }); } else { console.log(`[icestark] can not find app ${appName} when call unloadMicroApp`); } } // remove app config from cache export function removeMicroApp(appName: string) { const appIndex = getAppNames().indexOf(appName); if (appIndex > -1) { // unload micro app in case of app is mounted unloadMicroApp(appName); microApps.splice(appIndex, 1); } else { console.log(`[icestark] can not find app ${appName} when call removeMicroApp`); } } export function removeMicroApps(appNames: string[]) { appNames.forEach((appName) => { removeMicroApp(appName); }); } // clear all micro app configs export function clearMicroApps() { getAppNames().forEach((name) => { unloadMicroApp(name); }); microApps = []; }
the_stack
import * as vscode from 'vscode'; import { Rules } from './rules'; import { Line, Element, BlockElement, ElementType, BlockElementType, Analyst } from './analyst'; export interface FormatterConfig { allowInlineFormat: boolean, allowSplitLine: boolean, newLineForBlockStart: boolean, } export class Formatter { constructor( public rules: Rules, public config: FormatterConfig, ) { if (!config) this.config = { allowInlineFormat: true, allowSplitLine: true, newLineForBlockStart: false } } formate(document: vscode.TextDocument, options: vscode.FormattingOptions, token: vscode.CancellationToken): vscode.TextEdit[] { let edits: vscode.TextEdit[] = []; const spaceStr = options.insertSpaces ? " ".repeat(options.tabSize) : "\t"; let lineTexts: string[] = []; let lines: vscode.TextLine[] = []; for (let i = 0; i < document.lineCount; i++) { lines.push(document.lineAt(i)); lineTexts.push(lines[i].text); } let analyst = new Analyst(lineTexts, this.rules, !this.config.allowInlineFormat); analyst.analysis(); return this.getEdits(analyst.lines, lines, spaceStr, this.config.allowInlineFormat, this.config.allowSplitLine); } private getEdits(lines: Line[], rangeLines: vscode.TextLine[], spaceStr: string, allowInlineFormat: boolean, allowSplitLine: boolean): vscode.TextEdit[] { let edits: vscode.TextEdit[] = []; let blockLevel = 0; if (!allowSplitLine) { lines.map((line, i) => { let delta = 0; let newText = allowInlineFormat ? this.formatLine(line) : line.text; let appliedLevel = blockLevel; // apply level of first blockElement if (line.blockElements.length) { switch (line.blockElements[0].type) { case BlockElementType.blockStart: appliedLevel = appliedLevel + 1; delta = -1; break; case BlockElementType.blockEnd: appliedLevel = appliedLevel - 1; delta = 0; break; case BlockElementType.blockAgain: delta = -1; default: break; } } //calc level change blockLevel = line.blockElements.reduce((p, c) => { switch (c.type) { case BlockElementType.blockStart: p++; break; case BlockElementType.blockEnd: p--; break; default: break; } return p; }, blockLevel); newText = this.indent(newText, spaceStr, appliedLevel + delta); edits.push(new vscode.TextEdit(rangeLines[i].range, newText)); }); } else { let splitedLines = lines.map(v => { // p.push(...this.splitLine(v)); return this.splitLine(v, this.config.newLineForBlockStart); }) let blockLevel = 0; for (let i = 0; i < splitedLines.length; i++) { let newText = ""; splitedLines[i].map((line, i) => { let delta = 0; if (line.blockElements.length) { switch (line.blockElements[0].type) { case BlockElementType.blockStart: blockLevel++; delta = -1; break; case BlockElementType.blockEnd: blockLevel--; delta = 0; break; case BlockElementType.blockAgain: delta = -1; default: break; } } newText += (newText ? "\n" : "") + this.indent(this.formatLine(line), spaceStr, blockLevel + delta); }); edits.push(new vscode.TextEdit(rangeLines[i].range, newText)); } } return edits; } private indent(lineText: string, spaceStr: string, level: number): string { if (!lineText.trim()) return ""; level = level < 0 ? 0 : level; return spaceStr.repeat(level) + lineText.trim(); } private formatLine(line: Line): string { if (line.text && line.text.trim() && !line.elements.length) throw ("no element found for a non-empty line!"); if (!line.elements.length) return ""; if (!this.config.allowInlineFormat) return line.elements.reduce((p, c) => p + c.text, ""); let text = getElementText(line.elements[0]); for (let i = 0; i < line.elements.length - 1; i++) { let thisEl = line.elements[i]; let nextEl = line.elements[i + 1]; switch (thisEl.type) { case ElementType.none: case ElementType.word: switch (nextEl.type) { case ElementType.none: case ElementType.punctLeftSpace: case ElementType.operater: case ElementType.word: text += " " + getElementText(nextEl); break; default: text += getElementText(nextEl); break; } break; case ElementType.operater: text += " " + getElementText(nextEl); break; case ElementType.punctRightSpace: switch (nextEl.type) { case ElementType.none: case ElementType.word: case ElementType.operater: case ElementType.punctLeftSpace: text += " " + getElementText(nextEl); break; default: text += getElementText(nextEl); break; } break; case ElementType.punctLeftSpace: case ElementType.connector: default: switch (nextEl.type) { case ElementType.operater: text += " " + getElementText(nextEl); break; default: text += getElementText(nextEl); break; } break; } } return text; function getElementText(el: Element): string { if (el.type == ElementType.asIs) return el.text; return el.text.trim(); } } private splitLine(line: Line, newLineForBlockStart: boolean): Line[] { let splitedLine: Line = null; let splitedLines: Line[] = []; let newLineElements: BlockElement[] = []; let lastNewLineBlockElementEnd = -1; //Previously pushed elements are part of a blockElement or not let inBlockElement = false; for (let b of line.blockElements) { if (!isInlineBlock(b, line.blockElements)) { for (let e of line.elements) { //do not deal with elements after this blockElement if (e.start > b.end) break; //ignore elements before last blockElement if (e.end <= lastNewLineBlockElementEnd) continue; //deal with elements before this blockElement if (e.end < b.start) { if (inBlockElement) pushSplitLine(); pushElement(e, null); inBlockElement = false; } if (e.start >= b.start && e.end <= b.end) { //deal with elements of this blockElement if (b.type == BlockElementType.blockStart && !newLineForBlockStart) { pushElement(e, b); } else { if (!inBlockElement) pushSplitLine(); pushElement(e, b); } inBlockElement = true; } } lastNewLineBlockElementEnd = b.end; } } pushSplitLine(); for (let e of line.elements) { if (e.end <= lastNewLineBlockElementEnd) continue; pushElement(e, null); } pushSplitLine(); return splitedLines; function pushSplitLine() { if (splitedLine) { splitedLines.push(splitedLine); splitedLine = null } } function pushElement(el: Element, bl: BlockElement) { if (!splitedLine) splitedLine = <Line>{ elements: [], blockElements: [] }; if (el) splitedLine.elements.push(el); if (bl) splitedLine.blockElements.push(bl); } function isInlineBlock(element: BlockElement, elements: BlockElement[]): boolean { let findBegin = false; let findEnd = false; return elements.reduce((p, e) => { //if already true, or not target block, or is self, return previous value. if (p || element.level != e.level || element.index != e.index || element.start == e.start) return p; if (element.type == BlockElementType.blockStart || element.type == BlockElementType.blockEnd) { if (e.type == (element.type == BlockElementType.blockStart ? BlockElementType.blockEnd : BlockElementType.blockStart)) { return true; } } else { if (e.type == BlockElementType.blockStart) findBegin = true; if (e.type == BlockElementType.blockEnd) findEnd = true; if (findBegin && findEnd) return true; } return false; }, false); } } }
the_stack
import { debugExec, fetchToCache, notNull, withTmpDir } from "@adpt/utils"; import db from "debug"; import execa from "execa"; import { writeFile } from "fs-extra"; import * as ld from "lodash"; import * as os from "os"; import * as path from "path"; import * as readline from "readline"; import { Readable } from "stream"; import { isExecaError } from "../common"; import { Environment, mergeEnvSimple } from "../env"; import { Kubeconfig } from "./common"; import { Manifest } from "./manifest_support"; export const debug = db("adapt:cloud:k8s"); // Enable with DEBUG=adapt:cloud:k8s:out* export const debugOut = db("adapt:cloud:k8s:out"); const exec = debugExec(debug, debugOut); function kubectlPlatform(platform: string) { switch (platform) { case "linux": case "darwin": return platform; case "win32": return "windows"; default: throw new Error(`Unsupported platform for kubectl: ${platform}`); } } const kubeRelease = "v1.19.2"; /** * Downloads kubectl and returns path to its location * * @returns path to kubectl on host * @internal */ export async function getKubectl(): Promise<string> { const platform = kubectlPlatform(os.platform()); const extension = platform === "windows" ? ".exe" : ""; const url = `https://storage.googleapis.com/kubernetes-release/release/${kubeRelease}/bin/${platform}/amd64/kubectl${extension}`; const { file } = await fetchToCache({ name: "kubectl", url, mode: 0o700, version: kubeRelease, }); return file; } /** @internal */ interface KubectlOptions { /** path to kubeconfig */ kubeconfig?: string; env?: Environment; printFailure?: boolean; reject?: boolean; } const kubectlDefaults = { printFailure: true, reject: true, }; export async function kubectl(args: string[], options: KubectlOptions) { const kubectlPath = await getKubectl(); const { kubeconfig, env, printFailure, reject } = { ...kubectlDefaults, ...options }; const actualArgs = []; if (kubeconfig) actualArgs.push("--kubeconfig", kubeconfig); actualArgs.push(...args); return exec(kubectlPath, actualArgs, { env: mergeEnvSimple(env), printFailure, reject, }); } async function getKubeconfigPath(tmpDir: string, config: Kubeconfig | string) { if (ld.isString(config)) return config; const loc = path.join(tmpDir, "kubeconfig"); await writeFile(loc, JSON.stringify(config)); return loc; } /** @internal */ export interface KubectlGetOptions { /** path to kubeconfig, or kubeconfig as a Javascript object */ kubeconfig?: Kubeconfig | string; /** Type of k8s object to get (e.g., pod, service) */ kind: string; /** Name of object to get */ name: string; /** Namespace of object to get */ namespace?: string; } const getManifestDefaults = {}; /** @internal */ export async function kubectlGet(options: KubectlGetOptions) { const opts = { ...getManifestDefaults, ...options }; const { kubeconfig, kind, name, namespace } = opts; return withTmpDir(async (tmpDir) => { const configPath = kubeconfig && await getKubeconfigPath(tmpDir, kubeconfig); const args = ["get", "-o", "json", namespace ? `--namespace=${namespace}` : null, kind, name].filter(notNull); let result: execa.ExecaReturnValue<string>; try { result = await kubectl(args, { kubeconfig: configPath }); } catch (e) { if (isExecaError(e) && e.all) { if (e.exitCode !== 0) { if (e.all.match(/Error from server \(NotFound\)/)) return undefined; } } throw e; } return JSON.parse(result.stdout); }); } /** @internal */ export interface KubectlDiffOptions { kubeconfig?: Kubeconfig | string; manifest: Manifest; } const diffDefaults = {}; const lastApplied = "kubectl.kubernetes.io/last-applied-configuration"; export interface KubectlDiffReturns { diff?: string; errs: string; forbidden: boolean; clientFallback: boolean; } const diffEnv: Environment = os.platform() === "win32" ? { KUBECTL_EXTERNAL_DIFF: path.join(__dirname, "diff.cmd") } : {}; /** @internal */ export async function kubectlDiff(options: KubectlDiffOptions): Promise<KubectlDiffReturns> { const opts = { ...diffDefaults, ...options }; const { kubeconfig, manifest } = opts; return withTmpDir(async (tmpDir) => { const configPath = kubeconfig && await getKubeconfigPath(tmpDir, kubeconfig); const manifestLoc = path.join(tmpDir, "manifest.json"); await writeFile(manifestLoc, JSON.stringify(manifest)); const args = ["diff", "-f", manifestLoc]; let result: execa.ExecaError | execa.ExecaReturnValue<string> = await kubectl(args, { env: diffEnv, kubeconfig: configPath, printFailure: false, reject: false, }); const serverInternalErrorRegex = new RegExp("^Error from server \\(InternalError\\)"); if ((result.exitCode !== 0) && serverInternalErrorRegex.test(result.stderr)) { // Some k8s clusters, GKE included, do not support API-server dry-run for all resources, // which kubectl diff uses so fallback to using the old style client side diff algorithm that kubectl uses. result = await kubectl(["get", "-o", "json", "-f", manifestLoc], { kubeconfig: configPath, reject: false, }); if (result.exitCode === 0) { const srvManifest = JSON.parse(result.stdout); if (!srvManifest.annotations || !srvManifest.annotations[lastApplied]) { return { //FIXME(manishv) mimic kubectl diff output here diff: `No ${lastApplied} annotation, assuming diff`, errs: "", forbidden: false, clientFallback: true }; } const srvApplyManifestJSON = srvManifest.annotations[lastApplied]; const srvApplyManifest = JSON.parse(srvApplyManifestJSON); const strippedManifest = JSON.parse(JSON.stringify(manifest)); if (!ld.isEqual(strippedManifest, srvApplyManifest)) { return { diff: "Unknown diff", //FIXME(manishv) mimic kubectl diff output here errs: "", forbidden: false, clientFallback: true }; } else { return { errs: result.stderr, forbidden: false, clientFallback: true }; } } } if (result.exitCode === 0) { return { errs: result.stderr, forbidden: false, clientFallback: false }; } const forbiddenRegex = new RegExp(`^The ${manifest.kind} \"${manifest.metadata.name}\" is invalid: spec: Forbidden`); if (forbiddenRegex.test(result.stderr)) { return { errs: result.stderr, forbidden: true, clientFallback: false }; } if ((result.exitCode === 1) && (result.stderr.length === 0) && (result.stdout.startsWith("diff "))) { return { diff: result.stdout, errs: "", forbidden: false, clientFallback: false }; } throw result; //Should be ExecaError if result.exitCode was not zero }); } /** @internal */ export interface KubectlOpManifestOptions { /** kubeconfig as a Javascript object, or a path to a kubeconfig file */ kubeconfig?: Kubeconfig | string; dryRun?: boolean; manifest: Manifest; wait?: boolean; } const opManifestDefaults = { dryRun: false, wait: false }; export async function kubectlOpManifest(op: "create" | "apply" | "delete", options: KubectlOpManifestOptions) { const opts = { ...opManifestDefaults, ...options }; const { kubeconfig, manifest, dryRun } = opts; return withTmpDir(async (tmpDir) => { const configPath = kubeconfig && await getKubeconfigPath(tmpDir, kubeconfig); const manifestLoc = path.join(tmpDir, "manifest.json"); await writeFile(manifestLoc, JSON.stringify(manifest)); const args = [op, "-f", manifestLoc]; if (op !== "delete" && dryRun) args.push("--dry-run"); if (op === "delete" && dryRun) throw new Error("Cannot dry-run delete"); if (op !== "create") args.push(`--wait=${opts.wait}`); return kubectl(args, { kubeconfig: configPath }); }); } /** @internal */ export interface KubectlProxyOptions { kubeconfig?: Kubeconfig | string; } const proxyDefaults = {}; async function firstLine(stream: Readable): Promise<{ first: string, rest: readline.Interface }> { return new Promise((res, rej) => { const lines = readline.createInterface({ input: stream, crlfDelay: Infinity }); let done = false; lines.prependOnceListener("line", (text) => { if (!done) res({ first: text, rest: lines }); done = true; }); lines.prependOnceListener("error", (e) => { if (!done) rej(e); done = true; }); lines.prependOnceListener("close", () => { if (!done) rej(new Error("Stream closed before first line was complete")); done = true; }); }); } function extractHostPort(line: string): string { const match = /^Starting to serve on (.+)$/.exec(line); if (match === null) throw new Error("Cannot parse host line"); if (match[1] === undefined || match[1] === "") throw new Error("No host/port information found"); return match[1]; } export interface KubectlProxyInfo { url: string; child: execa.ExecaChildProcess<string>; kill: () => void; } /** @internal */ export async function kubectlProxy(options: KubectlProxyOptions): Promise<KubectlProxyInfo> { const opts = { ...proxyDefaults, ...options }; const kubeconfig = opts.kubeconfig; return withTmpDir(async (tmpDir) => { const configPath = kubeconfig && await getKubeconfigPath(tmpDir, kubeconfig); const kubectlPath = await getKubectl(); const args = []; if (configPath) args.push("--kubeconfig", configPath); args.push("proxy", "--port=0"); const child = execa(kubectlPath, args, { all: true }); const kill = () => child.kill(); let hostPort: string; try { const { first: proxyInfoStr, rest } = await firstLine(child.stdout); rest.on("line", () => { return; }); //Eat extra lines, just in case hostPort = extractHostPort(proxyInfoStr); } catch (e) { if (isExecaError(e)) { if (e.all) e.message = `${e.shortMessage}\n${e.all}`; } else { kill(); e.message = `Failed to extract proxy host from command: ${kubectlPath} ${args.join(" ")} ` + e.message; } throw e; } const url = `http://${hostPort}`; return { url, child, kill }; }); }
the_stack
// TODO(1): Get Typescript to have string-enum types as WebRtc is full of string // enums. // https://typescript.codeplex.com/discussions/549207 // TODO(2): get Typescript to have union types as WebRtc uses them. // https://typescript.codeplex.com/workitem/1364 interface RTCConfiguration { iceServers: RTCIceServer[]; } declare var RTCConfiguration: { prototype: RTCConfiguration; new (): RTCConfiguration; }; interface RTCIceServer { urls: string; credential?: string; } declare var RTCIceServer: { prototype: RTCIceServer; new (): RTCIceServer; }; // moz (Firefox) specific prefixes. interface mozRTCPeerConnection extends RTCPeerConnection { } declare var mozRTCPeerConnection: { prototype: mozRTCPeerConnection; new (settings: RTCPeerConnectionConfig, constraints?:RTCMediaConstraints): mozRTCPeerConnection; }; // webkit (Chrome) specific prefixes. interface webkitRTCPeerConnection extends RTCPeerConnection { } declare var webkitRTCPeerConnection: { prototype: webkitRTCPeerConnection; new (settings: RTCPeerConnectionConfig, constraints?:RTCMediaConstraints): webkitRTCPeerConnection; }; // For Chrome, look at the code here: // https://code.google.com/p/chromium/codesearch#chromium/src/third_party/libjingle/source/talk/app/webrtc/webrtcsession.cc&sq=package:chromium&dr=C&l=63 interface RTCOptionalMediaConstraint { // When true, will use DTLS/SCTP data channels DtlsSrtpKeyAgreement?: boolean; // When true will use Rtp-based data channels (depreicated) RtpDataChannels?: boolean; } // ks 12/20/12 - There's more here that doesn't seem to be documented very well yet. // http://www.w3.org/TR/2013/WD-webrtc-20130910/ interface RTCMediaConstraints { mandatory?: RTCMediaOfferConstraints; optional?: RTCOptionalMediaConstraint[] } interface RTCMediaOfferConstraints { offerToReceiveAudio: boolean; offerToReceiveVideo: boolean; } interface RTCSessionDescriptionInit { type: string; // RTCSdpType; See TODO(1) sdp: string; } interface RTCSessionDescription { type?: string; // RTCSdpType; See TODO(1) sdp?: string; } declare var RTCSessionDescription: { prototype: RTCSessionDescription; new (descriptionInitDict?: RTCSessionDescriptionInit): RTCSessionDescription; // TODO: Add serializer. // See: http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSdpType) }; interface webkitRTCSessionDescription extends RTCSessionDescription{ type?: string; sdp?: string; } declare var webkitRTCSessionDescription: { prototype: webkitRTCSessionDescription; new (descriptionInitDict?: RTCSessionDescriptionInit): webkitRTCSessionDescription; }; interface mozRTCSessionDescription extends RTCSessionDescription{ type?: string; sdp?: string; } declare var mozRTCSessionDescription: { prototype: mozRTCSessionDescription; new (descriptionInitDict?: RTCSessionDescriptionInit): mozRTCSessionDescription; }; interface RTCDataChannelInit { ordered ?: boolean; // messages must be sent in-order. maxPacketLifeTime ?: number; // unsigned short maxRetransmits ?: number; // unsigned short protocol ?: string; // default = '' negotiated ?: boolean; // default = false; id ?: number; // unsigned short } // TODO(1) declare enum RTCSdpType { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcsdptype 'offer', 'pranswer', 'answer' } interface RTCMessageEvent { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#event-datachannel-message // At present, this can be an: ArrayBuffer, a string, or a Blob. // See TODO(2) data: any; } // TODO(1) declare enum RTCDataChannelState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelState 'connecting', 'open', 'closing', 'closed' } interface RTCDataChannel extends EventTarget { label: string; reliable: boolean; readyState: string; // RTCDataChannelState; see TODO(1) bufferedAmount: number; binaryType: string; onopen: (event: Event) => void; onerror: (event: Event) => void; onclose: (event: Event) => void; onmessage: (event: RTCMessageEvent) => void; close(): void; send(data: string): void ; send(data: ArrayBuffer): void; send(data: ArrayBufferView): void; send(data: Blob): void; } declare var RTCDataChannel: { prototype: RTCDataChannel; new (): RTCDataChannel; }; interface RTCDataChannelEvent extends Event { channel: RTCDataChannel; } declare var RTCDataChannelEvent: { prototype: RTCDataChannelEvent; new (eventInitDict: RTCDataChannelEventInit): RTCDataChannelEvent; }; interface RTCIceCandidateEvent extends Event { candidate: RTCIceCandidate; } interface RTCMediaStreamEvent extends Event { stream: MediaStream; } interface EventInit { } interface RTCDataChannelEventInit extends EventInit { channel: RTCDataChannel; } interface RTCVoidCallback { (): void; } interface RTCSessionDescriptionCallback { (sdp: RTCSessionDescription): void; } interface RTCPeerConnectionErrorCallback { (errorInformation: DOMError): void; } // TODO(1) declare enum RTCIceGatheringState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#rtcicegatheringstate-enum 'new', 'gathering', 'complete' } // TODO(1) declare enum RTCIceConnectionState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCIceConnectionState 'new', 'checking', 'connected', 'completed', 'failed', 'disconnected', 'closed' } // TODO(1) declare enum RTCSignalingState { // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCSignalingState 'stable', 'have-local-offer', 'have-remote-offer', 'have-local-pranswer', 'have-remote-pranswer', 'closed' } // This is based on the current implementation of WebRtc in Chrome; the spec is // a little unclear on this. // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCStatsReport interface RTCStatsReport { stat(id: string): string; } interface RTCStatsCallback { (report: RTCStatsReport): void; } interface RTCPeerConnection { createOffer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: RTCMediaConstraints): void; createAnswer(successCallback: RTCSessionDescriptionCallback, failureCallback?: RTCPeerConnectionErrorCallback, constraints?: RTCMediaConstraints): void; setLocalDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; localDescription: RTCSessionDescription; setRemoteDescription(description: RTCSessionDescription, successCallback?: RTCVoidCallback, failureCallback?: RTCPeerConnectionErrorCallback): void; remoteDescription: RTCSessionDescription; signalingState: string; // RTCSignalingState; see TODO(1) updateIce(configuration?: RTCConfiguration, constraints?: RTCMediaConstraints): void; addIceCandidate(candidate:RTCIceCandidate, successCallback:() => void, failureCallback:RTCPeerConnectionErrorCallback): void; iceGatheringState: string; // RTCIceGatheringState; see TODO(1) iceConnectionState: string; // RTCIceConnectionState; see TODO(1) getLocalStreams(): MediaStream[]; getRemoteStreams(): MediaStream[]; createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; ondatachannel: (event: Event) => void; addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; removeStream(stream: MediaStream): void; close(): void; onnegotiationneeded: (event: Event) => void; onconnecting: (event: Event) => void; onopen: (event: Event) => void; onaddstream: (event: RTCMediaStreamEvent) => void; onremovestream: (event: RTCMediaStreamEvent) => void; onstatechange: (event: Event) => void; oniceconnectionstatechange: (event: Event) => void; onicecandidate: (event: RTCIceCandidateEvent) => void; onidentityresult: (event: Event) => void; onsignalingstatechange: (event: Event) => void; getStats: (successCallback: RTCStatsCallback, failureCallback: RTCPeerConnectionErrorCallback) => void; } declare var RTCPeerConnection: { prototype: RTCPeerConnection; new (configuration: RTCConfiguration, constraints?: RTCMediaConstraints): RTCPeerConnection; }; interface RTCIceCandidate { candidate?: string; sdpMid?: string; sdpMLineIndex?: number; } declare var RTCIceCandidate: { prototype: RTCIceCandidate; new (candidateInitDict?: RTCIceCandidate): RTCIceCandidate; }; interface webkitRTCIceCandidate extends RTCIceCandidate { candidate?: string; sdpMid?: string; sdpMLineIndex?: number; } declare var webkitRTCIceCandidate: { prototype: webkitRTCIceCandidate; new (candidateInitDict?: webkitRTCIceCandidate): webkitRTCIceCandidate; }; interface mozRTCIceCandidate extends RTCIceCandidate { candidate?: string; sdpMid?: string; sdpMLineIndex?: number; } declare var mozRTCIceCandidate: { prototype: mozRTCIceCandidate; new (candidateInitDict?: mozRTCIceCandidate): mozRTCIceCandidate; }; interface RTCIceCandidateInit { candidate: string; sdpMid: string; sdpMLineIndex: number; } declare var RTCIceCandidateInit:{ prototype: RTCIceCandidateInit; new (): RTCIceCandidateInit; }; interface PeerConnectionIceEvent { peer: RTCPeerConnection; candidate: RTCIceCandidate; } declare var PeerConnectionIceEvent: { prototype: PeerConnectionIceEvent; new (): PeerConnectionIceEvent; }; interface RTCPeerConnectionConfig { iceServers: RTCIceServer[]; } declare var RTCPeerConnectionConfig: { prototype: RTCPeerConnectionConfig; new (): RTCPeerConnectionConfig; }; interface Window{ RTCPeerConnection: RTCPeerConnection; webkitRTCPeerConnection: webkitRTCPeerConnection; mozRTCPeerConnection: mozRTCPeerConnection; RTCSessionDescription: RTCSessionDescription; webkitRTCSessionDescription: webkitRTCSessionDescription; mozRTCSessionDescription: mozRTCSessionDescription; RTCIceCandidate: RTCIceCandidate; webkitRTCIceCandidate: webkitRTCIceCandidate; mozRTCIceCandidate: mozRTCIceCandidate; }
the_stack
import '../setup' /* External Imports */ import { DB, newInMemoryDB } from '@pigi/core-db' import { keccak256, DefaultSignatureProvider } from '@pigi/core-utils' /* Internal Imports */ import { abiEncodeTransition, DefaultRollupBlockSubmitter, RollupBlock, RollupBlockSubmitter, } from '../../src' const getIntFromDB = async (db: DB, key: Buffer): Promise<number> => { return parseInt((await db.get(key)).toString(), 10) } const getLastQueuedFromDB = async (db: DB): Promise<number> => { return getIntFromDB(db, DefaultRollupBlockSubmitter.LAST_QUEUED_KEY) } const getLastSubmittedFromDB = async (db: DB): Promise<number> => { return getIntFromDB(db, DefaultRollupBlockSubmitter.LAST_SUBMITTED_KEY) } const getLastConfirmedFromDB = async (db: DB): Promise<number> => { return getIntFromDB(db, DefaultRollupBlockSubmitter.LAST_CONFIRMED_KEY) } const initQueuedSubmittedConfirmed = async ( db: DB, dummyContract: DummyContract, queued: number, submitted: number, confirmed: number, blocks: RollupBlock[] = [] ): Promise<RollupBlockSubmitter> => { if (queued > 0) { await db.put( DefaultRollupBlockSubmitter.LAST_QUEUED_KEY, Buffer.from(queued.toString(10)) ) } if (submitted > 0) { await db.put( DefaultRollupBlockSubmitter.LAST_SUBMITTED_KEY, Buffer.from(submitted.toString(10)) ) } if (confirmed > 0) { await db.put( DefaultRollupBlockSubmitter.LAST_CONFIRMED_KEY, Buffer.from(confirmed.toString(10)) ) } for (const block of blocks) { await db.put( DefaultRollupBlockSubmitter.getBlockKey(block.blockNumber), DefaultRollupBlockSubmitter.serializeRollupBlockForStorage(block) ) } const blockSubmitter: DefaultRollupBlockSubmitter = await DefaultRollupBlockSubmitter.create( db, // @ts-ignore dummyContract ) // queued and confirmed won't change blockSubmitter.getLastQueued().should.equal(queued) blockSubmitter.getLastConfirmed().should.equal(confirmed) let expectedSubmitted: number switch (submitted) { case queued: expectedSubmitted = queued break case confirmed: expectedSubmitted = submitted + 1 break default: expectedSubmitted = submitted } blockSubmitter.getLastSubmitted().should.equal(expectedSubmitted) if (expectedSubmitted !== submitted) { // Check that block was submitted dummyContract.blocksSubmitted.length.should.equal(1) dummyContract.blocksSubmitted[0][0].should.equal( abiEncodeTransition(blocks[0].transitions[0]) ) // Check that last submitted was persisted const lastSubmittedFromDB: number = await getLastSubmittedFromDB(db) lastSubmittedFromDB.should.equal(expectedSubmitted) } return blockSubmitter } describe('DefaultRollupBlockSubmitter', () => { let dummyContract: DummyContract let db: DB let rollupBlock: RollupBlock let rollupBlock2: RollupBlock beforeEach(async () => { dummyContract = new DummyContract() db = newInMemoryDB() rollupBlock = { blockNumber: 1, transitions: [ { stateRoot: keccak256( Buffer.from('some stuff to hash').toString('hex') ), senderSlotIndex: 0, recipientSlotIndex: 1, tokenType: 0, amount: 10, signature: await new DefaultSignatureProvider().sign('test'), }, ], } rollupBlock2 = { blockNumber: 2, transitions: [ { stateRoot: keccak256( Buffer.from('different stuff to hash').toString('hex') ), senderSlotIndex: 1, recipientSlotIndex: 0, tokenType: 1, amount: 100, signature: await new DefaultSignatureProvider().sign('test'), }, ], } }) describe('init()', () => { it('should init without error when DB empty', async () => { await initQueuedSubmittedConfirmed(db, dummyContract, 0, 0, 0) }) it('should init without error when block one submitted but not confirmed', async () => { await initQueuedSubmittedConfirmed(db, dummyContract, 1, 1, 0, [ rollupBlock, ]) }) it('should init without error when block 2 submitted but not confirmed', async () => { await initQueuedSubmittedConfirmed(db, dummyContract, 2, 2, 0, [ rollupBlock, rollupBlock2, ]) }) it('should try to submit when one queued but not submitted', async () => { await initQueuedSubmittedConfirmed(db, dummyContract, 1, 0, 0, [ rollupBlock, ]) }) it('should only try to submit one when two queued but not submitted', async () => { await initQueuedSubmittedConfirmed(db, dummyContract, 2, 0, 0, [ rollupBlock, rollupBlock2, ]) }) }) describe('submitBlock()', () => { it('should submit new block with no previous blocks', async () => { // @ts-ignore const blockSubmitter: RollupBlockSubmitter = await DefaultRollupBlockSubmitter.create( db, // @ts-ignore dummyContract ) await blockSubmitter.submitBlock(rollupBlock) dummyContract.blocksSubmitted.length.should.equal(1) dummyContract.blocksSubmitted[0][0].should.equal( abiEncodeTransition(rollupBlock.transitions[0]) ) blockSubmitter.getLastConfirmed().should.equal(0) blockSubmitter.getLastSubmitted().should.equal(1) blockSubmitter.getLastQueued().should.equal(1) const lastQueuedFromDB: number = await getLastQueuedFromDB(db) lastQueuedFromDB.should.equal(1) const lastSubmittedFromDB: number = await getLastSubmittedFromDB(db) lastSubmittedFromDB.should.equal(1) }) it('should submit new block with one previous block', async () => { const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 1, 1, 1, [rollupBlock] ) await blockSubmitter.submitBlock(rollupBlock2) dummyContract.blocksSubmitted.length.should.equal(1) dummyContract.blocksSubmitted[0][0].should.equal( abiEncodeTransition(rollupBlock2.transitions[0]) ) blockSubmitter.getLastConfirmed().should.equal(1) blockSubmitter.getLastSubmitted().should.equal(2) blockSubmitter.getLastQueued().should.equal(2) const lastQueuedFromDB: number = await getLastQueuedFromDB(db) lastQueuedFromDB.should.equal(2) const lastSubmittedFromDB: number = await getLastSubmittedFromDB(db) lastSubmittedFromDB.should.equal(2) }) it('should ignore old block', async () => { const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 1, 1, 1, [rollupBlock] ) await blockSubmitter.submitBlock(rollupBlock) dummyContract.blocksSubmitted.length.should.equal(0) blockSubmitter.getLastConfirmed().should.equal(1) blockSubmitter.getLastSubmitted().should.equal(1) blockSubmitter.getLastQueued().should.equal(1) }) it('should queue block when there is one pending', async () => { const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 1, 1, 0, [rollupBlock] ) dummyContract.blocksSubmitted.length = 0 await blockSubmitter.submitBlock(rollupBlock2) dummyContract.blocksSubmitted.length.should.equal(0) blockSubmitter.getLastConfirmed().should.equal(0) blockSubmitter.getLastSubmitted().should.equal(1) blockSubmitter.getLastQueued().should.equal(2) const lastQueuedFromDB: number = await getLastQueuedFromDB(db) lastQueuedFromDB.should.equal(2) }) }) describe('handleNewRollupBlock()', () => { it('should do nothing when there are no pending blocks', async () => { // @ts-ignore const blockSubmitter: RollupBlockSubmitter = await DefaultRollupBlockSubmitter.create( db, // @ts-ignore dummyContract ) await blockSubmitter.handleNewRollupBlock(1) blockSubmitter.getLastConfirmed().should.equal(0) blockSubmitter.getLastSubmitted().should.equal(0) blockSubmitter.getLastQueued().should.equal(0) }) it('should confirm pending with empty queue', async () => { const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 1, 1, 0, [rollupBlock] ) await blockSubmitter.handleNewRollupBlock(1) blockSubmitter.getLastConfirmed().should.equal(1) blockSubmitter.getLastSubmitted().should.equal(1) blockSubmitter.getLastQueued().should.equal(1) const lastConfirmedFromDB: number = await getLastConfirmedFromDB(db) lastConfirmedFromDB.should.equal(1) }) it('should confirm pending with one in queue', async () => { const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 2, 1, 0, [rollupBlock, rollupBlock2] ) await blockSubmitter.handleNewRollupBlock(1) dummyContract.blocksSubmitted.length.should.equal(1) dummyContract.blocksSubmitted[0][0].should.equal( abiEncodeTransition(rollupBlock2.transitions[0]) ) blockSubmitter.getLastConfirmed().should.equal(1) blockSubmitter.getLastSubmitted().should.equal(2) blockSubmitter.getLastQueued().should.equal(2) const lastConfirmedFromDB: number = await getLastConfirmedFromDB(db) lastConfirmedFromDB.should.equal(1) const lastSubmittedFromDB: number = await getLastSubmittedFromDB(db) lastSubmittedFromDB.should.equal(2) }) it('should confirm pending with two in queue', async () => { const rollupBlock3: RollupBlock = { blockNumber: 3, transitions: [ { stateRoot: keccak256( Buffer.from('much different stuff to hash').toString('hex') ), senderSlotIndex: 1, recipientSlotIndex: 0, tokenType: 1, amount: 100, signature: await new DefaultSignatureProvider().sign('test'), }, ], } const blockSubmitter = await initQueuedSubmittedConfirmed( db, dummyContract, 3, 1, 0, [rollupBlock, rollupBlock2, rollupBlock3] ) await blockSubmitter.handleNewRollupBlock(1) dummyContract.blocksSubmitted.length.should.equal(1) dummyContract.blocksSubmitted[0][0].should.equal( abiEncodeTransition(rollupBlock2.transitions[0]) ) blockSubmitter.getLastConfirmed().should.equal(1) blockSubmitter.getLastSubmitted().should.equal(2) blockSubmitter.getLastQueued().should.equal(3) const lastConfirmedFromDB: number = await getLastConfirmedFromDB(db) lastConfirmedFromDB.should.equal(1) const lastSubmittedFromDB: number = await getLastSubmittedFromDB(db) lastSubmittedFromDB.should.equal(2) }) }) }) class DummyContract { public blocksSubmitted: string[] = [] public async submitBlock(abiEncodedLeaves: string): Promise<void> { this.blocksSubmitted.push(abiEncodedLeaves) } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [mgn](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsapplicationmigrationservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Mgn extends PolicyStatement { public servicePrefix = 'mgn'; /** * Statement provider for service [mgn](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsapplicationmigrationservice.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 create volume snapshot group * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toBatchCreateVolumeSnapshotGroupForMgn() { return this.to('BatchCreateVolumeSnapshotGroupForMgn'); } /** * Grants permission to batch delete snapshot request * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toBatchDeleteSnapshotRequestForMgn() { return this.to('BatchDeleteSnapshotRequestForMgn'); } /** * Grants permission to change source server life cycle state * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_ChangeServerLifeCycleState.html */ public toChangeServerLifeCycleState() { return this.to('ChangeServerLifeCycleState'); } /** * Grants permission to create replication configuration template * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_CreateReplicationConfigurationTemplate.html */ public toCreateReplicationConfigurationTemplate() { return this.to('CreateReplicationConfigurationTemplate'); } /** * Grants permission to delete job * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DeleteJob.html */ public toDeleteJob() { return this.to('DeleteJob'); } /** * Grants permission to delete replication configuration template * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DeleteReplicationConfigurationTemplate.html */ public toDeleteReplicationConfigurationTemplate() { return this.to('DeleteReplicationConfigurationTemplate'); } /** * Grants permission to delete source server * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DeleteSourceServer.html */ public toDeleteSourceServer() { return this.to('DeleteSourceServer'); } /** * Grants permission to describe job log items * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DescribeJobLogItems.html */ public toDescribeJobLogItems() { return this.to('DescribeJobLogItems'); } /** * Grants permission to describe jobs * * Access Level: List * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DescribeJobs.html */ public toDescribeJobs() { return this.to('DescribeJobs'); } /** * Grants permission to describe replication configuration template * * Access Level: List * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DescribeReplicationConfigurationTemplates.html */ public toDescribeReplicationConfigurationTemplates() { return this.to('DescribeReplicationConfigurationTemplates'); } /** * Grants permission to describe replication server associations * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toDescribeReplicationServerAssociationsForMgn() { return this.to('DescribeReplicationServerAssociationsForMgn'); } /** * Grants permission to describe snapshots requests * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toDescribeSnapshotRequestsForMgn() { return this.to('DescribeSnapshotRequestsForMgn'); } /** * Grants permission to describe source servers * * Access Level: List * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DescribeSourceServers.html */ public toDescribeSourceServers() { return this.to('DescribeSourceServers'); } /** * Grants permission to disconnect source server from service * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_DisconnectFromService.html */ public toDisconnectFromService() { return this.to('DisconnectFromService'); } /** * Grants permission to finalize cutover * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_FinalizeCutover.html */ public toFinalizeCutover() { return this.to('FinalizeCutover'); } /** * Grants permission to get agent command * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentCommandForMgn() { return this.to('GetAgentCommandForMgn'); } /** * Grants permission to get agent confirmed resume info * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentConfirmedResumeInfoForMgn() { return this.to('GetAgentConfirmedResumeInfoForMgn'); } /** * Grants permission to get agent installation assets * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentInstallationAssetsForMgn() { return this.to('GetAgentInstallationAssetsForMgn'); } /** * Grants permission to get agent replication info * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentReplicationInfoForMgn() { return this.to('GetAgentReplicationInfoForMgn'); } /** * Grants permission to get agent runtime configuration * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentRuntimeConfigurationForMgn() { return this.to('GetAgentRuntimeConfigurationForMgn'); } /** * Grants permission to get agent snapshots credits * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetAgentSnapshotCreditsForMgn() { return this.to('GetAgentSnapshotCreditsForMgn'); } /** * Grants permission to get channel commands * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toGetChannelCommandsForMgn() { return this.to('GetChannelCommandsForMgn'); } /** * Grants permission to get launch configuration * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_GetLaunchConfiguration.html */ public toGetLaunchConfiguration() { return this.to('GetLaunchConfiguration'); } /** * Grants permission to get replication configuration * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_GetReplicationConfiguration.html */ public toGetReplicationConfiguration() { return this.to('GetReplicationConfiguration'); } /** * Grants permission to initialize service * * Access Level: Write * * Dependent actions: * - iam:AddRoleToInstanceProfile * - iam:CreateInstanceProfile * - iam:CreateServiceLinkedRole * - iam:GetInstanceProfile * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_InitializeService.html */ public toInitializeService() { return this.to('InitializeService'); } /** * Grants permission to list tags for a resource * * Access Level: Read * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to mark source server as archived * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_MarkAsArchived.html */ public toMarkAsArchived() { return this.to('MarkAsArchived'); } /** * Grants permission to notify agent authentication * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toNotifyAgentAuthenticationForMgn() { return this.to('NotifyAgentAuthenticationForMgn'); } /** * Grants permission to notify agent is connected * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toNotifyAgentConnectedForMgn() { return this.to('NotifyAgentConnectedForMgn'); } /** * Grants permission to notify agent is disconnected * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toNotifyAgentDisconnectedForMgn() { return this.to('NotifyAgentDisconnectedForMgn'); } /** * Grants permission to notify agent replication progress * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toNotifyAgentReplicationProgressForMgn() { return this.to('NotifyAgentReplicationProgressForMgn'); } /** * Grants permission to register agent * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toRegisterAgentForMgn() { return this.to('RegisterAgentForMgn'); } /** * Grants permission to retry replication * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_RetryDataReplication.html */ public toRetryDataReplication() { return this.to('RetryDataReplication'); } /** * Grants permission to send agent logs * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toSendAgentLogsForMgn() { return this.to('SendAgentLogsForMgn'); } /** * Grants permission to send agent metrics * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toSendAgentMetricsForMgn() { return this.to('SendAgentMetricsForMgn'); } /** * Grants permission to send channel command result * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toSendChannelCommandResultForMgn() { return this.to('SendChannelCommandResultForMgn'); } /** * Grants permission to send client logs * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toSendClientLogsForMgn() { return this.to('SendClientLogsForMgn'); } /** * Grants permission to send client metrics * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toSendClientMetricsForMgn() { return this.to('SendClientMetricsForMgn'); } /** * Grants permission to start cutover * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:AttachVolume * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:CreateLaunchTemplate * - ec2:CreateLaunchTemplateVersion * - ec2:CreateSecurityGroup * - ec2:CreateSnapshot * - ec2:CreateTags * - ec2:CreateVolume * - ec2:DeleteLaunchTemplateVersions * - ec2:DeleteSnapshot * - ec2:DeleteVolume * - ec2:DescribeAccountAttributes * - ec2:DescribeAvailabilityZones * - ec2:DescribeImages * - ec2:DescribeInstanceAttribute * - ec2:DescribeInstanceStatus * - ec2:DescribeInstanceTypes * - ec2:DescribeInstances * - ec2:DescribeLaunchTemplateVersions * - ec2:DescribeLaunchTemplates * - ec2:DescribeSecurityGroups * - ec2:DescribeSnapshots * - ec2:DescribeSubnets * - ec2:DescribeVolumes * - ec2:DetachVolume * - ec2:ModifyInstanceAttribute * - ec2:ModifyLaunchTemplate * - ec2:ReportInstanceStatus * - ec2:RevokeSecurityGroupEgress * - ec2:RunInstances * - ec2:StartInstances * - ec2:StopInstances * - ec2:TerminateInstances * - iam:PassRole * - mgn:ListTagsForResource * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_StartCutover.html */ public toStartCutover() { return this.to('StartCutover'); } /** * Grants permission to start test * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:AttachVolume * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:CreateLaunchTemplate * - ec2:CreateLaunchTemplateVersion * - ec2:CreateSecurityGroup * - ec2:CreateSnapshot * - ec2:CreateTags * - ec2:CreateVolume * - ec2:DeleteLaunchTemplateVersions * - ec2:DeleteSnapshot * - ec2:DeleteVolume * - ec2:DescribeAccountAttributes * - ec2:DescribeAvailabilityZones * - ec2:DescribeImages * - ec2:DescribeInstanceAttribute * - ec2:DescribeInstanceStatus * - ec2:DescribeInstanceTypes * - ec2:DescribeInstances * - ec2:DescribeLaunchTemplateVersions * - ec2:DescribeLaunchTemplates * - ec2:DescribeSecurityGroups * - ec2:DescribeSnapshots * - ec2:DescribeSubnets * - ec2:DescribeVolumes * - ec2:DetachVolume * - ec2:ModifyInstanceAttribute * - ec2:ModifyLaunchTemplate * - ec2:ReportInstanceStatus * - ec2:RevokeSecurityGroupEgress * - ec2:RunInstances * - ec2:StartInstances * - ec2:StopInstances * - ec2:TerminateInstances * - iam:PassRole * - mgn:ListTagsForResource * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_StartTest.html */ public toStartTest() { return this.to('StartTest'); } /** * Grants permission to assign a resource tag * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to terminate target instances * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:DeleteVolume * - ec2:DescribeInstances * - ec2:DescribeVolumes * - ec2:TerminateInstances * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_TerminateTargetInstances.html */ public toTerminateTargetInstances() { return this.to('TerminateTargetInstances'); } /** * Grants permission to untag a resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update agent backlog * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toUpdateAgentBacklogForMgn() { return this.to('UpdateAgentBacklogForMgn'); } /** * Grants permission to update agent conversion info * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toUpdateAgentConversionInfoForMgn() { return this.to('UpdateAgentConversionInfoForMgn'); } /** * Grants permission to update agent replication info * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toUpdateAgentReplicationInfoForMgn() { return this.to('UpdateAgentReplicationInfoForMgn'); } /** * Grants permission to update agent replication process state * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toUpdateAgentReplicationProcessStateForMgn() { return this.to('UpdateAgentReplicationProcessStateForMgn'); } /** * Grants permission to update agent source properties * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/ug/mgn-apis.html */ public toUpdateAgentSourcePropertiesForMgn() { return this.to('UpdateAgentSourcePropertiesForMgn'); } /** * Grants permission to update launch configuration * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_UpdateLaunchConfiguration.html */ public toUpdateLaunchConfiguration() { return this.to('UpdateLaunchConfiguration'); } /** * Grants permission to update replication configuration * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_UpdateReplicationConfiguration.html */ public toUpdateReplicationConfiguration() { return this.to('UpdateReplicationConfiguration'); } /** * Grants permission to update replication configuration template * * Access Level: Write * * https://docs.aws.amazon.com/mgn/latest/APIReference/API_UpdateReplicationConfigurationTemplate.html */ public toUpdateReplicationConfigurationTemplate() { return this.to('UpdateReplicationConfigurationTemplate'); } protected accessLevelList: AccessLevelList = { "Write": [ "BatchCreateVolumeSnapshotGroupForMgn", "BatchDeleteSnapshotRequestForMgn", "ChangeServerLifeCycleState", "CreateReplicationConfigurationTemplate", "DeleteJob", "DeleteReplicationConfigurationTemplate", "DeleteSourceServer", "DisconnectFromService", "FinalizeCutover", "InitializeService", "MarkAsArchived", "NotifyAgentAuthenticationForMgn", "NotifyAgentConnectedForMgn", "NotifyAgentDisconnectedForMgn", "NotifyAgentReplicationProgressForMgn", "RegisterAgentForMgn", "RetryDataReplication", "SendAgentLogsForMgn", "SendAgentMetricsForMgn", "SendChannelCommandResultForMgn", "SendClientLogsForMgn", "SendClientMetricsForMgn", "StartCutover", "StartTest", "TerminateTargetInstances", "UpdateAgentBacklogForMgn", "UpdateAgentConversionInfoForMgn", "UpdateAgentReplicationInfoForMgn", "UpdateAgentReplicationProcessStateForMgn", "UpdateAgentSourcePropertiesForMgn", "UpdateLaunchConfiguration", "UpdateReplicationConfiguration", "UpdateReplicationConfigurationTemplate" ], "Read": [ "DescribeJobLogItems", "DescribeReplicationServerAssociationsForMgn", "DescribeSnapshotRequestsForMgn", "GetAgentCommandForMgn", "GetAgentConfirmedResumeInfoForMgn", "GetAgentInstallationAssetsForMgn", "GetAgentReplicationInfoForMgn", "GetAgentRuntimeConfigurationForMgn", "GetAgentSnapshotCreditsForMgn", "GetChannelCommandsForMgn", "GetLaunchConfiguration", "GetReplicationConfiguration", "ListTagsForResource" ], "List": [ "DescribeJobs", "DescribeReplicationConfigurationTemplates", "DescribeSourceServers" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type JobResource to the statement * * https://docs.aws.amazon.com/mgn/latest/ug/launching-target-servers.html * * @param jobID - Identifier for the jobID. * @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 onJobResource(jobID: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mgn:${Region}:${Account}:job/${JobID}'; arn = arn.replace('${JobID}', jobID); 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 ReplicationConfigurationTemplateResource to the statement * * https://docs.aws.amazon.com/mgn/latest/ug/replication-settings-template.html * * @param replicationConfigurationTemplateID - Identifier for the replicationConfigurationTemplateID. * @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 onReplicationConfigurationTemplateResource(replicationConfigurationTemplateID: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mgn:${Region}:${Account}:replication-configuration-template/${ReplicationConfigurationTemplateID}'; arn = arn.replace('${ReplicationConfigurationTemplateID}', replicationConfigurationTemplateID); 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 SourceServerResource to the statement * * https://docs.aws.amazon.com/mgn/latest/ug/source-servers.html * * @param sourceServerID - Identifier for the sourceServerID. * @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 onSourceServerResource(sourceServerID: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:mgn:${Region}:${Account}:source-server/${SourceServerID}'; arn = arn.replace('${SourceServerID}', sourceServerID); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import * as assert from 'assert'; import * as path from 'path'; import * as mockery from 'mockery'; import * as ttm from 'azure-pipelines-task-lib/mock-test'; class MockedTask { private _proxyUrl: string; private _proxyUsername: string; private _proxyPassword: string; private _proxyBypass: string; private _secret: string; public debug(message: string) {} public loc(message: string): string { return message; } public setMockedValues(proxyUrl?: string, proxyUsername?: string, proxyPassword?: string, proxyBypass?: string) { this._proxyUrl = proxyUrl; this._proxyUsername = proxyUsername; this._proxyPassword = proxyPassword; this._proxyBypass = proxyBypass; this._secret = ''; } public getVariable(name: string) { switch (name.toLowerCase()) { case "agent.proxyurl": return this._proxyUrl; case "agent.proxyusername": return this._proxyUsername; case "agent.proxypassword": return this._proxyPassword; case "agent.proxybypasslist": return this._proxyBypass; case "task.displayname": return "Npm Test" default: return undefined; } } public setSecret(secret: string) { this._secret = secret; } public getSecret(): string { return this._secret; } } describe('Npm Toolrunner', function () { var mockedTask: MockedTask = new MockedTask(); var mockedProxy: string = "http://proxy/"; var mockedUsername: string = "mockedUsername"; var mockedPassword: string = "mockedPassword#"; var e = mockery.registerMock("azure-pipelines-task-lib/task", mockedTask); beforeEach(() => { mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false }); }); afterEach(() => { mockery.disable(); }); it("No HTTP_PROXY", (done: MochaDone) => { mockedTask.setMockedValues(); let npmToolRunner = require("../npmtoolrunner"); let httpProxy: string = npmToolRunner.NpmToolRunner._getProxyFromEnvironment(); assert.strictEqual(httpProxy, undefined); done(); }); it("gets proxy without auth", (done: MochaDone) => { mockedTask.setMockedValues(mockedProxy); let npmToolRunner = require("../npmtoolrunner"); let httpProxy: string = npmToolRunner.NpmToolRunner._getProxyFromEnvironment(); assert.strictEqual(httpProxy, mockedProxy); done(); }); it("registers the proxy uri with a password as a secret", (done: MochaDone) => { mockedTask.setMockedValues(mockedProxy, mockedUsername, mockedPassword); let npmToolRunner = require("../npmtoolrunner"); let httpProxy: string = npmToolRunner.NpmToolRunner._getProxyFromEnvironment(); let expected = `http://${mockedUsername}:${encodeURIComponent(mockedPassword)}@proxy/`; assert.strictEqual(httpProxy, expected); assert.strictEqual(mockedTask.getSecret(), expected); done(); }); }); describe('Npm Task', function () { this.timeout(6000); before(() => { mockery.disable(); // needed to ensure that we can mock vsts-task-lib/task mockery.enable({ useCleanCache: true, warnOnUnregistered: false } as mockery.MockeryEnableArgs); }); after(() => { mockery.disable(); }); beforeEach(() => { mockery.resetCache(); }); afterEach(() => { mockery.deregisterAll(); }); // npm failure dumps log it('npm failure dumps debug log from npm cache', (done: MochaDone) => { const debugLog = 'NPM_DEBUG_LOG'; let tp = path.join(__dirname, 'npm-failureDumpsLog-cacheDir.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert(tr.failed, 'task should have failed'); assert(tr.stdOutContained(debugLog)); done(); }); it('npm failure dumps debug log from working directory', (done: MochaDone) => { this.timeout(3000); const debugLog = 'NPM_DEBUG_LOG'; let tp = path.join(__dirname, 'npm-failureDumpsLog-workingDir.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert(tr.failed, 'task should have failed'); assert(tr.stdOutContained(debugLog)); done(); }); // custom it('custom command succeeds with single service endpoint', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'custom-singleEndpoint.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert(tr.stdOutContained('npm custom successful'), 'npm custom command should have run'); assert(tr.stdOutContained('http://example.com/1/'), 'debug output should have contained endpoint'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it('custom command should return npm version', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'custom-version.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdOutContained('; debug cli configs'), 'should have debug npm config output'); assert(tr.stdOutContained('; cli configs') === false, 'should not have regular npm config output'); done(); }); // show config it('should execute \'npm config list\' without debug switch', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'config-noDebug.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.succeeded, 'task should have succeeded'); assert(tr.stdOutContained('; cli configs'), 'should have regular npm config output'); assert(tr.stdOutContained('; debug cli configs') === false, 'should not have debug npm config output'); done(); }); // install command it('should fail when npm fails', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'install-npmFailure.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert(tr.failed, 'task should have failed'); done(); }); it ('install using local feed', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'install-feed.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm install successful'), 'npm should have installed the package'); assert(tr.stdOutContained('OverridingProjectNpmrc'), 'install from feed shoud override project .npmrc'); assert(tr.stdOutContained('RestoringProjectNpmrc'), 'install from .npmrc shoud restore project .npmrc'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it ('install using local project-scoped feed', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'install-project-scoped-feed.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm install successful'), 'npm should have installed the package'); assert(tr.stdOutContained('OverridingProjectNpmrc'), 'install from feed shoud override project .npmrc'); assert(tr.stdOutContained('RestoringProjectNpmrc'), 'install from .npmrc shoud restore project .npmrc'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it ('install using npmrc', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'install-npmrc.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm install successful'), 'npm should have installed the package'); assert(!tr.stdOutContained('OverridingProjectNpmrc'), 'install from .npmrc shoud not override project .npmrc'); assert(!tr.stdOutContained('RestoringProjectNpmrc'), 'install from .npmrc shoud not restore project .npmrc'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it('install using multiple endpoints', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'install-multipleEndpoints.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert(tr.stdOutContained('npm install successful'), 'npm should have installed the package'); assert(tr.stdOutContained('http://example.com/1/'), 'debug output should have contained endpoint'); assert(tr.stdOutContained('http://example.com/2/'), 'debug output should have contained endpoint'); assert(tr.succeeded, 'task should have succeeded'); done(); }); // publish it ('publish using feed', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'publish-feed.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm publish successful'), 'npm should have published the package'); assert(tr.stdOutContained('OverridingProjectNpmrc'), 'publish should always ooverrideverride project .npmrc'); assert(tr.stdOutContained('RestoringProjectNpmrc'), 'publish should always restore project .npmrc'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it ('publish using project-scoped feed', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'publish-project-scoped-feed.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm publish successful'), 'npm should have published the package'); assert(tr.stdOutContained('OverridingProjectNpmrc'), 'publish should always ooverrideverride project .npmrc'); assert(tr.stdOutContained('RestoringProjectNpmrc'), 'publish should always restore project .npmrc'); assert(tr.succeeded, 'task should have succeeded'); done(); }); it ('publish using external registry', (done: MochaDone) => { this.timeout(1000); let tp = path.join(__dirname, 'publish-external.js'); let tr = new ttm.MockTestRunner(tp); tr.run(); assert.equal(tr.invokedToolCount, 3, 'task should have run npm'); assert(tr.stdOutContained('npm publish successful'), 'npm should have published the package'); assert(tr.succeeded, 'task should have succeeded'); done(); }); });
the_stack
import { ActivityMessage } from './common/messages/activity-message'; import { AuthMessage } from './common/messages/auth-message'; import { ErrorMessage } from './common/messages/error-message'; import { Message } from './common/messages/message'; import { MessageType } from './common/messages/message-type'; import { OpenOnRemoteDeviceMessage } from './common/messages/open-on-remote-device-message'; // Scopes required for this extension // See FAQ.md for more information. const scopes = ['UserActivity.ReadWrite.CreatedByApp', 'Device.Read', 'Device.Command', 'offline_access']; // Auth variables let accessToken: string; let refreshToken: string; let clientId: string; // Browser resources let browserName: string; let browserIcon: string; // Used to cache the users devices (since loading devices can take a long time) let userDevices: any; // Redirect url for auth login let redirectURL: string; // Client branding if (navigator.userAgent.includes('OPR/')) { browserName = 'Opera'; browserIcon = 'https://timeline.dominicmaas.co.nz/assets/browsers/opera-128.png'; } else if (navigator.userAgent.includes('Vivaldi')) { browserName = 'Vivaldi'; browserIcon = 'https://timeline.dominicmaas.co.nz/assets/browsers/vivaldi-32.png'; } else if (navigator.userAgent.includes('Chrome')) { browserName = 'Google Chrome'; browserIcon = 'https://timeline.dominicmaas.co.nz/assets/browsers/chrome-32.png'; } else if (navigator.userAgent.includes('Firefox')) { browserName = 'Firefox'; browserIcon = 'https://timeline.dominicmaas.co.nz/assets/browsers/firefox.png'; } // Log the browser name console.debug("Selected Browser: " + browserName); // Client Id if (navigator.userAgent.includes('Edge') || navigator.userAgent.includes('OPR/')) { // Microsoft Edge or Opera clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; console.debug('[Auth Setup] Using new auth based system.'); } else if (navigator.userAgent.includes('Firefox') && (navigator.userAgent.includes('Mobile') || navigator.userAgent.includes('Tablet'))) { // Firefox for phones and tablets clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; console.debug('[Auth Setup] Using new auth based system.'); } else if (navigator.userAgent.includes('Firefox')) { // Mozilla Add-Ons Catalog – (Firefox, Tor Browser) clientId = '6a421ae0-f2b1-4cf9-84e0-857dc0a4c9a3'; redirectURL = 'https://5bed674f74ec59875d4860fbe854e945b81b4dac.extensions.allizom.org/'; console.debug('[Auth Setup] Using legacy Firefox auth based system.'); } else if (navigator.userAgent.includes('Chrome')) { // Chrome Web Store – (Google Chrome, Chromium, Vivaldi, others) clientId = '70c5f06f-cef4-4541-a705-1adeea3fa58f'; redirectURL = 'https://meokcjmjkobffcgldbjjklmaaediikdj.chromiumapp.org/'; console.debug('[Auth Setup] Using legacy Chrome auth based system.'); } else { // Use the new auth system clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; console.debug('[Auth Setup] Using new auth based system.'); } // Get stored tokens chrome.storage.local.get(['access_token', 'refresh_token', 'new_login'], (data) => { // Get the access token (may be null if not logged in) if (data.access_token !== null) { accessToken = data.access_token; } // Get the refresh token (may be null if not logged in) if (data.refresh_token !== null) { refreshToken = data.refresh_token; } // If the user has not logged in before, set them up to use the fallback auth (now primary) // auth system or if the user has logged in before with the new system. if (accessToken === undefined || data.new_login === true) { clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; console.debug('[Auth Setup] Change to use new auth based system (either no access token, or logged in with the new system).'); } // This is a weird place to put this code, but it needs to run after the access // token has been loaded from storage. if (accessToken !== undefined) { getRemoteDevicesAsync().then((devices) => { userDevices = devices; }); } }); /** * Submit collected activity data to Microsoft * @param webActivity The activity to post * @param secondAttempt If this is the second attempt at posting the activity */ async function sendActivityAsync(webActivity: ActivityMessage, secondAttempt: boolean = false): Promise<void> { // Don't run if the user has not logged in if (!accessToken) { console.error('Unauthorized, no auth token set.'); return; } // Get the current date time and time zone const date = new Date().toISOString(); // Encode the url with base64, then make url friendly const activityId = window.btoa(webActivity.Description).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, ''); // Create the microsoft graph activity url const url = `https://graph.microsoft.com/v1.0/me/activities/${activityId}`; // Get icon const icon = webActivity.IconImage === '' ? browserIcon : webActivity.IconImage; // Build the data const data = JSON.stringify({ activationUrl: webActivity.Description, activitySourceHost: webActivity.OriginUrl, appActivityId: activityId, appDisplayName: browserName, fallbackUrl: webActivity.Description, historyItems: [{ activeDurationSeconds: 30, startedDateTime: date }], visualElements: { attribution: { addImageQuery: false, alternateText: webActivity.OriginUrl, iconUrl: icon }, content: { $schema: 'http://adaptivecards.io/schemas/adaptive-card.json', backgroundImage: webActivity.BackgroundImage, body: [{ items: [{ maxLines: 3, size: 'large', text: webActivity.Title, type: 'TextBlock', weight: 'bolder', wrap: true, }, { maxLines: 3, size: 'default', text: webActivity.Description, type: 'TextBlock', wrap: true }], type: 'Container', }], type: 'AdaptiveCard' }, description: webActivity.Description, displayText: webActivity.Title, } }); // Call the url and get the response const response = await fetch(url, { body: data, cache: 'no-cache', headers: { 'authorization': `Bearer ${accessToken}`, 'content-type': 'application/json', }, method: 'PUT' }); // If we get a 401 in return, we need to refresh the token if (response.status === 401) { console.debug("Returned 401, refreshing access token..."); // Attempt to refresh the token const refreshStatus = await refreshTokenAsync(); // If the refresh is successful and this is our first try, // call the method again if (refreshStatus && !secondAttempt) { return await sendActivityAsync(webActivity, true); } else { console.error("Could not post activity to Windows Timeline: " + webActivity); return; } } const body = await response.json(); console.debug(body); } // Open the Microsoft account login dialog, let the user login, // grab the token and then store it for later use. /** * Login the user into their Microsoft Account. */ function login() { // A little messy, but when logging in, force the user to use the new auth system clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; // Build the request url let authURL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'; authURL += `?client_id=${clientId}`; authURL += `&response_type=code`; authURL += `&response_mode=query`; authURL += `&redirect_uri=${encodeURIComponent(redirectURL)}`; authURL += `&scope=${encodeURIComponent(scopes.join(' '))}`; // The new auth system just opens a new tab for the user to login // Is more likely to work compared to the old system. Since login only // supports the new system, all old code has been removed. if (typeof browser === 'undefined' || !browser) { // Open the URL in a new tab chrome.tabs.create({ url: authURL }); } else { // Open the URL in a new tab browser.tabs.create({ url: authURL }); } } /** * Logout the user from their Microsoft Account and delete any cached resources. */ function logout() { // Remove the stored values chrome.storage.local.remove('preferred_username'); chrome.storage.local.remove('access_token'); // Update the local variables accessToken = undefined; refreshToken = undefined; // The user has logged out, so we can now use the new auth system (if not already) clientId = '3e8214c9-265d-42b6-aa93-bdd810fda5e6'; redirectURL = 'https://timeline.dominicmaas.co.nz/auth-callback/index.html'; console.debug('[Auth Setup] Change to use new auth based system.'); } /** * Callback for the Login method. Extracts the oauth code from the * redirect url, calls the azure function to get both an access and * refresh token. * @param redirectUrl Url containing the oauth code */ async function validateLoginAsync(redirectUrl: string) { // If using fallback, we need to close the window (as we cannot // do it in the script) // Close the tab as it cannot be closed in the window chrome.tabs.query({ url: redirectUrl }, (tabs) => { chrome.tabs.remove(tabs[0].id); }); // Get the data from the redirect url const data = redirectUrl.split('?')[1]; // Split the data into pairs const dataArray = data.split('&'); // Object that will store the key value pairs const parameters = { code: null, error: null, error_description: null }; // Store the data into a key value pair object for (const pair in dataArray) { const split = dataArray[pair].split('='); parameters[decodeURIComponent(split[0])] = decodeURIComponent(split[1]); } // If the request was not successful, log it if (parameters.error != null) { // Log the error, TODO: show some type of error dialog. console.error('Error validating token: ' + parameters); // Clear any tokens that may be cached. logout(); } else { // Get the code const urlCode = parameters.code; // Call the wrapper service which will handle getting the access and refresh tokens // The code for this function is located in the 'auth-backend' branch. const response = await fetch('https://ge-functions.azurewebsites.net/api/get-token', { body: JSON.stringify({ client_id: clientId, code: urlCode, redirect_uri: redirectURL, scope: scopes.join(' '), }), method: 'POST' }); // Grab the response body const body = await response.json(); // If the error is not null, run this code if (body.error !== undefined) { // Show an error message to the user and logout showErrorMessage(new ErrorMessage('Error refreshing token', body.error_description)); console.error('Error validating token: ' + body); logout(); return; } // Save the token in storage so it can be used later chrome.storage.local.set({ access_token : body.access_token, new_login: true, refresh_token: body.refresh_token }, null); // Update the local variable accessToken = body.access_token; refreshToken = body.refresh_token; // Update the users devices getRemoteDevicesAsync().then((devices) => { userDevices = devices; }); } } /** * Calls the refresh azure function which will return a new refresh and * access token so we can continue accessing resources from the Microsoft Graph. */ async function refreshTokenAsync(): Promise<boolean> { // Perform a post request to update the stored token const response = await fetch('https://ge-functions.azurewebsites.net/api/refresh-token', { body: JSON.stringify({ client_id: clientId, redirect_uri: redirectURL, refresh_token: refreshToken, scope: scopes.join(' ') }), method: 'POST' }); // Grab the response body const body = await response.json(); // If the error is not null, run this code if (body.error !== undefined) { // Show an error message to the user and logout showErrorMessage(new ErrorMessage('Error refreshing token', body.error_description)); console.error('Error refreshing token: ' + body); logout(); return false; } // Save the token in storage so it can be used later chrome.storage.local.set({ access_token : body.access_token, refresh_token: body.refresh_token }, null); // Update the local variable accessToken = body.access_token; refreshToken = body.refresh_token; // Everything was successful return true; } /** * Return a list of recent user activities. * @param secondAttempt If this is the second attempt at calling this function */ async function getUserActivitiesAsync(secondAttempt: boolean = false): Promise<any> { // Attempt to get a list of user activities const response = await fetch('https://graph.microsoft.com/beta/me/activities?$top=20', { cache: 'no-cache', headers: { 'authorization': `Bearer ${accessToken}`, 'content-type': 'application/json', }, method: 'GET' }); // If we get a 401 in return, we need to refresh the token if (response.status === 401) { console.debug("Returned 401, refreshing access token..."); // Attempt to refresh the token const refreshStatus = await refreshTokenAsync(); // If the refresh is successful and this is our first try, // call the method again if (refreshStatus && !secondAttempt) { return await getUserActivitiesAsync(true); } else { return { payload: null, reason: 'Could not authorize user. Please try again.', success : false }; } } // Grab the JSON body const body = await response.json(); // Return the list of devices return { payload: body.value, reason: '', success : true }; } /** * Returns a list of devices that belong to the logged in users account * @param secondAttempt If this is the second attempt at calling this function */ async function getRemoteDevicesAsync(secondAttempt: boolean = false): Promise<any> { // Attempt to grab a list of the users devices const response = await fetch('https://graph.microsoft.com/beta/me/devices/', { cache: 'no-cache', headers: { 'authorization': `Bearer ${accessToken}`, 'content-type': 'application/json', }, method: 'GET' }); // If we get a 401 in return, we need to refresh the token if (response.status === 401) { console.debug("Returned 401, refreshing access token..."); // Attempt to refresh the token const refreshStatus = await refreshTokenAsync(); // If the refresh is successful and this is our first try, // call the method again if (refreshStatus && !secondAttempt) { return await getRemoteDevicesAsync(true); } else { return { payload: null, reason: 'Could not authorize user. Please try again.', success : false }; } } // Grab the JSON body const body = await response.json(); // Return the list of devices return { payload: body.value, reason: '', success : true }; } async function launchOnRemoteDeviceAsync(payload: OpenOnRemoteDeviceMessage, secondAttempt: boolean = false): Promise<void> { // Attempt to open the url on the users device const response = await fetch('https://graph.microsoft.com/beta/me/devices/' + payload.DeviceId + '/commands', { body: '{"type":"LaunchUri","payload":{"uri":"' + payload.Url + '"}}', cache: 'no-cache', headers: { 'authorization': `Bearer ${accessToken}`, 'content-type': 'application/json', }, method: 'POST' }); // If we get a 401 in return, we need to refresh the token if (response.status === 401) { console.debug("Returned 401, refreshing access token..."); // Attempt to refresh the token const refreshStatus = await refreshTokenAsync(); // If the refresh is successful and this is our first try, // call the method again if (refreshStatus && !secondAttempt) { return await launchOnRemoteDeviceAsync(payload, true); } else { console.error('Could not authorize user. Please try again.'); showErrorMessage(new ErrorMessage('Could not open link', 'Could not authorize user. Please try again.')); } } // Grab the JSON body const body = await response.json(); console.debug(body); } /** * Log an error message to the console * @param message The error message */ function showErrorMessage(message: ErrorMessage) { console.error('Title: ' + message.Title + ', Message: ' + message.Description); } /** * Handle messages sent to this background script. Handles either */ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (typeof request === 'undefined') { return; } // Send a web activity request to the Microsoft Graph only if // the tab is not incognito. if ((request as Message).Type === MessageType.PublishActivity) { if (!sender.tab.incognito) { sendActivityAsync(request as ActivityMessage); } else { console.debug('Tab is in incognito mode, not sending activity.'); } return; } // The user has requested a login, open the login dialog if ((request as Message).Type === MessageType.Login) { login(); return; } // The user has requested a logout if ((request as Message).Type === MessageType.Logout) { logout(); return; } // The user has requested a logout if ((request as Message).Type === MessageType.Error) { // Show a notification showErrorMessage(request as ErrorMessage); return; } if ((request as Message).Type === MessageType.AuthSubmit) { // Get the message and then validate the token const message = request as AuthMessage; validateLoginAsync(message.QueryString); return; } if ((request as Message).Type === MessageType.GetActivities) { // Return the users activities getUserActivitiesAsync().then((data) => { sendResponse(data); }); return true; } if ((request as Message).Type === MessageType.GetRemoteDevices) { // If we have cached devices, return them if (userDevices !== undefined) { // Send the response sendResponse(userDevices); // Update cached values getRemoteDevicesAsync().then((data) => { userDevices = data; }); } else { // Get a list of devices, cache them and then send the response getRemoteDevicesAsync().then((data) => { userDevices = data; sendResponse(data); }); } return true; } if ((request as Message).Type === MessageType.OpenOnRemoteDevice) { launchOnRemoteDeviceAsync(request as OpenOnRemoteDeviceMessage); return; } });
the_stack
import { Cluster } from './cluster' import { CouchbaseError, CollectionNotFoundError, EventingFunctionCompilationFailureError, EventingFunctionDeployedError, EventingFunctionIdenticalKeyspaceError, EventingFunctionNotBootstrappedError, EventingFunctionNotDeployedError, EventingFunctionNotFoundError, } from './errors' import { HttpExecutor, HttpMethod, HttpServiceType } from './httpexecutor' import { QueryScanConsistency } from './querytypes' import { RequestSpan } from './tracing' import { NodeCallback, PromiseHelper } from './utilities' /** * Represents the various dcp boundary options for eventing functions. * * @category Management */ export enum EventingFunctionDcpBoundary { /** * Indicates all documents should be processed by the function. */ Everything = 'everything', /** * Indicates that only documents modified after a function is created * should be processed by the function. */ FromNow = 'from_now', } /** * Represents the various possible deployment statuses for an eventing function. * * @category Management */ export enum EventingFunctionDeploymentStatus { /** * Indicates that the function is deployed. */ Deployed = 'deployed', /** * Indicates that the function has not yet been deployed. */ Undeployed = 'undeployed', } /** * Represents the various possible processing statuses for an eventing function. * * @category Management */ export enum EventingFunctionProcessingStatus { /** * Indicates that the eventing function is currently running. */ Running = 'running', /** * Indicates that the eventing function is currently paused. */ Paused = 'paused', } /** * Represents the authentication method to use for a URL binding. * * @category Management */ export enum EventingFunctionStatus { /** * Indicates that the eventing function is undeployed. */ Undeployed = 'undeployed', /** * Indicates that the eventing function is deploying. */ Deploying = 'deploying', /** * Indicates that the eventing function is deployed. */ Deployed = 'deployed', /** * Indicates that the eventing function is undeploying. */ Undeploying = 'undeploying', /** * Indicates that the eventing function is paused. */ Paused = 'paused', /** * Indicates that the eventing function is pausing. */ Pausing = 'pausing', } /** * Represents the language compatibility levels of an eventing function. * * @category Management */ export enum EventingFunctionLanguageCompatibility { /** * Indicates that the function should run with compatibility with * Couchbase Server 6.0.0. */ Version_6_0_0 = '6.0.0', /** * Indicates that the function should run with compatibility with * Couchbase Server 6.5.0. */ Version_6_5_0 = '6.5.0', /** * Indicates that the function should run with compatibility with * Couchbase Server 6.6.2. */ Version_6_6_2 = '6.6.2', } /** * Represents the various log levels for an eventing function. * * @category Management */ export enum EventingFunctionLogLevel { /** * Indicates to use INFO level logging. */ Info = 'INFO', /** * Indicates to use ERROR level logging. */ Error = 'ERROR', /** * Indicates to use WARNING level logging. */ Warning = 'WARNING', /** * Indicates to use DEBUG level logging. */ Debug = 'DEBUG', /** * Indicates to use TRACE level logging. */ Trace = 'TRACE', } /** * Represents the various bucket access levels for an eventing function. * * @category Management */ export enum EventingFunctionBucketAccess { /** * Indicates that the function can only read the associated bucket. */ ReadOnly = 'r', /** * Indicates that the function can both read and write the associated bucket. */ ReadWrite = 'rw', } /** * Represents the authentication method to use for a URL binding. * * @category Management */ export enum EventingFunctionUrlAuthMethod { /** * Indicates that no authentication should be used. */ None = 'no-auth', /** * Indicates that Basic should be used. */ Basic = 'basic', /** * Indicates that Digest should be used. */ Digest = 'digest', /** * Indicates that Bearer should be used. */ Bearer = 'bearer', } /** * Specifies the bucket/scope/collection used by an eventing function. * * @category Management */ export class EventingFunctionKeyspace { constructor(v: EventingFunctionKeyspace) { this.bucket = v.bucket this.scope = v.scope this.collection = v.collection } /** * The bucket to use. */ bucket: string /** * The scope to use. */ scope?: string /** * The collection to use. */ collection?: string } /** * Specifies a bucket binding for an eventing function. * * @category Management */ export class EventingFunctionBucketBinding { constructor(v: EventingFunctionBucketBinding) { this.alias = v.alias this.name = v.name this.access = v.access } /** * The alias to use for referring to this binding. */ alias: string /** * The keyspace that this binding refers to. */ name: EventingFunctionKeyspace /** * The level of access configured for this binding. */ access: EventingFunctionBucketAccess /** * @internal */ static _fromEvtData(data: any): EventingFunctionBucketBinding { return new EventingFunctionBucketBinding({ name: new EventingFunctionKeyspace({ bucket: data.bucket_name, scope: data.scope_name, collection: data.collection_name, }), alias: data.alias, access: data.access, }) } /** * @internal */ static _toEvtData(data: EventingFunctionBucketBinding): any { return { bucket_name: data.name.bucket, scope_name: data.name.scope, collection_name: data.name.collection, alias: data.alias, access: data.access, } } } /** * Specifies a type of url authentication to use. * * @category Management */ export interface EventingFunctionUrlAuth { /** * The method of authentication to use. */ method: EventingFunctionUrlAuthMethod } /** * Specifies that Basic authentication should be used for the URL. * * @category Management */ export class EventingFunctionUrlAuthBasic implements EventingFunctionUrlAuth { /** * Sets the auth method to Basic. */ method = EventingFunctionUrlAuthMethod.Basic constructor(v: Omit<EventingFunctionUrlAuthBasic, 'method'>) { this.username = v.username this.password = v.password } /** * Specifies the username to use for authentication. */ username: string /** * Specifies the password to use for authentication. */ password: string } /** * Specifies that Digest authentication should be used for the URL. * * @category Management */ export class EventingFunctionUrlAuthDigest implements EventingFunctionUrlAuth { /** * Sets the auth method to Digest. */ method = EventingFunctionUrlAuthMethod.Digest constructor(v: Omit<EventingFunctionUrlAuthDigest, 'method'>) { this.username = v.username this.password = v.password } /** * Specifies the username to use for authentication. */ username: string /** * Specifies the password to use for authentication. */ password: string } /** * Specifies that Bearer authentication should be used for the URL. * * @category Management */ export class EventingFunctionUrlAuthBearer implements EventingFunctionUrlAuth { /** * Sets the auth method to Bearer. */ method = EventingFunctionUrlAuthMethod.Bearer constructor(v: Omit<EventingFunctionUrlAuthBearer, 'method'>) { this.key = v.key } /** * Specifies the bearer token to use. */ key: string } /** * Specifies a url binding for an eventing function. * * @category Management */ export class EventingFunctionUrlBinding { constructor(v: EventingFunctionUrlBinding) { this.hostname = v.hostname this.alias = v.alias this.auth = v.auth this.allowCookies = v.allowCookies this.validateSslCertificate = v.validateSslCertificate } /** * The alias to use for referring to this binding. */ alias: string /** * The hostname this url binding should refer to. */ hostname: string /** * The authentication that should be used. */ auth?: EventingFunctionUrlAuth /** * Whether or not cookies should be allowed. */ allowCookies: boolean /** * Whether the SSL certificate should be validated. */ validateSslCertificate: boolean /** * @internal */ static _fromEvtData(data: any): EventingFunctionUrlBinding { let authObj if (data.auth_type === EventingFunctionUrlAuthMethod.None) { authObj = undefined } else if (data.auth_type === EventingFunctionUrlAuthMethod.Basic) { authObj = new EventingFunctionUrlAuthBasic({ username: data.username, password: data.password, }) } else if (data.auth_type === EventingFunctionUrlAuthMethod.Digest) { authObj = new EventingFunctionUrlAuthDigest({ username: data.username, password: data.password, }) } else if (data.auth_type === EventingFunctionUrlAuthMethod.Bearer) { authObj = new EventingFunctionUrlAuthBearer({ key: data.bearer_key, }) } else { throw new Error('invalid auth type specified') } return { hostname: data.hostname, alias: data.value, allowCookies: data.allow_cookies, validateSslCertificate: data.validate_ssl_certificate, auth: authObj, } } /** * @internal */ static _toEvtData(data: EventingFunctionUrlBinding): any { return { hostname: data.hostname, value: data.alias, allow_cookies: data.allowCookies, validate_ssl_certificate: data.validateSslCertificate, auth_type: data.auth ? data.auth.method : EventingFunctionUrlAuthMethod.None, username: (data as any).username, password: (data as any).password, bearer_key: (data as any).key, } } } /** * Specifies a constant binding for an eventing function. * * @category Management */ export class EventingFunctionConstantBinding { constructor(v: EventingFunctionConstantBinding) { this.alias = v.alias this.literal = v.literal } /** * The alias to use for referring to this binding. */ alias: string /** * The literal value for this binding. */ literal: string /** * @internal */ static _fromEvtData(data: any): EventingFunctionConstantBinding { return new EventingFunctionConstantBinding({ alias: data.value, literal: data.literal, }) } /** * @internal */ static _toEvtData(data: EventingFunctionConstantBinding): any { return { value: data.alias, literal: data.literal, } } } /** * Specifies a number of options which can be used when updating or creating * a eventing function. * * @category Management */ export class EventingFunctionSettings { constructor(v: EventingFunctionSettings) { this.cppWorkerThreadCount = v.cppWorkerThreadCount this.dcpStreamBoundary = v.dcpStreamBoundary this.description = v.description this.deploymentStatus = v.deploymentStatus this.processingStatus = v.processingStatus this.languageCompatibility = v.languageCompatibility this.logLevel = v.logLevel this.executionTimeout = v.executionTimeout this.lcbInstCapacity = v.lcbInstCapacity this.lcbRetryCount = v.lcbRetryCount this.lcbTimeout = v.lcbTimeout this.queryConsistency = v.queryConsistency this.numTimerPartitions = v.numTimerPartitions this.sockBatchSize = v.sockBatchSize this.tickDuration = v.tickDuration this.timerContextSize = v.timerContextSize this.userPrefix = v.userPrefix this.bucketCacheSize = v.bucketCacheSize this.bucketCacheAge = v.bucketCacheAge this.curlMaxAllowedRespSize = v.curlMaxAllowedRespSize this.queryPrepareAll = v.queryPrepareAll this.workerCount = v.workerCount this.handlerHeaders = v.handlerHeaders this.handlerFooters = v.handlerFooters this.enableAppLogRotation = v.enableAppLogRotation this.appLogDir = v.appLogDir this.appLogMaxSize = v.appLogMaxSize this.appLogMaxFiles = v.appLogMaxFiles this.checkpointInterval = v.checkpointInterval } /** * The number of worker threads to use for the function. */ cppWorkerThreadCount: number /** * The DCP stream boundary to use. */ dcpStreamBoundary: EventingFunctionDcpBoundary /** * A description of this eventing function. */ description: string /** * The current deployment status of the function. */ deploymentStatus: EventingFunctionDeploymentStatus /** * The current processing status of the function. */ processingStatus: EventingFunctionProcessingStatus /** * The active compatibility mode for the function. */ languageCompatibility: EventingFunctionLanguageCompatibility /** * The level of logging that should be captured for the function. */ logLevel: EventingFunctionLogLevel /** * The maximum period of time the function can execute on a document * before timing out. */ executionTimeout: number /** * The maximum number of internal clients that the function should * maintain for KV operations. */ lcbInstCapacity: number /** * The maximum number of times to retry a KV operation before failing * the function. */ lcbRetryCount: number /** * The maximum period of time a KV operation within the function can * operate before timing out. */ lcbTimeout: number /** * The level of consistency to use when performing queries in the function. */ queryConsistency: QueryScanConsistency /** * The number of partitions that should be used for timer tracking. */ numTimerPartitions: number /** * The batch size for messages from producer to consumer. */ sockBatchSize: number /** * The duration to log stats from this handler, in milliseconds. */ tickDuration: number /** * The size limit of timer context object. */ timerContextSize: number /** * The key prefix for all data stored in metadata by this handler. */ userPrefix: string /** * The maximum size in bytes the bucket cache can grow to. */ bucketCacheSize: number /** * The time in milliseconds after which a cached bucket object is considered stale. */ bucketCacheAge: number /** * The maximum allowable curl call response in 'MegaBytes'. Setting the value to 0 * lifts the upper limit off. This parameters affects v8 engine stability since it * defines the maximum amount of heap space acquired by a curl call. */ curlMaxAllowedRespSize: number /** * Whether to automatically prepare all query statements in the handler. */ queryPrepareAll: boolean /** * The number of worker processes handler utilizes on each eventing node. */ workerCount: number /** * The code to automatically prepend to top of handler code. */ handlerHeaders: string[] /** * The code to automatically append to bottom of handler code. */ handlerFooters: string[] /** * Whether to enable rotating this handlers log() message files. */ enableAppLogRotation: boolean /** * The directory to write content of log() message files. */ appLogDir: string /** * The size in bytes of the log file when the file should be rotated. */ appLogMaxSize: number /** * The number of log() message files to retain when rotating. */ appLogMaxFiles: number /** * The number of seconds before writing a progress checkpoint. */ checkpointInterval: number /** * @internal */ static _fromEvtData(data: any): EventingFunctionSettings { return new EventingFunctionSettings({ cppWorkerThreadCount: data.cpp_worker_thread_count, dcpStreamBoundary: data.dcp_stream_boundary, description: data.description, logLevel: data.log_level, languageCompatibility: data.language_compatibility, executionTimeout: data.execution_timeout, lcbInstCapacity: data.lcb_inst_capacity, lcbRetryCount: data.lcb_retry_count, lcbTimeout: data.lcb_timeout, queryConsistency: data.n1ql_consistency, numTimerPartitions: data.num_timer_partitions, sockBatchSize: data.sock_batch_size, tickDuration: data.tick_duration, timerContextSize: data.timer_context_size, userPrefix: data.user_prefix, bucketCacheSize: data.bucket_cache_size, bucketCacheAge: data.bucket_cache_age, curlMaxAllowedRespSize: data.curl_max_allowed_resp_size, workerCount: data.worker_count, queryPrepareAll: data.n1ql_prepare_all, handlerHeaders: data.handler_headers, handlerFooters: data.handler_footers, enableAppLogRotation: data.enable_applog_rotation, appLogDir: data.app_log_dir, appLogMaxSize: data.app_log_max_size, appLogMaxFiles: data.app_log_max_files, checkpointInterval: data.checkpoint_interval, deploymentStatus: data.deployment_status ? EventingFunctionDeploymentStatus.Deployed : EventingFunctionDeploymentStatus.Undeployed, processingStatus: data.processing_status ? EventingFunctionProcessingStatus.Running : EventingFunctionProcessingStatus.Paused, }) } /** * @internal */ static _toEvtData(data: EventingFunctionSettings): any { if (!data) { return { deployment_status: false, } } return { cpp_worker_thread_count: data.cppWorkerThreadCount, dcp_stream_boundary: data.dcpStreamBoundary, description: data.description, log_level: data.logLevel, language_compatibility: data.languageCompatibility, execution_timeout: data.executionTimeout, lcb_inst_capacity: data.lcbInstCapacity, lcb_retry_count: data.lcbRetryCount, lcb_timeout: data.lcbTimeout, n1ql_consistency: data.queryConsistency, num_timer_partitions: data.numTimerPartitions, sock_batch_size: data.sockBatchSize, tick_duration: data.tickDuration, timer_context_size: data.timerContextSize, user_prefix: data.userPrefix, bucket_cache_size: data.bucketCacheSize, bucket_cache_age: data.bucketCacheAge, curl_max_allowed_resp_size: data.curlMaxAllowedRespSize, worker_count: data.workerCount, n1ql_prepare_all: data.queryPrepareAll, handler_headers: data.handlerHeaders, handler_footers: data.handlerFooters, enable_applog_rotation: data.enableAppLogRotation, app_log_dir: data.appLogDir, app_log_max_size: data.appLogMaxSize, app_log_max_files: data.appLogMaxFiles, checkpoint_interval: data.checkpointInterval, deployment_status: data.deploymentStatus === EventingFunctionDeploymentStatus.Deployed ? true : false, processing_status: data.processingStatus === EventingFunctionProcessingStatus.Running ? true : false, } } } /** * Describes an eventing function. * * @category Management */ export class EventingFunction { constructor(v: EventingFunction) { this.name = v.name this.code = v.code this.version = v.version this.enforceSchema = v.enforceSchema this.handlerUuid = v.handlerUuid this.functionInstanceId = v.functionInstanceId this.metadataKeyspace = v.metadataKeyspace this.sourceKeyspace = v.sourceKeyspace this.bucketBindings = v.bucketBindings this.urlBindings = v.urlBindings this.constantBindings = v.constantBindings this.settings = v.settings } /** * The name of the eventing function. */ name: string /** * The code for this eventing function. */ code: string /** * The authoring version of this eventing function. */ version: string /** * Whether to enable stricter validation of settings and configuration. */ enforceSchema: boolean /** * The unique ID for this eventing function. */ handlerUuid: number /** * The unique id for the deployment of the handler. */ functionInstanceId: string /** * The keyspace to store the functions metadata. */ metadataKeyspace: EventingFunctionKeyspace /** * The keyspace that the function should operate on. */ sourceKeyspace: EventingFunctionKeyspace /** * The buckets to bind to the function. */ bucketBindings: EventingFunctionBucketBinding[] /** * The URLs to bind to the function. */ urlBindings: EventingFunctionUrlBinding[] /** * The constants to bind to the function. */ constantBindings: EventingFunctionConstantBinding[] /** * The settings for this function. */ settings: EventingFunctionSettings /** * @internal */ static _fromEvtData(data: any): EventingFunction { return new EventingFunction({ name: data.appname, code: data.appcode, settings: EventingFunctionSettings._fromEvtData(data.settings), version: data.version, enforceSchema: data.enforce_schema, handlerUuid: data.handleruuid, functionInstanceId: data.function_instance_id, metadataKeyspace: new EventingFunctionKeyspace({ bucket: data.depcfg.metadata_bucket, scope: data.depcfg.metadata_scope, collection: data.depcfg.metadata_collection, }), sourceKeyspace: new EventingFunctionKeyspace({ bucket: data.depcfg.source_bucket, scope: data.depcfg.source_scope, collection: data.depcfg.source_collection, }), constantBindings: data.depcfg.constants.map((bindingData: any) => EventingFunctionConstantBinding._fromEvtData(bindingData) ), bucketBindings: data.depcfg.buckets.map((bindingData: any) => EventingFunctionBucketBinding._fromEvtData(bindingData) ), urlBindings: data.depcfg.curl.map((bindingData: any) => EventingFunctionUrlBinding._fromEvtData(bindingData) ), }) } /** * @internal */ static _toEvtData(data: EventingFunction): any { return { appname: data.name, appcode: data.code, settings: EventingFunctionSettings._toEvtData(data.settings), version: data.version, enforce_schema: data.enforceSchema, handleruuid: data.handlerUuid, function_instance_id: data.functionInstanceId, depcfg: { metadata_bucket: data.metadataKeyspace.bucket, metadata_scope: data.metadataKeyspace.scope, metadata_collection: data.metadataKeyspace.collection, source_bucket: data.sourceKeyspace.bucket, source_scope: data.sourceKeyspace.scope, source_collection: data.sourceKeyspace.collection, constants: data.constantBindings.map((binding) => EventingFunctionConstantBinding._toEvtData(binding) ), buckets: data.bucketBindings.map((binding) => EventingFunctionBucketBinding._toEvtData(binding) ), curl: data.urlBindings.map((binding) => EventingFunctionUrlBinding._toEvtData(binding) ), }, } } } /** * Describes the current state of an eventing function. * * @category Management */ export class EventingFunctionState { constructor(v: EventingFunctionState) { this.name = v.name this.status = v.status this.numBootstrappingNodes = v.numBootstrappingNodes this.numDeployedNodes = v.numDeployedNodes this.deploymentStatus = v.deploymentStatus this.processingStatus = v.processingStatus } /** * The name of the eventing function. */ name: string /** * The current overall state of this eventing function. */ status: EventingFunctionStatus /** * The number of nodes where this eventing function is bootstrapping. */ numBootstrappingNodes: number /** * The number of nodes where this eventing function is deployed. */ numDeployedNodes: number /** * The current deployment status of this eventing function. */ deploymentStatus: EventingFunctionDeploymentStatus /** * The current processing status of this eventing function. */ processingStatus: EventingFunctionProcessingStatus /** * @internal */ static _fromEvtData(data: any): EventingFunctionState { return new EventingFunctionState({ name: data.name, status: data.composite_status, numBootstrappingNodes: data.num_bootstrapping_nodes, numDeployedNodes: data.num_deployed_nodes, deploymentStatus: data.deployment_status ? EventingFunctionDeploymentStatus.Deployed : EventingFunctionDeploymentStatus.Undeployed, processingStatus: data.processing_status ? EventingFunctionProcessingStatus.Running : EventingFunctionProcessingStatus.Paused, }) } } /** * Describes the current state of all eventing function. * * @category Management */ export class EventingState { constructor(v: EventingState) { this.numEventingNodes = v.numEventingNodes this.functions = v.functions } /** * The number of eventing nodes that are currently active. */ numEventingNodes: number /** * The states of all registered eventing functions. */ functions: EventingFunctionState[] /** * @internal */ static _fromEvtData(data: any): EventingState { return new EventingState({ numEventingNodes: data.num_eventing_nodes, functions: data.apps.map((functionData: any) => EventingFunctionState._fromEvtData(functionData) ), }) } } /** * @category Management */ export interface UpsertFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface DropFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface GetAllFunctionsOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface GetFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface DeployFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface UndeployFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface PauseFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface ResumeFunctionOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * @category Management */ export interface FunctionsStatusOptions { /** * The parent tracing span that this operation will be part of. */ parentSpan?: RequestSpan /** * The timeout for this operation, represented in milliseconds. */ timeout?: number } /** * EventingFunctionManager provides an interface for managing the * eventing functions on the cluster. * Volatile: This API is subject to change at any time. * * @category Management */ export class EventingFunctionManager { private _cluster: Cluster /** * @internal */ constructor(cluster: Cluster) { this._cluster = cluster } private get _http() { return new HttpExecutor(this._cluster._getClusterConn()) } /** * Creates or updates an eventing function. * * @param functionDefinition The description of the eventing function to upsert. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async upsertFunction( functionDefinition: EventingFunction, options?: UpsertFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = functionDefinition.name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const encodedData = EventingFunction._toEvtData(functionDefinition) const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Post, path: `/api/v1/functions/${functionName}`, contentType: 'application/json', body: JSON.stringify(encodedData), parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_collection_missing')) { throw new CollectionNotFoundError(undefined, errCtx) } if (errText.includes('err_src_mb_same')) { throw new EventingFunctionIdenticalKeyspaceError(undefined, errCtx) } if (errText.includes('err_handler_compilation')) { throw new EventingFunctionCompilationFailureError(undefined, errCtx) } throw new CouchbaseError('failed to upsert function', undefined, errCtx) } }, callback) } /** * Deletes an eventing function. * * @param name The name of the eventing function to delete. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async dropFunction( name: string, options?: DropFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Delete, path: `/api/v1/functions/${functionName}`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } if (errText.includes('err_app_not_deployed')) { throw new EventingFunctionNotDeployedError(undefined, errCtx) } if (errText.includes('err_app_not_undeployed')) { throw new EventingFunctionDeployedError(undefined, errCtx) } throw new CouchbaseError('failed to drop function', undefined, errCtx) } }, callback) } /** * Fetches all eventing functions. * * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async getAllFunctions( options?: GetAllFunctionsOptions, callback?: NodeCallback<EventingFunction[]> ): Promise<EventingFunction[]> { if (options instanceof Function) { callback = arguments[0] options = undefined } if (!options) { options = {} } const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Get, path: `/api/v1/functions`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) throw new CouchbaseError('failed to get functions', undefined, errCtx) } const functionsData = JSON.parse(res.body.toString()) const functions = functionsData.map((functionData: any) => EventingFunction._fromEvtData(functionData) ) return functions }, callback) } /** * Fetches a specific eventing function. * * @param name The name of the eventing function to fetch. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async getFunction( name: string, options?: GetFunctionOptions, callback?: NodeCallback<EventingFunction> ): Promise<EventingFunction> { if (options instanceof Function) { callback = arguments[1] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Get, path: `/api/v1/functions/${functionName}`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } throw new CouchbaseError('failed to get function', undefined, errCtx) } const functionData = JSON.parse(res.body.toString()) return EventingFunction._fromEvtData(functionData) }, callback) } /** * Deploys an eventing function. * * @param name The name of the eventing function to deploy. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async deployFunction( name: string, options?: DeployFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Post, path: `/api/v1/functions/${functionName}/deploy`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } if (errText.includes('err_app_not_bootstrapped')) { throw new EventingFunctionNotBootstrappedError(undefined, errCtx) } throw new CouchbaseError('failed to deploy function', undefined, errCtx) } }, callback) } /** * Undeploys an eventing function. * * @param name The name of the eventing function to undeploy. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async undeployFunction( name: string, options?: DeployFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Post, path: `/api/v1/functions/${functionName}/undeploy`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } if (errText.includes('err_app_not_deployed')) { throw new EventingFunctionNotDeployedError(undefined, errCtx) } throw new CouchbaseError( 'failed to undeploy function', undefined, errCtx ) } }, callback) } /** * Pauses an eventing function. * * @param name The name of the eventing function to pause. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async pauseFunction( name: string, options?: PauseFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Post, path: `/api/v1/functions/${functionName}/pause`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } if (errText.includes('err_app_not_bootstrapped')) { throw new EventingFunctionNotBootstrappedError(undefined, errCtx) } throw new CouchbaseError('failed to pause function', undefined, errCtx) } }, callback) } /** * Resumes an eventing function. * * @param name The name of the eventing function to resume. * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async resumeFunction( name: string, options?: ResumeFunctionOptions, callback?: NodeCallback<void> ): Promise<void> { if (options instanceof Function) { callback = arguments[2] options = undefined } if (!options) { options = {} } const functionName = name const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Post, path: `/api/v1/functions/${functionName}/resume`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) const errText = res.body.toString().toLowerCase() if (errText.includes('err_app_not_found_ts')) { throw new EventingFunctionNotFoundError(undefined, errCtx) } if (errText.includes('err_app_not_deployed')) { throw new EventingFunctionNotDeployedError(undefined, errCtx) } throw new CouchbaseError('failed to resume function', undefined, errCtx) } }, callback) } /** * Fetches the status of all eventing functions. * * @param options Optional parameters for this operation. * @param callback A node-style callback to be invoked after execution. */ async functionsStatus( options?: FunctionsStatusOptions, callback?: NodeCallback<EventingState> ): Promise<EventingState> { if (options instanceof Function) { callback = arguments[0] options = undefined } if (!options) { options = {} } const parentSpan = options.parentSpan const timeout = options.timeout return PromiseHelper.wrapAsync(async () => { const res = await this._http.request({ type: HttpServiceType.Eventing, method: HttpMethod.Get, path: `/api/v1/status`, parentSpan: parentSpan, timeout: timeout, }) if (res.statusCode !== 200) { const errCtx = HttpExecutor.errorContextFromResponse(res) throw new CouchbaseError( 'failed to fetch functions status', undefined, errCtx ) } const statusData = JSON.parse(res.body.toString()) return EventingState._fromEvtData(statusData) }, callback) } }
the_stack
import React from "react"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import "@testing-library/jest-dom"; import { testAccount, testResult, TEST_CONFIG } from "../TestConstants"; import { MsalProvider, MsalAuthenticationTemplate, MsalAuthenticationResult, IMsalContext, useMsal } from "../../src/index"; import { PublicClientApplication, Configuration, InteractionType, EventType, AccountInfo, EventCallbackFunction, EventMessage, PopupRequest, AuthError } from "@azure/msal-browser"; describe("MsalAuthenticationTemplate tests", () => { let pca: PublicClientApplication; const msalConfig: Configuration = { auth: { clientId: TEST_CONFIG.MSAL_CLIENT_ID } }; let eventCallbacks: EventCallbackFunction[]; let handleRedirectSpy: jest.SpyInstance; let accounts: AccountInfo[] = []; beforeEach(() => { eventCallbacks = []; let eventId = 0; pca = new PublicClientApplication(msalConfig); jest.spyOn(pca, "addEventCallback").mockImplementation((callbackFn) => { eventCallbacks.push(callbackFn); eventId += 1; return eventId.toString(); }); handleRedirectSpy = jest.spyOn(pca, "handleRedirectPromise").mockImplementation(() => { const eventStart: EventMessage = { eventType: EventType.HANDLE_REDIRECT_START, interactionType: InteractionType.Redirect, payload: null, error: null, timestamp: 10000 }; eventCallbacks.forEach((callback) => { callback(eventStart); }); const eventEnd: EventMessage = { eventType: EventType.HANDLE_REDIRECT_END, interactionType: InteractionType.Redirect, payload: null, error: null, timestamp: 10000 }; eventCallbacks.forEach((callback) => { callback(eventEnd); }); return Promise.resolve(null); }); jest.spyOn(pca, "getAllAccounts").mockImplementation(() => accounts); }); afterEach(() => { // cleanup on exiting jest.clearAllMocks(); accounts = []; }); test("Calls loginPopup if no account is signed in", async () => { const loginPopupSpy = jest.spyOn(pca, "loginPopup").mockImplementation((request) => { expect(request).toBe(undefined); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Popup, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Popup}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginPopupSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("Calls loginRedirect if no account is signed in", async () => { const loginRedirectSpy = jest.spyOn(pca, "loginRedirect").mockImplementation((request) => { expect(request).toBe(undefined); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Redirect, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Redirect}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginRedirectSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("Calls ssoSilent if no account is signed in", async () => { const ssoSilentSpy = jest.spyOn(pca, "ssoSilent").mockImplementation((request) => { expect(request).toBe(undefined); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Silent, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Silent}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(ssoSilentSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("Calls loginPopup with provided request if no account is signed in", async () => { const loginRequest: PopupRequest = { scopes: ["openid"], redirectUri: "http://localhost" }; const loginPopupSpy = jest.spyOn(pca, "loginPopup").mockImplementation((request) => { expect(request).toBe(loginRequest); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Popup, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Popup} authenticationRequest={loginRequest}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginPopupSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("Calls loginRedirect with provided request if no account is signed in", async () => { const loginRequest: PopupRequest = { scopes: ["openid"], redirectUri: "http://localhost" }; const loginRedirectSpy = jest.spyOn(pca, "loginRedirect").mockImplementation((request) => { expect(request).toBe(loginRequest); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Redirect, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Redirect} authenticationRequest={loginRequest}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginRedirectSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("Calls ssoSilent with provided request if no account is signed in", async () => { const loginRequest: PopupRequest = { scopes: ["openid"] }; const ssoSilentSpy = jest.spyOn(pca, "ssoSilent").mockImplementation((request) => { expect(request).toBe(loginRequest); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Silent, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Silent} authenticationRequest={loginRequest}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(ssoSilentSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).toBeInTheDocument(); }); test("LoginRedirect is not called if handleRedirectPromise returns an error", async () => { const error = new AuthError("login_failed"); handleRedirectSpy = jest.spyOn(pca, "handleRedirectPromise").mockImplementation(() => { const startMessage: EventMessage = { eventType: EventType.HANDLE_REDIRECT_START, interactionType: InteractionType.Redirect, payload: null, error: null, timestamp: 10000 }; const failureMessage: EventMessage = { eventType: EventType.LOGIN_FAILURE, interactionType: InteractionType.Redirect, payload: null, error: error, timestamp: 10000 }; const endMessage: EventMessage = { eventType: EventType.HANDLE_REDIRECT_END, interactionType: InteractionType.Redirect, payload: null, error: null, timestamp: 10000 }; eventCallbacks.forEach((callback) => { callback(startMessage); callback(failureMessage); callback(endMessage); }); return Promise.reject(error); }); const loginRedirectSpy = jest.spyOn(pca, "loginRedirect"); const errorMessage = ({error}: MsalAuthenticationResult) => { if (error) { return <p>Error Occurred: {error.errorCode}</p>; } return null; }; render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Redirect} errorComponent={errorMessage}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(await screen.findByText("Error Occurred: login_failed")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).not.toBeInTheDocument(); expect(loginRedirectSpy).toHaveBeenCalledTimes(0); }); test("If user is signed in and MsalAuthenticationTemplate is rendered after MsalProvider, child renders and login is not called", async () => { const loginRedirectSpy = jest.spyOn(pca, "loginRedirect"); accounts = [testAccount]; const TestComponent = () => { const {inProgress} = useMsal(); if (inProgress === "none") { return ( <MsalAuthenticationTemplate interactionType={InteractionType.Redirect}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> ); } else { return null; } }; render( <MsalProvider instance={pca}> <p>This text will always display.</p> <TestComponent /> </MsalProvider> ); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(await screen.findByText("A user is authenticated!")).toBeInTheDocument(); expect(loginRedirectSpy).not.toHaveBeenCalled(); }); test("Renders provided error component when an error occurs", async () => { const error = new AuthError("login_failed"); const loginPopupSpy = jest.spyOn(pca, "loginPopup").mockImplementation(() => { const eventMessage: EventMessage = { eventType: EventType.LOGIN_FAILURE, interactionType: InteractionType.Popup, payload: null, error: error, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.reject(error); }); const errorMessage = ({error}: MsalAuthenticationResult) => { if (error) { return <p>Error Occurred: {error.errorCode}</p>; } return null; }; render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Popup} errorComponent={errorMessage}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginPopupSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(await screen.findByText("Error Occurred: login_failed")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).not.toBeInTheDocument(); }); test("Provided error component can resolve error by calling login again, child renders after success", async () => { const error = new AuthError("login_failed"); const ssoSilentSpy = jest.spyOn(pca, "ssoSilent").mockImplementation(() => { const eventMessage: EventMessage = { eventType: EventType.LOGIN_FAILURE, interactionType: InteractionType.Silent, payload: null, error: error, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.reject(error); }); const loginPopupSpy = jest.spyOn(pca, "loginPopup").mockImplementation((request) => { expect(request).toBe(undefined); accounts = [testAccount]; const eventMessage: EventMessage = { eventType: EventType.LOGIN_SUCCESS, interactionType: InteractionType.Popup, payload: testResult, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); const ErrorMessage = ({error, login}: MsalAuthenticationResult) => { return ( <> <p>Error Occurred: {error?.errorCode}</p> <button onClick={() => login(InteractionType.Popup)}>Retry</button> </> ); }; render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Silent} errorComponent={ErrorMessage}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); // Verify Error Component rendered expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); await waitFor(() => expect(ssoSilentSpy).toHaveBeenCalledTimes(1)); expect(await screen.findByText("Error Occurred: login_failed")).toBeInTheDocument(); const retryButton = await screen.findByRole("button", {name: "Retry"}); expect(retryButton).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).not.toBeInTheDocument(); // Verify the Error Component has access to the login function and successful login causes MsalAuthenticationTemplate to rerender with child fireEvent.click(retryButton); await waitFor(() => expect(loginPopupSpy).toHaveBeenCalledTimes(1)); expect(await screen.findByText("A user is authenticated!")).toBeInTheDocument(); expect(screen.queryByText("Error Occurred: login_failed")).not.toBeInTheDocument(); }); test("Renders provided loading component when interaction is in progress", async () => { const loginPopupSpy = jest.spyOn(pca, "loginPopup").mockImplementation(() => { const eventMessage: EventMessage = { eventType: EventType.LOGIN_START, interactionType: InteractionType.Popup, payload: null, error: null, timestamp: 10000 }; expect(eventCallbacks.length).toBe(3); eventCallbacks.forEach((callback) => { callback(eventMessage); }); return Promise.resolve(testResult); }); const loadingMessage = ({inProgress}: IMsalContext) => { return <p>In Progress: {inProgress}</p>; }; render( <MsalProvider instance={pca}> <p>This text will always display.</p> <MsalAuthenticationTemplate interactionType={InteractionType.Popup} loadingComponent={loadingMessage}> <span> A user is authenticated!</span> </MsalAuthenticationTemplate> </MsalProvider> ); await waitFor(() => expect(handleRedirectSpy).toHaveBeenCalledTimes(1)); await waitFor(() => expect(loginPopupSpy).toHaveBeenCalledTimes(1)); expect(screen.queryByText("This text will always display.")).toBeInTheDocument(); expect(await screen.findByText("In Progress: login")).toBeInTheDocument(); expect(screen.queryByText("A user is authenticated!")).not.toBeInTheDocument(); }); });
the_stack
// ======================================================================== // XML.ObjTree -- XML source code from/to JavaScript object like E4X // ======================================================================== let XML = function () { }; // constructor XML.ObjTree = function () { // @ts-ignore return this; }; // class variables XML.ObjTree.VERSION = "0.23"; // object prototype XML.ObjTree.prototype.xmlDecl = '<?xml version="1.0" encoding="UTF-8" ?>\n'; XML.ObjTree.prototype.attr_prefix = '-'; // method: parseXML( xmlsource ) XML.ObjTree.prototype.parseXML = function (xml) { var root; if (window.DOMParser) { var xmldom = new DOMParser(); // xmldom.async = false; // DOMParser is always sync-mode var dom = xmldom.parseFromString(xml, "application/xml"); if (!dom) return; root = dom.documentElement; } else if (window.ActiveXObject) { xmldom = new ActiveXObject('Microsoft.XMLDOM'); xmldom.async = false; xmldom.loadXML(xml); root = xmldom.documentElement; } if (!root) return; return this.parseDOM(root); }; // method: parseHTTP( url, options, callback ) XML.ObjTree.prototype.parseHTTP = function (url, options, callback) { var myopt = {}; for (var key in options) { myopt[key] = options[key]; // copy object } if (!myopt.method) { if (typeof (myopt.postBody) == "undefined" && typeof (myopt.postbody) == "undefined" && typeof (myopt.parameters) == "undefined") { myopt.method = "get"; } else { myopt.method = "post"; } } if (callback) { myopt.asynchronous = true; // async-mode var __this = this; var __func = callback; var __save = myopt.onComplete; myopt.onComplete = function (trans) { var tree; if (trans && trans.responseXML && trans.responseXML.documentElement) { tree = __this.parseDOM(trans.responseXML.documentElement); } __func(tree, trans); if (__save) __save(trans); }; } else { myopt.asynchronous = false; // sync-mode } var trans; if (typeof (HTTP) != "undefined" && HTTP.Request) { myopt.uri = url; var req = new HTTP.Request(myopt); // JSAN if (req) trans = req.transport; } else if (typeof (Ajax) != "undefined" && Ajax.Request) { var req = new Ajax.Request(url, myopt); // ptorotype.js if (req) trans = req.transport; } if (callback) return trans; if (trans && trans.responseXML && trans.responseXML.documentElement) { return this.parseDOM(trans.responseXML.documentElement); } } // method: parseDOM( documentroot ) XML.ObjTree.prototype.parseDOM = function (root) { if (!root) return; this.__force_array = {}; if (this.force_array) { for (var i = 0; i < this.force_array.length; i++) { this.__force_array[this.force_array[i]] = 1; } } var json = this.parseElement(root); // parse root node if (this.__force_array[root.nodeName]) { json = [json]; } if (root.nodeType != 11) { // DOCUMENT_FRAGMENT_NODE var tmp = {}; tmp[root.nodeName] = json; // root nodeName json = tmp; } return json; }; // method: parseElement( element ) XML.ObjTree.prototype.parseElement = function (elem) { // COMMENT_NODE if (elem.nodeType == 7) { return; } // TEXT_NODE CDATA_SECTION_NODE if (elem.nodeType == 3 || elem.nodeType == 4) { var bool = elem.nodeValue.match(/[^\x00-\x20]/); if (bool == null) return; // ignore white spaces return elem.nodeValue; } var retval; var cnt = {}; // parse attributes if (elem.attributes && elem.attributes.length) { retval = {}; for (var i = 0; i < elem.attributes.length; i++) { var key = elem.attributes[i].nodeName; if (typeof (key) != "string") continue; var val = elem.attributes[i].nodeValue; if (!val) continue; key = this.attr_prefix + key; if (typeof (cnt[key]) == "undefined") cnt[key] = 0; cnt[key]++; this.addNode(retval, key, cnt[key], val); } } // parse child nodes (recursive) if (elem.childNodes && elem.childNodes.length) { var textonly = true; if (retval) textonly = false; // some attributes exists for (var i = 0; i < elem.childNodes.length && textonly; i++) { var ntype = elem.childNodes[i].nodeType; if (ntype == 3 || ntype == 4) continue; textonly = false; } if (textonly) { if (!retval) retval = ""; for (var i = 0; i < elem.childNodes.length; i++) { retval += elem.childNodes[i].nodeValue; } } else { if (!retval) retval = {}; for (var i = 0; i < elem.childNodes.length; i++) { var key = elem.childNodes[i].nodeName; if (typeof (key) != "string") continue; var val = this.parseElement(elem.childNodes[i]); if (!val) continue; if (typeof (cnt[key]) == "undefined") cnt[key] = 0; cnt[key]++; this.addNode(retval, key, cnt[key], val); } } } return retval; }; // method: addNode( hash, key, count, value ) XML.ObjTree.prototype.addNode = function (hash, key, cnts, val) { if (this.__force_array[key]) { if (cnts == 1) hash[key] = []; hash[key][hash[key].length] = val; // push } else if (cnts == 1) { // 1st sibling hash[key] = val; } else if (cnts == 2) { // 2nd sibling hash[key] = [hash[key], val]; } else { // 3rd sibling and more hash[key][hash[key].length] = val; } }; // method: writeXML( tree ) XML.ObjTree.prototype.writeXML = function (tree) { var xml = this.hash_to_xml(null, tree); return this.xmlDecl + xml; }; // method: hash_to_xml( tagName, tree ) XML.ObjTree.prototype.hash_to_xml = function (name, tree) { var elem = []; var attr = []; for (var key in tree) { if (!tree.hasOwnProperty(key)) continue; var val = tree[key]; if (key.charAt(0) != this.attr_prefix) { if (typeof (val) == "undefined" || val == null) { elem[elem.length] = "<" + key + " />"; } else if (typeof (val) == "object" && val.constructor == Array) { elem[elem.length] = this.array_to_xml(key, val); } else if (typeof (val) == "object") { elem[elem.length] = this.hash_to_xml(key, val); } else { elem[elem.length] = this.scalar_to_xml(key, val); } } else { attr[attr.length] = " " + (key.substring(1)) + '="' + (this.xml_escape(val)) + '"'; } } var jattr = attr.join(""); var jelem = elem.join(""); if (typeof (name) == "undefined" || name == null) { // no tag } else if (elem.length > 0) { if (jelem.match(/\n/)) { jelem = "<" + name + jattr + ">\n" + jelem + "</" + name + ">\n"; } else { jelem = "<" + name + jattr + ">" + jelem + "</" + name + ">\n"; } } else { jelem = "<" + name + jattr + " />\n"; } return jelem; }; // method: array_to_xml( tagName, array ) XML.ObjTree.prototype.array_to_xml = function (name, array) { var out = []; for (var i = 0; i < array.length; i++) { var val = array[i]; if (typeof (val) == "undefined" || val == null) { out[out.length] = "<" + name + " />"; } else if (typeof (val) == "object" && val.constructor == Array) { out[out.length] = this.array_to_xml(name, val); } else if (typeof (val) == "object") { out[out.length] = this.hash_to_xml(name, val); } else { out[out.length] = this.scalar_to_xml(name, val); } } return out.join(""); }; // method: scalar_to_xml( tagName, text ) XML.ObjTree.prototype.scalar_to_xml = function (name, text) { if (name == "#text") { return this.xml_escape(text); } else { return "<" + name + ">" + this.xml_escape(text) + "</" + name + ">\n"; } }; // method: xml_escape( text ) XML.ObjTree.prototype.xml_escape = function (text) { return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); }; /* // ======================================================================== =head1 NAME XML.ObjTree -- XML source code from/to JavaScript object like E4X =head1 SYNOPSIS var xotree = new XML.ObjTree(); var tree1 = { root: { node: "Hello, World!" } }; var xml1 = xotree.writeXML( tree1 ); // object tree to XML source alert( "xml1: "+xml1 ); var xml2 = '<?xml version="1.0"?><response><error>0</error></response>'; var tree2 = xotree.parseXML( xml2 ); // XML source to object tree alert( "error: "+tree2.response.error ); =head1 DESCRIPTION XML.ObjTree class is a parser/generater between XML source code and JavaScript object like E4X, ECMAScript for XML. This is a JavaScript version of the XML::TreePP module for Perl. This also works as a wrapper for XMLHTTPRequest and successor to JKL.ParseXML class when this is used with prototype.js or JSAN's HTTP.Request class. =head2 JavaScript object tree format A sample XML source: <?xml version="1.0" encoding="UTF-8"?> <family name="Kawasaki"> <father>Yasuhisa</father> <mother>Chizuko</mother> <children> <girl>Shiori</girl> <boy>Yusuke</boy> <boy>Kairi</boy> </children> </family> Its JavaScript object tree like JSON/E4X: { 'family': { '-name': 'Kawasaki', 'father': 'Yasuhisa', 'mother': 'Chizuko', 'children': { 'girl': 'Shiori' 'boy': [ 'Yusuke', 'Kairi' ] } } }; Each elements are parsed into objects: tree.family.father; # the father's given name. Prefix '-' is inserted before every attributes' name. tree.family["-name"]; # this family's family name A array is used because this family has two boys. tree.family.children.boy[0]; # first boy's name tree.family.children.boy[1]; # second boy's name tree.family.children.girl; # (girl has no other sisiters) =head1 METHODS =head2 xotree = new XML.ObjTree() This constructor method returns a new XML.ObjTree object. =head2 xotree.force_array = [ "rdf:li", "item", "-xmlns" ]; This property allows you to specify a list of element names which should always be forced into an array representation. The default value is null, it means that context of the elements will determine to make array or to keep it scalar. =head2 xotree.attr_prefix = '@'; This property allows you to specify a prefix character which is inserted before each attribute names. Instead of default prefix '-', E4X-style prefix '@' is also available. The default character is '-'. Or set '@' to access attribute values like E4X, ECMAScript for XML. The length of attr_prefix must be just one character and not be empty. =head2 tree = xotree.parseXML( xmlsrc ); This method loads an XML document using the supplied string and returns its JavaScript object converted. =head2 tree = xotree.parseDOM( domnode ); This method parses a DOM tree (ex. responseXML.documentElement) and returns its JavaScript object converted. =head2 tree = xotree.parseHTTP( url, options ); This method loads a XML file from remote web server and returns its JavaScript object converted. XMLHTTPRequest's synchronous mode is always used. This mode blocks the process until the response is completed. First argument is a XML file's URL which must exist in the same domain as parent HTML file's. Cross-domain loading is not available for security reasons. Second argument is options' object which can contains some parameters: method, postBody, parameters, onLoading, etc. This method requires JSAN's L<HTTP.Request> class or prototype.js's Ajax.Request class. =head2 xotree.parseHTTP( url, options, callback ); If a callback function is set as third argument, XMLHTTPRequest's asynchronous mode is used. This mode calls a callback function with XML file's JavaScript object converted after the response is completed. =head2 xmlsrc = xotree.writeXML( tree ); This method parses a JavaScript object tree and returns its XML source generated. =head1 EXAMPLES =head2 Text node and attributes If a element has both of a text node and attributes or both of a text node and other child nodes, text node's value is moved to a special node named "#text". var xotree = new XML.ObjTree(); var xmlsrc = '<span class="author">Kawasaki Yusuke</span>'; var tree = xotree.parseXML( xmlsrc ); var class = tree.span["-class"]; # attribute var name = tree.span["#text"]; # text node =head2 parseHTTP() method with HTTP-GET and sync-mode HTTP/Request.js or prototype.js must be loaded before calling this method. var xotree = new XML.ObjTree(); var url = "http://example.com/index.html"; var tree = xotree.parseHTTP( url ); xotree.attr_prefix = '@'; // E4X-style alert( tree.html["@lang"] ); This code shows C<lang=""> attribute from a X-HTML source code. =head2 parseHTTP() method with HTTP-POST and async-mode Third argument is a callback function which is called on onComplete. var xotree = new XML.ObjTree(); var url = "http://example.com/mt-tb.cgi"; var opts = { postBody: "title=...&excerpt=...&url=...&blog_name=..." }; var func = function ( tree ) { alert( tree.response.error ); }; xotree.parseHTTP( url, opts, func ); This code send a trackback ping and shows its response code. =head2 Simple RSS reader This is a RSS reader which loads RDF file and displays all items. var xotree = new XML.ObjTree(); xotree.force_array = [ "rdf:li", "item" ]; var url = "http://example.com/news-rdf.xml"; var func = function( tree ) { var elem = document.getElementById("rss_here"); for( var i=0; i<tree["rdf:RDF"].item.length; i++ ) { var divtag = document.createElement( "div" ); var atag = document.createElement( "a" ); atag.href = tree["rdf:RDF"].item[i].link; var title = tree["rdf:RDF"].item[i].title; var tnode = document.createTextNode( title ); atag.appendChild( tnode ); divtag.appendChild( atag ); elem.appendChild( divtag ); } }; xotree.parseHTTP( url, {}, func ); =head2 XML-RPC using writeXML, prototype.js and parseDOM If you wish to use prototype.js's Ajax.Request class by yourself: var xotree = new XML.ObjTree(); var reqtree = { methodCall: { methodName: "weblogUpdates.ping", params: { param: [ { value: "Kawa.net xp top page" }, // 1st param { value: "http://www.kawa.net/" } // 2nd param ] } } }; var reqxml = xotree.writeXML( reqtree ); // JS-Object to XML code var url = "http://example.com/xmlrpc"; var func = function( req ) { var resdom = req.responseXML.documentElement; xotree.force_array = [ "member" ]; var restree = xotree.parseDOM( resdom ); // XML-DOM to JS-Object alert( restree.methodResponse.params.param.value.struct.member[0].value.string ); }; var opt = { method: "post", postBody: reqxml, asynchronous: true, onComplete: func }; new Ajax.Request( url, opt ); =head1 AUTHOR Yusuke Kawasaki http://www.kawa.net/ =head1 COPYRIGHT AND LICENSE Copyright (c) 2005-2006 Yusuke Kawasaki. All rights reserved. This program is free software; you can redistribute it and/or modify it under the Artistic license. Or whatever license I choose, which I will do instead of keeping this documentation like it is. =cut // ======================================================================== */ export default XML;
the_stack
module BABYLONX { export class NoiseGen { private _color1 = "#c0dec9"; private _color2 = "#282226"; private _octaves = 6; private _persistence = .9; private _scale = 36.3; private _seed = 1; private _size = 250; private _percentage = .6; private _type = 2; private _ctx; rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2); } hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } setPerlinNoise(ctx, options) { //setPerlinNoise(ctx, size, color1, color2, type, octaves, persistence, scale, seed, percentage) { this._ctx = ctx; var color1 = options.color1 || this._color1; var color2 = options.color2 || this._color2; var size = options.size || this._size; var octaves = options.octaves || this._octaves; var persistence = options.persistence || this._persistence; var scale = options.scale || this.scale; var seed = options.seed || this._seed; var percentage = options.percentage || this._percentage; var type = options.type || this._type; //var type = "PerlinNoise"; //var c = canvas; //var ctx = c.getContext("2d"); var max_w = size, max_h = size; var S = new SimplexNoise(seed); var imgData = ctx.getImageData(0, 0, max_w, max_h); var d = imgData.data; var col1_rgb = this.hexToRgb(color1); var col2_rgb = this.hexToRgb(color2); var scale_s = scale; var before = new Date().getTime(); var noise_type; if (type == 0) //(type == "PerlinNoise") noise_type = 0; else if (type == 1)//(type == "FractalNoise") noise_type = 1; else if (type == 2)//(type == "Turbulence") noise_type = 2; for (var y = 0; y < max_h; y++) for (var x = 0; x < max_w; x++) { // octaves, persistence, scale, loBound, hiBound, x, y var v = S.simplexNoise(noise_type, size, octaves, persistence, percentage, scale_s, x, y); //v = v * lo_hi_mul + lo_hi_add; // not sure what this does... //if (type == "PerlinNoise") //v = (v + 1.0) / 2.0; //interval [0,1]. var i = (x + y * max_w) * 4; d[i] = v * col1_rgb.r + ((1.0 - v) * col2_rgb.r); d[i + 1] = v * col1_rgb.g + ((1.0 - v) * col2_rgb.g); d[i + 2] = v * col1_rgb.b + ((1.0 - v) * col2_rgb.b); d[i + 3] = 255; } var after = new Date().getTime(); //console.log("noise: " + (after-before)); ctx.putImageData(imgData, 0, 0); } update() { this.setPerlinNoise(this._ctx, {}); } get color1() { return this._color1; } set color1(c) { this._color1 = c; this.update(); } get color2() { return this._color2; } set color2(c) { this._color2 = c; this.update(); } get octaves() { return this._octaves; } set octaves(o) { this._octaves = o; this.update(); } get persistence() { return this._persistence; } set persistence(o) { this._persistence = o; this.update(); } get scale() { return this._scale; } set scale(o) { this._scale = o; this.update(); } get seed() { return this._seed; } set seed(o) { this._seed = o; this.update(); } get percentage() { return this._percentage; } set percentage(o) { this._percentage = o; this.update(); } get type() { return this._type; } set type(o) { this._type = o; this.update(); } } export class TexGen { /* Original from Author: Christian Petry Homepage: www.petry-christian.de * Adapted by: Author: Johann Langhofer Homepage: johann.langhofer.net */ private _brick_color = "#b90000"; private _grout_color = "#e4ff66"; private _gradient_color = "#000000"; private _grout_space = 1; private _brick_gradient = 3; private _number = 0; private _width = 32; private _height = 32; private _numWidth = 8; private _numHeight = 8; private _rotation = 0; private _ctx; rational_tanh(x) { if (x < -3) return -1; else if (x > 3) return 1; else return x * (27 + x * x) / (27 + 9 * x * x); } calcTextilesPattern(x, y, patterndirection, patternpart, facetlength, delta_in, smoothness, offset, steepness, depth, round) { var PatternPart = { TOP: 0, MIDDLE: 1, BOTTOM: 2, BLOCK: 3 } var PatternDirection = { HORIZONTAL: 0, VERTICAL: 1 } var delta = 1.0 / (8.0 - delta_in); var TwistTrajectory = ((Math.asin(2.0 * y - 1.0) / (Math.PI / 2.0) + 1.0) * facetlength) / 2.0; var displacement = 2.0 * ((x + TwistTrajectory) - (x + TwistTrajectory) / delta * delta) / delta - 1.0; // added an extra "/ delta " to fix sth var rand_value = Math.random() * delta; // [0, delta) var pdisplacement = smoothness * displacement + (1.0 - smoothness) * rand_value; //console.log(pdis_quad); var TwistShading = Math.exp(-Math.abs(Math.pow(pdisplacement * depth, round ? 2 : 1))); var YShading = offset + (1.0 - offset) * Math.sin(y * Math.PI); /*if (patterndirection == PatternDirection.HORIZONTAL){ if ((patternpart == PatternPart.TOP && x < 0.5) || (patternpart == PatternPart.BOTTOM && x > 0.5) || (patternpart == PatternPart.BLOCK)) YShading = offset + (1.0 - offset) * Math.sin(y * Math.PI); else YShading = 1; }*/ var tanh_value = 0.5 * steepness; //var tanh = (Math.exp(tanh_value) - Math.exp(-tanh_value)) / (Math.exp(tanh_value) + Math.exp(-tanh_value)); var shading_border = 0.5; if (patterndirection == PatternDirection.VERTICAL) if ((patternpart == PatternPart.TOP && x < shading_border) || (patternpart == PatternPart.BOTTOM && x > shading_border) || (patternpart == PatternPart.BLOCK)) { if (x < shading_border) tanh_value = x * steepness; else if (x > shading_border) tanh_value = (1.0 - x) * steepness; } if (patterndirection == PatternDirection.HORIZONTAL) if ((patternpart == PatternPart.TOP && x < shading_border) || (patternpart == PatternPart.BOTTOM && x > shading_border) || (patternpart == PatternPart.BLOCK)) if (x < shading_border) tanh_value = x * steepness; else if (x > shading_border) tanh_value = (1.0 - x) * steepness; var XShading = offset + (1.0 - offset) * this.rational_tanh(tanh_value); //XShading = XShading * (x < 0.5 ? (1 - x) : x) var ThreadShading = TwistShading * XShading * YShading; return ThreadShading; } createTextilesPattern(canvas, patterndirection, patternpart, width, height, facetlength, delta, smoothness, offset, steepness, depth, round, col, col_bg) { canvas.width = width; canvas.height = height; var ctx = canvas.getContext('2d'); var imgData1 = ctx.getImageData(0, 0, canvas.width, canvas.height); var data1 = imgData1.data; var PatternDirection = { HORIZONTAL: 0, VERTICAL: 1 } for (var x = 0; x < canvas.width; x++) { for (var y = 0; y < canvas.height; y++) { var first = (patterndirection == PatternDirection.VERTICAL ? y / canvas.height : x / canvas.width); var second = (patterndirection == PatternDirection.VERTICAL ? x / canvas.height : y / canvas.width); var v = this.calcTextilesPattern(first, second, patterndirection, patternpart, facetlength, delta, smoothness, offset, steepness, depth, round); data1[(x + y * canvas.width) * 4 + 0] = v * col.r + ((1.0 - v) * col_bg.r); data1[(x + y * canvas.width) * 4 + 1] = v * col.g + ((1.0 - v) * col_bg.g); data1[(x + y * canvas.width) * 4 + 2] = v * col.b + ((1.0 - v) * col_bg.b); data1[(x + y * canvas.width) * 4 + 3] = 255; } } ctx.putImageData(imgData1, 0, 0); //ctx.scale( max_w/ img.width, img.height); //ctx.drawImage(canvas, 0,0); return ctx.createPattern(canvas, "repeat"); } setTextiles(ctx, img, max_w, max_h, scale, col1_rgb, col2_rgb, col_bg, facetlength, delta, smoothness, offset, steepness, depth, round) { var PatternPart = { TOP: 0, MIDDLE: 1, BOTTOM: 2, BLOCK: 3 } var PatternDirection = { HORIZONTAL: 0, VERTICAL: 1 } var width = max_w / (img.width * scale) + 0.5; var height = max_h / (img.height * scale) + 0.5; var c_p1_block = document.createElement('canvas'); var pat1_block = this.createTextilesPattern(c_p1_block, PatternDirection.VERTICAL, PatternPart.BLOCK, width, height, facetlength, delta, smoothness, offset, steepness, depth, round, col1_rgb, col_bg); var c_p1_middle = document.createElement('canvas'); var pat1_middle = this.createTextilesPattern(c_p1_middle, PatternDirection.VERTICAL, PatternPart.MIDDLE, width, height, facetlength, delta, smoothness, offset, steepness, depth, round, col1_rgb, col_bg); var c_p1_top = document.createElement('canvas'); var pat1_top = this.createTextilesPattern(c_p1_top, PatternDirection.VERTICAL, PatternPart.TOP, width, height, facetlength, delta, smoothness, offset, steepness, depth, round, col1_rgb, col_bg); var c_p1_bottom = document.createElement('canvas'); var pat1_bottom = this.createTextilesPattern(c_p1_bottom, PatternDirection.VERTICAL, PatternPart.BOTTOM, width, height, facetlength, delta, smoothness, offset, steepness, depth, round, col1_rgb, col_bg); var c_p2_block = document.createElement('canvas'); var pat2_block = this.createTextilesPattern(c_p2_block, PatternDirection.HORIZONTAL, PatternPart.BLOCK, height, width, facetlength, delta, smoothness, offset, steepness, depth, round, col2_rgb, col_bg); var c_p2_middle = document.createElement('canvas'); var pat2_middle = this.createTextilesPattern(c_p2_middle, PatternDirection.HORIZONTAL, PatternPart.MIDDLE, height, width, facetlength, delta, smoothness, offset, steepness, depth, round, col2_rgb, col_bg); var c_p2_top = document.createElement('canvas'); var pat2_top = this.createTextilesPattern(c_p2_top, PatternDirection.HORIZONTAL, PatternPart.TOP, height, width, facetlength, delta, smoothness, offset, steepness, depth, round, col2_rgb, col_bg); var c_p2_bottom = document.createElement('canvas'); var pat2_bottom = this.createTextilesPattern(c_p2_bottom, PatternDirection.HORIZONTAL, PatternPart.BOTTOM, height, width, facetlength, delta, smoothness, offset, steepness, depth, round, col2_rgb, col_bg); var c_ptrn = document.createElement('canvas'); var ctx_ptrn = c_ptrn.getContext('2d'); ctx_ptrn.imageSmoothingEnabled = false; for (var i = 0; i < scale; i++) { ctx_ptrn.drawImage(img, 0, 0, img.width, img.height); if (i >= 1) { for (var x = 0; x < i; x++) ctx_ptrn.drawImage(img, img.width * x, img.height * i, img.width, img.height); for (var y = 0; y < i; y++) ctx_ptrn.drawImage(img, img.width * i, img.height * y, img.width, img.height); ctx_ptrn.drawImage(img, img.width * i, img.height * i, img.width, img.height); } } var imgData3 = ctx_ptrn.getImageData(0, 0, img.width * scale, img.height * scale); var data3 = imgData3.data; //console.log(img.width); //ctx.fillStyle = pat1; //ctx.fillRect(0, 0, max_w / img.width, max_h / img.height); var width_mul = max_w / imgData3.width; var height_mul = max_h / imgData3.height; for (var y = 0; y < imgData3.height; y++) { for (var x = 0; x < imgData3.width; x++) { var pos = x * 4 + y * imgData3.width * 4 + 0; // vertical color if (data3[pos] == 0) { var top = x * 4 + ((y - 1) < 0 ? y - 1 + imgData3.width : y - 1) * imgData3.width * 4; var bottom = x * 4 + ((y + 1) == imgData3.width ? 0 : y + 1) * imgData3.width * 4; if (data3[top] == 0 && data3[bottom] == 0) { ctx.fillStyle = pat1_middle; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else if (data3[top] == 0 && data3[bottom] != 0) { ctx.fillStyle = pat1_bottom; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else if (data3[top] != 0 && data3[bottom] == 0) { ctx.fillStyle = pat1_top; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else { ctx.fillStyle = pat1_block; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } } // horizontal color else { var left = ((x - 1) < 0 ? x - 1 + imgData3.width : x - 1) * 4 + y * imgData3.width * 4; var right = ((x + 1) == imgData3.width ? 0 : x + 1) * 4 + y * imgData3.width * 4; if (data3[left] != 0 && data3[right] == 0) { ctx.fillStyle = pat2_bottom; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else if (data3[left] == 0 && data3[right] != 0) { ctx.fillStyle = pat2_top; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else if (data3[left] != 0 && data3[right] != 0) { ctx.fillStyle = pat2_middle; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } else { ctx.fillStyle = pat2_block; ctx.fillRect(x * width_mul, y * height_mul, width_mul, height_mul); } } } } /* var helper = function (fn) { 'use strict'; fn(); } var do_strict=function() { delete c_p1_block; delete c_p1_middle; delete c_p1_top; delete c_p1_bottom; delete c_p2_block; delete c_p2_middle; delete c_p2_top; delete c_p2_bottom; delete c_ptrn; delete img; } helper(do_strict); */ }; drawBrickRectangle(ctx, groutspace, brick_gradient, brick_col, brick_grout_col, gradient_color, x, y, w, h) { brick_gradient = Math.min(brick_gradient, Math.min((h - groutspace * 2) / 2, (w - groutspace * 2) / 2)); /* ctx.fillStyle = brick_grout_col; ctx.fillRect(x, Math.max(y,0), w, h); ctx.fillStyle = brick_col; ctx.fillRect(x + groutspace, y + groutspace < 0 ? 0 : y + groutspace , w - groutspace*2, y + groutspace < 0 ? h - groutspace : h - groutspace*2); */ ctx.fillStyle = brick_grout_col; ctx.fillRect(x, Math.max(y, 0), w, h); var grad = ctx.createLinearGradient(0, y, 0, y + h); var max_d = h; grad.addColorStop(0, brick_grout_col); grad.addColorStop(groutspace / max_d, brick_grout_col); grad.addColorStop(groutspace / max_d, gradient_color); grad.addColorStop((groutspace + brick_gradient) / max_d, brick_col); grad.addColorStop((h - groutspace - brick_gradient) / max_d, brick_col); grad.addColorStop((h - groutspace) / max_d, gradient_color); grad.addColorStop((h - groutspace) / max_d, brick_grout_col); grad.addColorStop(1.0, brick_grout_col); ctx.fillStyle = grad; ctx.fillRect(x + groutspace, y + groutspace < 0 ? 0 : y + groutspace, w - groutspace * 2, y + groutspace < 0 ? h - groutspace : h - groutspace * 2); //ctx.fillStyle = gradient([0, y, 0, h], ctx, y, groutspace, brick_col, brick_grout_col, gradient_color); //ctx.fillRect(x, y, w, h); ctx.save(); var mid_x = w / 2 + x; var mid_y = h / 2 + y; ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x + groutspace, y + groutspace); ctx.lineTo(x + groutspace + brick_gradient, y + groutspace + brick_gradient); ctx.lineTo(mid_x, mid_y); ctx.lineTo(w + x - brick_gradient - groutspace, h + y - brick_gradient - groutspace); ctx.lineTo(w + x - brick_gradient, h + y - brick_gradient); ctx.lineTo(w + x, y + h); ctx.lineTo(w + x, y); ctx.lineTo(w + x - groutspace, y + groutspace); ctx.lineTo(w + x - brick_gradient - groutspace, y + groutspace + brick_gradient); ctx.lineTo(mid_x, mid_y); ctx.lineTo(x + brick_gradient + groutspace, h + y - brick_gradient - groutspace); ctx.lineTo(x + groutspace, h + y - groutspace); ctx.lineTo(x, h + y); ctx.lineTo(x, y); ctx.clip(); grad = ctx.createLinearGradient(x, 0, x + w, 0); max_d = w; grad.addColorStop(0, brick_grout_col); grad.addColorStop(groutspace / max_d, brick_grout_col); grad.addColorStop(groutspace / max_d, gradient_color); grad.addColorStop((groutspace + brick_gradient) / max_d, brick_col); grad.addColorStop((w - groutspace - brick_gradient) / max_d, brick_col); grad.addColorStop((w - groutspace) / max_d, gradient_color); grad.addColorStop((w - groutspace) / max_d, brick_grout_col); grad.addColorStop(1.0, brick_grout_col); ctx.fillStyle = grad; //ctx.fillStyle = gradient([x, 0, w, 0], ctx, tile_part_x, hori_gap, x_tiles_gradient, tile_col_hex, grout_col_hex, tiles_smooth_col, grout_gradient_color); ctx.fillRect(x + groutspace, y + groutspace < 0 ? 0 : y + groutspace, w - groutspace * 2, y + groutspace < 0 ? h - groutspace : h - groutspace * 2); ctx.restore(); } rotate(ctx, rotation) { var max_w = 250; var max_h = 250; ctx.beginPath(); ctx.rect(0, 0, max_w, max_h); ctx.translate(max_w / 2, max_h / 2); ctx.rotate(rotation); ctx.translate(-max_w / 2, -max_h / 2); var pat = ctx.createPattern(ctx.canvas, "repeat"); ctx.clearRect(-max_w / 2, -max_h / 2, max_w / 2, max_h / 2); ctx.fillStyle = pat; ctx.fill(); ctx.translate(max_w / 2, max_h / 2); ctx.rotate(-rotation); ctx.translate(-max_w / 2, -max_h / 2); } createPattern(ctx, options) { var max_w = 250; var max_h = 250; if (options.number != null) { this._number = Number(options.number); } switch (this._number) { case 0: this.createStraightPattern(ctx, options); break; case 1: this.createWideBlockPattern(ctx, options); break; case 2: this.createBlockPattern(ctx, options); break; case 3: this.createCirclePattern(ctx, options); break; case 4: this.createEdgesPattern(ctx, options); break; } if (this._rotation != 0) { this.rotate(ctx, this._rotation); } } createStraightPattern(ctx, options) { this._ctx = ctx; this._width = options.width || this._width; this._height = options.height || this._height; this._numWidth = options.numWidth || this._numWidth; this._numHeight = options.numHeight || this._numHeight; this._grout_space = options.groutspace || this._grout_space; this._brick_gradient = options.brick_gradient || this._brick_gradient; this._brick_color = options.brick_color || this._brick_color; this._grout_color = options.grout_color || this._grout_color; this._gradient_color = options.gradient_color || this._gradient_color; var half_height = this._height / 2.0 + 0.5; for (var y = 0; y < this._numHeight + 1; y++) { for (var x = 0; x < this._numWidth + 1; x++) { if (x % 2 == 1) { this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * this._width, y * this._height - half_height, this._width, this._height); } else this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * this._width, y * this._height, this._width, this._height); } } } createBlockPattern(ctx, options) { this._ctx = ctx; this._width = options.width || this._width; this._height = options.height || this._height; this._numWidth = options.numWidth || this._numWidth; this._numHeight = options.numHeigth || this._numHeight; this._grout_color = options.grout_color || this._grout_color; this._grout_space = options.groutspace || this._grout_space; this._brick_gradient = options.brick_gradient || this._brick_gradient; this._brick_color = options.brick_color || this._brick_color; var width = this._width / 2.0 + 0.5; var height = this._height / 2.0 + 0.5; var count_y = this._numHeight * 2; var count_x = this._numWidth * 2; ctx.fillStyle = this._grout_color; ctx.fillRect(0, 0, 256, 256); for (var y = 0; y < count_y + 1; y += 2) { for (var x = 0; x < count_x + 1; x += 3) { if ((x + y) % 4 == 0) { this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * width, y * height, width, height * 2); this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * width + width, y * height, width, height); } else { this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * width, y * height, width * 2, height); this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this._gradient_color, x * width, y * height + height, width * 2, height); } } } } createWideBlockPattern(ctx, options) { this._ctx = ctx; this._width = options.width || this._width; this._height = options.height || this._height; this._numWidth = options.numWidth || this._numWidth; this._numHeight = options.numHeigth || this._numHeight; this._grout_color = options.grout_color || this._grout_color; this._grout_space = options.groutspace || this._grout_space; this._brick_gradient = options.brick_gradient || this._brick_gradient; this._brick_color = options.brick_color || this._brick_color; var width = this._width / 2.0 + 0.5; var height = this._height / 2.0 + 0.5; var count_y = this._numHeight * 2; var count_x = this._numWidth * 2; ctx.fillStyle = this._grout_color; ctx.fillRect(0, 0, 256, 256); for (var y = 0; y < count_y + 1; y += 2) { for (var x = 0; x < count_x + 1; x += 3) { this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this.gradient_color, x * width, y * height, width, height * 2); this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this.gradient_color, x * width + width, y * height, width * 2, height); this.drawBrickRectangle(ctx, this._grout_space, this._brick_gradient, this._brick_color, this._grout_color, this.gradient_color, x * width + width, y * height + height, width * 2, height); } } } createCirclePattern(ctx, options) { this._ctx = ctx; this._width = options.width || this._width; this._height = options.height || this._height; this._numWidth = options.numWidth || this._numWidth; this._numHeight = options.numHeigth || this._numHeight; this._grout_color = options.grout_color || this._grout_color; this._grout_space = options.groutspace || this._grout_space; this._brick_gradient = options.brick_gradient || this._brick_gradient; this._brick_color = options.brick_color || this._brick_color; var width = this._width / 3.0 + 0.5; var height = this._height / 3.0 + 0.5; var count_y = this._numHeight * 3; var count_x = this._numWidth * 3; for (var y = 0; y < count_y + 1; y += 3) { for (var x = 0; x < count_x + 1; x += 3) { this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width, y * height, width * 2, height); this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width + width, y * height + 2 * height, width * 2, height); this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width, y * height + height, width, height * 2); this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width + 2 * width, y * height, width, height * 2); this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width + width, y * height + height, width, height); } } } createEdgesPattern(ctx, options) { this._ctx = ctx; this._width = options.width || this._width; this._height = options.height || this._height; this._numWidth = options.numWidth || this._numWidth; this._numHeight = options.numHeigth || this._numHeight; this._grout_color = options.grout_color || this._grout_color; this._grout_space = options.groutspace || this._grout_space; this._brick_gradient = options.brick_gradient || this._brick_gradient; this._brick_color = options.brick_color || this._brick_color; var width = this._width / 2.0 + 0.5; var height = this._height / 2.0 + 0.5; var count_y = this._numHeight * 2; var count_x = this._numWidth * 2; ctx.translate(-width, -height); for (var y = 0; y < count_y + 2; y++) { for (var x = 0; x < count_x + 2; x++) { if (y % 4 == x % 4) this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width, y * height, width * 2, height); else if (y % 4 == (x % 4 + 1) || (y % 4 == 0 && x % 4 == 3)) this.drawBrickRectangle(ctx, this._grout_space, this.brick_gradient, this.brick_color, this.grout_color, this.gradient_color, x * width, y * height, width, height * 2); } } ctx.translate(width, height); } set brick_gradient(g) { this._brick_gradient = g; this.createPattern(this._ctx, {}); } get brick_gradient() { return this._brick_gradient; } set brick_color(c) { this._brick_color = c; this.createPattern(this._ctx, {}); } get brick_color() { return this._brick_color; } set grout_color(c) { this._grout_color = c; this.createPattern(this._ctx, {}); } get grout_color() { return this._grout_color; } get grout_space() { return this._grout_space; } set grout_space(n) { this._grout_space = n; this.createPattern(this._ctx, {}); } set gradient_color(c) { this._gradient_color = c; this.createPattern(this._ctx, {}); } get gradient_color() { return this._gradient_color; } get number() { return this._number; } set number(n) { this._number = n; this.createPattern(this._ctx, {}); } get width() { return this._width; } set width(n) { this._width = n; this.createPattern(this._ctx, {}); } get height() { return this._height; } set height(n) { this._height = n; this.createPattern(this._ctx, {}); } get numWidth() { return this._numWidth; } set numWidth(n) { this._numWidth = n; this.createPattern(this._ctx, {}); } get numHeight() { return this._numHeight; } set numHeight(n) { this._numHeight = n; this.createPattern(this._ctx, {}); } get rotation() { return this._rotation; } set rotation(r) { this._rotation = r; this.createPattern(this._ctx, {}); } } }
the_stack
import { assert } from '@0x/assert'; import { addressUtils } from '@0x/utils'; import EthereumTx = require('ethereumjs-tx'); import ethUtil = require('ethereumjs-util'); import HDNode = require('hdkey'); import * as _ from 'lodash'; import { Lock } from 'semaphore-async-await'; import { DerivedHDKeyInfo, LedgerEthereumClient, LedgerEthereumClientFactoryAsync, LedgerSubproviderConfigs, LedgerSubproviderErrors, PartialTxParams, WalletSubproviderErrors, } from '../types'; import { walletUtils } from '../utils/wallet_utils'; import { BaseWalletSubprovider } from './base_wallet_subprovider'; const DEFAULT_BASE_DERIVATION_PATH = `44'/60'/0'`; const ASK_FOR_ON_DEVICE_CONFIRMATION = false; const SHOULD_GET_CHAIN_CODE = true; const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10; const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000; /** * Subprovider for interfacing with a user's [Ledger Nano S](https://www.ledgerwallet.com/products/ledger-nano-s). * This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and * re-routes them to a Ledger device plugged into the users computer. */ export class LedgerSubprovider extends BaseWalletSubprovider { // tslint:disable-next-line:no-unused-variable private readonly _connectionLock = new Lock(); private readonly _networkId: number; private _baseDerivationPath: string; private readonly _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync; private _ledgerClientIfExists?: LedgerEthereumClient; private readonly _shouldAlwaysAskForConfirmation: boolean; private readonly _addressSearchLimit: number; /** * Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`. * TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired. * @param config Several available configurations * @return LedgerSubprovider instance */ constructor(config: LedgerSubproviderConfigs) { super(); this._networkId = config.networkId; this._ledgerEthereumClientFactoryAsync = config.ledgerEthereumClientFactoryAsync; this._baseDerivationPath = config.baseDerivationPath || DEFAULT_BASE_DERIVATION_PATH; this._shouldAlwaysAskForConfirmation = config.accountFetchingConfigs !== undefined && config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation !== undefined ? config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation : ASK_FOR_ON_DEVICE_CONFIRMATION; this._addressSearchLimit = config.accountFetchingConfigs !== undefined && config.accountFetchingConfigs.addressSearchLimit !== undefined ? config.accountFetchingConfigs.addressSearchLimit : DEFAULT_ADDRESS_SEARCH_LIMIT; } /** * Retrieve the set derivation path * @returns derivation path */ public getPath(): string { return this._baseDerivationPath; } /** * Set a desired derivation path when computing the available user addresses * @param basDerivationPath The desired derivation path (e.g `44'/60'/0'`) */ public setPath(basDerivationPath: string): void { this._baseDerivationPath = basDerivationPath; } /** * Retrieve a users Ledger accounts. The accounts are derived from the derivationPath, * master public key and chain code. Because of this, you can request as many accounts * as you wish and it only requires a single request to the Ledger device. This method * is automatically called when issuing a `eth_accounts` JSON RPC request via your providerEngine * instance. * @param numberOfAccounts Number of accounts to retrieve (default: 10) * @return An array of accounts */ public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise<string[]> { const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); const derivedKeyInfos = walletUtils.calculateDerivedHDKeyInfos(initialDerivedKeyInfo, numberOfAccounts); const accounts = _.map(derivedKeyInfos, k => k.address); return accounts; } /** * Signs a transaction on the Ledger with the account specificed by the `from` field in txParams. * If you've added the LedgerSubprovider to your app's provider, you can simply send an `eth_sendTransaction` * JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine * instance, you can call it directly. * @param txParams Parameters of the transaction to sign * @return Signed transaction hex string */ public async signTransactionAsync(txParams: PartialTxParams): Promise<string> { LedgerSubprovider._validateTxParams(txParams); if (txParams.from === undefined || !addressUtils.isAddress(txParams.from)) { throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid); } const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, txParams.from); this._ledgerClientIfExists = await this._createLedgerClientAsync(); const tx = new EthereumTx(txParams); // Set the EIP155 bits const vIndex = 6; tx.raw[vIndex] = Buffer.from([this._networkId]); // v const rIndex = 7; tx.raw[rIndex] = Buffer.from([]); // r const sIndex = 8; tx.raw[sIndex] = Buffer.from([]); // s const txHex = tx.serialize().toString('hex'); try { const fullDerivationPath = derivedKeyInfo.derivationPath; const result = await this._ledgerClientIfExists.signTransaction(fullDerivationPath, txHex); // Store signature in transaction tx.r = Buffer.from(result.r, 'hex'); tx.s = Buffer.from(result.s, 'hex'); tx.v = Buffer.from(result.v, 'hex'); // EIP155: v should be chain_id * 2 + {35, 36} const eip55Constant = 35; const signedChainId = Math.floor((tx.v[0] - eip55Constant) / 2); if (signedChainId !== this._networkId) { await this._destroyLedgerClientAsync(); const err = new Error(LedgerSubproviderErrors.TooOldLedgerFirmware); throw err; } const signedTxHex = `0x${tx.serialize().toString('hex')}`; await this._destroyLedgerClientAsync(); return signedTxHex; } catch (err) { await this._destroyLedgerClientAsync(); throw err; } } /** * Sign a personal Ethereum signed message. The signing account will be the account * associated with the provided address. * The Ledger adds the Ethereum signed message prefix on-device. If you've added * the LedgerSubprovider to your app's provider, you can simply send an `eth_sign` * or `personal_sign` JSON RPC request, and this method will be called auto-magically. * If you are not using this via a ProviderEngine instance, you can call it directly. * @param data Hex string message to sign * @param address Address of the account to sign with * @return Signature hex string (order: rsv) */ public async signPersonalMessageAsync(data: string, address: string): Promise<string> { if (data === undefined) { throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage); } assert.isHexString('data', data); assert.isETHAddressHex('address', address); const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync(); const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, address); this._ledgerClientIfExists = await this._createLedgerClientAsync(); try { const fullDerivationPath = derivedKeyInfo.derivationPath; const result = await this._ledgerClientIfExists.signPersonalMessage( fullDerivationPath, ethUtil.stripHexPrefix(data), ); const lowestValidV = 27; const v = result.v - lowestValidV; const hexBase = 16; let vHex = v.toString(hexBase); if (vHex.length < 2) { vHex = `0${v}`; } const signature = `0x${result.r}${result.s}${vHex}`; await this._destroyLedgerClientAsync(); return signature; } catch (err) { await this._destroyLedgerClientAsync(); throw err; } } /** * eth_signTypedData is currently not supported on Ledger devices. * @param address Address of the account to sign with * @param data the typed data object * @return Signature hex string (order: rsv) */ // tslint:disable-next-line:prefer-function-over-method public async signTypedDataAsync(address: string, typedData: any): Promise<string> { throw new Error(WalletSubproviderErrors.MethodNotSupported); } private async _createLedgerClientAsync(): Promise<LedgerEthereumClient> { await this._connectionLock.acquire(); if (this._ledgerClientIfExists !== undefined) { this._connectionLock.release(); throw new Error(LedgerSubproviderErrors.MultipleOpenConnectionsDisallowed); } const ledgerEthereumClient = await this._ledgerEthereumClientFactoryAsync(); this._connectionLock.release(); return ledgerEthereumClient; } private async _destroyLedgerClientAsync(): Promise<void> { await this._connectionLock.acquire(); if (this._ledgerClientIfExists === undefined) { this._connectionLock.release(); return; } await this._ledgerClientIfExists.transport.close(); this._ledgerClientIfExists = undefined; this._connectionLock.release(); } private async _initialDerivedKeyInfoAsync(): Promise<DerivedHDKeyInfo> { this._ledgerClientIfExists = await this._createLedgerClientAsync(); const parentKeyDerivationPath = `m/${this._baseDerivationPath}`; let ledgerResponse; try { ledgerResponse = await this._ledgerClientIfExists.getAddress( parentKeyDerivationPath, this._shouldAlwaysAskForConfirmation, SHOULD_GET_CHAIN_CODE, ); } finally { await this._destroyLedgerClientAsync(); } const hdKey = new HDNode(); hdKey.publicKey = new Buffer(ledgerResponse.publicKey, 'hex'); hdKey.chainCode = new Buffer(ledgerResponse.chainCode, 'hex'); const address = walletUtils.addressOfHDKey(hdKey); const initialDerivedKeyInfo = { hdKey, address, derivationPath: parentKeyDerivationPath, baseDerivationPath: this._baseDerivationPath, }; return initialDerivedKeyInfo; } private _findDerivedKeyInfoForAddress(initalHDKey: DerivedHDKeyInfo, address: string): DerivedHDKeyInfo { const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists( address, initalHDKey, this._addressSearchLimit, ); if (matchedDerivedKeyInfo === undefined) { throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`); } return matchedDerivedKeyInfo; } }
the_stack
import { action } from "mobx"; import Cartesian2 from "terriajs-cesium/Source/Core/Cartesian2"; import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3"; import Cartographic from "terriajs-cesium/Source/Core/Cartographic"; import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid"; import EllipsoidTerrainProvider from "terriajs-cesium/Source/Core/EllipsoidTerrainProvider"; import KeyboardEventModifier from "terriajs-cesium/Source/Core/KeyboardEventModifier"; import CesiumMath from "terriajs-cesium/Source/Core/Math"; import Matrix3 from "terriajs-cesium/Source/Core/Matrix3"; import Quaternion from "terriajs-cesium/Source/Core/Quaternion"; import sampleTerrainMostDetailed from "terriajs-cesium/Source/Core/sampleTerrainMostDetailed"; import ScreenSpaceEventHandler from "terriajs-cesium/Source/Core/ScreenSpaceEventHandler"; import ScreenSpaceEventType from "terriajs-cesium/Source/Core/ScreenSpaceEventType"; import Scene from "terriajs-cesium/Source/Scene/Scene"; import filterOutUndefined from "../../../Core/filterOutUndefined"; import makeRealPromise from "../../../Core/makeRealPromise"; import Cesium from "../../../Models/Cesium"; type Movement = | "forward" | "backward" | "left" | "right" | "up" | "down" | "look"; export type Mode = "walk" | "fly"; const KeyMap: Record<KeyboardEvent["code"], Movement> = { KeyW: "forward", KeyA: "left", KeyS: "backward", KeyD: "right", Space: "up", ShiftLeft: "down", ShiftRight: "down" }; export default class MovementsController { // Current mode mode: Mode = "walk"; // Current active movements activeMovements: Set<Movement> = new Set(); // Latest estimate of the height of the surface from the ellipsoid currentSurfaceHeightEstimate: number; // True if we are currently updating surface height estimate isUpdatingSurfaceHeightEstimate = false; // True if we are currently animating surface height change isAnimatingSurfaceHeightChange = false; // The position of the mouse when a mouse action is started private startMousePosition?: Cartesian2; // The latest position of the mouse while the action is active private currentMousePosition?: Cartesian2; constructor( readonly cesium: Cesium, readonly onMove: () => void, readonly pedestrianHeight: number, readonly maxVerticalLookAngle: number ) { this.currentSurfaceHeightEstimate = this.camera.positionCartographic.height; this.updateSurfaceHeightEstimate(); } get scene() { return this.cesium.scene; } get camera() { return this.scene.camera; } get currentPedestrianHeightFromSurface() { return ( this.camera.positionCartographic.height - this.currentSurfaceHeightEstimate ); } /** * moveAmount decides the motion speed. */ get moveAmount() { // A higher value means more speed. // High speed at lower heights and fastly changing terrain // can cause jittery, unpleasant movement. const baseAmount = 0.2; return this.mode === "walk" ? baseAmount : // In fly mode we want higher speeds as greater heights Math.max(baseAmount, this.currentPedestrianHeightFromSurface / 100); } /** * Moves the camera forward and parallel to the surface by moveAmount */ moveForward() { const direction = projectVectorToSurface( this.camera.direction, this.camera.position, this.scene.globe.ellipsoid ); this.camera.move(direction, this.moveAmount); } /** * Moves the camera backward and parallel to the surface by moveAmount */ moveBackward() { const direction = projectVectorToSurface( this.camera.direction, this.camera.position, this.scene.globe.ellipsoid ); this.camera.move(direction, -this.moveAmount); } /** * Moves the camera left and parallel to the surface by moveAmount/4 */ moveLeft() { const direction = projectVectorToSurface( this.camera.right, this.camera.position, this.scene.globe.ellipsoid ); this.camera.move(direction, -this.moveAmount / 4); } /** * Moves the camera right and parallel to the surface by moveAmount/4 */ moveRight() { const direction = projectVectorToSurface( this.camera.right, this.camera.position, this.scene.globe.ellipsoid ); this.camera.move(direction, this.moveAmount / 4); } /** * Moves the camera up and perpendicular to the surface by moveAmount */ moveUp() { const surfaceNormal = this.scene.globe.ellipsoid.geodeticSurfaceNormal( this.camera.position, new Cartesian3() ); this.camera.move(surfaceNormal, this.moveAmount); } /** * Moves the camera up and perpendicular to the surface by moveAmount */ moveDown() { const surfaceNormal = this.scene.globe.ellipsoid.geodeticSurfaceNormal( this.camera.position, new Cartesian3() ); this.camera.move(surfaceNormal, -this.moveAmount); } look() { if ( this.startMousePosition === undefined || this.currentMousePosition === undefined ) return; const startMousePosition = this.startMousePosition; const currentMousePosition = this.currentMousePosition; const camera = this.scene.camera; const canvas = this.scene.canvas; const width = canvas.width; const height = canvas.height; const x = (currentMousePosition.x - startMousePosition.x) / width; const y = (currentMousePosition.y - startMousePosition.y) / height; const lookFactor = 0.1; const ellipsoid = this.scene.globe.ellipsoid; const surfaceNormal = ellipsoid.geodeticSurfaceNormal( camera.position, new Cartesian3() ); const surfaceTangent = projectVectorToSurface( camera.right, camera.position, this.scene.globe.ellipsoid ); // Look left/right about the surface normal camera.look(surfaceNormal, x * lookFactor); // Look up/down about the surface tangent this.lookVertical(surfaceTangent, surfaceNormal, y * lookFactor); } /** * Look up/down limiting the maximum look angle to {@maxLookangle} * */ lookVertical( lookAxis: Cartesian3, surfaceNormal: Cartesian3, lookAmount: number ) { const camera = this.camera; const currentAngle = CesiumMath.toDegrees( Cartesian3.angleBetween(surfaceNormal, camera.up) ); const upAfterLook = rotateVectorAboutAxis(camera.up, lookAxis, lookAmount); const angleAfterLook = CesiumMath.toDegrees( Cartesian3.angleBetween(surfaceNormal, upAfterLook) ); // We apply NO friction when the camera angle with surface normal is decreasing // When the camera angle is increasing, we apply a friction which peaks as we approach // the maxLookAngle const maxLookAngle = this.maxVerticalLookAngle; const friction = angleAfterLook < currentAngle ? 1 : (maxLookAngle - currentAngle) / maxLookAngle; camera.look(lookAxis, lookAmount * friction); } /** * Perform a move step */ move(movement: Movement) { switch (movement) { case "forward": return this.moveForward(); case "backward": return this.moveBackward(); case "left": return this.moveLeft(); case "right": return this.moveRight(); case "up": return this.moveUp(); case "down": return this.moveDown(); case "look": return this.look(); } } async updateSurfaceHeightEstimate() { if (this.isUpdatingSurfaceHeightEstimate) { // avoid concurrent queries return false; } this.isUpdatingSurfaceHeightEstimate = true; // In fly mode we sample only the terrain height // In walk mode we sample the terrain & scene height and // take the maximum of both const position = this.camera.position; try { const samples = await Promise.all([ sampleTerrainHeight(this.scene, position), this.mode === "walk" ? sampleSceneHeight(this.scene, position) : undefined ]); const heights = filterOutUndefined(samples); if (heights.length > 0) { this.currentSurfaceHeightEstimate = Math.max(...heights); // trigger surface height change animation this.isAnimatingSurfaceHeightChange = true; } } catch { /* nothing to do */ } finally { this.isUpdatingSurfaceHeightEstimate = false; } } /** * Animate pedestrian height to match the change in surface height */ animateSurfaceHeightChange() { // round to 3 decimal places so that we converge to a stable height sooner const heightFromSurface = Math.round(this.currentPedestrianHeightFromSurface * 1000) / 1000; const hasReachedDesiredHeight = this.mode === "walk" ? heightFromSurface === this.pedestrianHeight : heightFromSurface >= this.pedestrianHeight; if (hasReachedDesiredHeight) { this.isAnimatingSurfaceHeightChange = false; return; } const gapHeight = this.pedestrianHeight - heightFromSurface; // If climbRate is atleast equal to moveAmount // we can ensure that going up an inclined slope of 45deg will // not result in the camera going underground. // When getting close to a building edge, we want the user // to be transported to the top, but very smoothly. To ensure smooth motion // we special case it by taking moveAmount / 4, if gapHeight is above 5metres. const climbRate = this.moveAmount / (Math.abs(gapHeight) > 5 ? 4 : 1); const climbHeight = gapHeight * climbRate; const surfaceNormal = this.scene.globe.ellipsoid.geodeticSurfaceNormal( this.camera.position, new Cartesian3() ); this.camera.move(surfaceNormal, climbHeight); } animate() { if (this.activeMovements.size > 0) { [...this.activeMovements].forEach(movement => this.move(movement)); this.updateSurfaceHeightEstimate(); this.onMove(); if ( this.activeMovements.has("down") && this.currentPedestrianHeightFromSurface < this.pedestrianHeight && this.mode !== "walk" ) { // Switch to walk mode when moving down and height is below the pedestrian height this.mode = "walk"; } else if (this.activeMovements.has("up") && this.mode !== "fly") { // Switch to fly mode when moving up this.mode = "fly"; } } if (this.isAnimatingSurfaceHeightChange) { this.animateSurfaceHeightChange(); } } /** * Map keyboard events to movements */ setupKeyMap(): () => void { const onKeyDown = (ev: KeyboardEvent) => { if ( // do not match if any modifiers are pressed so that we do not hijack window shortcuts. ev.ctrlKey === false && ev.altKey === false && KeyMap[ev.code] !== undefined ) this.activeMovements.add(KeyMap[ev.code]); }; const onKeyUp = (ev: KeyboardEvent) => { if (KeyMap[ev.code] !== undefined) this.activeMovements.delete(KeyMap[ev.code]); }; document.addEventListener("keydown", excludeInputEvents(onKeyDown), true); document.addEventListener("keyup", excludeInputEvents(onKeyUp), true); const keyMapDestroyer = () => { document.removeEventListener("keydown", onKeyDown); document.removeEventListener("keyup", onKeyUp); }; return keyMapDestroyer; } /** * Map mouse events to movements */ setupMouseMap(): () => void { const eventHandler = new ScreenSpaceEventHandler(this.scene.canvas); const startLook = (click: { position: Cartesian2 }) => { this.currentMousePosition = this.startMousePosition = click.position.clone(); this.activeMovements.add("look"); }; const look = (movement: { endPosition: Cartesian2 }) => { this.currentMousePosition = movement.endPosition.clone(); }; const stopLook = () => { this.activeMovements.delete("look"); this.currentMousePosition = this.startMousePosition = undefined; }; // User might try to turn while moving down (by pressing SHIFT) // so trigger look event even when SHIFT is pressed. eventHandler.setInputAction(startLook, ScreenSpaceEventType.LEFT_DOWN); eventHandler.setInputAction( startLook, ScreenSpaceEventType.LEFT_DOWN, KeyboardEventModifier.SHIFT ); eventHandler.setInputAction(look, ScreenSpaceEventType.MOUSE_MOVE); eventHandler.setInputAction( look, ScreenSpaceEventType.MOUSE_MOVE, KeyboardEventModifier.SHIFT ); eventHandler.setInputAction(stopLook, ScreenSpaceEventType.LEFT_UP); eventHandler.setInputAction( stopLook, ScreenSpaceEventType.LEFT_UP, KeyboardEventModifier.SHIFT ); const mouseMapDestroyer = () => eventHandler.destroy(); return mouseMapDestroyer; } /** * Animate on each clock tick */ startAnimating() { const stopAnimating = this.cesium.cesiumWidget.clock.onTick.addEventListener( this.animate.bind(this) ); return stopAnimating; } /** * Activates MovementsController * * 1. Disables default map interactions. * 2. Sets up keyboard, mouse & animation event handlers. * * @returns A function to de-activate the movements controller */ @action activate(): () => void { // Disable other map controls this.scene.screenSpaceCameraController.enableTranslate = false; this.scene.screenSpaceCameraController.enableRotate = false; this.scene.screenSpaceCameraController.enableLook = false; this.scene.screenSpaceCameraController.enableTilt = false; this.scene.screenSpaceCameraController.enableZoom = false; this.cesium.isFeaturePickingPaused = true; const destroyKeyMap = this.setupKeyMap(); const destroyMouseMap = this.setupMouseMap(); const stopAnimating = this.startAnimating(); const deactivate = action(() => { destroyKeyMap(); destroyMouseMap(); stopAnimating(); const screenSpaceCameraController = this.scene .screenSpaceCameraController; // screenSpaceCameraController will be undefined if the cesium map is already destroyed if (screenSpaceCameraController !== undefined) { screenSpaceCameraController.enableTranslate = true; screenSpaceCameraController.enableRotate = true; screenSpaceCameraController.enableLook = true; screenSpaceCameraController.enableTilt = true; screenSpaceCameraController.enableZoom = true; } this.cesium.isFeaturePickingPaused = false; }); return deactivate; } } const sampleScratch = new Cartographic(); /** * Sample the terrain height at the given position */ async function sampleTerrainHeight( scene: Scene, position: Cartesian3 ): Promise<number | undefined> { const terrainProvider = scene.terrainProvider; if (terrainProvider instanceof EllipsoidTerrainProvider) return 0; const [sample] = await makeRealPromise<Cartographic[]>( sampleTerrainMostDetailed(terrainProvider, [ Cartographic.fromCartesian(position, scene.globe.ellipsoid, sampleScratch) ]) ); return sample.height; } /** * Sample the scene height at the given position * * Scene height is the maximum height of a tileset feature or any other entity * at the given position. */ function sampleSceneHeight( scene: Scene, position: Cartesian3 ): number | undefined { if (scene.sampleHeightSupported === false) return; return scene.sampleHeight( Cartographic.fromCartesian(position, undefined, sampleScratch) ); } /** * Projects the {@vector} to the surface plane containing {@position} * * @param vector The input vector to project * @param position The position used to determine the surface plane * @param ellipsoid The ellipsoid used to compute the surface plane * @returns The projection of {@vector} on the surface plane at the given {@position} */ function projectVectorToSurface( vector: Cartesian3, position: Cartesian3, ellipsoid: Ellipsoid ) { const surfaceNormal = ellipsoid.geodeticSurfaceNormal( position, new Cartesian3() ); const magnitudeOfProjectionOnSurfaceNormal = Cartesian3.dot( vector, surfaceNormal ); const projectionOnSurfaceNormal = Cartesian3.multiplyByScalar( surfaceNormal, magnitudeOfProjectionOnSurfaceNormal, new Cartesian3() ); const projectionOnSurface = Cartesian3.subtract( vector, projectionOnSurfaceNormal, new Cartesian3() ); return projectionOnSurface; } const rotateScratchQuaternion = new Quaternion(); const rotateScratchMatrix = new Matrix3(); /** * Rotates a vector about rotateAxis by rotateAmount */ function rotateVectorAboutAxis( vector: Cartesian3, rotateAxis: Cartesian3, rotateAmount: number ) { const quaternion = Quaternion.fromAxisAngle( rotateAxis, -rotateAmount, rotateScratchQuaternion ); const rotation = Matrix3.fromQuaternion(quaternion, rotateScratchMatrix); const rotatedVector = Matrix3.multiplyByVector( rotation, vector, vector.clone() ); return rotatedVector; } // A regex matching input tag names const inputNodeRe = /input|textarea|select/i; function excludeInputEvents( handler: (ev: KeyboardEvent) => void ): (ev: KeyboardEvent) => void { return ev => { const target = ev.target; if (target !== null) { const nodeName = (target as any).nodeName; const isContentEditable = (target as any).getAttribute?.( "contenteditable" ); if (isContentEditable || inputNodeRe.test(nodeName)) { return; } } handler(ev); }; }
the_stack
import { Component, ViewChild, ViewChildren, QueryList, trigger, state, animate, transition, style } from '@angular/core'; import { NavParams, Slides, ViewController, LoadingController, AlertController, PopoverController } from 'ionic-angular'; //Components import { ProgressBarComponent } from '../../components/progress-bar/progress-bar.component'; import { PinoutPopover } from '../../components/pinout-popover/pinout-popover.component'; //Services import { StorageService } from '../../services/storage/storage.service'; import { SettingsService } from '../../services/settings/settings.service'; import { DeviceManagerService } from 'dip-angular2/services'; @Component({ templateUrl: 'calibrate.html', animations: [ trigger('expand', [ state('true', style({ height: '150px', visibility: 'visible' })), state('false', style({ height: '0', visibility: 'hidden' })), transition('void => *', animate('0s')), transition('* <=> *', animate('250ms ease-in-out')) ]), trigger('rotate', [ state('true', style({ transform: 'rotate(-180deg)' })), state('false', style({ transform: 'rotate(0deg)' })), transition('void => *', animate('0s')), transition('* <=> *', animate('250ms ease-in-out')) ]), trigger('expandMoreInfo', [ state('true', style({ visibility: 'visible' })), state('false', style({ height: '0', visibility: 'hidden' })), transition('void => *', animate('0s')), transition('* <=> *', animate('250ms ease-in-out')) ]) ] }) export class CalibratePage { @ViewChild('calibrationSlider') slider: Slides; @ViewChildren('digilentProgressBar') digilentProgressBar: QueryList<ProgressBarComponent>; public storageService: StorageService; public settingsService: SettingsService; public params: NavParams; public viewCtrl: ViewController; public deviceManagerService: DeviceManagerService; public isLogger: boolean = false; public loggerInstruments = [ { "dc": [1, 2], "awg": 1, "daq": [1] }, { "daq": [2] }, { "daq": [3] }, { "daq": [4] }, { "daq": [5] }, { "daq": [6] }, { "daq": [7] }, { "daq": [8] } ]; public calibrationInstructions: string[]; public noInstructions: string = 'There was an error loading the calibration instructions for your device. Check your reference manual for correct setup before starting the calibration process.'; public currentStep: number; public showInstructions: boolean = true; public runningCalibration: boolean = false; public calibrationStatus: string = 'Ready To Calibrate'; public calibrationFailed: boolean = false; public calibrationSuccessful: boolean = false; private calibrationSaved: boolean = false; public calibrationReadAttempts: number = 0; public maxCalibrationReadAttempts: number = 10; public timeBetweenReadAttempts: number = 2000; public storageLocations: string[] = ['No Locations Found']; public selectedLocation: string = 'No Location Selected'; public calibrationResults: string = 'Results here'; public calibrationResultsIndicator: string = ''; public showAdvanced: boolean = false; public showMoreInfo: boolean = false; public saveAsDefault: boolean = true; // public calibrationReason: string = "Calibration will adjust measurements that are taken, as differences in hardware on devices\ // as well as environmental factors such as temperature leave an effect on measured voltages and signals. To calibrate, the device\ // outputs different voltages and signals while simultaneously measuring them. It then compares the results to what was expected\ // in order to set an offset the device uses when making future measurements." public calibrationReason: string = "Device calibration compensates for component variance and temperature differences. Click here for <a href=\"/\">More Info</a>" constructor( _storageService: StorageService, _settingsService: SettingsService, _params: NavParams, _viewCtrl: ViewController, _deviceManagerService: DeviceManagerService, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private popoverCtrl: PopoverController ) { this.deviceManagerService = _deviceManagerService; this.storageService = _storageService; this.settingsService = _settingsService; this.viewCtrl = _viewCtrl; this.params = _params; this.isLogger = this.deviceManagerService.getActiveDevice().deviceModel === 'OpenLogger MZ'; console.log('calibrate constructor'); this.getCalibrationInstructions(); } //Need to use this lifecycle hook to make sure the slider exists before trying to get a reference to it ionViewDidEnter() { let swiperInstance: any = this.slider.getSlider(); if (swiperInstance == undefined) { setTimeout(() => { this.ionViewDidEnter(); }, 20); return; } swiperInstance.lockSwipes(); } toggleAdvanced() { this.showAdvanced = !this.showAdvanced; } toggleMoreInfo() { this.showMoreInfo = !this.showMoreInfo; } closeModal() { if (this.calibrationSuccessful && !this.calibrationSaved) { //Good calibration but not saved. this.presentConfirmNoSaveAlert() .catch((e) => { console.log(e); this.viewCtrl.dismiss(); }); } else { this.viewCtrl.dismiss(); } } private presentConfirmNoSaveAlert(): Promise<any> { return new Promise((resolve, reject) => { let alert = this.alertCtrl.create({ title: 'Calibration Not Saved', message: 'Would you like to save your calibration?', buttons: [ { text: 'No', handler: () => { reject(); } }, { text: 'Yes', handler: () => { resolve(); } } ] }); alert.present(); }); } selectStorage(event) { this.selectedLocation = event; console.log(this.selectedLocation); } toSlide(slideNum: number, noTransition?: boolean) { noTransition = noTransition == undefined ? false : noTransition; let swiperInstance: any = this.slider.getSlider(); swiperInstance.unlockSwipes(); if (noTransition) { this.slider.slideTo(slideNum, 0); } else { this.slider.slideTo(slideNum); } swiperInstance.lockSwipes(); } toCalibrationSuccessPage() { this.toNextSlide(); this.calibrationResultsIndicator = "Calibration completed succesfully and has been applied to the instruments. By default, this calibration will be applied each time the device boots."; // Select <strong>Save as Default</strong> and click <strong>Done</strong> to apply the calibration everytime the device boots."; // was successful and has been applied to the instruments but will be lost when powered down.\nPress save to have this calibration load at startup."; this.getStorageLocations(); } saveCalibrationToDevice(): Promise<any> { this.calibrationSaved = true; this.calibrationResultsIndicator = 'Saving calibration.'; if (this.selectedLocation === 'No Location Selected') { this.calibrationResultsIndicator = 'Error saving calibration. Choose a valid storage location.'; return Promise.reject(this.calibrationResultsIndicator); } if (this.calibrationResults.indexOf('IDEAL') !== -1 || this.calibrationResults.indexOf('UNCALIBRATED') !== -1 || this.calibrationResults.indexOf('uncalibrated') !== -1 || this.calibrationResults.indexOf('failed calibration') !== -1) { this.calibrationFailed = true; this.calibrationResultsIndicator = 'Error saving calibration. One or more channels fell back to ideal values. Rerun calibration.'; return Promise.reject(this.calibrationResultsIndicator); } console.log(this.selectedLocation); return this.saveCalibration(this.selectedLocation) .then(() => { this.calibrationResultsIndicator = 'Save successful'; return Promise.resolve(); }) .catch((err) => { this.calibrationResultsIndicator = 'Error saving calibration.'; return Promise.reject(this.calibrationResultsIndicator); }); } onSuccessfulCalibrationApply() { this.viewCtrl.dismiss(); } getStorageLocations() { this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationGetStorageTypes().subscribe( (data) => { console.log(data); this.storageLocations = data.device[0].storageTypes; this.selectedLocation = this.storageLocations[0]; }, (err) => { console.log(err); this.calibrationResultsIndicator = 'Could not get storage locations for device.'; }, () => { } ); } getCalibrationInstructions() { console.log(this.deviceManagerService); this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationGetInstructions().subscribe( (data) => { if (data.device[0].instructions == undefined && data.device[0].step == undefined) { this.calibrationInstructions = this.isLogger ? Array.apply(null, Array(8)) : [null]; return; } this.calibrationInstructions = this.isLogger ? data.device[0].step : [data.device[0].instructions]; }, (err) => { console.log(err); this.calibrationInstructions = this.isLogger ? Array.apply(null, Array(8)) : [null]; }, () => { } ); } connectionImage(step: number) { return this.isLogger ? 'assets/img/openlogger_calibration_' + step + '.svg' : 'assets/img/openscope_calibration.svg'; } toNextSlide() { this.calibrationStatus = 'Ready To Calibrate'; this.showInstructions = true; this.runningCalibration = false; let swiperInstance: any = this.slider.getSlider(); swiperInstance.unlockSwipes(); this.slider.slideTo(swiperInstance.activeIndex + 1, 0); swiperInstance.lockSwipes(); } runCalibration(step: number) { this.currentStep = step; this.calibrationFailed = false; this.calibrationSuccessful = false; // only reset instruments if first step if (this.currentStep === 0) { let loading = this.displayLoading(); this.resetInstruments().then(() => { this.startCalibration(); loading.dismiss(); this.showInstructions = false; this.runningCalibration = true; }).catch((e) => { this.calibrationStatus = 'Error resetting the device. Make sure it is still connected and is on the latest firmware.'; loading.dismiss(); }); } else { this.startCalibration(); this.showInstructions = false; this.runningCalibration = true; } } displayLoading(message?: string) { message = message == undefined ? 'Resetting Device...' : message; let loading = this.loadingCtrl.create({ content: message, spinner: 'crescent', cssClass: 'custom-loading-indicator' }); loading.present(); return loading; } resetInstruments(): Promise<any> { return new Promise((resolve, reject) => { this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].resetInstruments().subscribe( (data) => { console.log(data); if (data.device[0].wait) { setTimeout(() => { resolve(data); }, data.device[0].wait); } }, (err) => { reject(err); }, () => { } ); }); } startCalibration() { this.calibrationFailed = false; this.calibrationSuccessful = false; let instruments = this.isLogger ? this.loggerInstruments[this.currentStep] : {}; this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationStart(instruments).subscribe( (data) => { console.log(data); let waitTime = data.device[0].wait < 0 ? this.timeBetweenReadAttempts : data.device[0].wait; this.calibrationStatus = 'This should take about ' + Math.round(data.device[0].wait / 1000) + ' seconds.'; this.calibrationReadAttempts = 0; this.runProgressBar(waitTime); }, (err) => { console.log(err); this.calibrationFailed = true; if (err.device && err.device[0].statusCode === 2684354573) { this.calibrationStatus = 'Error running calibration. Please check your setup and try again.'; return; } this.calibrationStatus = 'Error starting calibration. Please try again.'; }, () => { } ); } runProgressBar(waitTime: number) { this.digilentProgressBar.toArray()[this.currentStep].start(waitTime); } progressBarFinished() { this.readCalibrationAfterCalibrating(); } exitModal() { /* note(andrew): saveCalibrationToDevice returns a Promise, so a conditional ternary is used to substitute an immediately resolved Promise in the case the user doesn't want to save */ ((this.saveAsDefault) ? this.saveCalibrationToDevice() : Promise.resolve()) .then(() => { this.viewCtrl.dismiss(); }) .catch((err) => { console.log('Failed to save calibration.'); }); } loadCalibration(type: string) { this.calibrationResultsIndicator = 'Loading calibration.'; if (this.selectedLocation === 'No Location Selected') { this.calibrationResultsIndicator = 'Error loading calibration. Choose a valid storage location.'; return; } this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationLoad(type).subscribe( (data) => { console.log(data); setTimeout(() => { this.readCalibration().catch((e) => { this.calibrationResultsIndicator = 'Error reading current calibration.'; }); }, 750); this.calibrationResultsIndicator = 'Loaded calibration successfully.'; }, (err) => { console.log(err); this.calibrationResultsIndicator = 'Error loading calibration.'; }, () => { } ); } loadSelectedCalibration() { this.loadCalibration(this.selectedLocation); } readCalibration(): Promise<any> { return new Promise((resolve, reject) => { this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationRead().subscribe( (data) => { console.log(data); this.calibrationStatus = 'Loaded current calibration data.'; this.parseCalibrationInformation(data); resolve(); }, (err) => { console.log(err); this.calibrationStatus = 'Error loading current calibration.'; reject(); }, () => { } ); }); } toLoadExistingPage() { let swiperInstance: any = this.slider.getSlider(); swiperInstance.unlockSwipes(); // this.slider.slideTo(3, 0); this.slider.slideTo(this.calibrationInstructions.length + 1, 0); swiperInstance.lockSwipes(); this.calibrationResultsIndicator = 'Select a storage location and click load.'; this.calibrationResults = ''; this.readCalibration().then(() => { this.getStorageLocations(); }).catch((e) => { }); } readCalibrationAfterCalibrating() { this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationRead().subscribe( (data) => { console.log(data); // Make sure calibration did not fail if (this.isLogger) { let status = data.device[0].calibrationData.daq[this.currentStep + 1].status; if (status === 'failed calibration' || status === 'uncalibrated') { this.calibrationFailed = true; this.calibrationStatus = 'Calibration failed. Check your calibration setup and try again.'; return; } } this.calibrationStatus = 'Calibration Successful!'; this.parseCalibrationInformation(data); this.calibrationSuccessful = true; }, (err) => { console.log(err); if (err.device == undefined && this.calibrationReadAttempts < this.maxCalibrationReadAttempts) { this.calibrationReadAttempts++; this.calibrationStatus = 'Attempting to read calibration.'; setTimeout(() => { this.readCalibrationAfterCalibrating(); }, this.timeBetweenReadAttempts); return; } if (err.device && err.device[0].statusCode === 8) { if (this.calibrationReadAttempts < this.maxCalibrationReadAttempts) { this.calibrationReadAttempts++; this.calibrationStatus = 'Attempting to read calibration.'; setTimeout(() => { this.readCalibrationAfterCalibrating(); }, this.timeBetweenReadAttempts); } else { this.calibrationFailed = true; this.calibrationStatus = 'Timeout attempting to read calibration. Check your calibration setup and try again.'; } } else if (err.device && err.device[0].statusCode === 2684354578) { //Bad setup this.calibrationFailed = true; this.calibrationStatus = 'Calibration failed. ' + (this.calibrationInstructions ? this.calibrationInstructions : 'Check your reference manual for correct setup.') + ' Click retry to restart calibration.'; return; } else if (this.calibrationReadAttempts >= this.maxCalibrationReadAttempts) { this.calibrationFailed = true; this.calibrationStatus = 'Timeout attempting to read calibration. Check your calibration setup and try again.'; } }, () => { } ); } parseCalibrationInformation(data: any) { let calibrationDataContainer = data.device[0].calibrationData; for (let instrument in calibrationDataContainer) { if (calibrationDataContainer[instrument].numChans) { delete calibrationDataContainer[instrument].numChans; } } let calibrationDataAsString: string = JSON.stringify(calibrationDataContainer, undefined, 4); this.calibrationResults = calibrationDataAsString; } saveCalibration(location: string): Promise<any> { return new Promise((resolve, reject) => { this.deviceManagerService.devices[this.deviceManagerService.activeDeviceIndex].calibrationSave(location).subscribe( (data) => { console.log(data); resolve(); }, (err) => { console.log(err); reject(err); }, () => { } ); }); } openDevicePinout(event) { let popover = this.popoverCtrl.create(PinoutPopover, undefined, { cssClass: 'pinoutPopover' }); popover.present({ ev: event }); } }
the_stack
import * as _ from "lodash"; import { ReducerFunction } from "./types"; import util from "./util"; // // Functions to process missing values out of a value list // /** * A pass through filter, keeps the input values just as they were. */ const keepMissing = (values: number[]) => values; /** * Filters out any missing values (`null`, `undefined` or `NaN`) from the input values */ const ignoreMissing = (values: number[]) => values.filter(util.isValid); /** * Replaces any missing value (`null`, `undefined` or `NaN`) with the value `0` */ const zeroMissing = (values: number[]) => values.map(v => (util.isValid(v) ? v : 0)); /** * Scans the input values for missing values (`null`, `undefined` or `NaN`) and * returns `null` if one or more exist, otherwise returns the original values. An * example of doing this might be that you are summing values of events in * an hour, but if you are missing any values you don't want do the sum at all, * you want to say that for that hour the sum is unknown. */ const propagateMissing = (values: number[]) => ignoreMissing(values).length === values.length ? values : null; /** * If the input values are an empty array, return `null`, otherwise return * the input values. */ const noneIfEmpty = (values: number[]) => (values.length === 0 ? null : values); /** * Like `first()` except it will return null if not all the values are * the same. This can be used to transfer a value when doing aggregation. * * For instance you might "group by" the 'type', then `avg` the 'value', but * you want to results to include the type. So you would `keep()` the type * and `avg()` the value. */ export function keep(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } const result = first()(cleanValues); cleanValues.forEach(v => { if (v !== result) { return null; } }); return result; }; } /** * Returns a `sum()` function, i.e. returns a function that takes a list * of values and returns their total. * * Example: * ``` * import { sum } from "pondjs"; * const aggregationFunction = sum() * const result = aggregationFunction([3, 5, 6]) // 14 * ``` * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the sum calculation. Other possibilities are: * * `propagateMissing` - which will cause the sum itself to be null if the * values contain a missing value * * `zeroMissing` - will replace missing values with a zero, which for a sum * is the same as excluding those values */ export function sum(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]): number => { const cleanValues = clean(values); if (!cleanValues) { return null; } return _.reduce(cleanValues, (a: number, b: number) => a + b, 0); }; } /** * Returns an `avg()` function. i.e. returns a function that takes a list * of values and returns the average of those. * * Example: * ``` * import { avg } from "pondjs"; * const aggregationFunction = avg() * const result = aggregationFunction([3, 5, 6]) // ~4.66666 * ``` * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the average calculation. Other possibilities are: * * `propagateMissing` - which will cause the resulting average to be null if the values * contain a missing value * * `zeroMissing` - will replace missing values with a zero, thus missing values will bring * the average down */ export function avg(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]): number => { const cleanValues = clean(values); if (!cleanValues) { return null; } const total = _.reduce( cleanValues, (a: number, b: number) => { return a + b; }, 0 ); return total / cleanValues.length; }; } /** * Return a `max()` function. i.e. returns a function that takes a list * of values and returns the average of those. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the maximum search. Other possibilities are: * * `propagateMissing` - which will cause the max itself to be null if the values * contain a missing value * * `zeroMissing` - will replace missing values with a zero */ export function max(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } const result = _.max(cleanValues); if (_.isFinite(result)) { return result; } }; } /** * Return a `min()` function. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the minimum search. Other possibilities are: * * `propagateMissing` - which will cause the min itself to be null if the * values contain a missing value * * `zeroMissing` - will replace missing values with a zero */ export function min(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } const result = _.min(cleanValues); if (_.isFinite(result)) { return result; } }; } /** * Returns a `count()` function. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the count. Other possibilities are: * * `propagateMissing` - which will cause the count itself to be null if the * values contain a missing value */ export function count(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } return cleanValues.length; }; } /** * Returns a `first()` function, i.e. a function that returns the first * value in the supplied values list. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the list, i.e to find the first non-missing value. Other * possibilities are: * * `keepMissing` - to return the first value, regardless of if it is a missing value or not. */ export function first(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } return cleanValues.length ? cleanValues[0] : undefined; }; } /** * Returns a `last()` function, i.e. a function that returns the list * value in the supplied values list. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the list, i.e to find the last non-missing value. Other * possibilities are: * * `keepMissing` - to return the last value, regardless of if it is a missing value or not. */ export function last(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } return cleanValues.length ? cleanValues[cleanValues.length - 1] : undefined; }; } /** * Returns a `difference()` function, i.e. a function that returns * the difference between the `min` and `max` values. * * Optionally you can specify the method by which unclean values * are treated. The default is to exclude missing values from * the list, i.e to find the last non-missing value. Other * possibilities are: * * `propagateMissing` - which will cause the min itself to be null if the * values contain a missing value * * `zeroMissing` - will replace missing values with a zero */ export function difference(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } return _.max(cleanValues) - _.min(cleanValues); }; } /** * Returns the `median()` function, i.e. a function that returns * the median of the values supplied to it. */ export function median(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } const sorted = cleanValues.sort(); const i = Math.floor(sorted.length / 2); if (sorted.length % 2 === 0) { const a = sorted[i]; const b = sorted[i - 1]; return (a + b) / 2; } else { return sorted[i]; } }; } /** * Returns a function that returns a `stdev()` function, i.e. a function * that returns the standard deviation of the values supplied to it. */ export function stdev(clean = filter.ignoreMissing): ReducerFunction { return (values: number[]) => { const cleanValues = clean(values); if (!cleanValues) { return null; } let sums = 0; const mean = avg(clean)(cleanValues); cleanValues.forEach(v => (sums += Math.pow(v - mean, 2))); return Math.sqrt(sums / values.length); }; } export enum InterpolationType { linear = 1, lower, higher, nearest, midpoint } /** * Returns a `percentile` function within the a values list. * * The parameters controlling the function: * * `q` - The percentile (should be between 0 and 100), e.g q=75 for 75th percentile. * * `interp` - Specifies the interpolation method to use when the desired * quantile lies between two data points. * Options are: * * linear: i + (j - i) * fraction, where fraction is * the fractional part of the index surrounded by i and j. * * lower: i. * * higher: j. * * nearest: i or j whichever is nearest. * * midpoint: (i + j) / 2. * * `clean` - Strategy to use when encountering missing data: * * `propagateMissing` - which will cause the min * itself to be null if the values contain a * missing value * * `zeroMissing` - will replace missing values * with a zero */ export function percentile( q: number, interp: InterpolationType = InterpolationType.linear, clean = filter.ignoreMissing ): ReducerFunction { return (values: number[]): number => { const cleanValues = clean(values); if (!cleanValues) { return null; } let v; const sorted = cleanValues.slice().sort((a, b) => a - b); const size = sorted.length; if (q < 0 || q > 100) { throw new Error("Percentile q must be between 0 and 100"); } const i = q / 100; const index = Math.floor((sorted.length - 1) * i); if (size === 1 || q === 0) { return sorted[0]; } if (q === 100) { return sorted[size - 1]; } if (index < size - 1) { const fraction = (size - 1) * i - index; const v0 = sorted[index]; const v1 = sorted[index + 1]; if (interp === InterpolationType.lower || fraction === 0) { v = v0; } else if (interp === InterpolationType.linear) { v = v0 + (v1 - v0) * fraction; } else if (interp === InterpolationType.higher) { v = v1; } else if (interp === InterpolationType.nearest) { v = fraction < 0.5 ? v0 : v1; } else if (interp === InterpolationType.midpoint) { v = (v0 + v1) / 2; } } return v; }; } export const filter = { keepMissing, ignoreMissing, zeroMissing, propagateMissing, noneIfEmpty };
the_stack
import { Disposable, languages as Languages, window as Window, workspace as Workspace, CancellationToken, ProviderResult, Diagnostic as VDiagnostic, CancellationTokenSource, TextDocument, CancellationError, Event as VEvent, EventEmitter, DiagnosticCollection, Uri } from 'vscode'; import { Proposed, ClientCapabilities, ServerCapabilities, DocumentSelector, DidOpenTextDocumentNotification, DidChangeTextDocumentNotification, DidSaveTextDocumentNotification, DidCloseTextDocumentNotification, LinkedMap, Touch, RAL } from 'vscode-languageserver-protocol'; import { generateUuid } from './utils/uuid'; import { TextDocumentFeature, BaseLanguageClient, Middleware, LSPCancellationError, DiagnosticPullMode } from './client'; function ensure<T, K extends keyof T>(target: T, key: K): T[K] { if (target[key] === void 0) { target[key] = {} as any; } return target[key]; } export namespace vsdiag { export enum DocumentDiagnosticReportKind { full = 'full', unChanged = 'unChanged' } export interface FullDocumentDiagnosticReport { kind: DocumentDiagnosticReportKind.full; resultId?: string; items: VDiagnostic[]; } export interface RelatedFullDocumentDiagnosticReport extends FullDocumentDiagnosticReport { relatedDocuments?: { [uri: string /** DocumentUri */]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; } } export interface UnchangedDocumentDiagnosticReport { kind: DocumentDiagnosticReportKind.unChanged; resultId: string; } export interface RelatedUnchangedDocumentDiagnosticReport extends UnchangedDocumentDiagnosticReport { relatedDocuments?: { [uri: string /** DocumentUri */]: FullDocumentDiagnosticReport | UnchangedDocumentDiagnosticReport; } } export type DocumentDiagnosticReport = RelatedFullDocumentDiagnosticReport | RelatedUnchangedDocumentDiagnosticReport; export type PreviousResultId = { uri: Uri; value: string; }; export interface WorkspaceFullDocumentDiagnosticReport extends FullDocumentDiagnosticReport { uri: Uri; version: number | null; } export interface WorkspaceUnchangedDocumentDiagnosticReport extends UnchangedDocumentDiagnosticReport { uri: Uri; version: number | null; } export type WorkspaceDocumentDiagnosticReport = WorkspaceFullDocumentDiagnosticReport | WorkspaceUnchangedDocumentDiagnosticReport; export interface WorkspaceDiagnosticReport { items: WorkspaceDocumentDiagnosticReport[]; } export interface WorkspaceDiagnosticReportPartialResult { items: WorkspaceDocumentDiagnosticReport[]; } export interface ResultReporter { (chunk: WorkspaceDiagnosticReportPartialResult | null): void; } export interface DiagnosticProvider { onDidChangeDiagnostics: VEvent<void>; provideDiagnostics(textDocument: TextDocument, previousResultId: string | undefined, token: CancellationToken): ProviderResult<DocumentDiagnosticReport>; provideWorkspaceDiagnostics?(resultIds: PreviousResultId[], token: CancellationToken, resultReporter: ResultReporter): ProviderResult<WorkspaceDiagnosticReport>; } } export interface ProvideDiagnosticSignature { (this: void, textDocument: TextDocument, previousResultId: string | undefined, token: CancellationToken): ProviderResult<vsdiag.DocumentDiagnosticReport>; } export interface ProvideWorkspaceDiagnosticSignature { (this: void, resultIds: vsdiag.PreviousResultId[], token: CancellationToken, resultReporter: vsdiag.ResultReporter): ProviderResult<vsdiag.WorkspaceDiagnosticReport>; } export interface DiagnosticProviderMiddleware { provideDiagnostics?: (this: void, document: TextDocument, previousResultId: string | undefined, token: CancellationToken, next: ProvideDiagnosticSignature) => ProviderResult<vsdiag.DocumentDiagnosticReport>; provideWorkspaceDiagnostics?: (this: void, resultIds: vsdiag.PreviousResultId[], token: CancellationToken, resultReporter: vsdiag.ResultReporter, next: ProvideWorkspaceDiagnosticSignature) => ProviderResult<vsdiag.WorkspaceDiagnosticReport>; } enum RequestStateKind { active = 'open', reschedule = 'reschedule', outDated = 'drop' } type RequestState = { state: RequestStateKind.active; version: number; textDocument: TextDocument; tokenSource: CancellationTokenSource; } | { state: RequestStateKind.reschedule; textDocument: TextDocument; } | { state: RequestStateKind.outDated; textDocument: TextDocument; }; class EditorTracker { private readonly open: Set<string>; private readonly disposable: Disposable; constructor() { this.open = new Set(); const openTabsHandler = () => { this.open.clear(); // New API if (Window.tabs !== undefined) { for (const tab of Window.tabs) { if (tab.resource !== undefined) { this.open.add(tab.resource.toString()); } } // Old pre 1.61 API } else if (Window.openEditors !== undefined) { for (const info of Window.openEditors) { if (info.resource !== undefined) { this.open.add(info.resource.toString()); } } } }; openTabsHandler(); if (Window.onDidChangeTabs !== undefined) { this.disposable = Window.onDidChangeTabs(openTabsHandler); } else if (Window.onDidChangeOpenEditors !== undefined) { this.disposable = Window.onDidChangeOpenEditors(openTabsHandler); } else { this.disposable = { dispose: () => {} }; } } public dispose(): void { this.disposable.dispose(); } public isActive(textDocument: TextDocument): boolean { return Window.activeTextEditor?.document === textDocument; } public isVisible(textDocument: TextDocument): boolean { return this.open.has(textDocument.uri.toString()); } } interface DocumentPullState { document: Uri; pulledVersion: number | undefined; resultId: string | undefined; } enum PullState { document = 1, workspace = 2 } class DocumentPullStateTracker { private readonly documentPullStates: Map<string, DocumentPullState>; private readonly workspacePullStates: Map<string, DocumentPullState>; constructor() { this.documentPullStates = new Map(); this.workspacePullStates = new Map(); } public track(kind: PullState, textDocument: TextDocument): DocumentPullState; public track(kind: PullState, uri: string, version: number | undefined): DocumentPullState; public track(kind: PullState, document: TextDocument | string, arg1?: number | undefined): DocumentPullState { const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; const [key, uri, version] = typeof document === 'string' ? [document, Uri.parse(document), arg1 as number | undefined] : [document.uri.toString(), document.uri, document.version]; let state = states.get(key); if (state === undefined) { state = { document: uri, pulledVersion: version, resultId: undefined }; states.set(key, state); } return state; } public update(kind: PullState, textDocument: TextDocument, resultId: string | undefined): void; public update(kind: PullState, uri: string, version: number | undefined, resultId: string | undefined): void; public update(kind: PullState, document: TextDocument | string, arg1: string | number | undefined, arg2?: string | undefined): void { const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; const [key, uri, version, resultId] = typeof document === 'string' ? [document, Uri.parse(document), arg1 as number | undefined, arg2] : [document.uri.toString(), document.uri, document.version, arg1 as string | undefined]; let state = states.get(key); if (state === undefined) { state = { document: uri, pulledVersion: version, resultId }; states.set(key, state); } else { state.pulledVersion = version; state.resultId = resultId; } } public unTrack(kind: PullState, textDocument: TextDocument): void { const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; states.delete(textDocument.uri.toString()); } public tracks(kind: PullState, textDocument: TextDocument): boolean; public tracks(kind: PullState, uri: string): boolean; public tracks(kind: PullState, document: TextDocument | string): boolean { const key = typeof document === 'string' ? document : document.uri.toString(); const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; return states.has(key); } public getResultId(kind: PullState, textDocument: TextDocument): string | undefined { const states = kind === PullState.document ? this.documentPullStates : this.workspacePullStates; return states.get(textDocument.uri.toString())?.resultId; } public getAllResultIds(): Proposed.PreviousResultId[] { const result: Proposed.PreviousResultId[] = []; for (let [uri, value] of this.workspacePullStates) { if (this.documentPullStates.has(uri)) { value = this.documentPullStates.get(uri)!; } if (value.resultId !== undefined) { result.push({ uri, value: value.resultId }); } } return result; } } class DiagnosticRequestor implements Disposable { private isDisposed: boolean; private readonly client: BaseLanguageClient; private readonly editorTracker: EditorTracker; private readonly options: Proposed.DiagnosticRegistrationOptions; public readonly onDidChangeDiagnosticsEmitter: EventEmitter<void>; public readonly provider: vsdiag.DiagnosticProvider; private readonly diagnostics: DiagnosticCollection; private readonly openRequests: Map<string, RequestState>; private readonly documentStates: DocumentPullStateTracker; private workspaceErrorCounter: number; private workspaceCancellation: CancellationTokenSource | undefined; private workspaceTimeout: Disposable | undefined; public constructor(client: BaseLanguageClient, editorTracker: EditorTracker, options: Proposed.DiagnosticRegistrationOptions) { this.client = client; this.editorTracker = editorTracker; this.options = options; this.isDisposed = false; this.onDidChangeDiagnosticsEmitter = new EventEmitter<void>(); this.provider = this.createProvider(); this.diagnostics = Languages.createDiagnosticCollection(options.identifier); this.openRequests = new Map(); this.documentStates = new DocumentPullStateTracker(); this.workspaceErrorCounter = 0; } public knows(kind: PullState, textDocument: TextDocument): boolean { return this.documentStates.tracks(kind, textDocument); } public pull(textDocument: TextDocument, cb?: () => void): void { this.pullAsync(textDocument).then(() => { if (cb) { cb(); } }, (error) => { this.client.error(`Document pull failed for text document ${textDocument.uri.toString()}`, error, false); }); } private async pullAsync(textDocument: TextDocument): Promise<void> { const key = textDocument.uri.toString(); const version = textDocument.version; const currentRequestState = this.openRequests.get(key); const documentState = this.documentStates.track(PullState.document, textDocument); if (currentRequestState === undefined) { const tokenSource = new CancellationTokenSource(); this.openRequests.set(key, { state: RequestStateKind.active, version: version, textDocument, tokenSource }); let report: vsdiag.DocumentDiagnosticReport | undefined; let afterState: RequestState | undefined; try { report = await this.provider.provideDiagnostics(textDocument, documentState.resultId, tokenSource.token) ?? { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }; } catch (error) { if (error instanceof LSPCancellationError && Proposed.DiagnosticServerCancellationData.is(error.data) && error.data.retriggerRequest === false) { afterState = { state: RequestStateKind.outDated, textDocument }; } if (afterState === undefined && error instanceof CancellationError) { afterState = { state: RequestStateKind.reschedule, textDocument }; } else { throw error; } } afterState = afterState ?? this.openRequests.get(key); if (afterState === undefined) { // This shouldn't happen. Log it this.client.error(`Lost request state in diagnostic pull model. Clearing diagnostics for ${key}`); this.diagnostics.delete(textDocument.uri); return; } this.openRequests.delete(key); if (!this.editorTracker.isVisible(textDocument)) { this.documentStates.unTrack(PullState.document, textDocument); return; } if (afterState.state === RequestStateKind.outDated) { return; } // report is only undefined if the request has thrown. if (report !== undefined) { if (report.kind === vsdiag.DocumentDiagnosticReportKind.full) { this.diagnostics.set(textDocument.uri, report.items); } documentState.pulledVersion = version; documentState.resultId = report.resultId; } if (afterState.state === RequestStateKind.reschedule) { this.pull(textDocument); } } else { if (currentRequestState.state === RequestStateKind.active) { // Cancel the current request and reschedule a new one when the old one returned. currentRequestState.tokenSource.cancel(); this.openRequests.set(key, { state: RequestStateKind.reschedule, textDocument: currentRequestState.textDocument }); } else if (currentRequestState.state === RequestStateKind.outDated) { this.openRequests.set(key, { state: RequestStateKind.reschedule, textDocument: currentRequestState.textDocument }); } } } public cleanupPull(textDocument: TextDocument): void { const key = textDocument.uri.toString(); const request = this.openRequests.get(key); if (this.options.workspaceDiagnostics || this.options.interFileDependencies) { if (request !== undefined) { this.openRequests.set(key, { state: RequestStateKind.reschedule, textDocument: textDocument }); } else { this.pull(textDocument); } } else { if (request !== undefined) { if (request.state === RequestStateKind.active) { request.tokenSource.cancel(); } this.openRequests.set(key, { state: RequestStateKind.outDated, textDocument: textDocument }); } this.diagnostics.delete(textDocument.uri); } } public pullWorkspace(): void { this.pullWorkspaceAsync().then(() => { this.workspaceTimeout = RAL().timer.setTimeout(() => { this.pullWorkspace(); }, 2000); }, (error) => { if (!(error instanceof LSPCancellationError) && !Proposed.DiagnosticServerCancellationData.is(error.data)) { this.client.error(`Workspace diagnostic pull failed.`, error, false); this.workspaceErrorCounter++; } if (this.workspaceErrorCounter <= 5) { this.workspaceTimeout = RAL().timer.setTimeout(() => { this.pullWorkspace(); }, 2000); } }); } private async pullWorkspaceAsync(): Promise<void> { if (!this.provider.provideWorkspaceDiagnostics) { return; } if (this.workspaceCancellation !== undefined) { this.workspaceCancellation.cancel(); this.workspaceCancellation = undefined; } this.workspaceCancellation = new CancellationTokenSource(); const previousResultIds: vsdiag.PreviousResultId[] = this.documentStates.getAllResultIds().map((item) => { return { uri: this.client.protocol2CodeConverter.asUri(item.uri), value: item.value }; }); await this.provider.provideWorkspaceDiagnostics(previousResultIds, this.workspaceCancellation.token, (chunk) => { if (!chunk || this.isDisposed) { return; } for (const item of chunk.items) { if (item.kind === vsdiag.DocumentDiagnosticReportKind.full) { // Favour document pull result over workspace results. So skip if it is tracked // as a document result. if (!this.documentStates.tracks(PullState.document, item.uri.toString())) { this.diagnostics.set(item.uri, item.items); } } this.documentStates.update(PullState.workspace, item.uri.toString(), item.version ?? undefined, item.resultId); } }); } private createProvider(): vsdiag.DiagnosticProvider { const result: vsdiag.DiagnosticProvider = { onDidChangeDiagnostics: this.onDidChangeDiagnosticsEmitter.event, provideDiagnostics: (textDocument, previousResultId, token) => { const provideDiagnostics: ProvideDiagnosticSignature = (textDocument, previousResultId, token) => { const params: Proposed.DocumentDiagnosticParams = { identifier: this.options.identifier, textDocument: { uri: this.client.code2ProtocolConverter.asUri(textDocument.uri) }, previousResultId: previousResultId }; return this.client.sendRequest(Proposed.DocumentDiagnosticRequest.type, params, token).then((result) => { if (result === undefined || result === null || this.isDisposed) { return { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }; } if (result.kind === Proposed.DocumentDiagnosticReportKind.full) { return { kind: vsdiag.DocumentDiagnosticReportKind.full, resultId: result.resultId, items: this.client.protocol2CodeConverter.asDiagnostics(result.items) }; } else { return { kind: vsdiag.DocumentDiagnosticReportKind.unChanged, resultId: result.resultId }; } }, (error) => { return this.client.handleFailedRequest(Proposed.DocumentDiagnosticRequest.type, token, error, { kind: vsdiag.DocumentDiagnosticReportKind.full, items: [] }); }); }; const middleware: Middleware & DiagnosticProviderMiddleware = this.client.clientOptions.middleware!; return middleware.provideDiagnostics ? middleware.provideDiagnostics(textDocument, previousResultId, token, provideDiagnostics) : provideDiagnostics(textDocument, previousResultId, token); } }; if (this.options.workspaceDiagnostics) { result.provideWorkspaceDiagnostics = (resultIds, token, resultReporter): ProviderResult<vsdiag.WorkspaceDiagnosticReport> => { const convertReport = (report: Proposed.WorkspaceDocumentDiagnosticReport): vsdiag.WorkspaceDocumentDiagnosticReport => { if (report.kind === Proposed.DocumentDiagnosticReportKind.full) { return { kind: vsdiag.DocumentDiagnosticReportKind.full, uri: this.client.protocol2CodeConverter.asUri(report.uri), resultId: report.resultId, version: report.version, items: this.client.protocol2CodeConverter.asDiagnostics(report.items) }; } else { return { kind: vsdiag.DocumentDiagnosticReportKind.unChanged, uri: this.client.protocol2CodeConverter.asUri(report.uri), resultId: report.resultId, version: report.version }; } }; const convertPreviousResultIds = (resultIds: vsdiag.PreviousResultId[]): Proposed.PreviousResultId[] => { const converted: Proposed.PreviousResultId[] = []; for (const item of resultIds) { converted.push({ uri: this.client.code2ProtocolConverter.asUri(item.uri), value: item.value}); } return converted; }; const provideDiagnostics: ProvideWorkspaceDiagnosticSignature = (resultIds, token): ProviderResult<vsdiag.WorkspaceDiagnosticReport> => { const partialResultToken: string = generateUuid(); const disposable = this.client.onProgress(Proposed.WorkspaceDiagnosticRequest.partialResult, partialResultToken, (partialResult) => { if (partialResult === undefined || partialResult === null) { resultReporter(null); return; } const converted: vsdiag.WorkspaceDiagnosticReportPartialResult = { items: [] }; for (const item of partialResult.items) { converted.items.push(convertReport(item)); } resultReporter(converted); }); const params: Proposed.WorkspaceDiagnosticParams = { identifier: this.options.identifier, previousResultIds: convertPreviousResultIds(resultIds), partialResultToken: partialResultToken }; return this.client.sendRequest(Proposed.WorkspaceDiagnosticRequest.type, params, token).then((result): vsdiag.WorkspaceDiagnosticReport => { const converted: vsdiag.WorkspaceDiagnosticReport = { items: [] }; for (const item of result.items) { converted.items.push(convertReport(item)); } disposable.dispose(); resultReporter(converted); return { items: [] }; }, (error) => { disposable.dispose(); return this.client.handleFailedRequest(Proposed.DocumentDiagnosticRequest.type, token, error, { items: [] }); }); }; const middleware: Middleware & DiagnosticProviderMiddleware = this.client.clientOptions.middleware!; return middleware.provideWorkspaceDiagnostics ? middleware.provideWorkspaceDiagnostics(resultIds, token, resultReporter, provideDiagnostics) : provideDiagnostics(resultIds, token, resultReporter); }; } return result; } public dispose(): void { this.isDisposed = true; // Cancel and clear workspace pull if present. this.workspaceCancellation?.cancel(); this.workspaceTimeout?.dispose(); // Cancel all request and mark open requests as outdated. for (const [key, request] of this.openRequests) { if (request.state === RequestStateKind.active) { request.tokenSource.cancel(); } this.openRequests.set(key, { state: RequestStateKind.outDated, textDocument: request.textDocument }); } } } export interface DiagnosticFeatureProvider { onDidChangeDiagnosticsEmitter: EventEmitter<void>; diagnostics: vsdiag.DiagnosticProvider; } class BackgroundScheduler implements Disposable { private readonly diagnosticRequestor: DiagnosticRequestor; private endDocument: TextDocument | undefined; private readonly documents: LinkedMap<string, TextDocument>; private intervalHandle: Disposable | undefined; public constructor(diagnosticRequestor: DiagnosticRequestor) { this.diagnosticRequestor = diagnosticRequestor; this.documents = new LinkedMap(); } public add(textDocument: TextDocument): void { const key = textDocument.uri.toString(); if (this.documents.has(key)) { return; } this.documents.set(textDocument.uri.toString(), textDocument, Touch.Last); this.trigger(); } public remove(textDocument: TextDocument): void { const key = textDocument.uri.toString(); if (this.documents.has(key)) { this.documents.delete(key); // Do a last pull this.diagnosticRequestor.pull(textDocument); } // No more documents. Stop background activity. if (this.documents.size === 0) { this.stop(); } else if (textDocument === this.endDocument) { // Make sure we have a correct last document. It could have this.endDocument = this.documents.last; } } public trigger(): void { // We have a round running. So simply make sure we run up to the // last document if (this.intervalHandle !== undefined) { this.endDocument = this.documents.last; return; } this.endDocument = this.documents.last; this.intervalHandle = RAL().timer.setInterval(() => { const document = this.documents.first; if (document !== undefined) { this.diagnosticRequestor.pull(document); this.documents.set(document.uri.toString(), document, Touch.Last); if (document === this.endDocument) { this.stop(); } } }, 200); } public dispose(): void { this.stop(); this.documents.clear(); } private stop(): void { this.intervalHandle?.dispose(); this.intervalHandle = undefined; this.endDocument = undefined; } } class DiagnosticFeatureProviderImpl implements DiagnosticFeatureProvider { public readonly disposable: Disposable; private readonly diagnosticRequestor: DiagnosticRequestor; private activeTextDocument: TextDocument | undefined; private readonly backgroundScheduler: BackgroundScheduler; constructor(client: BaseLanguageClient, editorTracker: EditorTracker, options: Proposed.DiagnosticRegistrationOptions) { const diagnosticPullOptions = client.clientOptions.diagnosticPullOptions ?? { onChange: true, onSave: false }; const documentSelector = options.documentSelector!; const disposables: Disposable[] = []; const matches = (textDocument: TextDocument): boolean => { return Languages.match(documentSelector, textDocument) > 0 && editorTracker.isVisible(textDocument); }; this.diagnosticRequestor = new DiagnosticRequestor(client, editorTracker, options); this.backgroundScheduler = new BackgroundScheduler(this.diagnosticRequestor); const addToBackgroundIfNeeded = (textDocument: TextDocument): void => { if (!matches(textDocument) || !options.interFileDependencies || this.activeTextDocument === textDocument) { return; } this.backgroundScheduler.add(textDocument); }; this.activeTextDocument = Window.activeTextEditor?.document; Window.onDidChangeActiveTextEditor((editor) => { const oldActive = this.activeTextDocument; this.activeTextDocument = editor?.document; if (oldActive !== undefined) { addToBackgroundIfNeeded(oldActive); } if (this.activeTextDocument !== undefined) { this.backgroundScheduler.remove(this.activeTextDocument); } }); // We always pull on open. const openFeature = client.getFeature(DidOpenTextDocumentNotification.method); disposables.push(openFeature.onNotificationSent((event) => { const textDocument = event.original; if (matches(textDocument)) { this.diagnosticRequestor.pull(textDocument, () => { addToBackgroundIfNeeded(textDocument); }); } })); // Pull all diagnostics for documents that are already open for (const textDocument of Workspace.textDocuments) { if (matches(textDocument)) { this.diagnosticRequestor.pull(textDocument, () => { addToBackgroundIfNeeded(textDocument); }); } } if (diagnosticPullOptions.onChange) { const changeFeature = client.getFeature(DidChangeTextDocumentNotification.method); disposables.push(changeFeature.onNotificationSent(async (event) => { const textDocument = event.original.document; if ((diagnosticPullOptions.filter === undefined || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onType)) && this.diagnosticRequestor.knows(PullState.document, textDocument) && event.original.contentChanges.length > 0) { this.diagnosticRequestor.pull(textDocument, () => { this.backgroundScheduler.trigger(); }); } })); } if (diagnosticPullOptions.onSave) { const saveFeature = client.getFeature(DidSaveTextDocumentNotification.method); disposables.push(saveFeature.onNotificationSent((event) => { const textDocument = event.original; if ((diagnosticPullOptions.filter === undefined || !diagnosticPullOptions.filter(textDocument, DiagnosticPullMode.onSave)) && this.diagnosticRequestor.knows(PullState.document, textDocument)) { this.diagnosticRequestor.pull(event.original, () => { this.backgroundScheduler.trigger(); }); } })); } // When the document closes clear things up const closeFeature = client.getFeature(DidCloseTextDocumentNotification.method); disposables.push(closeFeature.onNotificationSent((event) => { const textDocument = event.original; this.diagnosticRequestor.cleanupPull(textDocument); this.backgroundScheduler.remove(textDocument); })); // We received a did change from the server. this.diagnosticRequestor.onDidChangeDiagnosticsEmitter.event(() => { for (const textDocument of Workspace.textDocuments) { if (matches(textDocument)) { this.diagnosticRequestor.pull(textDocument); } } }); // da348dc5-c30a-4515-9d98-31ff3be38d14 is the test UUID to test the middle ware. So don't auto trigger pulls. if (options.workspaceDiagnostics === true && options.identifier !== 'da348dc5-c30a-4515-9d98-31ff3be38d14') { this.diagnosticRequestor.pullWorkspace(); } this.disposable = Disposable.from(...disposables, this.backgroundScheduler, this.diagnosticRequestor); } public get onDidChangeDiagnosticsEmitter(): EventEmitter<void> { return this.diagnosticRequestor.onDidChangeDiagnosticsEmitter; } public get diagnostics(): vsdiag.DiagnosticProvider { return this.diagnosticRequestor.provider; } } export class DiagnosticFeature extends TextDocumentFeature<Proposed.DiagnosticOptions, Proposed.DiagnosticRegistrationOptions, DiagnosticFeatureProvider> { private readonly editorTracker: EditorTracker; constructor(client: BaseLanguageClient) { super(client, Proposed.DocumentDiagnosticRequest.type); this.editorTracker = new EditorTracker(); } public fillClientCapabilities(capabilities: ClientCapabilities & Proposed.$DiagnosticClientCapabilities): void { let capability = ensure(ensure(capabilities, 'textDocument')!, 'diagnostic')!; capability.dynamicRegistration = true; // We first need to decide how a UI will look with related documents. // An easy implementation would be to only show related diagnostics for // the active editor. capability.relatedDocumentSupport = false; } public initialize(capabilities: ServerCapabilities & Proposed.$DiagnosticServerCapabilities, documentSelector: DocumentSelector): void { const client = this._client; client.onRequest(Proposed.DiagnosticRefreshRequest.type, async () => { for (const provider of this.getAllProviders()) { provider.onDidChangeDiagnosticsEmitter.fire(); } }); let [id, options] = this.getRegistration(documentSelector, capabilities.diagnosticProvider); if (!id || !options) { return; } this.register({ id: id, registerOptions: options }); } public dispose(): void { this.editorTracker.dispose(); super.dispose(); } protected registerLanguageProvider(options: Proposed.DiagnosticRegistrationOptions): [Disposable, DiagnosticFeatureProvider] { const provider = new DiagnosticFeatureProviderImpl(this._client, this.editorTracker, options); return [provider.disposable, provider]; } }
the_stack
export type Maybe<T> = T | null export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] } export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> } export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number /** * The `Date` scalar type represents a Date * value as specified by * [iso8601](https://en.wikipedia.org/wiki/ISO_8601). */ Date: any /** * The `DateTime` scalar type represents a DateTime * value as specified by * [iso8601](https://en.wikipedia.org/wiki/ISO_8601). */ DateTime: any /** * The `GenericScalar` scalar type represents a generic * GraphQL scalar value that could be: * String, Boolean, Int, Float, List or Object. */ GenericScalar: any /** * Allows use of a JSON String for input / output from the GraphQL schema. * * Use of this type is *not recommended* as you lose the benefits of having a defined, static * schema (one of the key benefits of GraphQL). */ JSONString: any /** * Positive Decimal scalar implementation. * * Should be used in places where value must be positive. */ PositiveDecimal: any UUID: any /** Variables of this type must be set to null in mutations. They will be replaced with a filename from a following multipart part containing a binary file. See: https://github.com/jaydenseric/graphql-multipart-request-spec. */ Upload: any WeightScalar: any /** Anything */ _Any: any } /** Create a new address for the customer. */ export type AccountAddressCreate = { __typename?: 'AccountAddressCreate' /** A user instance for which the address was created. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } /** Delete an address of the logged-in user. */ export type AccountAddressDelete = { __typename?: 'AccountAddressDelete' /** A user instance for which the address was deleted. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } /** Updates an address of the logged-in user. */ export type AccountAddressUpdate = { __typename?: 'AccountAddressUpdate' /** A user object for which the address was edited. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } /** Remove user account. */ export type AccountDelete = { __typename?: 'AccountDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } export type AccountError = { __typename?: 'AccountError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: AccountErrorCode /** A type of address that causes the error. */ addressType?: Maybe<AddressTypeEnum> } /** An enumeration. */ export enum AccountErrorCode { ActivateOwnAccount = 'ACTIVATE_OWN_ACCOUNT', ActivateSuperuserAccount = 'ACTIVATE_SUPERUSER_ACCOUNT', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', DeactivateOwnAccount = 'DEACTIVATE_OWN_ACCOUNT', DeactivateSuperuserAccount = 'DEACTIVATE_SUPERUSER_ACCOUNT', DeleteNonStaffUser = 'DELETE_NON_STAFF_USER', DeleteOwnAccount = 'DELETE_OWN_ACCOUNT', DeleteStaffAccount = 'DELETE_STAFF_ACCOUNT', DeleteSuperuserAccount = 'DELETE_SUPERUSER_ACCOUNT', GraphqlError = 'GRAPHQL_ERROR', Inactive = 'INACTIVE', Invalid = 'INVALID', InvalidPassword = 'INVALID_PASSWORD', LeftNotManageablePermission = 'LEFT_NOT_MANAGEABLE_PERMISSION', InvalidCredentials = 'INVALID_CREDENTIALS', NotFound = 'NOT_FOUND', OutOfScopeUser = 'OUT_OF_SCOPE_USER', OutOfScopeGroup = 'OUT_OF_SCOPE_GROUP', OutOfScopePermission = 'OUT_OF_SCOPE_PERMISSION', PasswordEntirelyNumeric = 'PASSWORD_ENTIRELY_NUMERIC', PasswordTooCommon = 'PASSWORD_TOO_COMMON', PasswordTooShort = 'PASSWORD_TOO_SHORT', PasswordTooSimilar = 'PASSWORD_TOO_SIMILAR', Required = 'REQUIRED', Unique = 'UNIQUE', JwtSignatureExpired = 'JWT_SIGNATURE_EXPIRED', JwtInvalidToken = 'JWT_INVALID_TOKEN', JwtDecodeError = 'JWT_DECODE_ERROR', JwtMissingToken = 'JWT_MISSING_TOKEN', JwtInvalidCsrfToken = 'JWT_INVALID_CSRF_TOKEN', ChannelInactive = 'CHANNEL_INACTIVE', MissingChannelSlug = 'MISSING_CHANNEL_SLUG', } export type AccountInput = { /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** Billing address of the customer. */ defaultBillingAddress?: Maybe<AddressInput> /** Shipping address of the customer. */ defaultShippingAddress?: Maybe<AddressInput> /** User language code. */ languageCode?: Maybe<LanguageCodeEnum> } /** Register a new user. */ export type AccountRegister = { __typename?: 'AccountRegister' /** Informs whether users need to confirm their email address. */ requiresConfirmation?: Maybe<Scalars['Boolean']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } export type AccountRegisterInput = { /** The email address of the user. */ email: Scalars['String'] /** Password. */ password: Scalars['String'] /** Base of frontend URL that will be needed to create confirmation URL. */ redirectUrl?: Maybe<Scalars['String']> /** User language code. */ languageCode?: Maybe<LanguageCodeEnum> /** User public metadata. */ metadata?: Maybe<Array<MetadataInput>> /** Slug of a channel which will be used to notify users. Optional when only one channel exists. */ channel?: Maybe<Scalars['String']> } /** Sends an email with the account removal link for the logged-in user. */ export type AccountRequestDeletion = { __typename?: 'AccountRequestDeletion' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Sets a default address for the authenticated user. */ export type AccountSetDefaultAddress = { __typename?: 'AccountSetDefaultAddress' /** An updated user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Updates the account of the logged-in user. */ export type AccountUpdate = { __typename?: 'AccountUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } /** Represents user address data. */ export type Address = Node & { __typename?: 'Address' /** The ID of the object. */ id: Scalars['ID'] firstName: Scalars['String'] lastName: Scalars['String'] companyName: Scalars['String'] streetAddress1: Scalars['String'] streetAddress2: Scalars['String'] city: Scalars['String'] cityArea: Scalars['String'] postalCode: Scalars['String'] /** Shop's default country. */ country: CountryDisplay countryArea: Scalars['String'] phone?: Maybe<Scalars['String']> /** Address is user's default shipping address. */ isDefaultShippingAddress?: Maybe<Scalars['Boolean']> /** Address is user's default billing address. */ isDefaultBillingAddress?: Maybe<Scalars['Boolean']> } /** Creates user address. */ export type AddressCreate = { __typename?: 'AddressCreate' /** A user instance for which the address was created. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } /** Deletes an address. */ export type AddressDelete = { __typename?: 'AddressDelete' /** A user instance for which the address was deleted. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } export type AddressInput = { /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** Company or organization. */ companyName?: Maybe<Scalars['String']> /** Address. */ streetAddress1?: Maybe<Scalars['String']> /** Address. */ streetAddress2?: Maybe<Scalars['String']> /** City. */ city?: Maybe<Scalars['String']> /** District. */ cityArea?: Maybe<Scalars['String']> /** Postal code. */ postalCode?: Maybe<Scalars['String']> /** Country. */ country?: Maybe<CountryCode> /** State or province. */ countryArea?: Maybe<Scalars['String']> /** Phone number. */ phone?: Maybe<Scalars['String']> } /** Sets a default address for the given user. */ export type AddressSetDefault = { __typename?: 'AddressSetDefault' /** An updated user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** An enumeration. */ export enum AddressTypeEnum { Billing = 'BILLING', Shipping = 'SHIPPING', } /** Updates an address. */ export type AddressUpdate = { __typename?: 'AddressUpdate' /** A user object for which the address was edited. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> address?: Maybe<Address> } export type AddressValidationData = { __typename?: 'AddressValidationData' countryCode?: Maybe<Scalars['String']> countryName?: Maybe<Scalars['String']> addressFormat?: Maybe<Scalars['String']> addressLatinFormat?: Maybe<Scalars['String']> allowedFields?: Maybe<Array<Maybe<Scalars['String']>>> requiredFields?: Maybe<Array<Maybe<Scalars['String']>>> upperFields?: Maybe<Array<Maybe<Scalars['String']>>> countryAreaType?: Maybe<Scalars['String']> countryAreaChoices?: Maybe<Array<Maybe<ChoiceValue>>> cityType?: Maybe<Scalars['String']> cityChoices?: Maybe<Array<Maybe<ChoiceValue>>> cityAreaType?: Maybe<Scalars['String']> cityAreaChoices?: Maybe<Array<Maybe<ChoiceValue>>> postalCodeType?: Maybe<Scalars['String']> postalCodeMatchers?: Maybe<Array<Maybe<Scalars['String']>>> postalCodeExamples?: Maybe<Array<Maybe<Scalars['String']>>> postalCodePrefix?: Maybe<Scalars['String']> } /** Represents allocation. */ export type Allocation = Node & { __typename?: 'Allocation' /** The ID of the object. */ id: Scalars['ID'] /** Quantity allocated for orders. */ quantity: Scalars['Int'] /** The warehouse were items were allocated. */ warehouse: Warehouse } /** Represents app data. */ export type App = Node & ObjectWithMetadata & { __typename?: 'App' /** The ID of the object. */ id: Scalars['ID'] /** Name of the app. */ name?: Maybe<Scalars['String']> /** The date and time when the app was created. */ created?: Maybe<Scalars['DateTime']> /** Determine if app will be set active or not. */ isActive?: Maybe<Scalars['Boolean']> /** List of the app's permissions. */ permissions?: Maybe<Array<Maybe<Permission>>> /** Last 4 characters of the tokens. */ tokens?: Maybe<Array<Maybe<AppToken>>> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Type of the app. */ type?: Maybe<AppTypeEnum> /** List of webhooks assigned to this app. */ webhooks?: Maybe<Array<Maybe<Webhook>>> /** Description of this app. */ aboutApp?: Maybe<Scalars['String']> /** Description of the data privacy defined for this app. */ dataPrivacy?: Maybe<Scalars['String']> /** Url to details about the privacy policy on the app owner page. */ dataPrivacyUrl?: Maybe<Scalars['String']> /** Homepage of the app. */ homepageUrl?: Maybe<Scalars['String']> /** Support page for the app. */ supportUrl?: Maybe<Scalars['String']> /** Url to iframe with the configuration for the app. */ configurationUrl?: Maybe<Scalars['String']> /** Url to iframe with the app. */ appUrl?: Maybe<Scalars['String']> /** Version number of the app. */ version?: Maybe<Scalars['String']> /** JWT token used to authenticate by thridparty app. */ accessToken?: Maybe<Scalars['String']> } /** Activate the app. */ export type AppActivate = { __typename?: 'AppActivate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> app?: Maybe<App> } export type AppCountableConnection = { __typename?: 'AppCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<AppCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type AppCountableEdge = { __typename?: 'AppCountableEdge' /** The item at the end of the edge. */ node: App /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new app. */ export type AppCreate = { __typename?: 'AppCreate' /** The newly created authentication token. */ authToken?: Maybe<Scalars['String']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> app?: Maybe<App> } /** Deactivate the app. */ export type AppDeactivate = { __typename?: 'AppDeactivate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> app?: Maybe<App> } /** Deletes an app. */ export type AppDelete = { __typename?: 'AppDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> app?: Maybe<App> } /** Delete failed installation. */ export type AppDeleteFailedInstallation = { __typename?: 'AppDeleteFailedInstallation' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> appInstallation?: Maybe<AppInstallation> } export type AppError = { __typename?: 'AppError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: AppErrorCode /** List of permissions which causes the error. */ permissions?: Maybe<Array<PermissionEnum>> } /** An enumeration. */ export enum AppErrorCode { Forbidden = 'FORBIDDEN', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', InvalidStatus = 'INVALID_STATUS', InvalidPermission = 'INVALID_PERMISSION', InvalidUrlFormat = 'INVALID_URL_FORMAT', InvalidManifestFormat = 'INVALID_MANIFEST_FORMAT', ManifestUrlCantConnect = 'MANIFEST_URL_CANT_CONNECT', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', OutOfScopeApp = 'OUT_OF_SCOPE_APP', OutOfScopePermission = 'OUT_OF_SCOPE_PERMISSION', } /** Fetch and validate manifest. */ export type AppFetchManifest = { __typename?: 'AppFetchManifest' manifest?: Maybe<Manifest> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> } export type AppFilterInput = { search?: Maybe<Scalars['String']> isActive?: Maybe<Scalars['Boolean']> type?: Maybe<AppTypeEnum> } export type AppInput = { /** Name of the app. */ name?: Maybe<Scalars['String']> /** List of permission code names to assign to this app. */ permissions?: Maybe<Array<Maybe<PermissionEnum>>> } /** Install new app by using app manifest. */ export type AppInstall = { __typename?: 'AppInstall' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> appInstallation?: Maybe<AppInstallation> } export type AppInstallInput = { /** Name of the app to install. */ appName?: Maybe<Scalars['String']> /** Url to app's manifest in JSON format. */ manifestUrl?: Maybe<Scalars['String']> /** Determine if app will be set active or not. */ activateAfterInstallation?: Maybe<Scalars['Boolean']> /** List of permission code names to assign to this app. */ permissions?: Maybe<Array<Maybe<PermissionEnum>>> } /** Represents ongoing installation of app. */ export type AppInstallation = Node & Job & { __typename?: 'AppInstallation' appName: Scalars['String'] manifestUrl: Scalars['String'] /** The ID of the object. */ id: Scalars['ID'] /** Job status. */ status: JobStatusEnum /** Created date time of job in ISO 8601 format. */ createdAt: Scalars['DateTime'] /** Date time of job last update in ISO 8601 format. */ updatedAt: Scalars['DateTime'] /** Job message. */ message?: Maybe<Scalars['String']> } /** Retry failed installation of new app. */ export type AppRetryInstall = { __typename?: 'AppRetryInstall' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> appInstallation?: Maybe<AppInstallation> } export enum AppSortField { /** Sort apps by name. */ Name = 'NAME', /** Sort apps by creation date. */ CreationDate = 'CREATION_DATE', } export type AppSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort apps by the selected field. */ field: AppSortField } /** Represents token data. */ export type AppToken = Node & { __typename?: 'AppToken' /** Name of the authenticated token. */ name?: Maybe<Scalars['String']> /** Last 4 characters of the token. */ authToken?: Maybe<Scalars['String']> /** The ID of the object. */ id: Scalars['ID'] } /** Creates a new token. */ export type AppTokenCreate = { __typename?: 'AppTokenCreate' /** The newly created authentication token. */ authToken?: Maybe<Scalars['String']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> appToken?: Maybe<AppToken> } /** Deletes an authentication token assigned to app. */ export type AppTokenDelete = { __typename?: 'AppTokenDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> appToken?: Maybe<AppToken> } export type AppTokenInput = { /** Name of the token. */ name?: Maybe<Scalars['String']> /** ID of app. */ app: Scalars['ID'] } /** Verify provided app token. */ export type AppTokenVerify = { __typename?: 'AppTokenVerify' /** Determine if token is valid or not. */ valid: Scalars['Boolean'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> } /** Enum determining type of your App. */ export enum AppTypeEnum { /** Local Saleor App. The app is fully manageable from dashboard. You can change assigned permissions, add webhooks, or authentication token */ Local = 'LOCAL', /** Third party external App. Installation is fully automated. Saleor uses a defined App manifest to gather all required information. */ Thirdparty = 'THIRDPARTY', } /** Updates an existing app. */ export type AppUpdate = { __typename?: 'AppUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ appErrors: Array<AppError> errors: Array<AppError> app?: Maybe<App> } /** An enumeration. */ export enum AreaUnitsEnum { SqCm = 'SQ_CM', SqM = 'SQ_M', SqKm = 'SQ_KM', SqFt = 'SQ_FT', SqYd = 'SQ_YD', SqInch = 'SQ_INCH', } /** Assigns storefront's navigation menus. */ export type AssignNavigation = { __typename?: 'AssignNavigation' /** Assigned navigation menu. */ menu?: Maybe<Menu> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> } /** Custom attribute of a product. Attributes can be assigned to products and variants at the product type level. */ export type Attribute = Node & ObjectWithMetadata & { __typename?: 'Attribute' /** The ID of the object. */ id: Scalars['ID'] productTypes: ProductTypeCountableConnection productVariantTypes: ProductTypeCountableConnection /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** The input type to use for entering attribute values in the dashboard. */ inputType?: Maybe<AttributeInputTypeEnum> /** The entity type which can be used as a reference. */ entityType?: Maybe<AttributeEntityTypeEnum> /** Name of an attribute displayed in the interface. */ name?: Maybe<Scalars['String']> /** Internal representation of an attribute name. */ slug?: Maybe<Scalars['String']> /** The attribute type. */ type?: Maybe<AttributeTypeEnum> /** The unit of attribute values. */ unit?: Maybe<MeasurementUnitsEnum> /** List of attribute's values. */ values?: Maybe<Array<Maybe<AttributeValue>>> /** Whether the attribute requires values to be passed or not. */ valueRequired: Scalars['Boolean'] /** Whether the attribute should be visible or not in storefront. */ visibleInStorefront: Scalars['Boolean'] /** Whether the attribute can be filtered in storefront. */ filterableInStorefront: Scalars['Boolean'] /** Whether the attribute can be filtered in dashboard. */ filterableInDashboard: Scalars['Boolean'] /** Whether the attribute can be displayed in the admin product list. */ availableInGrid: Scalars['Boolean'] /** Returns translated attribute fields for the given language code. */ translation?: Maybe<AttributeTranslation> /** The position of the attribute in the storefront navigation (0 by default). */ storefrontSearchPosition: Scalars['Int'] } /** Custom attribute of a product. Attributes can be assigned to products and variants at the product type level. */ export type AttributeProductTypesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Custom attribute of a product. Attributes can be assigned to products and variants at the product type level. */ export type AttributeProductVariantTypesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Custom attribute of a product. Attributes can be assigned to products and variants at the product type level. */ export type AttributeTranslationArgs = { languageCode: LanguageCodeEnum } /** Deletes attributes. */ export type AttributeBulkDelete = { __typename?: 'AttributeBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> } export type AttributeCountableConnection = { __typename?: 'AttributeCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<AttributeCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type AttributeCountableEdge = { __typename?: 'AttributeCountableEdge' /** The item at the end of the edge. */ node: Attribute /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates an attribute. */ export type AttributeCreate = { __typename?: 'AttributeCreate' attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> } export type AttributeCreateInput = { /** The input type to use for entering attribute values in the dashboard. */ inputType?: Maybe<AttributeInputTypeEnum> /** The entity type which can be used as a reference. */ entityType?: Maybe<AttributeEntityTypeEnum> /** Name of an attribute displayed in the interface. */ name: Scalars['String'] /** Internal representation of an attribute name. */ slug?: Maybe<Scalars['String']> /** The attribute type. */ type: AttributeTypeEnum /** The unit of attribute values. */ unit?: Maybe<MeasurementUnitsEnum> /** List of attribute's values. */ values?: Maybe<Array<Maybe<AttributeValueCreateInput>>> /** Whether the attribute requires values to be passed or not. */ valueRequired?: Maybe<Scalars['Boolean']> /** Whether the attribute is for variants only. */ isVariantOnly?: Maybe<Scalars['Boolean']> /** Whether the attribute should be visible or not in storefront. */ visibleInStorefront?: Maybe<Scalars['Boolean']> /** Whether the attribute can be filtered in storefront. */ filterableInStorefront?: Maybe<Scalars['Boolean']> /** Whether the attribute can be filtered in dashboard. */ filterableInDashboard?: Maybe<Scalars['Boolean']> /** The position of the attribute in the storefront navigation (0 by default). */ storefrontSearchPosition?: Maybe<Scalars['Int']> /** Whether the attribute can be displayed in the admin product list. */ availableInGrid?: Maybe<Scalars['Boolean']> } /** Deletes an attribute. */ export type AttributeDelete = { __typename?: 'AttributeDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> attribute?: Maybe<Attribute> } /** An enumeration. */ export enum AttributeEntityTypeEnum { Page = 'PAGE', Product = 'PRODUCT', } export type AttributeError = { __typename?: 'AttributeError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: AttributeErrorCode } /** An enumeration. */ export enum AttributeErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } export type AttributeFilterInput = { valueRequired?: Maybe<Scalars['Boolean']> isVariantOnly?: Maybe<Scalars['Boolean']> visibleInStorefront?: Maybe<Scalars['Boolean']> filterableInStorefront?: Maybe<Scalars['Boolean']> filterableInDashboard?: Maybe<Scalars['Boolean']> availableInGrid?: Maybe<Scalars['Boolean']> metadata?: Maybe<Array<Maybe<MetadataInput>>> search?: Maybe<Scalars['String']> ids?: Maybe<Array<Maybe<Scalars['ID']>>> type?: Maybe<AttributeTypeEnum> inCollection?: Maybe<Scalars['ID']> inCategory?: Maybe<Scalars['ID']> /** Specifies the channel by which the data should be sorted. */ channel?: Maybe<Scalars['String']> } export type AttributeInput = { /** Internal representation of an attribute name. */ slug: Scalars['String'] /** Internal representation of a value (unique per attribute). */ values?: Maybe<Array<Maybe<Scalars['String']>>> /** The range that the returned values should be in. */ valuesRange?: Maybe<IntRangeInput> } /** An enumeration. */ export enum AttributeInputTypeEnum { Dropdown = 'DROPDOWN', Multiselect = 'MULTISELECT', File = 'FILE', Reference = 'REFERENCE', Numeric = 'NUMERIC', RichText = 'RICH_TEXT', } /** Reorder the values of an attribute. */ export type AttributeReorderValues = { __typename?: 'AttributeReorderValues' /** Attribute from which values are reordered. */ attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> } export enum AttributeSortField { /** Sort attributes by name */ Name = 'NAME', /** Sort attributes by slug */ Slug = 'SLUG', /** Sort attributes by the value required flag */ ValueRequired = 'VALUE_REQUIRED', /** Sort attributes by the variant only flag */ IsVariantOnly = 'IS_VARIANT_ONLY', /** Sort attributes by visibility in the storefront */ VisibleInStorefront = 'VISIBLE_IN_STOREFRONT', /** Sort attributes by the filterable in storefront flag */ FilterableInStorefront = 'FILTERABLE_IN_STOREFRONT', /** Sort attributes by the filterable in dashboard flag */ FilterableInDashboard = 'FILTERABLE_IN_DASHBOARD', /** Sort attributes by their position in storefront */ StorefrontSearchPosition = 'STOREFRONT_SEARCH_POSITION', /** Sort attributes based on whether they can be displayed or not in a product grid. */ AvailableInGrid = 'AVAILABLE_IN_GRID', } export type AttributeSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort attributes by the selected field. */ field: AttributeSortField } export type AttributeTranslatableContent = Node & { __typename?: 'AttributeTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Returns translated attribute fields for the given language code. */ translation?: Maybe<AttributeTranslation> /** Custom attribute of a product. */ attribute?: Maybe<Attribute> } export type AttributeTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for attribute. */ export type AttributeTranslate = { __typename?: 'AttributeTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> attribute?: Maybe<Attribute> } export type AttributeTranslation = Node & { __typename?: 'AttributeTranslation' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Translation language. */ language: LanguageDisplay } /** An enumeration. */ export enum AttributeTypeEnum { ProductType = 'PRODUCT_TYPE', PageType = 'PAGE_TYPE', } /** Updates attribute. */ export type AttributeUpdate = { __typename?: 'AttributeUpdate' attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> } export type AttributeUpdateInput = { /** Name of an attribute displayed in the interface. */ name?: Maybe<Scalars['String']> /** Internal representation of an attribute name. */ slug?: Maybe<Scalars['String']> /** The unit of attribute values. */ unit?: Maybe<MeasurementUnitsEnum> /** IDs of values to be removed from this attribute. */ removeValues?: Maybe<Array<Maybe<Scalars['ID']>>> /** New values to be created for this attribute. */ addValues?: Maybe<Array<Maybe<AttributeValueCreateInput>>> /** Whether the attribute requires values to be passed or not. */ valueRequired?: Maybe<Scalars['Boolean']> /** Whether the attribute is for variants only. */ isVariantOnly?: Maybe<Scalars['Boolean']> /** Whether the attribute should be visible or not in storefront. */ visibleInStorefront?: Maybe<Scalars['Boolean']> /** Whether the attribute can be filtered in storefront. */ filterableInStorefront?: Maybe<Scalars['Boolean']> /** Whether the attribute can be filtered in dashboard. */ filterableInDashboard?: Maybe<Scalars['Boolean']> /** The position of the attribute in the storefront navigation (0 by default). */ storefrontSearchPosition?: Maybe<Scalars['Int']> /** Whether the attribute can be displayed in the admin product list. */ availableInGrid?: Maybe<Scalars['Boolean']> } /** Represents a value of an attribute. */ export type AttributeValue = Node & { __typename?: 'AttributeValue' /** The ID of the object. */ id: Scalars['ID'] /** Name of a value displayed in the interface. */ name?: Maybe<Scalars['String']> /** Internal representation of a value (unique per attribute). */ slug?: Maybe<Scalars['String']> /** Represents the value of the attribute value. */ value?: Maybe<Scalars['String']> /** Returns translated attribute value fields for the given language code. */ translation?: Maybe<AttributeValueTranslation> /** The input type to use for entering attribute values in the dashboard. */ inputType?: Maybe<AttributeInputTypeEnum> /** The ID of the attribute reference. */ reference?: Maybe<Scalars['ID']> /** Represents file URL and content type (if attribute value is a file). */ file?: Maybe<File> /** Represents the text (JSON) of the attribute value. */ richText?: Maybe<Scalars['JSONString']> } /** Represents a value of an attribute. */ export type AttributeValueTranslationArgs = { languageCode: LanguageCodeEnum } /** Deletes values of attributes. */ export type AttributeValueBulkDelete = { __typename?: 'AttributeValueBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> } /** Creates a value for an attribute. */ export type AttributeValueCreate = { __typename?: 'AttributeValueCreate' /** The updated attribute. */ attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> attributeValue?: Maybe<AttributeValue> } export type AttributeValueCreateInput = { /** Name of a value displayed in the interface. */ name: Scalars['String'] /** Represents the value of the attribute value. */ value?: Maybe<Scalars['String']> /** Represents the text (JSON) of the attribute value. */ richText?: Maybe<Scalars['JSONString']> } /** Deletes a value of an attribute. */ export type AttributeValueDelete = { __typename?: 'AttributeValueDelete' /** The updated attribute. */ attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> attributeValue?: Maybe<AttributeValue> } export type AttributeValueInput = { /** ID of the selected attribute. */ id?: Maybe<Scalars['ID']> /** The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created. */ values?: Maybe<Array<Maybe<Scalars['String']>>> /** URL of the file attribute. Every time, a new value is created. */ file?: Maybe<Scalars['String']> /** File content type. */ contentType?: Maybe<Scalars['String']> /** List of entity IDs that will be used as references. */ references?: Maybe<Array<Scalars['ID']>> /** Text content in JSON format. */ richText?: Maybe<Scalars['JSONString']> } export type AttributeValueTranslatableContent = Node & { __typename?: 'AttributeValueTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Returns translated attribute value fields for the given language code. */ translation?: Maybe<AttributeValueTranslation> /** Represents a value of an attribute. */ attributeValue?: Maybe<AttributeValue> } export type AttributeValueTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for attribute value. */ export type AttributeValueTranslate = { __typename?: 'AttributeValueTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> attributeValue?: Maybe<AttributeValue> } export type AttributeValueTranslation = Node & { __typename?: 'AttributeValueTranslation' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] richText?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay } export type AttributeValueTranslationInput = { name?: Maybe<Scalars['String']> richText?: Maybe<Scalars['JSONString']> } /** Updates value of an attribute. */ export type AttributeValueUpdate = { __typename?: 'AttributeValueUpdate' /** The updated attribute. */ attribute?: Maybe<Attribute> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ attributeErrors: Array<AttributeError> errors: Array<AttributeError> attributeValue?: Maybe<AttributeValue> } export type BulkAttributeValueInput = { /** ID of the selected attribute. */ id?: Maybe<Scalars['ID']> /** The value or slug of an attribute to resolve. If the passed value is non-existent, it will be created. */ values: Array<Maybe<Scalars['String']>> } export type BulkProductError = { __typename?: 'BulkProductError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ProductErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> /** Index of an input list item that caused the error. */ index?: Maybe<Scalars['Int']> /** List of warehouse IDs which causes the error. */ warehouses?: Maybe<Array<Scalars['ID']>> /** List of channel IDs which causes the error. */ channels?: Maybe<Array<Scalars['ID']>> } export type BulkStockError = { __typename?: 'BulkStockError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ProductErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> /** Index of an input list item that caused the error. */ index?: Maybe<Scalars['Int']> } export type CatalogueInput = { /** Products related to the discount. */ products?: Maybe<Array<Maybe<Scalars['ID']>>> /** Categories related to the discount. */ categories?: Maybe<Array<Maybe<Scalars['ID']>>> /** Collections related to the discount. */ collections?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type Category = Node & ObjectWithMetadata & { __typename?: 'Category' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> slug: Scalars['String'] parent?: Maybe<Category> level: Scalars['Int'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** * Description of the category (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** List of ancestors of the category. */ ancestors?: Maybe<CategoryCountableConnection> /** List of products in the category. */ products?: Maybe<ProductCountableConnection> /** List of children of the category. */ children?: Maybe<CategoryCountableConnection> backgroundImage?: Maybe<Image> /** Returns translated category fields for the given language code. */ translation?: Maybe<CategoryTranslation> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type CategoryAncestorsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type CategoryProductsArgs = { channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type CategoryChildrenArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type CategoryBackgroundImageArgs = { size?: Maybe<Scalars['Int']> } /** Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront. */ export type CategoryTranslationArgs = { languageCode: LanguageCodeEnum } /** Deletes categories. */ export type CategoryBulkDelete = { __typename?: 'CategoryBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type CategoryCountableConnection = { __typename?: 'CategoryCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<CategoryCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type CategoryCountableEdge = { __typename?: 'CategoryCountableEdge' /** The item at the end of the edge. */ node: Category /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new category. */ export type CategoryCreate = { __typename?: 'CategoryCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> category?: Maybe<Category> } /** Deletes a category. */ export type CategoryDelete = { __typename?: 'CategoryDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> category?: Maybe<Category> } export type CategoryFilterInput = { search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> ids?: Maybe<Array<Maybe<Scalars['ID']>>> } export type CategoryInput = { /** Category description (JSON). */ description?: Maybe<Scalars['JSONString']> /** Category name. */ name?: Maybe<Scalars['String']> /** Category slug. */ slug?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** Background image file. */ backgroundImage?: Maybe<Scalars['Upload']> /** Alt text for a product media. */ backgroundImageAlt?: Maybe<Scalars['String']> } export enum CategorySortField { /** Sort categories by name. */ Name = 'NAME', /** Sort categories by product count. */ ProductCount = 'PRODUCT_COUNT', /** Sort categories by subcategory count. */ SubcategoryCount = 'SUBCATEGORY_COUNT', } export type CategorySortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Specifies the channel in which to sort the data. */ channel?: Maybe<Scalars['String']> /** Sort categories by the selected field. */ field: CategorySortField } export type CategoryTranslatableContent = Node & { __typename?: 'CategoryTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** * Description of the category (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** Returns translated category fields for the given language code. */ translation?: Maybe<CategoryTranslation> /** Represents a single category of products. */ category?: Maybe<Category> } export type CategoryTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Category. */ export type CategoryTranslate = { __typename?: 'CategoryTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> category?: Maybe<Category> } export type CategoryTranslation = Node & { __typename?: 'CategoryTranslation' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay /** * Translated description of the product (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> } /** Updates a category. */ export type CategoryUpdate = { __typename?: 'CategoryUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> category?: Maybe<Category> } /** Represents channel. */ export type Channel = Node & { __typename?: 'Channel' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] isActive: Scalars['Boolean'] slug: Scalars['String'] currencyCode: Scalars['String'] /** Whether a channel has associated orders. */ hasOrders: Scalars['Boolean'] } /** Activate a channel. */ export type ChannelActivate = { __typename?: 'ChannelActivate' /** Activated channel. */ channel?: Maybe<Channel> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ channelErrors: Array<ChannelError> errors: Array<ChannelError> } /** Creates new channel. */ export type ChannelCreate = { __typename?: 'ChannelCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ channelErrors: Array<ChannelError> errors: Array<ChannelError> channel?: Maybe<Channel> } export type ChannelCreateInput = { /** isActive flag. */ isActive?: Maybe<Scalars['Boolean']> /** Name of the channel. */ name: Scalars['String'] /** Slug of the channel. */ slug: Scalars['String'] /** Currency of the channel. */ currencyCode: Scalars['String'] /** List of shipping zones to assign to the channel. */ addShippingZones?: Maybe<Array<Scalars['ID']>> } /** Deactivate a channel. */ export type ChannelDeactivate = { __typename?: 'ChannelDeactivate' /** Deactivated channel. */ channel?: Maybe<Channel> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ channelErrors: Array<ChannelError> errors: Array<ChannelError> } /** Delete a channel. Orders associated with the deleted channel will be moved to the target channel. Checkouts, product availability, and pricing will be removed. */ export type ChannelDelete = { __typename?: 'ChannelDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ channelErrors: Array<ChannelError> errors: Array<ChannelError> channel?: Maybe<Channel> } export type ChannelDeleteInput = { /** ID of channel to migrate orders from origin channel. */ targetChannel: Scalars['ID'] } export type ChannelError = { __typename?: 'ChannelError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ChannelErrorCode /** List of shipping zone IDs which causes the error. */ shippingZones?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum ChannelErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', ChannelTargetIdMustBeDifferent = 'CHANNEL_TARGET_ID_MUST_BE_DIFFERENT', ChannelsCurrencyMustBeTheSame = 'CHANNELS_CURRENCY_MUST_BE_THE_SAME', ChannelWithOrders = 'CHANNEL_WITH_ORDERS', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', } /** Update a channel. */ export type ChannelUpdate = { __typename?: 'ChannelUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ channelErrors: Array<ChannelError> errors: Array<ChannelError> channel?: Maybe<Channel> } export type ChannelUpdateInput = { /** isActive flag. */ isActive?: Maybe<Scalars['Boolean']> /** Name of the channel. */ name?: Maybe<Scalars['String']> /** Slug of the channel. */ slug?: Maybe<Scalars['String']> /** List of shipping zones to assign to the channel. */ addShippingZones?: Maybe<Array<Scalars['ID']>> /** List of shipping zones to unassign from the channel. */ removeShippingZones?: Maybe<Array<Scalars['ID']>> } /** Checkout object. */ export type Checkout = Node & ObjectWithMetadata & { __typename?: 'Checkout' created: Scalars['DateTime'] lastChange: Scalars['DateTime'] user?: Maybe<User> channel: Channel billingAddress?: Maybe<Address> shippingAddress?: Maybe<Address> note: Scalars['String'] discount?: Maybe<Money> discountName?: Maybe<Scalars['String']> translatedDiscountName?: Maybe<Scalars['String']> voucherCode?: Maybe<Scalars['String']> /** List of gift cards associated with this checkout. */ giftCards?: Maybe<Array<Maybe<GiftCard>>> /** The ID of the object. */ id: Scalars['ID'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Shipping methods that can be used with this order. */ availableShippingMethods: Array<Maybe<ShippingMethod>> /** List of available payment gateways. */ availablePaymentGateways: Array<PaymentGateway> /** Email of a customer. */ email: Scalars['String'] /** Returns True, if checkout requires shipping. */ isShippingRequired: Scalars['Boolean'] /** The number of items purchased. */ quantity: Scalars['Int'] /** A list of checkout lines, each containing information about an item in the checkout. */ lines?: Maybe<Array<Maybe<CheckoutLine>>> /** The price of the shipping, with all the taxes included. */ shippingPrice?: Maybe<TaxedMoney> /** The shipping method related with checkout. */ shippingMethod?: Maybe<ShippingMethod> /** The price of the checkout before shipping, with taxes included. */ subtotalPrice?: Maybe<TaxedMoney> /** The checkout's token. */ token: Scalars['UUID'] /** The sum of the the checkout line prices, with all the taxes,shipping costs, and discounts included. */ totalPrice?: Maybe<TaxedMoney> /** Checkout language code. */ languageCode: LanguageCodeEnum } /** Adds a gift card or a voucher to a checkout. */ export type CheckoutAddPromoCode = { __typename?: 'CheckoutAddPromoCode' /** The checkout with the added gift card or voucher. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Update billing address in the existing checkout. */ export type CheckoutBillingAddressUpdate = { __typename?: 'CheckoutBillingAddressUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Completes the checkout. As a result a new order is created and a payment charge is made. This action requires a successful payment before it can be performed. In case additional confirmation step as 3D secure is required confirmationNeeded flag will be set to True and no order created until payment is confirmed with second call of this mutation. */ export type CheckoutComplete = { __typename?: 'CheckoutComplete' /** Placed order. */ order?: Maybe<Order> /** Set to true if payment needs to be confirmed before checkout is complete. */ confirmationNeeded: Scalars['Boolean'] /** Confirmation data used to process additional authorization steps. */ confirmationData?: Maybe<Scalars['JSONString']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } export type CheckoutCountableConnection = { __typename?: 'CheckoutCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<CheckoutCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type CheckoutCountableEdge = { __typename?: 'CheckoutCountableEdge' /** The item at the end of the edge. */ node: Checkout /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Create a new checkout. */ export type CheckoutCreate = { __typename?: 'CheckoutCreate' /** Whether the checkout was created or the current active one was returned. Refer to checkoutLinesAdd and checkoutLinesUpdate to merge a cart with an active checkout.DEPRECATED: Will be removed in Saleor 4.0. Always returns True. */ created?: Maybe<Scalars['Boolean']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> checkout?: Maybe<Checkout> } export type CheckoutCreateInput = { /** Slug of a channel in which to create a checkout. */ channel?: Maybe<Scalars['String']> /** A list of checkout lines, each containing information about an item in the checkout. */ lines: Array<Maybe<CheckoutLineInput>> /** The customer's email address. */ email?: Maybe<Scalars['String']> /** The mailing address to where the checkout will be shipped. Note: the address will be ignored if the checkout doesn't contain shippable items. */ shippingAddress?: Maybe<AddressInput> /** Billing address of the customer. */ billingAddress?: Maybe<AddressInput> /** Checkout language code. */ languageCode?: Maybe<LanguageCodeEnum> } /** Sets the customer as the owner of the checkout. */ export type CheckoutCustomerAttach = { __typename?: 'CheckoutCustomerAttach' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Removes the user assigned as the owner of the checkout. */ export type CheckoutCustomerDetach = { __typename?: 'CheckoutCustomerDetach' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Updates email address in the existing checkout object. */ export type CheckoutEmailUpdate = { __typename?: 'CheckoutEmailUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } export type CheckoutError = { __typename?: 'CheckoutError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: CheckoutErrorCode /** List of varint IDs which causes the error. */ variants?: Maybe<Array<Scalars['ID']>> /** A type of address that causes the error. */ addressType?: Maybe<AddressTypeEnum> } /** An enumeration. */ export enum CheckoutErrorCode { BillingAddressNotSet = 'BILLING_ADDRESS_NOT_SET', CheckoutNotFullyPaid = 'CHECKOUT_NOT_FULLY_PAID', GraphqlError = 'GRAPHQL_ERROR', ProductNotPublished = 'PRODUCT_NOT_PUBLISHED', ProductUnavailableForPurchase = 'PRODUCT_UNAVAILABLE_FOR_PURCHASE', InsufficientStock = 'INSUFFICIENT_STOCK', Invalid = 'INVALID', InvalidShippingMethod = 'INVALID_SHIPPING_METHOD', NotFound = 'NOT_FOUND', PaymentError = 'PAYMENT_ERROR', QuantityGreaterThanLimit = 'QUANTITY_GREATER_THAN_LIMIT', Required = 'REQUIRED', ShippingAddressNotSet = 'SHIPPING_ADDRESS_NOT_SET', ShippingMethodNotApplicable = 'SHIPPING_METHOD_NOT_APPLICABLE', ShippingMethodNotSet = 'SHIPPING_METHOD_NOT_SET', ShippingNotRequired = 'SHIPPING_NOT_REQUIRED', TaxError = 'TAX_ERROR', Unique = 'UNIQUE', VoucherNotApplicable = 'VOUCHER_NOT_APPLICABLE', ZeroQuantity = 'ZERO_QUANTITY', MissingChannelSlug = 'MISSING_CHANNEL_SLUG', ChannelInactive = 'CHANNEL_INACTIVE', UnavailableVariantInChannel = 'UNAVAILABLE_VARIANT_IN_CHANNEL', } /** Update language code in the existing checkout. */ export type CheckoutLanguageCodeUpdate = { __typename?: 'CheckoutLanguageCodeUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Represents an item in the checkout. */ export type CheckoutLine = Node & { __typename?: 'CheckoutLine' /** The ID of the object. */ id: Scalars['ID'] variant: ProductVariant quantity: Scalars['Int'] /** The sum of the checkout line price, taxes and discounts. */ totalPrice?: Maybe<TaxedMoney> /** Indicates whether the item need to be delivered. */ requiresShipping?: Maybe<Scalars['Boolean']> } export type CheckoutLineCountableConnection = { __typename?: 'CheckoutLineCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<CheckoutLineCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type CheckoutLineCountableEdge = { __typename?: 'CheckoutLineCountableEdge' /** The item at the end of the edge. */ node: CheckoutLine /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Deletes a CheckoutLine. */ export type CheckoutLineDelete = { __typename?: 'CheckoutLineDelete' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } export type CheckoutLineInput = { /** The number of items purchased. */ quantity: Scalars['Int'] /** ID of the product variant. */ variantId: Scalars['ID'] } /** Adds a checkout line to the existing checkout. */ export type CheckoutLinesAdd = { __typename?: 'CheckoutLinesAdd' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Updates checkout line in the existing checkout. */ export type CheckoutLinesUpdate = { __typename?: 'CheckoutLinesUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Create a new payment for given checkout. */ export type CheckoutPaymentCreate = { __typename?: 'CheckoutPaymentCreate' /** Related checkout object. */ checkout?: Maybe<Checkout> /** A newly created payment. */ payment?: Maybe<Payment> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ paymentErrors: Array<PaymentError> errors: Array<PaymentError> } /** Remove a gift card or a voucher from a checkout. */ export type CheckoutRemovePromoCode = { __typename?: 'CheckoutRemovePromoCode' /** The checkout with the removed gift card or voucher. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Update shipping address in the existing checkout. */ export type CheckoutShippingAddressUpdate = { __typename?: 'CheckoutShippingAddressUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } /** Updates the shipping address of the checkout. */ export type CheckoutShippingMethodUpdate = { __typename?: 'CheckoutShippingMethodUpdate' /** An updated checkout. */ checkout?: Maybe<Checkout> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ checkoutErrors: Array<CheckoutError> errors: Array<CheckoutError> } export type ChoiceValue = { __typename?: 'ChoiceValue' raw?: Maybe<Scalars['String']> verbose?: Maybe<Scalars['String']> } /** Represents a collection of products. */ export type Collection = Node & ObjectWithMetadata & { __typename?: 'Collection' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> slug: Scalars['String'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** * Description of the collection (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** List of products in this collection. */ products?: Maybe<ProductCountableConnection> backgroundImage?: Maybe<Image> /** Returns translated collection fields for the given language code. */ translation?: Maybe<CollectionTranslation> /** List of channels in which the collection is available. */ channelListings?: Maybe<Array<CollectionChannelListing>> } /** Represents a collection of products. */ export type CollectionProductsArgs = { filter?: Maybe<ProductFilterInput> sortBy?: Maybe<ProductOrder> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents a collection of products. */ export type CollectionBackgroundImageArgs = { size?: Maybe<Scalars['Int']> } /** Represents a collection of products. */ export type CollectionTranslationArgs = { languageCode: LanguageCodeEnum } /** Adds products to a collection. */ export type CollectionAddProducts = { __typename?: 'CollectionAddProducts' /** Collection to which products will be added. */ collection?: Maybe<Collection> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> } /** Deletes collections. */ export type CollectionBulkDelete = { __typename?: 'CollectionBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> } /** Represents collection channel listing. */ export type CollectionChannelListing = Node & { __typename?: 'CollectionChannelListing' /** The ID of the object. */ id: Scalars['ID'] publicationDate?: Maybe<Scalars['Date']> isPublished: Scalars['Boolean'] channel: Channel } export type CollectionChannelListingError = { __typename?: 'CollectionChannelListingError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ProductErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> /** List of channels IDs which causes the error. */ channels?: Maybe<Array<Scalars['ID']>> } /** Manage collection's availability in channels. */ export type CollectionChannelListingUpdate = { __typename?: 'CollectionChannelListingUpdate' /** An updated collection instance. */ collection?: Maybe<Collection> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionChannelListingErrors: Array<CollectionChannelListingError> errors: Array<CollectionChannelListingError> } export type CollectionChannelListingUpdateInput = { /** List of channels to which the collection should be assigned. */ addChannels?: Maybe<Array<PublishableChannelListingInput>> /** List of channels from which the collection should be unassigned. */ removeChannels?: Maybe<Array<Scalars['ID']>> } export type CollectionCountableConnection = { __typename?: 'CollectionCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<CollectionCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type CollectionCountableEdge = { __typename?: 'CollectionCountableEdge' /** The item at the end of the edge. */ node: Collection /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new collection. */ export type CollectionCreate = { __typename?: 'CollectionCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> collection?: Maybe<Collection> } export type CollectionCreateInput = { /** Informs whether a collection is published. */ isPublished?: Maybe<Scalars['Boolean']> /** Name of the collection. */ name?: Maybe<Scalars['String']> /** Slug of the collection. */ slug?: Maybe<Scalars['String']> /** Description of the collection (JSON). */ description?: Maybe<Scalars['JSONString']> /** Background image file. */ backgroundImage?: Maybe<Scalars['Upload']> /** Alt text for an image. */ backgroundImageAlt?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['Date']> /** List of products to be added to the collection. */ products?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Deletes a collection. */ export type CollectionDelete = { __typename?: 'CollectionDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> collection?: Maybe<Collection> } export type CollectionError = { __typename?: 'CollectionError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** List of products IDs which causes the error. */ products?: Maybe<Array<Scalars['ID']>> /** The error code. */ code: CollectionErrorCode } /** An enumeration. */ export enum CollectionErrorCode { DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', CannotManageProductWithoutVariant = 'CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT', } export type CollectionFilterInput = { published?: Maybe<CollectionPublished> search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> ids?: Maybe<Array<Maybe<Scalars['ID']>>> /** Specifies the channel by which the data should be sorted. */ channel?: Maybe<Scalars['String']> } export type CollectionInput = { /** Informs whether a collection is published. */ isPublished?: Maybe<Scalars['Boolean']> /** Name of the collection. */ name?: Maybe<Scalars['String']> /** Slug of the collection. */ slug?: Maybe<Scalars['String']> /** Description of the collection (JSON). */ description?: Maybe<Scalars['JSONString']> /** Background image file. */ backgroundImage?: Maybe<Scalars['Upload']> /** Alt text for an image. */ backgroundImageAlt?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['Date']> } export enum CollectionPublished { Published = 'PUBLISHED', Hidden = 'HIDDEN', } /** Remove products from a collection. */ export type CollectionRemoveProducts = { __typename?: 'CollectionRemoveProducts' /** Collection from which products will be removed. */ collection?: Maybe<Collection> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> } /** Reorder the products of a collection. */ export type CollectionReorderProducts = { __typename?: 'CollectionReorderProducts' /** Collection from which products are reordered. */ collection?: Maybe<Collection> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> } export enum CollectionSortField { /** Sort collections by name. */ Name = 'NAME', /** Sort collections by availability. */ Availability = 'AVAILABILITY', /** Sort collections by product count. */ ProductCount = 'PRODUCT_COUNT', /** Sort collections by publication date. */ PublicationDate = 'PUBLICATION_DATE', } export type CollectionSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Specifies the channel in which to sort the data. */ channel?: Maybe<Scalars['String']> /** Sort collections by the selected field. */ field: CollectionSortField } export type CollectionTranslatableContent = Node & { __typename?: 'CollectionTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** * Description of the collection (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** Returns translated collection fields for the given language code. */ translation?: Maybe<CollectionTranslation> /** Represents a collection of products. */ collection?: Maybe<Collection> } export type CollectionTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for collection. */ export type CollectionTranslate = { __typename?: 'CollectionTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> collection?: Maybe<Collection> } export type CollectionTranslation = Node & { __typename?: 'CollectionTranslation' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay /** * Translated description of the product (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> } /** Updates a collection. */ export type CollectionUpdate = { __typename?: 'CollectionUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ collectionErrors: Array<CollectionError> errors: Array<CollectionError> collection?: Maybe<Collection> } /** Stores information about a single configuration field. */ export type ConfigurationItem = { __typename?: 'ConfigurationItem' /** Name of the field. */ name: Scalars['String'] /** Current value of the field. */ value?: Maybe<Scalars['String']> /** Type of the field. */ type?: Maybe<ConfigurationTypeFieldEnum> /** Help text for the field. */ helpText?: Maybe<Scalars['String']> /** Label for the field. */ label?: Maybe<Scalars['String']> } export type ConfigurationItemInput = { /** Name of the field to update. */ name: Scalars['String'] /** Value of the given field to update. */ value?: Maybe<Scalars['String']> } /** An enumeration. */ export enum ConfigurationTypeFieldEnum { String = 'STRING', Multiline = 'MULTILINE', Boolean = 'BOOLEAN', Secret = 'SECRET', Password = 'PASSWORD', Secretmultiline = 'SECRETMULTILINE', Output = 'OUTPUT', } /** Confirm user account with token sent by email during registration. */ export type ConfirmAccount = { __typename?: 'ConfirmAccount' /** An activated user account. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Confirm the email change of the logged-in user. */ export type ConfirmEmailChange = { __typename?: 'ConfirmEmailChange' /** A user instance with a new email. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** An enumeration. */ export enum CountryCode { Af = 'AF', Ax = 'AX', Al = 'AL', Dz = 'DZ', As = 'AS', Ad = 'AD', Ao = 'AO', Ai = 'AI', Aq = 'AQ', Ag = 'AG', Ar = 'AR', Am = 'AM', Aw = 'AW', Au = 'AU', At = 'AT', Az = 'AZ', Bs = 'BS', Bh = 'BH', Bd = 'BD', Bb = 'BB', By = 'BY', Be = 'BE', Bz = 'BZ', Bj = 'BJ', Bm = 'BM', Bt = 'BT', Bo = 'BO', Bq = 'BQ', Ba = 'BA', Bw = 'BW', Bv = 'BV', Br = 'BR', Io = 'IO', Bn = 'BN', Bg = 'BG', Bf = 'BF', Bi = 'BI', Cv = 'CV', Kh = 'KH', Cm = 'CM', Ca = 'CA', Ky = 'KY', Cf = 'CF', Td = 'TD', Cl = 'CL', Cn = 'CN', Cx = 'CX', Cc = 'CC', Co = 'CO', Km = 'KM', Cg = 'CG', Cd = 'CD', Ck = 'CK', Cr = 'CR', Ci = 'CI', Hr = 'HR', Cu = 'CU', Cw = 'CW', Cy = 'CY', Cz = 'CZ', Dk = 'DK', Dj = 'DJ', Dm = 'DM', Do = 'DO', Ec = 'EC', Eg = 'EG', Sv = 'SV', Gq = 'GQ', Er = 'ER', Ee = 'EE', Sz = 'SZ', Et = 'ET', Eu = 'EU', Fk = 'FK', Fo = 'FO', Fj = 'FJ', Fi = 'FI', Fr = 'FR', Gf = 'GF', Pf = 'PF', Tf = 'TF', Ga = 'GA', Gm = 'GM', Ge = 'GE', De = 'DE', Gh = 'GH', Gi = 'GI', Gr = 'GR', Gl = 'GL', Gd = 'GD', Gp = 'GP', Gu = 'GU', Gt = 'GT', Gg = 'GG', Gn = 'GN', Gw = 'GW', Gy = 'GY', Ht = 'HT', Hm = 'HM', Va = 'VA', Hn = 'HN', Hk = 'HK', Hu = 'HU', Is = 'IS', In = 'IN', Id = 'ID', Ir = 'IR', Iq = 'IQ', Ie = 'IE', Im = 'IM', Il = 'IL', It = 'IT', Jm = 'JM', Jp = 'JP', Je = 'JE', Jo = 'JO', Kz = 'KZ', Ke = 'KE', Ki = 'KI', Kw = 'KW', Kg = 'KG', La = 'LA', Lv = 'LV', Lb = 'LB', Ls = 'LS', Lr = 'LR', Ly = 'LY', Li = 'LI', Lt = 'LT', Lu = 'LU', Mo = 'MO', Mg = 'MG', Mw = 'MW', My = 'MY', Mv = 'MV', Ml = 'ML', Mt = 'MT', Mh = 'MH', Mq = 'MQ', Mr = 'MR', Mu = 'MU', Yt = 'YT', Mx = 'MX', Fm = 'FM', Md = 'MD', Mc = 'MC', Mn = 'MN', Me = 'ME', Ms = 'MS', Ma = 'MA', Mz = 'MZ', Mm = 'MM', Na = 'NA', Nr = 'NR', Np = 'NP', Nl = 'NL', Nc = 'NC', Nz = 'NZ', Ni = 'NI', Ne = 'NE', Ng = 'NG', Nu = 'NU', Nf = 'NF', Kp = 'KP', Mk = 'MK', Mp = 'MP', No = 'NO', Om = 'OM', Pk = 'PK', Pw = 'PW', Ps = 'PS', Pa = 'PA', Pg = 'PG', Py = 'PY', Pe = 'PE', Ph = 'PH', Pn = 'PN', Pl = 'PL', Pt = 'PT', Pr = 'PR', Qa = 'QA', Re = 'RE', Ro = 'RO', Ru = 'RU', Rw = 'RW', Bl = 'BL', Sh = 'SH', Kn = 'KN', Lc = 'LC', Mf = 'MF', Pm = 'PM', Vc = 'VC', Ws = 'WS', Sm = 'SM', St = 'ST', Sa = 'SA', Sn = 'SN', Rs = 'RS', Sc = 'SC', Sl = 'SL', Sg = 'SG', Sx = 'SX', Sk = 'SK', Si = 'SI', Sb = 'SB', So = 'SO', Za = 'ZA', Gs = 'GS', Kr = 'KR', Ss = 'SS', Es = 'ES', Lk = 'LK', Sd = 'SD', Sr = 'SR', Sj = 'SJ', Se = 'SE', Ch = 'CH', Sy = 'SY', Tw = 'TW', Tj = 'TJ', Tz = 'TZ', Th = 'TH', Tl = 'TL', Tg = 'TG', Tk = 'TK', To = 'TO', Tt = 'TT', Tn = 'TN', Tr = 'TR', Tm = 'TM', Tc = 'TC', Tv = 'TV', Ug = 'UG', Ua = 'UA', Ae = 'AE', Gb = 'GB', Um = 'UM', Us = 'US', Uy = 'UY', Uz = 'UZ', Vu = 'VU', Ve = 'VE', Vn = 'VN', Vg = 'VG', Vi = 'VI', Wf = 'WF', Eh = 'EH', Ye = 'YE', Zm = 'ZM', Zw = 'ZW', } export type CountryDisplay = { __typename?: 'CountryDisplay' /** Country code. */ code: Scalars['String'] /** Country name. */ country: Scalars['String'] /** Country tax. */ vat?: Maybe<Vat> } /** Create JWT token. */ export type CreateToken = { __typename?: 'CreateToken' /** JWT token, required to authenticate. */ token?: Maybe<Scalars['String']> /** JWT refresh token, required to re-generate access token. */ refreshToken?: Maybe<Scalars['String']> /** CSRF token required to re-generate access token. */ csrfToken?: Maybe<Scalars['String']> /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } export type CreditCard = { __typename?: 'CreditCard' /** Card brand. */ brand: Scalars['String'] /** First 4 digits of the card number. */ firstDigits?: Maybe<Scalars['String']> /** Last 4 digits of the card number. */ lastDigits: Scalars['String'] /** Two-digit number representing the card’s expiration month. */ expMonth?: Maybe<Scalars['Int']> /** Four-digit number representing the card’s expiration year. */ expYear?: Maybe<Scalars['Int']> } /** Deletes customers. */ export type CustomerBulkDelete = { __typename?: 'CustomerBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Creates a new customer. */ export type CustomerCreate = { __typename?: 'CustomerCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } /** Deletes a customer. */ export type CustomerDelete = { __typename?: 'CustomerDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } /** History log of the customer. */ export type CustomerEvent = Node & { __typename?: 'CustomerEvent' /** The ID of the object. */ id: Scalars['ID'] /** Date when event happened at in ISO 8601 format. */ date?: Maybe<Scalars['DateTime']> /** Customer event type. */ type?: Maybe<CustomerEventsEnum> /** User who performed the action. */ user?: Maybe<User> /** Content of the event. */ message?: Maybe<Scalars['String']> /** Number of objects concerned by the event. */ count?: Maybe<Scalars['Int']> /** The concerned order. */ order?: Maybe<Order> /** The concerned order line. */ orderLine?: Maybe<OrderLine> } /** An enumeration. */ export enum CustomerEventsEnum { AccountCreated = 'ACCOUNT_CREATED', PasswordResetLinkSent = 'PASSWORD_RESET_LINK_SENT', PasswordReset = 'PASSWORD_RESET', EmailChangedRequest = 'EMAIL_CHANGED_REQUEST', PasswordChanged = 'PASSWORD_CHANGED', EmailChanged = 'EMAIL_CHANGED', PlacedOrder = 'PLACED_ORDER', NoteAddedToOrder = 'NOTE_ADDED_TO_ORDER', DigitalLinkDownloaded = 'DIGITAL_LINK_DOWNLOADED', CustomerDeleted = 'CUSTOMER_DELETED', NameAssigned = 'NAME_ASSIGNED', EmailAssigned = 'EMAIL_ASSIGNED', NoteAdded = 'NOTE_ADDED', } export type CustomerFilterInput = { dateJoined?: Maybe<DateRangeInput> numberOfOrders?: Maybe<IntRangeInput> placedOrders?: Maybe<DateRangeInput> search?: Maybe<Scalars['String']> } export type CustomerInput = { /** Billing address of the customer. */ defaultBillingAddress?: Maybe<AddressInput> /** Shipping address of the customer. */ defaultShippingAddress?: Maybe<AddressInput> /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** The unique email address of the user. */ email?: Maybe<Scalars['String']> /** User account is active. */ isActive?: Maybe<Scalars['Boolean']> /** A note about the user. */ note?: Maybe<Scalars['String']> /** User language code. */ languageCode?: Maybe<LanguageCodeEnum> } /** Updates an existing customer. */ export type CustomerUpdate = { __typename?: 'CustomerUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> user?: Maybe<User> } export type DateRangeInput = { /** Start date. */ gte?: Maybe<Scalars['Date']> /** End date. */ lte?: Maybe<Scalars['Date']> } export type DateTimeRangeInput = { /** Start date. */ gte?: Maybe<Scalars['DateTime']> /** End date. */ lte?: Maybe<Scalars['DateTime']> } /** Deactivate all JWT tokens of the currently authenticated user. */ export type DeactivateAllUserTokens = { __typename?: 'DeactivateAllUserTokens' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Delete metadata of an object. */ export type DeleteMetadata = { __typename?: 'DeleteMetadata' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ metadataErrors: Array<MetadataError> errors: Array<MetadataError> item?: Maybe<ObjectWithMetadata> } /** Delete object's private metadata. */ export type DeletePrivateMetadata = { __typename?: 'DeletePrivateMetadata' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ metadataErrors: Array<MetadataError> errors: Array<MetadataError> item?: Maybe<ObjectWithMetadata> } export type DigitalContent = Node & ObjectWithMetadata & { __typename?: 'DigitalContent' useDefaultSettings: Scalars['Boolean'] automaticFulfillment: Scalars['Boolean'] contentFile: Scalars['String'] maxDownloads?: Maybe<Scalars['Int']> urlValidDays?: Maybe<Scalars['Int']> /** List of URLs for the digital variant. */ urls?: Maybe<Array<Maybe<DigitalContentUrl>>> /** The ID of the object. */ id: Scalars['ID'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Product variant assigned to digital content. */ productVariant: ProductVariant } export type DigitalContentCountableConnection = { __typename?: 'DigitalContentCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<DigitalContentCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type DigitalContentCountableEdge = { __typename?: 'DigitalContentCountableEdge' /** The item at the end of the edge. */ node: DigitalContent /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ export type DigitalContentCreate = { __typename?: 'DigitalContentCreate' variant?: Maybe<ProductVariant> content?: Maybe<DigitalContent> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Remove digital content assigned to given variant. */ export type DigitalContentDelete = { __typename?: 'DigitalContentDelete' variant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type DigitalContentInput = { /** Use default digital content settings for this product. */ useDefaultSettings: Scalars['Boolean'] /** Determines how many times a download link can be accessed by a customer. */ maxDownloads?: Maybe<Scalars['Int']> /** Determines for how many days a download link is active since it was generated. */ urlValidDays?: Maybe<Scalars['Int']> /** Overwrite default automatic_fulfillment setting for variant. */ automaticFulfillment?: Maybe<Scalars['Boolean']> } /** Update digital content. */ export type DigitalContentUpdate = { __typename?: 'DigitalContentUpdate' variant?: Maybe<ProductVariant> content?: Maybe<DigitalContent> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type DigitalContentUploadInput = { /** Use default digital content settings for this product. */ useDefaultSettings: Scalars['Boolean'] /** Determines how many times a download link can be accessed by a customer. */ maxDownloads?: Maybe<Scalars['Int']> /** Determines for how many days a download link is active since it was generated. */ urlValidDays?: Maybe<Scalars['Int']> /** Overwrite default automatic_fulfillment setting for variant. */ automaticFulfillment?: Maybe<Scalars['Boolean']> /** Represents an file in a multipart request. */ contentFile: Scalars['Upload'] } export type DigitalContentUrl = Node & { __typename?: 'DigitalContentUrl' content: DigitalContent created: Scalars['DateTime'] downloadNum: Scalars['Int'] /** The ID of the object. */ id: Scalars['ID'] /** URL for digital content. */ url?: Maybe<Scalars['String']> /** UUID of digital content. */ token: Scalars['UUID'] } /** Generate new URL to digital content. */ export type DigitalContentUrlCreate = { __typename?: 'DigitalContentUrlCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> digitalContentUrl?: Maybe<DigitalContentUrl> } export type DigitalContentUrlCreateInput = { /** Digital content ID which URL will belong to. */ content: Scalars['ID'] } export type DiscountError = { __typename?: 'DiscountError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** List of products IDs which causes the error. */ products?: Maybe<Array<Scalars['ID']>> /** The error code. */ code: DiscountErrorCode /** List of channels IDs which causes the error. */ channels?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum DiscountErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', CannotManageProductWithoutVariant = 'CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', } export enum DiscountStatusEnum { Active = 'ACTIVE', Expired = 'EXPIRED', Scheduled = 'SCHEDULED', } export enum DiscountValueTypeEnum { Fixed = 'FIXED', Percentage = 'PERCENTAGE', } /** An enumeration. */ export enum DistanceUnitsEnum { Cm = 'CM', M = 'M', Km = 'KM', Ft = 'FT', Yd = 'YD', Inch = 'INCH', } /** Represents shop's domain. */ export type Domain = { __typename?: 'Domain' /** The host name of the domain. */ host: Scalars['String'] /** Inform if SSL is enabled. */ sslEnabled: Scalars['Boolean'] /** Shop's absolute URL. */ url: Scalars['String'] } /** Deletes draft orders. */ export type DraftOrderBulkDelete = { __typename?: 'DraftOrderBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Completes creating an order. */ export type DraftOrderComplete = { __typename?: 'DraftOrderComplete' /** Completed order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Creates a new draft order. */ export type DraftOrderCreate = { __typename?: 'DraftOrderCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> order?: Maybe<Order> } export type DraftOrderCreateInput = { /** Billing address of the customer. */ billingAddress?: Maybe<AddressInput> user?: Maybe<Scalars['ID']> /** Email address of the customer. */ userEmail?: Maybe<Scalars['String']> /** Discount amount for the order. */ discount?: Maybe<Scalars['PositiveDecimal']> /** Shipping address of the customer. */ shippingAddress?: Maybe<AddressInput> /** ID of a selected shipping method. */ shippingMethod?: Maybe<Scalars['ID']> /** ID of the voucher associated with the order. */ voucher?: Maybe<Scalars['ID']> /** A note from a customer. Visible by customers in the order summary. */ customerNote?: Maybe<Scalars['String']> /** ID of the channel associated with the order. */ channel?: Maybe<Scalars['ID']> /** URL of a view where users should be redirected to see the order details. URL in RFC 1808 format. */ redirectUrl?: Maybe<Scalars['String']> /** Variant line input consisting of variant ID and quantity of products. */ lines?: Maybe<Array<Maybe<OrderLineCreateInput>>> } /** Deletes a draft order. */ export type DraftOrderDelete = { __typename?: 'DraftOrderDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> order?: Maybe<Order> } export type DraftOrderInput = { /** Billing address of the customer. */ billingAddress?: Maybe<AddressInput> user?: Maybe<Scalars['ID']> /** Email address of the customer. */ userEmail?: Maybe<Scalars['String']> /** Discount amount for the order. */ discount?: Maybe<Scalars['PositiveDecimal']> /** Shipping address of the customer. */ shippingAddress?: Maybe<AddressInput> /** ID of a selected shipping method. */ shippingMethod?: Maybe<Scalars['ID']> /** ID of the voucher associated with the order. */ voucher?: Maybe<Scalars['ID']> /** A note from a customer. Visible by customers in the order summary. */ customerNote?: Maybe<Scalars['String']> /** ID of the channel associated with the order. */ channel?: Maybe<Scalars['ID']> /** URL of a view where users should be redirected to see the order details. URL in RFC 1808 format. */ redirectUrl?: Maybe<Scalars['String']> } /** Deletes order lines. */ export type DraftOrderLinesBulkDelete = { __typename?: 'DraftOrderLinesBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Updates a draft order. */ export type DraftOrderUpdate = { __typename?: 'DraftOrderUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> order?: Maybe<Order> } export type ExportError = { __typename?: 'ExportError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ExportErrorCode } /** An enumeration. */ export enum ExportErrorCode { Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', } /** History log of export file. */ export type ExportEvent = Node & { __typename?: 'ExportEvent' /** The ID of the object. */ id: Scalars['ID'] /** Date when event happened at in ISO 8601 format. */ date: Scalars['DateTime'] /** Export event type. */ type: ExportEventsEnum /** User who performed the action. */ user?: Maybe<User> /** App which performed the action. */ app?: Maybe<App> /** Content of the event. */ message: Scalars['String'] } /** An enumeration. */ export enum ExportEventsEnum { ExportPending = 'EXPORT_PENDING', ExportSuccess = 'EXPORT_SUCCESS', ExportFailed = 'EXPORT_FAILED', ExportDeleted = 'EXPORT_DELETED', ExportedFileSent = 'EXPORTED_FILE_SENT', ExportFailedInfoSent = 'EXPORT_FAILED_INFO_SENT', } /** Represents a job data of exported file. */ export type ExportFile = Node & Job & { __typename?: 'ExportFile' /** The ID of the object. */ id: Scalars['ID'] user?: Maybe<User> app?: Maybe<App> /** Job status. */ status: JobStatusEnum /** Created date time of job in ISO 8601 format. */ createdAt: Scalars['DateTime'] /** Date time of job last update in ISO 8601 format. */ updatedAt: Scalars['DateTime'] /** Job message. */ message?: Maybe<Scalars['String']> /** The URL of field to download. */ url?: Maybe<Scalars['String']> /** List of events associated with the export. */ events?: Maybe<Array<ExportEvent>> } export type ExportFileCountableConnection = { __typename?: 'ExportFileCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<ExportFileCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type ExportFileCountableEdge = { __typename?: 'ExportFileCountableEdge' /** The item at the end of the edge. */ node: ExportFile /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type ExportFileFilterInput = { createdAt?: Maybe<DateTimeRangeInput> updatedAt?: Maybe<DateTimeRangeInput> status?: Maybe<JobStatusEnum> user?: Maybe<Scalars['String']> app?: Maybe<Scalars['String']> } export enum ExportFileSortField { /** Sort export file by status. */ Status = 'STATUS', /** Sort export file by created at. */ CreatedAt = 'CREATED_AT', /** Sort export file by updated at. */ UpdatedAt = 'UPDATED_AT', } export type ExportFileSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort export file by the selected field. */ field: ExportFileSortField } export type ExportInfoInput = { /** List of attribute ids witch should be exported. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of warehouse ids witch should be exported. */ warehouses?: Maybe<Array<Scalars['ID']>> /** List of channels ids which should be exported. */ channels?: Maybe<Array<Scalars['ID']>> /** List of product fields witch should be exported. */ fields?: Maybe<Array<ProductFieldEnum>> } /** Export products to csv file. */ export type ExportProducts = { __typename?: 'ExportProducts' /** The newly created export file job which is responsible for export data. */ exportFile?: Maybe<ExportFile> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ exportErrors: Array<ExportError> errors: Array<ExportError> } export type ExportProductsInput = { /** Determine which products should be exported. */ scope: ExportScope /** Filtering options for products. */ filter?: Maybe<ProductFilterInput> /** List of products IDS to export. */ ids?: Maybe<Array<Scalars['ID']>> /** Input with info about fields which should be exported. */ exportInfo?: Maybe<ExportInfoInput> /** Type of exported file. */ fileType: FileTypesEnum } export enum ExportScope { /** Export all products. */ All = 'ALL', /** Export products with given ids. */ Ids = 'IDS', /** Export the filtered products. */ Filter = 'FILTER', } export type ExternalAuthentication = { __typename?: 'ExternalAuthentication' /** ID of external authentication plugin. */ id: Scalars['String'] /** Name of external authentication plugin. */ name?: Maybe<Scalars['String']> } /** Prepare external authentication url for user by custom plugin. */ export type ExternalAuthenticationUrl = { __typename?: 'ExternalAuthenticationUrl' /** The data returned by authentication plugin. */ authenticationData?: Maybe<Scalars['JSONString']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Logout user by custom plugin. */ export type ExternalLogout = { __typename?: 'ExternalLogout' /** The data returned by authentication plugin. */ logoutData?: Maybe<Scalars['JSONString']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Obtain external access tokens for user by custom plugin. */ export type ExternalObtainAccessTokens = { __typename?: 'ExternalObtainAccessTokens' /** The token, required to authenticate. */ token?: Maybe<Scalars['String']> /** The refresh token, required to re-generate external access token. */ refreshToken?: Maybe<Scalars['String']> /** CSRF token required to re-generate external access token. */ csrfToken?: Maybe<Scalars['String']> /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Refresh user's access by custom plugin. */ export type ExternalRefresh = { __typename?: 'ExternalRefresh' /** The token, required to authenticate. */ token?: Maybe<Scalars['String']> /** The refresh token, required to re-generate external access token. */ refreshToken?: Maybe<Scalars['String']> /** CSRF token required to re-generate external access token. */ csrfToken?: Maybe<Scalars['String']> /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Verify external authentication data by plugin. */ export type ExternalVerify = { __typename?: 'ExternalVerify' /** User assigned to data. */ user?: Maybe<User> /** Determine if authentication data is valid or not. */ isValid: Scalars['Boolean'] /** External data. */ verifyData?: Maybe<Scalars['JSONString']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } export type File = { __typename?: 'File' /** The URL of the file. */ url: Scalars['String'] /** Content type of the file. */ contentType?: Maybe<Scalars['String']> } /** An enumeration. */ export enum FileTypesEnum { Csv = 'CSV', Xlsx = 'XLSX', } /** Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ export type FileUpload = { __typename?: 'FileUpload' uploadedFile?: Maybe<File> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ uploadErrors: Array<UploadError> errors: Array<UploadError> } /** Represents order fulfillment. */ export type Fulfillment = Node & ObjectWithMetadata & { __typename?: 'Fulfillment' /** The ID of the object. */ id: Scalars['ID'] fulfillmentOrder: Scalars['Int'] status: FulfillmentStatus trackingNumber: Scalars['String'] created: Scalars['DateTime'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** List of lines for the fulfillment. */ lines?: Maybe<Array<Maybe<FulfillmentLine>>> /** User-friendly fulfillment status. */ statusDisplay?: Maybe<Scalars['String']> /** Warehouse from fulfillment was fulfilled. */ warehouse?: Maybe<Warehouse> } /** Cancels existing fulfillment and optionally restocks items. */ export type FulfillmentCancel = { __typename?: 'FulfillmentCancel' /** A canceled fulfillment. */ fulfillment?: Maybe<Fulfillment> /** Order which fulfillment was cancelled. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type FulfillmentCancelInput = { /** ID of warehouse where items will be restock. */ warehouseId: Scalars['ID'] } /** Represents line of the fulfillment. */ export type FulfillmentLine = Node & { __typename?: 'FulfillmentLine' /** The ID of the object. */ id: Scalars['ID'] quantity: Scalars['Int'] orderLine?: Maybe<OrderLine> } /** Refund products. */ export type FulfillmentRefundProducts = { __typename?: 'FulfillmentRefundProducts' /** A refunded fulfillment. */ fulfillment?: Maybe<Fulfillment> /** Order which fulfillment was refunded. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Return products. */ export type FulfillmentReturnProducts = { __typename?: 'FulfillmentReturnProducts' /** A return fulfillment. */ returnFulfillment?: Maybe<Fulfillment> /** A replace fulfillment. */ replaceFulfillment?: Maybe<Fulfillment> /** Order which fulfillment was returned. */ order?: Maybe<Order> /** A draft order which was created for products with replace flag. */ replaceOrder?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** An enumeration. */ export enum FulfillmentStatus { /** Fulfilled */ Fulfilled = 'FULFILLED', /** Refunded */ Refunded = 'REFUNDED', /** Returned */ Returned = 'RETURNED', /** Replaced */ Replaced = 'REPLACED', /** Refunded and returned */ RefundedAndReturned = 'REFUNDED_AND_RETURNED', /** Canceled */ Canceled = 'CANCELED', } /** Updates a fulfillment for an order. */ export type FulfillmentUpdateTracking = { __typename?: 'FulfillmentUpdateTracking' /** A fulfillment with updated tracking. */ fulfillment?: Maybe<Fulfillment> /** Order for which fulfillment was updated. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type FulfillmentUpdateTrackingInput = { /** Fulfillment tracking number. */ trackingNumber?: Maybe<Scalars['String']> /** If true, send an email notification to the customer. */ notifyCustomer?: Maybe<Scalars['Boolean']> } /** Payment gateway client configuration key and value pair. */ export type GatewayConfigLine = { __typename?: 'GatewayConfigLine' /** Gateway config key. */ field: Scalars['String'] /** Gateway config value for key. */ value?: Maybe<Scalars['String']> } /** A gift card is a prepaid electronic payment card accepted in stores. They can be used during checkout by providing a valid gift card codes. */ export type GiftCard = Node & { __typename?: 'GiftCard' /** Gift card code. */ code?: Maybe<Scalars['String']> /** The customer who bought a gift card. */ user?: Maybe<User> created: Scalars['DateTime'] startDate: Scalars['Date'] endDate?: Maybe<Scalars['Date']> lastUsedOn?: Maybe<Scalars['DateTime']> isActive: Scalars['Boolean'] initialBalance?: Maybe<Money> currentBalance?: Maybe<Money> /** The ID of the object. */ id: Scalars['ID'] /** Code in format which allows displaying in a user interface. */ displayCode?: Maybe<Scalars['String']> } /** Activate a gift card. */ export type GiftCardActivate = { __typename?: 'GiftCardActivate' /** A gift card to activate. */ giftCard?: Maybe<GiftCard> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ giftCardErrors: Array<GiftCardError> errors: Array<GiftCardError> } export type GiftCardCountableConnection = { __typename?: 'GiftCardCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<GiftCardCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type GiftCardCountableEdge = { __typename?: 'GiftCardCountableEdge' /** The item at the end of the edge. */ node: GiftCard /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new gift card. */ export type GiftCardCreate = { __typename?: 'GiftCardCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ giftCardErrors: Array<GiftCardError> errors: Array<GiftCardError> giftCard?: Maybe<GiftCard> } export type GiftCardCreateInput = { /** Start date of the gift card in ISO 8601 format. */ startDate?: Maybe<Scalars['Date']> /** End date of the gift card in ISO 8601 format. */ endDate?: Maybe<Scalars['Date']> /** Value of the gift card. */ balance?: Maybe<Scalars['PositiveDecimal']> /** The customer's email of the gift card buyer. */ userEmail?: Maybe<Scalars['String']> /** Code to use the gift card. */ code?: Maybe<Scalars['String']> } /** Deactivate a gift card. */ export type GiftCardDeactivate = { __typename?: 'GiftCardDeactivate' /** A gift card to deactivate. */ giftCard?: Maybe<GiftCard> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ giftCardErrors: Array<GiftCardError> errors: Array<GiftCardError> } export type GiftCardError = { __typename?: 'GiftCardError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: GiftCardErrorCode } /** An enumeration. */ export enum GiftCardErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } /** Update a gift card. */ export type GiftCardUpdate = { __typename?: 'GiftCardUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ giftCardErrors: Array<GiftCardError> errors: Array<GiftCardError> giftCard?: Maybe<GiftCard> } export type GiftCardUpdateInput = { /** Start date of the gift card in ISO 8601 format. */ startDate?: Maybe<Scalars['Date']> /** End date of the gift card in ISO 8601 format. */ endDate?: Maybe<Scalars['Date']> /** Value of the gift card. */ balance?: Maybe<Scalars['PositiveDecimal']> /** The customer's email of the gift card buyer. */ userEmail?: Maybe<Scalars['String']> } /** Represents permission group data. */ export type Group = Node & { __typename?: 'Group' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** List of group permissions */ permissions?: Maybe<Array<Maybe<Permission>>> /** List of group users */ users?: Maybe<Array<Maybe<User>>> /** True, if the currently authenticated user has rights to manage a group. */ userCanManage: Scalars['Boolean'] } export type GroupCountableConnection = { __typename?: 'GroupCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<GroupCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type GroupCountableEdge = { __typename?: 'GroupCountableEdge' /** The item at the end of the edge. */ node: Group /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Represents an image. */ export type Image = { __typename?: 'Image' /** The URL of the image. */ url: Scalars['String'] /** Alt text for an image. */ alt?: Maybe<Scalars['String']> } export type IntRangeInput = { /** Value greater than or equal to. */ gte?: Maybe<Scalars['Int']> /** Value less than or equal to. */ lte?: Maybe<Scalars['Int']> } /** Represents an Invoice. */ export type Invoice = ObjectWithMetadata & Job & Node & { __typename?: 'Invoice' /** The ID of the object. */ id: Scalars['ID'] /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Job status. */ status: JobStatusEnum number?: Maybe<Scalars['String']> externalUrl?: Maybe<Scalars['String']> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** Created date time of job in ISO 8601 format. */ createdAt: Scalars['DateTime'] /** Date time of job last update in ISO 8601 format. */ updatedAt: Scalars['DateTime'] /** Job message. */ message?: Maybe<Scalars['String']> /** URL to download an invoice. */ url?: Maybe<Scalars['String']> } /** Creates a ready to send invoice. */ export type InvoiceCreate = { __typename?: 'InvoiceCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } export type InvoiceCreateInput = { /** Invoice number. */ number: Scalars['String'] /** URL of an invoice to download. */ url: Scalars['String'] } /** Deletes an invoice. */ export type InvoiceDelete = { __typename?: 'InvoiceDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } export type InvoiceError = { __typename?: 'InvoiceError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: InvoiceErrorCode } /** An enumeration. */ export enum InvoiceErrorCode { Required = 'REQUIRED', NotReady = 'NOT_READY', UrlNotSet = 'URL_NOT_SET', EmailNotSet = 'EMAIL_NOT_SET', NumberNotSet = 'NUMBER_NOT_SET', NotFound = 'NOT_FOUND', InvalidStatus = 'INVALID_STATUS', } /** Request an invoice for the order using plugin. */ export type InvoiceRequest = { __typename?: 'InvoiceRequest' /** Order related to an invoice. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } /** Requests deletion of an invoice. */ export type InvoiceRequestDelete = { __typename?: 'InvoiceRequestDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } /** Send an invoice notification to the customer. */ export type InvoiceSendNotification = { __typename?: 'InvoiceSendNotification' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } /** Updates an invoice. */ export type InvoiceUpdate = { __typename?: 'InvoiceUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ invoiceErrors: Array<InvoiceError> errors: Array<InvoiceError> invoice?: Maybe<Invoice> } export type Job = { /** Job status. */ status: JobStatusEnum /** Created date time of job in ISO 8601 format. */ createdAt: Scalars['DateTime'] /** Date time of job last update in ISO 8601 format. */ updatedAt: Scalars['DateTime'] /** Job message. */ message?: Maybe<Scalars['String']> } /** An enumeration. */ export enum JobStatusEnum { Pending = 'PENDING', Success = 'SUCCESS', Failed = 'FAILED', Deleted = 'DELETED', } /** An enumeration. */ export enum LanguageCodeEnum { Ar = 'AR', Az = 'AZ', Bg = 'BG', Bn = 'BN', Ca = 'CA', Cs = 'CS', Da = 'DA', De = 'DE', El = 'EL', En = 'EN', Es = 'ES', EsCo = 'ES_CO', Et = 'ET', Fa = 'FA', Fi = 'FI', Fr = 'FR', Hi = 'HI', Hu = 'HU', Hy = 'HY', Id = 'ID', Is = 'IS', It = 'IT', Ja = 'JA', Ka = 'KA', Km = 'KM', Ko = 'KO', Lt = 'LT', Mn = 'MN', My = 'MY', Nb = 'NB', Nl = 'NL', Pl = 'PL', Pt = 'PT', PtBr = 'PT_BR', Ro = 'RO', Ru = 'RU', Sk = 'SK', Sl = 'SL', Sq = 'SQ', Sr = 'SR', Sv = 'SV', Sw = 'SW', Ta = 'TA', Th = 'TH', Tr = 'TR', Uk = 'UK', Vi = 'VI', ZhHans = 'ZH_HANS', ZhHant = 'ZH_HANT', } export type LanguageDisplay = { __typename?: 'LanguageDisplay' /** ISO 639 representation of the language name. */ code: LanguageCodeEnum /** Full name of the language. */ language: Scalars['String'] } export type LimitInfo = { __typename?: 'LimitInfo' /** Defines the current resource usage. */ currentUsage: Limits /** Defines the allowed maximum resource usage, null means unlimited. */ allowedUsage: Limits } export type Limits = { __typename?: 'Limits' channels?: Maybe<Scalars['Int']> orders?: Maybe<Scalars['Int']> productVariants?: Maybe<Scalars['Int']> staffUsers?: Maybe<Scalars['Int']> warehouses?: Maybe<Scalars['Int']> } /** The manifest definition. */ export type Manifest = { __typename?: 'Manifest' identifier: Scalars['String'] version: Scalars['String'] name: Scalars['String'] about?: Maybe<Scalars['String']> permissions?: Maybe<Array<Maybe<Permission>>> appUrl?: Maybe<Scalars['String']> configurationUrl?: Maybe<Scalars['String']> tokenTargetUrl?: Maybe<Scalars['String']> dataPrivacy?: Maybe<Scalars['String']> dataPrivacyUrl?: Maybe<Scalars['String']> homepageUrl?: Maybe<Scalars['String']> supportUrl?: Maybe<Scalars['String']> } export type Margin = { __typename?: 'Margin' start?: Maybe<Scalars['Int']> stop?: Maybe<Scalars['Int']> } /** An enumeration. */ export enum MeasurementUnitsEnum { Cm = 'CM', M = 'M', Km = 'KM', Ft = 'FT', Yd = 'YD', Inch = 'INCH', SqCm = 'SQ_CM', SqM = 'SQ_M', SqKm = 'SQ_KM', SqFt = 'SQ_FT', SqYd = 'SQ_YD', SqInch = 'SQ_INCH', CubicMillimeter = 'CUBIC_MILLIMETER', CubicCentimeter = 'CUBIC_CENTIMETER', CubicDecimeter = 'CUBIC_DECIMETER', CubicMeter = 'CUBIC_METER', Liter = 'LITER', CubicFoot = 'CUBIC_FOOT', CubicInch = 'CUBIC_INCH', CubicYard = 'CUBIC_YARD', Qt = 'QT', Pint = 'PINT', FlOz = 'FL_OZ', AcreIn = 'ACRE_IN', AcreFt = 'ACRE_FT', G = 'G', Lb = 'LB', Oz = 'OZ', Kg = 'KG', Tonne = 'TONNE', } /** Represents a single menu - an object that is used to help navigate through the store. */ export type Menu = Node & ObjectWithMetadata & { __typename?: 'Menu' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] slug: Scalars['String'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> items?: Maybe<Array<Maybe<MenuItem>>> } /** Deletes menus. */ export type MenuBulkDelete = { __typename?: 'MenuBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> } export type MenuCountableConnection = { __typename?: 'MenuCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<MenuCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type MenuCountableEdge = { __typename?: 'MenuCountableEdge' /** The item at the end of the edge. */ node: Menu /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new Menu. */ export type MenuCreate = { __typename?: 'MenuCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menu?: Maybe<Menu> } export type MenuCreateInput = { /** Name of the menu. */ name: Scalars['String'] /** Slug of the menu. Will be generated if not provided. */ slug?: Maybe<Scalars['String']> /** List of menu items. */ items?: Maybe<Array<Maybe<MenuItemInput>>> } /** Deletes a menu. */ export type MenuDelete = { __typename?: 'MenuDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menu?: Maybe<Menu> } export type MenuError = { __typename?: 'MenuError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: MenuErrorCode } /** An enumeration. */ export enum MenuErrorCode { CannotAssignNode = 'CANNOT_ASSIGN_NODE', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', InvalidMenuItem = 'INVALID_MENU_ITEM', NoMenuItemProvided = 'NO_MENU_ITEM_PROVIDED', NotFound = 'NOT_FOUND', Required = 'REQUIRED', TooManyMenuItems = 'TOO_MANY_MENU_ITEMS', Unique = 'UNIQUE', } export type MenuFilterInput = { search?: Maybe<Scalars['String']> slug?: Maybe<Array<Maybe<Scalars['String']>>> metadata?: Maybe<Array<Maybe<MetadataInput>>> } export type MenuInput = { /** Name of the menu. */ name?: Maybe<Scalars['String']> /** Slug of the menu. */ slug?: Maybe<Scalars['String']> } /** Represents a single item of the related menu. Can store categories, collection or pages. */ export type MenuItem = Node & ObjectWithMetadata & { __typename?: 'MenuItem' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] menu: Menu parent?: Maybe<MenuItem> category?: Maybe<Category> collection?: Maybe<Collection> page?: Maybe<Page> level: Scalars['Int'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> children?: Maybe<Array<Maybe<MenuItem>>> /** URL to the menu item. */ url?: Maybe<Scalars['String']> /** Returns translated menu item fields for the given language code. */ translation?: Maybe<MenuItemTranslation> } /** Represents a single item of the related menu. Can store categories, collection or pages. */ export type MenuItemTranslationArgs = { languageCode: LanguageCodeEnum } /** Deletes menu items. */ export type MenuItemBulkDelete = { __typename?: 'MenuItemBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> } export type MenuItemCountableConnection = { __typename?: 'MenuItemCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<MenuItemCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type MenuItemCountableEdge = { __typename?: 'MenuItemCountableEdge' /** The item at the end of the edge. */ node: MenuItem /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new menu item. */ export type MenuItemCreate = { __typename?: 'MenuItemCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menuItem?: Maybe<MenuItem> } export type MenuItemCreateInput = { /** Name of the menu item. */ name: Scalars['String'] /** URL of the pointed item. */ url?: Maybe<Scalars['String']> /** Category to which item points. */ category?: Maybe<Scalars['ID']> /** Collection to which item points. */ collection?: Maybe<Scalars['ID']> /** Page to which item points. */ page?: Maybe<Scalars['ID']> /** Menu to which item belongs. */ menu: Scalars['ID'] /** ID of the parent menu. If empty, menu will be top level menu. */ parent?: Maybe<Scalars['ID']> } /** Deletes a menu item. */ export type MenuItemDelete = { __typename?: 'MenuItemDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menuItem?: Maybe<MenuItem> } export type MenuItemFilterInput = { search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> } export type MenuItemInput = { /** Name of the menu item. */ name?: Maybe<Scalars['String']> /** URL of the pointed item. */ url?: Maybe<Scalars['String']> /** Category to which item points. */ category?: Maybe<Scalars['ID']> /** Collection to which item points. */ collection?: Maybe<Scalars['ID']> /** Page to which item points. */ page?: Maybe<Scalars['ID']> } /** Moves items of menus. */ export type MenuItemMove = { __typename?: 'MenuItemMove' /** Assigned menu to move within. */ menu?: Maybe<Menu> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> } export type MenuItemMoveInput = { /** The menu item ID to move. */ itemId: Scalars['ID'] /** ID of the parent menu. If empty, menu will be top level menu. */ parentId?: Maybe<Scalars['ID']> /** The new relative sorting position of the item (from -inf to +inf). 1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged. */ sortOrder?: Maybe<Scalars['Int']> } export type MenuItemSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort menu items by the selected field. */ field: MenuItemsSortField } export type MenuItemTranslatableContent = Node & { __typename?: 'MenuItemTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Returns translated menu item fields for the given language code. */ translation?: Maybe<MenuItemTranslation> /** Represents a single item of the related menu. Can store categories, collection or pages. */ menuItem?: Maybe<MenuItem> } export type MenuItemTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Menu Item. */ export type MenuItemTranslate = { __typename?: 'MenuItemTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> menuItem?: Maybe<MenuItem> } export type MenuItemTranslation = Node & { __typename?: 'MenuItemTranslation' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Translation language. */ language: LanguageDisplay } /** Updates a menu item. */ export type MenuItemUpdate = { __typename?: 'MenuItemUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menuItem?: Maybe<MenuItem> } export enum MenuItemsSortField { /** Sort menu items by name. */ Name = 'NAME', } export enum MenuSortField { /** Sort menus by name. */ Name = 'NAME', /** Sort menus by items count. */ ItemsCount = 'ITEMS_COUNT', } export type MenuSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort menus by the selected field. */ field: MenuSortField } /** Updates a menu. */ export type MenuUpdate = { __typename?: 'MenuUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ menuErrors: Array<MenuError> errors: Array<MenuError> menu?: Maybe<Menu> } export type MetadataError = { __typename?: 'MetadataError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: MetadataErrorCode } /** An enumeration. */ export enum MetadataErrorCode { GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', } export type MetadataInput = { /** Key of a metadata item. */ key: Scalars['String'] /** Value of a metadata item. */ value: Scalars['String'] } export type MetadataItem = { __typename?: 'MetadataItem' /** Key of a metadata item. */ key: Scalars['String'] /** Value of a metadata item. */ value: Scalars['String'] } /** Represents amount of money in specific currency. */ export type Money = { __typename?: 'Money' /** Currency code. */ currency: Scalars['String'] /** Amount of money. */ amount: Scalars['Float'] } /** Represents a range of amounts of money. */ export type MoneyRange = { __typename?: 'MoneyRange' /** Lower bound of a price range. */ start?: Maybe<Money> /** Upper bound of a price range. */ stop?: Maybe<Money> } export type MoveProductInput = { /** The ID of the product to move. */ productId: Scalars['ID'] /** The relative sorting position of the product (from -inf to +inf) starting from the first given product's actual position.1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged. */ sortOrder?: Maybe<Scalars['Int']> } export type Mutation = { __typename?: 'Mutation' /** Creates a new webhook subscription. */ webhookCreate?: Maybe<WebhookCreate> /** Deletes a webhook subscription. */ webhookDelete?: Maybe<WebhookDelete> /** Updates a webhook subscription. */ webhookUpdate?: Maybe<WebhookUpdate> /** Creates new warehouse. */ createWarehouse?: Maybe<WarehouseCreate> /** Updates given warehouse. */ updateWarehouse?: Maybe<WarehouseUpdate> /** Deletes selected warehouse. */ deleteWarehouse?: Maybe<WarehouseDelete> /** Add shipping zone to given warehouse. */ assignWarehouseShippingZone?: Maybe<WarehouseShippingZoneAssign> /** Remove shipping zone from given warehouse. */ unassignWarehouseShippingZone?: Maybe<WarehouseShippingZoneUnassign> /** Creates a new staff notification recipient. */ staffNotificationRecipientCreate?: Maybe<StaffNotificationRecipientCreate> /** Updates a staff notification recipient. */ staffNotificationRecipientUpdate?: Maybe<StaffNotificationRecipientUpdate> /** Delete staff notification recipient. */ staffNotificationRecipientDelete?: Maybe<StaffNotificationRecipientDelete> /** Updates site domain of the shop. */ shopDomainUpdate?: Maybe<ShopDomainUpdate> /** Updates shop settings. */ shopSettingsUpdate?: Maybe<ShopSettingsUpdate> /** Fetch tax rates. */ shopFetchTaxRates?: Maybe<ShopFetchTaxRates> /** Creates/Updates translations for Shop Settings. */ shopSettingsTranslate?: Maybe<ShopSettingsTranslate> /** Update the shop's address. If the `null` value is passed, the currently selected address will be deleted. */ shopAddressUpdate?: Maybe<ShopAddressUpdate> /** Update shop order settings. */ orderSettingsUpdate?: Maybe<OrderSettingsUpdate> /** Manage shipping method's availability in channels. */ shippingMethodChannelListingUpdate?: Maybe<ShippingMethodChannelListingUpdate> /** Creates a new shipping price. */ shippingPriceCreate?: Maybe<ShippingPriceCreate> /** Deletes a shipping price. */ shippingPriceDelete?: Maybe<ShippingPriceDelete> /** Deletes shipping prices. */ shippingPriceBulkDelete?: Maybe<ShippingPriceBulkDelete> /** Updates a new shipping price. */ shippingPriceUpdate?: Maybe<ShippingPriceUpdate> /** Creates/Updates translations for shipping method. */ shippingPriceTranslate?: Maybe<ShippingPriceTranslate> /** Exclude products from shipping price. */ shippingPriceExcludeProducts?: Maybe<ShippingPriceExcludeProducts> /** Remove product from excluded list for shipping price. */ shippingPriceRemoveProductFromExclude?: Maybe<ShippingPriceRemoveProductFromExclude> /** Creates a new shipping zone. */ shippingZoneCreate?: Maybe<ShippingZoneCreate> /** Deletes a shipping zone. */ shippingZoneDelete?: Maybe<ShippingZoneDelete> /** Deletes shipping zones. */ shippingZoneBulkDelete?: Maybe<ShippingZoneBulkDelete> /** Updates a new shipping zone. */ shippingZoneUpdate?: Maybe<ShippingZoneUpdate> /** Assign attributes to a given product type. */ productAttributeAssign?: Maybe<ProductAttributeAssign> /** Un-assign attributes from a given product type. */ productAttributeUnassign?: Maybe<ProductAttributeUnassign> /** Creates a new category. */ categoryCreate?: Maybe<CategoryCreate> /** Deletes a category. */ categoryDelete?: Maybe<CategoryDelete> /** Deletes categories. */ categoryBulkDelete?: Maybe<CategoryBulkDelete> /** Updates a category. */ categoryUpdate?: Maybe<CategoryUpdate> /** Creates/Updates translations for Category. */ categoryTranslate?: Maybe<CategoryTranslate> /** Adds products to a collection. */ collectionAddProducts?: Maybe<CollectionAddProducts> /** Creates a new collection. */ collectionCreate?: Maybe<CollectionCreate> /** Deletes a collection. */ collectionDelete?: Maybe<CollectionDelete> /** Reorder the products of a collection. */ collectionReorderProducts?: Maybe<CollectionReorderProducts> /** Deletes collections. */ collectionBulkDelete?: Maybe<CollectionBulkDelete> /** Remove products from a collection. */ collectionRemoveProducts?: Maybe<CollectionRemoveProducts> /** Updates a collection. */ collectionUpdate?: Maybe<CollectionUpdate> /** Creates/Updates translations for collection. */ collectionTranslate?: Maybe<CollectionTranslate> /** Manage collection's availability in channels. */ collectionChannelListingUpdate?: Maybe<CollectionChannelListingUpdate> /** Creates a new product. */ productCreate?: Maybe<ProductCreate> /** Deletes a product. */ productDelete?: Maybe<ProductDelete> /** Deletes products. */ productBulkDelete?: Maybe<ProductBulkDelete> /** Updates an existing product. */ productUpdate?: Maybe<ProductUpdate> /** Creates/Updates translations for Product. */ productTranslate?: Maybe<ProductTranslate> /** Manage product's availability in channels. */ productChannelListingUpdate?: Maybe<ProductChannelListingUpdate> /** Create a media object (image or video URL) associated with product. For image, this mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ productMediaCreate?: Maybe<ProductMediaCreate> /** Reorder the variants of a product. Mutation updates updated_at on product and triggers PRODUCT_UPDATED webhook. */ productVariantReorder?: Maybe<ProductVariantReorder> /** Deletes a product media. */ productMediaDelete?: Maybe<ProductMediaDelete> /** Deletes product media. */ productMediaBulkDelete?: Maybe<ProductMediaBulkDelete> /** Changes ordering of the product media. */ productMediaReorder?: Maybe<ProductMediaReorder> /** Updates a product media. */ productMediaUpdate?: Maybe<ProductMediaUpdate> /** Creates a new product type. */ productTypeCreate?: Maybe<ProductTypeCreate> /** Deletes a product type. */ productTypeDelete?: Maybe<ProductTypeDelete> /** Deletes product types. */ productTypeBulkDelete?: Maybe<ProductTypeBulkDelete> /** Updates an existing product type. */ productTypeUpdate?: Maybe<ProductTypeUpdate> /** Reorder the attributes of a product type. */ productTypeReorderAttributes?: Maybe<ProductTypeReorderAttributes> /** Reorder product attribute values. */ productReorderAttributeValues?: Maybe<ProductReorderAttributeValues> /** Create new digital content. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ digitalContentCreate?: Maybe<DigitalContentCreate> /** Remove digital content assigned to given variant. */ digitalContentDelete?: Maybe<DigitalContentDelete> /** Update digital content. */ digitalContentUpdate?: Maybe<DigitalContentUpdate> /** Generate new URL to digital content. */ digitalContentUrlCreate?: Maybe<DigitalContentUrlCreate> /** Creates a new variant for a product. */ productVariantCreate?: Maybe<ProductVariantCreate> /** Deletes a product variant. */ productVariantDelete?: Maybe<ProductVariantDelete> /** Creates product variants for a given product. */ productVariantBulkCreate?: Maybe<ProductVariantBulkCreate> /** Deletes product variants. */ productVariantBulkDelete?: Maybe<ProductVariantBulkDelete> /** Creates stocks for product variant. */ productVariantStocksCreate?: Maybe<ProductVariantStocksCreate> /** Delete stocks from product variant. */ productVariantStocksDelete?: Maybe<ProductVariantStocksDelete> /** Update stocks for product variant. */ productVariantStocksUpdate?: Maybe<ProductVariantStocksUpdate> /** Updates an existing variant for product. */ productVariantUpdate?: Maybe<ProductVariantUpdate> /** Set default variant for a product. Mutation triggers PRODUCT_UPDATED webhook. */ productVariantSetDefault?: Maybe<ProductVariantSetDefault> /** Creates/Updates translations for Product Variant. */ productVariantTranslate?: Maybe<ProductVariantTranslate> /** Manage product variant prices in channels. */ productVariantChannelListingUpdate?: Maybe<ProductVariantChannelListingUpdate> /** Reorder product variant attribute values. */ productVariantReorderAttributeValues?: Maybe<ProductVariantReorderAttributeValues> /** Assign an media to a product variant. */ variantMediaAssign?: Maybe<VariantMediaAssign> /** Unassign an media from a product variant. */ variantMediaUnassign?: Maybe<VariantMediaUnassign> /** Captures the authorized payment amount. */ paymentCapture?: Maybe<PaymentCapture> /** Refunds the captured payment amount. */ paymentRefund?: Maybe<PaymentRefund> /** Voids the authorized payment. */ paymentVoid?: Maybe<PaymentVoid> /** Initializes payment process when it is required by gateway. */ paymentInitialize?: Maybe<PaymentInitialize> /** Creates a new page. */ pageCreate?: Maybe<PageCreate> /** Deletes a page. */ pageDelete?: Maybe<PageDelete> /** Deletes pages. */ pageBulkDelete?: Maybe<PageBulkDelete> /** Publish pages. */ pageBulkPublish?: Maybe<PageBulkPublish> /** Updates an existing page. */ pageUpdate?: Maybe<PageUpdate> /** Creates/Updates translations for Page. */ pageTranslate?: Maybe<PageTranslate> /** Create a new page type. */ pageTypeCreate?: Maybe<PageTypeCreate> /** Update page type. */ pageTypeUpdate?: Maybe<PageTypeUpdate> /** Delete a page type. */ pageTypeDelete?: Maybe<PageTypeDelete> /** Delete page types. */ pageTypeBulkDelete?: Maybe<PageTypeBulkDelete> /** Assign attributes to a given page type. */ pageAttributeAssign?: Maybe<PageAttributeAssign> /** Unassign attributes from a given page type. */ pageAttributeUnassign?: Maybe<PageAttributeUnassign> /** Reorder the attributes of a page type. */ pageTypeReorderAttributes?: Maybe<PageTypeReorderAttributes> /** Reorder page attribute values. */ pageReorderAttributeValues?: Maybe<PageReorderAttributeValues> /** Completes creating an order. */ draftOrderComplete?: Maybe<DraftOrderComplete> /** Creates a new draft order. */ draftOrderCreate?: Maybe<DraftOrderCreate> /** Deletes a draft order. */ draftOrderDelete?: Maybe<DraftOrderDelete> /** Deletes draft orders. */ draftOrderBulkDelete?: Maybe<DraftOrderBulkDelete> /** Deletes order lines. */ draftOrderLinesBulkDelete?: Maybe<DraftOrderLinesBulkDelete> /** Updates a draft order. */ draftOrderUpdate?: Maybe<DraftOrderUpdate> /** Adds note to the order. */ orderAddNote?: Maybe<OrderAddNote> /** Cancel an order. */ orderCancel?: Maybe<OrderCancel> /** Capture an order. */ orderCapture?: Maybe<OrderCapture> /** Confirms an unconfirmed order by changing status to unfulfilled. */ orderConfirm?: Maybe<OrderConfirm> /** Creates new fulfillments for an order. */ orderFulfill?: Maybe<OrderFulfill> /** Cancels existing fulfillment and optionally restocks items. */ orderFulfillmentCancel?: Maybe<FulfillmentCancel> /** Updates a fulfillment for an order. */ orderFulfillmentUpdateTracking?: Maybe<FulfillmentUpdateTracking> /** Refund products. */ orderFulfillmentRefundProducts?: Maybe<FulfillmentRefundProducts> /** Return products. */ orderFulfillmentReturnProducts?: Maybe<FulfillmentReturnProducts> /** Create order lines for an order. */ orderLinesCreate?: Maybe<OrderLinesCreate> /** Deletes an order line from an order. */ orderLineDelete?: Maybe<OrderLineDelete> /** Updates an order line of an order. */ orderLineUpdate?: Maybe<OrderLineUpdate> /** Adds discount to the order. */ orderDiscountAdd?: Maybe<OrderDiscountAdd> /** Update discount for the order. */ orderDiscountUpdate?: Maybe<OrderDiscountUpdate> /** Remove discount from the order. */ orderDiscountDelete?: Maybe<OrderDiscountDelete> /** Update discount for the order line. */ orderLineDiscountUpdate?: Maybe<OrderLineDiscountUpdate> /** Remove discount applied to the order line. */ orderLineDiscountRemove?: Maybe<OrderLineDiscountRemove> /** Mark order as manually paid. */ orderMarkAsPaid?: Maybe<OrderMarkAsPaid> /** Refund an order. */ orderRefund?: Maybe<OrderRefund> /** Updates an order. */ orderUpdate?: Maybe<OrderUpdate> /** Updates a shipping method of the order. */ orderUpdateShipping?: Maybe<OrderUpdateShipping> /** Void an order. */ orderVoid?: Maybe<OrderVoid> /** Cancels orders. */ orderBulkCancel?: Maybe<OrderBulkCancel> /** Delete metadata of an object. */ deleteMetadata?: Maybe<DeleteMetadata> /** Delete object's private metadata. */ deletePrivateMetadata?: Maybe<DeletePrivateMetadata> /** Updates metadata of an object. */ updateMetadata?: Maybe<UpdateMetadata> /** Updates private metadata of an object. */ updatePrivateMetadata?: Maybe<UpdatePrivateMetadata> /** Assigns storefront's navigation menus. */ assignNavigation?: Maybe<AssignNavigation> /** Creates a new Menu. */ menuCreate?: Maybe<MenuCreate> /** Deletes a menu. */ menuDelete?: Maybe<MenuDelete> /** Deletes menus. */ menuBulkDelete?: Maybe<MenuBulkDelete> /** Updates a menu. */ menuUpdate?: Maybe<MenuUpdate> /** Creates a new menu item. */ menuItemCreate?: Maybe<MenuItemCreate> /** Deletes a menu item. */ menuItemDelete?: Maybe<MenuItemDelete> /** Deletes menu items. */ menuItemBulkDelete?: Maybe<MenuItemBulkDelete> /** Updates a menu item. */ menuItemUpdate?: Maybe<MenuItemUpdate> /** Creates/Updates translations for Menu Item. */ menuItemTranslate?: Maybe<MenuItemTranslate> /** Moves items of menus. */ menuItemMove?: Maybe<MenuItemMove> /** Request an invoice for the order using plugin. */ invoiceRequest?: Maybe<InvoiceRequest> /** Requests deletion of an invoice. */ invoiceRequestDelete?: Maybe<InvoiceRequestDelete> /** Creates a ready to send invoice. */ invoiceCreate?: Maybe<InvoiceCreate> /** Deletes an invoice. */ invoiceDelete?: Maybe<InvoiceDelete> /** Updates an invoice. */ invoiceUpdate?: Maybe<InvoiceUpdate> /** Send an invoice notification to the customer. */ invoiceSendNotification?: Maybe<InvoiceSendNotification> /** Activate a gift card. */ giftCardActivate?: Maybe<GiftCardActivate> /** Creates a new gift card. */ giftCardCreate?: Maybe<GiftCardCreate> /** Deactivate a gift card. */ giftCardDeactivate?: Maybe<GiftCardDeactivate> /** Update a gift card. */ giftCardUpdate?: Maybe<GiftCardUpdate> /** Update plugin configuration. */ pluginUpdate?: Maybe<PluginUpdate> /** Creates a new sale. */ saleCreate?: Maybe<SaleCreate> /** Deletes a sale. */ saleDelete?: Maybe<SaleDelete> /** Deletes sales. */ saleBulkDelete?: Maybe<SaleBulkDelete> /** Updates a sale. */ saleUpdate?: Maybe<SaleUpdate> /** Adds products, categories, collections to a voucher. */ saleCataloguesAdd?: Maybe<SaleAddCatalogues> /** Removes products, categories, collections from a sale. */ saleCataloguesRemove?: Maybe<SaleRemoveCatalogues> /** Creates/updates translations for a sale. */ saleTranslate?: Maybe<SaleTranslate> /** Manage sale's availability in channels. */ saleChannelListingUpdate?: Maybe<SaleChannelListingUpdate> /** Creates a new voucher. */ voucherCreate?: Maybe<VoucherCreate> /** Deletes a voucher. */ voucherDelete?: Maybe<VoucherDelete> /** Deletes vouchers. */ voucherBulkDelete?: Maybe<VoucherBulkDelete> /** Updates a voucher. */ voucherUpdate?: Maybe<VoucherUpdate> /** Adds products, categories, collections to a voucher. */ voucherCataloguesAdd?: Maybe<VoucherAddCatalogues> /** Removes products, categories, collections from a voucher. */ voucherCataloguesRemove?: Maybe<VoucherRemoveCatalogues> /** Creates/Updates translations for Voucher. */ voucherTranslate?: Maybe<VoucherTranslate> /** Manage voucher's availability in channels. */ voucherChannelListingUpdate?: Maybe<VoucherChannelListingUpdate> /** Export products to csv file. */ exportProducts?: Maybe<ExportProducts> /** Upload a file. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ fileUpload?: Maybe<FileUpload> /** Adds a gift card or a voucher to a checkout. */ checkoutAddPromoCode?: Maybe<CheckoutAddPromoCode> /** Update billing address in the existing checkout. */ checkoutBillingAddressUpdate?: Maybe<CheckoutBillingAddressUpdate> /** Completes the checkout. As a result a new order is created and a payment charge is made. This action requires a successful payment before it can be performed. In case additional confirmation step as 3D secure is required confirmationNeeded flag will be set to True and no order created until payment is confirmed with second call of this mutation. */ checkoutComplete?: Maybe<CheckoutComplete> /** Create a new checkout. */ checkoutCreate?: Maybe<CheckoutCreate> /** Sets the customer as the owner of the checkout. */ checkoutCustomerAttach?: Maybe<CheckoutCustomerAttach> /** Removes the user assigned as the owner of the checkout. */ checkoutCustomerDetach?: Maybe<CheckoutCustomerDetach> /** Updates email address in the existing checkout object. */ checkoutEmailUpdate?: Maybe<CheckoutEmailUpdate> /** Deletes a CheckoutLine. */ checkoutLineDelete?: Maybe<CheckoutLineDelete> /** Adds a checkout line to the existing checkout. */ checkoutLinesAdd?: Maybe<CheckoutLinesAdd> /** Updates checkout line in the existing checkout. */ checkoutLinesUpdate?: Maybe<CheckoutLinesUpdate> /** Remove a gift card or a voucher from a checkout. */ checkoutRemovePromoCode?: Maybe<CheckoutRemovePromoCode> /** Create a new payment for given checkout. */ checkoutPaymentCreate?: Maybe<CheckoutPaymentCreate> /** Update shipping address in the existing checkout. */ checkoutShippingAddressUpdate?: Maybe<CheckoutShippingAddressUpdate> /** Updates the shipping address of the checkout. */ checkoutShippingMethodUpdate?: Maybe<CheckoutShippingMethodUpdate> /** Update language code in the existing checkout. */ checkoutLanguageCodeUpdate?: Maybe<CheckoutLanguageCodeUpdate> /** Creates new channel. */ channelCreate?: Maybe<ChannelCreate> /** Update a channel. */ channelUpdate?: Maybe<ChannelUpdate> /** Delete a channel. Orders associated with the deleted channel will be moved to the target channel. Checkouts, product availability, and pricing will be removed. */ channelDelete?: Maybe<ChannelDelete> /** Activate a channel. */ channelActivate?: Maybe<ChannelActivate> /** Deactivate a channel. */ channelDeactivate?: Maybe<ChannelDeactivate> /** Creates an attribute. */ attributeCreate?: Maybe<AttributeCreate> /** Deletes an attribute. */ attributeDelete?: Maybe<AttributeDelete> /** Updates attribute. */ attributeUpdate?: Maybe<AttributeUpdate> /** Creates/Updates translations for attribute. */ attributeTranslate?: Maybe<AttributeTranslate> /** Deletes attributes. */ attributeBulkDelete?: Maybe<AttributeBulkDelete> /** Deletes values of attributes. */ attributeValueBulkDelete?: Maybe<AttributeValueBulkDelete> /** Creates a value for an attribute. */ attributeValueCreate?: Maybe<AttributeValueCreate> /** Deletes a value of an attribute. */ attributeValueDelete?: Maybe<AttributeValueDelete> /** Updates value of an attribute. */ attributeValueUpdate?: Maybe<AttributeValueUpdate> /** Creates/Updates translations for attribute value. */ attributeValueTranslate?: Maybe<AttributeValueTranslate> /** Reorder the values of an attribute. */ attributeReorderValues?: Maybe<AttributeReorderValues> /** Creates a new app. */ appCreate?: Maybe<AppCreate> /** Updates an existing app. */ appUpdate?: Maybe<AppUpdate> /** Deletes an app. */ appDelete?: Maybe<AppDelete> /** Creates a new token. */ appTokenCreate?: Maybe<AppTokenCreate> /** Deletes an authentication token assigned to app. */ appTokenDelete?: Maybe<AppTokenDelete> /** Verify provided app token. */ appTokenVerify?: Maybe<AppTokenVerify> /** Install new app by using app manifest. */ appInstall?: Maybe<AppInstall> /** Retry failed installation of new app. */ appRetryInstall?: Maybe<AppRetryInstall> /** Delete failed installation. */ appDeleteFailedInstallation?: Maybe<AppDeleteFailedInstallation> /** Fetch and validate manifest. */ appFetchManifest?: Maybe<AppFetchManifest> /** Activate the app. */ appActivate?: Maybe<AppActivate> /** Deactivate the app. */ appDeactivate?: Maybe<AppDeactivate> /** Create JWT token. */ tokenCreate?: Maybe<CreateToken> /** Refresh JWT token. Mutation tries to take refreshToken from the input.If it fails it will try to take refreshToken from the http-only cookie -refreshToken. csrfToken is required when refreshToken is provided as a cookie. */ tokenRefresh?: Maybe<RefreshToken> /** Verify JWT token. */ tokenVerify?: Maybe<VerifyToken> /** Deactivate all JWT tokens of the currently authenticated user. */ tokensDeactivateAll?: Maybe<DeactivateAllUserTokens> /** Prepare external authentication url for user by custom plugin. */ externalAuthenticationUrl?: Maybe<ExternalAuthenticationUrl> /** Obtain external access tokens for user by custom plugin. */ externalObtainAccessTokens?: Maybe<ExternalObtainAccessTokens> /** Refresh user's access by custom plugin. */ externalRefresh?: Maybe<ExternalRefresh> /** Logout user by custom plugin. */ externalLogout?: Maybe<ExternalLogout> /** Verify external authentication data by plugin. */ externalVerify?: Maybe<ExternalVerify> /** Sends an email with the account password modification link. */ requestPasswordReset?: Maybe<RequestPasswordReset> /** Confirm user account with token sent by email during registration. */ confirmAccount?: Maybe<ConfirmAccount> /** Sets the user's password from the token sent by email using the RequestPasswordReset mutation. */ setPassword?: Maybe<SetPassword> /** Change the password of the logged in user. */ passwordChange?: Maybe<PasswordChange> /** Request email change of the logged in user. */ requestEmailChange?: Maybe<RequestEmailChange> /** Confirm the email change of the logged-in user. */ confirmEmailChange?: Maybe<ConfirmEmailChange> /** Create a new address for the customer. */ accountAddressCreate?: Maybe<AccountAddressCreate> /** Updates an address of the logged-in user. */ accountAddressUpdate?: Maybe<AccountAddressUpdate> /** Delete an address of the logged-in user. */ accountAddressDelete?: Maybe<AccountAddressDelete> /** Sets a default address for the authenticated user. */ accountSetDefaultAddress?: Maybe<AccountSetDefaultAddress> /** Register a new user. */ accountRegister?: Maybe<AccountRegister> /** Updates the account of the logged-in user. */ accountUpdate?: Maybe<AccountUpdate> /** Sends an email with the account removal link for the logged-in user. */ accountRequestDeletion?: Maybe<AccountRequestDeletion> /** Remove user account. */ accountDelete?: Maybe<AccountDelete> /** Creates user address. */ addressCreate?: Maybe<AddressCreate> /** Updates an address. */ addressUpdate?: Maybe<AddressUpdate> /** Deletes an address. */ addressDelete?: Maybe<AddressDelete> /** Sets a default address for the given user. */ addressSetDefault?: Maybe<AddressSetDefault> /** Creates a new customer. */ customerCreate?: Maybe<CustomerCreate> /** Updates an existing customer. */ customerUpdate?: Maybe<CustomerUpdate> /** Deletes a customer. */ customerDelete?: Maybe<CustomerDelete> /** Deletes customers. */ customerBulkDelete?: Maybe<CustomerBulkDelete> /** Creates a new staff user. */ staffCreate?: Maybe<StaffCreate> /** Updates an existing staff user. */ staffUpdate?: Maybe<StaffUpdate> /** Deletes a staff user. */ staffDelete?: Maybe<StaffDelete> /** Deletes staff users. */ staffBulkDelete?: Maybe<StaffBulkDelete> /** Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ userAvatarUpdate?: Maybe<UserAvatarUpdate> /** Deletes a user avatar. Only for staff members. */ userAvatarDelete?: Maybe<UserAvatarDelete> /** Activate or deactivate users. */ userBulkSetActive?: Maybe<UserBulkSetActive> /** Create new permission group. */ permissionGroupCreate?: Maybe<PermissionGroupCreate> /** Update permission group. */ permissionGroupUpdate?: Maybe<PermissionGroupUpdate> /** Delete permission group. */ permissionGroupDelete?: Maybe<PermissionGroupDelete> } export type MutationWebhookCreateArgs = { input: WebhookCreateInput } export type MutationWebhookDeleteArgs = { id: Scalars['ID'] } export type MutationWebhookUpdateArgs = { id: Scalars['ID'] input: WebhookUpdateInput } export type MutationCreateWarehouseArgs = { input: WarehouseCreateInput } export type MutationUpdateWarehouseArgs = { id: Scalars['ID'] input: WarehouseUpdateInput } export type MutationDeleteWarehouseArgs = { id: Scalars['ID'] } export type MutationAssignWarehouseShippingZoneArgs = { id: Scalars['ID'] shippingZoneIds: Array<Scalars['ID']> } export type MutationUnassignWarehouseShippingZoneArgs = { id: Scalars['ID'] shippingZoneIds: Array<Scalars['ID']> } export type MutationStaffNotificationRecipientCreateArgs = { input: StaffNotificationRecipientInput } export type MutationStaffNotificationRecipientUpdateArgs = { id: Scalars['ID'] input: StaffNotificationRecipientInput } export type MutationStaffNotificationRecipientDeleteArgs = { id: Scalars['ID'] } export type MutationShopDomainUpdateArgs = { input?: Maybe<SiteDomainInput> } export type MutationShopSettingsUpdateArgs = { input: ShopSettingsInput } export type MutationShopSettingsTranslateArgs = { input: ShopSettingsTranslationInput languageCode: LanguageCodeEnum } export type MutationShopAddressUpdateArgs = { input?: Maybe<AddressInput> } export type MutationOrderSettingsUpdateArgs = { input: OrderSettingsUpdateInput } export type MutationShippingMethodChannelListingUpdateArgs = { id: Scalars['ID'] input: ShippingMethodChannelListingInput } export type MutationShippingPriceCreateArgs = { input: ShippingPriceInput } export type MutationShippingPriceDeleteArgs = { id: Scalars['ID'] } export type MutationShippingPriceBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationShippingPriceUpdateArgs = { id: Scalars['ID'] input: ShippingPriceInput } export type MutationShippingPriceTranslateArgs = { id: Scalars['ID'] input: ShippingPriceTranslationInput languageCode: LanguageCodeEnum } export type MutationShippingPriceExcludeProductsArgs = { id: Scalars['ID'] input: ShippingPriceExcludeProductsInput } export type MutationShippingPriceRemoveProductFromExcludeArgs = { id: Scalars['ID'] products: Array<Maybe<Scalars['ID']>> } export type MutationShippingZoneCreateArgs = { input: ShippingZoneCreateInput } export type MutationShippingZoneDeleteArgs = { id: Scalars['ID'] } export type MutationShippingZoneBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationShippingZoneUpdateArgs = { id: Scalars['ID'] input: ShippingZoneUpdateInput } export type MutationProductAttributeAssignArgs = { operations: Array<Maybe<ProductAttributeAssignInput>> productTypeId: Scalars['ID'] } export type MutationProductAttributeUnassignArgs = { attributeIds: Array<Maybe<Scalars['ID']>> productTypeId: Scalars['ID'] } export type MutationCategoryCreateArgs = { input: CategoryInput parent?: Maybe<Scalars['ID']> } export type MutationCategoryDeleteArgs = { id: Scalars['ID'] } export type MutationCategoryBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationCategoryUpdateArgs = { id: Scalars['ID'] input: CategoryInput } export type MutationCategoryTranslateArgs = { id: Scalars['ID'] input: TranslationInput languageCode: LanguageCodeEnum } export type MutationCollectionAddProductsArgs = { collectionId: Scalars['ID'] products: Array<Maybe<Scalars['ID']>> } export type MutationCollectionCreateArgs = { input: CollectionCreateInput } export type MutationCollectionDeleteArgs = { id: Scalars['ID'] } export type MutationCollectionReorderProductsArgs = { collectionId: Scalars['ID'] moves: Array<Maybe<MoveProductInput>> } export type MutationCollectionBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationCollectionRemoveProductsArgs = { collectionId: Scalars['ID'] products: Array<Maybe<Scalars['ID']>> } export type MutationCollectionUpdateArgs = { id: Scalars['ID'] input: CollectionInput } export type MutationCollectionTranslateArgs = { id: Scalars['ID'] input: TranslationInput languageCode: LanguageCodeEnum } export type MutationCollectionChannelListingUpdateArgs = { id: Scalars['ID'] input: CollectionChannelListingUpdateInput } export type MutationProductCreateArgs = { input: ProductCreateInput } export type MutationProductDeleteArgs = { id: Scalars['ID'] } export type MutationProductBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationProductUpdateArgs = { id: Scalars['ID'] input: ProductInput } export type MutationProductTranslateArgs = { id: Scalars['ID'] input: TranslationInput languageCode: LanguageCodeEnum } export type MutationProductChannelListingUpdateArgs = { id: Scalars['ID'] input: ProductChannelListingUpdateInput } export type MutationProductMediaCreateArgs = { input: ProductMediaCreateInput } export type MutationProductVariantReorderArgs = { moves: Array<Maybe<ReorderInput>> productId: Scalars['ID'] } export type MutationProductMediaDeleteArgs = { id: Scalars['ID'] } export type MutationProductMediaBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationProductMediaReorderArgs = { mediaIds: Array<Maybe<Scalars['ID']>> productId: Scalars['ID'] } export type MutationProductMediaUpdateArgs = { id: Scalars['ID'] input: ProductMediaUpdateInput } export type MutationProductTypeCreateArgs = { input: ProductTypeInput } export type MutationProductTypeDeleteArgs = { id: Scalars['ID'] } export type MutationProductTypeBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationProductTypeUpdateArgs = { id: Scalars['ID'] input: ProductTypeInput } export type MutationProductTypeReorderAttributesArgs = { moves: Array<Maybe<ReorderInput>> productTypeId: Scalars['ID'] type: ProductAttributeType } export type MutationProductReorderAttributeValuesArgs = { attributeId: Scalars['ID'] moves: Array<Maybe<ReorderInput>> productId: Scalars['ID'] } export type MutationDigitalContentCreateArgs = { input: DigitalContentUploadInput variantId: Scalars['ID'] } export type MutationDigitalContentDeleteArgs = { variantId: Scalars['ID'] } export type MutationDigitalContentUpdateArgs = { input: DigitalContentInput variantId: Scalars['ID'] } export type MutationDigitalContentUrlCreateArgs = { input: DigitalContentUrlCreateInput } export type MutationProductVariantCreateArgs = { input: ProductVariantCreateInput } export type MutationProductVariantDeleteArgs = { id: Scalars['ID'] } export type MutationProductVariantBulkCreateArgs = { product: Scalars['ID'] variants: Array<Maybe<ProductVariantBulkCreateInput>> } export type MutationProductVariantBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationProductVariantStocksCreateArgs = { stocks: Array<StockInput> variantId: Scalars['ID'] } export type MutationProductVariantStocksDeleteArgs = { variantId: Scalars['ID'] warehouseIds?: Maybe<Array<Scalars['ID']>> } export type MutationProductVariantStocksUpdateArgs = { stocks: Array<StockInput> variantId: Scalars['ID'] } export type MutationProductVariantUpdateArgs = { id: Scalars['ID'] input: ProductVariantInput } export type MutationProductVariantSetDefaultArgs = { productId: Scalars['ID'] variantId: Scalars['ID'] } export type MutationProductVariantTranslateArgs = { id: Scalars['ID'] input: NameTranslationInput languageCode: LanguageCodeEnum } export type MutationProductVariantChannelListingUpdateArgs = { id: Scalars['ID'] input: Array<ProductVariantChannelListingAddInput> } export type MutationProductVariantReorderAttributeValuesArgs = { attributeId: Scalars['ID'] moves: Array<Maybe<ReorderInput>> variantId: Scalars['ID'] } export type MutationVariantMediaAssignArgs = { mediaId: Scalars['ID'] variantId: Scalars['ID'] } export type MutationVariantMediaUnassignArgs = { mediaId: Scalars['ID'] variantId: Scalars['ID'] } export type MutationPaymentCaptureArgs = { amount?: Maybe<Scalars['PositiveDecimal']> paymentId: Scalars['ID'] } export type MutationPaymentRefundArgs = { amount?: Maybe<Scalars['PositiveDecimal']> paymentId: Scalars['ID'] } export type MutationPaymentVoidArgs = { paymentId: Scalars['ID'] } export type MutationPaymentInitializeArgs = { channel?: Maybe<Scalars['String']> gateway: Scalars['String'] paymentData?: Maybe<Scalars['JSONString']> } export type MutationPageCreateArgs = { input: PageCreateInput } export type MutationPageDeleteArgs = { id: Scalars['ID'] } export type MutationPageBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationPageBulkPublishArgs = { ids: Array<Maybe<Scalars['ID']>> isPublished: Scalars['Boolean'] } export type MutationPageUpdateArgs = { id: Scalars['ID'] input: PageInput } export type MutationPageTranslateArgs = { id: Scalars['ID'] input: PageTranslationInput languageCode: LanguageCodeEnum } export type MutationPageTypeCreateArgs = { input: PageTypeCreateInput } export type MutationPageTypeUpdateArgs = { id?: Maybe<Scalars['ID']> input: PageTypeUpdateInput } export type MutationPageTypeDeleteArgs = { id: Scalars['ID'] } export type MutationPageTypeBulkDeleteArgs = { ids: Array<Scalars['ID']> } export type MutationPageAttributeAssignArgs = { attributeIds: Array<Scalars['ID']> pageTypeId: Scalars['ID'] } export type MutationPageAttributeUnassignArgs = { attributeIds: Array<Scalars['ID']> pageTypeId: Scalars['ID'] } export type MutationPageTypeReorderAttributesArgs = { moves: Array<ReorderInput> pageTypeId: Scalars['ID'] } export type MutationPageReorderAttributeValuesArgs = { attributeId: Scalars['ID'] moves: Array<Maybe<ReorderInput>> pageId: Scalars['ID'] } export type MutationDraftOrderCompleteArgs = { id: Scalars['ID'] } export type MutationDraftOrderCreateArgs = { input: DraftOrderCreateInput } export type MutationDraftOrderDeleteArgs = { id: Scalars['ID'] } export type MutationDraftOrderBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationDraftOrderLinesBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationDraftOrderUpdateArgs = { id: Scalars['ID'] input: DraftOrderInput } export type MutationOrderAddNoteArgs = { order: Scalars['ID'] input: OrderAddNoteInput } export type MutationOrderCancelArgs = { id: Scalars['ID'] } export type MutationOrderCaptureArgs = { amount: Scalars['PositiveDecimal'] id: Scalars['ID'] } export type MutationOrderConfirmArgs = { id: Scalars['ID'] } export type MutationOrderFulfillArgs = { input: OrderFulfillInput order?: Maybe<Scalars['ID']> } export type MutationOrderFulfillmentCancelArgs = { id: Scalars['ID'] input: FulfillmentCancelInput } export type MutationOrderFulfillmentUpdateTrackingArgs = { id: Scalars['ID'] input: FulfillmentUpdateTrackingInput } export type MutationOrderFulfillmentRefundProductsArgs = { input: OrderRefundProductsInput order: Scalars['ID'] } export type MutationOrderFulfillmentReturnProductsArgs = { input: OrderReturnProductsInput order: Scalars['ID'] } export type MutationOrderLinesCreateArgs = { id: Scalars['ID'] input: Array<Maybe<OrderLineCreateInput>> } export type MutationOrderLineDeleteArgs = { id: Scalars['ID'] } export type MutationOrderLineUpdateArgs = { id: Scalars['ID'] input: OrderLineInput } export type MutationOrderDiscountAddArgs = { input: OrderDiscountCommonInput orderId: Scalars['ID'] } export type MutationOrderDiscountUpdateArgs = { discountId: Scalars['ID'] input: OrderDiscountCommonInput } export type MutationOrderDiscountDeleteArgs = { discountId: Scalars['ID'] } export type MutationOrderLineDiscountUpdateArgs = { input: OrderDiscountCommonInput orderLineId: Scalars['ID'] } export type MutationOrderLineDiscountRemoveArgs = { orderLineId: Scalars['ID'] } export type MutationOrderMarkAsPaidArgs = { id: Scalars['ID'] transactionReference?: Maybe<Scalars['String']> } export type MutationOrderRefundArgs = { amount: Scalars['PositiveDecimal'] id: Scalars['ID'] } export type MutationOrderUpdateArgs = { id: Scalars['ID'] input: OrderUpdateInput } export type MutationOrderUpdateShippingArgs = { order: Scalars['ID'] input?: Maybe<OrderUpdateShippingInput> } export type MutationOrderVoidArgs = { id: Scalars['ID'] } export type MutationOrderBulkCancelArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationDeleteMetadataArgs = { id: Scalars['ID'] keys: Array<Scalars['String']> } export type MutationDeletePrivateMetadataArgs = { id: Scalars['ID'] keys: Array<Scalars['String']> } export type MutationUpdateMetadataArgs = { id: Scalars['ID'] input: Array<MetadataInput> } export type MutationUpdatePrivateMetadataArgs = { id: Scalars['ID'] input: Array<MetadataInput> } export type MutationAssignNavigationArgs = { menu?: Maybe<Scalars['ID']> navigationType: NavigationType } export type MutationMenuCreateArgs = { input: MenuCreateInput } export type MutationMenuDeleteArgs = { id: Scalars['ID'] } export type MutationMenuBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationMenuUpdateArgs = { id: Scalars['ID'] input: MenuInput } export type MutationMenuItemCreateArgs = { input: MenuItemCreateInput } export type MutationMenuItemDeleteArgs = { id: Scalars['ID'] } export type MutationMenuItemBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationMenuItemUpdateArgs = { id: Scalars['ID'] input: MenuItemInput } export type MutationMenuItemTranslateArgs = { id: Scalars['ID'] input: NameTranslationInput languageCode: LanguageCodeEnum } export type MutationMenuItemMoveArgs = { menu: Scalars['ID'] moves: Array<Maybe<MenuItemMoveInput>> } export type MutationInvoiceRequestArgs = { number?: Maybe<Scalars['String']> orderId: Scalars['ID'] } export type MutationInvoiceRequestDeleteArgs = { id: Scalars['ID'] } export type MutationInvoiceCreateArgs = { input: InvoiceCreateInput orderId: Scalars['ID'] } export type MutationInvoiceDeleteArgs = { id: Scalars['ID'] } export type MutationInvoiceUpdateArgs = { id: Scalars['ID'] input: UpdateInvoiceInput } export type MutationInvoiceSendNotificationArgs = { id: Scalars['ID'] } export type MutationGiftCardActivateArgs = { id: Scalars['ID'] } export type MutationGiftCardCreateArgs = { input: GiftCardCreateInput } export type MutationGiftCardDeactivateArgs = { id: Scalars['ID'] } export type MutationGiftCardUpdateArgs = { id: Scalars['ID'] input: GiftCardUpdateInput } export type MutationPluginUpdateArgs = { channel?: Maybe<Scalars['ID']> id: Scalars['ID'] input: PluginUpdateInput } export type MutationSaleCreateArgs = { input: SaleInput } export type MutationSaleDeleteArgs = { id: Scalars['ID'] } export type MutationSaleBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationSaleUpdateArgs = { id: Scalars['ID'] input: SaleInput } export type MutationSaleCataloguesAddArgs = { id: Scalars['ID'] input: CatalogueInput } export type MutationSaleCataloguesRemoveArgs = { id: Scalars['ID'] input: CatalogueInput } export type MutationSaleTranslateArgs = { id: Scalars['ID'] input: NameTranslationInput languageCode: LanguageCodeEnum } export type MutationSaleChannelListingUpdateArgs = { id: Scalars['ID'] input: SaleChannelListingInput } export type MutationVoucherCreateArgs = { input: VoucherInput } export type MutationVoucherDeleteArgs = { id: Scalars['ID'] } export type MutationVoucherBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationVoucherUpdateArgs = { id: Scalars['ID'] input: VoucherInput } export type MutationVoucherCataloguesAddArgs = { id: Scalars['ID'] input: CatalogueInput } export type MutationVoucherCataloguesRemoveArgs = { id: Scalars['ID'] input: CatalogueInput } export type MutationVoucherTranslateArgs = { id: Scalars['ID'] input: NameTranslationInput languageCode: LanguageCodeEnum } export type MutationVoucherChannelListingUpdateArgs = { id: Scalars['ID'] input: VoucherChannelListingInput } export type MutationExportProductsArgs = { input: ExportProductsInput } export type MutationFileUploadArgs = { file: Scalars['Upload'] } export type MutationCheckoutAddPromoCodeArgs = { checkoutId: Scalars['ID'] promoCode: Scalars['String'] } export type MutationCheckoutBillingAddressUpdateArgs = { billingAddress: AddressInput checkoutId: Scalars['ID'] } export type MutationCheckoutCompleteArgs = { checkoutId: Scalars['ID'] paymentData?: Maybe<Scalars['JSONString']> redirectUrl?: Maybe<Scalars['String']> storeSource?: Maybe<Scalars['Boolean']> } export type MutationCheckoutCreateArgs = { input: CheckoutCreateInput } export type MutationCheckoutCustomerAttachArgs = { checkoutId: Scalars['ID'] } export type MutationCheckoutCustomerDetachArgs = { checkoutId: Scalars['ID'] } export type MutationCheckoutEmailUpdateArgs = { checkoutId?: Maybe<Scalars['ID']> email: Scalars['String'] } export type MutationCheckoutLineDeleteArgs = { checkoutId: Scalars['ID'] lineId?: Maybe<Scalars['ID']> } export type MutationCheckoutLinesAddArgs = { checkoutId: Scalars['ID'] lines: Array<Maybe<CheckoutLineInput>> } export type MutationCheckoutLinesUpdateArgs = { checkoutId: Scalars['ID'] lines: Array<Maybe<CheckoutLineInput>> } export type MutationCheckoutRemovePromoCodeArgs = { checkoutId: Scalars['ID'] promoCode: Scalars['String'] } export type MutationCheckoutPaymentCreateArgs = { checkoutId: Scalars['ID'] input: PaymentInput } export type MutationCheckoutShippingAddressUpdateArgs = { checkoutId: Scalars['ID'] shippingAddress: AddressInput } export type MutationCheckoutShippingMethodUpdateArgs = { checkoutId?: Maybe<Scalars['ID']> shippingMethodId: Scalars['ID'] } export type MutationCheckoutLanguageCodeUpdateArgs = { checkoutId: Scalars['ID'] languageCode: LanguageCodeEnum } export type MutationChannelCreateArgs = { input: ChannelCreateInput } export type MutationChannelUpdateArgs = { id: Scalars['ID'] input: ChannelUpdateInput } export type MutationChannelDeleteArgs = { id: Scalars['ID'] input?: Maybe<ChannelDeleteInput> } export type MutationChannelActivateArgs = { id: Scalars['ID'] } export type MutationChannelDeactivateArgs = { id: Scalars['ID'] } export type MutationAttributeCreateArgs = { input: AttributeCreateInput } export type MutationAttributeDeleteArgs = { id: Scalars['ID'] } export type MutationAttributeUpdateArgs = { id: Scalars['ID'] input: AttributeUpdateInput } export type MutationAttributeTranslateArgs = { id: Scalars['ID'] input: NameTranslationInput languageCode: LanguageCodeEnum } export type MutationAttributeBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationAttributeValueBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationAttributeValueCreateArgs = { attribute: Scalars['ID'] input: AttributeValueCreateInput } export type MutationAttributeValueDeleteArgs = { id: Scalars['ID'] } export type MutationAttributeValueUpdateArgs = { id: Scalars['ID'] input: AttributeValueCreateInput } export type MutationAttributeValueTranslateArgs = { id: Scalars['ID'] input: AttributeValueTranslationInput languageCode: LanguageCodeEnum } export type MutationAttributeReorderValuesArgs = { attributeId: Scalars['ID'] moves: Array<Maybe<ReorderInput>> } export type MutationAppCreateArgs = { input: AppInput } export type MutationAppUpdateArgs = { id: Scalars['ID'] input: AppInput } export type MutationAppDeleteArgs = { id: Scalars['ID'] } export type MutationAppTokenCreateArgs = { input: AppTokenInput } export type MutationAppTokenDeleteArgs = { id: Scalars['ID'] } export type MutationAppTokenVerifyArgs = { token: Scalars['String'] } export type MutationAppInstallArgs = { input: AppInstallInput } export type MutationAppRetryInstallArgs = { activateAfterInstallation?: Maybe<Scalars['Boolean']> id: Scalars['ID'] } export type MutationAppDeleteFailedInstallationArgs = { id: Scalars['ID'] } export type MutationAppFetchManifestArgs = { manifestUrl: Scalars['String'] } export type MutationAppActivateArgs = { id: Scalars['ID'] } export type MutationAppDeactivateArgs = { id: Scalars['ID'] } export type MutationTokenCreateArgs = { email: Scalars['String'] password: Scalars['String'] } export type MutationTokenRefreshArgs = { csrfToken?: Maybe<Scalars['String']> refreshToken?: Maybe<Scalars['String']> } export type MutationTokenVerifyArgs = { token: Scalars['String'] } export type MutationExternalAuthenticationUrlArgs = { input: Scalars['JSONString'] pluginId: Scalars['String'] } export type MutationExternalObtainAccessTokensArgs = { input: Scalars['JSONString'] pluginId: Scalars['String'] } export type MutationExternalRefreshArgs = { input: Scalars['JSONString'] pluginId: Scalars['String'] } export type MutationExternalLogoutArgs = { input: Scalars['JSONString'] pluginId: Scalars['String'] } export type MutationExternalVerifyArgs = { input: Scalars['JSONString'] pluginId: Scalars['String'] } export type MutationRequestPasswordResetArgs = { channel?: Maybe<Scalars['String']> email: Scalars['String'] redirectUrl: Scalars['String'] } export type MutationConfirmAccountArgs = { email: Scalars['String'] token: Scalars['String'] } export type MutationSetPasswordArgs = { email: Scalars['String'] password: Scalars['String'] token: Scalars['String'] } export type MutationPasswordChangeArgs = { newPassword: Scalars['String'] oldPassword: Scalars['String'] } export type MutationRequestEmailChangeArgs = { channel?: Maybe<Scalars['String']> newEmail: Scalars['String'] password: Scalars['String'] redirectUrl: Scalars['String'] } export type MutationConfirmEmailChangeArgs = { channel?: Maybe<Scalars['String']> token: Scalars['String'] } export type MutationAccountAddressCreateArgs = { input: AddressInput type?: Maybe<AddressTypeEnum> } export type MutationAccountAddressUpdateArgs = { id: Scalars['ID'] input: AddressInput } export type MutationAccountAddressDeleteArgs = { id: Scalars['ID'] } export type MutationAccountSetDefaultAddressArgs = { id: Scalars['ID'] type: AddressTypeEnum } export type MutationAccountRegisterArgs = { input: AccountRegisterInput } export type MutationAccountUpdateArgs = { input: AccountInput } export type MutationAccountRequestDeletionArgs = { channel?: Maybe<Scalars['String']> redirectUrl: Scalars['String'] } export type MutationAccountDeleteArgs = { token: Scalars['String'] } export type MutationAddressCreateArgs = { input: AddressInput userId: Scalars['ID'] } export type MutationAddressUpdateArgs = { id: Scalars['ID'] input: AddressInput } export type MutationAddressDeleteArgs = { id: Scalars['ID'] } export type MutationAddressSetDefaultArgs = { addressId: Scalars['ID'] type: AddressTypeEnum userId: Scalars['ID'] } export type MutationCustomerCreateArgs = { input: UserCreateInput } export type MutationCustomerUpdateArgs = { id: Scalars['ID'] input: CustomerInput } export type MutationCustomerDeleteArgs = { id: Scalars['ID'] } export type MutationCustomerBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationStaffCreateArgs = { input: StaffCreateInput } export type MutationStaffUpdateArgs = { id: Scalars['ID'] input: StaffUpdateInput } export type MutationStaffDeleteArgs = { id: Scalars['ID'] } export type MutationStaffBulkDeleteArgs = { ids: Array<Maybe<Scalars['ID']>> } export type MutationUserAvatarUpdateArgs = { image: Scalars['Upload'] } export type MutationUserBulkSetActiveArgs = { ids: Array<Maybe<Scalars['ID']>> isActive: Scalars['Boolean'] } export type MutationPermissionGroupCreateArgs = { input: PermissionGroupCreateInput } export type MutationPermissionGroupUpdateArgs = { id: Scalars['ID'] input: PermissionGroupUpdateInput } export type MutationPermissionGroupDeleteArgs = { id: Scalars['ID'] } export type NameTranslationInput = { name?: Maybe<Scalars['String']> } export enum NavigationType { /** Main storefront navigation. */ Main = 'MAIN', /** Secondary storefront navigation. */ Secondary = 'SECONDARY', } /** An object with an ID */ export type Node = { /** The ID of the object. */ id: Scalars['ID'] } export type ObjectWithMetadata = { /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> } /** Represents an order in the shop. */ export type Order = Node & ObjectWithMetadata & { __typename?: 'Order' /** The ID of the object. */ id: Scalars['ID'] created: Scalars['DateTime'] status: OrderStatus user?: Maybe<User> trackingClientId: Scalars['String'] billingAddress?: Maybe<Address> shippingAddress?: Maybe<Address> shippingMethod?: Maybe<ShippingMethod> shippingMethodName?: Maybe<Scalars['String']> channel: Channel /** Total price of shipping. */ shippingPrice: TaxedMoney shippingTaxRate: Scalars['Float'] token: Scalars['String'] voucher?: Maybe<Voucher> /** List of user gift cards. */ giftCards?: Maybe<Array<Maybe<GiftCard>>> displayGrossPrices: Scalars['Boolean'] customerNote: Scalars['String'] weight?: Maybe<Weight> redirectUrl?: Maybe<Scalars['String']> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** List of shipments for the order. */ fulfillments: Array<Maybe<Fulfillment>> /** List of order lines. */ lines: Array<Maybe<OrderLine>> /** List of actions that can be performed in the current state of an order. */ actions: Array<Maybe<OrderAction>> /** Shipping methods that can be used with this order. */ availableShippingMethods?: Maybe<Array<Maybe<ShippingMethod>>> /** List of order invoices. */ invoices?: Maybe<Array<Maybe<Invoice>>> /** User-friendly number of an order. */ number?: Maybe<Scalars['String']> /** The ID of the order that was the base for this order. */ original?: Maybe<Scalars['ID']> /** The order origin. */ origin: OrderOriginEnum /** Informs if an order is fully paid. */ isPaid: Scalars['Boolean'] /** Internal payment status. */ paymentStatus: PaymentChargeStatusEnum /** User-friendly payment status. */ paymentStatusDisplay: Scalars['String'] /** List of payments for the order. */ payments?: Maybe<Array<Maybe<Payment>>> /** Total amount of the order. */ total: TaxedMoney /** Undiscounted total amount of the order. */ undiscountedTotal: TaxedMoney /** The sum of line prices not including shipping. */ subtotal: TaxedMoney /** User-friendly order status. */ statusDisplay?: Maybe<Scalars['String']> /** Informs whether a draft order can be finalized(turned into a regular order). */ canFinalize: Scalars['Boolean'] /** Amount authorized for the order. */ totalAuthorized: Money /** Amount captured by payment. */ totalCaptured: Money /** List of events associated with the order. */ events?: Maybe<Array<Maybe<OrderEvent>>> /** The difference between the paid and the order total amount. */ totalBalance: Money /** Email address of the customer. */ userEmail?: Maybe<Scalars['String']> /** Returns True, if order requires shipping. */ isShippingRequired: Scalars['Boolean'] /** @deprecated Use the `languageCodeEnum` field to fetch the language code. This field will be removed in Saleor 4.0. */ languageCode: Scalars['String'] /** Order language code. */ languageCodeEnum: LanguageCodeEnum /** * Returns applied discount. * @deprecated Use discounts field. This field will be removed in Saleor 4.0. */ discount?: Maybe<Money> /** * Discount name. * @deprecated Use discounts field. This field will be removed in Saleor 4.0. */ discountName?: Maybe<Scalars['String']> /** * Translated discount name. * @deprecated Use discounts field. This field will be removed in Saleor 4.0. */ translatedDiscountName?: Maybe<Scalars['String']> /** List of all discounts assigned to the order. */ discounts?: Maybe<Array<OrderDiscount>> } export enum OrderAction { /** Represents the capture action. */ Capture = 'CAPTURE', /** Represents a mark-as-paid action. */ MarkAsPaid = 'MARK_AS_PAID', /** Represents a refund action. */ Refund = 'REFUND', /** Represents a void action. */ Void = 'VOID', } /** Adds note to the order. */ export type OrderAddNote = { __typename?: 'OrderAddNote' /** Order with the note added. */ order?: Maybe<Order> /** Order note created. */ event?: Maybe<OrderEvent> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderAddNoteInput = { /** Note message. */ message: Scalars['String'] } /** Cancels orders. */ export type OrderBulkCancel = { __typename?: 'OrderBulkCancel' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Cancel an order. */ export type OrderCancel = { __typename?: 'OrderCancel' /** Canceled order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Capture an order. */ export type OrderCapture = { __typename?: 'OrderCapture' /** Captured order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Confirms an unconfirmed order by changing status to unfulfilled. */ export type OrderConfirm = { __typename?: 'OrderConfirm' order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderCountableConnection = { __typename?: 'OrderCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<OrderCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type OrderCountableEdge = { __typename?: 'OrderCountableEdge' /** The item at the end of the edge. */ node: Order /** A cursor for use in pagination. */ cursor: Scalars['String'] } export enum OrderDirection { /** Specifies an ascending sort order. */ Asc = 'ASC', /** Specifies a descending sort order. */ Desc = 'DESC', } /** Contains all details related to the applied discount to the order. */ export type OrderDiscount = Node & { __typename?: 'OrderDiscount' /** The ID of the object. */ id: Scalars['ID'] type: OrderDiscountType /** Type of the discount: fixed or percent */ valueType: DiscountValueTypeEnum /** Value of the discount. Can store fixed value or percent value */ value: Scalars['PositiveDecimal'] name?: Maybe<Scalars['String']> translatedName?: Maybe<Scalars['String']> /** Explanation for the applied discount. */ reason?: Maybe<Scalars['String']> /** Returns amount of discount. */ amount: Money } /** Adds discount to the order. */ export type OrderDiscountAdd = { __typename?: 'OrderDiscountAdd' /** Order which has been discounted. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderDiscountCommonInput = { /** Type of the discount: fixed or percent */ valueType: DiscountValueTypeEnum /** Value of the discount. Can store fixed value or percent value */ value: Scalars['PositiveDecimal'] /** Explanation for the applied discount. */ reason?: Maybe<Scalars['String']> } /** Remove discount from the order. */ export type OrderDiscountDelete = { __typename?: 'OrderDiscountDelete' /** Order which has removed discount. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** An enumeration. */ export enum OrderDiscountType { /** Voucher */ Voucher = 'VOUCHER', /** Manual */ Manual = 'MANUAL', } /** Update discount for the order. */ export type OrderDiscountUpdate = { __typename?: 'OrderDiscountUpdate' /** Order which has been discounted. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderDraftFilterInput = { customer?: Maybe<Scalars['String']> created?: Maybe<DateRangeInput> search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> channels?: Maybe<Array<Maybe<Scalars['ID']>>> } export type OrderError = { __typename?: 'OrderError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: OrderErrorCode /** Warehouse ID which causes the error. */ warehouse?: Maybe<Scalars['ID']> /** Order line ID which causes the error. */ orderLine?: Maybe<Scalars['ID']> /** List of product variants that are associated with the error */ variants?: Maybe<Array<Scalars['ID']>> /** A type of address that causes the error. */ addressType?: Maybe<AddressTypeEnum> } /** An enumeration. */ export enum OrderErrorCode { BillingAddressNotSet = 'BILLING_ADDRESS_NOT_SET', CannotCancelFulfillment = 'CANNOT_CANCEL_FULFILLMENT', CannotCancelOrder = 'CANNOT_CANCEL_ORDER', CannotDelete = 'CANNOT_DELETE', CannotDiscount = 'CANNOT_DISCOUNT', CannotRefund = 'CANNOT_REFUND', CaptureInactivePayment = 'CAPTURE_INACTIVE_PAYMENT', NotEditable = 'NOT_EDITABLE', FulfillOrderLine = 'FULFILL_ORDER_LINE', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', ProductNotPublished = 'PRODUCT_NOT_PUBLISHED', ProductUnavailableForPurchase = 'PRODUCT_UNAVAILABLE_FOR_PURCHASE', NotFound = 'NOT_FOUND', OrderNoShippingAddress = 'ORDER_NO_SHIPPING_ADDRESS', PaymentError = 'PAYMENT_ERROR', PaymentMissing = 'PAYMENT_MISSING', Required = 'REQUIRED', ShippingMethodNotApplicable = 'SHIPPING_METHOD_NOT_APPLICABLE', ShippingMethodRequired = 'SHIPPING_METHOD_REQUIRED', TaxError = 'TAX_ERROR', Unique = 'UNIQUE', VoidInactivePayment = 'VOID_INACTIVE_PAYMENT', ZeroQuantity = 'ZERO_QUANTITY', InvalidQuantity = 'INVALID_QUANTITY', InsufficientStock = 'INSUFFICIENT_STOCK', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', NotAvailableInChannel = 'NOT_AVAILABLE_IN_CHANNEL', ChannelInactive = 'CHANNEL_INACTIVE', } /** History log of the order. */ export type OrderEvent = Node & { __typename?: 'OrderEvent' /** The ID of the object. */ id: Scalars['ID'] /** Date when event happened at in ISO 8601 format. */ date?: Maybe<Scalars['DateTime']> /** Order event type. */ type?: Maybe<OrderEventsEnum> /** User who performed the action. */ user?: Maybe<User> /** Content of the event. */ message?: Maybe<Scalars['String']> /** Email of the customer. */ email?: Maybe<Scalars['String']> /** Type of an email sent to the customer. */ emailType?: Maybe<OrderEventsEmailsEnum> /** Amount of money. */ amount?: Maybe<Scalars['Float']> /** The payment ID from the payment gateway. */ paymentId?: Maybe<Scalars['String']> /** The payment gateway of the payment. */ paymentGateway?: Maybe<Scalars['String']> /** Number of items. */ quantity?: Maybe<Scalars['Int']> /** Composed ID of the Fulfillment. */ composedId?: Maybe<Scalars['String']> /** User-friendly number of an order. */ orderNumber?: Maybe<Scalars['String']> /** Number of an invoice related to the order. */ invoiceNumber?: Maybe<Scalars['String']> /** List of oversold lines names. */ oversoldItems?: Maybe<Array<Maybe<Scalars['String']>>> /** The concerned lines. */ lines?: Maybe<Array<Maybe<OrderEventOrderLineObject>>> /** The lines fulfilled. */ fulfilledItems?: Maybe<Array<Maybe<FulfillmentLine>>> /** The warehouse were items were restocked. */ warehouse?: Maybe<Warehouse> /** The transaction reference of captured payment. */ transactionReference?: Maybe<Scalars['String']> /** Define if shipping costs were included to the refund. */ shippingCostsIncluded?: Maybe<Scalars['Boolean']> /** The order which is related to this order. */ relatedOrder?: Maybe<Order> /** The discount applied to the order. */ discount?: Maybe<OrderEventDiscountObject> } export type OrderEventCountableConnection = { __typename?: 'OrderEventCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<OrderEventCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type OrderEventCountableEdge = { __typename?: 'OrderEventCountableEdge' /** The item at the end of the edge. */ node: OrderEvent /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type OrderEventDiscountObject = { __typename?: 'OrderEventDiscountObject' /** Type of the discount: fixed or percent. */ valueType: DiscountValueTypeEnum /** Value of the discount. Can store fixed value or percent value. */ value: Scalars['PositiveDecimal'] /** Explanation for the applied discount. */ reason?: Maybe<Scalars['String']> /** Returns amount of discount. */ amount?: Maybe<Money> /** Type of the discount: fixed or percent. */ oldValueType?: Maybe<DiscountValueTypeEnum> /** Value of the discount. Can store fixed value or percent value. */ oldValue?: Maybe<Scalars['PositiveDecimal']> /** Returns amount of discount. */ oldAmount?: Maybe<Money> } export type OrderEventOrderLineObject = { __typename?: 'OrderEventOrderLineObject' /** The variant quantity. */ quantity?: Maybe<Scalars['Int']> /** The order line. */ orderLine?: Maybe<OrderLine> /** The variant name. */ itemName?: Maybe<Scalars['String']> /** The discount applied to the order line. */ discount?: Maybe<OrderEventDiscountObject> } /** An enumeration. */ export enum OrderEventsEmailsEnum { PaymentConfirmation = 'PAYMENT_CONFIRMATION', Confirmed = 'CONFIRMED', ShippingConfirmation = 'SHIPPING_CONFIRMATION', TrackingUpdated = 'TRACKING_UPDATED', OrderConfirmation = 'ORDER_CONFIRMATION', OrderCancel = 'ORDER_CANCEL', OrderRefund = 'ORDER_REFUND', FulfillmentConfirmation = 'FULFILLMENT_CONFIRMATION', DigitalLinks = 'DIGITAL_LINKS', } /** An enumeration. */ export enum OrderEventsEnum { DraftCreated = 'DRAFT_CREATED', DraftCreatedFromReplace = 'DRAFT_CREATED_FROM_REPLACE', AddedProducts = 'ADDED_PRODUCTS', RemovedProducts = 'REMOVED_PRODUCTS', Placed = 'PLACED', PlacedFromDraft = 'PLACED_FROM_DRAFT', OversoldItems = 'OVERSOLD_ITEMS', Canceled = 'CANCELED', OrderMarkedAsPaid = 'ORDER_MARKED_AS_PAID', OrderFullyPaid = 'ORDER_FULLY_PAID', OrderReplacementCreated = 'ORDER_REPLACEMENT_CREATED', OrderDiscountAdded = 'ORDER_DISCOUNT_ADDED', OrderDiscountAutomaticallyUpdated = 'ORDER_DISCOUNT_AUTOMATICALLY_UPDATED', OrderDiscountUpdated = 'ORDER_DISCOUNT_UPDATED', OrderDiscountDeleted = 'ORDER_DISCOUNT_DELETED', OrderLineDiscountUpdated = 'ORDER_LINE_DISCOUNT_UPDATED', OrderLineDiscountRemoved = 'ORDER_LINE_DISCOUNT_REMOVED', UpdatedAddress = 'UPDATED_ADDRESS', EmailSent = 'EMAIL_SENT', Confirmed = 'CONFIRMED', PaymentAuthorized = 'PAYMENT_AUTHORIZED', PaymentCaptured = 'PAYMENT_CAPTURED', ExternalServiceNotification = 'EXTERNAL_SERVICE_NOTIFICATION', PaymentRefunded = 'PAYMENT_REFUNDED', PaymentVoided = 'PAYMENT_VOIDED', PaymentFailed = 'PAYMENT_FAILED', InvoiceRequested = 'INVOICE_REQUESTED', InvoiceGenerated = 'INVOICE_GENERATED', InvoiceUpdated = 'INVOICE_UPDATED', InvoiceSent = 'INVOICE_SENT', FulfillmentCanceled = 'FULFILLMENT_CANCELED', FulfillmentRestockedItems = 'FULFILLMENT_RESTOCKED_ITEMS', FulfillmentFulfilledItems = 'FULFILLMENT_FULFILLED_ITEMS', FulfillmentRefunded = 'FULFILLMENT_REFUNDED', FulfillmentReturned = 'FULFILLMENT_RETURNED', FulfillmentReplaced = 'FULFILLMENT_REPLACED', TrackingUpdated = 'TRACKING_UPDATED', NoteAdded = 'NOTE_ADDED', Other = 'OTHER', } export type OrderFilterInput = { paymentStatus?: Maybe<Array<Maybe<PaymentChargeStatusEnum>>> status?: Maybe<Array<Maybe<OrderStatusFilter>>> customer?: Maybe<Scalars['String']> created?: Maybe<DateRangeInput> search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> channels?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Creates new fulfillments for an order. */ export type OrderFulfill = { __typename?: 'OrderFulfill' /** List of created fulfillments. */ fulfillments?: Maybe<Array<Maybe<Fulfillment>>> /** Fulfilled order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderFulfillInput = { /** List of items informing how to fulfill the order. */ lines: Array<OrderFulfillLineInput> /** If true, send an email notification to the customer. */ notifyCustomer?: Maybe<Scalars['Boolean']> } export type OrderFulfillLineInput = { /** The ID of the order line. */ orderLineId?: Maybe<Scalars['ID']> /** List of stock items to create. */ stocks: Array<OrderFulfillStockInput> } export type OrderFulfillStockInput = { /** The number of line items to be fulfilled from given warehouse. */ quantity: Scalars['Int'] /** ID of the warehouse from which the item will be fulfilled. */ warehouse: Scalars['ID'] } /** Represents order line of particular order. */ export type OrderLine = Node & { __typename?: 'OrderLine' /** The ID of the object. */ id: Scalars['ID'] productName: Scalars['String'] variantName: Scalars['String'] productSku: Scalars['String'] isShippingRequired: Scalars['Boolean'] quantity: Scalars['Int'] quantityFulfilled: Scalars['Int'] unitDiscountReason?: Maybe<Scalars['String']> taxRate: Scalars['Float'] digitalContentUrl?: Maybe<DigitalContentUrl> /** The main thumbnail for the ordered product. */ thumbnail?: Maybe<Image> /** Price of the single item in the order line. */ unitPrice: TaxedMoney /** Price of the single item in the order line without applied an order line discount. */ undiscountedUnitPrice: TaxedMoney /** The discount applied to the single order line. */ unitDiscount: Money /** Value of the discount. Can store fixed value or percent value */ unitDiscountValue: Scalars['PositiveDecimal'] /** Price of the order line. */ totalPrice: TaxedMoney /** A purchased product variant. Note: this field may be null if the variant has been removed from stock at all. */ variant?: Maybe<ProductVariant> /** Product name in the customer's language */ translatedProductName: Scalars['String'] /** Variant name in the customer's language */ translatedVariantName: Scalars['String'] /** List of allocations across warehouses. */ allocations?: Maybe<Array<Allocation>> /** Type of the discount: fixed or percent */ unitDiscountType?: Maybe<DiscountValueTypeEnum> } /** Represents order line of particular order. */ export type OrderLineThumbnailArgs = { size?: Maybe<Scalars['Int']> } export type OrderLineCreateInput = { /** Number of variant items ordered. */ quantity: Scalars['Int'] /** Product variant ID. */ variantId: Scalars['ID'] } /** Deletes an order line from an order. */ export type OrderLineDelete = { __typename?: 'OrderLineDelete' /** A related order. */ order?: Maybe<Order> /** An order line that was deleted. */ orderLine?: Maybe<OrderLine> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Remove discount applied to the order line. */ export type OrderLineDiscountRemove = { __typename?: 'OrderLineDiscountRemove' /** Order line which has removed discount. */ orderLine?: Maybe<OrderLine> /** Order which is related to line which has removed discount. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Update discount for the order line. */ export type OrderLineDiscountUpdate = { __typename?: 'OrderLineDiscountUpdate' /** Order line which has been discounted. */ orderLine?: Maybe<OrderLine> /** Order which is related to the discounted line. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderLineInput = { /** Number of variant items ordered. */ quantity: Scalars['Int'] } /** Updates an order line of an order. */ export type OrderLineUpdate = { __typename?: 'OrderLineUpdate' /** Related order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> orderLine?: Maybe<OrderLine> } /** Create order lines for an order. */ export type OrderLinesCreate = { __typename?: 'OrderLinesCreate' /** Related order. */ order?: Maybe<Order> /** List of added order lines. */ orderLines?: Maybe<Array<OrderLine>> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** Mark order as manually paid. */ export type OrderMarkAsPaid = { __typename?: 'OrderMarkAsPaid' /** Order marked as paid. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** An enumeration. */ export enum OrderOriginEnum { Checkout = 'CHECKOUT', Draft = 'DRAFT', Reissue = 'REISSUE', } /** Refund an order. */ export type OrderRefund = { __typename?: 'OrderRefund' /** A refunded order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderRefundFulfillmentLineInput = { /** The ID of the fulfillment line to refund. */ fulfillmentLineId: Scalars['ID'] /** The number of items to be refunded. */ quantity: Scalars['Int'] } export type OrderRefundLineInput = { /** The ID of the order line to refund. */ orderLineId: Scalars['ID'] /** The number of items to be refunded. */ quantity: Scalars['Int'] } export type OrderRefundProductsInput = { /** List of unfulfilled lines to refund. */ orderLines?: Maybe<Array<OrderRefundLineInput>> /** List of fulfilled lines to refund. */ fulfillmentLines?: Maybe<Array<OrderRefundFulfillmentLineInput>> /** The total amount of refund when the value is provided manually. */ amountToRefund?: Maybe<Scalars['PositiveDecimal']> /** If true, Saleor will refund shipping costs. If amountToRefund is providedincludeShippingCosts will be ignored. */ includeShippingCosts?: Maybe<Scalars['Boolean']> } export type OrderReturnFulfillmentLineInput = { /** The ID of the fulfillment line to return. */ fulfillmentLineId: Scalars['ID'] /** The number of items to be returned. */ quantity: Scalars['Int'] /** Determines, if the line should be added to replace order. */ replace?: Maybe<Scalars['Boolean']> } export type OrderReturnLineInput = { /** The ID of the order line to return. */ orderLineId: Scalars['ID'] /** The number of items to be returned. */ quantity: Scalars['Int'] /** Determines, if the line should be added to replace order. */ replace?: Maybe<Scalars['Boolean']> } export type OrderReturnProductsInput = { /** List of unfulfilled lines to return. */ orderLines?: Maybe<Array<OrderReturnLineInput>> /** List of fulfilled lines to return. */ fulfillmentLines?: Maybe<Array<OrderReturnFulfillmentLineInput>> /** The total amount of refund when the value is provided manually. */ amountToRefund?: Maybe<Scalars['PositiveDecimal']> /** If true, Saleor will refund shipping costs. If amountToRefund is providedincludeShippingCosts will be ignored. */ includeShippingCosts?: Maybe<Scalars['Boolean']> /** If true, Saleor will call refund action for all lines. */ refund?: Maybe<Scalars['Boolean']> } /** Order related settings from site settings. */ export type OrderSettings = { __typename?: 'OrderSettings' automaticallyConfirmAllNewOrders: Scalars['Boolean'] } export type OrderSettingsError = { __typename?: 'OrderSettingsError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: OrderSettingsErrorCode } /** An enumeration. */ export enum OrderSettingsErrorCode { Invalid = 'INVALID', } /** Update shop order settings. */ export type OrderSettingsUpdate = { __typename?: 'OrderSettingsUpdate' /** Order settings. */ orderSettings?: Maybe<OrderSettings> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderSettingsErrors: Array<OrderSettingsError> errors: Array<OrderSettingsError> } export type OrderSettingsUpdateInput = { /** When disabled, all new orders from checkout will be marked as unconfirmed. When enabled orders from checkout will become unfulfilled immediately. */ automaticallyConfirmAllNewOrders: Scalars['Boolean'] } export enum OrderSortField { /** Sort orders by number. */ Number = 'NUMBER', /** Sort orders by creation date. */ CreationDate = 'CREATION_DATE', /** Sort orders by customer. */ Customer = 'CUSTOMER', /** Sort orders by payment. */ Payment = 'PAYMENT', /** Sort orders by fulfillment status. */ FulfillmentStatus = 'FULFILLMENT_STATUS', } export type OrderSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort orders by the selected field. */ field: OrderSortField } /** An enumeration. */ export enum OrderStatus { /** Draft */ Draft = 'DRAFT', /** Unconfirmed */ Unconfirmed = 'UNCONFIRMED', /** Unfulfilled */ Unfulfilled = 'UNFULFILLED', /** Partially fulfilled */ PartiallyFulfilled = 'PARTIALLY_FULFILLED', /** Partially returned */ PartiallyReturned = 'PARTIALLY_RETURNED', /** Returned */ Returned = 'RETURNED', /** Fulfilled */ Fulfilled = 'FULFILLED', /** Canceled */ Canceled = 'CANCELED', } export enum OrderStatusFilter { ReadyToFulfill = 'READY_TO_FULFILL', ReadyToCapture = 'READY_TO_CAPTURE', Unfulfilled = 'UNFULFILLED', Unconfirmed = 'UNCONFIRMED', PartiallyFulfilled = 'PARTIALLY_FULFILLED', Fulfilled = 'FULFILLED', Canceled = 'CANCELED', } /** Updates an order. */ export type OrderUpdate = { __typename?: 'OrderUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> order?: Maybe<Order> } export type OrderUpdateInput = { /** Billing address of the customer. */ billingAddress?: Maybe<AddressInput> /** Email address of the customer. */ userEmail?: Maybe<Scalars['String']> /** Shipping address of the customer. */ shippingAddress?: Maybe<AddressInput> } /** Updates a shipping method of the order. */ export type OrderUpdateShipping = { __typename?: 'OrderUpdateShipping' /** Order with updated shipping method. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } export type OrderUpdateShippingInput = { /** ID of the selected shipping method. */ shippingMethod?: Maybe<Scalars['ID']> } /** Void an order. */ export type OrderVoid = { __typename?: 'OrderVoid' /** A voided order. */ order?: Maybe<Order> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ orderErrors: Array<OrderError> errors: Array<OrderError> } /** A static page that can be manually added by a shop operator through the dashboard. */ export type Page = Node & ObjectWithMetadata & { __typename?: 'Page' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> title: Scalars['String'] content?: Maybe<Scalars['JSONString']> publicationDate?: Maybe<Scalars['Date']> isPublished: Scalars['Boolean'] slug: Scalars['String'] pageType: PageType created: Scalars['DateTime'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** * Content of the page (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `content` field instead. */ contentJson: Scalars['JSONString'] /** Returns translated page fields for the given language code. */ translation?: Maybe<PageTranslation> /** List of attributes assigned to this product. */ attributes: Array<SelectedAttribute> } /** A static page that can be manually added by a shop operator through the dashboard. */ export type PageTranslationArgs = { languageCode: LanguageCodeEnum } /** Assign attributes to a given page type. */ export type PageAttributeAssign = { __typename?: 'PageAttributeAssign' /** The updated page type. */ pageType?: Maybe<PageType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } /** Unassign attributes from a given page type. */ export type PageAttributeUnassign = { __typename?: 'PageAttributeUnassign' /** The updated page type. */ pageType?: Maybe<PageType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } /** Deletes pages. */ export type PageBulkDelete = { __typename?: 'PageBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } /** Publish pages. */ export type PageBulkPublish = { __typename?: 'PageBulkPublish' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } export type PageCountableConnection = { __typename?: 'PageCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<PageCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type PageCountableEdge = { __typename?: 'PageCountableEdge' /** The item at the end of the edge. */ node: Page /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new page. */ export type PageCreate = { __typename?: 'PageCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> page?: Maybe<Page> } export type PageCreateInput = { /** Page internal name. */ slug?: Maybe<Scalars['String']> /** Page title. */ title?: Maybe<Scalars['String']> /** Page content in JSON format. */ content?: Maybe<Scalars['JSONString']> /** List of attributes. */ attributes?: Maybe<Array<AttributeValueInput>> /** Determines if page is visible in the storefront. */ isPublished?: Maybe<Scalars['Boolean']> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** ID of the page type that page belongs to. */ pageType: Scalars['ID'] } /** Deletes a page. */ export type PageDelete = { __typename?: 'PageDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> page?: Maybe<Page> } export type PageError = { __typename?: 'PageError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: PageErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum PageErrorCode { GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', AttributeAlreadyAssigned = 'ATTRIBUTE_ALREADY_ASSIGNED', } export type PageFilterInput = { search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> pageTypes?: Maybe<Array<Maybe<Scalars['ID']>>> } /** The Relay compliant `PageInfo` type, containing data necessary to paginate this connection. */ export type PageInfo = { __typename?: 'PageInfo' /** When paginating forwards, are there more items? */ hasNextPage: Scalars['Boolean'] /** When paginating backwards, are there more items? */ hasPreviousPage: Scalars['Boolean'] /** When paginating backwards, the cursor to continue. */ startCursor?: Maybe<Scalars['String']> /** When paginating forwards, the cursor to continue. */ endCursor?: Maybe<Scalars['String']> } export type PageInput = { /** Page internal name. */ slug?: Maybe<Scalars['String']> /** Page title. */ title?: Maybe<Scalars['String']> /** Page content in JSON format. */ content?: Maybe<Scalars['JSONString']> /** List of attributes. */ attributes?: Maybe<Array<AttributeValueInput>> /** Determines if page is visible in the storefront. */ isPublished?: Maybe<Scalars['Boolean']> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> } /** Reorder page attribute values. */ export type PageReorderAttributeValues = { __typename?: 'PageReorderAttributeValues' /** Page from which attribute values are reordered. */ page?: Maybe<Page> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } export enum PageSortField { /** Sort pages by title. */ Title = 'TITLE', /** Sort pages by slug. */ Slug = 'SLUG', /** Sort pages by visibility. */ Visibility = 'VISIBILITY', /** Sort pages by creation date. */ CreationDate = 'CREATION_DATE', /** Sort pages by publication date. */ PublicationDate = 'PUBLICATION_DATE', } export type PageSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort pages by the selected field. */ field: PageSortField } export type PageTranslatableContent = Node & { __typename?: 'PageTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> title: Scalars['String'] content?: Maybe<Scalars['JSONString']> /** * Content of the page (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `content` field instead. */ contentJson?: Maybe<Scalars['JSONString']> /** Returns translated page fields for the given language code. */ translation?: Maybe<PageTranslation> /** ('A static page that can be manually added by a shop operator ', 'through the dashboard.') */ page?: Maybe<Page> } export type PageTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Page. */ export type PageTranslate = { __typename?: 'PageTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> page?: Maybe<PageTranslatableContent> } export type PageTranslation = Node & { __typename?: 'PageTranslation' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> title: Scalars['String'] content?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay /** * Translated description of the page (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `content` field instead. */ contentJson?: Maybe<Scalars['JSONString']> } export type PageTranslationInput = { seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> title?: Maybe<Scalars['String']> content?: Maybe<Scalars['JSONString']> } /** Represents a type of page. It defines what attributes are available to pages of this type. */ export type PageType = Node & ObjectWithMetadata & { __typename?: 'PageType' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] slug: Scalars['String'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Page attributes of that page type. */ attributes?: Maybe<Array<Maybe<Attribute>>> /** Attributes that can be assigned to the page type. */ availableAttributes?: Maybe<AttributeCountableConnection> /** Whether page type has pages assigned. */ hasPages?: Maybe<Scalars['Boolean']> } /** Represents a type of page. It defines what attributes are available to pages of this type. */ export type PageTypeAvailableAttributesArgs = { filter?: Maybe<AttributeFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Delete page types. */ export type PageTypeBulkDelete = { __typename?: 'PageTypeBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } export type PageTypeCountableConnection = { __typename?: 'PageTypeCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<PageTypeCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type PageTypeCountableEdge = { __typename?: 'PageTypeCountableEdge' /** The item at the end of the edge. */ node: PageType /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Create a new page type. */ export type PageTypeCreate = { __typename?: 'PageTypeCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> pageType?: Maybe<PageType> } export type PageTypeCreateInput = { /** Name of the page type. */ name?: Maybe<Scalars['String']> /** Page type slug. */ slug?: Maybe<Scalars['String']> /** List of attribute IDs to be assigned to the page type. */ addAttributes?: Maybe<Array<Scalars['ID']>> } /** Delete a page type. */ export type PageTypeDelete = { __typename?: 'PageTypeDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> pageType?: Maybe<PageType> } export type PageTypeFilterInput = { search?: Maybe<Scalars['String']> } /** Reorder the attributes of a page type. */ export type PageTypeReorderAttributes = { __typename?: 'PageTypeReorderAttributes' /** Page type from which attributes are reordered. */ pageType?: Maybe<PageType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> } export enum PageTypeSortField { /** Sort page types by name. */ Name = 'NAME', /** Sort page types by slug. */ Slug = 'SLUG', } export type PageTypeSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort page types by the selected field. */ field: PageTypeSortField } /** Update page type. */ export type PageTypeUpdate = { __typename?: 'PageTypeUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> pageType?: Maybe<PageType> } export type PageTypeUpdateInput = { /** Name of the page type. */ name?: Maybe<Scalars['String']> /** Page type slug. */ slug?: Maybe<Scalars['String']> /** List of attribute IDs to be assigned to the page type. */ addAttributes?: Maybe<Array<Scalars['ID']>> /** List of attribute IDs to be assigned to the page type. */ removeAttributes?: Maybe<Array<Scalars['ID']>> } /** Updates an existing page. */ export type PageUpdate = { __typename?: 'PageUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pageErrors: Array<PageError> errors: Array<PageError> page?: Maybe<Page> } /** Change the password of the logged in user. */ export type PasswordChange = { __typename?: 'PasswordChange' /** A user instance with a new password. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Represents a payment of a given type. */ export type Payment = Node & { __typename?: 'Payment' /** The ID of the object. */ id: Scalars['ID'] gateway: Scalars['String'] isActive: Scalars['Boolean'] created: Scalars['DateTime'] modified: Scalars['DateTime'] token: Scalars['String'] checkout?: Maybe<Checkout> order?: Maybe<Order> paymentMethodType: Scalars['String'] customerIpAddress?: Maybe<Scalars['String']> /** Internal payment status. */ chargeStatus: PaymentChargeStatusEnum /** List of actions that can be performed in the current state of a payment. */ actions: Array<Maybe<OrderAction>> /** Total amount of the payment. */ total?: Maybe<Money> /** Total amount captured for this payment. */ capturedAmount?: Maybe<Money> /** List of all transactions within this payment. */ transactions?: Maybe<Array<Maybe<Transaction>>> /** Maximum amount of money that can be captured. */ availableCaptureAmount?: Maybe<Money> /** Maximum amount of money that can be refunded. */ availableRefundAmount?: Maybe<Money> /** The details of the card used for this payment. */ creditCard?: Maybe<CreditCard> } /** Captures the authorized payment amount. */ export type PaymentCapture = { __typename?: 'PaymentCapture' /** Updated payment. */ payment?: Maybe<Payment> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ paymentErrors: Array<PaymentError> errors: Array<PaymentError> } /** An enumeration. */ export enum PaymentChargeStatusEnum { NotCharged = 'NOT_CHARGED', Pending = 'PENDING', PartiallyCharged = 'PARTIALLY_CHARGED', FullyCharged = 'FULLY_CHARGED', PartiallyRefunded = 'PARTIALLY_REFUNDED', FullyRefunded = 'FULLY_REFUNDED', Refused = 'REFUSED', Cancelled = 'CANCELLED', } export type PaymentCountableConnection = { __typename?: 'PaymentCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<PaymentCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type PaymentCountableEdge = { __typename?: 'PaymentCountableEdge' /** The item at the end of the edge. */ node: Payment /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type PaymentError = { __typename?: 'PaymentError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: PaymentErrorCode } /** An enumeration. */ export enum PaymentErrorCode { BillingAddressNotSet = 'BILLING_ADDRESS_NOT_SET', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', PartialPaymentNotAllowed = 'PARTIAL_PAYMENT_NOT_ALLOWED', ShippingAddressNotSet = 'SHIPPING_ADDRESS_NOT_SET', InvalidShippingMethod = 'INVALID_SHIPPING_METHOD', ShippingMethodNotSet = 'SHIPPING_METHOD_NOT_SET', PaymentError = 'PAYMENT_ERROR', NotSupportedGateway = 'NOT_SUPPORTED_GATEWAY', ChannelInactive = 'CHANNEL_INACTIVE', } export type PaymentFilterInput = { checkouts?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Available payment gateway backend with configuration necessary to setup client. */ export type PaymentGateway = { __typename?: 'PaymentGateway' /** Payment gateway name. */ name: Scalars['String'] /** Payment gateway ID. */ id: Scalars['ID'] /** Payment gateway client configuration. */ config: Array<GatewayConfigLine> /** Payment gateway supported currencies. */ currencies: Array<Maybe<Scalars['String']>> } /** Initializes payment process when it is required by gateway. */ export type PaymentInitialize = { __typename?: 'PaymentInitialize' initializedPayment?: Maybe<PaymentInitialized> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ paymentErrors: Array<PaymentError> errors: Array<PaymentError> } /** Server-side data generated by a payment gateway. Optional step when the payment provider requires an additional action to initialize payment session. */ export type PaymentInitialized = { __typename?: 'PaymentInitialized' /** ID of a payment gateway. */ gateway: Scalars['String'] /** Payment gateway name. */ name: Scalars['String'] /** Initialized data by gateway. */ data?: Maybe<Scalars['JSONString']> } export type PaymentInput = { /** A gateway to use with that payment. */ gateway: Scalars['String'] /** Client-side generated payment token, representing customer's billing data in a secure manner. */ token?: Maybe<Scalars['String']> /** Total amount of the transaction, including all taxes and discounts. If no amount is provided, the checkout total will be used. */ amount?: Maybe<Scalars['PositiveDecimal']> /** URL of a storefront view where user should be redirected after requiring additional actions. Payment with additional actions will not be finished if this field is not provided. */ returnUrl?: Maybe<Scalars['String']> } /** Refunds the captured payment amount. */ export type PaymentRefund = { __typename?: 'PaymentRefund' /** Updated payment. */ payment?: Maybe<Payment> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ paymentErrors: Array<PaymentError> errors: Array<PaymentError> } /** Represents a payment source stored for user in payment gateway, such as credit card. */ export type PaymentSource = { __typename?: 'PaymentSource' /** Payment gateway name. */ gateway: Scalars['String'] /** Stored credit card details if available. */ creditCardInfo?: Maybe<CreditCard> } /** Voids the authorized payment. */ export type PaymentVoid = { __typename?: 'PaymentVoid' /** Updated payment. */ payment?: Maybe<Payment> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ paymentErrors: Array<PaymentError> errors: Array<PaymentError> } /** Represents a permission object in a friendly form. */ export type Permission = { __typename?: 'Permission' /** Internal code for permission. */ code: PermissionEnum /** Describe action(s) allowed to do by permission. */ name: Scalars['String'] } /** An enumeration. */ export enum PermissionEnum { ManageUsers = 'MANAGE_USERS', ManageStaff = 'MANAGE_STAFF', ManageApps = 'MANAGE_APPS', ManageChannels = 'MANAGE_CHANNELS', ManageDiscounts = 'MANAGE_DISCOUNTS', ManagePlugins = 'MANAGE_PLUGINS', ManageGiftCard = 'MANAGE_GIFT_CARD', ManageMenus = 'MANAGE_MENUS', ManageOrders = 'MANAGE_ORDERS', ManagePages = 'MANAGE_PAGES', ManagePageTypesAndAttributes = 'MANAGE_PAGE_TYPES_AND_ATTRIBUTES', ManageProducts = 'MANAGE_PRODUCTS', ManageProductTypesAndAttributes = 'MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES', ManageShipping = 'MANAGE_SHIPPING', ManageSettings = 'MANAGE_SETTINGS', ManageTranslations = 'MANAGE_TRANSLATIONS', ManageCheckouts = 'MANAGE_CHECKOUTS', } /** Create new permission group. */ export type PermissionGroupCreate = { __typename?: 'PermissionGroupCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ permissionGroupErrors: Array<PermissionGroupError> errors: Array<PermissionGroupError> group?: Maybe<Group> } export type PermissionGroupCreateInput = { /** List of permission code names to assign to this group. */ addPermissions?: Maybe<Array<PermissionEnum>> /** List of users to assign to this group. */ addUsers?: Maybe<Array<Scalars['ID']>> /** Group name. */ name: Scalars['String'] } /** Delete permission group. */ export type PermissionGroupDelete = { __typename?: 'PermissionGroupDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ permissionGroupErrors: Array<PermissionGroupError> errors: Array<PermissionGroupError> group?: Maybe<Group> } export type PermissionGroupError = { __typename?: 'PermissionGroupError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: PermissionGroupErrorCode /** List of permissions which causes the error. */ permissions?: Maybe<Array<PermissionEnum>> /** List of user IDs which causes the error. */ users?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum PermissionGroupErrorCode { AssignNonStaffMember = 'ASSIGN_NON_STAFF_MEMBER', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', CannotRemoveFromLastGroup = 'CANNOT_REMOVE_FROM_LAST_GROUP', LeftNotManageablePermission = 'LEFT_NOT_MANAGEABLE_PERMISSION', OutOfScopePermission = 'OUT_OF_SCOPE_PERMISSION', OutOfScopeUser = 'OUT_OF_SCOPE_USER', Required = 'REQUIRED', Unique = 'UNIQUE', } export type PermissionGroupFilterInput = { search?: Maybe<Scalars['String']> } export enum PermissionGroupSortField { /** Sort permission group accounts by name. */ Name = 'NAME', } export type PermissionGroupSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort permission group by the selected field. */ field: PermissionGroupSortField } /** Update permission group. */ export type PermissionGroupUpdate = { __typename?: 'PermissionGroupUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ permissionGroupErrors: Array<PermissionGroupError> errors: Array<PermissionGroupError> group?: Maybe<Group> } export type PermissionGroupUpdateInput = { /** List of permission code names to assign to this group. */ addPermissions?: Maybe<Array<PermissionEnum>> /** List of users to assign to this group. */ addUsers?: Maybe<Array<Scalars['ID']>> /** Group name. */ name?: Maybe<Scalars['String']> /** List of permission code names to unassign from this group. */ removePermissions?: Maybe<Array<PermissionEnum>> /** List of users to unassign from this group. */ removeUsers?: Maybe<Array<Scalars['ID']>> } /** Plugin. */ export type Plugin = { __typename?: 'Plugin' /** Identifier of the plugin. */ id: Scalars['ID'] /** Name of the plugin. */ name: Scalars['String'] /** Description of the plugin. */ description: Scalars['String'] /** Global configuration of the plugin (not channel-specific). */ globalConfiguration?: Maybe<PluginConfiguration> /** Channel-specific plugin configuration. */ channelConfigurations: Array<PluginConfiguration> } /** Stores information about a configuration of plugin. */ export type PluginConfiguration = { __typename?: 'PluginConfiguration' /** Determines if plugin is active or not. */ active: Scalars['Boolean'] /** The channel to which the plugin configuration is assigned to. */ channel?: Maybe<Channel> /** Configuration of the plugin. */ configuration?: Maybe<Array<Maybe<ConfigurationItem>>> } export enum PluginConfigurationType { PerChannel = 'PER_CHANNEL', Global = 'GLOBAL', } export type PluginCountableConnection = { __typename?: 'PluginCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<PluginCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type PluginCountableEdge = { __typename?: 'PluginCountableEdge' /** The item at the end of the edge. */ node: Plugin /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type PluginError = { __typename?: 'PluginError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: PluginErrorCode } /** An enumeration. */ export enum PluginErrorCode { GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', PluginMisconfigured = 'PLUGIN_MISCONFIGURED', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } export type PluginFilterInput = { statusInChannels?: Maybe<PluginStatusInChannelsInput> search?: Maybe<Scalars['String']> type?: Maybe<PluginConfigurationType> } export enum PluginSortField { Name = 'NAME', IsActive = 'IS_ACTIVE', } export type PluginSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort plugins by the selected field. */ field: PluginSortField } export type PluginStatusInChannelsInput = { active: Scalars['Boolean'] channels: Array<Scalars['ID']> } /** Update plugin configuration. */ export type PluginUpdate = { __typename?: 'PluginUpdate' plugin?: Maybe<Plugin> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ pluginsErrors: Array<PluginError> errors: Array<PluginError> } export type PluginUpdateInput = { /** Indicates whether the plugin should be enabled. */ active?: Maybe<Scalars['Boolean']> /** Configuration of the plugin. */ configuration?: Maybe<Array<Maybe<ConfigurationItemInput>>> } /** An enumeration. */ export enum PostalCodeRuleInclusionTypeEnum { Include = 'INCLUDE', Exclude = 'EXCLUDE', } export type PriceRangeInput = { /** Price greater than or equal to. */ gte?: Maybe<Scalars['Float']> /** Price less than or equal to. */ lte?: Maybe<Scalars['Float']> } /** Represents an individual item for sale in the storefront. */ export type Product = Node & ObjectWithMetadata & { __typename?: 'Product' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> productType: ProductType slug: Scalars['String'] category?: Maybe<Category> updatedAt?: Maybe<Scalars['DateTime']> chargeTaxes: Scalars['Boolean'] weight?: Maybe<Weight> defaultVariant?: Maybe<ProductVariant> rating?: Maybe<Scalars['Float']> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** * Description of the product (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** The main thumbnail for a product. */ thumbnail?: Maybe<Image> /** Lists the storefront product's pricing, the current price and discounts, only meant for displaying. */ pricing?: Maybe<ProductPricingInfo> /** Whether the product is in stock and visible or not. */ isAvailable?: Maybe<Scalars['Boolean']> /** A type of tax. Assigned by enabled tax gateway */ taxType?: Maybe<TaxType> /** List of attributes assigned to this product. */ attributes: Array<SelectedAttribute> /** List of availability in channels for the product. */ channelListings?: Maybe<Array<ProductChannelListing>> /** Get a single product media by ID. */ mediaById: ProductMedia /** * Get a single product image by ID. * @deprecated Will be removed in Saleor 4.0. Use the `mediaById` field instead. */ imageById?: Maybe<ProductImage> /** List of variants for the product. */ variants?: Maybe<Array<Maybe<ProductVariant>>> /** List of media for the product. */ media?: Maybe<Array<ProductMedia>> /** * List of images for the product. * @deprecated Will be removed in Saleor 4.0. Use the `media` field instead. */ images?: Maybe<Array<Maybe<ProductImage>>> /** List of collections for the product. */ collections?: Maybe<Array<Maybe<Collection>>> /** Returns translated product fields for the given language code. */ translation?: Maybe<ProductTranslation> /** Date when product is available for purchase. */ availableForPurchase?: Maybe<Scalars['Date']> /** Whether the product is available for purchase. */ isAvailableForPurchase?: Maybe<Scalars['Boolean']> } /** Represents an individual item for sale in the storefront. */ export type ProductThumbnailArgs = { size?: Maybe<Scalars['Int']> } /** Represents an individual item for sale in the storefront. */ export type ProductPricingArgs = { address?: Maybe<AddressInput> } /** Represents an individual item for sale in the storefront. */ export type ProductIsAvailableArgs = { address?: Maybe<AddressInput> } /** Represents an individual item for sale in the storefront. */ export type ProductMediaByIdArgs = { id?: Maybe<Scalars['ID']> } /** Represents an individual item for sale in the storefront. */ export type ProductImageByIdArgs = { id?: Maybe<Scalars['ID']> } /** Represents an individual item for sale in the storefront. */ export type ProductTranslationArgs = { languageCode: LanguageCodeEnum } /** Assign attributes to a given product type. */ export type ProductAttributeAssign = { __typename?: 'ProductAttributeAssign' /** The updated product type. */ productType?: Maybe<ProductType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type ProductAttributeAssignInput = { /** The ID of the attribute to assign. */ id: Scalars['ID'] /** The attribute type to be assigned as. */ type: ProductAttributeType } export enum ProductAttributeType { Product = 'PRODUCT', Variant = 'VARIANT', } /** Un-assign attributes from a given product type. */ export type ProductAttributeUnassign = { __typename?: 'ProductAttributeUnassign' /** The updated product type. */ productType?: Maybe<ProductType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Deletes products. */ export type ProductBulkDelete = { __typename?: 'ProductBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Represents product channel listing. */ export type ProductChannelListing = Node & { __typename?: 'ProductChannelListing' /** The ID of the object. */ id: Scalars['ID'] publicationDate?: Maybe<Scalars['Date']> isPublished: Scalars['Boolean'] channel: Channel visibleInListings: Scalars['Boolean'] availableForPurchase?: Maybe<Scalars['Date']> /** The price of the cheapest variant (including discounts). */ discountedPrice?: Maybe<Money> /** Purchase cost of product. */ purchaseCost?: Maybe<MoneyRange> /** Range of margin percentage value. */ margin?: Maybe<Margin> /** Whether the product is available for purchase. */ isAvailableForPurchase?: Maybe<Scalars['Boolean']> /** Lists the storefront product's pricing, the current price and discounts, only meant for displaying. */ pricing?: Maybe<ProductPricingInfo> } /** Represents product channel listing. */ export type ProductChannelListingPricingArgs = { address?: Maybe<AddressInput> } export type ProductChannelListingAddInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** Determines if object is visible to customers. */ isPublished?: Maybe<Scalars['Boolean']> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['Date']> /** Determines if product is visible in product listings (doesn't apply to product collections). */ visibleInListings?: Maybe<Scalars['Boolean']> /** Determine if product should be available for purchase. */ isAvailableForPurchase?: Maybe<Scalars['Boolean']> /** A start date from which a product will be available for purchase. When not set and isAvailable is set to True, the current day is assumed. */ availableForPurchaseDate?: Maybe<Scalars['Date']> /** List of variants to which the channel should be assigned. */ addVariants?: Maybe<Array<Scalars['ID']>> /** List of variants from which the channel should be unassigned. */ removeVariants?: Maybe<Array<Scalars['ID']>> } export type ProductChannelListingError = { __typename?: 'ProductChannelListingError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ProductErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> /** List of channels IDs which causes the error. */ channels?: Maybe<Array<Scalars['ID']>> /** List of variants IDs which causes the error. */ variants?: Maybe<Array<Scalars['ID']>> } /** Manage product's availability in channels. */ export type ProductChannelListingUpdate = { __typename?: 'ProductChannelListingUpdate' /** An updated product instance. */ product?: Maybe<Product> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productChannelListingErrors: Array<ProductChannelListingError> errors: Array<ProductChannelListingError> } export type ProductChannelListingUpdateInput = { /** List of channels to which the product should be assigned or updated. */ updateChannels?: Maybe<Array<ProductChannelListingAddInput>> /** List of channels from which the product should be unassigned. */ removeChannels?: Maybe<Array<Scalars['ID']>> } export type ProductCountableConnection = { __typename?: 'ProductCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<ProductCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type ProductCountableEdge = { __typename?: 'ProductCountableEdge' /** The item at the end of the edge. */ node: Product /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new product. */ export type ProductCreate = { __typename?: 'ProductCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> product?: Maybe<Product> } export type ProductCreateInput = { /** List of attributes. */ attributes?: Maybe<Array<AttributeValueInput>> /** ID of the product's category. */ category?: Maybe<Scalars['ID']> /** Determine if taxes are being charged for the product. */ chargeTaxes?: Maybe<Scalars['Boolean']> /** List of IDs of collections that the product belongs to. */ collections?: Maybe<Array<Scalars['ID']>> /** Product description (JSON). */ description?: Maybe<Scalars['JSONString']> /** Product name. */ name?: Maybe<Scalars['String']> /** Product slug. */ slug?: Maybe<Scalars['String']> /** Tax rate for enabled tax gateway. */ taxCode?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** Weight of the Product. */ weight?: Maybe<Scalars['WeightScalar']> /** Defines the product rating value. */ rating?: Maybe<Scalars['Float']> /** ID of the type that product belongs to. */ productType: Scalars['ID'] } /** Deletes a product. */ export type ProductDelete = { __typename?: 'ProductDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> product?: Maybe<Product> } export type ProductError = { __typename?: 'ProductError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ProductErrorCode /** List of attributes IDs which causes the error. */ attributes?: Maybe<Array<Scalars['ID']>> /** List of attribute values IDs which causes the error. */ values?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum ProductErrorCode { AlreadyExists = 'ALREADY_EXISTS', AttributeAlreadyAssigned = 'ATTRIBUTE_ALREADY_ASSIGNED', AttributeCannotBeAssigned = 'ATTRIBUTE_CANNOT_BE_ASSIGNED', AttributeVariantsDisabled = 'ATTRIBUTE_VARIANTS_DISABLED', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', ProductWithoutCategory = 'PRODUCT_WITHOUT_CATEGORY', NotProductsImage = 'NOT_PRODUCTS_IMAGE', NotProductsVariant = 'NOT_PRODUCTS_VARIANT', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', VariantNoDigitalContent = 'VARIANT_NO_DIGITAL_CONTENT', CannotManageProductWithoutVariant = 'CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT', ProductNotAssignedToChannel = 'PRODUCT_NOT_ASSIGNED_TO_CHANNEL', UnsupportedMediaProvider = 'UNSUPPORTED_MEDIA_PROVIDER', } export enum ProductFieldEnum { Name = 'NAME', Description = 'DESCRIPTION', ProductType = 'PRODUCT_TYPE', Category = 'CATEGORY', ProductWeight = 'PRODUCT_WEIGHT', Collections = 'COLLECTIONS', ChargeTaxes = 'CHARGE_TAXES', ProductMedia = 'PRODUCT_MEDIA', VariantSku = 'VARIANT_SKU', VariantWeight = 'VARIANT_WEIGHT', VariantMedia = 'VARIANT_MEDIA', } export type ProductFilterInput = { isPublished?: Maybe<Scalars['Boolean']> collections?: Maybe<Array<Maybe<Scalars['ID']>>> categories?: Maybe<Array<Maybe<Scalars['ID']>>> hasCategory?: Maybe<Scalars['Boolean']> attributes?: Maybe<Array<Maybe<AttributeInput>>> stockAvailability?: Maybe<StockAvailability> stocks?: Maybe<ProductStockFilterInput> search?: Maybe<Scalars['String']> metadata?: Maybe<Array<Maybe<MetadataInput>>> price?: Maybe<PriceRangeInput> minimalPrice?: Maybe<PriceRangeInput> productTypes?: Maybe<Array<Maybe<Scalars['ID']>>> ids?: Maybe<Array<Maybe<Scalars['ID']>>> /** Specifies the channel by which the data should be sorted. */ channel?: Maybe<Scalars['String']> } /** Represents a product image. */ export type ProductImage = { __typename?: 'ProductImage' /** The ID of the image. */ id: Scalars['ID'] /** The alt text of the image. */ alt?: Maybe<Scalars['String']> /** The new relative sorting position of the item (from -inf to +inf). 1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged. */ sortOrder?: Maybe<Scalars['Int']> /** The URL of the image. */ url: Scalars['String'] } /** Represents a product image. */ export type ProductImageUrlArgs = { size?: Maybe<Scalars['Int']> } export type ProductInput = { /** List of attributes. */ attributes?: Maybe<Array<AttributeValueInput>> /** ID of the product's category. */ category?: Maybe<Scalars['ID']> /** Determine if taxes are being charged for the product. */ chargeTaxes?: Maybe<Scalars['Boolean']> /** List of IDs of collections that the product belongs to. */ collections?: Maybe<Array<Scalars['ID']>> /** Product description (JSON). */ description?: Maybe<Scalars['JSONString']> /** Product name. */ name?: Maybe<Scalars['String']> /** Product slug. */ slug?: Maybe<Scalars['String']> /** Tax rate for enabled tax gateway. */ taxCode?: Maybe<Scalars['String']> /** Search engine optimization fields. */ seo?: Maybe<SeoInput> /** Weight of the Product. */ weight?: Maybe<Scalars['WeightScalar']> /** Defines the product rating value. */ rating?: Maybe<Scalars['Float']> } /** Represents a product media. */ export type ProductMedia = Node & { __typename?: 'ProductMedia' /** The ID of the object. */ id: Scalars['ID'] sortOrder?: Maybe<Scalars['Int']> alt: Scalars['String'] type: ProductMediaType oembedData: Scalars['JSONString'] /** The URL of the media. */ url: Scalars['String'] } /** Represents a product media. */ export type ProductMediaUrlArgs = { size?: Maybe<Scalars['Int']> } /** Deletes product media. */ export type ProductMediaBulkDelete = { __typename?: 'ProductMediaBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Create a media object (image or video URL) associated with product. For image, this mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ export type ProductMediaCreate = { __typename?: 'ProductMediaCreate' product?: Maybe<Product> media?: Maybe<ProductMedia> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type ProductMediaCreateInput = { /** Alt text for a product media. */ alt?: Maybe<Scalars['String']> /** Represents an image file in a multipart request. */ image?: Maybe<Scalars['Upload']> /** ID of an product. */ product: Scalars['ID'] /** Represents an URL to an external media. */ mediaUrl?: Maybe<Scalars['String']> } /** Deletes a product media. */ export type ProductMediaDelete = { __typename?: 'ProductMediaDelete' product?: Maybe<Product> media?: Maybe<ProductMedia> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Changes ordering of the product media. */ export type ProductMediaReorder = { __typename?: 'ProductMediaReorder' product?: Maybe<Product> media?: Maybe<Array<ProductMedia>> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** An enumeration. */ export enum ProductMediaType { /** An uploaded image or an URL to an image */ Image = 'IMAGE', /** A URL to an external video */ Video = 'VIDEO', } /** Updates a product media. */ export type ProductMediaUpdate = { __typename?: 'ProductMediaUpdate' product?: Maybe<Product> media?: Maybe<ProductMedia> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type ProductMediaUpdateInput = { /** Alt text for a product media. */ alt?: Maybe<Scalars['String']> } export type ProductOrder = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Specifies the channel in which to sort the data. */ channel?: Maybe<Scalars['String']> /** * Sort product by the selected attribute's values. * Note: this doesn't take translations into account yet. */ attributeId?: Maybe<Scalars['ID']> /** Sort products by the selected field. */ field?: Maybe<ProductOrderField> } export enum ProductOrderField { /** Sort products by name. */ Name = 'NAME', /** Sort products by rank. Note: This option is available only with the `search` filter. */ Rank = 'RANK', /** Sort products by price. */ Price = 'PRICE', /** Sort products by a minimal price of a product's variant. */ MinimalPrice = 'MINIMAL_PRICE', /** Sort products by update date. */ Date = 'DATE', /** Sort products by type. */ Type = 'TYPE', /** Sort products by publication status. */ Published = 'PUBLISHED', /** Sort products by publication date. */ PublicationDate = 'PUBLICATION_DATE', /** Sort products by collection. Note: This option is available only for the `Collection.products` query. */ Collection = 'COLLECTION', /** Sort products by rating. */ Rating = 'RATING', } /** Represents availability of a product in the storefront. */ export type ProductPricingInfo = { __typename?: 'ProductPricingInfo' /** Whether it is in sale or not. */ onSale?: Maybe<Scalars['Boolean']> /** The discount amount if in sale (null otherwise). */ discount?: Maybe<TaxedMoney> /** The discount amount in the local currency. */ discountLocalCurrency?: Maybe<TaxedMoney> /** The discounted price range of the product variants. */ priceRange?: Maybe<TaxedMoneyRange> /** The undiscounted price range of the product variants. */ priceRangeUndiscounted?: Maybe<TaxedMoneyRange> /** The discounted price range of the product variants in the local currency. */ priceRangeLocalCurrency?: Maybe<TaxedMoneyRange> } /** Reorder product attribute values. */ export type ProductReorderAttributeValues = { __typename?: 'ProductReorderAttributeValues' /** Product from which attribute values are reordered. */ product?: Maybe<Product> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export type ProductStockFilterInput = { warehouseIds?: Maybe<Array<Scalars['ID']>> quantity?: Maybe<IntRangeInput> } export type ProductTranslatableContent = Node & { __typename?: 'ProductTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** * Description of the product (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> /** Returns translated product fields for the given language code. */ translation?: Maybe<ProductTranslation> /** Represents an individual item for sale in the storefront. */ product?: Maybe<Product> } export type ProductTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Product. */ export type ProductTranslate = { __typename?: 'ProductTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> product?: Maybe<Product> } export type ProductTranslation = Node & { __typename?: 'ProductTranslation' /** The ID of the object. */ id: Scalars['ID'] seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay /** * Translated description of the product (JSON). * @deprecated Will be removed in Saleor 4.0. Use the `description` field instead. */ descriptionJson?: Maybe<Scalars['JSONString']> } /** Represents a type of product. It defines what attributes are available to products of this type. */ export type ProductType = Node & ObjectWithMetadata & { __typename?: 'ProductType' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] slug: Scalars['String'] hasVariants: Scalars['Boolean'] isShippingRequired: Scalars['Boolean'] isDigital: Scalars['Boolean'] weight?: Maybe<Weight> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** * List of products of this type. * @deprecated Will be removed in Saleor 4.0. Use the top-level `products` query with the `productTypes` filter. */ products?: Maybe<ProductCountableConnection> /** A type of tax. Assigned by enabled tax gateway */ taxType?: Maybe<TaxType> /** Variant attributes of that product type. */ variantAttributes?: Maybe<Array<Maybe<Attribute>>> /** Product attributes of that product type. */ productAttributes?: Maybe<Array<Maybe<Attribute>>> availableAttributes?: Maybe<AttributeCountableConnection> } /** Represents a type of product. It defines what attributes are available to products of this type. */ export type ProductTypeProductsArgs = { channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents a type of product. It defines what attributes are available to products of this type. */ export type ProductTypeVariantAttributesArgs = { variantSelection?: Maybe<VariantAttributeScope> } /** Represents a type of product. It defines what attributes are available to products of this type. */ export type ProductTypeAvailableAttributesArgs = { filter?: Maybe<AttributeFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Deletes product types. */ export type ProductTypeBulkDelete = { __typename?: 'ProductTypeBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export enum ProductTypeConfigurable { Configurable = 'CONFIGURABLE', Simple = 'SIMPLE', } export type ProductTypeCountableConnection = { __typename?: 'ProductTypeCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<ProductTypeCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type ProductTypeCountableEdge = { __typename?: 'ProductTypeCountableEdge' /** The item at the end of the edge. */ node: ProductType /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new product type. */ export type ProductTypeCreate = { __typename?: 'ProductTypeCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productType?: Maybe<ProductType> } /** Deletes a product type. */ export type ProductTypeDelete = { __typename?: 'ProductTypeDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productType?: Maybe<ProductType> } export enum ProductTypeEnum { Digital = 'DIGITAL', Shippable = 'SHIPPABLE', } export type ProductTypeFilterInput = { search?: Maybe<Scalars['String']> configurable?: Maybe<ProductTypeConfigurable> productType?: Maybe<ProductTypeEnum> metadata?: Maybe<Array<Maybe<MetadataInput>>> ids?: Maybe<Array<Maybe<Scalars['ID']>>> } export type ProductTypeInput = { /** Name of the product type. */ name?: Maybe<Scalars['String']> /** Product type slug. */ slug?: Maybe<Scalars['String']> /** Determines if product of this type has multiple variants. This option mainly simplifies product management in the dashboard. There is always at least one variant created under the hood. */ hasVariants?: Maybe<Scalars['Boolean']> /** List of attributes shared among all product variants. */ productAttributes?: Maybe<Array<Maybe<Scalars['ID']>>> /** List of attributes used to distinguish between different variants of a product. */ variantAttributes?: Maybe<Array<Maybe<Scalars['ID']>>> /** Determines if shipping is required for products of this variant. */ isShippingRequired?: Maybe<Scalars['Boolean']> /** Determines if products are digital. */ isDigital?: Maybe<Scalars['Boolean']> /** Weight of the ProductType items. */ weight?: Maybe<Scalars['WeightScalar']> /** Tax rate for enabled tax gateway. */ taxCode?: Maybe<Scalars['String']> } /** Reorder the attributes of a product type. */ export type ProductTypeReorderAttributes = { __typename?: 'ProductTypeReorderAttributes' /** Product type from which attributes are reordered. */ productType?: Maybe<ProductType> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } export enum ProductTypeSortField { /** Sort products by name. */ Name = 'NAME', /** Sort products by type. */ Digital = 'DIGITAL', /** Sort products by shipping. */ ShippingRequired = 'SHIPPING_REQUIRED', } export type ProductTypeSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort product types by the selected field. */ field: ProductTypeSortField } /** Updates an existing product type. */ export type ProductTypeUpdate = { __typename?: 'ProductTypeUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productType?: Maybe<ProductType> } /** Updates an existing product. */ export type ProductUpdate = { __typename?: 'ProductUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> product?: Maybe<Product> } /** Represents a version of a product such as different size or color. */ export type ProductVariant = Node & ObjectWithMetadata & { __typename?: 'ProductVariant' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] sku: Scalars['String'] product: Product trackInventory: Scalars['Boolean'] weight?: Maybe<Weight> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** List of price information in channels for the product. */ channelListings?: Maybe<Array<ProductVariantChannelListing>> /** Lists the storefront variant's pricing, the current price and discounts, only meant for displaying. */ pricing?: Maybe<VariantPricingInfo> /** List of attributes assigned to this variant. */ attributes: Array<SelectedAttribute> /** Cost price of the variant. */ costPrice?: Maybe<Money> /** Gross margin percentage value. */ margin?: Maybe<Scalars['Int']> /** Total quantity ordered. */ quantityOrdered?: Maybe<Scalars['Int']> /** Total revenue generated by a variant in given period of time. Note: this field should be queried using `reportProductSales` query as it uses optimizations suitable for such calculations. */ revenue?: Maybe<TaxedMoney> /** * List of images for the product variant. * @deprecated Will be removed in Saleor 4.0. Use the `media` instead. */ images?: Maybe<Array<Maybe<ProductImage>>> /** List of media for the product variant. */ media?: Maybe<Array<ProductMedia>> /** Returns translated product variant fields for the given language code. */ translation?: Maybe<ProductVariantTranslation> /** Digital content for the product variant. */ digitalContent?: Maybe<DigitalContent> /** Stocks for the product variant. */ stocks?: Maybe<Array<Maybe<Stock>>> /** Quantity of a product available for sale in one checkout. */ quantityAvailable: Scalars['Int'] } /** Represents a version of a product such as different size or color. */ export type ProductVariantPricingArgs = { address?: Maybe<AddressInput> } /** Represents a version of a product such as different size or color. */ export type ProductVariantAttributesArgs = { variantSelection?: Maybe<VariantAttributeScope> } /** Represents a version of a product such as different size or color. */ export type ProductVariantRevenueArgs = { period?: Maybe<ReportingPeriod> } /** Represents a version of a product such as different size or color. */ export type ProductVariantTranslationArgs = { languageCode: LanguageCodeEnum } /** Represents a version of a product such as different size or color. */ export type ProductVariantStocksArgs = { address?: Maybe<AddressInput> countryCode?: Maybe<CountryCode> } /** Represents a version of a product such as different size or color. */ export type ProductVariantQuantityAvailableArgs = { address?: Maybe<AddressInput> countryCode?: Maybe<CountryCode> } /** Creates product variants for a given product. */ export type ProductVariantBulkCreate = { __typename?: 'ProductVariantBulkCreate' /** Returns how many objects were created. */ count: Scalars['Int'] /** List of the created variants. */ productVariants: Array<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ bulkProductErrors: Array<BulkProductError> errors: Array<BulkProductError> } export type ProductVariantBulkCreateInput = { /** List of attributes specific to this variant. */ attributes: Array<Maybe<BulkAttributeValueInput>> /** Stock keeping unit. */ sku: Scalars['String'] /** Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. */ trackInventory?: Maybe<Scalars['Boolean']> /** Weight of the Product Variant. */ weight?: Maybe<Scalars['WeightScalar']> /** Stocks of a product available for sale. */ stocks?: Maybe<Array<StockInput>> /** List of prices assigned to channels. */ channelListings?: Maybe<Array<ProductVariantChannelListingAddInput>> } /** Deletes product variants. */ export type ProductVariantBulkDelete = { __typename?: 'ProductVariantBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Represents product varaint channel listing. */ export type ProductVariantChannelListing = Node & { __typename?: 'ProductVariantChannelListing' /** The ID of the object. */ id: Scalars['ID'] channel: Channel price?: Maybe<Money> /** Cost price of the variant. */ costPrice?: Maybe<Money> /** Gross margin percentage value. */ margin?: Maybe<Scalars['Int']> } export type ProductVariantChannelListingAddInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** Price of the particular variant in channel. */ price: Scalars['PositiveDecimal'] /** Cost price of the variant in channel. */ costPrice?: Maybe<Scalars['PositiveDecimal']> } /** Manage product variant prices in channels. */ export type ProductVariantChannelListingUpdate = { __typename?: 'ProductVariantChannelListingUpdate' /** An updated product variant instance. */ variant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productChannelListingErrors: Array<ProductChannelListingError> errors: Array<ProductChannelListingError> } export type ProductVariantCountableConnection = { __typename?: 'ProductVariantCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<ProductVariantCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type ProductVariantCountableEdge = { __typename?: 'ProductVariantCountableEdge' /** The item at the end of the edge. */ node: ProductVariant /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new variant for a product. */ export type ProductVariantCreate = { __typename?: 'ProductVariantCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productVariant?: Maybe<ProductVariant> } export type ProductVariantCreateInput = { /** List of attributes specific to this variant. */ attributes: Array<Maybe<AttributeValueInput>> /** Stock keeping unit. */ sku?: Maybe<Scalars['String']> /** Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. */ trackInventory?: Maybe<Scalars['Boolean']> /** Weight of the Product Variant. */ weight?: Maybe<Scalars['WeightScalar']> /** Product ID of which type is the variant. */ product: Scalars['ID'] /** Stocks of a product available for sale. */ stocks?: Maybe<Array<StockInput>> } /** Deletes a product variant. */ export type ProductVariantDelete = { __typename?: 'ProductVariantDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productVariant?: Maybe<ProductVariant> } export type ProductVariantFilterInput = { search?: Maybe<Scalars['String']> sku?: Maybe<Array<Maybe<Scalars['String']>>> metadata?: Maybe<Array<Maybe<MetadataInput>>> } export type ProductVariantInput = { /** List of attributes specific to this variant. */ attributes?: Maybe<Array<Maybe<AttributeValueInput>>> /** Stock keeping unit. */ sku?: Maybe<Scalars['String']> /** Determines if the inventory of this variant should be tracked. If false, the quantity won't change when customers buy this item. */ trackInventory?: Maybe<Scalars['Boolean']> /** Weight of the Product Variant. */ weight?: Maybe<Scalars['WeightScalar']> } /** Reorder the variants of a product. Mutation updates updated_at on product and triggers PRODUCT_UPDATED webhook. */ export type ProductVariantReorder = { __typename?: 'ProductVariantReorder' product?: Maybe<Product> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Reorder product variant attribute values. */ export type ProductVariantReorderAttributeValues = { __typename?: 'ProductVariantReorderAttributeValues' /** Product variant from which attribute values are reordered. */ productVariant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Set default variant for a product. Mutation triggers PRODUCT_UPDATED webhook. */ export type ProductVariantSetDefault = { __typename?: 'ProductVariantSetDefault' product?: Maybe<Product> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Creates stocks for product variant. */ export type ProductVariantStocksCreate = { __typename?: 'ProductVariantStocksCreate' /** Updated product variant. */ productVariant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ bulkStockErrors: Array<BulkStockError> errors: Array<BulkStockError> } /** Delete stocks from product variant. */ export type ProductVariantStocksDelete = { __typename?: 'ProductVariantStocksDelete' /** Updated product variant. */ productVariant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ stockErrors: Array<StockError> errors: Array<StockError> } /** Update stocks for product variant. */ export type ProductVariantStocksUpdate = { __typename?: 'ProductVariantStocksUpdate' /** Updated product variant. */ productVariant?: Maybe<ProductVariant> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ bulkStockErrors: Array<BulkStockError> errors: Array<BulkStockError> } export type ProductVariantTranslatableContent = Node & { __typename?: 'ProductVariantTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Returns translated product variant fields for the given language code. */ translation?: Maybe<ProductVariantTranslation> /** Represents a version of a product such as different size or color. */ productVariant?: Maybe<ProductVariant> } export type ProductVariantTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Product Variant. */ export type ProductVariantTranslate = { __typename?: 'ProductVariantTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> productVariant?: Maybe<ProductVariant> } export type ProductVariantTranslation = Node & { __typename?: 'ProductVariantTranslation' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Translation language. */ language: LanguageDisplay } /** Updates an existing variant for product. */ export type ProductVariantUpdate = { __typename?: 'ProductVariantUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> productVariant?: Maybe<ProductVariant> } export type PublishableChannelListingInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** Determines if object is visible to customers. */ isPublished?: Maybe<Scalars['Boolean']> /** Publication date. ISO 8601 standard. */ publicationDate?: Maybe<Scalars['Date']> } export type Query = { __typename?: 'Query' /** Look up a webhook by ID. */ webhook?: Maybe<Webhook> /** List of all available webhook events. */ webhookEvents?: Maybe<Array<Maybe<WebhookEvent>>> /** Retrieve a sample payload for a given webhook event based on real data. It can be useful for some integrations where sample payload is required. */ webhookSamplePayload?: Maybe<Scalars['JSONString']> /** Look up a warehouse by ID. */ warehouse?: Maybe<Warehouse> /** List of warehouses. */ warehouses?: Maybe<WarehouseCountableConnection> /** Returns a list of all translatable items of a given kind. */ translations?: Maybe<TranslatableItemConnection> translation?: Maybe<TranslatableItem> /** Look up a stock by ID */ stock?: Maybe<Stock> /** List of stocks. */ stocks?: Maybe<StockCountableConnection> /** Return information about the shop. */ shop: Shop /** Order related settings from site settings. */ orderSettings?: Maybe<OrderSettings> /** Look up a shipping zone by ID. */ shippingZone?: Maybe<ShippingZone> /** List of the shop's shipping zones. */ shippingZones?: Maybe<ShippingZoneCountableConnection> /** Look up digital content by ID. */ digitalContent?: Maybe<DigitalContent> /** List of digital content. */ digitalContents?: Maybe<DigitalContentCountableConnection> /** List of the shop's categories. */ categories?: Maybe<CategoryCountableConnection> /** Look up a category by ID or slug. */ category?: Maybe<Category> /** Look up a collection by ID. */ collection?: Maybe<Collection> /** List of the shop's collections. */ collections?: Maybe<CollectionCountableConnection> /** Look up a product by ID. */ product?: Maybe<Product> /** List of the shop's products. */ products?: Maybe<ProductCountableConnection> /** Look up a product type by ID. */ productType?: Maybe<ProductType> /** List of the shop's product types. */ productTypes?: Maybe<ProductTypeCountableConnection> /** Look up a product variant by ID or SKU. */ productVariant?: Maybe<ProductVariant> /** List of product variants. */ productVariants?: Maybe<ProductVariantCountableConnection> /** List of top selling products. */ reportProductSales?: Maybe<ProductVariantCountableConnection> /** Look up a payment by ID. */ payment?: Maybe<Payment> /** List of payments. */ payments?: Maybe<PaymentCountableConnection> /** Look up a page by ID or slug. */ page?: Maybe<Page> /** List of the shop's pages. */ pages?: Maybe<PageCountableConnection> /** Look up a page type by ID. */ pageType?: Maybe<PageType> /** List of the page types. */ pageTypes?: Maybe<PageTypeCountableConnection> /** List of activity events to display on homepage (at the moment it only contains order-events). */ homepageEvents?: Maybe<OrderEventCountableConnection> /** Look up an order by ID. */ order?: Maybe<Order> /** List of orders. */ orders?: Maybe<OrderCountableConnection> /** List of draft orders. */ draftOrders?: Maybe<OrderCountableConnection> /** Return the total sales amount from a specific period. */ ordersTotal?: Maybe<TaxedMoney> /** Look up an order by token. */ orderByToken?: Maybe<Order> /** Look up a navigation menu by ID or name. */ menu?: Maybe<Menu> /** List of the storefront's menus. */ menus?: Maybe<MenuCountableConnection> /** Look up a menu item by ID. */ menuItem?: Maybe<MenuItem> /** List of the storefronts's menu items. */ menuItems?: Maybe<MenuItemCountableConnection> /** Look up a gift card by ID. */ giftCard?: Maybe<GiftCard> /** List of gift cards. */ giftCards?: Maybe<GiftCardCountableConnection> /** Look up a plugin by ID. */ plugin?: Maybe<Plugin> /** List of plugins. */ plugins?: Maybe<PluginCountableConnection> /** Look up a sale by ID. */ sale?: Maybe<Sale> /** List of the shop's sales. */ sales?: Maybe<SaleCountableConnection> /** Look up a voucher by ID. */ voucher?: Maybe<Voucher> /** List of the shop's vouchers. */ vouchers?: Maybe<VoucherCountableConnection> /** Look up a export file by ID. */ exportFile?: Maybe<ExportFile> /** List of export files. */ exportFiles?: Maybe<ExportFileCountableConnection> /** List of all tax rates available from tax gateway. */ taxTypes?: Maybe<Array<Maybe<TaxType>>> /** Look up a checkout by token and slug of channel. */ checkout?: Maybe<Checkout> /** List of checkouts. */ checkouts?: Maybe<CheckoutCountableConnection> /** Look up a checkout line by ID. */ checkoutLine?: Maybe<CheckoutLine> /** List of checkout lines. */ checkoutLines?: Maybe<CheckoutLineCountableConnection> /** Look up a channel by ID. */ channel?: Maybe<Channel> /** List of all channels. */ channels?: Maybe<Array<Channel>> /** List of the shop's attributes. */ attributes?: Maybe<AttributeCountableConnection> /** Look up an attribute by ID. */ attribute?: Maybe<Attribute> /** List of all apps installations */ appsInstallations: Array<AppInstallation> /** List of the apps. */ apps?: Maybe<AppCountableConnection> /** Look up an app by ID. If ID is not provided, return the currently authenticated app. */ app?: Maybe<App> /** Returns address validation rules. */ addressValidationRules?: Maybe<AddressValidationData> /** Look up an address by ID. */ address?: Maybe<Address> /** List of the shop's customers. */ customers?: Maybe<UserCountableConnection> /** List of permission groups. */ permissionGroups?: Maybe<GroupCountableConnection> /** Look up permission group by ID. */ permissionGroup?: Maybe<Group> /** Return the currently authenticated user. */ me?: Maybe<User> /** List of the shop's staff users. */ staffUsers?: Maybe<UserCountableConnection> /** Look up a user by ID or email address. */ user?: Maybe<User> _entities?: Maybe<Array<Maybe<_Entity>>> _service?: Maybe<_Service> } export type QueryWebhookArgs = { id: Scalars['ID'] } export type QueryWebhookSamplePayloadArgs = { eventType: WebhookSampleEventTypeEnum } export type QueryWarehouseArgs = { id: Scalars['ID'] } export type QueryWarehousesArgs = { filter?: Maybe<WarehouseFilterInput> sortBy?: Maybe<WarehouseSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryTranslationsArgs = { kind: TranslatableKinds before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryTranslationArgs = { id: Scalars['ID'] kind: TranslatableKinds } export type QueryStockArgs = { id: Scalars['ID'] } export type QueryStocksArgs = { filter?: Maybe<StockFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryShippingZoneArgs = { id: Scalars['ID'] channel?: Maybe<Scalars['String']> } export type QueryShippingZonesArgs = { filter?: Maybe<ShippingZoneFilterInput> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryDigitalContentArgs = { id: Scalars['ID'] } export type QueryDigitalContentsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryCategoriesArgs = { filter?: Maybe<CategoryFilterInput> sortBy?: Maybe<CategorySortingInput> level?: Maybe<Scalars['Int']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryCategoryArgs = { id?: Maybe<Scalars['ID']> slug?: Maybe<Scalars['String']> } export type QueryCollectionArgs = { id?: Maybe<Scalars['ID']> slug?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> } export type QueryCollectionsArgs = { filter?: Maybe<CollectionFilterInput> sortBy?: Maybe<CollectionSortingInput> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryProductArgs = { id?: Maybe<Scalars['ID']> slug?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> } export type QueryProductsArgs = { filter?: Maybe<ProductFilterInput> sortBy?: Maybe<ProductOrder> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryProductTypeArgs = { id: Scalars['ID'] } export type QueryProductTypesArgs = { filter?: Maybe<ProductTypeFilterInput> sortBy?: Maybe<ProductTypeSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryProductVariantArgs = { id?: Maybe<Scalars['ID']> sku?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> } export type QueryProductVariantsArgs = { ids?: Maybe<Array<Maybe<Scalars['ID']>>> channel?: Maybe<Scalars['String']> filter?: Maybe<ProductVariantFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryReportProductSalesArgs = { period: ReportingPeriod channel: Scalars['String'] before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPaymentArgs = { id: Scalars['ID'] } export type QueryPaymentsArgs = { filter?: Maybe<PaymentFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPageArgs = { id?: Maybe<Scalars['ID']> slug?: Maybe<Scalars['String']> } export type QueryPagesArgs = { sortBy?: Maybe<PageSortingInput> filter?: Maybe<PageFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPageTypeArgs = { id: Scalars['ID'] } export type QueryPageTypesArgs = { sortBy?: Maybe<PageTypeSortingInput> filter?: Maybe<PageTypeFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryHomepageEventsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryOrderArgs = { id: Scalars['ID'] } export type QueryOrdersArgs = { sortBy?: Maybe<OrderSortingInput> filter?: Maybe<OrderFilterInput> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryDraftOrdersArgs = { sortBy?: Maybe<OrderSortingInput> filter?: Maybe<OrderDraftFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryOrdersTotalArgs = { period?: Maybe<ReportingPeriod> channel?: Maybe<Scalars['String']> } export type QueryOrderByTokenArgs = { token: Scalars['UUID'] } export type QueryMenuArgs = { channel?: Maybe<Scalars['String']> id?: Maybe<Scalars['ID']> name?: Maybe<Scalars['String']> slug?: Maybe<Scalars['String']> } export type QueryMenusArgs = { channel?: Maybe<Scalars['String']> sortBy?: Maybe<MenuSortingInput> filter?: Maybe<MenuFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryMenuItemArgs = { id: Scalars['ID'] channel?: Maybe<Scalars['String']> } export type QueryMenuItemsArgs = { channel?: Maybe<Scalars['String']> sortBy?: Maybe<MenuItemSortingInput> filter?: Maybe<MenuItemFilterInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryGiftCardArgs = { id: Scalars['ID'] } export type QueryGiftCardsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPluginArgs = { id: Scalars['ID'] } export type QueryPluginsArgs = { filter?: Maybe<PluginFilterInput> sortBy?: Maybe<PluginSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QuerySaleArgs = { id: Scalars['ID'] channel?: Maybe<Scalars['String']> } export type QuerySalesArgs = { filter?: Maybe<SaleFilterInput> sortBy?: Maybe<SaleSortingInput> query?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryVoucherArgs = { id: Scalars['ID'] channel?: Maybe<Scalars['String']> } export type QueryVouchersArgs = { filter?: Maybe<VoucherFilterInput> sortBy?: Maybe<VoucherSortingInput> query?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryExportFileArgs = { id: Scalars['ID'] } export type QueryExportFilesArgs = { filter?: Maybe<ExportFileFilterInput> sortBy?: Maybe<ExportFileSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryCheckoutArgs = { token?: Maybe<Scalars['UUID']> } export type QueryCheckoutsArgs = { channel?: Maybe<Scalars['String']> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryCheckoutLineArgs = { id?: Maybe<Scalars['ID']> } export type QueryCheckoutLinesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryChannelArgs = { id?: Maybe<Scalars['ID']> } export type QueryAttributesArgs = { filter?: Maybe<AttributeFilterInput> sortBy?: Maybe<AttributeSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryAttributeArgs = { id?: Maybe<Scalars['ID']> slug?: Maybe<Scalars['String']> } export type QueryAppsArgs = { filter?: Maybe<AppFilterInput> sortBy?: Maybe<AppSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryAppArgs = { id?: Maybe<Scalars['ID']> } export type QueryAddressValidationRulesArgs = { countryCode: CountryCode countryArea?: Maybe<Scalars['String']> city?: Maybe<Scalars['String']> cityArea?: Maybe<Scalars['String']> } export type QueryAddressArgs = { id: Scalars['ID'] } export type QueryCustomersArgs = { filter?: Maybe<CustomerFilterInput> sortBy?: Maybe<UserSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPermissionGroupsArgs = { filter?: Maybe<PermissionGroupFilterInput> sortBy?: Maybe<PermissionGroupSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryPermissionGroupArgs = { id: Scalars['ID'] } export type QueryStaffUsersArgs = { filter?: Maybe<StaffUserInput> sortBy?: Maybe<UserSortingInput> before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type QueryUserArgs = { id?: Maybe<Scalars['ID']> email?: Maybe<Scalars['String']> } export type Query_EntitiesArgs = { representations?: Maybe<Array<Maybe<Scalars['_Any']>>> } /** Represents a reduced VAT rate for a particular type of goods. */ export type ReducedRate = { __typename?: 'ReducedRate' /** Reduced VAT rate in percent. */ rate: Scalars['Float'] /** A type of goods. */ rateType: TaxRateType } /** Refresh JWT token. Mutation tries to take refreshToken from the input.If it fails it will try to take refreshToken from the http-only cookie -refreshToken. csrfToken is required when refreshToken is provided as a cookie. */ export type RefreshToken = { __typename?: 'RefreshToken' /** JWT token, required to authenticate. */ token?: Maybe<Scalars['String']> /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } export type ReorderInput = { /** The ID of the item to move. */ id: Scalars['ID'] /** The new relative sorting position of the item (from -inf to +inf). 1 moves the item one position forward, -1 moves the item one position backward, 0 leaves the item unchanged. */ sortOrder?: Maybe<Scalars['Int']> } export enum ReportingPeriod { Today = 'TODAY', ThisMonth = 'THIS_MONTH', } /** Request email change of the logged in user. */ export type RequestEmailChange = { __typename?: 'RequestEmailChange' /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Sends an email with the account password modification link. */ export type RequestPasswordReset = { __typename?: 'RequestPasswordReset' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ export type Sale = Node & { __typename?: 'Sale' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] type: SaleType startDate: Scalars['DateTime'] endDate?: Maybe<Scalars['DateTime']> /** List of categories this sale applies to. */ categories?: Maybe<CategoryCountableConnection> /** List of collections this sale applies to. */ collections?: Maybe<CollectionCountableConnection> /** List of products this sale applies to. */ products?: Maybe<ProductCountableConnection> /** Returns translated sale fields for the given language code. */ translation?: Maybe<SaleTranslation> /** List of channels available for the sale. */ channelListings?: Maybe<Array<SaleChannelListing>> /** Sale value. */ discountValue?: Maybe<Scalars['Float']> /** Currency code for sale. */ currency?: Maybe<Scalars['String']> } /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ export type SaleCategoriesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ export type SaleCollectionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ export type SaleProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ export type SaleTranslationArgs = { languageCode: LanguageCodeEnum } /** Adds products, categories, collections to a voucher. */ export type SaleAddCatalogues = { __typename?: 'SaleAddCatalogues' /** Sale of which catalogue IDs will be modified. */ sale?: Maybe<Sale> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } /** Deletes sales. */ export type SaleBulkDelete = { __typename?: 'SaleBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } /** Represents sale channel listing. */ export type SaleChannelListing = Node & { __typename?: 'SaleChannelListing' /** The ID of the object. */ id: Scalars['ID'] channel: Channel discountValue: Scalars['Float'] currency: Scalars['String'] } export type SaleChannelListingAddInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** The value of the discount. */ discountValue: Scalars['PositiveDecimal'] } export type SaleChannelListingInput = { /** List of channels to which the sale should be assigned. */ addChannels?: Maybe<Array<SaleChannelListingAddInput>> /** List of channels from which the sale should be unassigned. */ removeChannels?: Maybe<Array<Scalars['ID']>> } /** Manage sale's availability in channels. */ export type SaleChannelListingUpdate = { __typename?: 'SaleChannelListingUpdate' /** An updated sale instance. */ sale?: Maybe<Sale> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } export type SaleCountableConnection = { __typename?: 'SaleCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<SaleCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type SaleCountableEdge = { __typename?: 'SaleCountableEdge' /** The item at the end of the edge. */ node: Sale /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new sale. */ export type SaleCreate = { __typename?: 'SaleCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> sale?: Maybe<Sale> } /** Deletes a sale. */ export type SaleDelete = { __typename?: 'SaleDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> sale?: Maybe<Sale> } export type SaleFilterInput = { status?: Maybe<Array<Maybe<DiscountStatusEnum>>> saleType?: Maybe<DiscountValueTypeEnum> started?: Maybe<DateTimeRangeInput> search?: Maybe<Scalars['String']> } export type SaleInput = { /** Voucher name. */ name?: Maybe<Scalars['String']> /** Fixed or percentage. */ type?: Maybe<DiscountValueTypeEnum> /** Value of the voucher. */ value?: Maybe<Scalars['PositiveDecimal']> /** Products related to the discount. */ products?: Maybe<Array<Maybe<Scalars['ID']>>> /** Categories related to the discount. */ categories?: Maybe<Array<Maybe<Scalars['ID']>>> /** Collections related to the discount. */ collections?: Maybe<Array<Maybe<Scalars['ID']>>> /** Start date of the voucher in ISO 8601 format. */ startDate?: Maybe<Scalars['DateTime']> /** End date of the voucher in ISO 8601 format. */ endDate?: Maybe<Scalars['DateTime']> } /** Removes products, categories, collections from a sale. */ export type SaleRemoveCatalogues = { __typename?: 'SaleRemoveCatalogues' /** Sale of which catalogue IDs will be modified. */ sale?: Maybe<Sale> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } export enum SaleSortField { /** Sort sales by name. */ Name = 'NAME', /** Sort sales by start date. */ StartDate = 'START_DATE', /** Sort sales by end date. */ EndDate = 'END_DATE', /** Sort sales by value. */ Value = 'VALUE', /** Sort sales by type. */ Type = 'TYPE', } export type SaleSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Specifies the channel in which to sort the data. */ channel?: Maybe<Scalars['String']> /** Sort sales by the selected field. */ field: SaleSortField } export type SaleTranslatableContent = Node & { __typename?: 'SaleTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] /** Returns translated sale fields for the given language code. */ translation?: Maybe<SaleTranslation> /** Sales allow creating discounts for categories, collections or products and are visible to all the customers. */ sale?: Maybe<Sale> } export type SaleTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/updates translations for a sale. */ export type SaleTranslate = { __typename?: 'SaleTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> sale?: Maybe<Sale> } export type SaleTranslation = Node & { __typename?: 'SaleTranslation' /** The ID of the object. */ id: Scalars['ID'] name?: Maybe<Scalars['String']> /** Translation language. */ language: LanguageDisplay } /** An enumeration. */ export enum SaleType { /** fixed */ Fixed = 'FIXED', /** % */ Percentage = 'PERCENTAGE', } /** Updates a sale. */ export type SaleUpdate = { __typename?: 'SaleUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> sale?: Maybe<Sale> } /** Represents a custom attribute. */ export type SelectedAttribute = { __typename?: 'SelectedAttribute' /** Name of an attribute displayed in the interface. */ attribute: Attribute /** Values of an attribute. */ values: Array<Maybe<AttributeValue>> } export type SeoInput = { /** SEO title. */ title?: Maybe<Scalars['String']> /** SEO description. */ description?: Maybe<Scalars['String']> } /** Sets the user's password from the token sent by email using the RequestPasswordReset mutation. */ export type SetPassword = { __typename?: 'SetPassword' /** JWT token, required to authenticate. */ token?: Maybe<Scalars['String']> /** JWT refresh token, required to re-generate access token. */ refreshToken?: Maybe<Scalars['String']> /** CSRF token required to re-generate access token. */ csrfToken?: Maybe<Scalars['String']> /** A user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } export type ShippingError = { __typename?: 'ShippingError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ShippingErrorCode /** List of warehouse IDs which causes the error. */ warehouses?: Maybe<Array<Scalars['ID']>> /** List of channels IDs which causes the error. */ channels?: Maybe<Array<Scalars['ID']>> } /** An enumeration. */ export enum ShippingErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', MaxLessThanMin = 'MAX_LESS_THAN_MIN', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', DuplicatedInputItem = 'DUPLICATED_INPUT_ITEM', } /** Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers. */ export type ShippingMethod = Node & ObjectWithMetadata & { __typename?: 'ShippingMethod' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] description?: Maybe<Scalars['JSONString']> minimumOrderWeight?: Maybe<Weight> maximumOrderWeight?: Maybe<Weight> maximumDeliveryDays?: Maybe<Scalars['Int']> minimumDeliveryDays?: Maybe<Scalars['Int']> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Type of the shipping method. */ type?: Maybe<ShippingMethodTypeEnum> /** Returns translated shipping method fields for the given language code. */ translation?: Maybe<ShippingMethodTranslation> /** List of channels available for the method. */ channelListings?: Maybe<Array<ShippingMethodChannelListing>> /** The price of the cheapest variant (including discounts). */ price?: Maybe<Money> /** The price of the cheapest variant (including discounts). */ maximumOrderPrice?: Maybe<Money> /** The price of the cheapest variant (including discounts). */ minimumOrderPrice?: Maybe<Money> /** Postal code ranges rule of exclusion or inclusion of the shipping method. */ postalCodeRules?: Maybe<Array<Maybe<ShippingMethodPostalCodeRule>>> /** List of excluded products for the shipping method. */ excludedProducts?: Maybe<ProductCountableConnection> } /** Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers. */ export type ShippingMethodTranslationArgs = { languageCode: LanguageCodeEnum } /** Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers. */ export type ShippingMethodExcludedProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents shipping method channel listing. */ export type ShippingMethodChannelListing = Node & { __typename?: 'ShippingMethodChannelListing' /** The ID of the object. */ id: Scalars['ID'] channel: Channel minimumOrderPrice?: Maybe<Money> maximumOrderPrice?: Maybe<Money> price?: Maybe<Money> } export type ShippingMethodChannelListingAddInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** Shipping price of the shipping method in this channel. */ price?: Maybe<Scalars['PositiveDecimal']> /** Minimum order price to use this shipping method. */ minimumOrderPrice?: Maybe<Scalars['PositiveDecimal']> /** Maximum order price to use this shipping method. */ maximumOrderPrice?: Maybe<Scalars['PositiveDecimal']> } export type ShippingMethodChannelListingInput = { /** List of channels to which the shipping method should be assigned. */ addChannels?: Maybe<Array<ShippingMethodChannelListingAddInput>> /** List of channels from which the shipping method should be unassigned. */ removeChannels?: Maybe<Array<Scalars['ID']>> } /** Manage shipping method's availability in channels. */ export type ShippingMethodChannelListingUpdate = { __typename?: 'ShippingMethodChannelListingUpdate' /** An updated shipping method instance. */ shippingMethod?: Maybe<ShippingMethod> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Represents shipping method postal code rule. */ export type ShippingMethodPostalCodeRule = Node & { __typename?: 'ShippingMethodPostalCodeRule' /** Start address range. */ start?: Maybe<Scalars['String']> /** End address range. */ end?: Maybe<Scalars['String']> /** Inclusion type of the postal code rule. */ inclusionType?: Maybe<PostalCodeRuleInclusionTypeEnum> /** The ID of the object. */ id: Scalars['ID'] } export type ShippingMethodTranslatableContent = Node & { __typename?: 'ShippingMethodTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] description?: Maybe<Scalars['JSONString']> /** Returns translated shipping method fields for the given language code. */ translation?: Maybe<ShippingMethodTranslation> /** Shipping method are the methods you'll use to get customer's orders to them. They are directly exposed to the customers. */ shippingMethod?: Maybe<ShippingMethod> } export type ShippingMethodTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } export type ShippingMethodTranslation = Node & { __typename?: 'ShippingMethodTranslation' /** The ID of the object. */ id: Scalars['ID'] name?: Maybe<Scalars['String']> description?: Maybe<Scalars['JSONString']> /** Translation language. */ language: LanguageDisplay } /** An enumeration. */ export enum ShippingMethodTypeEnum { Price = 'PRICE', Weight = 'WEIGHT', } export type ShippingPostalCodeRulesCreateInputRange = { /** Start range of the postal code. */ start: Scalars['String'] /** End range of the postal code. */ end?: Maybe<Scalars['String']> } /** Deletes shipping prices. */ export type ShippingPriceBulkDelete = { __typename?: 'ShippingPriceBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Creates a new shipping price. */ export type ShippingPriceCreate = { __typename?: 'ShippingPriceCreate' /** A shipping zone to which the shipping method belongs. */ shippingZone?: Maybe<ShippingZone> shippingMethod?: Maybe<ShippingMethod> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Deletes a shipping price. */ export type ShippingPriceDelete = { __typename?: 'ShippingPriceDelete' /** A shipping method to delete. */ shippingMethod?: Maybe<ShippingMethod> /** A shipping zone to which the shipping method belongs. */ shippingZone?: Maybe<ShippingZone> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Exclude products from shipping price. */ export type ShippingPriceExcludeProducts = { __typename?: 'ShippingPriceExcludeProducts' /** A shipping method with new list of excluded products. */ shippingMethod?: Maybe<ShippingMethod> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } export type ShippingPriceExcludeProductsInput = { /** List of products which will be excluded. */ products: Array<Maybe<Scalars['ID']>> } export type ShippingPriceInput = { /** Name of the shipping method. */ name?: Maybe<Scalars['String']> /** Shipping method description (JSON). */ description?: Maybe<Scalars['JSONString']> /** Minimum order weight to use this shipping method. */ minimumOrderWeight?: Maybe<Scalars['WeightScalar']> /** Maximum order weight to use this shipping method. */ maximumOrderWeight?: Maybe<Scalars['WeightScalar']> /** Maximum number of days for delivery. */ maximumDeliveryDays?: Maybe<Scalars['Int']> /** Minimal number of days for delivery. */ minimumDeliveryDays?: Maybe<Scalars['Int']> /** Shipping type: price or weight based. */ type?: Maybe<ShippingMethodTypeEnum> /** Shipping zone this method belongs to. */ shippingZone?: Maybe<Scalars['ID']> /** Postal code rules to add. */ addPostalCodeRules?: Maybe<Array<ShippingPostalCodeRulesCreateInputRange>> /** Postal code rules to delete. */ deletePostalCodeRules?: Maybe<Array<Scalars['ID']>> /** Inclusion type for currently assigned postal code rules. */ inclusionType?: Maybe<PostalCodeRuleInclusionTypeEnum> } /** Remove product from excluded list for shipping price. */ export type ShippingPriceRemoveProductFromExclude = { __typename?: 'ShippingPriceRemoveProductFromExclude' /** A shipping method with new list of excluded products. */ shippingMethod?: Maybe<ShippingMethod> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Creates/Updates translations for shipping method. */ export type ShippingPriceTranslate = { __typename?: 'ShippingPriceTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> shippingMethod?: Maybe<ShippingMethod> } export type ShippingPriceTranslationInput = { name?: Maybe<Scalars['String']> /** Translated shipping method description (JSON). */ description?: Maybe<Scalars['JSONString']> } /** Updates a new shipping price. */ export type ShippingPriceUpdate = { __typename?: 'ShippingPriceUpdate' /** A shipping zone to which the shipping method belongs. */ shippingZone?: Maybe<ShippingZone> shippingMethod?: Maybe<ShippingMethod> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } /** Represents a shipping zone in the shop. Zones are the concept used only for grouping shipping methods in the dashboard, and are never exposed to the customers directly. */ export type ShippingZone = Node & ObjectWithMetadata & { __typename?: 'ShippingZone' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] default: Scalars['Boolean'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** Lowest and highest prices for the shipping. */ priceRange?: Maybe<MoneyRange> /** List of countries available for the method. */ countries?: Maybe<Array<Maybe<CountryDisplay>>> /** List of shipping methods available for orders shipped to countries within this shipping zone. */ shippingMethods?: Maybe<Array<Maybe<ShippingMethod>>> /** List of warehouses for shipping zone. */ warehouses: Array<Warehouse> /** List of channels for shipping zone. */ channels: Array<Channel> /** Description of a shipping zone. */ description?: Maybe<Scalars['String']> } /** Deletes shipping zones. */ export type ShippingZoneBulkDelete = { __typename?: 'ShippingZoneBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> } export type ShippingZoneCountableConnection = { __typename?: 'ShippingZoneCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<ShippingZoneCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type ShippingZoneCountableEdge = { __typename?: 'ShippingZoneCountableEdge' /** The item at the end of the edge. */ node: ShippingZone /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new shipping zone. */ export type ShippingZoneCreate = { __typename?: 'ShippingZoneCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> shippingZone?: Maybe<ShippingZone> } export type ShippingZoneCreateInput = { /** Shipping zone's name. Visible only to the staff. */ name?: Maybe<Scalars['String']> /** Description of the shipping zone. */ description?: Maybe<Scalars['String']> /** List of countries in this shipping zone. */ countries?: Maybe<Array<Maybe<Scalars['String']>>> /** Default shipping zone will be used for countries not covered by other zones. */ default?: Maybe<Scalars['Boolean']> /** List of warehouses to assign to a shipping zone */ addWarehouses?: Maybe<Array<Maybe<Scalars['ID']>>> /** List of channels to assign to the shipping zone. */ addChannels?: Maybe<Array<Scalars['ID']>> } /** Deletes a shipping zone. */ export type ShippingZoneDelete = { __typename?: 'ShippingZoneDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> shippingZone?: Maybe<ShippingZone> } export type ShippingZoneFilterInput = { search?: Maybe<Scalars['String']> channels?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Updates a new shipping zone. */ export type ShippingZoneUpdate = { __typename?: 'ShippingZoneUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shippingErrors: Array<ShippingError> errors: Array<ShippingError> shippingZone?: Maybe<ShippingZone> } export type ShippingZoneUpdateInput = { /** Shipping zone's name. Visible only to the staff. */ name?: Maybe<Scalars['String']> /** Description of the shipping zone. */ description?: Maybe<Scalars['String']> /** List of countries in this shipping zone. */ countries?: Maybe<Array<Maybe<Scalars['String']>>> /** Default shipping zone will be used for countries not covered by other zones. */ default?: Maybe<Scalars['Boolean']> /** List of warehouses to assign to a shipping zone */ addWarehouses?: Maybe<Array<Maybe<Scalars['ID']>>> /** List of channels to assign to the shipping zone. */ addChannels?: Maybe<Array<Scalars['ID']>> /** List of warehouses to unassign from a shipping zone */ removeWarehouses?: Maybe<Array<Maybe<Scalars['ID']>>> /** List of channels to unassign from the shipping zone. */ removeChannels?: Maybe<Array<Scalars['ID']>> } /** Represents a shop resource containing general shop data and configuration. */ export type Shop = { __typename?: 'Shop' /** List of available payment gateways. */ availablePaymentGateways: Array<PaymentGateway> /** List of available external authentications. */ availableExternalAuthentications: Array<ExternalAuthentication> /** Shipping methods that are available for the shop. */ availableShippingMethods?: Maybe<Array<Maybe<ShippingMethod>>> /** List of countries available in the shop. */ countries: Array<CountryDisplay> /** Shop's default country. */ defaultCountry?: Maybe<CountryDisplay> /** Default shop's email sender's name. */ defaultMailSenderName?: Maybe<Scalars['String']> /** Default shop's email sender's address. */ defaultMailSenderAddress?: Maybe<Scalars['String']> /** Shop's description. */ description?: Maybe<Scalars['String']> /** Shop's domain data. */ domain: Domain /** List of the shops's supported languages. */ languages: Array<Maybe<LanguageDisplay>> /** Shop's name. */ name: Scalars['String'] /** List of available permissions. */ permissions: Array<Maybe<Permission>> /** List of possible phone prefixes. */ phonePrefixes: Array<Maybe<Scalars['String']>> /** Header text. */ headerText?: Maybe<Scalars['String']> /** Include taxes in prices. */ includeTaxesInPrices: Scalars['Boolean'] /** Display prices with tax in store. */ displayGrossPrices: Scalars['Boolean'] /** Charge taxes on shipping. */ chargeTaxesOnShipping: Scalars['Boolean'] /** Enable inventory tracking. */ trackInventoryByDefault?: Maybe<Scalars['Boolean']> /** Default weight unit. */ defaultWeightUnit?: Maybe<WeightUnitsEnum> /** Returns translated shop fields for the given language code. */ translation?: Maybe<ShopTranslation> /** Enable automatic fulfillment for all digital products. */ automaticFulfillmentDigitalProducts?: Maybe<Scalars['Boolean']> /** Default number of max downloads per digital content URL. */ defaultDigitalMaxDownloads?: Maybe<Scalars['Int']> /** Default number of days which digital content URL will be valid. */ defaultDigitalUrlValidDays?: Maybe<Scalars['Int']> /** Company address. */ companyAddress?: Maybe<Address> /** URL of a view where customers can set their password. */ customerSetPasswordUrl?: Maybe<Scalars['String']> /** List of staff notification recipients. */ staffNotificationRecipients?: Maybe<Array<Maybe<StaffNotificationRecipient>>> /** Resource limitations and current usage if any set for a shop */ limits: LimitInfo /** Saleor API version. */ version: Scalars['String'] } /** Represents a shop resource containing general shop data and configuration. */ export type ShopAvailablePaymentGatewaysArgs = { currency?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> } /** Represents a shop resource containing general shop data and configuration. */ export type ShopAvailableShippingMethodsArgs = { channel: Scalars['String'] address?: Maybe<AddressInput> } /** Represents a shop resource containing general shop data and configuration. */ export type ShopCountriesArgs = { languageCode?: Maybe<LanguageCodeEnum> } /** Represents a shop resource containing general shop data and configuration. */ export type ShopTranslationArgs = { languageCode: LanguageCodeEnum } /** Update the shop's address. If the `null` value is passed, the currently selected address will be deleted. */ export type ShopAddressUpdate = { __typename?: 'ShopAddressUpdate' /** Updated shop. */ shop?: Maybe<Shop> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> } /** Updates site domain of the shop. */ export type ShopDomainUpdate = { __typename?: 'ShopDomainUpdate' /** Updated shop. */ shop?: Maybe<Shop> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> } export type ShopError = { __typename?: 'ShopError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: ShopErrorCode } /** An enumeration. */ export enum ShopErrorCode { AlreadyExists = 'ALREADY_EXISTS', CannotFetchTaxRates = 'CANNOT_FETCH_TAX_RATES', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } /** Fetch tax rates. */ export type ShopFetchTaxRates = { __typename?: 'ShopFetchTaxRates' /** Updated shop. */ shop?: Maybe<Shop> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> } export type ShopSettingsInput = { /** Header text. */ headerText?: Maybe<Scalars['String']> /** SEO description. */ description?: Maybe<Scalars['String']> /** Include taxes in prices. */ includeTaxesInPrices?: Maybe<Scalars['Boolean']> /** Display prices with tax in store. */ displayGrossPrices?: Maybe<Scalars['Boolean']> /** Charge taxes on shipping. */ chargeTaxesOnShipping?: Maybe<Scalars['Boolean']> /** Enable inventory tracking. */ trackInventoryByDefault?: Maybe<Scalars['Boolean']> /** Default weight unit. */ defaultWeightUnit?: Maybe<WeightUnitsEnum> /** Enable automatic fulfillment for all digital products. */ automaticFulfillmentDigitalProducts?: Maybe<Scalars['Boolean']> /** Default number of max downloads per digital content URL. */ defaultDigitalMaxDownloads?: Maybe<Scalars['Int']> /** Default number of days which digital content URL will be valid. */ defaultDigitalUrlValidDays?: Maybe<Scalars['Int']> /** Default email sender's name. */ defaultMailSenderName?: Maybe<Scalars['String']> /** Default email sender's address. */ defaultMailSenderAddress?: Maybe<Scalars['String']> /** URL of a view where customers can set their password. */ customerSetPasswordUrl?: Maybe<Scalars['String']> } /** Creates/Updates translations for Shop Settings. */ export type ShopSettingsTranslate = { __typename?: 'ShopSettingsTranslate' /** Updated shop. */ shop?: Maybe<Shop> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> } export type ShopSettingsTranslationInput = { headerText?: Maybe<Scalars['String']> description?: Maybe<Scalars['String']> } /** Updates shop settings. */ export type ShopSettingsUpdate = { __typename?: 'ShopSettingsUpdate' /** Updated shop. */ shop?: Maybe<Shop> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> } export type ShopTranslation = Node & { __typename?: 'ShopTranslation' /** The ID of the object. */ id: Scalars['ID'] headerText: Scalars['String'] description: Scalars['String'] /** Translation language. */ language: LanguageDisplay } export type SiteDomainInput = { /** Domain name for shop. */ domain?: Maybe<Scalars['String']> /** Shop site name. */ name?: Maybe<Scalars['String']> } /** Deletes staff users. */ export type StaffBulkDelete = { __typename?: 'StaffBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ staffErrors: Array<StaffError> errors: Array<StaffError> } /** Creates a new staff user. */ export type StaffCreate = { __typename?: 'StaffCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ staffErrors: Array<StaffError> errors: Array<StaffError> user?: Maybe<User> } export type StaffCreateInput = { /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** The unique email address of the user. */ email?: Maybe<Scalars['String']> /** User account is active. */ isActive?: Maybe<Scalars['Boolean']> /** A note about the user. */ note?: Maybe<Scalars['String']> /** List of permission group IDs to which user should be assigned. */ addGroups?: Maybe<Array<Scalars['ID']>> /** URL of a view where users should be redirected to set the password. URL in RFC 1808 format. */ redirectUrl?: Maybe<Scalars['String']> } /** Deletes a staff user. */ export type StaffDelete = { __typename?: 'StaffDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ staffErrors: Array<StaffError> errors: Array<StaffError> user?: Maybe<User> } export type StaffError = { __typename?: 'StaffError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: AccountErrorCode /** A type of address that causes the error. */ addressType?: Maybe<AddressTypeEnum> /** List of permissions which causes the error. */ permissions?: Maybe<Array<PermissionEnum>> /** List of permission group IDs which cause the error. */ groups?: Maybe<Array<Scalars['ID']>> /** List of user IDs which causes the error. */ users?: Maybe<Array<Scalars['ID']>> } export enum StaffMemberStatus { /** User account has been activated. */ Active = 'ACTIVE', /** User account has not been activated yet. */ Deactivated = 'DEACTIVATED', } /** Represents a recipient of email notifications send by Saleor, such as notifications about new orders. Notifications can be assigned to staff users or arbitrary email addresses. */ export type StaffNotificationRecipient = Node & { __typename?: 'StaffNotificationRecipient' /** Returns a user subscribed to email notifications. */ user?: Maybe<User> /** Determines if a notification active. */ active?: Maybe<Scalars['Boolean']> /** The ID of the object. */ id: Scalars['ID'] /** Returns email address of a user subscribed to email notifications. */ email?: Maybe<Scalars['String']> } /** Creates a new staff notification recipient. */ export type StaffNotificationRecipientCreate = { __typename?: 'StaffNotificationRecipientCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> staffNotificationRecipient?: Maybe<StaffNotificationRecipient> } /** Delete staff notification recipient. */ export type StaffNotificationRecipientDelete = { __typename?: 'StaffNotificationRecipientDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> staffNotificationRecipient?: Maybe<StaffNotificationRecipient> } export type StaffNotificationRecipientInput = { /** The ID of the user subscribed to email notifications.. */ user?: Maybe<Scalars['ID']> /** Email address of a user subscribed to email notifications. */ email?: Maybe<Scalars['String']> /** Determines if a notification active. */ active?: Maybe<Scalars['Boolean']> } /** Updates a staff notification recipient. */ export type StaffNotificationRecipientUpdate = { __typename?: 'StaffNotificationRecipientUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ shopErrors: Array<ShopError> errors: Array<ShopError> staffNotificationRecipient?: Maybe<StaffNotificationRecipient> } /** Updates an existing staff user. */ export type StaffUpdate = { __typename?: 'StaffUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ staffErrors: Array<StaffError> errors: Array<StaffError> user?: Maybe<User> } export type StaffUpdateInput = { /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** The unique email address of the user. */ email?: Maybe<Scalars['String']> /** User account is active. */ isActive?: Maybe<Scalars['Boolean']> /** A note about the user. */ note?: Maybe<Scalars['String']> /** List of permission group IDs to which user should be assigned. */ addGroups?: Maybe<Array<Scalars['ID']>> /** List of permission group IDs from which user should be unassigned. */ removeGroups?: Maybe<Array<Scalars['ID']>> } export type StaffUserInput = { status?: Maybe<StaffMemberStatus> search?: Maybe<Scalars['String']> } /** Represents stock. */ export type Stock = Node & { __typename?: 'Stock' warehouse: Warehouse productVariant: ProductVariant /** Quantity of a product in the warehouse's possession, including the allocated stock that is waiting for shipment. */ quantity: Scalars['Int'] /** The ID of the object. */ id: Scalars['ID'] /** Quantity allocated for orders */ quantityAllocated: Scalars['Int'] } export enum StockAvailability { InStock = 'IN_STOCK', OutOfStock = 'OUT_OF_STOCK', } export type StockCountableConnection = { __typename?: 'StockCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<StockCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type StockCountableEdge = { __typename?: 'StockCountableEdge' /** The item at the end of the edge. */ node: Stock /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type StockError = { __typename?: 'StockError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: StockErrorCode } /** An enumeration. */ export enum StockErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } export type StockFilterInput = { quantity?: Maybe<Scalars['Float']> search?: Maybe<Scalars['String']> } export type StockInput = { /** Warehouse in which stock is located. */ warehouse: Scalars['ID'] /** Quantity of items available for sell. */ quantity: Scalars['Int'] } /** An enumeration. */ export enum TaxRateType { Accommodation = 'ACCOMMODATION', AdmissionToCulturalEvents = 'ADMISSION_TO_CULTURAL_EVENTS', AdmissionToEntertainmentEvents = 'ADMISSION_TO_ENTERTAINMENT_EVENTS', AdmissionToSportingEvents = 'ADMISSION_TO_SPORTING_EVENTS', Advertising = 'ADVERTISING', AgriculturalSupplies = 'AGRICULTURAL_SUPPLIES', BabyFoodstuffs = 'BABY_FOODSTUFFS', Bikes = 'BIKES', Books = 'BOOKS', ChildrensClothing = 'CHILDRENS_CLOTHING', DomesticFuel = 'DOMESTIC_FUEL', DomesticServices = 'DOMESTIC_SERVICES', EBooks = 'E_BOOKS', Foodstuffs = 'FOODSTUFFS', Hotels = 'HOTELS', Medical = 'MEDICAL', Newspapers = 'NEWSPAPERS', PassengerTransport = 'PASSENGER_TRANSPORT', Pharmaceuticals = 'PHARMACEUTICALS', PropertyRenovations = 'PROPERTY_RENOVATIONS', Restaurants = 'RESTAURANTS', SocialHousing = 'SOCIAL_HOUSING', Standard = 'STANDARD', Water = 'WATER', Wine = 'WINE', } /** Representation of tax types fetched from tax gateway. */ export type TaxType = { __typename?: 'TaxType' /** Description of the tax type. */ description?: Maybe<Scalars['String']> /** External tax code used to identify given tax group. */ taxCode?: Maybe<Scalars['String']> } /** Represents a monetary value with taxes. In cases where taxes were not applied, net and gross values will be equal. */ export type TaxedMoney = { __typename?: 'TaxedMoney' /** Currency code. */ currency: Scalars['String'] /** Amount of money including taxes. */ gross: Money /** Amount of money without taxes. */ net: Money /** Amount of taxes. */ tax: Money } /** Represents a range of monetary values. */ export type TaxedMoneyRange = { __typename?: 'TaxedMoneyRange' /** Lower bound of a price range. */ start?: Maybe<TaxedMoney> /** Upper bound of a price range. */ stop?: Maybe<TaxedMoney> } /** An object representing a single payment. */ export type Transaction = Node & { __typename?: 'Transaction' /** The ID of the object. */ id: Scalars['ID'] created: Scalars['DateTime'] payment: Payment token: Scalars['String'] kind: TransactionKind isSuccess: Scalars['Boolean'] error?: Maybe<Scalars['String']> gatewayResponse: Scalars['JSONString'] /** Total amount of the transaction. */ amount?: Maybe<Money> } /** An enumeration. */ export enum TransactionKind { /** External reference */ External = 'EXTERNAL', /** Authorization */ Auth = 'AUTH', /** Pending */ Pending = 'PENDING', /** Action to confirm */ ActionToConfirm = 'ACTION_TO_CONFIRM', /** Refund */ Refund = 'REFUND', /** Refund in progress */ RefundOngoing = 'REFUND_ONGOING', /** Capture */ Capture = 'CAPTURE', /** Void */ Void = 'VOID', /** Confirm */ Confirm = 'CONFIRM', /** Cancel */ Cancel = 'CANCEL', } export type TranslatableItem = | ProductTranslatableContent | CollectionTranslatableContent | CategoryTranslatableContent | AttributeTranslatableContent | AttributeValueTranslatableContent | ProductVariantTranslatableContent | PageTranslatableContent | ShippingMethodTranslatableContent | SaleTranslatableContent | VoucherTranslatableContent | MenuItemTranslatableContent export type TranslatableItemConnection = { __typename?: 'TranslatableItemConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<TranslatableItemEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type TranslatableItemEdge = { __typename?: 'TranslatableItemEdge' /** The item at the end of the edge. */ node: TranslatableItem /** A cursor for use in pagination. */ cursor: Scalars['String'] } export enum TranslatableKinds { Attribute = 'ATTRIBUTE', AttributeValue = 'ATTRIBUTE_VALUE', Category = 'CATEGORY', Collection = 'COLLECTION', MenuItem = 'MENU_ITEM', Page = 'PAGE', Product = 'PRODUCT', Sale = 'SALE', ShippingMethod = 'SHIPPING_METHOD', Variant = 'VARIANT', Voucher = 'VOUCHER', } export type TranslationError = { __typename?: 'TranslationError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: TranslationErrorCode } /** An enumeration. */ export enum TranslationErrorCode { GraphqlError = 'GRAPHQL_ERROR', NotFound = 'NOT_FOUND', Required = 'REQUIRED', } export type TranslationInput = { seoTitle?: Maybe<Scalars['String']> seoDescription?: Maybe<Scalars['String']> name?: Maybe<Scalars['String']> description?: Maybe<Scalars['JSONString']> } export type UpdateInvoiceInput = { /** Invoice number */ number?: Maybe<Scalars['String']> /** URL of an invoice to download. */ url?: Maybe<Scalars['String']> } /** Updates metadata of an object. */ export type UpdateMetadata = { __typename?: 'UpdateMetadata' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ metadataErrors: Array<MetadataError> errors: Array<MetadataError> item?: Maybe<ObjectWithMetadata> } /** Updates private metadata of an object. */ export type UpdatePrivateMetadata = { __typename?: 'UpdatePrivateMetadata' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ metadataErrors: Array<MetadataError> errors: Array<MetadataError> item?: Maybe<ObjectWithMetadata> } export type UploadError = { __typename?: 'UploadError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: UploadErrorCode } /** An enumeration. */ export enum UploadErrorCode { GraphqlError = 'GRAPHQL_ERROR', } /** Represents user data. */ export type User = Node & ObjectWithMetadata & { __typename?: 'User' /** The ID of the object. */ id: Scalars['ID'] lastLogin?: Maybe<Scalars['DateTime']> email: Scalars['String'] firstName: Scalars['String'] lastName: Scalars['String'] isStaff: Scalars['Boolean'] isActive: Scalars['Boolean'] /** A note about the customer. */ note?: Maybe<Scalars['String']> dateJoined: Scalars['DateTime'] defaultShippingAddress?: Maybe<Address> defaultBillingAddress?: Maybe<Address> /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> /** List of all user's addresses. */ addresses?: Maybe<Array<Maybe<Address>>> /** * Returns the last open checkout of this user. * @deprecated Will be removed in Saleor 4.0. Use the `checkout_tokens` field to fetch the user checkouts. */ checkout?: Maybe<Checkout> /** Returns the checkout UUID's assigned to this user. */ checkoutTokens?: Maybe<Array<Scalars['UUID']>> /** List of the user gift cards. */ giftCards?: Maybe<GiftCardCountableConnection> /** List of user's orders. */ orders?: Maybe<OrderCountableConnection> /** List of user's permissions. */ userPermissions?: Maybe<Array<Maybe<UserPermission>>> /** List of user's permission groups. */ permissionGroups?: Maybe<Array<Maybe<Group>>> /** List of user's permission groups which user can manage. */ editableGroups?: Maybe<Array<Maybe<Group>>> avatar?: Maybe<Image> /** List of events associated with the user. */ events?: Maybe<Array<Maybe<CustomerEvent>>> /** List of stored payment sources. */ storedPaymentSources?: Maybe<Array<Maybe<PaymentSource>>> /** User language code. */ languageCode: LanguageCodeEnum } /** Represents user data. */ export type UserCheckoutTokensArgs = { channel?: Maybe<Scalars['String']> } /** Represents user data. */ export type UserGiftCardsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents user data. */ export type UserOrdersArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Represents user data. */ export type UserAvatarArgs = { size?: Maybe<Scalars['Int']> } /** Represents user data. */ export type UserStoredPaymentSourcesArgs = { channel?: Maybe<Scalars['String']> } /** Deletes a user avatar. Only for staff members. */ export type UserAvatarDelete = { __typename?: 'UserAvatarDelete' /** An updated user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Create a user avatar. Only for staff members. This mutation must be sent as a `multipart` request. More detailed specs of the upload format can be found here: https://github.com/jaydenseric/graphql-multipart-request-spec */ export type UserAvatarUpdate = { __typename?: 'UserAvatarUpdate' /** An updated user instance. */ user?: Maybe<User> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** Activate or deactivate users. */ export type UserBulkSetActive = { __typename?: 'UserBulkSetActive' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } export type UserCountableConnection = { __typename?: 'UserCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<UserCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type UserCountableEdge = { __typename?: 'UserCountableEdge' /** The item at the end of the edge. */ node: User /** A cursor for use in pagination. */ cursor: Scalars['String'] } export type UserCreateInput = { /** Billing address of the customer. */ defaultBillingAddress?: Maybe<AddressInput> /** Shipping address of the customer. */ defaultShippingAddress?: Maybe<AddressInput> /** Given name. */ firstName?: Maybe<Scalars['String']> /** Family name. */ lastName?: Maybe<Scalars['String']> /** The unique email address of the user. */ email?: Maybe<Scalars['String']> /** User account is active. */ isActive?: Maybe<Scalars['Boolean']> /** A note about the user. */ note?: Maybe<Scalars['String']> /** User language code. */ languageCode?: Maybe<LanguageCodeEnum> /** URL of a view where users should be redirected to set the password. URL in RFC 1808 format. */ redirectUrl?: Maybe<Scalars['String']> /** Slug of a channel which will be used for notify user. Optional when only one channel exists. */ channel?: Maybe<Scalars['String']> } export type UserPermission = { __typename?: 'UserPermission' /** Internal code for permission. */ code: PermissionEnum /** Describe action(s) allowed to do by permission. */ name: Scalars['String'] /** List of user permission groups which contains this permission. */ sourcePermissionGroups?: Maybe<Array<Group>> } export type UserPermissionSourcePermissionGroupsArgs = { userId: Scalars['ID'] } export enum UserSortField { /** Sort users by first name. */ FirstName = 'FIRST_NAME', /** Sort users by last name. */ LastName = 'LAST_NAME', /** Sort users by email. */ Email = 'EMAIL', /** Sort users by order count. */ OrderCount = 'ORDER_COUNT', } export type UserSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort users by the selected field. */ field: UserSortField } /** Represents a VAT rate for a country. */ export type Vat = { __typename?: 'VAT' /** Country code. */ countryCode: Scalars['String'] /** Standard VAT rate in percent. */ standardRate?: Maybe<Scalars['Float']> /** Country's VAT rate exceptions for specific types of goods. */ reducedRates: Array<Maybe<ReducedRate>> } export enum VariantAttributeScope { All = 'ALL', VariantSelection = 'VARIANT_SELECTION', NotVariantSelection = 'NOT_VARIANT_SELECTION', } /** Assign an media to a product variant. */ export type VariantMediaAssign = { __typename?: 'VariantMediaAssign' productVariant?: Maybe<ProductVariant> media?: Maybe<ProductMedia> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Unassign an media from a product variant. */ export type VariantMediaUnassign = { __typename?: 'VariantMediaUnassign' productVariant?: Maybe<ProductVariant> media?: Maybe<ProductMedia> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ productErrors: Array<ProductError> errors: Array<ProductError> } /** Represents availability of a variant in the storefront. */ export type VariantPricingInfo = { __typename?: 'VariantPricingInfo' /** Whether it is in sale or not. */ onSale?: Maybe<Scalars['Boolean']> /** The discount amount if in sale (null otherwise). */ discount?: Maybe<TaxedMoney> /** The discount amount in the local currency. */ discountLocalCurrency?: Maybe<TaxedMoney> /** The price, with any discount subtracted. */ price?: Maybe<TaxedMoney> /** The price without any discount. */ priceUndiscounted?: Maybe<TaxedMoney> /** The discounted price in the local currency. */ priceLocalCurrency?: Maybe<TaxedMoney> } /** Verify JWT token. */ export type VerifyToken = { __typename?: 'VerifyToken' /** User assigned to token. */ user?: Maybe<User> /** Determine if token is valid or not. */ isValid: Scalars['Boolean'] /** JWT payload. */ payload?: Maybe<Scalars['GenericScalar']> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ accountErrors: Array<AccountError> errors: Array<AccountError> } /** An enumeration. */ export enum VolumeUnitsEnum { CubicMillimeter = 'CUBIC_MILLIMETER', CubicCentimeter = 'CUBIC_CENTIMETER', CubicDecimeter = 'CUBIC_DECIMETER', CubicMeter = 'CUBIC_METER', Liter = 'LITER', CubicFoot = 'CUBIC_FOOT', CubicInch = 'CUBIC_INCH', CubicYard = 'CUBIC_YARD', Qt = 'QT', Pint = 'PINT', FlOz = 'FL_OZ', AcreIn = 'ACRE_IN', AcreFt = 'ACRE_FT', } /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ export type Voucher = Node & { __typename?: 'Voucher' /** The ID of the object. */ id: Scalars['ID'] name?: Maybe<Scalars['String']> /** Determines a type of voucher. */ type: VoucherTypeEnum code: Scalars['String'] usageLimit?: Maybe<Scalars['Int']> used: Scalars['Int'] startDate: Scalars['DateTime'] endDate?: Maybe<Scalars['DateTime']> applyOncePerOrder: Scalars['Boolean'] applyOncePerCustomer: Scalars['Boolean'] /** Determines a type of discount for voucher - value or percentage */ discountValueType: DiscountValueTypeEnum minCheckoutItemsQuantity?: Maybe<Scalars['Int']> /** List of categories this voucher applies to. */ categories?: Maybe<CategoryCountableConnection> /** List of collections this voucher applies to. */ collections?: Maybe<CollectionCountableConnection> /** List of products this voucher applies to. */ products?: Maybe<ProductCountableConnection> /** List of countries available for the shipping voucher. */ countries?: Maybe<Array<Maybe<CountryDisplay>>> /** Returns translated voucher fields for the given language code. */ translation?: Maybe<VoucherTranslation> /** Voucher value. */ discountValue?: Maybe<Scalars['Float']> /** Currency code for voucher. */ currency?: Maybe<Scalars['String']> /** Minimum order value to apply voucher. */ minSpent?: Maybe<Money> /** List of availability in channels for the voucher. */ channelListings?: Maybe<Array<VoucherChannelListing>> } /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ export type VoucherCategoriesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ export type VoucherCollectionsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ export type VoucherProductsArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ export type VoucherTranslationArgs = { languageCode: LanguageCodeEnum } /** Adds products, categories, collections to a voucher. */ export type VoucherAddCatalogues = { __typename?: 'VoucherAddCatalogues' /** Voucher of which catalogue IDs will be modified. */ voucher?: Maybe<Voucher> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } /** Deletes vouchers. */ export type VoucherBulkDelete = { __typename?: 'VoucherBulkDelete' /** Returns how many objects were affected. */ count: Scalars['Int'] /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } /** Represents voucher channel listing. */ export type VoucherChannelListing = Node & { __typename?: 'VoucherChannelListing' /** The ID of the object. */ id: Scalars['ID'] channel: Channel discountValue: Scalars['Float'] currency: Scalars['String'] minSpent?: Maybe<Money> } export type VoucherChannelListingAddInput = { /** ID of a channel. */ channelId: Scalars['ID'] /** Value of the voucher. */ discountValue?: Maybe<Scalars['PositiveDecimal']> /** Min purchase amount required to apply the voucher. */ minAmountSpent?: Maybe<Scalars['PositiveDecimal']> } export type VoucherChannelListingInput = { /** List of channels to which the voucher should be assigned. */ addChannels?: Maybe<Array<VoucherChannelListingAddInput>> /** List of channels from which the voucher should be unassigned. */ removeChannels?: Maybe<Array<Scalars['ID']>> } /** Manage voucher's availability in channels. */ export type VoucherChannelListingUpdate = { __typename?: 'VoucherChannelListingUpdate' /** An updated voucher instance. */ voucher?: Maybe<Voucher> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } export type VoucherCountableConnection = { __typename?: 'VoucherCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<VoucherCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type VoucherCountableEdge = { __typename?: 'VoucherCountableEdge' /** The item at the end of the edge. */ node: Voucher /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates a new voucher. */ export type VoucherCreate = { __typename?: 'VoucherCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> voucher?: Maybe<Voucher> } /** Deletes a voucher. */ export type VoucherDelete = { __typename?: 'VoucherDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> voucher?: Maybe<Voucher> } export enum VoucherDiscountType { Fixed = 'FIXED', Percentage = 'PERCENTAGE', Shipping = 'SHIPPING', } export type VoucherFilterInput = { status?: Maybe<Array<Maybe<DiscountStatusEnum>>> timesUsed?: Maybe<IntRangeInput> discountType?: Maybe<Array<Maybe<VoucherDiscountType>>> started?: Maybe<DateTimeRangeInput> search?: Maybe<Scalars['String']> } export type VoucherInput = { /** Voucher type: PRODUCT, CATEGORY SHIPPING or ENTIRE_ORDER. */ type?: Maybe<VoucherTypeEnum> /** Voucher name. */ name?: Maybe<Scalars['String']> /** Code to use the voucher. */ code?: Maybe<Scalars['String']> /** Start date of the voucher in ISO 8601 format. */ startDate?: Maybe<Scalars['DateTime']> /** End date of the voucher in ISO 8601 format. */ endDate?: Maybe<Scalars['DateTime']> /** Choices: fixed or percentage. */ discountValueType?: Maybe<DiscountValueTypeEnum> /** Products discounted by the voucher. */ products?: Maybe<Array<Maybe<Scalars['ID']>>> /** Collections discounted by the voucher. */ collections?: Maybe<Array<Maybe<Scalars['ID']>>> /** Categories discounted by the voucher. */ categories?: Maybe<Array<Maybe<Scalars['ID']>>> /** Minimal quantity of checkout items required to apply the voucher. */ minCheckoutItemsQuantity?: Maybe<Scalars['Int']> /** Country codes that can be used with the shipping voucher. */ countries?: Maybe<Array<Maybe<Scalars['String']>>> /** Voucher should be applied to the cheapest item or entire order. */ applyOncePerOrder?: Maybe<Scalars['Boolean']> /** Voucher should be applied once per customer. */ applyOncePerCustomer?: Maybe<Scalars['Boolean']> /** Limit number of times this voucher can be used in total. */ usageLimit?: Maybe<Scalars['Int']> } /** Removes products, categories, collections from a voucher. */ export type VoucherRemoveCatalogues = { __typename?: 'VoucherRemoveCatalogues' /** Voucher of which catalogue IDs will be modified. */ voucher?: Maybe<Voucher> /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> } export enum VoucherSortField { /** Sort vouchers by code. */ Code = 'CODE', /** Sort vouchers by start date. */ StartDate = 'START_DATE', /** Sort vouchers by end date. */ EndDate = 'END_DATE', /** Sort vouchers by value. */ Value = 'VALUE', /** Sort vouchers by type. */ Type = 'TYPE', /** Sort vouchers by usage limit. */ UsageLimit = 'USAGE_LIMIT', /** Sort vouchers by minimum spent amount. */ MinimumSpentAmount = 'MINIMUM_SPENT_AMOUNT', } export type VoucherSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Specifies the channel in which to sort the data. */ channel?: Maybe<Scalars['String']> /** Sort vouchers by the selected field. */ field: VoucherSortField } export type VoucherTranslatableContent = Node & { __typename?: 'VoucherTranslatableContent' /** The ID of the object. */ id: Scalars['ID'] name?: Maybe<Scalars['String']> /** Returns translated voucher fields for the given language code. */ translation?: Maybe<VoucherTranslation> /** Vouchers allow giving discounts to particular customers on categories, collections or specific products. They can be used during checkout by providing valid voucher codes. */ voucher?: Maybe<Voucher> } export type VoucherTranslatableContentTranslationArgs = { languageCode: LanguageCodeEnum } /** Creates/Updates translations for Voucher. */ export type VoucherTranslate = { __typename?: 'VoucherTranslate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ translationErrors: Array<TranslationError> errors: Array<TranslationError> voucher?: Maybe<Voucher> } export type VoucherTranslation = Node & { __typename?: 'VoucherTranslation' /** The ID of the object. */ id: Scalars['ID'] name?: Maybe<Scalars['String']> /** Translation language. */ language: LanguageDisplay } export enum VoucherTypeEnum { Shipping = 'SHIPPING', EntireOrder = 'ENTIRE_ORDER', SpecificProduct = 'SPECIFIC_PRODUCT', } /** Updates a voucher. */ export type VoucherUpdate = { __typename?: 'VoucherUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ discountErrors: Array<DiscountError> errors: Array<DiscountError> voucher?: Maybe<Voucher> } /** Represents warehouse. */ export type Warehouse = Node & ObjectWithMetadata & { __typename?: 'Warehouse' /** The ID of the object. */ id: Scalars['ID'] name: Scalars['String'] slug: Scalars['String'] companyName: Scalars['String'] shippingZones: ShippingZoneCountableConnection address: Address email: Scalars['String'] /** List of private metadata items.Requires proper staff permissions to access. */ privateMetadata: Array<Maybe<MetadataItem>> /** List of public metadata items. Can be accessed without permissions. */ metadata: Array<Maybe<MetadataItem>> } /** Represents warehouse. */ export type WarehouseShippingZonesArgs = { before?: Maybe<Scalars['String']> after?: Maybe<Scalars['String']> first?: Maybe<Scalars['Int']> last?: Maybe<Scalars['Int']> } export type WarehouseAddressInput = { /** Address. */ streetAddress1: Scalars['String'] /** Address. */ streetAddress2?: Maybe<Scalars['String']> /** City. */ city: Scalars['String'] /** District. */ cityArea?: Maybe<Scalars['String']> /** Postal code. */ postalCode?: Maybe<Scalars['String']> /** Country. */ country: CountryCode /** State or province. */ countryArea?: Maybe<Scalars['String']> /** Phone number. */ phone?: Maybe<Scalars['String']> } export type WarehouseCountableConnection = { __typename?: 'WarehouseCountableConnection' /** Pagination data for this connection. */ pageInfo: PageInfo edges: Array<WarehouseCountableEdge> /** A total count of items in the collection. */ totalCount?: Maybe<Scalars['Int']> } export type WarehouseCountableEdge = { __typename?: 'WarehouseCountableEdge' /** The item at the end of the edge. */ node: Warehouse /** A cursor for use in pagination. */ cursor: Scalars['String'] } /** Creates new warehouse. */ export type WarehouseCreate = { __typename?: 'WarehouseCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ warehouseErrors: Array<WarehouseError> errors: Array<WarehouseError> warehouse?: Maybe<Warehouse> } export type WarehouseCreateInput = { /** Warehouse slug. */ slug?: Maybe<Scalars['String']> /** Company name. */ companyName?: Maybe<Scalars['String']> /** The email address of the warehouse. */ email?: Maybe<Scalars['String']> /** Warehouse name. */ name: Scalars['String'] /** Address of the warehouse. */ address: WarehouseAddressInput /** Shipping zones supported by the warehouse. */ shippingZones?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Deletes selected warehouse. */ export type WarehouseDelete = { __typename?: 'WarehouseDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ warehouseErrors: Array<WarehouseError> errors: Array<WarehouseError> warehouse?: Maybe<Warehouse> } export type WarehouseError = { __typename?: 'WarehouseError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: WarehouseErrorCode } /** An enumeration. */ export enum WarehouseErrorCode { AlreadyExists = 'ALREADY_EXISTS', GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } export type WarehouseFilterInput = { search?: Maybe<Scalars['String']> ids?: Maybe<Array<Maybe<Scalars['ID']>>> } /** Add shipping zone to given warehouse. */ export type WarehouseShippingZoneAssign = { __typename?: 'WarehouseShippingZoneAssign' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ warehouseErrors: Array<WarehouseError> errors: Array<WarehouseError> warehouse?: Maybe<Warehouse> } /** Remove shipping zone from given warehouse. */ export type WarehouseShippingZoneUnassign = { __typename?: 'WarehouseShippingZoneUnassign' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ warehouseErrors: Array<WarehouseError> errors: Array<WarehouseError> warehouse?: Maybe<Warehouse> } export enum WarehouseSortField { /** Sort warehouses by name. */ Name = 'NAME', } export type WarehouseSortingInput = { /** Specifies the direction in which to sort products. */ direction: OrderDirection /** Sort warehouses by the selected field. */ field: WarehouseSortField } /** Updates given warehouse. */ export type WarehouseUpdate = { __typename?: 'WarehouseUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ warehouseErrors: Array<WarehouseError> errors: Array<WarehouseError> warehouse?: Maybe<Warehouse> } export type WarehouseUpdateInput = { /** Warehouse slug. */ slug?: Maybe<Scalars['String']> /** Company name. */ companyName?: Maybe<Scalars['String']> /** The email address of the warehouse. */ email?: Maybe<Scalars['String']> /** Warehouse name. */ name?: Maybe<Scalars['String']> /** Address of the warehouse. */ address?: Maybe<WarehouseAddressInput> } /** Webhook. */ export type Webhook = Node & { __typename?: 'Webhook' name: Scalars['String'] targetUrl: Scalars['String'] isActive: Scalars['Boolean'] secretKey?: Maybe<Scalars['String']> /** The ID of the object. */ id: Scalars['ID'] /** List of webhook events. */ events: Array<WebhookEvent> app: App } /** Creates a new webhook subscription. */ export type WebhookCreate = { __typename?: 'WebhookCreate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ webhookErrors: Array<WebhookError> errors: Array<WebhookError> webhook?: Maybe<Webhook> } export type WebhookCreateInput = { /** The name of the webhook. */ name?: Maybe<Scalars['String']> /** The url to receive the payload. */ targetUrl?: Maybe<Scalars['String']> /** The events that webhook wants to subscribe. */ events?: Maybe<Array<Maybe<WebhookEventTypeEnum>>> /** ID of the app to which webhook belongs. */ app?: Maybe<Scalars['ID']> /** Determine if webhook will be set active or not. */ isActive?: Maybe<Scalars['Boolean']> /** The secret key used to create a hash signature with each payload. */ secretKey?: Maybe<Scalars['String']> } /** Deletes a webhook subscription. */ export type WebhookDelete = { __typename?: 'WebhookDelete' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ webhookErrors: Array<WebhookError> errors: Array<WebhookError> webhook?: Maybe<Webhook> } export type WebhookError = { __typename?: 'WebhookError' /** Name of a field that caused the error. A value of `null` indicates that the error isn't associated with a particular field. */ field?: Maybe<Scalars['String']> /** The error message. */ message?: Maybe<Scalars['String']> /** The error code. */ code: WebhookErrorCode } /** An enumeration. */ export enum WebhookErrorCode { GraphqlError = 'GRAPHQL_ERROR', Invalid = 'INVALID', NotFound = 'NOT_FOUND', Required = 'REQUIRED', Unique = 'UNIQUE', } /** Webhook event. */ export type WebhookEvent = { __typename?: 'WebhookEvent' /** Internal name of the event type. */ eventType: WebhookEventTypeEnum /** Display name of the event. */ name: Scalars['String'] } /** Enum determining type of webhook. */ export enum WebhookEventTypeEnum { /** All the events. */ AnyEvents = 'ANY_EVENTS', /** A new order is placed. */ OrderCreated = 'ORDER_CREATED', /** An order is confirmed (status change unconfirmed -> unfulfilled) by a staff user using the OrderConfirm mutation. It also triggers when the user completes the checkout and the shop setting `automatically_confirm_all_new_orders` is enabled. */ OrderConfirmed = 'ORDER_CONFIRMED', /** Payment is made and an order is fully paid. */ OrderFullyPaid = 'ORDER_FULLY_PAID', /** An order is updated; triggered for all changes related to an order; covers all other order webhooks, except for ORDER_CREATED. */ OrderUpdated = 'ORDER_UPDATED', /** An order is cancelled. */ OrderCancelled = 'ORDER_CANCELLED', /** An order is fulfilled. */ OrderFulfilled = 'ORDER_FULFILLED', /** An invoice for order requested. */ InvoiceRequested = 'INVOICE_REQUESTED', /** An invoice is deleted. */ InvoiceDeleted = 'INVOICE_DELETED', /** Invoice has been sent. */ InvoiceSent = 'INVOICE_SENT', /** A new customer account is created. */ CustomerCreated = 'CUSTOMER_CREATED', /** A customer account is updated. */ CustomerUpdated = 'CUSTOMER_UPDATED', /** A new product is created. */ ProductCreated = 'PRODUCT_CREATED', /** A product is updated. */ ProductUpdated = 'PRODUCT_UPDATED', /** A product is deleted. */ ProductDeleted = 'PRODUCT_DELETED', /** A new product variant is created. */ ProductVariantCreated = 'PRODUCT_VARIANT_CREATED', /** A product variant is updated. */ ProductVariantUpdated = 'PRODUCT_VARIANT_UPDATED', /** A product variant is deleted. */ ProductVariantDeleted = 'PRODUCT_VARIANT_DELETED', /** A new checkout is created. */ CheckoutCreated = 'CHECKOUT_CREATED', /** A checkout is updated. It also triggers all updates related to the checkout. */ CheckoutUpdated = 'CHECKOUT_UPDATED', /** A new fulfillment is created. */ FulfillmentCreated = 'FULFILLMENT_CREATED', /** User notification triggered. */ NotifyUser = 'NOTIFY_USER', /** A new page is created. */ PageCreated = 'PAGE_CREATED', /** A page is updated. */ PageUpdated = 'PAGE_UPDATED', /** A page is deleted. */ PageDeleted = 'PAGE_DELETED', } /** An enumeration. */ export enum WebhookSampleEventTypeEnum { OrderCreated = 'ORDER_CREATED', OrderConfirmed = 'ORDER_CONFIRMED', OrderFullyPaid = 'ORDER_FULLY_PAID', OrderUpdated = 'ORDER_UPDATED', OrderCancelled = 'ORDER_CANCELLED', OrderFulfilled = 'ORDER_FULFILLED', InvoiceRequested = 'INVOICE_REQUESTED', InvoiceDeleted = 'INVOICE_DELETED', InvoiceSent = 'INVOICE_SENT', CustomerCreated = 'CUSTOMER_CREATED', CustomerUpdated = 'CUSTOMER_UPDATED', ProductCreated = 'PRODUCT_CREATED', ProductUpdated = 'PRODUCT_UPDATED', ProductDeleted = 'PRODUCT_DELETED', ProductVariantCreated = 'PRODUCT_VARIANT_CREATED', ProductVariantUpdated = 'PRODUCT_VARIANT_UPDATED', ProductVariantDeleted = 'PRODUCT_VARIANT_DELETED', CheckoutCreated = 'CHECKOUT_CREATED', CheckoutUpdated = 'CHECKOUT_UPDATED', FulfillmentCreated = 'FULFILLMENT_CREATED', NotifyUser = 'NOTIFY_USER', PageCreated = 'PAGE_CREATED', PageUpdated = 'PAGE_UPDATED', PageDeleted = 'PAGE_DELETED', } /** Updates a webhook subscription. */ export type WebhookUpdate = { __typename?: 'WebhookUpdate' /** @deprecated Use errors field instead. This field will be removed in Saleor 4.0. */ webhookErrors: Array<WebhookError> errors: Array<WebhookError> webhook?: Maybe<Webhook> } export type WebhookUpdateInput = { /** The new name of the webhook. */ name?: Maybe<Scalars['String']> /** The url to receive the payload. */ targetUrl?: Maybe<Scalars['String']> /** The events that webhook wants to subscribe. */ events?: Maybe<Array<Maybe<WebhookEventTypeEnum>>> /** ID of the app to which webhook belongs. */ app?: Maybe<Scalars['ID']> /** Determine if webhook will be set active or not. */ isActive?: Maybe<Scalars['Boolean']> /** Use to create a hash signature with each payload. */ secretKey?: Maybe<Scalars['String']> } /** Represents weight value in a specific weight unit. */ export type Weight = { __typename?: 'Weight' /** Weight unit. */ unit: WeightUnitsEnum /** Weight value. */ value: Scalars['Float'] } /** An enumeration. */ export enum WeightUnitsEnum { G = 'G', Lb = 'LB', Oz = 'OZ', Kg = 'KG', Tonne = 'TONNE', } export type _Entity = | Address | User | Group | App | ProductVariant | Product | ProductType | Collection | Category | ProductMedia | ProductImage | PageType export type _Service = { __typename?: '_Service' sdl?: Maybe<Scalars['String']> } export type GetAllProductPathsQueryVariables = Exact<{ first?: Maybe<Scalars['Int']> cursor?: Maybe<Scalars['String']> channel?: Maybe<Scalars['String']> }> export type GetAllProductPathsQuery = { __typename?: 'Query' } & { products?: Maybe< { __typename?: 'ProductCountableConnection' } & { pageInfo: { __typename?: 'PageInfo' } & Pick<PageInfo, 'hasNextPage' | 'hasPreviousPage'> edges: Array< { __typename?: 'ProductCountableEdge' } & Pick<ProductCountableEdge, 'cursor'> & { node: { __typename?: 'Product' } & Pick<Product, 'slug'> } > } > } export type ProductConnectionFragment = { __typename?: 'ProductCountableConnection' } & { pageInfo: { __typename?: 'PageInfo' } & Pick<PageInfo, 'hasNextPage' | 'hasPreviousPage'> edges: Array< { __typename?: 'ProductCountableEdge' } & { node: { __typename?: 'Product' } & Pick<Product, 'id' | 'name' | 'description' | 'slug'> & { pricing?: Maybe< { __typename?: 'ProductPricingInfo' } & { priceRange?: Maybe< { __typename?: 'TaxedMoneyRange' } & { start?: Maybe< { __typename?: 'TaxedMoney' } & { net: { __typename?: 'Money' } & Pick<Money, 'amount'> } > } > } > media?: Maybe<Array<{ __typename?: 'ProductMedia' } & Pick<ProductMedia, 'url' | 'alt'>>> } } > } export type GetAllProductsQueryVariables = Exact<{ first?: Maybe<Scalars['Int']> filter?: Maybe<ProductFilterInput> sortBy?: Maybe<ProductOrder> channel?: Maybe<Scalars['String']> }> export type GetAllProductsQuery = { __typename?: 'Query' } & { products?: Maybe<{ __typename?: 'ProductCountableConnection' } & ProductConnectionFragment> }
the_stack
import Grid, { GRID_PROPERTY_TYPES, withMethods } from "@egjs/grid"; import { diff } from "@egjs/list-differ"; import { GROUP_TYPE, IGNORE_PROPERITES_MAP, INFINITEGRID_METHODS, ITEM_INFO_PROPERTIES, ITEM_TYPE } from "./consts"; import { GroupManagerStatus, InfiniteGridGroupStatus } from "./GroupManager"; import InfiniteGrid from "./InfiniteGrid"; import { InfiniteGridItem, InfiniteGridItemStatus } from "./InfiniteGridItem"; import { CategorizedGroup, InfiniteGridGroup, InfiniteGridInsertedItems, InfiniteGridItemInfo, RenderingOptions, } from "./types"; export function isWindow(el: Window | Element): el is Window { return el === window; } export function isNumber(val: any): val is number { return typeof val === "number"; } export function isString(val: any): val is string { return typeof val === "string"; } export function isObject(val: any): val is object { return typeof val === "object"; } export function flat<T>(arr: T[][]): T[] { return arr.reduce((prev, cur) => { return [...prev, ...cur]; }, []); } export function splitOptions(options: Record<string, any>) { const { gridOptions, ...otherOptions } = options; return { ...splitGridOptions(gridOptions), ...otherOptions, }; } export function splitGridOptions(options: Record<string, any>) { const nextOptions: Record<string, any> = {}; const gridOptions: Record<string, any> = {}; const defaultOptions = Grid.defaultOptions; for (const name in options) { const value = options[name]; if (!(name in IGNORE_PROPERITES_MAP)) { gridOptions[name] = value; } if (name in defaultOptions) { nextOptions[name] = value; } } return { ...nextOptions, gridOptions, }; } export function categorize<Item extends InfiniteGridItemInfo = InfiniteGridItem>(items: Item[]) { const groups: Array<CategorizedGroup<Item>> = []; const groupKeys: Record<string | number, CategorizedGroup<Item>> = {}; const registeredGroupKeys: Record<string | number, boolean> = {}; items.filter((item) => item.groupKey != null).forEach(({ groupKey }) => { registeredGroupKeys[groupKey!] = true; }); let generatedGroupKey: number | string; let isContinuousGroupKey = false; items.forEach((item) => { if (item.groupKey != null) { isContinuousGroupKey = false; } else { if (!isContinuousGroupKey) { generatedGroupKey = makeKey(registeredGroupKeys); isContinuousGroupKey = true; registeredGroupKeys[generatedGroupKey] = true; } item.groupKey = generatedGroupKey; } const groupKey = item.groupKey; let group = groupKeys[groupKey]; if (!group) { group = { groupKey, items: [], }; groupKeys[groupKey] = group; groups.push(group); } group.items.push(item); }); return groups; } export function getNextCursors( prevKeys: Array<string | number>, nextKeys: Array<string | number>, prevStartCursor: number, prevEndCursor: number, ) { const result = diff(prevKeys, nextKeys, (key) => key); let nextStartCursor = -1; let nextEndCursor = -1; // sync cursors result.maintained.forEach(([prevIndex, nextIndex]) => { if (prevStartCursor <= prevIndex && prevIndex <= prevEndCursor) { if (nextStartCursor === -1) { nextStartCursor = nextIndex; nextEndCursor = nextIndex; } else { nextStartCursor = Math.min(nextStartCursor, nextIndex); nextEndCursor = Math.max(nextEndCursor, nextIndex); } } }); return { startCursor: nextStartCursor, endCursor: nextEndCursor, }; } export function splitVirtualGroups<Group extends { type: GROUP_TYPE, groupKey: string | number }>( groups: Group[], direction: "start" | "end", nextGroups: CategorizedGroup<InfiniteGridItemStatus>[], ) { let virtualGroups: Group[] = []; if (direction === "start") { const index = findIndex(groups, (group) => group.type === GROUP_TYPE.NORMAL); if (index === -1) { return []; } virtualGroups = groups.slice(0, index); } else { const index = findLastIndex(groups, (group) => group.type === GROUP_TYPE.NORMAL); if (index === -1) { return []; } virtualGroups = groups.slice(index + 1); } const nextVirtualGroups = diff<{ groupKey: string | number }>( virtualGroups, nextGroups, ({ groupKey }) => groupKey, ).removed.map((index) => { return virtualGroups[index]; }).reverse(); return nextVirtualGroups; } export function getFirstRenderingItems( nextItems: InfiniteGridItemStatus[], horizontal: boolean, ) { const groups = categorize(nextItems); if (!groups[0]) { return []; } return groups[0].items.map((item) => { return new InfiniteGridItem(horizontal, { ...item, }); }); } export function getRenderingItemsByStatus( groupManagerStatus: GroupManagerStatus, nextItems: InfiniteGridItemStatus[], usePlaceholder: boolean, horizontal: boolean, ) { const prevGroups = groupManagerStatus.groups; const groups = categorize(nextItems); const startVirtualGroups = splitVirtualGroups(prevGroups, "start", groups); const endVirtualGroups = splitVirtualGroups(prevGroups, "end", groups); const nextGroups = [ ...startVirtualGroups, ...groups, ...endVirtualGroups, ] as Array<InfiniteGridGroupStatus | CategorizedGroup<InfiniteGridItemStatus>>; const { startCursor, endCursor, } = getNextCursors( prevGroups.map((group) => group.groupKey), nextGroups.map((group) => group.groupKey), groupManagerStatus.cursors[0], groupManagerStatus.cursors[1], ); let nextVisibleItems = flat(nextGroups.slice(startCursor, endCursor + 1).map((group) => { return group.items.map((item) => { return new InfiniteGridItem(horizontal, { ...item }); }); })); if (!usePlaceholder) { nextVisibleItems = nextVisibleItems.filter((item) => { return item.type !== ITEM_TYPE.VIRTUAL; }); } return nextVisibleItems; } export function mountRenderingItems(items: InfiniteGridItemInfo[], options: RenderingOptions) { const { grid, usePlaceholder, useLoading, useFirstRender, status, } = options; if (!grid) { return; } if (usePlaceholder) { grid.setPlaceholder({}); } if (useLoading) { grid.setLoading({}); } if (status) { grid.setStatus(status, true); } grid.syncItems(items); if (useFirstRender && !status && grid.getGroups().length) { grid.setCursors(0, 0, true); } } export function getRenderingItems(items: InfiniteGridItemInfo[], options: RenderingOptions) { const { status, usePlaceholder, useLoading, horizontal, useFirstRender, grid, } = options; let visibleItems: InfiniteGridItem[] = []; if (grid) { grid.setPlaceholder(usePlaceholder ? {} : null); grid.setLoading(useLoading ? {} : null); grid.syncItems(items); visibleItems = grid.getRenderingItems(); } else if (status) { visibleItems = getRenderingItemsByStatus(status.groupManager, items, !!usePlaceholder, !!horizontal); } else if (useFirstRender) { visibleItems = getFirstRenderingItems(items, !!horizontal); } return visibleItems; } /* Class Decorator */ export function InfiniteGridGetterSetter(component: { prototype: InfiniteGrid<any>, propertyTypes: typeof GRID_PROPERTY_TYPES, }) { const { prototype, propertyTypes, } = component; for (const name in propertyTypes) { const attributes: Record<string, any> = { enumerable: true, configurable: true, get(this: InfiniteGrid) { const options = this.groupManager.options; if (name in options) { return options[name]; } else { return options.gridOptions[name]; } }, set(this: InfiniteGrid, value: any) { const prevValue = this.groupManager[name]; if (prevValue === value) { return; } this.groupManager.gridOptions = { [name]: value, }; }, }; Object.defineProperty(prototype, name, attributes); } } export function makeKey(registeredKeys: Record<string, any>) { // eslint-disable-next-line no-constant-condition while (true) { const key = new Date().getTime() + Math.floor(Math.random() * 1000); if (!(key in registeredKeys)) { return key; } } } export function convertHTMLtoElement(html: string) { const dummy = document.createElement("div"); dummy.innerHTML = html; return toArray(dummy.children); } export function convertInsertedItems( items: InfiniteGridInsertedItems, groupKey?: string | number, ): InfiniteGridItemInfo[] { let insertedItems: Array<string | HTMLElement | InfiniteGridItemInfo>; if (isString(items)) { insertedItems = convertHTMLtoElement(items); } else { insertedItems = items; } return insertedItems.map((item) => { let element!: HTMLElement; let html = ""; let key!: string | number; if (isString(item)) { html = item; } else if ("parentNode" in item) { element = item; html = item.outerHTML; } else { return { groupKey, ...item }; } return { key, groupKey, html, element, }; }); } export function toArray(nodes: HTMLCollection): HTMLElement[]; export function toArray<T>(nodes: { length: number, [key: number]: T }): T[]; export function toArray<T>(nodes: { length: number, [key: number]: T }): T[] { const array: T[] = []; if (nodes) { const length = nodes.length; for (let i = 0; i < length; i++) { array.push(nodes[i]); } } return array; } export function findIndex<T>(arr: T[], callback: (value: T, index: number) => boolean) { const length = arr.length; for (let i = 0; i < length; ++i) { if (callback(arr[i], i)) { return i; } } return -1; } export function findLastIndex<T>(arr: T[], callback: (value: T, index: number) => boolean) { const length = arr.length; for (let i = length - 1; i >= 0; --i) { if (callback(arr[i], i)) { return i; } } return -1; } export function getItemInfo(info: InfiniteGridItemInfo) { const nextInfo: InfiniteGridItemInfo = {}; for (const name in info) { if (name in ITEM_INFO_PROPERTIES) { nextInfo[name] = info[name]; } } return nextInfo; } export function setPlaceholder(item: InfiniteGridItem, info: InfiniteGridItemStatus) { for (const name in info) { const value = info[name]; if (isObject(value)) { item[name] = { ...item[name], ...value, }; } else { item[name] = info[name]; } } } export function isFlatOutline(start: number[], end: number[]) { return start.length === end.length && start.every((pos, i) => end[i] === pos); } export function range(length: number): number[] { const arr: number[] = []; for (let i = 0; i < length; ++i) { arr.push(i); } return arr; } export function flatGroups(groups: InfiniteGridGroup[]) { return flat(groups.map(({ grid }) => grid.getItems() as InfiniteGridItem[])); } export function filterVirtuals<T extends InfiniteGridItem | InfiniteGridGroup>( items: T[], includePlaceholders?: boolean ): T[] { if (includePlaceholders) { return items; } else { return items.filter((item) => item.type !== ITEM_TYPE.VIRTUAL); } } /** * Decorator that makes the method of InfiniteGrid available in the framework. * @ko 프레임워크에서 InfiniteGrid의 메소드를 사용할 수 있게 하는 데코레이터. * @private * @example * ```js * import { withInfiniteGridMethods } from "@egjs/infinitegrid"; * * class Grid extends React.Component<Partial<InfiniteGridProps & InfiniteGridOptions>> { * &#64;withInfiniteGridMethods * private grid: NativeGrid; * } * ``` */ export const withInfiniteGridMethods = withMethods(INFINITEGRID_METHODS);
the_stack
import {CacheInfo, ImageId, ImageData, ImagesList, ImagesMap} from './api'; import {ImageEventWithId} from './index'; import {styled, Layout, Toolbar, theme} from 'flipper-plugin'; import { Button, Switch, Empty, Skeleton, Typography, Image, Row, Col, Badge, } from 'antd'; import MultipleSelect from './MultipleSelect'; import React, {PureComponent} from 'react'; import {DeleteFilled} from '@ant-design/icons'; function toMB(bytes: number) { return Math.floor(bytes / (1024 * 1024)); } export function toKB(bytes: number) { return Math.floor(bytes / 1024); } export function formatMB(bytes: number) { return toMB(bytes) + 'MB'; } export function formatKB(bytes: number) { return Math.floor(bytes / 1024) + 'KB'; } type ToggleProps = { label: string; onClick?: (newValue: boolean) => void; toggled: boolean; }; function Toggle(props: ToggleProps) { return ( <> <Switch onClick={() => { props.onClick && props.onClick(!props.toggled); }} checked={props.toggled} /> <Typography.Text>{props.label}</Typography.Text> </> ); } type ImagesCacheOverviewProps = { onColdStartChange: (checked: boolean) => void; coldStartFilter: boolean; allSurfacesOption: string; surfaceOptions: Set<string>; selectedSurfaces: Set<string>; onChangeSurface: (key: Set<string>) => void; images: ImagesList; onClear: (type: string) => void; onTrimMemory: () => void; onRefresh: () => void; onEnableDebugOverlay: (enabled: boolean) => void; isDebugOverlayEnabled: boolean; onEnableAutoRefresh: (enabled: boolean) => void; isAutoRefreshEnabled: boolean; onImageSelected: (selectedImage: ImageId) => void; imagesMap: ImagesMap; events: Array<ImageEventWithId>; onTrackLeaks: (enabled: boolean) => void; isLeakTrackingEnabled: boolean; onShowDiskImages: (enabled: boolean) => void; showDiskImages: boolean; }; type ImagesCacheOverviewState = { selectedImage: ImageId | null; size: number; }; export default class ImagesCacheOverview extends PureComponent< ImagesCacheOverviewProps, ImagesCacheOverviewState > { state = { selectedImage: null, size: 150, }; onImageSelected = (selectedImage: ImageId) => { this.setState({selectedImage}); this.props.onImageSelected(selectedImage); }; onEnableDebugOverlayToggled = () => { this.props.onEnableDebugOverlay(!this.props.isDebugOverlayEnabled); }; onEnableAutoRefreshToggled = () => { this.props.onEnableAutoRefresh(!this.props.isAutoRefreshEnabled); }; onSurfaceOptionsChange = (selectedItem: string, checked: boolean) => { const {allSurfacesOption, surfaceOptions} = this.props; const selectedSurfaces = new Set([...this.props.selectedSurfaces]); if (checked && selectedItem === allSurfacesOption) { this.props.onChangeSurface(surfaceOptions); return; } if (!checked && selectedSurfaces.size === 1) { return; } if (selectedItem !== allSurfacesOption) { selectedSurfaces.delete(allSurfacesOption); if (checked) { selectedSurfaces.add(selectedItem); } else { selectedSurfaces.delete(selectedItem); } } if ( surfaceOptions.size - selectedSurfaces.size === 1 && !selectedSurfaces.has(allSurfacesOption) ) { selectedSurfaces.add(allSurfacesOption); } this.props.onChangeSurface(selectedSurfaces); }; render() { const hasImages = this.props.images.reduce( (c, cacheInfo) => c + cacheInfo.imageIds.length, 0, ) > 0; return ( <Layout.ScrollContainer> <Toolbar> <Button icon={<DeleteFilled></DeleteFilled>} onClick={this.props.onTrimMemory}> Trim Memory </Button> <Button onClick={this.props.onRefresh}>Refresh</Button> <MultipleSelect selected={this.props.selectedSurfaces} options={this.props.surfaceOptions} onChange={this.onSurfaceOptionsChange} label="Surfaces" /> <Toggle onClick={this.onEnableAutoRefreshToggled} toggled={this.props.isAutoRefreshEnabled} label="Auto Refresh" /> <Toggle onClick={this.onEnableDebugOverlayToggled} toggled={this.props.isDebugOverlayEnabled} label="Show Debug Overlay" /> <Toggle toggled={this.props.coldStartFilter} onClick={this.props.onColdStartChange} label="Show Cold Start Images" /> <Toggle toggled={this.props.isLeakTrackingEnabled} onClick={this.props.onTrackLeaks} label="Track Leaks" /> <Toggle toggled={this.props.showDiskImages} onClick={this.props.onShowDiskImages} label="Show Disk Images" /> </Toolbar> {!hasImages ? ( <Layout.Container pad> <Empty /> </Layout.Container> ) : ( <Layout.ScrollContainer> {this.props.images.map((data: CacheInfo, index: number) => { const maxSize = data.maxSizeBytes; const subtitle = maxSize ? formatMB(data.sizeBytes) + ' / ' + formatMB(maxSize) : formatMB(data.sizeBytes); const onClear = data.clearKey !== undefined ? () => this.props.onClear(data.clearKey as string) : undefined; return ( <ImageGrid key={index} title={data.cacheType} subtitle={subtitle} images={data.imageIds} onImageSelected={this.onImageSelected} selectedImage={this.state.selectedImage} imagesMap={this.props.imagesMap} events={this.props.events} onClear={onClear} /> ); })} </Layout.ScrollContainer> )} </Layout.ScrollContainer> ); } } class ImageGrid extends PureComponent<{ title: string; subtitle: string; images: Array<ImageId>; selectedImage: ImageId | null; onImageSelected: (image: ImageId) => void; onClear: (() => void) | undefined; imagesMap: ImagesMap; events: Array<ImageEventWithId>; }> { static Content = styled.div({ paddingLeft: 15, }); render() { const {images, onImageSelected, selectedImage} = this.props; if (images.length === 0) { return null; } const ROW_SIZE = 6; const imageRows = Array(Math.ceil(images.length / ROW_SIZE)) .fill(0) .map((_, index) => index * ROW_SIZE) .map((begin) => images.slice(begin, begin + ROW_SIZE)); return ( <Layout.Container gap> <ImageGridHeader key="header" title={this.props.title} subtitle={this.props.subtitle} onClear={this.props.onClear} /> <Layout.Container pad> {imageRows.map((row, rowIndex) => ( <Layout.Container pad key={rowIndex}> <Row key={rowIndex} align={'middle'} gutter={[8, 24]}> {row.map((imageId, colIndex) => ( <Col key={colIndex} span={24 / ROW_SIZE}> <ImageItem imageId={imageId} image={this.props.imagesMap[imageId]} key={imageId} selected={ selectedImage != null && selectedImage === imageId } onSelected={onImageSelected} numberOfRequests={ this.props.events.filter((e) => e.imageIds.includes(imageId), ).length } /> </Col> ))} </Row> </Layout.Container> ))} </Layout.Container> </Layout.Container> ); } } class ImageGridHeader extends PureComponent<{ title: string; subtitle: string; onClear: (() => void) | undefined; }> { static Subtitle = styled.span({ fontSize: 22, fontWeight: 300, }); render() { return ( <Layout.Horizontal gap pad grow borderBottom> <Typography.Title>{this.props.title}</Typography.Title> <ImageGridHeader.Subtitle> {this.props.subtitle} </ImageGridHeader.Subtitle> {this.props.onClear ? ( <Button onClick={this.props.onClear}>Clear Cache</Button> ) : null} </Layout.Horizontal> ); } } class ImageItem extends PureComponent<{ imageId: ImageId; image: ImageData; selected: boolean; onSelected: (image: ImageId) => void; size: number; numberOfRequests: number; }> { static defaultProps = { size: 150, }; static SelectedHighlight = styled.div<{selected: boolean}>((props) => ({ borderColor: theme.primaryColor, borderStyle: 'solid', borderWidth: props.selected ? 3 : 0, borderRadius: 4, boxShadow: props.selected ? `inset 0 0 0 1px ${theme.white}` : 'none', bottom: 0, left: 0, position: 'absolute', right: 0, top: 0, })); static HoverOverlay = styled(Layout.Container)<{ selected: boolean; size: number; }>((props) => ({ alignItems: 'center', backgroundColor: 'rgba(255,255,255,0.8)', bottom: props.selected ? 4 : 0, fontSize: props.size > 100 ? 16 : 11, justifyContent: 'center', left: props.selected ? 4 : 0, opacity: 0, position: 'absolute', right: props.selected ? 4 : 0, top: props.selected ? 4 : 0, overflow: 'hidden', transition: '.1s opacity', '&:hover': { opacity: 1, }, })); static MemoryLabel = styled.span({ fontWeight: 600, marginBottom: 6, }); static SizeLabel = styled.span({ fontWeight: 300, }); static EventBadge = styled(Badge)({ position: 'absolute', top: 0, right: 0, zIndex: 1, }); onClick = () => { this.props.onSelected(this.props.imageId); }; render() { const {image, selected, size, numberOfRequests} = this.props; return ( <Layout.Container onClick={this.onClick} gap> {numberOfRequests > 0 && image != null && ( <ImageItem.EventBadge count={numberOfRequests}></ImageItem.EventBadge> )} {image != null ? ( <Image src={image.data} preview={false} /> ) : ( <Skeleton.Image /> )} <ImageItem.SelectedHighlight selected={selected} /> {image != null && ( <ImageItem.HoverOverlay selected={selected} size={size}> <ImageItem.MemoryLabel> {formatKB(image.sizeBytes)} </ImageItem.MemoryLabel> <ImageItem.SizeLabel> {image.width}&times;{image.height} </ImageItem.SizeLabel> </ImageItem.HoverOverlay> )} </Layout.Container> ); } }
the_stack
import fetch from '@/util/fetch' import qs from 'qs' import { BASE, BUILD, DEPINFO, EVENT, HEALTH, TRACE } from './initialState' import model from './model' const application = { heapDownloadUrl: (id: string) => `${apiHost}/admin/instances/${id}/actuator/heapdump`, fetchServiceList: ( findType = 0, pageNum = 1, appName = '', pageSize = 8 ): Promise<ServiceData> => { const appNameParam = (appName && appName.length) > 0 ? `appName=${appName}&` : '' const findTypeParam = findType ? `&findType=${findType}` : '' return fetch({ method: 'get', url: `/admin/applications?${appNameParam}pageNum=${pageNum}&pageSize=${pageSize}${findTypeParam}`, }).then((data: any) => { return model.Service(data) }) }, fetchApplicationList: ( data: { appName?: string pageNum?: number pageSize?: number } = {} ): Promise<InstanceData> => { return fetch({ method: 'get', url: `admin/instances?${qs.stringify(data)}`, }).then((resp: any) => { return model.index(resp) }) }, clearApplicationList: () => { model.index({}) // reset data }, fetchApplicationMetrics: (id: string): Promise<{ id: string; metrics: MetricsData }> => { return fetch<MetricsData>( { method: 'get', url: `admin/instances/${id}/actuator/metricsInfo`, }, { showLoading: false } ).then(data => { return { id, metrics: data, } }) }, fetchApplicationDetail: (id: string): Promise<InstanceItem> => { model.detail.base(BASE) return fetch({ method: 'get', url: `admin/instances/${id}`, }) .then((data: any) => { return model.detail.base(data) }) .catch(() => { return model.detail.base(BASE) }) }, fetchApplicationInfo: (id: string): Promise<Info> => { model.detail.build(BUILD) return fetch({ method: 'get', url: `admin/instances/${id}/actuator/info`, }) .then(data => { return model.detail.build(data) }) .catch(() => { return model.detail.build(BUILD) }) }, fetchApplicationEvent: (id: string): Promise<InstanceEvent[]> => { model.detail.event(EVENT) return fetch({ method: 'get', url: `admin/instances/events/${id}`, }) .then(data => { return model.detail.event(data) }) .catch(() => { return model.detail.event(EVENT) }) }, fetchApplicationHealth: (id: string): Promise<HealthData> => { model.detail.health(HEALTH) return fetch({ method: 'get', headers: { Accept: '*/*' }, url: `admin/instances/${id}/actuator/health`, }) .then(data => { return model.detail.health(data) }) .catch(() => { return model.detail.health(HEALTH) }) }, fetchApplicationDepInfo: (id: string): Promise<AppDepInfo> => { model.detail.depInfo(DEPINFO) return fetch({ url: `admin/instances/${id}/actuator/appinfo`, }) .then(data => { return model.detail.depInfo(data) }) .catch(() => { return model.detail.depInfo(DEPINFO) }) }, // topo fetchApplicationTopo: (name: string) => { return fetch({ method: 'get', url: `admin/app/trace/${name}`, }) }, /* 日志列表 */ fetchApplicationLoggers: (id: string) => { return fetch({ method: 'get', url: `admin/instances/${id}/actuator/loggers`, }).then((data: any) => { return Promise.resolve(model.log(data)) }) }, fetchApplicationGCLog: (id: string, page = 1, size = 100): Promise<GCLogData> => { return fetch({ header: { Accept: 'application/json' }, url: `admin/instances/${id}/actuator/gc?page=${page}&size=${size}`, }).then(data => { return model.GCLog(data) }) }, /* 修改日志级别 */ fetchApplicationModifyLogLevel: (id: string, level: string, options: object) => { return fetch({ data: options, method: 'post', url: `admin/instances/${id}/actuator/loggers/${level}`, }).then(() => { application.fetchApplicationLoggers(id) }) }, fetchApplicationLogfileType: ( id: string, showLoading?: boolean ) => { const requestConf: any = { method: 'get', url: `admin/instances/${id}/actuator/logfile`, } return fetch(requestConf, { fullResponse: true, showLoading }).then((resp: any) => { return resp; }) }, /* 获取日志详情 */ fetchApplicationModifyLogDel: ( id: string, value: string, offset?: number, showLoading?: boolean ) => { const requestConf: any = { method: 'get', responseType: 'buffer', url: `admin/instances/${id}/actuator/logfile/${value}`, } if (offset && offset > 0) { requestConf['headers'] = { Range: `bytes=${offset}-` } } return fetch(requestConf, { fullResponse: true, showLoading }).then((resp: any) => { model.LogDel(resp.data) return resp }) }, // 新实例列表 fetchApplicationExampleList: ( name: string = '', projectName: string = '', status: string = '', pageNo: number = 1, pageSize: number = 10, isAccept: boolean = false, takeOver: number = -1 ) => { const params: any = { name, projectName, status, pageNo, pageSize, isAccept } if (takeOver > -1) { params['takeOver'] = takeOver } return fetch({ method: 'POST', url: `admin/app/searchByPage`, data: params, }).then((data: any) => { data.list = data.list.map((d: any) => { if (!d.springApplicationName) { d.springApplicationName = '' } d.isDeleted = d.isDeleted === 1 ? true : false d.takeOver = d.takeOver === 1 ? true : false return d }) return model.AppSearch.AppSearchList(data) }) }, // 归属项目 fetchApplicationSearchToobar: () => { return fetch({ method: 'get', url: `admin/app/queryCriteria`, }).then((data: any) => { return model.AppSearch.SearchToobar(data) }) }, // 环境配置 fetchApplicationEnv: (id: any) => { return fetch({ method: 'get', headers: { Accept: '*/*', }, url: `admin/instances/${id}/actuator/env`, }).then((data: any) => { return Promise.resolve(model.EnvironConfig(data)) }) }, // 获取JMX菜单列表 fetchApplicationJmx: (id: string) => { return fetch({ method: 'post', url: `admin/instances/${id}/actuator/jolokia/`, data: { type: 'list', config: { ignoreErrors: true } }, headers: { Accept: '*/*', }, }).then((data: any) => { return Promise.resolve(model.Jmx(data.value)) }) }, // 应用实例同步 fetchApplicationsynch: () => { return fetch({ method: 'get', url: `admin/synch/synch`, }) }, // Trace fetchApplicationTrace: (id: string) => { model.Trace(TRACE) return fetch({ method: 'get', headers: { Accept: '*/*', }, url: `admin/instances/${id}/actuator/httptrace`, }) .then((data: any) => { return Promise.resolve(model.Trace(data.traces)) }) .catch(() => { return model.Trace(TRACE) }) }, // Thread fetchApplicationThread: (id: string, showLoading: boolean) => { return fetch( { url: `admin/instances/${id}/actuator/threaddump`, headers: { Accept: '*/*', }, }, { showLoading } ).then((data: any) => { return Promise.resolve(model.Thread(data.threads)) }) }, // 收藏操作 fetchApplicationIsNeedCollect: (mailNickname: string, isCollect: boolean, appId: string) => { return fetch({ method: 'get', url: `admin/user/isNeedCollect?mailNickname=${mailNickname}&appId=${appId}&isCollect=${isCollect}`, }) }, // Jar fetchApplicationJar: (id: string): Promise<JardepsData> => { return fetch<JardepsData>({ url: `admin/instances/${id}/actuator/jardeps`, timeout: 1000 * 100, // 100s : backend api slow in V1 api }).then(data => { return model.Jar(data) }) }, // EventLog 事件日志 fetchEventLogs: (pageNum = 1, pageSize = 8): Promise<EventLogData> => { return fetch<EventLogData>({ url: `admin/instances/events?pageNum=${pageNum}&pageSize=${pageSize}`, }).then(data => { return model.EventLog(data) }) }, //注册中心管理 fetchRegisterCenters: (code: string = '', pageNo: number = 1, pageSize: number = 10) => { return fetch({ method: 'POST', url: `admin/registerCenter/list`, data: { code, pageNo, pageSize }, }).then((data: any) => { data.list = data.list.map((d: any) => { d.isDeleted = d.isDeleted === 1 ? true : false return d }) return model.RegisterCenter(data) }) }, deleteRegisterCenter: (registerCenterId: number) => { return fetch({ url: `admin/registerCenter/delete/${registerCenterId}`, }) }, createRegisterCenter: (registerCenterData: any) => { return fetch({ method: 'POST', url: `admin/registerCenter/add`, data: registerCenterData, }) }, updateRegisterCenter: (registerCenterData: any) => { return fetch({ method: 'POST', url: `admin/registerCenter/update`, data: registerCenterData, }) }, // 项目列表 fetchProjects: ( name: string = '', pageNo: number = 1, pageSize: number = 10 ): Promise<ProjectData> => { return fetch<ProjectData>({ method: 'POST', url: `admin/project/list`, data: { name, pageNo, pageSize }, }).then(data => { data.list = data.list.map((d: any) => { d.isDeleted = d.isDeleted === 1 ? true : false return d }) return model.Project(data) }) }, deleteProject: (projectId: number) => { return fetch({ url: `admin/project/delete/${projectId}`, }) }, createProject: (projectData: any) => { return fetch({ method: 'POST', url: `admin/project/add`, data: projectData, }) }, updateProject: (projectData: any) => { return fetch({ method: 'POST', url: `admin/project/update`, data: projectData, }) }, // 作为 owner 的选项 fetchUserList: () => { return fetch({ url: '/admin/user/list', }).then(data => { return model.UserList(data) }) }, fetchRemoteConfigs: (search: string = '', page: number = 1): Promise<RemoteConfigData> => { return fetch<RemoteConfigData>({ method: 'POST', url: 'admin/metadata/pageList', data: { dictName: search, pageNo: page, pageSize: 8, }, }).then(data => { return model.RemoteConfigs(data) }) }, updateRemoteConfig: (conf: RemoteConfigModel) => { return fetch({ method: 'POST', url: 'admin/metadata/updateDictType', data: conf, }) }, updateRemoteConfigOption: (conf: RemoteConfigModel) => { return fetch({ method: 'POST', url: 'admin/metadata/updateDictData', data: conf, }) }, createRemoteConfig: (conf: RemoteConfigModel) => { return fetch({ method: 'POST', url: 'admin/metadata/addDictType', data: conf, }) }, createRemoteConfigOption: (conf: RemoteConfigModel) => { return fetch({ method: 'POST', url: 'admin/metadata/addDictData', data: conf, }) }, deleteRemoteConfig: (id: number) => { return fetch({ url: `/admin/metadata/deleteDictType/${id}`, }) }, deleteRemoteConfigOption: (id: number) => { return fetch({ url: `/admin/metadata/deleteDictData/${id}`, }) }, fetchTrajectory: (data?: any) => { const defaultData = { pageNo: 1, pageSize: 10 } const mergedData = { ...defaultData, ...data } return fetch({ method: 'POST', url: `/admin/app/mqTrace`, data: mergedData, }).then(data => { return model.Trajectory(data) }) }, fetchTotalRequestNum: (instanceId: string, time: string, groupByTime: string) => { return fetch({ url: `admin/app/totalRequestNum?instanceId=${instanceId}&time=${time}&groupByTime=${groupByTime}`, }).then(data => { return model.TotalRequestNum(data) }) }, fetchRequestCostTime: (id: string, time: string, groupByTime: string) => { return fetch({ url: `admin/app/requestCostTime?time=${time}&instanceId=${id}&groupByTime=${groupByTime}`, }).then(data => { return model.RequestCostTime(data) }) }, } export default application
the_stack
import { TransactionCollectorOptions, indexer as BaseIndexerModule, Output, OutPoint, TransactionWithStatus, } from "@ckb-lumos/base"; import { SearchKeyFilter, CKBIndexerQueryOptions, GetTransactionsResult, GetTransactionsResults, IOType, Order, TransactionWithIOType, GetTransactionRPCResult, } from "./type"; import { CkbIndexer } from "./indexer"; import { generateSearchKey, getHexStringBytes, instanceOfScriptWrapper, requestBatch, request, } from "./services"; interface GetTransactionDetailResult { objects: TransactionWithStatus[]; lastCursor: string | undefined; } export class CKBIndexerTransactionCollector extends BaseIndexerModule.TransactionCollector { filterOptions: TransactionCollectorOptions; constructor( public indexer: CkbIndexer, public queries: CKBIndexerQueryOptions, public CKBRpcUrl: string, public options?: TransactionCollectorOptions ) { super(indexer, queries, options); const defaultOptions: TransactionCollectorOptions = { skipMissing: false, includeStatus: true, }; this.filterOptions = { ...defaultOptions, ...this.options }; } /* *lock?: ScriptWrapper.script query by ckb-indexer,ScriptWrapper.ioType filter after get transaction from indexer, ScriptWrapper.argsLen filter after get transaction from rpc; *type?: ScriptWrapper.script query by ckb-indexer,ScriptWrapper.ioType filter after get transaction from indexer, ScriptWrapper.argsLen filter after get transaction from rpc; *data?: will not filter *argsLen?: filter after get transaction detail; *fromBlock?: query by ckb-indexer; *toBlock?: query by ckb-indexer; *skip?: filter after get transaction from ckb-indexer;; *order?: query by ckb-indexer; */ private async getTransactions( lastCursor?: string, ): Promise<GetTransactionDetailResult> { const searchKeyFilter: SearchKeyFilter = { sizeLimit: this.queries.bufferSize, order: this.queries.order as Order, }; if (lastCursor) { searchKeyFilter.lastCursor = lastCursor; } let transactionHashList: GetTransactionsResults = { objects: [], lastCursor: "", }; /* * if both lock and type exist,we need search them in independent and then get intersection * cause ckb-indexer use searchKey script on each cell but native indexer use lock and type on transaction, * and one transaction may have many cells both in input and output, more detail in test 'Test query transaction by both input lock and output type script' */ //if both lock and type, search search them in independent and then get intersection, GetTransactionsResults.lastCursor change to `${lockLastCursor}-${typeLastCursor}` if ( instanceOfScriptWrapper(this.queries.lock) && instanceOfScriptWrapper(this.queries.type) ) { transactionHashList = await this.getTransactionByLockAndTypeIndependent( searchKeyFilter ); lastCursor = transactionHashList.lastCursor; } else { //query by ScriptWrapper.script,block_range,order transactionHashList = await this.indexer.getTransactions( generateSearchKey(this.queries), searchKeyFilter ); lastCursor = transactionHashList.lastCursor; } // filter by ScriptWrapper.io_type transactionHashList.objects = this.filterByTypeIoTypeAndLockIoType( transactionHashList.objects, this.queries ); // return if transaction hash list if empty if (transactionHashList.objects.length === 0) { return { objects: [], lastCursor: lastCursor, }; } let transactionList: TransactionWithIOType[] = await this.getTransactionListFromRpc( transactionHashList ); for (const transactionWrapper of transactionList) { if (transactionWrapper.ioType === "input") { const targetOutPoint: OutPoint = transactionWrapper.transaction.inputs[ parseInt(transactionWrapper.ioIndex) ].previous_output; const targetCell = await this.getCellByOutPoint(targetOutPoint); transactionWrapper.inputCell = targetCell; } } //filter by ScriptWrapper.argsLen transactionList = transactionList.filter( (transactionWrapper: TransactionWithIOType) => { if ( transactionWrapper.ioType === "input" && transactionWrapper.inputCell ) { return this.isCellScriptArgsValid(transactionWrapper.inputCell); } else { const targetCell: Output = transactionWrapper.transaction.outputs[ parseInt(transactionWrapper.ioIndex) ]; return this.isCellScriptArgsValid(targetCell); } } ); const objects = transactionList.map((tx) => ({ transaction: tx.transaction, tx_status: tx.tx_status, })); return { objects: objects, lastCursor: lastCursor, }; } private async getTxHashesWithCursor(lastCursor?: string) { const searchKeyFilter: SearchKeyFilter = { sizeLimit: this.queries.bufferSize, order: this.queries.order as Order, }; if (lastCursor) { searchKeyFilter.lastCursor = lastCursor; } let transactionHashList: GetTransactionsResults = { objects: [], lastCursor: "", }; /* * if both lock and type exist,we need search them in independent and then get intersection * cause ckb-indexer use searchKey script on each cell but native indexer use lock and type on transaction, * and one transaction may have many cells both in input and output, more detail in test 'Test query transaction by both input lock and output type script' */ //if both lock and type, search search them in independent and then get intersection, GetTransactionsResults.lastCursor change to `${lockLastCursor}-${typeLastCursor}` if ( instanceOfScriptWrapper(this.queries.lock) && instanceOfScriptWrapper(this.queries.type) ) { transactionHashList = await this.getTransactionByLockAndTypeIndependent( searchKeyFilter ); lastCursor = transactionHashList.lastCursor; } else { //query by ScriptWrapper.script,block_range,order transactionHashList = await this.indexer.getTransactions( generateSearchKey(this.queries), searchKeyFilter ); lastCursor = transactionHashList.lastCursor; } // filter by ScriptWrapper.io_type transactionHashList.objects = this.filterByTypeIoTypeAndLockIoType( transactionHashList.objects, this.queries ); return transactionHashList; } private async getTransactionByLockAndTypeIndependent( searchKeyFilter: SearchKeyFilter ): Promise<GetTransactionsResults> { const queryWithTypeAdditionOptions = { ...searchKeyFilter }; const queryWithLockAdditionOptions = { ...searchKeyFilter }; if (searchKeyFilter.lastCursor) { const [lockLastCursor, typeLastCursor] = searchKeyFilter.lastCursor.split( "-" ); queryWithLockAdditionOptions.lastCursor = lockLastCursor; queryWithTypeAdditionOptions.lastCursor = typeLastCursor; } const queriesWithoutType = { ...this.queries, type: undefined }; const transactionByLock = await this.indexer.getTransactions( generateSearchKey(queriesWithoutType), queryWithTypeAdditionOptions ); const queriesWithoutLock = { ...this.queries, lock: undefined }; const transactionByType = await this.indexer.getTransactions( generateSearchKey(queriesWithoutLock), queryWithLockAdditionOptions ); const intersection = ( transactionList1: GetTransactionsResult[], transactionList2: GetTransactionsResult[] ) => { const result: GetTransactionsResult[] = []; transactionList1.forEach((tx1) => { const tx2 = transactionList2.find( (item) => item.tx_hash === tx1.tx_hash ); if (tx2) { // put the output io_type to intersection result, cause output have cells const targetTx = tx1.io_type === "output" ? tx1 : tx2; // change io_type to both cause targetTx exist both input and output result.push({ ...targetTx, io_type: "both" }); } }); return result; }; let hashList = intersection( transactionByType.objects, transactionByLock.objects ); const lastCursor = transactionByLock.lastCursor + "-" + transactionByType.lastCursor; const objects = hashList; return { objects, lastCursor }; } private getTransactionListFromRpc = async ( transactionHashList: GetTransactionsResults ) => { const getDetailRequestData = transactionHashList.objects.map( (hashItem: GetTransactionsResult, index: number) => { return { id: index, jsonrpc: "2.0", method: "get_transaction", params: [hashItem.tx_hash], }; } ); const transactionList: TransactionWithIOType[] = await requestBatch( this.CKBRpcUrl, getDetailRequestData ).then((response: GetTransactionRPCResult[]) => { return response.map( (item: GetTransactionRPCResult): TransactionWithIOType => { if (!this.filterOptions.skipMissing && !item.result) { throw new Error( `Transaction ${ transactionHashList.objects[item.id].tx_hash } is missing!` ); } const ioType = transactionHashList.objects[item.id].io_type; const ioIndex = transactionHashList.objects[item.id].io_index; return { ioType, ioIndex, ...item.result }; } ); }); return transactionList; }; private getCellByOutPoint = async (output: OutPoint) => { const res = await request( this.CKBRpcUrl, "get_transaction", [output.tx_hash] ); return res.transaction.outputs[parseInt(output.index)]; }; private isLockArgsLenMatched = ( args: string | undefined, argsLen?: number | "any" ) => { if (!argsLen) return true; if (argsLen === "any") return true; if (argsLen === -1) return true; return getHexStringBytes(args as string) === argsLen; }; // only valid after pass flow three validate private isCellScriptArgsValid = (targetCell: Output) => { if (this.queries.lock) { let lockArgsLen = instanceOfScriptWrapper(this.queries.lock) ? this.queries.lock.argsLen : this.queries.argsLen; if (!this.isLockArgsLenMatched(targetCell.lock.args, lockArgsLen)) { return false; } } if (this.queries.type && this.queries.type !== "empty") { let typeArgsLen = instanceOfScriptWrapper(this.queries.type) ? this.queries.type.argsLen : this.queries.argsLen; if (!this.isLockArgsLenMatched(targetCell.type?.args, typeArgsLen)) { return false; } } if (this.queries.type && this.queries.type === "empty") { if (targetCell.type) { return false; } } return true; }; private filterByIoType = ( inputResult: GetTransactionsResult[], ioType: IOType ) => { if (ioType === "both") { return inputResult; } if (ioType === "input" || ioType === "output") { return inputResult.filter( (item: GetTransactionsResult) => item.io_type === ioType || item.io_type === "both" ); } return inputResult; }; private filterByTypeIoTypeAndLockIoType = ( inputResult: GetTransactionsResult[], queries: CKBIndexerQueryOptions ) => { let result = inputResult; if (instanceOfScriptWrapper(queries.lock) && queries.lock.ioType) { result = this.filterByIoType(result, queries.lock.ioType); } if (instanceOfScriptWrapper(queries.type) && queries.type.ioType) { result = this.filterByIoType(result, queries.type.ioType); } return result; }; async count(): Promise<number> { let lastCursor: undefined | string = undefined; const getTxWithCursor = async (): Promise<TransactionWithStatus[]> => { const result: GetTransactionDetailResult = await this.getTransactions( lastCursor ); lastCursor = result.lastCursor; return result.objects; }; let counter = 0; //skip query result in first query let txs: TransactionWithStatus[] = await getTxWithCursor(); if (txs.length === 0) { return 0; } let buffer: Promise<TransactionWithStatus[]> = getTxWithCursor(); let index: number = 0; while (true) { if (this.queries.skip && index < this.queries.skip) { index++; continue; } counter += 1; index++; //reset index and exchange `txs` and `buffer` after count last tx if (index === txs.length) { index = 0; txs = await buffer; // break if can not get more txs if (txs.length === 0) { break; } buffer = getTxWithCursor(); } } return counter; } async getTransactionHashes(): Promise<string[]> { let lastCursor: undefined | string = undefined; const getTxWithCursor = async (): Promise<GetTransactionsResult[]> => { const result = await this.getTxHashesWithCursor( lastCursor ); lastCursor = result.lastCursor; return result.objects; }; let transactionHashes: string[] = []; //skip query result in first query let txs = await getTxWithCursor(); if (txs.length === 0) { return []; } let buffer = getTxWithCursor(); let index: number = 0; while (true) { if (this.queries.skip && index < this.queries.skip) { index++; continue; } if (txs[index]?.tx_hash) { transactionHashes.push(txs[index].tx_hash as string); } index++; //reset index and exchange `txs` and `buffer` after count last tx if (index === txs.length) { index = 0; txs = await buffer; // break if can not get more txs if (txs.length === 0) { break; } buffer = getTxWithCursor(); } } return transactionHashes; } async *collect() { let lastCursor: undefined | string = undefined; const getTxWithCursor = async (): Promise<TransactionWithStatus[]> => { const result: GetTransactionDetailResult = await this.getTransactions( lastCursor ); lastCursor = result.lastCursor; return result.objects; }; //skip query result in first query let txs: TransactionWithStatus[] = await getTxWithCursor(); if (txs.length === 0) { return 0; } let buffer: Promise<TransactionWithStatus[]> = getTxWithCursor(); let index: number = 0; while (true) { if (this.queries.skip && index < this.queries.skip) { index++; continue; } if (this.filterOptions.includeStatus) { yield txs[index]; } else { yield txs[index].transaction; } index++; //reset index and exchange `txs` and `buffer` after count last tx if (index === txs.length) { index = 0; txs = await buffer; // break if can not get more txs if (txs.length === 0) { break; } buffer = getTxWithCursor(); } } } }
the_stack
import { Component, OnInit, Renderer2, ViewChild } from '@angular/core'; import { IgxGridComponent, RowType, IgxTreeGridComponent, IgxHierarchicalGridComponent, IPinningConfig, RowPinningPosition, IRowDragStartEventArgs, GridSummaryCalculationMode, GridSummaryPosition } from 'igniteui-angular'; import { HIERARCHICAL_SAMPLE_DATA } from '../shared/sample-data'; @Component({ selector: 'app-grid-row-api-sample', styleUrls: ['grid-row-api.sample.css'], templateUrl: 'grid-row-api.sample.html' }) export class GridRowAPISampleComponent implements OnInit { @ViewChild('grid', { static: true }) private grid: IgxGridComponent; @ViewChild('targetGrid', { static: true }) private targetGrid: IgxGridComponent; @ViewChild('treeGridHier', { static: true }) private treeGridHier: IgxTreeGridComponent; @ViewChild('hGrid', { static: true }) private hGrid: IgxTreeGridComponent; public countIcon = 'drag_indicator'; public dragIcon = 'arrow_right_alt'; public data2: any; public data: any[]; public treeGridHierData: any[]; public hierarchicalData: any[]; public columns: any[]; public hColumns: any[]; public treeGridHierColumns: any[]; public treeColumns: any[]; public treeData: any[]; public index = 0; public tIndex = 0; public tHIndex = 0; public hIndex = 0; public key = ''; public tKey = ''; public tHKey = ''; public hKey = ''; public pinningConfig: IPinningConfig = { rows: RowPinningPosition.Top }; constructor(private renderer: Renderer2) { } public ngOnInit(): void { this.grid.summaryCalculationMode = GridSummaryCalculationMode.childLevelsOnly; this.grid.summaryPosition = GridSummaryPosition.bottom; this.treeGridHier.summaryCalculationMode = GridSummaryCalculationMode.childLevelsOnly; this.columns = [ { field: 'ID', width: '200px', hidden: true }, { field: 'CompanyName', width: '200px', groupable: true }, { field: 'ContactName', width: '200px', pinned: false, groupable: true }, { field: 'ContactTitle', width: '300px', pinned: false, groupable: true }, { field: 'Address', width: '250px' }, { field: 'City', width: '200px' }, { field: 'Region', width: '300px' }, { field: 'PostalCode', width: '150px' }, { field: 'Phone', width: '200px' }, { field: 'Fax', width: '200px' } ]; this.hColumns = [ { field: 'ID', width: '200px' }, { field: 'ChildLevels', width: '200px' }, { field: 'ProductName', width: '200px' }, { field: 'Col1', width: '200px' }, { field: 'Col2', width: '200px' }, { field: 'Col3', width: '200px' }, { field: 'childData', width: '200px' }, { field: 'childData2', width: '200px' }, { field: 'hasChild', width: '200px' } ]; this.treeGridHierColumns = [ { field: 'ID', width: 200, resizable: true, movable: true, pinned: true }, { field: 'CompanyName', width: 150, resizable: true, movable: true }, { field: 'ContactName', width: 150, resizable: true, movable: true }, { field: 'ContactTitle', width: 150, resizable: true, movable: true }, { field: 'Address', width: 150, resizable: true, movable: true }, { field: 'City', width: 150, resizable: true, movable: true, summary: true }, { field: 'Region', width: 150, resizable: true, movable: true }, { field: 'PostalCode', width: 150, resizable: true, movable: true }, { field: 'Phone', width: 150, resizable: true, movable: true }, { field: 'Fax', width: 150, resizable: true, movable: true } ]; this.treeGridHierData = HIERARCHICAL_SAMPLE_DATA.slice(0); this.data = [ /* eslint-disable max-len */ { ID: 'ALFKI', CompanyName: 'Alfreds Futterkiste', ContactName: 'Maria Anders', ContactTitle: 'Sales Representative', Address: 'Obere Str. 57', City: 'Berlin', Region: null, PostalCode: '12209', Country: 'Germany', Phone: '030-0074321', Fax: '030-0076545' }, { ID: 'ANATR', CompanyName: 'Ana Trujillo Emparedados y helados', ContactName: 'Ana Trujillo', ContactTitle: 'Owner', Address: 'Avda. de la Constitución 2222', City: 'México D.F.', Region: null, PostalCode: '05021', Country: 'Mexico', Phone: '(5) 555-4729', Fax: '(5) 555-3745' }, { ID: 'ANTON', CompanyName: 'Antonio Moreno Taquería', ContactName: 'Antonio Moreno', ContactTitle: 'Owner', Address: 'Mataderos 2312', City: 'México D.F.', Region: null, PostalCode: '05023', Country: 'Mexico', Phone: '(5) 555-3932', Fax: null }, { ID: 'AROUT', CompanyName: 'Around the Horn', ContactName: 'Thomas Hardy', ContactTitle: 'Sales Representative', Address: '120 Hanover Sq.', City: 'London', Region: null, PostalCode: 'WA1 1DP', Country: 'UK', Phone: '(171) 555-7788', Fax: '(171) 555-6750' }, { ID: 'BERGS', CompanyName: 'Berglunds snabbköp', ContactName: 'Christina Berglund', ContactTitle: 'Order Administrator', Address: 'Berguvsvägen 8', City: 'Luleå', Region: null, PostalCode: 'S-958 22', Country: 'Sweden', Phone: '0921-12 34 65', Fax: '0921-12 34 67' }, { ID: 'BLAUS', CompanyName: 'Blauer See Delikatessen', ContactName: 'Hanna Moos', ContactTitle: 'Sales Representative', Address: 'Forsterstr. 57', City: 'Mannheim', Region: null, PostalCode: '68306', Country: 'Germany', Phone: '0621-08460', Fax: '0621-08924' }, { ID: 'BLONP', CompanyName: 'Blondesddsl père et fils', ContactName: 'Frédérique Citeaux', ContactTitle: 'Marketing Manager', Address: '24, place Kléber', City: 'Strasbourg', Region: null, PostalCode: '67000', Country: 'France', Phone: '88.60.15.31', Fax: '88.60.15.32' }, { ID: 'BOLID', CompanyName: 'Bólido Comidas preparadas', ContactName: 'Martín Sommer', ContactTitle: 'Owner', Address: 'C/ Araquil, 67', City: 'Madrid', Region: null, PostalCode: '28023', Country: 'Spain', Phone: '(91) 555 22 82', Fax: '(91) 555 91 99' }, { ID: 'BONAP', CompanyName: 'Bon app\'', ContactName: 'Laurence Lebihan', ContactTitle: 'Owner', Address: '12, rue des Bouchers', City: 'Marseille', Region: null, PostalCode: '13008', Country: 'France', Phone: '91.24.45.40', Fax: '91.24.45.41' }, { ID: 'BOTTM', CompanyName: 'Bottom-Dollar Markets', ContactName: 'Elizabeth Lincoln', ContactTitle: 'Accounting Manager', Address: '23 Tsawassen Blvd.', City: 'Tsawassen', Region: 'BC', PostalCode: 'T2F 8M4', Country: 'Canada', Phone: '(604) 555-4729', Fax: '(604) 555-3745' }, { ID: 'BSBEV', CompanyName: 'B\'s Beverages', ContactName: 'Victoria Ashworth', ContactTitle: 'Sales Representative', Address: 'Fauntleroy Circus', City: 'London', Region: null, PostalCode: 'EC2 5NT', Country: 'UK', Phone: '(171) 555-1212', Fax: null }, { ID: 'CACTU', CompanyName: 'Cactus Comidas para llevar', ContactName: 'Patricio Simpson', ContactTitle: 'Sales Agent', Address: 'Cerrito 333', City: 'Buenos Aires', Region: null, PostalCode: '1010', Country: 'Argentina', Phone: '(1) 135-5555', Fax: '(1) 135-4892' }, { ID: 'CENTC', CompanyName: 'Centro comercial Moctezuma', ContactName: 'Francisco Chang', ContactTitle: 'Marketing Manager', Address: 'Sierras de Granada 9993', City: 'México D.F.', Region: null, PostalCode: '05022', Country: 'Mexico', Phone: '(5) 555-3392', Fax: '(5) 555-7293' }, { ID: 'CHOPS', CompanyName: 'Chop-suey Chinese', ContactName: 'Yang Wang', ContactTitle: 'Owner', Address: 'Hauptstr. 29', City: 'Bern', Region: null, PostalCode: '3012', Country: 'Switzerland', Phone: '0452-076545', Fax: null }, { ID: 'COMMI', CompanyName: 'Comércio Mineiro', ContactName: 'Pedro Afonso', ContactTitle: 'Sales Associate', Address: 'Av. dos Lusíadas, 23', City: 'Sao Paulo', Region: 'SP', PostalCode: '05432-043', Country: 'Brazil', Phone: '(11) 555-7647', Fax: null }, { ID: 'CONSH', CompanyName: 'Consolidated Holdings', ContactName: 'Elizabeth Brown', ContactTitle: 'Sales Representative', Address: 'Berkeley Gardens 12 Brewery', City: 'London', Region: null, PostalCode: 'WX1 6LT', Country: 'UK', Phone: '(171) 555-2282', Fax: '(171) 555-9199' }, { ID: 'DRACD', CompanyName: 'Drachenblut Delikatessen', ContactName: 'Sven Ottlieb', ContactTitle: 'Order Administrator', Address: 'Walserweg 21', City: 'Aachen', Region: null, PostalCode: '52066', Country: 'Germany', Phone: '0241-039123', Fax: '0241-059428' }, { ID: 'DUMON', CompanyName: 'Du monde entier', ContactName: 'Janine Labrune', ContactTitle: 'Owner', Address: '67, rue des Cinquante Otages', City: 'Nantes', Region: null, PostalCode: '44000', Country: 'France', Phone: '40.67.88.88', Fax: '40.67.89.89' }, { ID: 'EASTC', CompanyName: 'Eastern Connection', ContactName: 'Ann Devon', ContactTitle: 'Sales Agent', Address: '35 King George', City: 'London', Region: null, PostalCode: 'WX3 6FW', Country: 'UK', Phone: '(171) 555-0297', Fax: '(171) 555-3373' }, { ID: 'ERNSH', CompanyName: 'Ernst Handel', ContactName: 'Roland Mendel', ContactTitle: 'Sales Manager', Address: 'Kirchgasse 6', City: 'Graz', Region: null, PostalCode: '8010', Country: 'Austria', Phone: '7675-3425', Fax: '7675-3426' }, { ID: 'FAMIA', CompanyName: 'Familia Arquibaldo', ContactName: 'Aria Cruz', ContactTitle: 'Marketing Assistant', Address: 'Rua Orós, 92', City: 'Sao Paulo', Region: 'SP', PostalCode: '05442-030', Country: 'Brazil', Phone: '(11) 555-9857', Fax: null }, { ID: 'FISSA', CompanyName: 'FISSA Fabrica Inter. Salchichas S.A.', ContactName: 'Diego Roel', ContactTitle: 'Accounting Manager', Address: 'C/ Moralzarzal, 86', City: 'Madrid', Region: null, PostalCode: '28034', Country: 'Spain', Phone: '(91) 555 94 44', Fax: '(91) 555 55 93' }, { ID: 'FOLIG', CompanyName: 'Folies gourmandes', ContactName: 'Martine Rancé', ContactTitle: 'Assistant Sales Agent', Address: '184, chaussée de Tournai', City: 'Lille', Region: null, PostalCode: '59000', Country: 'France', Phone: '20.16.10.16', Fax: '20.16.10.17' }, { ID: 'FOLKO', CompanyName: 'Folk och fä HB', ContactName: 'Maria Larsson', ContactTitle: 'Owner', Address: 'Åkergatan 24', City: 'Bräcke', Region: null, PostalCode: 'S-844 67', Country: 'Sweden', Phone: '0695-34 67 21', Fax: null }, { ID: 'FRANK', CompanyName: 'Frankenversand', ContactName: 'Peter Franken', ContactTitle: 'Marketing Manager', Address: 'Berliner Platz 43', City: 'München', Region: null, PostalCode: '80805', Country: 'Germany', Phone: '089-0877310', Fax: '089-0877451' }, { ID: 'FRANR', CompanyName: 'France restauration', ContactName: 'Carine Schmitt', ContactTitle: 'Marketing Manager', Address: '54, rue Royale', City: 'Nantes', Region: null, PostalCode: '44000', Country: 'France', Phone: '40.32.21.21', Fax: '40.32.21.20' }, { ID: 'FRANS', CompanyName: 'Franchi S.p.A.', ContactName: 'Paolo Accorti', ContactTitle: 'Sales Representative', Address: 'Via Monte Bianco 34', City: 'Torino', Region: null, PostalCode: '10100', Country: 'Italy', Phone: '011-4988260', Fax: '011-4988261' } ]; this.hierarchicalData = this.generateDataUneven(100, 3); // treegrid cols and data this.treeColumns = [ { field: 'employeeID', label: 'ID', width: 200, resizable: true, movable: true, dataType: 'number', hasSummary: false }, { field: 'Salary', label: 'Salary', width: 200, resizable: true, movable: true, dataType: 'number', hasSummary: true }, { field: 'firstName', label: 'First Name', width: 300, resizable: true, movable: true, dataType: 'string', hasSummary: false }, { field: 'lastName', label: 'Last Name', width: 150, resizable: true, movable: true, dataType: 'string', hasSummary: false }, { field: 'Title', label: 'Title', width: 200, resizable: true, movable: true, dataType: 'string', hasSummary: true } ]; this.treeData = [ { Salary: 2500, employeeID: 0, PID: -1, firstName: 'Andrew', lastName: 'Fuller', Title: 'Vice President, Sales' }, { Salary: 3500, employeeID: 1, PID: -1, firstName: 'Jonathan', lastName: 'Smith', Title: 'Human resources' }, { Salary: 1500, employeeID: 2, PID: -1, firstName: 'Nancy', lastName: 'Davolio', Title: 'CFO' }, { Salary: 2500, employeeID: 3, PID: -1, firstName: 'Steven', lastName: 'Buchanan', Title: 'CTO' }, // sub of ID 0 { Salary: 2500, employeeID: 4, PID: 0, firstName: 'Janet', lastName: 'Leverling', Title: 'Sales Manager' }, { Salary: 3500, employeeID: 5, PID: 0, firstName: 'Laura', lastName: 'Callahan', Title: 'Inside Sales Coordinator' }, { Salary: 1500, employeeID: 6, PID: 0, firstName: 'Margaret', lastName: 'Peacock', Title: 'Sales Representative' }, { Salary: 2500, employeeID: 7, PID: 0, firstName: 'Michael', lastName: 'Suyama', Title: 'Sales Representative' }, // sub of ID 4 { Salary: 2500, employeeID: 8, PID: 4, firstName: 'Anne', lastName: 'Dodsworth', Title: 'Sales Representative' }, { Salary: 3500, employeeID: 9, PID: 4, firstName: 'Danielle', lastName: 'Davis', Title: 'Sales Representative' }, { Salary: 1500, employeeID: 10, PID: 4, firstName: 'Robert', lastName: 'King', Title: 'Sales Representative' }, // sub of ID 2 { Salary: 2500, employeeID: 11, PID: 2, firstName: 'Peter', lastName: 'Lewis', Title: 'Chief Accountant' }, { Salary: 3500, employeeID: 12, PID: 2, firstName: 'Ryder', lastName: 'Zenaida', Title: 'Accountant' }, { Salary: 1500, employeeID: 13, PID: 2, firstName: 'Wang', lastName: 'Mercedes', Title: 'Accountant' }, // sub of ID 3 { Salary: 1500, employeeID: 14, PID: 3, firstName: 'Theodore', lastName: 'Zia', Title: 'Software Architect' }, { Salary: 4500, employeeID: 15, PID: 3, firstName: 'Lacota', lastName: 'Mufutau', Title: 'Product Manager' }, // sub of ID 16 { Salary: 2500, employeeID: 16, PID: 15, firstName: 'Jin', lastName: 'Elliott', Title: 'Product Owner' }, { Salary: 3500, employeeID: 17, PID: 15, firstName: 'Armand', lastName: 'Ross', Title: 'Product Owner' }, { Salary: 1500, employeeID: 18, PID: 15, firstName: 'Dane', lastName: 'Rodriquez', Title: 'Team Leader' }, // sub of ID 19 { Salary: 2500, employeeID: 19, PID: 18, firstName: 'Declan', lastName: 'Lester', Title: 'Senior Software Developer' }, { Salary: 3500, employeeID: 20, PID: 18, firstName: 'Bernard', lastName: 'Jarvis', Title: 'Senior Software Developer' }, { Salary: 1500, employeeID: 21, PID: 18, firstName: 'Jason', lastName: 'Clark', Title: 'QA' }, { Salary: 1500, employeeID: 22, PID: 18, firstName: 'Mark', lastName: 'Young', Title: 'QA' }, // sub of ID 20 { Salary: 1500, employeeID: 23, PID: 20, firstName: 'Jeremy', lastName: 'Donaldson', Title: 'Software Developer' } ]; /* eslint-enable max-len */ } public togglePinning(grid: IgxGridComponent | IgxTreeGridComponent | IgxHierarchicalGridComponent, byIndex: boolean, index: number, key: any) { const row: RowType = byIndex ? grid.getRowByIndex(index) : grid.getRowByKey(key); const index2: number = row.index; if (row.pinned) { row.unpin(); } else { row.pin(); } } public deleteRow(grid: IgxGridComponent | IgxTreeGridComponent | IgxHierarchicalGridComponent, index: number) { const row = grid.getRowByIndex(index); row.delete(); } public toggle(grid: IgxGridComponent | IgxTreeGridComponent | IgxHierarchicalGridComponent, index: number) { const row = grid.getRowByIndex(index); row.expanded = !row.expanded; } public select(grid: IgxGridComponent | IgxTreeGridComponent | IgxHierarchicalGridComponent, index: number) { const row = grid.getRowByIndex(index); row.selected = !row.selected; } public selectChildren(grid: IgxGridComponent | IgxTreeGridComponent, index: number) { const row = grid.getRowByIndex(index); const children = row.children; children.forEach(ch => { ch.selected = !ch.selected; }); } public selectParent(grid: IgxGridComponent | IgxTreeGridComponent, index: number) { const row = grid.getRowByIndex(index); const parent = row.parent; parent.selected = !parent.selected; } public generateDataUneven(count: number, level: number, parendID: string = null) { const prods = []; const currLevel = level; let children; for (let i = 0; i < count; i++) { const rowID = parendID ? parendID + i : i.toString(); if (level > 0) { // Have child grids for row with even id less rows by not multiplying by 2 children = this.generateDataUneven(((i % 2) + 1) * Math.round(count / 3), currLevel - 1, rowID); } prods.push({ ID: rowID, ChildLevels: currLevel, ProductName: 'Product: A' + i, Col1: i, Col2: i, Col3: i, childData: children, childData2: children, hasChild: true }); } return prods; } public clearLog(logger: HTMLElement) { const elements = logger.querySelectorAll('p'); elements.forEach(element => { this.renderer.removeChild(logger, element); }); } public logState(grid: IgxGridComponent | IgxTreeGridComponent | IgxHierarchicalGridComponent, index: number, logger: HTMLElement) { this.clearLog(logger); const row = grid.getRowByIndex(index); const state = ` index: ${row.index}, viewIndex: ${row.viewIndex}, -----------------------------, isSummaryRow: ${row.isSummaryRow}, summaries: ${row.summaries}, -----------------------------, isGroupByRow: ${row.isGroupByRow}, groupByRow: ${row.groupRow?.value}, -----------------------------, parent: ${row.parent}, expanded: ${row.expanded}, key: ${row.key}, pinned: ${row.pinned}, deleted: ${row.deleted}, inEditMode: ${row.inEditMode}, selected: ${row.selected}, hasChildren: ${row.hasChildren}, disabled: ${row.disabled}, --------------------------------, cells.length: ${row.cells?.length}`; // firstCell: ${row.cells[0].value}, // lastCell: ${row.cells[row.cells.length - 1].value}`; const states = state.split(','); const createElem = this.renderer.createElement('p'); states.forEach(st => { const text = this.renderer.createText(st); this.renderer.appendChild(createElem, text); this.renderer.appendChild(createElem, this.renderer.createElement('br')); }); this.renderer.insertBefore(logger, createElem, logger.children[0]); } public onRowDragEnd(args) { args.animation = true; } public onDropAllowed(args) { let selected = false; const ids = this.grid.selectedRows; const selectedRowData = this.grid.data.filter((record) => ids.includes(record.ID)); selectedRowData.forEach((rowData) => { selected = true; this.targetGrid.addRow(rowData); this.grid.deleteRow(rowData.ID); }); if (selected === false) { this.targetGrid.addRow(args.dragData.rowData); // this.grid.deleteRow(args.dragData.rowID); } } public onEnter(args) { this.dragIcon = 'add'; } public onRowDragStart(args: IRowDragStartEventArgs) { const row = args.dragData; const count = this.grid.selectedRows.length || 1; this.countIcon = `filter_${count > 9 ? '9_plus' : `${count}`}`; } public onLeave(args) { this.onRowDragStart(args); this.dragIcon = 'arrow_right_alt'; } }
the_stack
import { Utility } from "../../utility/Utility"; export interface IMathematicsHelper { // ---- NOTE-REFERENCE ---- https://en.wikipedia.org/wiki/Softmax_function softmaxSingleFunction(inputs: number[], index: number): number; smoothArgmaxApproximationSingleFunction(inputs: number[], index: number): number; // ---- NOTE-REFERENCE ---- https://en.wikipedia.org/wiki/Softmax_function softmaxFunction(inputs: number[]): number[]; smoothArgmaxApproximationFunction(inputs: number[]): number[]; // ---- NOTE-REFERENCE ---- https://en.wikipedia.org/wiki/LogSumExp logsumexpStrictConvexSingleFunction(inputs: number[]): number; smoothMaxApproximationStrictConvexFunction(inputs: number[]): number; // ---- NOTE-REFERENCE ---- https://en.wikipedia.org/wiki/LogSumExp logsumexpSingleFunction(inputs: number[]): number; smoothMaxApproximationFunction(inputs: number[]): number; sigmoidLogisticGradientFunction(input: number): number; sigmoidLogisticFunction(input: number): number; sigmoidHyperbolicTangentFunction(input: number): number; sigmoidArctangentFunction(input: number): number; sigmoidGudermannianFunction(input: number): number; sigmoidGeneralizedLogisticFunction(input: number, alpha: number): number; sigmoidAlgebraicFunction(input: number): number; getL1Regularized(weight: number, l1Regularization: number): number; getL2Regularized(weight: number, l2Regularization: number): number; getL1l2RegularizedWeightOptimizedSparse( weight: number, l1Regularization: number, l2Regularization: number): number; getL1l2RegularizedWeightOptimizedDense( weight: number, l1Regularization: number, l2Regularization: number): number; /* * return: * softmaxVectors: number[][]: * update: * matrixWeightDenseArrays * biasVectorDenseValueArray * input: * instanceGroundTruthPositiveLabelIndexes: * Each element is a label index. * Dimension: N, N: #instances. * instanceFeatureVectorSparseIndexArrays: * Each row represents a sparse feature, one-hot-encoder vector for an input instance. * #rows is the number of input instances * #columns is the number of space feature index for that row/instance. * There is no limit to the length of each row, as long as the elements, feature indexes, * fall in the feature range [0, #features). * Dimension: N X iF, N: #instances, iF: indefinite #features. * matrixWeightDenseArrays: * Each row represents a dense feature, floating-point weight vector for a label. * Row length is equal to #features. * Dimension: L x F, L: #labels, F: #features. * biasVectorDenseValueArray: * A bias vector, each element is for a label. * #biases is equal to #labels. * Dimension: L, L: #labels. * learningRate: * learning rate for SGD. * l1Regularization: * l1 regularization coefficient. * l2Regularization: * l2 regularization coefficient. * instanceFeatureVectorIndexBegin: * The begin index for a mini batch. * instanceFeatureVectorIndexEnd: * The end index for a mini batch. * internal data structure: * matrixWeightGradientDenseArrays: * Each row represents a dense feature gradient vector for a label. * Row length is equal to #features. * Dimension: L x F, L: #labels, F: #features. * biasVectorGradientDenseValueArray: * Each element represents a bias-term gradient for a label. * #biases is equal to #labels. * Dimension: L, L: #labels. */ softmaxLogLossGradientUpdate( instanceGroundTruthPositiveLabelIndexes: number[], instanceFeatureVectorSparseIndexArrays: number[][], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[], learningRate: number, l1Regularization: number, l2Regularization: number, instanceFeatureVectorIndexBegin: number, instanceFeatureVectorIndexEnd: number): number[][]; logLoss( probabilityVector: number[], instanceGroundTruthPositiveLabelIndex: number): number; logLossGeneric( probabilityVector: number[], labelVector: number[]): number; softmaxLogLoss( softmaxVectors: number[][], instanceGroundTruthPositiveLabelIndexes: number[]): number; softmaxLogLossGeneric( softmaxVectors: number[][], labelVectors: number[][]): number; matrixVectorProductSoftmaxSparseIndexesValues( instanceFeatureVectorSparseIndexArrays: number[][], instanceFeatureVectorSparseValueArrays: number[][], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[], instanceFeatureVectorIndexBegin: number, instanceFeatureVectorIndexEnd: number): number[][]; /* * return: * softmaxVectors: * Each row is a softmax vector for an input instance. * #rows is equivalent to #labels. * Dimension: N X L, N: #instances, L: #labels. * inputs: * instanceFeatureVectorSparseIndexArrays: * Each row represents a sparse feature, one-hot-encoder vector for an input instance. * #rows is the number of input instances * #columns is the number of space feature index for that row/instance. * There is no limit to the length of each row, as long as the elements, feature indexes, * fall in the feature range [0, #features). * Dimension: N X iF, N: #instances, iF: indefinite #features. * matrixWeightDenseArrays: * Each row represents a dense feature, floating-point weight vector for a label. * Row length is equal to #features. * Dimension: L x F, L: #labels, F: #features. * biasVectorDenseValueArray: * A bias vector, each element is for a label. * #biases is equal to #labels. * Dimension: L, L: #labels. * instanceFeatureVectorIndexBegin: * The begin index for a mini batch. * instanceFeatureVectorIndexEnd: * The end index for a mini batch. */ matrixVectorProductSoftmaxSparseIndexes( instanceFeatureVectorSparseIndexArrays: number[][], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[], instanceFeatureVectorIndexBegin: number, instanceFeatureVectorIndexEnd: number): number[][]; /* * return: * softmaxVectors: * Each row is a softmax vector for an input instance. * #rows is equivalent to #labels. * Dimension: N X L, N: #instances, L: #labels. * inputs: * instanceFeatureVectorDenseValueArrays: * Each row represents a dense feature value vector for an input instance. * #rows is the number of input instances * #columns is the number of dense features for that row/instance. * There is no limit to the length of each row should be equal to the number of features. * Dimension: N X F, N: #instances, F: #features. * matrixWeightDenseArrays: * Each row represents a dense feature, floating-point weight vector for a label. * Row length is equal to #features. * Dimension: L x F, L: #labels, F: #features. * biasVectorDenseValueArray: * A bias vector, each element is for a label. * #biases is equal to #labels. * Dimension: L, L: #labels. * instanceFeatureVectorIndexBegin: * The begin index for a mini batch. * instanceFeatureVectorIndexEnd: * The end index for a mini batch. */ matrixVectorProductSoftmaxDenseValues( instanceFeatureVectorDenseValueArrays: number[][], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[], instanceFeatureVectorIndexBegin: number, instanceFeatureVectorIndexEnd: number): number[][]; matrixVectorProductSparseIndexesValues( instanceFeatureVectorSparseIndexArray: number[], instanceFeatureVectorSparseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; matrixVectorProductSparseIndexes( instanceFeatureVectorSparseIndexArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; matrixVectorProductDenseValues( vectorDenseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; matrixVectorProductSparseIndexesValuesTo( matrixVectorProduct: number[], instanceFeatureVectorSparseIndexArray: number[], instanceFeatureVectorSparseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; matrixVectorProductSparseIndexesTo( matrixVectorProduct: number[], instanceFeatureVectorSparseIndexArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; matrixVectorProductDenseValuesTo( matrixVectorProduct: number[], vectorDenseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductSparseIndexesValues( instanceFeatureVectorSparseIndexArray: number[], instanceFeatureVectorSparseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductSparseIndexes( instanceFeatureVectorSparseIndexArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductDenseValues( vectorDenseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductSparseIndexesValuesTo( vectorMatrixProduct: number[], instanceFeatureVectorSparseIndexArray: number[], instanceFeatureVectorSparseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductSparseIndexesTo( vectorMatrixProduct: number[], instanceFeatureVectorSparseIndexArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; vectorMatrixProductDenseValuesTo( vectorMatrixProduct: number[], vectorDenseValueArray: number[], matrixWeightDenseArrays: number[][], biasVectorDenseValueArray: number[]): number[]; dotProductSparseIndexesValues( sparseIndexArray: number[], sparseValueArray: number[], weights: number[], weightBias: number): number; dotProductSparseIndexes( sparseIndexArray: number[], weights: number[], weightBias: number): number; dotProductDenseValues( denseValueArray: number[], weights: number[], weightBias: number): number; matrixDenseSubtractScaledFromAndL1l2RegularizedSparseTo( denseValueArray0: number[][], denseValueArray1: number[][], constant: number, l1Regularization: number, l2Regularization: number): number[][]; matrixDenseSubtractScaledFromAndL1l2RegularizedDenseTo( denseValueArray0: number[][], denseValueArray1: number[][], constant: number, l1Regularization: number, l2Regularization: number): number[][]; vectorDenseSubtractScaledFromAndL1l2RegularizedSparseTo( denseValueArray0: number[], denseValueArray1: number[], constant: number, l1Regularization: number, l2Regularization: number): number[]; vectorDenseSubtractScaledFromAndL1l2RegularizedDenseTo( denseValueArray0: number[], denseValueArray1: number[], constant: number, l1Regularization: number, l2Regularization: number): number[]; matrixDenseL1l2RegularizedSparseTo( denseValueArray: number[][], l1Regularization: number, l2Regularization: number): number[][]; matrixDenseL1l2RegularizedDenseTo( denseValueArray: number[][], l1Regularization: number, l2Regularization: number): number[][]; vectorDenseL1l2RegularizedSparseTo( denseValueArray: number[], l1Regularization: number, l2Regularization: number): number[]; vectorDenseL1l2RegularizedDenseTo( denseValueArray: number[], l1Regularization: number, l2Regularization: number): number[]; tensor4dDenseAssignRandomTo( denseValueArray0: number[][][][]): number[][][][]; tensor4dDenseAssignConstantTo( denseValueArray0: number[][][][], constant: number): number[][][][]; tensor4dDenseAddConstantTo( denseValueArray0: number[][][][], constant: number): number[][][][]; tensor4dDenseMultiplyConstantTo( denseValueArray0: number[][][][], constant: number): number[][][][]; tensor4dDenseSubtractConstantFrom( denseValueArray0: number[][][][], constant: number): number[][][][]; tensor4dDenseDivideConstantFrom( denseValueArray0: number[][][][], constant: number): number[][][][]; tensor4dDenseAssignTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][]): number[][][][]; tensor4dDenseAddTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][]): number[][][][]; tensor4dDenseMultiplyTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][]): number[][][][]; tensor4dDenseSubtractFrom( denseValueArray0: number[][][][], denseValueArray1: number[][][][]): number[][][][]; tensor4dDenseDivideFrom( denseValueArray0: number[][][][], denseValueArray1: number[][][][]): number[][][][]; tensor4dDenseAssignScaledTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][], constant: number): number[][][][]; tensor4dDenseAddScaledTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][], constant: number): number[][][][]; tensor4dDenseMultiplyScaledTo( denseValueArray0: number[][][][], denseValueArray1: number[][][][], constant: number): number[][][][]; tensor4dDenseSubtractScaledFrom( denseValueArray0: number[][][][], denseValueArray1: number[][][][], constant: number): number[][][][]; tensor4dDenseDivideScaledFrom( denseValueArray0: number[][][][], denseValueArray1: number[][][][], constant: number): number[][][][]; tensor3dDenseAssignRandomTo( denseValueArray0: number[][][]): number[][][]; tensor3dDenseAssignConstantTo( denseValueArray0: number[][][], constant: number): number[][][]; tensor3dDenseAddConstantTo( denseValueArray0: number[][][], constant: number): number[][][]; tensor3dDenseMultiplyConstantTo( denseValueArray0: number[][][], constant: number): number[][][]; tensor3dDenseSubtractConstantFrom( denseValueArray0: number[][][], constant: number): number[][][]; tensor3dDenseDivideConstantFrom( denseValueArray0: number[][][], constant: number): number[][][]; tensor3dDenseAssignTo( denseValueArray0: number[][][], denseValueArray1: number[][][]): number[][][]; tensor3dDenseAddTo( denseValueArray0: number[][][], denseValueArray1: number[][][]): number[][][]; tensor3dDenseMultiplyTo( denseValueArray0: number[][][], denseValueArray1: number[][][]): number[][][]; tensor3dDenseSubtractFrom( denseValueArray0: number[][][], denseValueArray1: number[][][]): number[][][]; tensor3dDenseDivideFrom( denseValueArray0: number[][][], denseValueArray1: number[][][]): number[][][]; tensor3dDenseAssignScaledTo( denseValueArray0: number[][][], denseValueArray1: number[][][], constant: number): number[][][]; tensor3dDenseAddScaledTo( denseValueArray0: number[][][], denseValueArray1: number[][][], constant: number): number[][][]; tensor3dDenseMultiplyScaledTo( denseValueArray0: number[][][], denseValueArray1: number[][][], constant: number): number[][][]; tensor3dDenseSubtractScaledFrom( denseValueArray0: number[][][], denseValueArray1: number[][][], constant: number): number[][][]; tensor3dDenseDivideScaledFrom( denseValueArray0: number[][][], denseValueArray1: number[][][], constant: number): number[][][]; matrixDenseAssignRandomTo( denseValueArray0: number[][]): number[][]; matrixDenseAssignConstantTo( denseValueArray0: number[][], constant: number): number[][]; matrixDenseAddConstantTo( denseValueArray0: number[][], constant: number): number[][]; matrixDenseMultiplyConstantTo( denseValueArray0: number[][], constant: number): number[][]; matrixDenseSubtractConstantFrom( denseValueArray0: number[][], constant: number): number[][]; matrixDenseDivideConstantFrom( denseValueArray0: number[][], constant: number): number[][]; matrixDenseAssignTo( denseValueArray0: number[][], denseValueArray1: number[][]): number[][]; matrixDenseAddTo( denseValueArray0: number[][], denseValueArray1: number[][]): number[][]; matrixDenseMultiplyTo( denseValueArray0: number[][], denseValueArray1: number[][]): number[][]; matrixDenseSubtractFrom( denseValueArray0: number[][], denseValueArray1: number[][]): number[][]; matrixDenseDivideFrom( denseValueArray0: number[][], denseValueArray1: number[][]): number[][]; matrixDenseAssignScaledTo( denseValueArray0: number[][], denseValueArray1: number[][], constant: number): number[][]; matrixDenseAddScaledTo( denseValueArray0: number[][], denseValueArray1: number[][], constant: number): number[][]; matrixDenseMultiplyScaledTo( denseValueArray0: number[][], denseValueArray1: number[][], constant: number): number[][]; matrixDenseSubtractScaledFrom( denseValueArray0: number[][], denseValueArray1: number[][], constant: number): number[][]; matrixDenseDivideScaledFrom( denseValueArray0: number[][], denseValueArray1: number[][], constant: number): number[][]; vectorDenseAssignRandomTo( denseValueArray0: number[]): number[]; vectorDenseAssignConstantTo( denseValueArray0: number[], constant: number): number[]; vectorDenseAddConstantTo( denseValueArray0: number[], constant: number): number[]; vectorDenseMultiplyConstantTo( denseValueArray0: number[], constant: number): number[]; vectorDenseSubtractConstantFrom( denseValueArray0: number[], constant: number): number[]; vectorDenseDivideConstantFrom( denseValueArray0: number[], constant: number): number[]; vectorDenseAssignTo( denseValueArray0: number[], denseValueArray1: number[]): number[]; vectorDenseAddTo( denseValueArray0: number[], denseValueArray1: number[]): number[]; vectorDenseMultiplyTo( denseValueArray0: number[], denseValueArray1: number[]): number[]; vectorDenseSubtractFrom( denseValueArray0: number[], denseValueArray1: number[]): number[]; vectorDenseDivideFrom( denseValueArray0: number[], denseValueArray1: number[]): number[]; vectorDenseAssignScaledTo( denseValueArray0: number[], denseValueArray1: number[], constant: number): number[]; vectorDenseAddScaledTo( denseValueArray0: number[], denseValueArray1: number[], constant: number): number[]; vectorDenseMultiplyScaledTo( denseValueArray0: number[], denseValueArray1: number[], constant: number): number[]; vectorDenseSubtractScaledFrom( denseValueArray0: number[], denseValueArray1: number[], constant: number): number[]; vectorDenseDivideScaledFrom( denseValueArray0: number[], denseValueArray1: number[], constant: number): number[]; vectorSparseAssignRandomTo( sparseIndexArray0: number[], sparseValueArray0: number[]): [number[], number[]]; vectorSparseAssignConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseAddConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMultiplyConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseSubtractConstantFrom( sparseIndexArray0: number[], sparseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseDivideConstantFrom( sparseIndexArray0: number[], sparseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseAssignTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[]): [number[], number[]]; vectorSparseAddTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[]): [number[], number[]]; vectorSparseMultiplyTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[]): [number[], number[]]; vectorSparseSubtractFrom( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[]): [number[], number[]]; vectorSparseDivideFrom( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[]): [number[], number[]]; vectorSparseAssignScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseAddScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMultiplyScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseSubtractScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseDivideScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayAssignRandomTo( sparseIndexArray0: number[], denseValueArray0: number[]): [number[], number[]]; vectorSparseIndexDenseArrayAssignConstantTo( sparseIndexArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayAddConstantTo( sparseIndexArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayMultiplyConstantTo( sparseIndexArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArraySubtractConstantFrom( sparseIndexArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayDivideConstantFrom( sparseIndexArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayAssignTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseIndexDenseArrayAddTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseIndexDenseArrayMultiplyTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseIndexDenseArraySubtractFrom( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseIndexDenseArrayDivideFrom( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseIndexDenseArrayAssignScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayAddScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayMultiplyScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArraySubtractScaledFrom( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseIndexDenseArrayDivideScaledFrom( sparseIndexArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseIndexDenseArrayAssignTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseIndexDenseArrayAddTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseIndexDenseArrayMultiplyTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseIndexDenseArraySubtractFrom( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseIndexDenseArrayDivideFrom( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseIndexDenseArrayAssignScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseIndexDenseArrayAddScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseIndexDenseArrayMultiplyScaledTo( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseIndexDenseArraySubtractScaledFrom( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseIndexDenseArrayDivideScaledFrom( sparseIndexArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayAssignRandomTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[]): [number[], number[]]; vectorSparseMapDenseArrayAssignConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayAddConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayMultiplyConstantTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArraySubtractConstantFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayDivideConstantFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayAssignTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseMapDenseArrayAddTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseMapDenseArrayMultiplyTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseMapDenseArraySubtractFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseMapDenseArrayDivideFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[]): [number[], number[]]; vectorSparseMapDenseArrayAssignScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayAddScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayMultiplyScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArraySubtractScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorSparseMapDenseArrayDivideScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseMapDenseArrayAssignTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseMapDenseArrayAddTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseMapDenseArrayMultiplyTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseMapDenseArraySubtractFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseMapDenseArrayDivideFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[]): [number[], number[]]; vectorIndependentSparseMapDenseArrayAssignScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseMapDenseArrayAddScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseMapDenseArrayMultiplyScaledTo( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseMapDenseArraySubtractScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; vectorIndependentSparseMapDenseArrayDivideScaledFrom( sparseIndexArray0: number[], sparseValueArray0: number[], denseValueArray0: number[], sparseIndexArray1: number[], sparseValueArray1: number[], denseValueArray1: number[], constant: number): [number[], number[]]; tensor4dNewLikeWithRandomCells( tensor4d: number[][][][]): number[][][][]; tensor4dNewLikeWithRandomCellsScaled( tensor4d: number[][][][], scale: number): number[][][][]; tensor4dNewLikeWithZeroCells( tensor4d: number[][][][]): number[][][][]; tensor4dNewLikeWithConstantCells( tensor4d: number[][][][], constant: number): number[][][][]; tensor4dNewLikeWithScaledCells( tensor4d: number[][][][], scale: number): number[][][][]; tensor4dNewLikeWithL1l2RegularizedSparseCells( tensor4d: number[][][][], l1Regularization: number, l2Regularization: number): number[][][][]; tensor4dNewLikeWithL1l2RegularizedDenseCells( tensor4d: number[][][][], l1Regularization: number, l2Regularization: number): number[][][][]; tensor3dNewLikeWithRandomCells( tensor3d: number[][][]): number[][][]; tensor3dNewLikeWithRandomCellsScaled( tensor3d: number[][][], scale: number): number[][][]; tensor3dNewLikeWithZeroCells( tensor3d: number[][][]): number[][][]; tensor3dNewLikeWithConstantCells( tensor3d: number[][][], constant: number): number[][][]; tensor3dNewLikeWithScaledCells( tensor3d: number[][][], scale: number): number[][][]; tensor3dNewLikeWithL1l2RegularizedSparseCells( tensor3d: number[][][], l1Regularization: number, l2Regularization: number): number[][][]; tensor3dNewLikeWithL1l2RegularizedDenseCells( tensor3d: number[][][], l1Regularization: number, l2Regularization: number): number[][][]; matrixNewLikeWithRandomCells( matrix: number[][]): number[][]; matrixNewLikeWithRandomCellsScaled( matrix: number[][], scale: number): number[][]; matrixNewLikeWithZeroCells( matrix: number[][]): number[][]; matrixNewLikeWithConstantCells( matrix: number[][], constant: number): number[][]; matrixNewLikeWithScaledCells( matrix: number[][], scale: number): number[][]; matrixNewLikeWithL1l2RegularizedSparseCells( matrix: number[][], l1Regularization: number, l2Regularization: number): number[][]; matrixNewLikeWithL1l2RegularizedDenseCells( matrix: number[][], l1Regularization: number, l2Regularization: number): number[][]; vectorNewLikeWithRandomElements( vector: number[]): number[]; vectorNewLikeWithRandomElementsScaled( vector: number[], scale: number): number[]; vectorNewLikeWithZeroElements( vector: number[]): number[]; vectorNewLikeWithConstantElements( vector: number[], constant: number): number[]; vectorNewLikeWithScaledElements( vector: number[], scale: number): number[]; vectorNewLikeWithL1l2RegularizedSparseElements( vector: number[], l1Regularization: number, l2Regularization: number): number[]; vectorNewLikeWithL1l2RegularizedDenseElements( vector: number[], l1Regularization: number, l2Regularization: number): number[]; tensor4dNewWithRandomCells( rows: number, columns: number, dimension3ds: number, dimension4ds: number): number[][][][]; tensor4dNewWithRandomCellsScaled( rows: number, columns: number, dimension3ds: number, dimension4ds: number, scale: number): number[][][][]; tensor4dNewWithZeroCells( rows: number, columns: number, dimension3ds: number, dimension4ds: number): number[][][][]; tensor4dNewWithConstantCells( rows: number, columns: number, dimension3ds: number, dimension4ds: number, constant: number): number[][][][]; tensor4dNewWithScaledCells( existingTensor4d: number[][][][], scale: number): number[][][][]; tensor4dNewWithL1l2RegularizedSparseCells( existingTensor4d: number[][][][], l1Regularization: number, l2Regularization: number): number[][][][]; tensor4dNewWithL1l2RegularizedDenseCells( existingTensor4d: number[][][][], l1Regularization: number, l2Regularization: number): number[][][][]; tensor3dNewWithRandomCells( rows: number, columns: number, dimension3ds: number): number[][][]; tensor3dNewWithRandomCellsScaled( rows: number, columns: number, dimension3ds: number, scale: number): number[][][]; tensor3dNewWithZeroCells( rows: number, columns: number, dimension3ds: number): number[][][]; tensor3dNewWithConstantCells( rows: number, columns: number, dimension3ds: number, constant: number): number[][][]; tensor3dNewWithScaledCells( existingTensor3d: number[][][], scale: number): number[][][]; tensor3dNewWithL1l2RegularizedSparseCells( existingTensor3d: number[][][], l1Regularization: number, l2Regularization: number): number[][][]; tensor3dNewWithL1l2RegularizedDenseCells( existingTensor3d: number[][][], l1Regularization: number, l2Regularization: number): number[][][]; matrixNewWithRandomCells( rows: number, columns: number): number[][]; matrixNewWithRandomCellsScaled( rows: number, columns: number, scale: number): number[][]; matrixNewWithZeroCells( rows: number, columns: number): number[][]; matrixNewWithConstantCells( rows: number, columns: number, constant: number): number[][]; matrixNewWithScaledCells( existingMatrix: number[][], scale: number): number[][]; matrixNewWithL1l2RegularizedSparseCells( existingMatrix: number[][], l1Regularization: number, l2Regularization: number): number[][]; matrixNewWithL1l2RegularizedDenseCells( existingMatrix: number[][], l1Regularization: number, l2Regularization: number): number[][]; vectorNewWithRandomElements( length: number): number[]; vectorNewWithRandomElementsScaled( length: number, scale: number): number[]; vectorNewWithZeroElements( length: number): number[]; vectorNewWithConstantElements( length: number, constant: number): number[]; vectorNewWithScaledElements( existingVector: number[], scale: number): number[]; vectorNewWithL1l2RegularizedSparseElements( existingVector: number[], l1Regularization: number, l2Regularization: number): number[]; vectorNewWithL1l2RegularizedDenseElements( existingVector: number[], l1Regularization: number, l2Regularization: number): number[]; getIndexesOnMaxOrEntriesOverThresholdOnArray( inputArray: Float32Array | Int32Array | Uint8Array, threshold: number): { "indexesMax": number[]; "max": number }; getIndexesOnMaxOrEntriesOverThreshold( inputArray: number[], threshold: number): { "indexesMax": number[]; "max": number }; getIndexesOnMaxEntriesOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexesMax": number[], "max": number }; getIndexesOnMaxEntries( inputArray: number[]): { "indexesMax": number[], "max": number }; getIndexOnFirstMaxEntryOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexMax": number, "max": number }; getIndexOnLastMaxEntryOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexMax": number, "max": number }; getIndexOnFirstMaxEntry( inputArray: number[]): { "indexMax": number, "max": number }; getIndexOnLastMaxEntry( inputArray: number[]): { "indexMax": number, "max": number }; getIndexesOnMinOrEntriesLessThanThresholdOnArray( inputArray: Float32Array | Int32Array | Uint8Array, threshold: number): { "indexesMin": number[]; "min": number }; getIndexesOnMinOrEntriesLessThanThreshold( inputArray: number[], threshold: number): { "indexesMin": number[]; "min": number }; getIndexesOnMinEntriesOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexesMin": number[], "min": number }; getIndexesOnMinEntries( inputArray: number[]): { "indexesMin": number[], "min": number }; getIndexOnFirstMinEntryOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexMin": number, "min": number }; getIndexOnLastMinEntryOnArray( inputArray: Float32Array | Int32Array | Uint8Array): { "indexMin": number, "min": number }; getIndexOnFirstMinEntry( inputArray: number[]): { "indexMin": number, "min": number }; getIndexOnLastMinEntry( inputArray: number[]): { "indexMin": number, "min": number }; safeDivide(numerator: number, denominator: number): number; safeLog(value: number): number; clipValue(value: number): number; safeZeroSmallNegativeErrorSubtract(value0: number, value1: number): number; }
the_stack
import Alignment, { Bounds } from "./alignment"; import BiStringBuilder from "./builder"; import heuristicInfer from "./infer"; import { Replacer, normalizeReplacer, cloneRegExp } from "./regex"; import * as unicode from "./unicode"; export type AnyString = string | BiString; /** * A bidirectionally transformed string. */ export default class BiString implements Iterable<String> { /** The original string, before any modifications. */ readonly original: string; /** The current value of the string, after all modifications. */ readonly modified: string; /** The sequence alignment between `original` and `modified`. */ readonly alignment: Alignment; /** The length of the modified string. */ readonly length: number; /** Indexes the code units of the modified string. */ readonly [i: number]: string; /** * A BiString can be constructed from only a single string, which will give it identical original and modified * strings and an identity alignment: * * .. code-block:: ts * * new BiString("test"); * * You can also explicitly specify both the original and modified strings. The inferred alignment will be as course * as possible: * * .. code-block:: ts * * new BiString("TEST", "test"); * * Finally, you can specify the alignment explicitly, if you know it: * * .. code-block:: ts * * new BiString("TEST", "test", Alignment.identity(4)); * * @param original * The original string, before any modifications. * @param modified * The modified string, after any modifications. * @param alignment * The alignment between the original and modified strings. */ constructor(original: string, modified?: string, alignment?: Alignment) { if (typeof(original) !== "string") { throw new TypeError("original was not a string"); } this.original = original; if (modified === undefined) { modified = original; if (alignment === undefined) { alignment = Alignment.identity(original.length); } } else if (typeof(modified) === "string") { if (alignment === undefined) { alignment = new Alignment([[0, 0], [original.length, modified.length]]); } } else { throw new TypeError("modified was not a string"); } this.modified = modified; if (!(alignment instanceof Alignment)) { throw new TypeError("alignment was not an Alignment"); } const [ostart, oend] = alignment.originalBounds(); if (ostart !== 0 || oend !== original.length) { throw new RangeError("Alignment incompatible with original string"); } const [mstart, mend] = alignment.modifiedBounds(); if (mstart !== 0 || mend !== modified.length) { throw new RangeError("Alignment incompatible with modified string"); } this.alignment = alignment; this.length = this.modified.length; for (let i = 0; i < this.length; ++i) { // @ts-ignore: https://github.com/microsoft/TypeScript/issues/6781 this[i] = this.modified[i]; } Object.freeze(this); } /** * Create a `BiString` from a string-like object. * * @param str * Either a `string` or a `BiString`. * @returns * The input coerced to a `BiString`. */ static from(str: AnyString): BiString { if (str instanceof BiString) { return str; } else { return new BiString(str); } } /** * Create a `BiString`, automatically inferring an alignment between the `original` and `modified` strings. * * @param original * The original string. * @param modified * The modified string. */ static infer(original: string, modified: string): BiString { return heuristicInfer(original, modified); } /** * Iterates over the code points in the modified string. */ [Symbol.iterator](): IterableIterator<string> { return this.modified[Symbol.iterator](); } /** * Like :js:meth:`String.prototype.charAt`, returns a code unit as a string from the modified string. */ charAt(pos: number): string { return this.modified.charAt(pos); } /** * Like :js:meth:`String.prototype.charCodeAt`, returns a code unit as a number from the modified string. */ charCodeAt(pos: number): number { return this.modified.charCodeAt(pos); } /** * Like :js:meth:`String.prototype.codePointAt`, returns a code point from the modified string. */ codePointAt(pos: number): number | undefined { return this.modified.codePointAt(pos); } /** * Extract a substring of this BiString, with similar semantics to :js:meth:`String.prototype.substring`. */ substring(start: number, end?: number): BiString { if (end === undefined) { end = this.length; } if (start > end) { [start, end] = [end, start]; } start = Math.max(0, Math.min(start, this.length)); end = Math.max(0, Math.min(end, this.length)); return this.slice(start, end); } /** * Extract a slice of this BiString, with similar semantics to :js:meth:`String.prototype.slice`. */ slice(start: number, end?: number): BiString { if (end === undefined) { end = this.length; } if (start < 0) { start += this.length; } if (end < 0) { end += this.length; } if (end < start) { end = start; } start = Math.max(0, Math.min(start, this.length)); end = Math.max(0, Math.min(end, this.length)); const alignment = this.alignment.sliceByModified(start, end); const modified = this.modified.slice(...alignment.modifiedBounds()); const original = this.original.slice(...alignment.originalBounds()); const [o0, m0] = alignment.values[0]; return new BiString(original, modified, alignment.shift(-o0, -m0)); } /** * Concatenate this string together with one or more others. The additional strings can be either BiStrings or * normal strings. */ concat(...others: AnyString[]): BiString { let original = this.original; let modified = this.modified; let alignment = this.alignment; for (const other of others) { const biother = BiString.from(other); alignment = alignment.concat(biother.alignment.shift(original.length, modified.length)); original += biother.original; modified += biother.modified; } return new BiString(original, modified, alignment); } /** * @returns * The inverse of this string, swapping the original and modified strings. */ inverse(): BiString { return new BiString(this.modified, this.original, this.alignment.inverse()); } /** * @returns * Whether this BiString is equal to another. */ equals(other: BiString): boolean { return this.original === other.original && this.modified === other.modified && this.alignment.equals(other.alignment); } /** * Like :js:meth:`String.prototype.indexOf`, finds the first occurrence of a substring. */ indexOf(searchValue: string, fromIndex?: number): number { return this.modified.indexOf(searchValue, fromIndex); } /** * Like :js:meth:`String.prototype.lastIndexOf`, finds the last occurrence of a substring. */ lastIndexOf(searchValue: string, fromIndex?: number): number { return this.modified.lastIndexOf(searchValue, fromIndex); } /** * Like :js:meth:`indexOf`, but returns both the start and end positions for convenience. */ boundsOf(searchValue: string, fromIndex?: number): Bounds { let start = this.indexOf(searchValue, fromIndex); if (start === -1) { return [-1, -1]; } else { return [start, start + searchValue.length]; } } /** * Like :js:meth:`lastIndexOf`, but returns both the start and end positions for convenience. */ lastBoundsOf(searchValue: string, fromIndex?: number): Bounds { let start = this.lastIndexOf(searchValue, fromIndex); if (start === -1) { return [-1, -1]; } else { return [start, start + searchValue.length]; } } /** * Like :js:meth:`String.prototype.search`, finds the position of the first match of a regular expression. */ search(regexp: RegExp): number { return this.modified.search(regexp); } /** * Like :js:meth:`search`, but returns both the start and end positions for convenience. */ searchBounds(regexp: RegExp): Bounds { const match = regexp.exec(this.modified); if (match === null) { return [-1, -1]; } else { return [match.index, match.index + match[0].length]; } } /** * Like :js:meth:`String.prototype.match`, returns the result of a regular expression match. */ match(regexp: RegExp): RegExpMatchArray | null { return this.modified.match(regexp); } /** * Like :js:meth:`String.prototype.matchAll`, returns an iterator over all regular expression matches. */ matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray> { return this.modified.matchAll(regexp); } private _replaceString(pattern: string, replacement: string | Replacer): BiString { const replacer = normalizeReplacer(replacement); const builder = new BiStringBuilder(this); while (!builder.isComplete) { const next = this.indexOf(pattern, builder.position); if (next < 0) { break; } builder.skip(next - builder.position); const match = [this.modified.slice(next, next + pattern.length)] as RegExpMatchArray; match.index = next; match.input = this.modified; builder.replace(pattern.length, replacer(match)); } builder.skipRest(); return builder.build(); } private _replaceRegExp(pattern: RegExp, replacement: string | Replacer): BiString { const builder = new BiStringBuilder(this); builder.replaceAll(pattern, replacement); return builder.build(); } /** * Like :js:meth:`String.prototype.replace`, returns a new string with regex or fixed-string matches replaced. */ replace(pattern: string | RegExp, replacement: string | Replacer): BiString { if (typeof(pattern) === "string") { return this._replaceString(pattern, replacement); } else { return this._replaceRegExp(pattern, replacement); } } /** * Like :js:meth:`String.prototype.trim`, returns a new string with leading and trailing whitespace removed. */ trim(): BiString { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); } /** * Like :js:meth:`String.prototype.trim`, returns a new string with leading whitespace removed. */ trimStart(): BiString { return this.replace(/^[\s\uFEFF\xA0]+/, ""); } /** * Like :js:meth:`String.prototype.trim`, returns a new string with trailing whitespace removed. */ trimEnd(): BiString { return this.replace(/[\s\uFEFF\xA0]+$/, ""); } /** * Like :js:meth:`String.prototype.padStart`, pads a string at the beginning to a target length. */ padStart(targetLength: number, padString: string = " "): BiString { const padLength = targetLength - this.length; if (padLength <= 0) { return this; } if (padString.length < padLength) { padString += padString.repeat(targetLength / padString.length); } padString = padString.slice(0, padLength); return new BiString("", padString).concat(this); } /** * Like :js:meth:`String.prototype.padEnd`, pads a string at the end to a target length. */ padEnd(targetLength: number, padString: string = " "): BiString { const padLength = targetLength - this.length; if (padLength <= 0) { return this; } if (padString.length < padLength) { padString += padString.repeat(targetLength / padString.length); } padString = padString.slice(0, padLength); return this.concat(new BiString("", padString)); } /** * Like :js:meth:`String.prototype.startsWith`, returns whether this string starts with the given prefix. */ startsWith(searchString: string, position?: number): boolean { return this.modified.startsWith(searchString, position); } /** * Like :js:meth:`String.prototype.endsWith`, returns whether this string ends with the given prefix. */ endsWith(searchString: string, position?: number): boolean { return this.modified.endsWith(searchString, position); } private _splitString(pattern: string, limit?: number): BiString[] { if (limit === undefined) { limit = Infinity; } const result = []; for (let i = 0, j, k; i >= 0 && result.length < limit; i = k) { if (pattern.length === 0) { if (i + 1 < this.length) { j = k = i + 1; } else { j = k = -1; } } else { [j, k] = this.boundsOf(pattern, i); } if (j >= 0) { result.push(this.slice(i, j)); } else { result.push(this.slice(i)); } } return result; } private _splitRegExp(pattern: RegExp, limit?: number): BiString[] { pattern = cloneRegExp(pattern, "g", "y"); if (limit === undefined) { limit = Infinity; } const result = []; let last = 0; for (const match of this.matchAll(pattern)) { if (result.length >= limit) { break; } const start = match.index!; const end = start + match[0].length; result.push(this.slice(last, start)); // String.prototype.split() will include any captured substrings in the result. But we can't support that // easily, since JS regexes give us no information about the position of matched capture groups if (match.length > 1) { throw new Error("split() with capture groups is not supported"); } last = end; } if (result.length < limit) { result.push(this.slice(last)); } return result; } /** * Like :js:meth:`String.prototype.split`, splits this string into chunks using a separator. */ split(separator?: string | RegExp, limit?: number): BiString[] { if (separator === undefined) { return [this]; } else if (typeof(separator) === "string") { return this._splitString(separator, limit); } else { return this._splitRegExp(separator, limit); } } /** * Like :js:meth:`Array.prototype.join`, joins a sequence together with this `BiString` as the separator. */ join(items: Iterable<AnyString>): BiString { let [first, ...rest] = items; if (first === undefined) { return new BiString(""); } first = BiString.from(first); rest = rest.flatMap(s => [this, s]); return first.concat(...rest); } private static _normalFormRegex(form: string) { switch (form) { case "NFC": return unicode.NFC_CHUNK; case "NFD": return unicode.NFD_CHUNK; case "NFKC": return unicode.NFKC_CHUNK; case "NFKD": return unicode.NFKD_CHUNK; default: throw new RangeError(`Expected a normalization form (NFC, NFD, NFKC, NFKD); found ${form}`); } } /** * Like :js:meth:`String.prototype.normalize`, applies a Unicode normalization form. * * @param form * The normalization form to apply, one of "NFC", "NFD", "NFKC", or "NFKD". */ normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): BiString { const regex = BiString._normalFormRegex(form); return this.replace(regex, m => { const result = m.normalize(form); if (result === m) { return new BiString(m); } else { return new BiString(m, result); } }); } private _isFinalSigmaAt(index: number): boolean { if (this[index] !== "Σ") { return false; } // Emulate negative lookahead: (?!\p{Case_Ignorable}*+\p{Cased}) for (let i = index + 1; i < this.length; ++i) { const cp = this.codePointAt(i)!; const c = String.fromCodePoint(cp); if (/\P{Case_Ignorable}/uy.test(c)) { if (/\p{Cased}/uy.test(c)) { return false; } else { break; } } if (cp > 0xFFFF) { ++i; } } // Emulate positive lookbehind: (?<=\p{Cased}\p{Case_Ignorable}*+) for (let i = index; i-- > 0;) { let cp = this.charCodeAt(i); if (i > 0 && (cp & 0xFC00) == 0xDC00 && (this.charCodeAt(i - 1) & 0xFC00) == 0xD800) { --i; cp = this.codePointAt(i)!; } const c = String.fromCodePoint(cp); if (/\P{Case_Ignorable}/uy.test(c)) { if (/\p{Cased}/uy.test(c)) { return true; } else { break; } } } return false; } /** * Like :js:meth:`String.prototype.toLowerCase`, converts a string to lowercase. */ toLowerCase(): BiString { return this.replace(/\p{Changes_When_Lowercased}/gu, (m, ...args) => { // This is the only contextual but non-language-specific mapping in SpecialCasing.txt as of Unicode 12.1 if (this._isFinalSigmaAt(args[args.length - 2])) { return "ς"; } else { return m.toLowerCase(); } }); } /** * Like :js:meth:`String.prototype.toUpperCase`, converts a string to uppercase. */ toUpperCase(): BiString { return this.replace(/\p{Changes_When_Uppercased}/gu, m => m.toUpperCase()); } }
the_stack
import { ProposalStatus, Proposal, Vote, VotingParams, DepositParams, TallyParams, Deposit, TallyResult } from '../../../cosmos/gov/v1beta1/gov'; import { Reader, Writer } from 'protobufjs/minimal'; import { PageRequest, PageResponse } from '../../../cosmos/base/query/v1beta1/pagination'; export declare const protobufPackage = "cosmos.gov.v1beta1"; /** QueryProposalRequest is the request type for the Query/Proposal RPC method. */ export interface QueryProposalRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; } /** QueryProposalResponse is the response type for the Query/Proposal RPC method. */ export interface QueryProposalResponse { proposal: Proposal | undefined; } /** QueryProposalsRequest is the request type for the Query/Proposals RPC method. */ export interface QueryProposalsRequest { /** proposal_status defines the status of the proposals. */ proposalStatus: ProposalStatus; /** voter defines the voter address for the proposals. */ voter: string; /** depositor defines the deposit addresses from the proposals. */ depositor: string; /** pagination defines an optional pagination for the request. */ pagination: PageRequest | undefined; } /** * QueryProposalsResponse is the response type for the Query/Proposals RPC * method. */ export interface QueryProposalsResponse { proposals: Proposal[]; /** pagination defines the pagination in the response. */ pagination: PageResponse | undefined; } /** QueryVoteRequest is the request type for the Query/Vote RPC method. */ export interface QueryVoteRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; /** voter defines the oter address for the proposals. */ voter: string; } /** QueryVoteResponse is the response type for the Query/Vote RPC method. */ export interface QueryVoteResponse { /** vote defined the queried vote. */ vote: Vote | undefined; } /** QueryVotesRequest is the request type for the Query/Votes RPC method. */ export interface QueryVotesRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; /** pagination defines an optional pagination for the request. */ pagination: PageRequest | undefined; } /** QueryVotesResponse is the response type for the Query/Votes RPC method. */ export interface QueryVotesResponse { /** votes defined the queried votes. */ votes: Vote[]; /** pagination defines the pagination in the response. */ pagination: PageResponse | undefined; } /** QueryParamsRequest is the request type for the Query/Params RPC method. */ export interface QueryParamsRequest { /** * params_type defines which parameters to query for, can be one of "voting", * "tallying" or "deposit". */ paramsType: string; } /** QueryParamsResponse is the response type for the Query/Params RPC method. */ export interface QueryParamsResponse { /** voting_params defines the parameters related to voting. */ votingParams: VotingParams | undefined; /** deposit_params defines the parameters related to deposit. */ depositParams: DepositParams | undefined; /** tally_params defines the parameters related to tally. */ tallyParams: TallyParams | undefined; } /** QueryDepositRequest is the request type for the Query/Deposit RPC method. */ export interface QueryDepositRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; /** depositor defines the deposit addresses from the proposals. */ depositor: string; } /** QueryDepositResponse is the response type for the Query/Deposit RPC method. */ export interface QueryDepositResponse { /** deposit defines the requested deposit. */ deposit: Deposit | undefined; } /** QueryDepositsRequest is the request type for the Query/Deposits RPC method. */ export interface QueryDepositsRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; /** pagination defines an optional pagination for the request. */ pagination: PageRequest | undefined; } /** QueryDepositsResponse is the response type for the Query/Deposits RPC method. */ export interface QueryDepositsResponse { deposits: Deposit[]; /** pagination defines the pagination in the response. */ pagination: PageResponse | undefined; } /** QueryTallyResultRequest is the request type for the Query/Tally RPC method. */ export interface QueryTallyResultRequest { /** proposal_id defines the unique id of the proposal. */ proposalId: number; } /** QueryTallyResultResponse is the response type for the Query/Tally RPC method. */ export interface QueryTallyResultResponse { /** tally defines the requested tally. */ tally: TallyResult | undefined; } export declare const QueryProposalRequest: { encode(message: QueryProposalRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryProposalRequest; fromJSON(object: any): QueryProposalRequest; toJSON(message: QueryProposalRequest): unknown; fromPartial(object: DeepPartial<QueryProposalRequest>): QueryProposalRequest; }; export declare const QueryProposalResponse: { encode(message: QueryProposalResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryProposalResponse; fromJSON(object: any): QueryProposalResponse; toJSON(message: QueryProposalResponse): unknown; fromPartial(object: DeepPartial<QueryProposalResponse>): QueryProposalResponse; }; export declare const QueryProposalsRequest: { encode(message: QueryProposalsRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryProposalsRequest; fromJSON(object: any): QueryProposalsRequest; toJSON(message: QueryProposalsRequest): unknown; fromPartial(object: DeepPartial<QueryProposalsRequest>): QueryProposalsRequest; }; export declare const QueryProposalsResponse: { encode(message: QueryProposalsResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryProposalsResponse; fromJSON(object: any): QueryProposalsResponse; toJSON(message: QueryProposalsResponse): unknown; fromPartial(object: DeepPartial<QueryProposalsResponse>): QueryProposalsResponse; }; export declare const QueryVoteRequest: { encode(message: QueryVoteRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryVoteRequest; fromJSON(object: any): QueryVoteRequest; toJSON(message: QueryVoteRequest): unknown; fromPartial(object: DeepPartial<QueryVoteRequest>): QueryVoteRequest; }; export declare const QueryVoteResponse: { encode(message: QueryVoteResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryVoteResponse; fromJSON(object: any): QueryVoteResponse; toJSON(message: QueryVoteResponse): unknown; fromPartial(object: DeepPartial<QueryVoteResponse>): QueryVoteResponse; }; export declare const QueryVotesRequest: { encode(message: QueryVotesRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryVotesRequest; fromJSON(object: any): QueryVotesRequest; toJSON(message: QueryVotesRequest): unknown; fromPartial(object: DeepPartial<QueryVotesRequest>): QueryVotesRequest; }; export declare const QueryVotesResponse: { encode(message: QueryVotesResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryVotesResponse; fromJSON(object: any): QueryVotesResponse; toJSON(message: QueryVotesResponse): unknown; fromPartial(object: DeepPartial<QueryVotesResponse>): QueryVotesResponse; }; export declare const QueryParamsRequest: { encode(message: QueryParamsRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryParamsRequest; fromJSON(object: any): QueryParamsRequest; toJSON(message: QueryParamsRequest): unknown; fromPartial(object: DeepPartial<QueryParamsRequest>): QueryParamsRequest; }; export declare const QueryParamsResponse: { encode(message: QueryParamsResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryParamsResponse; fromJSON(object: any): QueryParamsResponse; toJSON(message: QueryParamsResponse): unknown; fromPartial(object: DeepPartial<QueryParamsResponse>): QueryParamsResponse; }; export declare const QueryDepositRequest: { encode(message: QueryDepositRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryDepositRequest; fromJSON(object: any): QueryDepositRequest; toJSON(message: QueryDepositRequest): unknown; fromPartial(object: DeepPartial<QueryDepositRequest>): QueryDepositRequest; }; export declare const QueryDepositResponse: { encode(message: QueryDepositResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryDepositResponse; fromJSON(object: any): QueryDepositResponse; toJSON(message: QueryDepositResponse): unknown; fromPartial(object: DeepPartial<QueryDepositResponse>): QueryDepositResponse; }; export declare const QueryDepositsRequest: { encode(message: QueryDepositsRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryDepositsRequest; fromJSON(object: any): QueryDepositsRequest; toJSON(message: QueryDepositsRequest): unknown; fromPartial(object: DeepPartial<QueryDepositsRequest>): QueryDepositsRequest; }; export declare const QueryDepositsResponse: { encode(message: QueryDepositsResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryDepositsResponse; fromJSON(object: any): QueryDepositsResponse; toJSON(message: QueryDepositsResponse): unknown; fromPartial(object: DeepPartial<QueryDepositsResponse>): QueryDepositsResponse; }; export declare const QueryTallyResultRequest: { encode(message: QueryTallyResultRequest, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryTallyResultRequest; fromJSON(object: any): QueryTallyResultRequest; toJSON(message: QueryTallyResultRequest): unknown; fromPartial(object: DeepPartial<QueryTallyResultRequest>): QueryTallyResultRequest; }; export declare const QueryTallyResultResponse: { encode(message: QueryTallyResultResponse, writer?: Writer): Writer; decode(input: Reader | Uint8Array, length?: number): QueryTallyResultResponse; fromJSON(object: any): QueryTallyResultResponse; toJSON(message: QueryTallyResultResponse): unknown; fromPartial(object: DeepPartial<QueryTallyResultResponse>): QueryTallyResultResponse; }; /** Query defines the gRPC querier service for gov module */ export interface Query { /** Proposal queries proposal details based on ProposalID. */ Proposal(request: QueryProposalRequest): Promise<QueryProposalResponse>; /** Proposals queries all proposals based on given status. */ Proposals(request: QueryProposalsRequest): Promise<QueryProposalsResponse>; /** Vote queries voted information based on proposalID, voterAddr. */ Vote(request: QueryVoteRequest): Promise<QueryVoteResponse>; /** Votes queries votes of a given proposal. */ Votes(request: QueryVotesRequest): Promise<QueryVotesResponse>; /** Params queries all parameters of the gov module. */ Params(request: QueryParamsRequest): Promise<QueryParamsResponse>; /** Deposit queries single deposit information based proposalID, depositAddr. */ Deposit(request: QueryDepositRequest): Promise<QueryDepositResponse>; /** Deposits queries all deposits of a single proposal. */ Deposits(request: QueryDepositsRequest): Promise<QueryDepositsResponse>; /** TallyResult queries the tally of a proposal vote. */ TallyResult(request: QueryTallyResultRequest): Promise<QueryTallyResultResponse>; } export declare class QueryClientImpl implements Query { private readonly rpc; constructor(rpc: Rpc); Proposal(request: QueryProposalRequest): Promise<QueryProposalResponse>; Proposals(request: QueryProposalsRequest): Promise<QueryProposalsResponse>; Vote(request: QueryVoteRequest): Promise<QueryVoteResponse>; Votes(request: QueryVotesRequest): Promise<QueryVotesResponse>; Params(request: QueryParamsRequest): Promise<QueryParamsResponse>; Deposit(request: QueryDepositRequest): Promise<QueryDepositResponse>; Deposits(request: QueryDepositsRequest): Promise<QueryDepositsResponse>; TallyResult(request: QueryTallyResultRequest): Promise<QueryTallyResultResponse>; } interface Rpc { request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>; } declare type Builtin = Date | Function | Uint8Array | string | number | undefined; export declare type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]>; } : Partial<T>; export {};
the_stack
import { ViewChild, Component, DebugElement, OnInit } from '@angular/core'; import { TestBed, fakeAsync, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IgxGridComponent } from './grid.component'; import { IgxGridModule } from './public_api'; import { configureTestSuite } from '../../test-utils/configure-suite'; import { ColumnPinningPosition, RowPinningPosition } from '../common/enums'; import { IPinningConfig } from '../grid.common'; import { SampleTestData } from '../../test-utils/sample-test-data.spec'; import { GridFunctions } from '../../test-utils/grid-functions.spec'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { GridSummaryFunctions } from '../../test-utils/grid-functions.spec'; import { IgxStringFilteringOperand } from '../../data-operations/filtering-condition'; import { IgxPaginatorComponent } from '../../paginator/paginator.component'; import { wait, UIInteractions } from '../../test-utils/ui-interactions.spec'; import { setupGridScrollDetection } from '../../test-utils/helper-utils.spec'; import { GridRowConditionalStylingComponent } from '../../test-utils/grid-base-components.spec'; describe('Row Pinning #grid', () => { const FIXED_ROW_CONTAINER = '.igx-grid__tr--pinned '; const CELL_CSS_CLASS = '.igx-grid__td'; const DEBOUNCE_TIME = 60; let fix; let grid: IgxGridComponent; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ GridRowPinningComponent, GridRowPinningWithMRLComponent, GridRowPinningWithMDVComponent, GridRowPinningWithTransactionsComponent, GridRowPinningWithInitialPinningComponent, GridRowConditionalStylingComponent ], imports: [ NoopAnimationsModule, IgxGridModule ] }); })); describe('', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningComponent); fix.detectChanges(); grid = fix.componentInstance.instance; tick(); fix.detectChanges(); })); it('should pin rows to top.', () => { // pin 2nd data row grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].nativeElement).toBe(grid.gridAPI.get_row_by_index(0).nativeElement); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(3).rowID).toBe(fix.componentInstance.data[2]); // pin 3rd data row grid.pinRow(fix.componentInstance.data[2]); fix.detectChanges(); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[1].context.rowID).toBe(fix.componentInstance.data[2]); expect(grid.gridAPI.get_row_by_index(2).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(5).rowID).toBe(fix.componentInstance.data[3]); fix.detectChanges(); // 2 records pinned + 2px border expect(grid.pinnedRowHeight).toBe(2 * grid.renderedRowHeight + 2); const expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); }); it('should pin rows to bottom.', () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fix.detectChanges(); // pin 2nd grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].context.index - grid.pinnedRows.length).toBe(fix.componentInstance.data.length - 1); expect(pinRowContainer[0].children[0].nativeElement) .toBe(grid.gridAPI.get_row_by_index(fix.componentInstance.data.length).nativeElement); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(2).rowID).toBe(fix.componentInstance.data[2]); // pin 1st grid.pinRow(fix.componentInstance.data[0]); fix.detectChanges(); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[1].context.rowID).toBe(fix.componentInstance.data[0]); fix.detectChanges(); // check last pinned is fully in view const last = pinRowContainer[0].children[1].context.nativeElement; expect(last.getBoundingClientRect().bottom - grid.tbody.nativeElement.getBoundingClientRect().bottom).toBe(0); // 2 records pinned + 2px border expect(grid.pinnedRowHeight).toBe(2 * grid.renderedRowHeight + 2); const expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); }); it('should allow pinning row at specified index via API.', () => { grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); expect(grid.pinnedRows[0].rowData).toBe(fix.componentInstance.data[1]); // pin at index 0 grid.pinRow(fix.componentInstance.data[2], 0); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(2); expect(grid.pinnedRows[0].rowData).toBe(fix.componentInstance.data[2]); expect(grid.pinnedRows[1].rowData).toBe(fix.componentInstance.data[1]); // pin at index 1 grid.pinRow(fix.componentInstance.data[3], 1); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(3); expect(grid.pinnedRows[0].rowData).toBe(fix.componentInstance.data[2]); expect(grid.pinnedRows[1].rowData).toBe(fix.componentInstance.data[3]); expect(grid.pinnedRows[2].rowData).toBe(fix.componentInstance.data[1]); }); it('should emit rowPinning on pin/unpin.', () => { spyOn(grid.rowPinning, 'emit').and.callThrough(); let row = grid.getRowByIndex(0); const rowID = row.key; row.pin(); // Check pinned state with getRowByIndex after pin action expect(row.pinned).toBe(true); expect(grid.rowPinning.emit).toHaveBeenCalledTimes(1); expect(grid.rowPinning.emit).toHaveBeenCalledWith({ rowID, insertAtIndex: 0, isPinned: true, row }); row = grid.getRowByIndex(0); row.unpin(); // Check pinned state with getRowByIndex after unpin action expect(row.pinned).toBe(false); expect(grid.rowPinning.emit).toHaveBeenCalledTimes(2); }); it('should emit rowPinned on pin/unpin.', () => { spyOn(grid.rowPinned, 'emit').and.callThrough(); const row = grid.getRowByIndex(0); const rowID = row.key; row.pin(); // Check pinned state with getRowByIndex after pin action expect(row.pinned).toBe(true); expect(grid.rowPinned.emit).toHaveBeenCalledTimes(1); expect(grid.rowPinned.emit).toHaveBeenCalledWith({ rowID, insertAtIndex: 0, isPinned: true, row }); row.unpin(); // Check pinned state with getRowByIndex after unpin action expect(row.pinned).toBe(false); expect(grid.rowPinned.emit).toHaveBeenCalledTimes(2); }); it('should pin/unpin via grid API methods.', () => { // pin 2nd row grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].context.index).toBe(0); expect(pinRowContainer[0].children[0].nativeElement).toBe(grid.gridAPI.get_row_by_index(0).nativeElement); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[0]); // unpin 2nd row grid.unpinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(0); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[1]); }); it('should pin/unpin via row API methods.', () => { // pin 2nd row let row = grid.gridAPI.get_row_by_index(1); row.pin(); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[0]); // unpin row = grid.gridAPI.get_row_by_index(0); row.unpin(); expect(grid.pinnedRows.length).toBe(0); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(0); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[1]); }); it('should pin/unpin via row pinned setter.', () => { // pin 2nd row let row = grid.gridAPI.get_row_by_index(1); row.pinned = true; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[0]); // unpin row = grid.gridAPI.get_row_by_index(0); row.pinned = false; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(0); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[1]); }); it('should search in both pinned and unpinned rows.', () => { // pin 1st row let row = grid.gridAPI.get_row_by_index(0); row.pinned = true; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); let finds = grid.findNext('mari'); fix.detectChanges(); const fixNativeElement = fix.debugElement.nativeElement; let spans = fixNativeElement.querySelectorAll('.igx-highlight'); expect(spans.length).toBe(2); expect(finds).toEqual(3); finds = grid.findNext('antonio'); fix.detectChanges(); spans = fixNativeElement.querySelectorAll('.igx-highlight'); expect(spans.length).toBe(2); expect(finds).toEqual(2); // pin 3rd row row = grid.gridAPI.get_row_by_index(2); row.pinned = true; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(2); finds = grid.findNext('antonio'); fix.detectChanges(); spans = fixNativeElement.querySelectorAll('.igx-highlight'); expect(spans.length).toBe(2); expect(finds).toEqual(2); }); it('should allow pinning onInit', () => { expect(() => { fix = TestBed.createComponent(GridRowPinningComponent); grid = fix.componentInstance.instance; fix.detectChanges(); grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); }).not.toThrow(); expect(grid.pinnedRows.length).toBe(1); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); }); it('should pin rows when columns are grouped.', () => { grid.height = '650px'; fix.detectChanges(); // pin 1st and 2nd data row grid.pinRow(fix.componentInstance.data[0]); grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); // group by string column grid.groupBy({ fieldName: 'ContactTitle', dir: SortingDirection.Desc, ignoreCase: false }); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(2); // verify rows const groupRows = grid.groupsRowList.toArray(); const dataRows = grid.dataRowList.toArray(); expect(groupRows.length).toEqual(2); expect(dataRows.length).toEqual(9); expect(groupRows[0].groupRow.records[0].ID).toEqual('ALFKI'); expect(groupRows[0].groupRow.records[1].ID).toEqual('AROUT'); // pin 4th data row with ID:AROUT grid.pinRow(fix.componentInstance.data[3]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(3); // make sure the pinned rows is in the unpinned area as disabled row expect(groupRows[0].groupRow.records[0].ID).toEqual('ALFKI'); expect(groupRows[0].groupRow.records[1].ID).toEqual('AROUT'); expect(groupRows[0].groupRow.records[2].ID).toEqual('BLAUS'); }); it('should apply filtering to both pinned and unpinned rows.', () => { grid.gridAPI.get_row_by_index(1).pin(); fix.detectChanges(); grid.gridAPI.get_row_by_index(5).pin(); fix.detectChanges(); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[1].context.rowID).toBe(fix.componentInstance.data[4]); grid.filter('ID', 'B', IgxStringFilteringOperand.instance().condition('contains'), false); fix.detectChanges(); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[4]); }); it('should calculate global summaries correctly when filtering is applied.', () => { grid.getColumnByName('ID').hasSummary = true; fix.detectChanges(); grid.filter('ID', 'BERGS', IgxStringFilteringOperand.instance().condition('contains'), false); fix.detectChanges(); let summaryRow = GridSummaryFunctions.getRootSummaryRow(fix); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['1']); // pin row grid.gridAPI.get_row_by_index(0).pin(); fix.detectChanges(); summaryRow = GridSummaryFunctions.getRootSummaryRow(fix); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['1']); }); it('should remove pinned container and recalculate sizes when all pinned records are filtered out.', () => { grid.gridAPI.get_row_by_index(1).pin(); fix.detectChanges(); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); fix.detectChanges(); let expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); grid.filter('ID', 'B', IgxStringFilteringOperand.instance().condition('startsWith'), false); fix.detectChanges(); pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(0); fix.detectChanges(); expect(grid.pinnedRowHeight).toBe(0); expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); }); it('should return correct filterData collection.', () => { grid.gridAPI.get_row_by_index(1).pin(); fix.detectChanges(); grid.gridAPI.get_row_by_index(6).pin(); fix.detectChanges(); grid.filter('ID', 'B', IgxStringFilteringOperand.instance().condition('contains'), false); fix.detectChanges(); let gridFilterData = grid.filteredData; expect(gridFilterData.length).toBe(8); expect(gridFilterData[0].ID).toBe('BLAUS'); expect(gridFilterData[1].ID).toBe('BERGS'); fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fix.detectChanges(); gridFilterData = grid.filteredData; expect(gridFilterData.length).toBe(8); expect(gridFilterData[0].ID).toBe('BLAUS'); expect(gridFilterData[1].ID).toBe('BERGS'); }); it('should apply sorting to both pinned and unpinned rows.', () => { grid.gridAPI.get_row_by_index(1).pin(); grid.gridAPI.get_row_by_index(6).pin(); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[5]); grid.sort({ fieldName: 'ID', dir: SortingDirection.Desc, ignoreCase: false }); fix.detectChanges(); // check pinned rows data is sorted expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[5]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[1]); // check unpinned rows data is sorted const lastIndex = fix.componentInstance.data.length - 1; expect(grid.gridAPI.get_row_by_index(2).rowID).toBe(fix.componentInstance.data[lastIndex]); }); }); describe('Row pinning with Master Detail View', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningWithMDVComponent); fix.detectChanges(); grid = fix.componentInstance.instance; tick(); fix.detectChanges(); })); it('should be in view when expanded and pinning row to bottom of the grid.', async () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fix.detectChanges(); // pin 1st row const row = grid.gridAPI.get_row_by_index(0); row.pinned = true; fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); GridFunctions.toggleMasterRow(fix, grid.pinnedRows[0]); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const firstRowIconName = GridFunctions.getRowExpandIconName(grid.rowList.toArray()[0]); const pinnedRow = grid.pinnedRows[0]; expect(grid.expansionStates.size).toEqual(1); expect(grid.expansionStates.has(pinnedRow.rowID)).toBeTruthy(); expect(grid.expansionStates.get(pinnedRow.rowID)).toBeTruthy(); // disabled row should have expand icon expect(firstRowIconName).toEqual('expand_more'); // disabled row should have chip const cell = grid.gridAPI.get_row_by_index(0).cells.first; expect(cell.nativeElement.getElementsByClassName('igx-grid__td--pinned-chip').length).toBe(1); // pinned row shouldn't have expand icon const hasIconForPinnedRow = pinnedRow.cells.first.nativeElement.querySelector('igx-icon'); expect(hasIconForPinnedRow).toBeNull(); // check last pinned row is fully in view expect(pinnedRow.nativeElement.getBoundingClientRect().bottom - grid.tbody.nativeElement.getBoundingClientRect().bottom) .toBe(0); }); it('should calculate global summaries with both pinned and unpinned collections', () => { // enable summaries for each column grid.columns.forEach(c => { c.hasSummary = true; }); fix.detectChanges(); grid.groupBy({ fieldName: 'ContactTitle', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); let row = grid.gridAPI.get_row_by_index(1); row.pinned = true; fix.detectChanges(); let summaryRow = GridSummaryFunctions.getRootSummaryRow(fix); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['27']); row = grid.pinnedRows[0]; row.pinned = false; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); summaryRow = GridSummaryFunctions.getRootSummaryRow(fix); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['27']); }); it('should calculate groupby row summaries only within unpinned collection', () => { // enable summaries for each column grid.columns.forEach(c => { c.hasSummary = true; }); fix.detectChanges(); grid.groupBy({ fieldName: 'ContactTitle', dir: SortingDirection.Asc, ignoreCase: false }); fix.detectChanges(); let row = grid.gridAPI.get_row_by_index(1); row.pinned = true; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); // get first summary row and make sure that the pinned record is not contained within the calculations let summaryRow = GridSummaryFunctions.getSummaryRowByDataRowIndex(fix, 4); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['2']); // unpin the row and check if the summary is recalculated row = grid.pinnedRows[0]; row.pinned = false; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); summaryRow = GridSummaryFunctions.getSummaryRowByDataRowIndex(fix, 3); GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['2']); }); }); describe('Paging', () => { let paginator: IgxPaginatorComponent; beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningComponent); fix.componentInstance.createSimpleData(12); fix.detectChanges(); grid = fix.componentInstance.instance; fix.componentInstance.paging = true; fix.detectChanges(); grid.perPage = 5; fix.detectChanges(); tick(); paginator = fix.debugElement.query(By.directive(IgxPaginatorComponent)).componentInstance; })); it('should correctly apply paging state for grid and paginator when there are pinned rows.', () => { // pin the first row grid.gridAPI.get_row_by_index(0).pin(); expect(grid.rowList.length).toEqual(6); expect(grid.perPage).toEqual(5); expect(paginator.perPage).toEqual(5); expect(paginator.totalRecords).toEqual(12); expect(paginator.totalPages).toEqual(3); // pin the second row grid.gridAPI.get_row_by_index(2).pin(); expect(grid.rowList.length).toEqual(7); expect(grid.perPage).toEqual(5); expect(paginator.perPage).toEqual(5); expect(paginator.totalRecords).toEqual(12); expect(paginator.totalPages).toEqual(3); }); it('should have the correct records shown for pages with pinned rows', () => { grid.gridAPI.get_row_by_index(0).pin(); let rows = grid.rowList.toArray(); [1, 1, 2, 3, 4, 5].forEach((x, index) => expect(rows[index].cells.first.value).toEqual(x)); grid.paginate(2); fix.detectChanges(); rows = grid.rowList.toArray(); [1, 11, 12].forEach((x, index) => expect(rows[index].cells.first.value).toEqual(x)); }); }); describe(' Editing ', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningWithTransactionsComponent); fix.detectChanges(); grid = fix.componentInstance.instance; tick(); fix.detectChanges(); })); it('should allow pinning edited row.', () => { grid.updateCell('New value', 'ANTON', 'CompanyName'); fix.detectChanges(); grid.pinRow('ANTON'); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe('ANTON'); expect(pinRowContainer[0].children[0].context.rowData.CompanyName).toBe('New value'); }); it('should allow pinning deleted row.', () => { grid.deleteRow('ALFKI'); fix.detectChanges(); grid.pinRow('ALFKI'); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe('ALFKI'); }); it('should allow pinning added row.', () => { grid.addRow({ ID: 'Test', CompanyName: 'Test' }); fix.detectChanges(); grid.pinRow('Test'); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe('Test'); }); it('should stop editing when edited row is pinned/unpinned.', () => { grid.getColumnByName('CompanyName').editable = true; fix.detectChanges(); let cell = grid.getCellByColumn(0, 'CompanyName'); let cellDomNumber = fix.debugElement.queryAll(By.css(CELL_CSS_CLASS))[1]; cellDomNumber.triggerEventHandler('dblclick', {}); fix.detectChanges(); expect(cell.editMode).toBeTruthy(); grid.pinRow(cell.row.key); fix.detectChanges(); cell = grid.getCellByColumn(0, 'CompanyName'); expect(cell.editMode).toBeFalsy(); cellDomNumber = fix.debugElement.queryAll(By.css(CELL_CSS_CLASS))[1]; cellDomNumber.triggerEventHandler('dblclick', {}); fix.detectChanges(); expect(cell.editMode).toBeTruthy(); grid.unpinRow(cell.row.key); fix.detectChanges(); cell = grid.getCellByColumn(0, 'CompanyName'); expect(cell.editMode).toBeFalsy(); }); }); describe('Row pinning with MRL', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningWithMRLComponent); fix.detectChanges(); grid = fix.componentInstance.instance; tick(); fix.detectChanges(); })); it('should pin/unpin correctly to top', () => { // pin grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].nativeElement).toBe(grid.gridAPI.get_row_by_index(0).nativeElement); expect(grid.gridAPI.get_row_by_index(0).pinned).toBeTruthy(); const gridPinnedRow = grid.pinnedRows[0]; const pinnedRowCells = gridPinnedRow.cells.toArray(); // const headerCells = grid.headerGroups.first.children.toArray(); const headerCells = grid.headerGroupsList[0].children.toArray(); // headers are aligned to cells GridFunctions.verifyLayoutHeadersAreAligned(headerCells, pinnedRowCells); GridFunctions.verifyDOMMatchesLayoutSettings(gridPinnedRow, fix.componentInstance.colGroups); // unpin const row = grid.pinnedRows[0]; row.pinned = false; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); expect(row.pinned).toBeFalsy(); const gridUnpinnedRow = grid.gridAPI.get_row_by_index(1); const unpinnedRowCells = gridUnpinnedRow.cells.toArray(); GridFunctions.verifyLayoutHeadersAreAligned(headerCells, unpinnedRowCells); GridFunctions.verifyDOMMatchesLayoutSettings(gridUnpinnedRow, fix.componentInstance.colGroups); }); it('should pin/unpin correctly to bottom', () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fix.detectChanges(); // pin grid.pinRow(fix.componentInstance.data[1]); fix.detectChanges(); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].nativeElement) .toBe(grid.gridAPI.get_row_by_index(fix.componentInstance.data.length).nativeElement); expect(grid.gridAPI.get_row_by_index(fix.componentInstance.data.length).pinned).toBeTruthy(); const gridPinnedRow = grid.pinnedRows[0]; const pinnedRowCells = gridPinnedRow.cells.toArray(); // const headerCells = grid.headerGroups.first.children.toArray(); const headerCells = grid.headerGroupsList[0].children.toArray(); // headers are aligned to cells GridFunctions.verifyLayoutHeadersAreAligned(headerCells, pinnedRowCells); GridFunctions.verifyDOMMatchesLayoutSettings(gridPinnedRow, fix.componentInstance.colGroups); // unpin const row = grid.pinnedRows[0]; row.pinned = false; fix.detectChanges(); expect(grid.pinnedRows.length).toBe(0); expect(row.pinned).toBeFalsy(); const gridUnpinnedRow = grid.gridAPI.get_row_by_index(1); const unpinnedRowCells = gridUnpinnedRow.cells.toArray(); GridFunctions.verifyLayoutHeadersAreAligned(headerCells, unpinnedRowCells); GridFunctions.verifyDOMMatchesLayoutSettings(gridUnpinnedRow, fix.componentInstance.colGroups); }); it('should test getRowByIndex API members.', () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fix.detectChanges(); // pin 1st grid.pinRow(fix.componentInstance.data[0]); fix.detectChanges(); const firstRow = grid.getRowByIndex(0); // Check if the row is pinned to the bottom through the Row pinned API expect(firstRow.pinned).toBe(true); // Toggle pin state with row API firstRow.pinned = false; expect(firstRow.pinned).toBe(false); fix.detectChanges(); firstRow.pinned = true; expect(firstRow.pinned).toBe(true); fix.detectChanges(); // Check dom existence expect(grid.pinnedRows.length).toBe(1); let pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children[0].nativeElement) .toBe(grid.gridAPI.get_row_by_index(fix.componentInstance.data.length).nativeElement); // Pin/Unpin with the methods firstRow.unpin(); expect(firstRow.pinned).toBe(false); firstRow.pin(); expect(firstRow.pinned).toBe(true); // Check again pinned row presence pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children[0].nativeElement) .toBe(grid.gridAPI.get_row_by_index(fix.componentInstance.data.length).nativeElement); // Check select firstRow.selected = true; fix.detectChanges(); expect(firstRow.selected).toBe(true); // Check pinned row existence after the selection expect(pinRowContainer[0].children[0].nativeElement.offsetParent).toBeDefined(); expect(pinRowContainer[0].children[0].nativeElement.offsetWidth).toBeGreaterThan(0); firstRow.selected = false; fix.detectChanges(); expect(firstRow.selected).toBe(false); // Delete row firstRow.delete(); fix.detectChanges(); expect(grid.gridAPI.get_row_by_index(0).rowData.ID).toEqual('ANATR'); // TO DO Check pinned row existence after the row deletion expect(pinRowContainer[0].children[0].nativeElement.offsetParent).toBeNull(); expect(pinRowContainer[0].children[0].nativeElement.offsetWidth).toEqual(0); // Check API methods expect(firstRow.key).toBeTruthy(); expect(firstRow.data).toBeTruthy(); expect(firstRow.pinned).toBe(true); }); }); describe(' Hiding', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningComponent); fix.detectChanges(); grid = fix.componentInstance.instance; tick(); fix.detectChanges(); })); it('should hide columns in pinned and unpinned area', () => { // pin 2nd data row grid.pinRow(fix.componentInstance.data[1]); const hiddenCol = grid.columns[1]; hiddenCol.hidden = true; fix.detectChanges(); const pinnedCells = grid.pinnedRows[0].cells; expect(pinnedCells.filter(cell => cell.column.field === hiddenCol.field).length).toBe(0); const unpinnedCells = grid.rowList.first.cells; expect(unpinnedCells.filter(cell => cell.column.field === hiddenCol.field).length).toBe(0); expect(pinnedCells.length).toBe(unpinnedCells.length); const headerCells = grid.headerCellList; expect(headerCells.filter(cell => cell.column.field === hiddenCol.field).length).toBe(0); expect(grid.pinnedRows.length).toBe(1); const pinRowContainer = fix.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe(fix.componentInstance.data[1]); expect(pinRowContainer[0].children[0].nativeElement).toBe(grid.gridAPI.get_row_by_index(0).nativeElement); expect(grid.gridAPI.get_row_by_index(0).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(1).rowID).toBe(fix.componentInstance.data[0]); expect(grid.gridAPI.get_row_by_index(2).rowID).toBe(fix.componentInstance.data[1]); expect(grid.gridAPI.get_row_by_index(3).rowID).toBe(fix.componentInstance.data[2]); fix.detectChanges(); // 1 records pinned + 2px border expect(grid.pinnedRowHeight).toBe(grid.renderedRowHeight + 2); const expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); }); it('should keep the scrollbar sizes correct when partially filtering out pinned records', () => { grid.gridAPI.get_row_by_index(1).pin(); grid.gridAPI.get_row_by_index(3).pin(); grid.gridAPI.get_row_by_index(5).pin(); grid.gridAPI.get_row_by_index(7).pin(); fix.detectChanges(); // 4 records pinned + 2px border expect(grid.pinnedRowHeight).toBe(4 * grid.renderedRowHeight + 2); let expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); grid.filter('ContactTitle', 'Owner', IgxStringFilteringOperand.instance().condition('contains'), false); fix.detectChanges(); // 2 records pinned + 2px border expect(grid.pinnedRowHeight).toBe(2 * grid.renderedRowHeight + 2); expectedHeight = parseInt(grid.height, 10) - grid.pinnedRowHeight - 18 - grid.theadRow.nativeElement.offsetHeight; expect(grid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); }); }); describe(' Cell Editing', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningComponent); fix.detectChanges(); // enable cell editing for column grid = fix.componentInstance.instance; grid.getColumnByName('CompanyName').editable = true; })); it('should enter edit mode for the next editable cell when tabbing.', () => { const gridContent = GridFunctions.getGridContent(fix); grid.gridAPI.get_row_by_index(0).pin(); grid.gridAPI.get_row_by_index(3).pin(); const firstEditable = grid.gridAPI.get_cell_by_index(0, 'CompanyName'); const secondEditable = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const thirdEditable = grid.gridAPI.get_cell_by_index(3, 'CompanyName'); const fourthEditable = grid.gridAPI.get_cell_by_index(5, 'CompanyName'); // enter edit mode for pinned row UIInteractions.simulateDoubleClickAndSelectEvent(firstEditable); fix.detectChanges(); expect(firstEditable.editMode).toBeTruthy(); // press tab on edited cell UIInteractions.triggerEventHandlerKeyDown('tab', gridContent); fix.detectChanges(); expect(firstEditable.editMode).toBeFalsy(); expect(secondEditable.editMode).toBeTruthy(); // press tab on edited cell UIInteractions.triggerEventHandlerKeyDown('tab', gridContent); fix.detectChanges(); expect(secondEditable.editMode).toBeFalsy(); expect(thirdEditable.editMode).toBeTruthy(); UIInteractions.triggerEventHandlerKeyDown('tab', gridContent); fix.detectChanges(); expect(thirdEditable.editMode).toBeFalsy(); expect(fourthEditable.editMode).toBeTruthy(); }); it('should enter edit mode for the previous editable cell when shift+tabbing.', () => { const gridContent = GridFunctions.getGridContent(fix); grid.gridAPI.get_row_by_index(0).pin(); grid.gridAPI.get_row_by_index(3).pin(); const firstEditable = grid.gridAPI.get_cell_by_index(0, 'CompanyName'); const secondEditable = grid.gridAPI.get_cell_by_index(1, 'CompanyName'); const thirdEditable = grid.gridAPI.get_cell_by_index(3, 'CompanyName'); const fourthEditable = grid.gridAPI.get_cell_by_index(5, 'CompanyName'); // enter edit mode for unpinned row UIInteractions.simulateDoubleClickAndSelectEvent(fourthEditable); fix.detectChanges(); expect(fourthEditable.editMode).toBeTruthy(); // press shift+tab on edited cell UIInteractions.triggerEventHandlerKeyDown('tab', gridContent, false, true); fix.detectChanges(); expect(fourthEditable.editMode).toBeFalsy(); expect(thirdEditable.editMode).toBeTruthy(); // press shift+tab on edited cell UIInteractions.triggerEventHandlerKeyDown('tab', gridContent, false, true); fix.detectChanges(); expect(thirdEditable.editMode).toBeFalsy(); expect(secondEditable.editMode).toBeTruthy(); // press shift+tab on edited cell UIInteractions.triggerEventHandlerKeyDown('tab', gridContent, false, true); fix.detectChanges(); expect(secondEditable.editMode).toBeFalsy(); expect(firstEditable.editMode).toBeTruthy(); }); }); describe(' Navigation', () => { let gridContent: DebugElement; beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningComponent); fix.detectChanges(); grid = fix.componentInstance.instance; setupGridScrollDetection(fix, grid); gridContent = GridFunctions.getGridContent(fix); })); it('should navigate to bottom from top pinned row using Ctrl+ArrowDown', async () => { grid.gridAPI.get_row_by_index(5).pin(); const firstRowCell = grid.gridAPI.get_row_by_index(0).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridContent, false, false, true); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastRowCell = grid.getRowByIndex(27).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; // expect(selectedCell).toBe(lastRowCell); expect(selectedCell.row.index).toBe(lastRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(lastRowCell.column.visibleIndex); }); it('should navigate and scroll to first unpinned row from top pinned row using ArrowDown', async () => { grid.gridAPI.get_row_by_index(5).pin(); grid.navigateTo(10); await wait(DEBOUNCE_TIME); fix.detectChanges(); const firstRowCell = grid.gridAPI.get_row_by_index(0).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridContent); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const secondRowCell = grid.getRowByIndex(1).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(secondRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(secondRowCell.column.visibleIndex); }); it('should navigate to top pinned row from bottom unpinned row without scrolling using Ctrl+ArrowUp', async () => { grid.gridAPI.get_row_by_index(5).pin(); grid.navigateTo(27); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); expect(grid.verticalScrollContainer.getScroll().scrollTop).not.toEqual(0); const lastRowCell = grid.gridAPI.get_row_by_index(27).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(lastRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridContent, false, false, true); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const firstRowCell = grid.getRowByIndex(0).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(firstRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(firstRowCell.column.visibleIndex); expect(grid.verticalScrollContainer.getScroll().scrollTop).not.toEqual(0); }); it('should navigate to top pinned row from first unpinned row using ArrowUp', async () => { grid.gridAPI.get_row_by_index(5).pin(); grid.gridAPI.get_row_by_index(1).pin(); const thirdRowCell = grid.gridAPI.get_row_by_index(2).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(thirdRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); expect(grid.navigation.activeNode.row).toBe(2); expect(grid.navigation.activeNode.column).toBe(1); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridContent); await wait(DEBOUNCE_TIME); fix.detectChanges(); const secondRowCell = grid.getRowByIndex(1).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(secondRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(secondRowCell.column.visibleIndex); }); it('should navigate and scroll to top from bottom pinned row using Ctrl+ArrowUp', async () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; grid.gridAPI.get_row_by_index(5).pin(); grid.navigateTo(26); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastRowCell = grid.gridAPI.get_row_by_index(27).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(lastRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); expect(grid.navigation.activeNode.row).toBe(27); expect(grid.navigation.activeNode.column).toBe(1); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridContent, false, false, true); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const firstRowCell = grid.getRowByIndex(0).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(firstRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(firstRowCell.column.visibleIndex); }); it('should navigate to last unpinned row from bottom pinned row using ArrowUp', async () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; grid.gridAPI.get_row_by_index(5).pin(); fix.detectChanges(); const firstRowCell = grid.gridAPI.get_row_by_index(27).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowUp', gridContent); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastUnpinnedRowCell = grid.getRowByIndex(26).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(lastUnpinnedRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(lastUnpinnedRowCell.column.visibleIndex); }); it('should navigate to bottom pinned row from top unpinned row without scrolling using Ctrl+ArrowDown', async () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; grid.gridAPI.get_row_by_index(5).pin(); expect(grid.verticalScrollContainer.getScroll().scrollTop).toEqual(0); const firstRowCell = grid.gridAPI.get_row_by_index(0).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridContent, false, false, true); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastRowCell = grid.getRowByIndex(27).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(lastRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(lastRowCell.column.visibleIndex); expect(grid.verticalScrollContainer.getScroll().scrollTop).toEqual(0); }); it('should navigate to bottom pinned row from last unpinned row using ArrowDown', async () => { fix.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; grid.gridAPI.get_row_by_index(5).pin(); grid.gridAPI.get_row_by_index(1).pin(); await wait(DEBOUNCE_TIME); grid.navigateTo(26); await wait(DEBOUNCE_TIME); fix.detectChanges(); await wait(DEBOUNCE_TIME); fix.detectChanges(); const firstRowCell = grid.gridAPI.get_row_by_index(26).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); expect(grid.navigation.activeNode.row).toBe(26); expect(grid.navigation.activeNode.column).toBe(1); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridContent); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastRowCell = grid.getRowByIndex(27).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(lastRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(lastRowCell.column.visibleIndex); }); it('should navigate down from pinned to unpinned row when there are filtered out pinned rows', async () => { grid.gridAPI.get_row_by_index(5).pin(); grid.gridAPI.get_row_by_index(1).pin(); grid.filter('ID', 'B', IgxStringFilteringOperand.instance().condition('contains'), false); fix.detectChanges(); const firstRowCell = grid.gridAPI.get_row_by_index(0).cells.toArray()[1]; UIInteractions.simulateClickAndSelectEvent(firstRowCell); await wait(DEBOUNCE_TIME); fix.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('ArrowDown', gridContent); await wait(DEBOUNCE_TIME); fix.detectChanges(); const lastRowCell = grid.getRowByIndex(1).cells[1]; const selectedCell = fix.componentInstance.instance.selectedCells[0]; expect(selectedCell.row.index).toBe(lastRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(lastRowCell.column.visibleIndex); }); }); describe(' Initial pinning', () => { let gridContent: DebugElement; beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowPinningWithInitialPinningComponent); fix.detectChanges(); grid = fix.componentInstance.grid1; setupGridScrollDetection(fix, grid); gridContent = GridFunctions.getGridContent(fix); })); it('should pin rows on OnInit.', () => { fix.detectChanges(); expect(grid.hasPinnedRecords).toBeTrue(); }); }); describe('Conditional row styling', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(GridRowConditionalStylingComponent); fix.detectChanges(); grid = fix.componentInstance.grid; tick(); fix.detectChanges(); })); it('Shoud be able to conditionally style rows. Check is the class present in the row native element class list', () => { fix.detectChanges(); const firstRow = grid.gridAPI.get_row_by_index(0); const fourthRow = grid.gridAPI.get_row_by_index(3); expect(firstRow).toBeDefined(); expect(firstRow.element.nativeElement.classList.contains('eventRow')).toBeTrue(); expect(firstRow.element.nativeElement.classList.contains('oddRow')).toBeFalse(); expect(fourthRow.element.nativeElement.classList.contains('eventRow')).toBeFalse(); expect(fourthRow.element.nativeElement.classList.contains('oddRow')).toBeTrue(); }); it('Should apply custom CSS bindings to the grid cells/rows. Check the style attribute to match each binding', () => { const evenColStyles = { background: (row) => row.index % 2 === 0 ? 'gray' : 'white', animation: '0.75s popin' }; fix.detectChanges(); grid.rowStyles = evenColStyles; grid.notifyChanges(true); fix.detectChanges(); const firstRow = grid.gridAPI.get_row_by_index(0); const fourthRow = grid.gridAPI.get_row_by_index(3); const expectedEvenStyles = 'background: gray; animation: 0.75s ease 0s 1 normal none running popin;'; const expectedOddStyles = 'background: white; animation: 0.75s ease 0s 1 normal none running popin;'; expect(firstRow.element.nativeElement.style.cssText).toEqual(expectedEvenStyles); expect(fourthRow.element.nativeElement.style.cssText).toEqual(expectedOddStyles); }); }); }); @Component({ template: ` <igx-grid [allowFiltering]="true" [pinning]='pinningConfig' [width]='"800px"' [height]='"500px"' [data]="data" [autoGenerate]="true"> <igx-paginator *ngIf="paging"></igx-paginator> </igx-grid> ` }) export class GridRowPinningComponent { @ViewChild(IgxGridComponent, { read: IgxGridComponent, static: true }) public instance: IgxGridComponent; public paging = false; public data: any[] = SampleTestData.contactInfoDataFull(); public pinningConfig: IPinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Top }; public createSimpleData(count: number) { this.data = Array(count).fill({}).map((x, idx) => x = { idx: idx + 1 }); } } @Component({ template: ` <igx-grid [data]="data" height="500px" [pinning]='pinningConfig' [rowSelection]="'single'" [rowEditable]="true"> <igx-column-layout *ngFor='let group of colGroups'> <igx-column *ngFor='let col of group.columns' [rowStart]="col.rowStart" [colStart]="col.colStart" [width]='col.width' [colEnd]="col.colEnd" [rowEnd]="col.rowEnd" [field]='col.field'></igx-column> </igx-column-layout> </igx-grid> ` }) export class GridRowPinningWithMRLComponent extends GridRowPinningComponent { public cols: Array<any> = [ { field: 'ID', rowStart: 1, colStart: 1 }, { field: 'CompanyName', rowStart: 1, colStart: 2 }, { field: 'ContactName', rowStart: 1, colStart: 3 }, { field: 'ContactTitle', rowStart: 2, colStart: 1, rowEnd: 4, colEnd: 4 }, ]; public colGroups = [ { group: 'group1', columns: this.cols } ]; } @Component({ template: ` <igx-grid [pinning]='pinningConfig' [width]='"800px"' [height]='"500px"' [data]="data" [autoGenerate]="true"> <ng-template igxGridDetail let-dataItem> <div> <div><span class='categoryStyle'>Country:</span> {{dataItem.Country}}</div> <div><span class='categoryStyle'>City:</span> {{dataItem.City}}</div> <div><span class='categoryStyle'>Address:</span> {{dataItem.Address}}</div> </div> </ng-template> </igx-grid>` }) export class GridRowPinningWithMDVComponent extends GridRowPinningComponent { } @Component({ template: ` <igx-grid [pinning]='pinningConfig' primaryKey='ID' [width]='"800px"' [height]='"500px"' [batchEditing]="true" [data]="data" [autoGenerate]="true"> </igx-grid> ` }) export class GridRowPinningWithTransactionsComponent extends GridRowPinningComponent { } @Component({ template: ` <igx-grid #grid1 [allowFiltering]="true" [pinning]='pinningConfig' [width]='"800px"' [height]='"500px"' [data]="data" [autoGenerate]="true"> </igx-grid> ` }) export class GridRowPinningWithInitialPinningComponent implements OnInit { @ViewChild(IgxGridComponent, { read: IgxGridComponent, static: true }) public grid1: IgxGridComponent; public data: any[] = SampleTestData.contactInfoDataFull(); public pinningConfig: IPinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Top }; public ngOnInit(): void { this.grid1.pinRow(this.data[0].ID); } }
the_stack
import { calculateFairnessMetric } from "./calculateFairnessMetric"; import { FairnessModes } from "./FairnessMetrics"; const closeTo = (expected: number, precision = 2) => ({ asymmetricMatch: (actual: number) => Math.abs(expected - actual) < Math.pow(10, -precision) / 2 }); describe("calculateFairnessMetric", () => { it("should return NaN for no values", () => { const mockValue = { bins: [], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { overall: Number.NaN }; expect(result).toEqual(expectedResult); }); it("should return NaN for invalid FairnessMode", () => { const mockValue = { bins: [], global: 0.5 }; const result = calculateFairnessMetric( mockValue, "invalid" as FairnessModes.Max ); const expectedResult = { overall: Number.NaN }; expect(result).toEqual(expectedResult); }); it("should calculate difference without binBounds correctly", () => { const mockValue = { bins: [0.5, 0.2], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { overall: 0.3 }; expect(result).toEqual(expectedResult); }); it("should return only overall result if binBounds falsely", () => { const mockValue = { binBounds: [], bins: [0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (with overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.55 }, { lower: 0.45, upper: 0.75 } ], bins: [0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: 0, upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (with overlap and reverse order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.75 }, { lower: 0.25, upper: 0.55 } ], bins: [0.7, 0.3], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: 0, upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (with complete overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.2, upper: 0.8 }, { lower: 0.5, upper: 0.7 } ], bins: [0.5, 0.6], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: 0, upper: closeTo(0.5) }, overall: closeTo(0.1) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (with complete overlap and reversed order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.5, upper: 0.7 }, { lower: 0.2, upper: 0.8 } ], bins: [0.5, 0.6], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: 0, upper: closeTo(0.5) }, overall: closeTo(0.1) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (without overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.35 }, { lower: 0.65, upper: 0.75 } ], bins: [0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0.3), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference (without overlap and reverse order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.65, upper: 0.75 }, { lower: 0.25, upper: 0.35 } ], bins: [0.7, 0.3], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0.3), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference with 3+ groups correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.35 }, { lower: 0.65, upper: 0.75 }, { lower: 0.45, upper: 0.55 } ], bins: [0.3, 0.7, 0.5], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0.3), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference with 3+ groups correctly (permuted order)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.55 }, { lower: 0.25, upper: 0.35 }, { lower: 0.65, upper: 0.75 } ], bins: [0.5, 0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0.3), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference with 3+ groups correctly (with overlap)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.7 }, { lower: 0.25, upper: 0.35 }, { lower: 0.65, upper: 0.75 } ], bins: [0.5, 0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0.3), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should calculate difference with 3+ groups correctly (with all overlap)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.7 }, { lower: 0.25, upper: 0.55 }, { lower: 0.45, upper: 0.75 } ], bins: [0.5, 0.3, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { bounds: { lower: closeTo(0), upper: closeTo(0.5) }, overall: closeTo(0.4) }; expect(result).toMatchObject(expectedResult); }); it("should handle difference case with large binBound that provides the largest and smallest bounds", () => { const mockValue = { binBounds: [ { lower: 0.1, upper: 0.3 }, { lower: 0.7, upper: 0.9 }, { lower: 0.08, upper: 0.95 } ], bins: [0.2, 0.8, 0.5], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Difference); const expectedResult = { // from the 1st and 2nd point: the lower bound = 0.7 - 0.3 = 0.4 // from the 1st and 3rd point: the upper bound = 0.95 - 0.1 = 0.85 // the largest difference between nominal bins: overall = 0.8 - 0.2 = 0.6 bounds: { lower: closeTo(0.4), upper: closeTo(0.85) }, overall: closeTo(0.6) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio without binBounds correctly", () => { const mockValue = { bins: [0.5, 0.2], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { overall: 0.4 }; expect(result).toEqual(expectedResult); }); it("should calculate ratio (with overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.6 }, { lower: 0.4, upper: 0.75 } ], bins: [0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: 1 }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio (with overlap and reverse order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.4, upper: 0.75 }, { lower: 0.25, upper: 0.6 } ], bins: [0.7, 0.35], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: 1 }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio (with complete overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.2, upper: 0.8 }, { lower: 0.5, upper: 0.7 } ], bins: [0.5, 0.6], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.29), upper: 1 }, overall: closeTo(0.83) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio (with complete overlap and reversed order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.5, upper: 0.7 }, { lower: 0.2, upper: 0.8 } ], bins: [0.5, 0.6], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.29), upper: 1 }, overall: closeTo(0.83) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio (without overlap) correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 } ], bins: [0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(0.67) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio (without overlap and reverse order) correctly", () => { const mockValue = { binBounds: [ { lower: 0.6, upper: 0.75 }, { lower: 0.25, upper: 0.4 } ], bins: [0.7, 0.35], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(0.67) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio with 3+ groups correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 }, { lower: 0.45, upper: 0.55 } ], bins: [0.35, 0.7, 0.5], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(0.67) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio with 3+ groups correctly (permuted order)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.55 }, { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 } ], bins: [0.5, 0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(0.67) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio with 3+ groups correctly (with overlap)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.65 }, { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 } ], bins: [0.5, 0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(0.67) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should calculate ratio with 3+ groups correctly (with all overlap)", () => { const mockValue = { binBounds: [ { lower: 0.45, upper: 0.7 }, { lower: 0.25, upper: 0.55 }, { lower: 0.45, upper: 0.75 } ], bins: [0.5, 0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { bounds: { lower: closeTo(0.33), upper: closeTo(1) }, overall: closeTo(0.5) }; expect(result).toMatchObject(expectedResult); }); it("should handle ratio case with large binBound that provides the largest and smallest bounds", () => { const mockValue = { binBounds: [ { lower: 0.1, upper: 0.3 }, { lower: 0.7, upper: 0.9 }, { lower: 0.08, upper: 0.95 } ], bins: [0.2, 0.8, 0.5], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Ratio); const expectedResult = { // from the 1st and 3rd point: the lower bound = 0.08 / 0.9 // from the 1st and 2nd point: the upper bound = 0.3 / 0.7 // the smallest ratio between nominal bins: overall = 0.2 / 0.8 bounds: { lower: closeTo(0.09), upper: closeTo(0.43) }, overall: closeTo(0.25) }; expect(result).toMatchObject(expectedResult); }); it("should calculate minimum with no binBounds correctly", () => { const mockValue = { bins: [0.5, 0.2], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Min); const expectedResult = { overall: 0.2 }; expect(result).toEqual(expectedResult); }); it("should calculate minimum with binBounds correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 } ], bins: [0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Min); const expectedResult = { bounds: { lower: closeTo(0.25), upper: closeTo(0.4) }, overall: closeTo(0.35) }; expect(result).toMatchObject(expectedResult); }); it("should calculate maximum with no binBounds correctly", () => { const mockValue = { bins: [0.5, 0.2], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Max); const expectedResult = { overall: 0.5 }; expect(result).toEqual(expectedResult); }); it("should calculate maximum with binBounds correctly", () => { const mockValue = { binBounds: [ { lower: 0.25, upper: 0.4 }, { lower: 0.6, upper: 0.75 } ], bins: [0.35, 0.7], global: 0.5 }; const result = calculateFairnessMetric(mockValue, FairnessModes.Max); const expectedResult = { bounds: { lower: closeTo(0.6), upper: closeTo(0.75) }, overall: closeTo(0.7) }; expect(result).toMatchObject(expectedResult); }); });
the_stack
import { ComprModeType } from './compr-mode-type' import { Context } from './context' import { LoaderOptions, Library, Instance } from './seal' import { Exception, SealError } from './exception' import { MemoryPoolHandle } from './memory-pool-handle' import { ParmsIdType, ParmsIdTypeConstructorOptions } from './parms-id-type' import { VectorConstructorOptions } from './vector' import { INVALID_PLAIN_CONSRUCTOR_OPTIONS } from './constants' export type PlainTextDependencyOptions = { readonly Exception: Exception readonly ComprModeType: ComprModeType readonly ParmsIdType: ParmsIdTypeConstructorOptions readonly MemoryPoolHandle: MemoryPoolHandle readonly Vector: VectorConstructorOptions } export type PlainTextDependencies = { ({ Exception, ComprModeType, ParmsIdType, MemoryPoolHandle, Vector }: PlainTextDependencyOptions): PlainTextConstructorOptions } export type PlainTextConstructorOptions = { ({ capacity, coeffCount, pool }?: { capacity?: number coeffCount?: number pool?: MemoryPoolHandle }): PlainText } export type PlainText = { readonly instance: Instance readonly unsafeInject: (instance: Instance) => void readonly delete: () => void readonly reserve: (capacity: number) => void readonly shrinkToFit: () => void readonly release: () => void readonly resize: (coeffCount: number) => void readonly setZero: () => void readonly isZero: boolean readonly capacity: number readonly coeffCount: number readonly significantCoeffCount: number readonly nonzeroCoeffCount: number readonly toPolynomial: () => string readonly isNttForm: boolean readonly parmsId: ParmsIdType readonly scale: number readonly setScale: (scale: number) => void readonly pool: MemoryPoolHandle readonly save: (compression?: ComprModeType) => string readonly saveArray: (compression?: ComprModeType) => Uint8Array readonly load: (context: Context, encoded: string) => void readonly loadArray: (context: Context, array: Uint8Array) => void readonly copy: (plain: PlainText) => void readonly clone: () => PlainText readonly move: (plain: PlainText) => void } const PlainTextConstructor = (library: Library): PlainTextDependencies => ({ Exception, ComprModeType, ParmsIdType, MemoryPoolHandle, Vector }: PlainTextDependencyOptions): PlainTextConstructorOptions => ({ capacity, coeffCount, pool = MemoryPoolHandle.global } = {}): PlainText => { // Static methods const Constructor = library.Plaintext let _instance = construct({ capacity, coeffCount, pool }) function construct({ capacity, coeffCount, pool = MemoryPoolHandle.global }: { capacity?: number coeffCount?: number pool?: MemoryPoolHandle }) { try { if (capacity === undefined && coeffCount === undefined) { return new Constructor(pool) } else if (capacity === undefined && coeffCount !== undefined) { return new Constructor(coeffCount, pool) } else if (capacity !== undefined && coeffCount !== undefined) { return new Constructor(capacity, coeffCount, pool) } else { throw new Error(INVALID_PLAIN_CONSRUCTOR_OPTIONS) } } catch (e) { throw Exception.safe(e as SealError) } } /** * @implements PlainText */ /** * @interface PlainText */ return { /** * Get the underlying WASM instance * * @private * @readonly * @name PlainText#instance * @type {Instance} */ get instance() { return _instance }, /** * Inject this object with a raw WASM instance. No type checking is performed. * * @private * @function * @name PlainText#unsafeInject * @param {Instance} instance WASM instance */ unsafeInject(instance: Instance) { if (_instance) { _instance.delete() _instance = undefined } _instance = instance }, /** * Delete the underlying WASM instance. * * Should be called before dereferencing this object to prevent the * WASM heap from growing indefinitely. * @function * @name PlainText#delete */ delete() { if (_instance) { _instance.delete() _instance = undefined } }, /** * Allocates enough memory to accommodate the backing array of a plaintext * with given capacity. * * @function * @name PlainText#reserve * @param {number} capacity The capacity to reserve */ reserve(capacity: number) { try { return _instance.reserve(capacity) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Allocates enough memory to accommodate the backing array of the current * PlainText and copies it over to the new location. This function is meant * to reduce the memory use of the PlainText to smallest possible and can be * particularly important after modulus switching. * * @function * @name PlainText#shrinkToFit */ shrinkToFit() { _instance.shrinkToFit() }, /** * Resets the PlainText. This function releases any memory allocated by the * PlainText, returning it to the memory pool. * * @function * @name PlainText#release */ release() { _instance.release() }, /** * Resizes the PlainText to have a given coefficient count. The PlainText * is automatically reallocated if the new coefficient count does not fit in * the current capacity. * * @function * @name PlainText#resize * @param {number} coeffCount The number of coefficients in the plaintext polynomial */ resize(coeffCount: number) { try { _instance.resize(coeffCount) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Sets the PlainText polynomial to zero. * * @function * @name PlainText#setZero */ setZero() { _instance.setZero() }, /** * Whether the current PlainText polynomial has all zero coefficients. * * @readonly * @name PlainText#isZero * @type {boolean} */ get isZero() { return _instance.isZero() }, /** * The capacity of the current allocation. * * @readonly * @name PlainText#capacity * @type {number} */ get capacity() { return _instance.capacity() }, /** * The coefficient count of the current PlainText polynomial. * * @readonly * @name PlainText#coeffCount * @type {number} */ get coeffCount() { return _instance.coeffCount() }, /** * The significant coefficient count of the current PlainText polynomial. * * @readonly * @name PlainText#significantCoeffCount * @type {number} */ get significantCoeffCount() { return _instance.significantCoeffCount() }, /** * Returns the non-zero coefficient count of the current PlainText polynomial. * * @readonly * @name PlainText#nonzeroCoeffCount * @type {number} */ get nonzeroCoeffCount() { return _instance.nonzeroCoeffCount() }, /** * Returns a human-readable string description of the PlainText polynomial. * * The returned string is of the form "7FFx^3 + 1x^1 + 3" with a format * summarized by the following: * 1. Terms are listed in order of strictly decreasing exponent * 2. Coefficient values are non-negative and in hexadecimal format (hexadecimal * letters are in upper-case) * 3. Exponents are positive and in decimal format * 4. Zero coefficient terms (including the constant term) are omitted unless * the polynomial is exactly 0 (see rule 9) * 5. Term with the exponent value of one is written as x^1 * 6. Term with the exponent value of zero (the constant term) is written as * just a hexadecimal number without x or exponent * 7. Terms are separated exactly by <space>+<space> * 8. Other than the +, no other terms have whitespace * 9. If the polynomial is exactly 0, the string "0" is returned * * @function * @name PlainText#toPolynomial * @throws std::invalid_argument if the PlainText is in NTT transformed form * @returns {string} Polynomial string */ toPolynomial(): string { try { return _instance.toPolynomial() } catch (e) { throw Exception.safe(e as SealError) } }, /** * Whether the PlainText is in NTT form. * * @readonly * @name PlainText#isNttForm * @type {boolean} */ get isNttForm() { return _instance.isNttForm() }, /** * The reference to parmsId of the PlainText. The parmsId must remain zero unless the * PlainText polynomial is in NTT form. * * @see {@link EncryptionParameters} for more information about parmsId. * * @readonly * @name PlainText#parmsId * @type {ParmsIdType} */ get parmsId() { const parms = ParmsIdType() parms.inject(_instance.parmsId()) return parms }, /** * The reference to the scale. This is only needed when using the CKKS * encryption scheme. The user should have little or no reason to ever change * the scale by hand. * * @readonly * @name PlainText#scale * @type {number} */ get scale() { return _instance.scale() }, /** * Sets the PlainText scale. This is only needed when using the * CKKS encryption scheme. The user should have little or no reason to ever * change the scale by hand. * * @function * @name PlainText#setScale * @param {number} scale The scale to set */ setScale(scale: number) { _instance.setScale(scale) }, /** * The currently used MemoryPoolHandle. * * @readonly * @name PlainText#pool * @type {MemoryPoolHandle} */ get pool() { return _instance.pool() }, /** * Save the PlainText to a base64 string * * @function * @name PlainText#save * @param {ComprModeType} [compression={@link ComprModeType.zstd}] The compression mode to use * @returns {string} Base64 encoded string */ save(compression: ComprModeType = ComprModeType.zstd): string { return _instance.saveToString(compression) }, /** * Save the PlainText as a binary Uint8Array * * @function * @name PlainText#saveArray * @param {ComprModeType} [compression={@link ComprModeType.zstd}] The compression mode to use * @returns {Uint8Array} A byte array containing the PlainText in binary form */ saveArray(compression: ComprModeType = ComprModeType.zstd): Uint8Array { const tempVect = Vector() const instance = _instance.saveToArray(compression) tempVect.unsafeInject(instance) tempVect.setType('Uint8Array') const tempArr = tempVect.toArray() as Uint8Array tempVect.delete() return tempArr }, /** * Load a PlainText from a base64 string * * @function * @name PlainText#load * @param {Context} context Encryption context to enforce * @param {string} encoded Base64 encoded string */ load(context: Context, encoded: string) { try { _instance.loadFromString(context.instance, encoded) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Load a PlainText from an Uint8Array holding binary data * * @function * @name PlainText#loadArray * @param {Context} context Encryption context to enforce * @param {Uint8Array} array TypedArray containing binary data */ loadArray(context: Context, array: Uint8Array) { try { _instance.loadFromArray(context.instance, array) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Copy an existing PlainText and overwrite this instance * * @function * @name PlainText#copy * @param {PlainText} plain PlainText to copy * @example * const plainTextA = seal.PlainText() * // ... after encoding some data ... * const plainTextB = seal.PlainText() * plainTextB.copy(plainTextA) * // plainTextB holds a copy of plainTextA */ copy(plain: PlainText) { try { _instance.copy(plain.instance) } catch (e) { throw Exception.safe(e as SealError) } }, /** * Clone and return a new instance of this PlainText * * @function * @name PlainText#clone * @returns {PlainText} * @example * const plainTextA = seal.PlainText() * // ... after encoding some data ... * const plainTextB = plainTextA.clone() * // plainTextB holds a copy of plainTextA */ clone(): PlainText { try { const clonedInstance = _instance.clone() const plain = PlainTextConstructor(library)({ Exception, ComprModeType, ParmsIdType, MemoryPoolHandle, Vector })() plain.unsafeInject(clonedInstance) return plain } catch (e) { throw Exception.safe(e as SealError) } }, /** * Move a PlainText into this one and delete the old reference * * @function * @name PlainText#move * @param {PlainText} plain PlainText to move * @example * const plainTextA = seal.PlainText() * // ... after encoding some data ... * const plainTextB = seal.PlainText() * plainTextB.move(plainTextA) * // plainTextB holds a the instance of plainTextA. * // plainTextA no longer holds an instance */ move(plain: PlainText) { try { _instance.move(plain.instance) // TODO: find optimization // This method results in a copy instead of a real move. // Therefore, we need to delete the old instance. plain.delete() } catch (e) { throw Exception.safe(e as SealError) } } } } export const PlainTextInit = ({ loader }: LoaderOptions): PlainTextDependencies => { const library: Library = loader.library return PlainTextConstructor(library) }
the_stack
/* tslint:disable */ /* eslint-disable */ //---------------------- // <auto-generated> // Generated using the NSwag toolchain v12.3.1.0 (NJsonSchema v9.14.1.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org) // </auto-generated> //---------------------- // ReSharper disable InconsistentNaming import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators'; import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs'; import { Injectable, Inject, Optional, InjectionToken } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http'; import * as moment from 'moment'; export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL'); @Injectable() export class AccountServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * 修改密码 * @param body (optional) * @return Success */ changePassword(body: ChangePasswordInput | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Account/ChangePassword"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processChangePassword(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processChangePassword(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processChangePassword(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * 获取账户设置 * @return Success */ getProfile(): Observable<AccountProfileDto> { let url_ = this.baseUrl + "/api/services/app/Account/GetProfile"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetProfile(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetProfile(<any>response_); } catch (e) { return <Observable<AccountProfileDto>><any>_observableThrow(e); } } else return <Observable<AccountProfileDto>><any>_observableThrow(response_); })); } protected processGetProfile(response: HttpResponseBase): Observable<AccountProfileDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? AccountProfileDto.fromJS(resultData200) : new AccountProfileDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<AccountProfileDto>(<any>null); } /** * @param body (optional) * @return Success */ isTenantAvailable(body: IsTenantAvailableInput | undefined): Observable<IsTenantAvailableOutput> { let url_ = this.baseUrl + "/api/services/app/Account/IsTenantAvailable"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processIsTenantAvailable(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processIsTenantAvailable(<any>response_); } catch (e) { return <Observable<IsTenantAvailableOutput>><any>_observableThrow(e); } } else return <Observable<IsTenantAvailableOutput>><any>_observableThrow(response_); })); } protected processIsTenantAvailable(response: HttpResponseBase): Observable<IsTenantAvailableOutput> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? IsTenantAvailableOutput.fromJS(resultData200) : new IsTenantAvailableOutput(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<IsTenantAvailableOutput>(<any>null); } /** * @param body (optional) * @return Success */ register(body: RegisterInput | undefined): Observable<RegisterOutput> { let url_ = this.baseUrl + "/api/services/app/Account/Register"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processRegister(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processRegister(<any>response_); } catch (e) { return <Observable<RegisterOutput>><any>_observableThrow(e); } } else return <Observable<RegisterOutput>><any>_observableThrow(response_); })); } protected processRegister(response: HttpResponseBase): Observable<RegisterOutput> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RegisterOutput.fromJS(resultData200) : new RegisterOutput(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RegisterOutput>(<any>null); } /** * @param body (optional) * @return Success */ syncWechatUserInfo(body: WechatUserInfoInput | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Account/SyncWechatUserInfo"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processSyncWechatUserInfo(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processSyncWechatUserInfo(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processSyncWechatUserInfo(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * 更新账户设置 * @param body (optional) * @return Success */ updateProfile(body: AccountProfileDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Account/UpdateProfile"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdateProfile(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdateProfile(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdateProfile(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class AuditLogServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<AuditLogDto> { let url_ = this.baseUrl + "/api/services/app/AuditLog/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<AuditLogDto>><any>_observableThrow(e); } } else return <Observable<AuditLogDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<AuditLogDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? AuditLogDto.fromJS(resultData200) : new AuditLogDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<AuditLogDto>(<any>null); } /** * @param exeDurationGreaterThan (optional) * @param exeDurationLessThan (optional) * @param methodName (optional) * @param serviceName (optional) * @param from (optional) * @param to (optional) * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(exeDurationGreaterThan: number | undefined, exeDurationLessThan: number | undefined, methodName: string | undefined, serviceName: string | undefined, from: moment.Moment | undefined, to: moment.Moment | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<AuditLogDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/AuditLog/GetAll?"; if (exeDurationGreaterThan === null) throw new Error("The parameter 'exeDurationGreaterThan' cannot be null."); else if (exeDurationGreaterThan !== undefined) url_ += "ExeDurationGreaterThan=" + encodeURIComponent("" + exeDurationGreaterThan) + "&"; if (exeDurationLessThan === null) throw new Error("The parameter 'exeDurationLessThan' cannot be null."); else if (exeDurationLessThan !== undefined) url_ += "ExeDurationLessThan=" + encodeURIComponent("" + exeDurationLessThan) + "&"; if (methodName === null) throw new Error("The parameter 'methodName' cannot be null."); else if (methodName !== undefined) url_ += "MethodName=" + encodeURIComponent("" + methodName) + "&"; if (serviceName === null) throw new Error("The parameter 'serviceName' cannot be null."); else if (serviceName !== undefined) url_ += "ServiceName=" + encodeURIComponent("" + serviceName) + "&"; if (from === null) throw new Error("The parameter 'from' cannot be null."); else if (from !== undefined) url_ += "From=" + encodeURIComponent(from ? "" + from.toJSON() : "") + "&"; if (to === null) throw new Error("The parameter 'to' cannot be null."); else if (to !== undefined) url_ += "To=" + encodeURIComponent(to ? "" + to.toJSON() : "") + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<AuditLogDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<AuditLogDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<AuditLogDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? AuditLogDtoPagedResultDto.fromJS(resultData200) : new AuditLogDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<AuditLogDtoPagedResultDto>(<any>null); } } @Injectable() export class CategoryServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<CategoryDto> { let url_ = this.baseUrl + "/api/services/app/Category/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<CategoryDto>><any>_observableThrow(e); } } else return <Observable<CategoryDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<CategoryDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? CategoryDto.fromJS(resultData200) : new CategoryDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<CategoryDto>(<any>null); } /** * @param keyword (optional) 关键词 * @param parentCategoryId (optional) 父分类 * @param onlyRoot (optional) 只看父分类 * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(keyword: string | undefined, parentCategoryId: number | undefined, onlyRoot: boolean | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<CategoryDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/Category/GetAll?"; if (keyword === null) throw new Error("The parameter 'keyword' cannot be null."); else if (keyword !== undefined) url_ += "Keyword=" + encodeURIComponent("" + keyword) + "&"; if (parentCategoryId === null) throw new Error("The parameter 'parentCategoryId' cannot be null."); else if (parentCategoryId !== undefined) url_ += "ParentCategoryId=" + encodeURIComponent("" + parentCategoryId) + "&"; if (onlyRoot === null) throw new Error("The parameter 'onlyRoot' cannot be null."); else if (onlyRoot !== undefined) url_ += "OnlyRoot=" + encodeURIComponent("" + onlyRoot) + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<CategoryDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<CategoryDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<CategoryDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? CategoryDtoPagedResultDto.fromJS(resultData200) : new CategoryDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<CategoryDtoPagedResultDto>(<any>null); } /** * @param body (optional) * @return Success */ create(body: CreateCategoryDto | undefined): Observable<CategoryDto> { let url_ = this.baseUrl + "/api/services/app/Category/Create"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processCreate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processCreate(<any>response_); } catch (e) { return <Observable<CategoryDto>><any>_observableThrow(e); } } else return <Observable<CategoryDto>><any>_observableThrow(response_); })); } protected processCreate(response: HttpResponseBase): Observable<CategoryDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? CategoryDto.fromJS(resultData200) : new CategoryDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<CategoryDto>(<any>null); } /** * @param body (optional) * @return Success */ update(body: CategoryDto | undefined): Observable<CategoryDto> { let url_ = this.baseUrl + "/api/services/app/Category/Update"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdate(<any>response_); } catch (e) { return <Observable<CategoryDto>><any>_observableThrow(e); } } else return <Observable<CategoryDto>><any>_observableThrow(response_); })); } protected processUpdate(response: HttpResponseBase): Observable<CategoryDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? CategoryDto.fromJS(resultData200) : new CategoryDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<CategoryDto>(<any>null); } /** * @param id (optional) * @return Success */ delete(id: number | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Category/Delete?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDelete(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDelete(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDelete(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class ConfigurationServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ changeUiTheme(body: ChangeUiThemeInput | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/ChangeUiTheme"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processChangeUiTheme(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processChangeUiTheme(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processChangeUiTheme(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @return Success */ getEmailSettings(): Observable<EmailSettingsDto> { let url_ = this.baseUrl + "/api/services/app/Configuration/GetEmailSettings"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetEmailSettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetEmailSettings(<any>response_); } catch (e) { return <Observable<EmailSettingsDto>><any>_observableThrow(e); } } else return <Observable<EmailSettingsDto>><any>_observableThrow(response_); })); } protected processGetEmailSettings(response: HttpResponseBase): Observable<EmailSettingsDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? EmailSettingsDto.fromJS(resultData200) : new EmailSettingsDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<EmailSettingsDto>(<any>null); } /** * @param body (optional) * @return Success */ testEmailSettings(body: TestEmailSettingsInput | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/TestEmailSettings"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processTestEmailSettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processTestEmailSettings(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processTestEmailSettings(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ updateEmailSettings(body: EmailSettingsDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/UpdateEmailSettings"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdateEmailSettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdateEmailSettings(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdateEmailSettings(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @return Success */ getSecuritySettings(): Observable<SecuritySettingsDto> { let url_ = this.baseUrl + "/api/services/app/Configuration/GetSecuritySettings"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetSecuritySettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetSecuritySettings(<any>response_); } catch (e) { return <Observable<SecuritySettingsDto>><any>_observableThrow(e); } } else return <Observable<SecuritySettingsDto>><any>_observableThrow(response_); })); } protected processGetSecuritySettings(response: HttpResponseBase): Observable<SecuritySettingsDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? SecuritySettingsDto.fromJS(resultData200) : new SecuritySettingsDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<SecuritySettingsDto>(<any>null); } /** * @param body (optional) * @return Success */ updateUserLockoutSettings(body: UserLockOutSettingsDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/UpdateUserLockoutSettings"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdateUserLockoutSettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdateUserLockoutSettings(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdateUserLockoutSettings(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ updateTwoFactorLoginSettings(body: TwoFactorLoginSettingsDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/UpdateTwoFactorLoginSettings"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdateTwoFactorLoginSettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdateTwoFactorLoginSettings(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdateTwoFactorLoginSettings(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ updatePasswordComplexitySettings(body: PasswordComplexitySettingsDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/UpdatePasswordComplexitySettings"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdatePasswordComplexitySettings(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdatePasswordComplexitySettings(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdatePasswordComplexitySettings(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ updateEmailConfirmationSetting(body: EmailConfirmationSettingDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/UpdateEmailConfirmationSetting"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdateEmailConfirmationSetting(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdateEmailConfirmationSetting(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUpdateEmailConfirmationSetting(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class MemberUserServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param id (optional) * @return Success */ getTags(id: number | undefined): Observable<MemberTagsDto> { let url_ = this.baseUrl + "/api/services/app/MemberUser/GetTags?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetTags(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetTags(<any>response_); } catch (e) { return <Observable<MemberTagsDto>><any>_observableThrow(e); } } else return <Observable<MemberTagsDto>><any>_observableThrow(response_); })); } protected processGetTags(response: HttpResponseBase): Observable<MemberTagsDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? MemberTagsDto.fromJS(resultData200) : new MemberTagsDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<MemberTagsDto>(<any>null); } /** * @param body (optional) * @return Success */ setTags(body: MemberTagsDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/MemberUser/SetTags"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processSetTags(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processSetTags(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processSetTags(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<MemberUserDto> { let url_ = this.baseUrl + "/api/services/app/MemberUser/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<MemberUserDto>><any>_observableThrow(e); } } else return <Observable<MemberUserDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<MemberUserDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? MemberUserDto.fromJS(resultData200) : new MemberUserDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<MemberUserDto>(<any>null); } /** * @param keyword (optional) * @param from (optional) * @param to (optional) * @param sorting (optional) * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(keyword: string | undefined, from: moment.Moment | undefined, to: moment.Moment | undefined, sorting: string | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<MemberUserDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/MemberUser/GetAll?"; if (keyword === null) throw new Error("The parameter 'keyword' cannot be null."); else if (keyword !== undefined) url_ += "Keyword=" + encodeURIComponent("" + keyword) + "&"; if (from === null) throw new Error("The parameter 'from' cannot be null."); else if (from !== undefined) url_ += "From=" + encodeURIComponent(from ? "" + from.toJSON() : "") + "&"; if (to === null) throw new Error("The parameter 'to' cannot be null."); else if (to !== undefined) url_ += "To=" + encodeURIComponent(to ? "" + to.toJSON() : "") + "&"; if (sorting === null) throw new Error("The parameter 'sorting' cannot be null."); else if (sorting !== undefined) url_ += "Sorting=" + encodeURIComponent("" + sorting) + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<MemberUserDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<MemberUserDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<MemberUserDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? MemberUserDtoPagedResultDto.fromJS(resultData200) : new MemberUserDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<MemberUserDtoPagedResultDto>(<any>null); } } @Injectable() export class RegionServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param parentId (optional) * @return Success */ getAll(parentId: string | undefined): Observable<RegionDtoListResultDto> { let url_ = this.baseUrl + "/api/services/app/Region/GetAll?"; if (parentId === null) throw new Error("The parameter 'parentId' cannot be null."); else if (parentId !== undefined) url_ += "parentId=" + encodeURIComponent("" + parentId) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<RegionDtoListResultDto>><any>_observableThrow(e); } } else return <Observable<RegionDtoListResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<RegionDtoListResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RegionDtoListResultDto.fromJS(resultData200) : new RegionDtoListResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RegionDtoListResultDto>(<any>null); } } @Injectable() export class RoleServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ create(body: CreateRoleDto | undefined): Observable<RoleDto> { let url_ = this.baseUrl + "/api/services/app/Role/Create"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processCreate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processCreate(<any>response_); } catch (e) { return <Observable<RoleDto>><any>_observableThrow(e); } } else return <Observable<RoleDto>><any>_observableThrow(response_); })); } protected processCreate(response: HttpResponseBase): Observable<RoleDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleDto.fromJS(resultData200) : new RoleDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleDto>(<any>null); } /** * @param permission (optional) * @return Success */ getRoles(permission: string | undefined): Observable<RoleListDtoListResultDto> { let url_ = this.baseUrl + "/api/services/app/Role/GetRoles?"; if (permission === null) throw new Error("The parameter 'permission' cannot be null."); else if (permission !== undefined) url_ += "Permission=" + encodeURIComponent("" + permission) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetRoles(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetRoles(<any>response_); } catch (e) { return <Observable<RoleListDtoListResultDto>><any>_observableThrow(e); } } else return <Observable<RoleListDtoListResultDto>><any>_observableThrow(response_); })); } protected processGetRoles(response: HttpResponseBase): Observable<RoleListDtoListResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleListDtoListResultDto.fromJS(resultData200) : new RoleListDtoListResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleListDtoListResultDto>(<any>null); } /** * @param body (optional) * @return Success */ update(body: RoleDto | undefined): Observable<RoleDto> { let url_ = this.baseUrl + "/api/services/app/Role/Update"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdate(<any>response_); } catch (e) { return <Observable<RoleDto>><any>_observableThrow(e); } } else return <Observable<RoleDto>><any>_observableThrow(response_); })); } protected processUpdate(response: HttpResponseBase): Observable<RoleDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleDto.fromJS(resultData200) : new RoleDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleDto>(<any>null); } /** * @param id (optional) * @return Success */ delete(id: number | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Role/Delete?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDelete(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDelete(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDelete(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @return Success */ getAllPermissions(): Observable<PermissionDtoListResultDto> { let url_ = this.baseUrl + "/api/services/app/Role/GetAllPermissions"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAllPermissions(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAllPermissions(<any>response_); } catch (e) { return <Observable<PermissionDtoListResultDto>><any>_observableThrow(e); } } else return <Observable<PermissionDtoListResultDto>><any>_observableThrow(response_); })); } protected processGetAllPermissions(response: HttpResponseBase): Observable<PermissionDtoListResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? PermissionDtoListResultDto.fromJS(resultData200) : new PermissionDtoListResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<PermissionDtoListResultDto>(<any>null); } /** * @param id (optional) * @return Success */ getRoleForEdit(id: number | undefined): Observable<GetRoleForEditOutput> { let url_ = this.baseUrl + "/api/services/app/Role/GetRoleForEdit?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetRoleForEdit(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetRoleForEdit(<any>response_); } catch (e) { return <Observable<GetRoleForEditOutput>><any>_observableThrow(e); } } else return <Observable<GetRoleForEditOutput>><any>_observableThrow(response_); })); } protected processGetRoleForEdit(response: HttpResponseBase): Observable<GetRoleForEditOutput> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? GetRoleForEditOutput.fromJS(resultData200) : new GetRoleForEditOutput(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<GetRoleForEditOutput>(<any>null); } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<RoleDto> { let url_ = this.baseUrl + "/api/services/app/Role/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<RoleDto>><any>_observableThrow(e); } } else return <Observable<RoleDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<RoleDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleDto.fromJS(resultData200) : new RoleDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleDto>(<any>null); } /** * @param roleName (optional) * @param displayName (optional) * @param description (optional) * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(roleName: string | undefined, displayName: string | undefined, description: string | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<RoleDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/Role/GetAll?"; if (roleName === null) throw new Error("The parameter 'roleName' cannot be null."); else if (roleName !== undefined) url_ += "RoleName=" + encodeURIComponent("" + roleName) + "&"; if (displayName === null) throw new Error("The parameter 'displayName' cannot be null."); else if (displayName !== undefined) url_ += "DisplayName=" + encodeURIComponent("" + displayName) + "&"; if (description === null) throw new Error("The parameter 'description' cannot be null."); else if (description !== undefined) url_ += "Description=" + encodeURIComponent("" + description) + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<RoleDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<RoleDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<RoleDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleDtoPagedResultDto.fromJS(resultData200) : new RoleDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleDtoPagedResultDto>(<any>null); } } @Injectable() export class SessionServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ getCurrentLoginInformations(): Observable<GetCurrentLoginInformationsOutput> { let url_ = this.baseUrl + "/api/services/app/Session/GetCurrentLoginInformations"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetCurrentLoginInformations(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetCurrentLoginInformations(<any>response_); } catch (e) { return <Observable<GetCurrentLoginInformationsOutput>><any>_observableThrow(e); } } else return <Observable<GetCurrentLoginInformationsOutput>><any>_observableThrow(response_); })); } protected processGetCurrentLoginInformations(response: HttpResponseBase): Observable<GetCurrentLoginInformationsOutput> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? GetCurrentLoginInformationsOutput.fromJS(resultData200) : new GetCurrentLoginInformationsOutput(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<GetCurrentLoginInformationsOutput>(<any>null); } } @Injectable() export class TagServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<TagDto> { let url_ = this.baseUrl + "/api/services/app/Tag/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<TagDto>><any>_observableThrow(e); } } else return <Observable<TagDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<TagDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TagDto.fromJS(resultData200) : new TagDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TagDto>(<any>null); } /** * @param tagType (optional) 标签类型 * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(tagType: TagType | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<TagDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/Tag/GetAll?"; if (tagType === null) throw new Error("The parameter 'tagType' cannot be null."); else if (tagType !== undefined) url_ += "TagType=" + encodeURIComponent("" + tagType) + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<TagDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<TagDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<TagDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TagDtoPagedResultDto.fromJS(resultData200) : new TagDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TagDtoPagedResultDto>(<any>null); } /** * @param body (optional) * @return Success */ create(body: TagDto | undefined): Observable<TagDto> { let url_ = this.baseUrl + "/api/services/app/Tag/Create"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processCreate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processCreate(<any>response_); } catch (e) { return <Observable<TagDto>><any>_observableThrow(e); } } else return <Observable<TagDto>><any>_observableThrow(response_); })); } protected processCreate(response: HttpResponseBase): Observable<TagDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TagDto.fromJS(resultData200) : new TagDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TagDto>(<any>null); } /** * @param body (optional) * @return Success */ update(body: TagDto | undefined): Observable<TagDto> { let url_ = this.baseUrl + "/api/services/app/Tag/Update"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdate(<any>response_); } catch (e) { return <Observable<TagDto>><any>_observableThrow(e); } } else return <Observable<TagDto>><any>_observableThrow(response_); })); } protected processUpdate(response: HttpResponseBase): Observable<TagDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TagDto.fromJS(resultData200) : new TagDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TagDto>(<any>null); } /** * @param id (optional) * @return Success */ delete(id: number | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Tag/Delete?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDelete(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDelete(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDelete(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class TenantServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ create(body: CreateTenantDto | undefined): Observable<TenantDto> { let url_ = this.baseUrl + "/api/services/app/Tenant/Create"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processCreate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processCreate(<any>response_); } catch (e) { return <Observable<TenantDto>><any>_observableThrow(e); } } else return <Observable<TenantDto>><any>_observableThrow(response_); })); } protected processCreate(response: HttpResponseBase): Observable<TenantDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TenantDto.fromJS(resultData200) : new TenantDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TenantDto>(<any>null); } /** * @param id (optional) * @return Success */ delete(id: number | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Tenant/Delete?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDelete(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDelete(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDelete(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<TenantDto> { let url_ = this.baseUrl + "/api/services/app/Tenant/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<TenantDto>><any>_observableThrow(e); } } else return <Observable<TenantDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<TenantDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TenantDto.fromJS(resultData200) : new TenantDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TenantDto>(<any>null); } /** * @param tenancyName (optional) * @param name (optional) * @param isActive (optional) * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(tenancyName: string | undefined, name: string | undefined, isActive: boolean | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<TenantDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/Tenant/GetAll?"; if (tenancyName === null) throw new Error("The parameter 'tenancyName' cannot be null."); else if (tenancyName !== undefined) url_ += "TenancyName=" + encodeURIComponent("" + tenancyName) + "&"; if (name === null) throw new Error("The parameter 'name' cannot be null."); else if (name !== undefined) url_ += "Name=" + encodeURIComponent("" + name) + "&"; if (isActive === null) throw new Error("The parameter 'isActive' cannot be null."); else if (isActive !== undefined) url_ += "IsActive=" + encodeURIComponent("" + isActive) + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<TenantDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<TenantDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<TenantDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TenantDtoPagedResultDto.fromJS(resultData200) : new TenantDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TenantDtoPagedResultDto>(<any>null); } /** * @param body (optional) * @return Success */ update(body: TenantDto | undefined): Observable<TenantDto> { let url_ = this.baseUrl + "/api/services/app/Tenant/Update"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdate(<any>response_); } catch (e) { return <Observable<TenantDto>><any>_observableThrow(e); } } else return <Observable<TenantDto>><any>_observableThrow(response_); })); } protected processUpdate(response: HttpResponseBase): Observable<TenantDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? TenantDto.fromJS(resultData200) : new TenantDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<TenantDto>(<any>null); } } @Injectable() export class TokenAuthServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ authenticate(body: AuthenticateModel | undefined): Observable<AuthenticateResultModel> { let url_ = this.baseUrl + "/api/TokenAuth/Authenticate"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processAuthenticate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processAuthenticate(<any>response_); } catch (e) { return <Observable<AuthenticateResultModel>><any>_observableThrow(e); } } else return <Observable<AuthenticateResultModel>><any>_observableThrow(response_); })); } protected processAuthenticate(response: HttpResponseBase): Observable<AuthenticateResultModel> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? AuthenticateResultModel.fromJS(resultData200) : new AuthenticateResultModel(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<AuthenticateResultModel>(<any>null); } /** * @return Success */ getExternalAuthenticationProviders(): Observable<ExternalLoginProviderInfoModel[]> { let url_ = this.baseUrl + "/api/TokenAuth/GetExternalAuthenticationProviders"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetExternalAuthenticationProviders(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetExternalAuthenticationProviders(<any>response_); } catch (e) { return <Observable<ExternalLoginProviderInfoModel[]>><any>_observableThrow(e); } } else return <Observable<ExternalLoginProviderInfoModel[]>><any>_observableThrow(response_); })); } protected processGetExternalAuthenticationProviders(response: HttpResponseBase): Observable<ExternalLoginProviderInfoModel[]> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); if (resultData200 && resultData200.constructor === Array) { result200 = [] as any; for (let item of resultData200) result200.push(ExternalLoginProviderInfoModel.fromJS(item)); } return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<ExternalLoginProviderInfoModel[]>(<any>null); } /** * @param body (optional) * @return Success */ externalAuthenticate(body: ExternalAuthenticateModel | undefined): Observable<ExternalAuthenticateResultModel> { let url_ = this.baseUrl + "/api/TokenAuth/ExternalAuthenticate"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processExternalAuthenticate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processExternalAuthenticate(<any>response_); } catch (e) { return <Observable<ExternalAuthenticateResultModel>><any>_observableThrow(e); } } else return <Observable<ExternalAuthenticateResultModel>><any>_observableThrow(response_); })); } protected processExternalAuthenticate(response: HttpResponseBase): Observable<ExternalAuthenticateResultModel> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? ExternalAuthenticateResultModel.fromJS(resultData200) : new ExternalAuthenticateResultModel(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<ExternalAuthenticateResultModel>(<any>null); } } @Injectable() export class WechatH5AuthServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param targetUrl (optional) * @return Success */ wechatH5Auth(targetUrl: string | undefined): Observable<void> { let url_ = this.baseUrl + "/api/TokenAuth/WechatH5Auth/WechatH5Auth?"; if (targetUrl === null) throw new Error("The parameter 'targetUrl' cannot be null."); else if (targetUrl !== undefined) url_ += "targetUrl=" + encodeURIComponent("" + targetUrl) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processWechatH5Auth(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processWechatH5Auth(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processWechatH5Auth(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class WechatH5AuthCallbackServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param code (optional) * @param state (optional) * @param targetUrl (optional) * @return Success */ wechatH5AuthCallback(code: string | undefined, state: string | undefined, targetUrl: string | undefined): Observable<void> { let url_ = this.baseUrl + "/api/TokenAuth/WechatH5AuthCallback/WechatH5AuthCallback?"; if (code === null) throw new Error("The parameter 'code' cannot be null."); else if (code !== undefined) url_ += "code=" + encodeURIComponent("" + code) + "&"; if (state === null) throw new Error("The parameter 'state' cannot be null."); else if (state !== undefined) url_ += "state=" + encodeURIComponent("" + state) + "&"; if (targetUrl === null) throw new Error("The parameter 'targetUrl' cannot be null."); else if (targetUrl !== undefined) url_ += "targetUrl=" + encodeURIComponent("" + targetUrl) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processWechatH5AuthCallback(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processWechatH5AuthCallback(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processWechatH5AuthCallback(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class ServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ uploadFile(body: Blob | undefined): Observable<void> { let url_ = this.baseUrl + "/UploadFile"; url_ = url_.replace(/[?&]$/, ""); const content_ = body; let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "multipart/form-data", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUploadFile(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUploadFile(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processUploadFile(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } } @Injectable() export class UserServiceProxy { private http: HttpClient; private baseUrl: string; protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined; constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @param body (optional) * @return Success */ create(body: CreateUserDto | undefined): Observable<UserDto> { let url_ = this.baseUrl + "/api/services/app/User/Create"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processCreate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processCreate(<any>response_); } catch (e) { return <Observable<UserDto>><any>_observableThrow(e); } } else return <Observable<UserDto>><any>_observableThrow(response_); })); } protected processCreate(response: HttpResponseBase): Observable<UserDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? UserDto.fromJS(resultData200) : new UserDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<UserDto>(<any>null); } /** * @param body (optional) * @return Success */ update(body: UserDto | undefined): Observable<UserDto> { let url_ = this.baseUrl + "/api/services/app/User/Update"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processUpdate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processUpdate(<any>response_); } catch (e) { return <Observable<UserDto>><any>_observableThrow(e); } } else return <Observable<UserDto>><any>_observableThrow(response_); })); } protected processUpdate(response: HttpResponseBase): Observable<UserDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? UserDto.fromJS(resultData200) : new UserDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<UserDto>(<any>null); } /** * @param id (optional) * @return Success */ delete(id: number | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/Delete?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ }) }; return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDelete(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDelete(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDelete(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ activate(body: Int64EntityDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/Activate"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processActivate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processActivate(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processActivate(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ deActivate(body: Int64EntityDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/DeActivate"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processDeActivate(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processDeActivate(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processDeActivate(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @return Success */ getRoles(): Observable<RoleDtoListResultDto> { let url_ = this.baseUrl + "/api/services/app/User/GetRoles"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetRoles(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetRoles(<any>response_); } catch (e) { return <Observable<RoleDtoListResultDto>><any>_observableThrow(e); } } else return <Observable<RoleDtoListResultDto>><any>_observableThrow(response_); })); } protected processGetRoles(response: HttpResponseBase): Observable<RoleDtoListResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? RoleDtoListResultDto.fromJS(resultData200) : new RoleDtoListResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<RoleDtoListResultDto>(<any>null); } /** * @param body (optional) * @return Success */ changeLanguage(body: ChangeUserLanguageDto | undefined): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/ChangeLanguage"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processChangeLanguage(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processChangeLanguage(<any>response_); } catch (e) { return <Observable<void>><any>_observableThrow(e); } } else return <Observable<void>><any>_observableThrow(response_); })); } protected processChangeLanguage(response: HttpResponseBase): Observable<void> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return _observableOf<void>(<any>null); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<void>(<any>null); } /** * @param body (optional) * @return Success */ changePassword(body: ChangePasswordDto | undefined): Observable<boolean> { let url_ = this.baseUrl + "/api/services/app/User/ChangePassword"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processChangePassword(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processChangePassword(<any>response_); } catch (e) { return <Observable<boolean>><any>_observableThrow(e); } } else return <Observable<boolean>><any>_observableThrow(response_); })); } protected processChangePassword(response: HttpResponseBase): Observable<boolean> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 !== undefined ? resultData200 : <any>null; return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<boolean>(<any>null); } /** * @param body (optional) * @return Success */ resetPassword(body: ResetPasswordDto | undefined): Observable<boolean> { let url_ = this.baseUrl + "/api/services/app/User/ResetPassword"; url_ = url_.replace(/[?&]$/, ""); const content_ = JSON.stringify(body); let options_ : any = { body: content_, observe: "response", responseType: "blob", headers: new HttpHeaders({ "Content-Type": "application/json-patch+json", "Accept": "text/plain" }) }; return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processResetPassword(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processResetPassword(<any>response_); } catch (e) { return <Observable<boolean>><any>_observableThrow(e); } } else return <Observable<boolean>><any>_observableThrow(response_); })); } protected processResetPassword(response: HttpResponseBase): Observable<boolean> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 !== undefined ? resultData200 : <any>null; return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<boolean>(<any>null); } /** * @param id (optional) * @return Success */ get(id: number | undefined): Observable<UserDto> { let url_ = this.baseUrl + "/api/services/app/User/Get?"; if (id === null) throw new Error("The parameter 'id' cannot be null."); else if (id !== undefined) url_ += "Id=" + encodeURIComponent("" + id) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGet(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGet(<any>response_); } catch (e) { return <Observable<UserDto>><any>_observableThrow(e); } } else return <Observable<UserDto>><any>_observableThrow(response_); })); } protected processGet(response: HttpResponseBase): Observable<UserDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? UserDto.fromJS(resultData200) : new UserDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<UserDto>(<any>null); } /** * @param userName (optional) * @param name (optional) * @param isActive (optional) * @param from (optional) * @param to (optional) * @param skipCount (optional) * @param maxResultCount (optional) * @return Success */ getAll(userName: string | undefined, name: string | undefined, isActive: boolean | undefined, from: moment.Moment | undefined, to: moment.Moment | undefined, skipCount: number | undefined, maxResultCount: number | undefined): Observable<UserDtoPagedResultDto> { let url_ = this.baseUrl + "/api/services/app/User/GetAll?"; if (userName === null) throw new Error("The parameter 'userName' cannot be null."); else if (userName !== undefined) url_ += "UserName=" + encodeURIComponent("" + userName) + "&"; if (name === null) throw new Error("The parameter 'name' cannot be null."); else if (name !== undefined) url_ += "Name=" + encodeURIComponent("" + name) + "&"; if (isActive === null) throw new Error("The parameter 'isActive' cannot be null."); else if (isActive !== undefined) url_ += "IsActive=" + encodeURIComponent("" + isActive) + "&"; if (from === null) throw new Error("The parameter 'from' cannot be null."); else if (from !== undefined) url_ += "From=" + encodeURIComponent(from ? "" + from.toJSON() : "") + "&"; if (to === null) throw new Error("The parameter 'to' cannot be null."); else if (to !== undefined) url_ += "To=" + encodeURIComponent(to ? "" + to.toJSON() : "") + "&"; if (skipCount === null) throw new Error("The parameter 'skipCount' cannot be null."); else if (skipCount !== undefined) url_ += "SkipCount=" + encodeURIComponent("" + skipCount) + "&"; if (maxResultCount === null) throw new Error("The parameter 'maxResultCount' cannot be null."); else if (maxResultCount !== undefined) url_ += "MaxResultCount=" + encodeURIComponent("" + maxResultCount) + "&"; url_ = url_.replace(/[?&]$/, ""); let options_ : any = { observe: "response", responseType: "blob", headers: new HttpHeaders({ "Accept": "text/plain" }) }; return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => { return this.processGetAll(response_); })).pipe(_observableCatch((response_: any) => { if (response_ instanceof HttpResponseBase) { try { return this.processGetAll(<any>response_); } catch (e) { return <Observable<UserDtoPagedResultDto>><any>_observableThrow(e); } } else return <Observable<UserDtoPagedResultDto>><any>_observableThrow(response_); })); } protected processGetAll(response: HttpResponseBase): Observable<UserDtoPagedResultDto> { const status = response.status; const responseBlob = response instanceof HttpResponse ? response.body : (<any>response).error instanceof Blob ? (<any>response).error : undefined; let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }}; if (status === 200) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { let result200: any = null; let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver); result200 = resultData200 ? UserDtoPagedResultDto.fromJS(resultData200) : new UserDtoPagedResultDto(); return _observableOf(result200); })); } else if (status !== 200 && status !== 204) { return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => { return throwException("An unexpected server error occurred.", status, _responseText, _headers); })); } return _observableOf<UserDtoPagedResultDto>(<any>null); } } export class AccountProfileDto implements IAccountProfileDto { name: string; surname: string; headLogo: string | undefined; constructor(data?: IAccountProfileDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.surname = data["surname"]; this.headLogo = data["headLogo"]; } } static fromJS(data: any): AccountProfileDto { data = typeof data === 'object' ? data : {}; let result = new AccountProfileDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["surname"] = this.surname; data["headLogo"] = this.headLogo; return data; } clone(): AccountProfileDto { const json = this.toJSON(); let result = new AccountProfileDto(); result.init(json); return result; } } export interface IAccountProfileDto { name: string; surname: string; headLogo: string | undefined; } export class ApplicationInfoDto implements IApplicationInfoDto { version: string | undefined; releaseDate: moment.Moment; features: { [key: string] : boolean; } | undefined; constructor(data?: IApplicationInfoDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.version = data["version"]; this.releaseDate = data["releaseDate"] ? moment(data["releaseDate"].toString()) : <any>undefined; if (data["features"]) { this.features = {} as any; for (let key in data["features"]) { if (data["features"].hasOwnProperty(key)) this.features[key] = data["features"][key]; } } } } static fromJS(data: any): ApplicationInfoDto { data = typeof data === 'object' ? data : {}; let result = new ApplicationInfoDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["version"] = this.version; data["releaseDate"] = this.releaseDate ? this.releaseDate.toISOString() : <any>undefined; if (this.features) { data["features"] = {}; for (let key in this.features) { if (this.features.hasOwnProperty(key)) data["features"][key] = this.features[key]; } } return data; } clone(): ApplicationInfoDto { const json = this.toJSON(); let result = new ApplicationInfoDto(); result.init(json); return result; } } export interface IApplicationInfoDto { version: string | undefined; releaseDate: moment.Moment; features: { [key: string] : boolean; } | undefined; } export class AuditLogDto implements IAuditLogDto { impersonatorUserId: number | undefined; exception: string | undefined; browserInfo: string | undefined; clientName: string | undefined; clientIpAddress: string | undefined; executionDuration: number; executionTime: moment.Moment; tenantId: number | undefined; methodName: string | undefined; serviceName: string | undefined; userId: number | undefined; impersonatorTenantId: number | undefined; parameters: string | undefined; customData: string | undefined; readonly hasException: boolean; id: number; constructor(data?: IAuditLogDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.impersonatorUserId = data["impersonatorUserId"]; this.exception = data["exception"]; this.browserInfo = data["browserInfo"]; this.clientName = data["clientName"]; this.clientIpAddress = data["clientIpAddress"]; this.executionDuration = data["executionDuration"]; this.executionTime = data["executionTime"] ? moment(data["executionTime"].toString()) : <any>undefined; this.tenantId = data["tenantId"]; this.methodName = data["methodName"]; this.serviceName = data["serviceName"]; this.userId = data["userId"]; this.impersonatorTenantId = data["impersonatorTenantId"]; this.parameters = data["parameters"]; this.customData = data["customData"]; (<any>this).hasException = data["hasException"]; this.id = data["id"]; } } static fromJS(data: any): AuditLogDto { data = typeof data === 'object' ? data : {}; let result = new AuditLogDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["impersonatorUserId"] = this.impersonatorUserId; data["exception"] = this.exception; data["browserInfo"] = this.browserInfo; data["clientName"] = this.clientName; data["clientIpAddress"] = this.clientIpAddress; data["executionDuration"] = this.executionDuration; data["executionTime"] = this.executionTime ? this.executionTime.toISOString() : <any>undefined; data["tenantId"] = this.tenantId; data["methodName"] = this.methodName; data["serviceName"] = this.serviceName; data["userId"] = this.userId; data["impersonatorTenantId"] = this.impersonatorTenantId; data["parameters"] = this.parameters; data["customData"] = this.customData; data["hasException"] = this.hasException; data["id"] = this.id; return data; } clone(): AuditLogDto { const json = this.toJSON(); let result = new AuditLogDto(); result.init(json); return result; } } export interface IAuditLogDto { impersonatorUserId: number | undefined; exception: string | undefined; browserInfo: string | undefined; clientName: string | undefined; clientIpAddress: string | undefined; executionDuration: number; executionTime: moment.Moment; tenantId: number | undefined; methodName: string | undefined; serviceName: string | undefined; userId: number | undefined; impersonatorTenantId: number | undefined; parameters: string | undefined; customData: string | undefined; hasException: boolean; id: number; } export class AuditLogDtoPagedResultDto implements IAuditLogDtoPagedResultDto { totalCount: number; items: AuditLogDto[] | undefined; constructor(data?: IAuditLogDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(AuditLogDto.fromJS(item)); } } } static fromJS(data: any): AuditLogDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new AuditLogDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): AuditLogDtoPagedResultDto { const json = this.toJSON(); let result = new AuditLogDtoPagedResultDto(); result.init(json); return result; } } export interface IAuditLogDtoPagedResultDto { totalCount: number; items: AuditLogDto[] | undefined; } export class AuthenticateModel implements IAuthenticateModel { userNameOrEmailAddress: string; password: string; rememberClient: boolean; constructor(data?: IAuthenticateModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.userNameOrEmailAddress = data["userNameOrEmailAddress"]; this.password = data["password"]; this.rememberClient = data["rememberClient"]; } } static fromJS(data: any): AuthenticateModel { data = typeof data === 'object' ? data : {}; let result = new AuthenticateModel(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["userNameOrEmailAddress"] = this.userNameOrEmailAddress; data["password"] = this.password; data["rememberClient"] = this.rememberClient; return data; } clone(): AuthenticateModel { const json = this.toJSON(); let result = new AuthenticateModel(); result.init(json); return result; } } export interface IAuthenticateModel { userNameOrEmailAddress: string; password: string; rememberClient: boolean; } export class AuthenticateResultModel implements IAuthenticateResultModel { accessToken: string | undefined; encryptedAccessToken: string | undefined; expireInSeconds: number; userId: number; constructor(data?: IAuthenticateResultModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.accessToken = data["accessToken"]; this.encryptedAccessToken = data["encryptedAccessToken"]; this.expireInSeconds = data["expireInSeconds"]; this.userId = data["userId"]; } } static fromJS(data: any): AuthenticateResultModel { data = typeof data === 'object' ? data : {}; let result = new AuthenticateResultModel(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["accessToken"] = this.accessToken; data["encryptedAccessToken"] = this.encryptedAccessToken; data["expireInSeconds"] = this.expireInSeconds; data["userId"] = this.userId; return data; } clone(): AuthenticateResultModel { const json = this.toJSON(); let result = new AuthenticateResultModel(); result.init(json); return result; } } export interface IAuthenticateResultModel { accessToken: string | undefined; encryptedAccessToken: string | undefined; expireInSeconds: number; userId: number; } export class CategoryDto implements ICategoryDto { /** 分类名称 */ name: string | undefined; /** 父分类名 */ parentCategoryName: string | undefined; /** 父分类 */ parentCategoryId: number | undefined; /** 创建时间 */ creationTime: moment.Moment; id: number; constructor(data?: ICategoryDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.parentCategoryName = data["parentCategoryName"]; this.parentCategoryId = data["parentCategoryId"]; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : <any>undefined; this.id = data["id"]; } } static fromJS(data: any): CategoryDto { data = typeof data === 'object' ? data : {}; let result = new CategoryDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["parentCategoryName"] = this.parentCategoryName; data["parentCategoryId"] = this.parentCategoryId; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : <any>undefined; data["id"] = this.id; return data; } clone(): CategoryDto { const json = this.toJSON(); let result = new CategoryDto(); result.init(json); return result; } } export interface ICategoryDto { /** 分类名称 */ name: string | undefined; /** 父分类名 */ parentCategoryName: string | undefined; /** 父分类 */ parentCategoryId: number | undefined; /** 创建时间 */ creationTime: moment.Moment; id: number; } export class CategoryDtoPagedResultDto implements ICategoryDtoPagedResultDto { totalCount: number; items: CategoryDto[] | undefined; constructor(data?: ICategoryDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(CategoryDto.fromJS(item)); } } } static fromJS(data: any): CategoryDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new CategoryDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): CategoryDtoPagedResultDto { const json = this.toJSON(); let result = new CategoryDtoPagedResultDto(); result.init(json); return result; } } export interface ICategoryDtoPagedResultDto { totalCount: number; items: CategoryDto[] | undefined; } export class ChangePasswordDto implements IChangePasswordDto { currentPassword: string; newPassword: string; constructor(data?: IChangePasswordDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.currentPassword = data["currentPassword"]; this.newPassword = data["newPassword"]; } } static fromJS(data: any): ChangePasswordDto { data = typeof data === 'object' ? data : {}; let result = new ChangePasswordDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["currentPassword"] = this.currentPassword; data["newPassword"] = this.newPassword; return data; } clone(): ChangePasswordDto { const json = this.toJSON(); let result = new ChangePasswordDto(); result.init(json); return result; } } export interface IChangePasswordDto { currentPassword: string; newPassword: string; } export class ChangePasswordInput implements IChangePasswordInput { currentPassword: string; newPassword: string; constructor(data?: IChangePasswordInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.currentPassword = data["currentPassword"]; this.newPassword = data["newPassword"]; } } static fromJS(data: any): ChangePasswordInput { data = typeof data === 'object' ? data : {}; let result = new ChangePasswordInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["currentPassword"] = this.currentPassword; data["newPassword"] = this.newPassword; return data; } clone(): ChangePasswordInput { const json = this.toJSON(); let result = new ChangePasswordInput(); result.init(json); return result; } } export interface IChangePasswordInput { currentPassword: string; newPassword: string; } export class ChangeUiThemeInput implements IChangeUiThemeInput { theme: string; constructor(data?: IChangeUiThemeInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.theme = data["theme"]; } } static fromJS(data: any): ChangeUiThemeInput { data = typeof data === 'object' ? data : {}; let result = new ChangeUiThemeInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["theme"] = this.theme; return data; } clone(): ChangeUiThemeInput { const json = this.toJSON(); let result = new ChangeUiThemeInput(); result.init(json); return result; } } export interface IChangeUiThemeInput { theme: string; } export class ChangeUserLanguageDto implements IChangeUserLanguageDto { languageName: string; constructor(data?: IChangeUserLanguageDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.languageName = data["languageName"]; } } static fromJS(data: any): ChangeUserLanguageDto { data = typeof data === 'object' ? data : {}; let result = new ChangeUserLanguageDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["languageName"] = this.languageName; return data; } clone(): ChangeUserLanguageDto { const json = this.toJSON(); let result = new ChangeUserLanguageDto(); result.init(json); return result; } } export interface IChangeUserLanguageDto { languageName: string; } export class CreateCategoryDto implements ICreateCategoryDto { /** 分类名称 */ name: string | undefined; /** 父分类 */ parentCategoryId: number | undefined; constructor(data?: ICreateCategoryDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.parentCategoryId = data["parentCategoryId"]; } } static fromJS(data: any): CreateCategoryDto { data = typeof data === 'object' ? data : {}; let result = new CreateCategoryDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["parentCategoryId"] = this.parentCategoryId; return data; } clone(): CreateCategoryDto { const json = this.toJSON(); let result = new CreateCategoryDto(); result.init(json); return result; } } export interface ICreateCategoryDto { /** 分类名称 */ name: string | undefined; /** 父分类 */ parentCategoryId: number | undefined; } export class CreateRoleDto implements ICreateRoleDto { name: string; displayName: string; normalizedName: string | undefined; description: string | undefined; isDefault: boolean; permissions: string[] | undefined; constructor(data?: ICreateRoleDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.normalizedName = data["normalizedName"]; this.description = data["description"]; this.isDefault = data["isDefault"]; if (data["permissions"] && data["permissions"].constructor === Array) { this.permissions = [] as any; for (let item of data["permissions"]) this.permissions.push(item); } } } static fromJS(data: any): CreateRoleDto { data = typeof data === 'object' ? data : {}; let result = new CreateRoleDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["normalizedName"] = this.normalizedName; data["description"] = this.description; data["isDefault"] = this.isDefault; if (this.permissions && this.permissions.constructor === Array) { data["permissions"] = []; for (let item of this.permissions) data["permissions"].push(item); } return data; } clone(): CreateRoleDto { const json = this.toJSON(); let result = new CreateRoleDto(); result.init(json); return result; } } export interface ICreateRoleDto { name: string; displayName: string; normalizedName: string | undefined; description: string | undefined; isDefault: boolean; permissions: string[] | undefined; } export class CreateTenantDto implements ICreateTenantDto { tenancyName: string; name: string; adminEmailAddress: string; connectionString: string | undefined; isActive: boolean; constructor(data?: ICreateTenantDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.tenancyName = data["tenancyName"]; this.name = data["name"]; this.adminEmailAddress = data["adminEmailAddress"]; this.connectionString = data["connectionString"]; this.isActive = data["isActive"]; } } static fromJS(data: any): CreateTenantDto { data = typeof data === 'object' ? data : {}; let result = new CreateTenantDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["tenancyName"] = this.tenancyName; data["name"] = this.name; data["adminEmailAddress"] = this.adminEmailAddress; data["connectionString"] = this.connectionString; data["isActive"] = this.isActive; return data; } clone(): CreateTenantDto { const json = this.toJSON(); let result = new CreateTenantDto(); result.init(json); return result; } } export interface ICreateTenantDto { tenancyName: string; name: string; adminEmailAddress: string; connectionString: string | undefined; isActive: boolean; } export class CreateUserDto implements ICreateUserDto { userName: string; name: string; surname: string; emailAddress: string; isActive: boolean; roleNames: string[] | undefined; password: string; constructor(data?: ICreateUserDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.userName = data["userName"]; this.name = data["name"]; this.surname = data["surname"]; this.emailAddress = data["emailAddress"]; this.isActive = data["isActive"]; if (data["roleNames"] && data["roleNames"].constructor === Array) { this.roleNames = [] as any; for (let item of data["roleNames"]) this.roleNames.push(item); } this.password = data["password"]; } } static fromJS(data: any): CreateUserDto { data = typeof data === 'object' ? data : {}; let result = new CreateUserDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["userName"] = this.userName; data["name"] = this.name; data["surname"] = this.surname; data["emailAddress"] = this.emailAddress; data["isActive"] = this.isActive; if (this.roleNames && this.roleNames.constructor === Array) { data["roleNames"] = []; for (let item of this.roleNames) data["roleNames"].push(item); } data["password"] = this.password; return data; } clone(): CreateUserDto { const json = this.toJSON(); let result = new CreateUserDto(); result.init(json); return result; } } export interface ICreateUserDto { userName: string; name: string; surname: string; emailAddress: string; isActive: boolean; roleNames: string[] | undefined; password: string; } export class EmailConfirmationSettingDto implements IEmailConfirmationSettingDto { isEmailConfirmationRequiredForLogin: boolean; constructor(data?: IEmailConfirmationSettingDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.isEmailConfirmationRequiredForLogin = data["isEmailConfirmationRequiredForLogin"]; } } static fromJS(data: any): EmailConfirmationSettingDto { data = typeof data === 'object' ? data : {}; let result = new EmailConfirmationSettingDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isEmailConfirmationRequiredForLogin"] = this.isEmailConfirmationRequiredForLogin; return data; } clone(): EmailConfirmationSettingDto { const json = this.toJSON(); let result = new EmailConfirmationSettingDto(); result.init(json); return result; } } export interface IEmailConfirmationSettingDto { isEmailConfirmationRequiredForLogin: boolean; } export class EmailSettingsDto implements IEmailSettingsDto { defaultFromAddress: string | undefined; defaultFromDisplayName: string | undefined; smtpHost: string | undefined; smtpPort: number; smtpUserName: string | undefined; smtpPassword: string | undefined; smtpDomain: string | undefined; smtpEnableSsl: boolean; smtpUseDefaultCredentials: boolean; constructor(data?: IEmailSettingsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.defaultFromAddress = data["defaultFromAddress"]; this.defaultFromDisplayName = data["defaultFromDisplayName"]; this.smtpHost = data["smtpHost"]; this.smtpPort = data["smtpPort"]; this.smtpUserName = data["smtpUserName"]; this.smtpPassword = data["smtpPassword"]; this.smtpDomain = data["smtpDomain"]; this.smtpEnableSsl = data["smtpEnableSsl"]; this.smtpUseDefaultCredentials = data["smtpUseDefaultCredentials"]; } } static fromJS(data: any): EmailSettingsDto { data = typeof data === 'object' ? data : {}; let result = new EmailSettingsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["defaultFromAddress"] = this.defaultFromAddress; data["defaultFromDisplayName"] = this.defaultFromDisplayName; data["smtpHost"] = this.smtpHost; data["smtpPort"] = this.smtpPort; data["smtpUserName"] = this.smtpUserName; data["smtpPassword"] = this.smtpPassword; data["smtpDomain"] = this.smtpDomain; data["smtpEnableSsl"] = this.smtpEnableSsl; data["smtpUseDefaultCredentials"] = this.smtpUseDefaultCredentials; return data; } clone(): EmailSettingsDto { const json = this.toJSON(); let result = new EmailSettingsDto(); result.init(json); return result; } } export interface IEmailSettingsDto { defaultFromAddress: string | undefined; defaultFromDisplayName: string | undefined; smtpHost: string | undefined; smtpPort: number; smtpUserName: string | undefined; smtpPassword: string | undefined; smtpDomain: string | undefined; smtpEnableSsl: boolean; smtpUseDefaultCredentials: boolean; } export class ExternalAuthenticateModel implements IExternalAuthenticateModel { authProvider: string; providerKey: string; providerAccessCode: string; constructor(data?: IExternalAuthenticateModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.authProvider = data["authProvider"]; this.providerKey = data["providerKey"]; this.providerAccessCode = data["providerAccessCode"]; } } static fromJS(data: any): ExternalAuthenticateModel { data = typeof data === 'object' ? data : {}; let result = new ExternalAuthenticateModel(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["authProvider"] = this.authProvider; data["providerKey"] = this.providerKey; data["providerAccessCode"] = this.providerAccessCode; return data; } clone(): ExternalAuthenticateModel { const json = this.toJSON(); let result = new ExternalAuthenticateModel(); result.init(json); return result; } } export interface IExternalAuthenticateModel { authProvider: string; providerKey: string; providerAccessCode: string; } export class ExternalAuthenticateResultModel implements IExternalAuthenticateResultModel { accessToken: string | undefined; encryptedAccessToken: string | undefined; expireInSeconds: number; waitingForActivation: boolean; constructor(data?: IExternalAuthenticateResultModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.accessToken = data["accessToken"]; this.encryptedAccessToken = data["encryptedAccessToken"]; this.expireInSeconds = data["expireInSeconds"]; this.waitingForActivation = data["waitingForActivation"]; } } static fromJS(data: any): ExternalAuthenticateResultModel { data = typeof data === 'object' ? data : {}; let result = new ExternalAuthenticateResultModel(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["accessToken"] = this.accessToken; data["encryptedAccessToken"] = this.encryptedAccessToken; data["expireInSeconds"] = this.expireInSeconds; data["waitingForActivation"] = this.waitingForActivation; return data; } clone(): ExternalAuthenticateResultModel { const json = this.toJSON(); let result = new ExternalAuthenticateResultModel(); result.init(json); return result; } } export interface IExternalAuthenticateResultModel { accessToken: string | undefined; encryptedAccessToken: string | undefined; expireInSeconds: number; waitingForActivation: boolean; } export class ExternalLoginProviderInfoModel implements IExternalLoginProviderInfoModel { name: string | undefined; clientId: string | undefined; constructor(data?: IExternalLoginProviderInfoModel) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.clientId = data["clientId"]; } } static fromJS(data: any): ExternalLoginProviderInfoModel { data = typeof data === 'object' ? data : {}; let result = new ExternalLoginProviderInfoModel(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["clientId"] = this.clientId; return data; } clone(): ExternalLoginProviderInfoModel { const json = this.toJSON(); let result = new ExternalLoginProviderInfoModel(); result.init(json); return result; } } export interface IExternalLoginProviderInfoModel { name: string | undefined; clientId: string | undefined; } export class FlatPermissionDto implements IFlatPermissionDto { name: string | undefined; displayName: string | undefined; description: string | undefined; constructor(data?: IFlatPermissionDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.description = data["description"]; } } static fromJS(data: any): FlatPermissionDto { data = typeof data === 'object' ? data : {}; let result = new FlatPermissionDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["description"] = this.description; return data; } clone(): FlatPermissionDto { const json = this.toJSON(); let result = new FlatPermissionDto(); result.init(json); return result; } } export interface IFlatPermissionDto { name: string | undefined; displayName: string | undefined; description: string | undefined; } export enum Gender { _0 = 0, _1 = 1, } export class GetCurrentLoginInformationsOutput implements IGetCurrentLoginInformationsOutput { application: ApplicationInfoDto; user: UserLoginInfoDto; tenant: TenantLoginInfoDto; constructor(data?: IGetCurrentLoginInformationsOutput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.application = data["application"] ? ApplicationInfoDto.fromJS(data["application"]) : <any>undefined; this.user = data["user"] ? UserLoginInfoDto.fromJS(data["user"]) : <any>undefined; this.tenant = data["tenant"] ? TenantLoginInfoDto.fromJS(data["tenant"]) : <any>undefined; } } static fromJS(data: any): GetCurrentLoginInformationsOutput { data = typeof data === 'object' ? data : {}; let result = new GetCurrentLoginInformationsOutput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["application"] = this.application ? this.application.toJSON() : <any>undefined; data["user"] = this.user ? this.user.toJSON() : <any>undefined; data["tenant"] = this.tenant ? this.tenant.toJSON() : <any>undefined; return data; } clone(): GetCurrentLoginInformationsOutput { const json = this.toJSON(); let result = new GetCurrentLoginInformationsOutput(); result.init(json); return result; } } export interface IGetCurrentLoginInformationsOutput { application: ApplicationInfoDto; user: UserLoginInfoDto; tenant: TenantLoginInfoDto; } export class GetRoleForEditOutput implements IGetRoleForEditOutput { role: RoleEditDto; permissions: FlatPermissionDto[] | undefined; grantedPermissionNames: string[] | undefined; constructor(data?: IGetRoleForEditOutput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.role = data["role"] ? RoleEditDto.fromJS(data["role"]) : <any>undefined; if (data["permissions"] && data["permissions"].constructor === Array) { this.permissions = [] as any; for (let item of data["permissions"]) this.permissions.push(FlatPermissionDto.fromJS(item)); } if (data["grantedPermissionNames"] && data["grantedPermissionNames"].constructor === Array) { this.grantedPermissionNames = [] as any; for (let item of data["grantedPermissionNames"]) this.grantedPermissionNames.push(item); } } } static fromJS(data: any): GetRoleForEditOutput { data = typeof data === 'object' ? data : {}; let result = new GetRoleForEditOutput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["role"] = this.role ? this.role.toJSON() : <any>undefined; if (this.permissions && this.permissions.constructor === Array) { data["permissions"] = []; for (let item of this.permissions) data["permissions"].push(item.toJSON()); } if (this.grantedPermissionNames && this.grantedPermissionNames.constructor === Array) { data["grantedPermissionNames"] = []; for (let item of this.grantedPermissionNames) data["grantedPermissionNames"].push(item); } return data; } clone(): GetRoleForEditOutput { const json = this.toJSON(); let result = new GetRoleForEditOutput(); result.init(json); return result; } } export interface IGetRoleForEditOutput { role: RoleEditDto; permissions: FlatPermissionDto[] | undefined; grantedPermissionNames: string[] | undefined; } export class Int64EntityDto implements IInt64EntityDto { id: number; constructor(data?: IInt64EntityDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.id = data["id"]; } } static fromJS(data: any): Int64EntityDto { data = typeof data === 'object' ? data : {}; let result = new Int64EntityDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["id"] = this.id; return data; } clone(): Int64EntityDto { const json = this.toJSON(); let result = new Int64EntityDto(); result.init(json); return result; } } export interface IInt64EntityDto { id: number; } export class IsTenantAvailableInput implements IIsTenantAvailableInput { tenancyName: string; constructor(data?: IIsTenantAvailableInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.tenancyName = data["tenancyName"]; } } static fromJS(data: any): IsTenantAvailableInput { data = typeof data === 'object' ? data : {}; let result = new IsTenantAvailableInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["tenancyName"] = this.tenancyName; return data; } clone(): IsTenantAvailableInput { const json = this.toJSON(); let result = new IsTenantAvailableInput(); result.init(json); return result; } } export interface IIsTenantAvailableInput { tenancyName: string; } export class IsTenantAvailableOutput implements IIsTenantAvailableOutput { state: TenantAvailabilityState; tenantId: number | undefined; constructor(data?: IIsTenantAvailableOutput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.state = data["state"]; this.tenantId = data["tenantId"]; } } static fromJS(data: any): IsTenantAvailableOutput { data = typeof data === 'object' ? data : {}; let result = new IsTenantAvailableOutput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["state"] = this.state; data["tenantId"] = this.tenantId; return data; } clone(): IsTenantAvailableOutput { const json = this.toJSON(); let result = new IsTenantAvailableOutput(); result.init(json); return result; } } export interface IIsTenantAvailableOutput { state: TenantAvailabilityState; tenantId: number | undefined; } export class MemberTagsDto implements IMemberTagsDto { tagIds: number[] | undefined; id: number; constructor(data?: IMemberTagsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { if (data["tagIds"] && data["tagIds"].constructor === Array) { this.tagIds = [] as any; for (let item of data["tagIds"]) this.tagIds.push(item); } this.id = data["id"]; } } static fromJS(data: any): MemberTagsDto { data = typeof data === 'object' ? data : {}; let result = new MemberTagsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.tagIds && this.tagIds.constructor === Array) { data["tagIds"] = []; for (let item of this.tagIds) data["tagIds"].push(item); } data["id"] = this.id; return data; } clone(): MemberTagsDto { const json = this.toJSON(); let result = new MemberTagsDto(); result.init(json); return result; } } export interface IMemberTagsDto { tagIds: number[] | undefined; id: number; } export class MemberUserDto implements IMemberUserDto { /** 昵称 */ nickName: string | undefined; /** 头像 */ headLogo: string | undefined; gender: Gender; /** 城市 */ city: string | undefined; /** 省份 */ province: string | undefined; /** 国家 */ country: string | undefined; /** 用户名 */ userName: string; /** 名 */ name: string; /** 姓 */ surname: string; /** 邮箱地址 */ emailAddress: string; /** 是否启用 */ isActive: boolean; /** 全名 */ fullName: string | undefined; /** 最近登陆时间 */ lastLoginTime: moment.Moment | undefined; /** 注册时间 */ creationTime: moment.Moment; roleNames: string[] | undefined; id: number; constructor(data?: IMemberUserDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.nickName = data["nickName"]; this.headLogo = data["headLogo"]; this.gender = data["gender"]; this.city = data["city"]; this.province = data["province"]; this.country = data["country"]; this.userName = data["userName"]; this.name = data["name"]; this.surname = data["surname"]; this.emailAddress = data["emailAddress"]; this.isActive = data["isActive"]; this.fullName = data["fullName"]; this.lastLoginTime = data["lastLoginTime"] ? moment(data["lastLoginTime"].toString()) : <any>undefined; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : <any>undefined; if (data["roleNames"] && data["roleNames"].constructor === Array) { this.roleNames = [] as any; for (let item of data["roleNames"]) this.roleNames.push(item); } this.id = data["id"]; } } static fromJS(data: any): MemberUserDto { data = typeof data === 'object' ? data : {}; let result = new MemberUserDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["nickName"] = this.nickName; data["headLogo"] = this.headLogo; data["gender"] = this.gender; data["city"] = this.city; data["province"] = this.province; data["country"] = this.country; data["userName"] = this.userName; data["name"] = this.name; data["surname"] = this.surname; data["emailAddress"] = this.emailAddress; data["isActive"] = this.isActive; data["fullName"] = this.fullName; data["lastLoginTime"] = this.lastLoginTime ? this.lastLoginTime.toISOString() : <any>undefined; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : <any>undefined; if (this.roleNames && this.roleNames.constructor === Array) { data["roleNames"] = []; for (let item of this.roleNames) data["roleNames"].push(item); } data["id"] = this.id; return data; } clone(): MemberUserDto { const json = this.toJSON(); let result = new MemberUserDto(); result.init(json); return result; } } export interface IMemberUserDto { /** 昵称 */ nickName: string | undefined; /** 头像 */ headLogo: string | undefined; gender: Gender; /** 城市 */ city: string | undefined; /** 省份 */ province: string | undefined; /** 国家 */ country: string | undefined; /** 用户名 */ userName: string; /** 名 */ name: string; /** 姓 */ surname: string; /** 邮箱地址 */ emailAddress: string; /** 是否启用 */ isActive: boolean; /** 全名 */ fullName: string | undefined; /** 最近登陆时间 */ lastLoginTime: moment.Moment | undefined; /** 注册时间 */ creationTime: moment.Moment; roleNames: string[] | undefined; id: number; } export class MemberUserDtoPagedResultDto implements IMemberUserDtoPagedResultDto { totalCount: number; items: MemberUserDto[] | undefined; constructor(data?: IMemberUserDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(MemberUserDto.fromJS(item)); } } } static fromJS(data: any): MemberUserDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new MemberUserDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): MemberUserDtoPagedResultDto { const json = this.toJSON(); let result = new MemberUserDtoPagedResultDto(); result.init(json); return result; } } export interface IMemberUserDtoPagedResultDto { totalCount: number; items: MemberUserDto[] | undefined; } export class PasswordComplexitySettingsDto implements IPasswordComplexitySettingsDto { requiredLength: number; requireNonAlphanumeric: boolean; requireLowercase: boolean; requireUppercase: boolean; requireDigit: boolean; constructor(data?: IPasswordComplexitySettingsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.requiredLength = data["requiredLength"]; this.requireNonAlphanumeric = data["requireNonAlphanumeric"]; this.requireLowercase = data["requireLowercase"]; this.requireUppercase = data["requireUppercase"]; this.requireDigit = data["requireDigit"]; } } static fromJS(data: any): PasswordComplexitySettingsDto { data = typeof data === 'object' ? data : {}; let result = new PasswordComplexitySettingsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["requiredLength"] = this.requiredLength; data["requireNonAlphanumeric"] = this.requireNonAlphanumeric; data["requireLowercase"] = this.requireLowercase; data["requireUppercase"] = this.requireUppercase; data["requireDigit"] = this.requireDigit; return data; } clone(): PasswordComplexitySettingsDto { const json = this.toJSON(); let result = new PasswordComplexitySettingsDto(); result.init(json); return result; } } export interface IPasswordComplexitySettingsDto { requiredLength: number; requireNonAlphanumeric: boolean; requireLowercase: boolean; requireUppercase: boolean; requireDigit: boolean; } export class PermissionDto implements IPermissionDto { name: string | undefined; displayName: string | undefined; description: string | undefined; id: number; constructor(data?: IPermissionDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.description = data["description"]; this.id = data["id"]; } } static fromJS(data: any): PermissionDto { data = typeof data === 'object' ? data : {}; let result = new PermissionDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["description"] = this.description; data["id"] = this.id; return data; } clone(): PermissionDto { const json = this.toJSON(); let result = new PermissionDto(); result.init(json); return result; } } export interface IPermissionDto { name: string | undefined; displayName: string | undefined; description: string | undefined; id: number; } export class PermissionDtoListResultDto implements IPermissionDtoListResultDto { items: PermissionDto[] | undefined; constructor(data?: IPermissionDtoListResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(PermissionDto.fromJS(item)); } } } static fromJS(data: any): PermissionDtoListResultDto { data = typeof data === 'object' ? data : {}; let result = new PermissionDtoListResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): PermissionDtoListResultDto { const json = this.toJSON(); let result = new PermissionDtoListResultDto(); result.init(json); return result; } } export interface IPermissionDtoListResultDto { items: PermissionDto[] | undefined; } export class RegionDto implements IRegionDto { name: string | undefined; id: string | undefined; constructor(data?: IRegionDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.id = data["id"]; } } static fromJS(data: any): RegionDto { data = typeof data === 'object' ? data : {}; let result = new RegionDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["id"] = this.id; return data; } clone(): RegionDto { const json = this.toJSON(); let result = new RegionDto(); result.init(json); return result; } } export interface IRegionDto { name: string | undefined; id: string | undefined; } export class RegionDtoListResultDto implements IRegionDtoListResultDto { items: RegionDto[] | undefined; constructor(data?: IRegionDtoListResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(RegionDto.fromJS(item)); } } } static fromJS(data: any): RegionDtoListResultDto { data = typeof data === 'object' ? data : {}; let result = new RegionDtoListResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): RegionDtoListResultDto { const json = this.toJSON(); let result = new RegionDtoListResultDto(); result.init(json); return result; } } export interface IRegionDtoListResultDto { items: RegionDto[] | undefined; } export class RegisterInput implements IRegisterInput { name: string; surname: string; userName: string; emailAddress: string; password: string; captchaResponse: string | undefined; constructor(data?: IRegisterInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.surname = data["surname"]; this.userName = data["userName"]; this.emailAddress = data["emailAddress"]; this.password = data["password"]; this.captchaResponse = data["captchaResponse"]; } } static fromJS(data: any): RegisterInput { data = typeof data === 'object' ? data : {}; let result = new RegisterInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["surname"] = this.surname; data["userName"] = this.userName; data["emailAddress"] = this.emailAddress; data["password"] = this.password; data["captchaResponse"] = this.captchaResponse; return data; } clone(): RegisterInput { const json = this.toJSON(); let result = new RegisterInput(); result.init(json); return result; } } export interface IRegisterInput { name: string; surname: string; userName: string; emailAddress: string; password: string; captchaResponse: string | undefined; } export class RegisterOutput implements IRegisterOutput { canLogin: boolean; constructor(data?: IRegisterOutput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.canLogin = data["canLogin"]; } } static fromJS(data: any): RegisterOutput { data = typeof data === 'object' ? data : {}; let result = new RegisterOutput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["canLogin"] = this.canLogin; return data; } clone(): RegisterOutput { const json = this.toJSON(); let result = new RegisterOutput(); result.init(json); return result; } } export interface IRegisterOutput { canLogin: boolean; } export class ResetPasswordDto implements IResetPasswordDto { adminPassword: string; userId: number; newPassword: string; constructor(data?: IResetPasswordDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.adminPassword = data["adminPassword"]; this.userId = data["userId"]; this.newPassword = data["newPassword"]; } } static fromJS(data: any): ResetPasswordDto { data = typeof data === 'object' ? data : {}; let result = new ResetPasswordDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["adminPassword"] = this.adminPassword; data["userId"] = this.userId; data["newPassword"] = this.newPassword; return data; } clone(): ResetPasswordDto { const json = this.toJSON(); let result = new ResetPasswordDto(); result.init(json); return result; } } export interface IResetPasswordDto { adminPassword: string; userId: number; newPassword: string; } export class RoleDto implements IRoleDto { /** 角色名 */ name: string; /** 角色展示名 */ displayName: string; normalizedName: string | undefined; description: string | undefined; isStatic: boolean; isDefault: boolean; permissions: string[] | undefined; id: number; constructor(data?: IRoleDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.normalizedName = data["normalizedName"]; this.description = data["description"]; this.isStatic = data["isStatic"]; this.isDefault = data["isDefault"]; if (data["permissions"] && data["permissions"].constructor === Array) { this.permissions = [] as any; for (let item of data["permissions"]) this.permissions.push(item); } this.id = data["id"]; } } static fromJS(data: any): RoleDto { data = typeof data === 'object' ? data : {}; let result = new RoleDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["normalizedName"] = this.normalizedName; data["description"] = this.description; data["isStatic"] = this.isStatic; data["isDefault"] = this.isDefault; if (this.permissions && this.permissions.constructor === Array) { data["permissions"] = []; for (let item of this.permissions) data["permissions"].push(item); } data["id"] = this.id; return data; } clone(): RoleDto { const json = this.toJSON(); let result = new RoleDto(); result.init(json); return result; } } export interface IRoleDto { /** 角色名 */ name: string; /** 角色展示名 */ displayName: string; normalizedName: string | undefined; description: string | undefined; isStatic: boolean; isDefault: boolean; permissions: string[] | undefined; id: number; } export class RoleDtoListResultDto implements IRoleDtoListResultDto { items: RoleDto[] | undefined; constructor(data?: IRoleDtoListResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(RoleDto.fromJS(item)); } } } static fromJS(data: any): RoleDtoListResultDto { data = typeof data === 'object' ? data : {}; let result = new RoleDtoListResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): RoleDtoListResultDto { const json = this.toJSON(); let result = new RoleDtoListResultDto(); result.init(json); return result; } } export interface IRoleDtoListResultDto { items: RoleDto[] | undefined; } export class RoleDtoPagedResultDto implements IRoleDtoPagedResultDto { totalCount: number; items: RoleDto[] | undefined; constructor(data?: IRoleDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(RoleDto.fromJS(item)); } } } static fromJS(data: any): RoleDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new RoleDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): RoleDtoPagedResultDto { const json = this.toJSON(); let result = new RoleDtoPagedResultDto(); result.init(json); return result; } } export interface IRoleDtoPagedResultDto { totalCount: number; items: RoleDto[] | undefined; } export class RoleEditDto implements IRoleEditDto { name: string; displayName: string; description: string | undefined; isStatic: boolean; isDefault: boolean; id: number; constructor(data?: IRoleEditDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.description = data["description"]; this.isStatic = data["isStatic"]; this.isDefault = data["isDefault"]; this.id = data["id"]; } } static fromJS(data: any): RoleEditDto { data = typeof data === 'object' ? data : {}; let result = new RoleEditDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["description"] = this.description; data["isStatic"] = this.isStatic; data["isDefault"] = this.isDefault; data["id"] = this.id; return data; } clone(): RoleEditDto { const json = this.toJSON(); let result = new RoleEditDto(); result.init(json); return result; } } export interface IRoleEditDto { name: string; displayName: string; description: string | undefined; isStatic: boolean; isDefault: boolean; id: number; } export class RoleListDto implements IRoleListDto { name: string | undefined; displayName: string | undefined; isStatic: boolean; isDefault: boolean; creationTime: moment.Moment; id: number; constructor(data?: IRoleListDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.displayName = data["displayName"]; this.isStatic = data["isStatic"]; this.isDefault = data["isDefault"]; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : <any>undefined; this.id = data["id"]; } } static fromJS(data: any): RoleListDto { data = typeof data === 'object' ? data : {}; let result = new RoleListDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["displayName"] = this.displayName; data["isStatic"] = this.isStatic; data["isDefault"] = this.isDefault; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : <any>undefined; data["id"] = this.id; return data; } clone(): RoleListDto { const json = this.toJSON(); let result = new RoleListDto(); result.init(json); return result; } } export interface IRoleListDto { name: string | undefined; displayName: string | undefined; isStatic: boolean; isDefault: boolean; creationTime: moment.Moment; id: number; } export class RoleListDtoListResultDto implements IRoleListDtoListResultDto { items: RoleListDto[] | undefined; constructor(data?: IRoleListDtoListResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(RoleListDto.fromJS(item)); } } } static fromJS(data: any): RoleListDtoListResultDto { data = typeof data === 'object' ? data : {}; let result = new RoleListDtoListResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): RoleListDtoListResultDto { const json = this.toJSON(); let result = new RoleListDtoListResultDto(); result.init(json); return result; } } export interface IRoleListDtoListResultDto { items: RoleListDto[] | undefined; } export class SecuritySettingsDto implements ISecuritySettingsDto { isEmailConfirmationRequiredForLogin: boolean; userLockOut: UserLockOutSettingsDto; twoFactorLogin: TwoFactorLoginSettingsDto; passwordComplexity: PasswordComplexitySettingsDto; constructor(data?: ISecuritySettingsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.isEmailConfirmationRequiredForLogin = data["isEmailConfirmationRequiredForLogin"]; this.userLockOut = data["userLockOut"] ? UserLockOutSettingsDto.fromJS(data["userLockOut"]) : <any>undefined; this.twoFactorLogin = data["twoFactorLogin"] ? TwoFactorLoginSettingsDto.fromJS(data["twoFactorLogin"]) : <any>undefined; this.passwordComplexity = data["passwordComplexity"] ? PasswordComplexitySettingsDto.fromJS(data["passwordComplexity"]) : <any>undefined; } } static fromJS(data: any): SecuritySettingsDto { data = typeof data === 'object' ? data : {}; let result = new SecuritySettingsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isEmailConfirmationRequiredForLogin"] = this.isEmailConfirmationRequiredForLogin; data["userLockOut"] = this.userLockOut ? this.userLockOut.toJSON() : <any>undefined; data["twoFactorLogin"] = this.twoFactorLogin ? this.twoFactorLogin.toJSON() : <any>undefined; data["passwordComplexity"] = this.passwordComplexity ? this.passwordComplexity.toJSON() : <any>undefined; return data; } clone(): SecuritySettingsDto { const json = this.toJSON(); let result = new SecuritySettingsDto(); result.init(json); return result; } } export interface ISecuritySettingsDto { isEmailConfirmationRequiredForLogin: boolean; userLockOut: UserLockOutSettingsDto; twoFactorLogin: TwoFactorLoginSettingsDto; passwordComplexity: PasswordComplexitySettingsDto; } export class TagDto implements ITagDto { /** 标签名称 */ name: string | undefined; type: TagType; /** 标签描述 */ description: string | undefined; /** 颜色 */ color: string | undefined; /** 创建时间 */ creationTime: moment.Moment; id: number; constructor(data?: ITagDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.type = data["type"]; this.description = data["description"]; this.color = data["color"]; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : <any>undefined; this.id = data["id"]; } } static fromJS(data: any): TagDto { data = typeof data === 'object' ? data : {}; let result = new TagDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["type"] = this.type; data["description"] = this.description; data["color"] = this.color; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : <any>undefined; data["id"] = this.id; return data; } clone(): TagDto { const json = this.toJSON(); let result = new TagDto(); result.init(json); return result; } } export interface ITagDto { /** 标签名称 */ name: string | undefined; type: TagType; /** 标签描述 */ description: string | undefined; /** 颜色 */ color: string | undefined; /** 创建时间 */ creationTime: moment.Moment; id: number; } export class TagDtoPagedResultDto implements ITagDtoPagedResultDto { totalCount: number; items: TagDto[] | undefined; constructor(data?: ITagDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(TagDto.fromJS(item)); } } } static fromJS(data: any): TagDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new TagDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): TagDtoPagedResultDto { const json = this.toJSON(); let result = new TagDtoPagedResultDto(); result.init(json); return result; } } export interface ITagDtoPagedResultDto { totalCount: number; items: TagDto[] | undefined; } /** 标签类型 */ export enum TagType { MemberUser = <any>"MemberUser", } export enum TenantAvailabilityState { Available = <any>"Available", InActive = <any>"InActive", NotFound = <any>"NotFound", } export class TenantDto implements ITenantDto { tenancyName: string; name: string; isActive: boolean; id: number; constructor(data?: ITenantDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.tenancyName = data["tenancyName"]; this.name = data["name"]; this.isActive = data["isActive"]; this.id = data["id"]; } } static fromJS(data: any): TenantDto { data = typeof data === 'object' ? data : {}; let result = new TenantDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["tenancyName"] = this.tenancyName; data["name"] = this.name; data["isActive"] = this.isActive; data["id"] = this.id; return data; } clone(): TenantDto { const json = this.toJSON(); let result = new TenantDto(); result.init(json); return result; } } export interface ITenantDto { tenancyName: string; name: string; isActive: boolean; id: number; } export class TenantDtoPagedResultDto implements ITenantDtoPagedResultDto { totalCount: number; items: TenantDto[] | undefined; constructor(data?: ITenantDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(TenantDto.fromJS(item)); } } } static fromJS(data: any): TenantDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new TenantDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): TenantDtoPagedResultDto { const json = this.toJSON(); let result = new TenantDtoPagedResultDto(); result.init(json); return result; } } export interface ITenantDtoPagedResultDto { totalCount: number; items: TenantDto[] | undefined; } export class TenantLoginInfoDto implements ITenantLoginInfoDto { tenancyName: string | undefined; name: string | undefined; id: number; constructor(data?: ITenantLoginInfoDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.tenancyName = data["tenancyName"]; this.name = data["name"]; this.id = data["id"]; } } static fromJS(data: any): TenantLoginInfoDto { data = typeof data === 'object' ? data : {}; let result = new TenantLoginInfoDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["tenancyName"] = this.tenancyName; data["name"] = this.name; data["id"] = this.id; return data; } clone(): TenantLoginInfoDto { const json = this.toJSON(); let result = new TenantLoginInfoDto(); result.init(json); return result; } } export interface ITenantLoginInfoDto { tenancyName: string | undefined; name: string | undefined; id: number; } export class TestEmailSettingsInput implements ITestEmailSettingsInput { to: string; constructor(data?: ITestEmailSettingsInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.to = data["to"]; } } static fromJS(data: any): TestEmailSettingsInput { data = typeof data === 'object' ? data : {}; let result = new TestEmailSettingsInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["to"] = this.to; return data; } clone(): TestEmailSettingsInput { const json = this.toJSON(); let result = new TestEmailSettingsInput(); result.init(json); return result; } } export interface ITestEmailSettingsInput { to: string; } export class TwoFactorLoginSettingsDto implements ITwoFactorLoginSettingsDto { isEnabled: boolean; isEmailProviderEnabled: boolean; isSmsProviderEnabled: boolean; isRememberBrowserEnabled: boolean; constructor(data?: ITwoFactorLoginSettingsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.isEnabled = data["isEnabled"]; this.isEmailProviderEnabled = data["isEmailProviderEnabled"]; this.isSmsProviderEnabled = data["isSmsProviderEnabled"]; this.isRememberBrowserEnabled = data["isRememberBrowserEnabled"]; } } static fromJS(data: any): TwoFactorLoginSettingsDto { data = typeof data === 'object' ? data : {}; let result = new TwoFactorLoginSettingsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isEnabled"] = this.isEnabled; data["isEmailProviderEnabled"] = this.isEmailProviderEnabled; data["isSmsProviderEnabled"] = this.isSmsProviderEnabled; data["isRememberBrowserEnabled"] = this.isRememberBrowserEnabled; return data; } clone(): TwoFactorLoginSettingsDto { const json = this.toJSON(); let result = new TwoFactorLoginSettingsDto(); result.init(json); return result; } } export interface ITwoFactorLoginSettingsDto { isEnabled: boolean; isEmailProviderEnabled: boolean; isSmsProviderEnabled: boolean; isRememberBrowserEnabled: boolean; } export class UserDto implements IUserDto { /** 用户名 */ userName: string; /** 名 */ name: string; /** 姓 */ surname: string; /** 邮箱地址 */ emailAddress: string; /** 是否启用 */ isActive: boolean; /** 全名 */ fullName: string | undefined; /** 最近登陆时间 */ lastLoginTime: moment.Moment | undefined; /** 注册时间 */ creationTime: moment.Moment; roleNames: string[] | undefined; id: number; constructor(data?: IUserDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.userName = data["userName"]; this.name = data["name"]; this.surname = data["surname"]; this.emailAddress = data["emailAddress"]; this.isActive = data["isActive"]; this.fullName = data["fullName"]; this.lastLoginTime = data["lastLoginTime"] ? moment(data["lastLoginTime"].toString()) : <any>undefined; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : <any>undefined; if (data["roleNames"] && data["roleNames"].constructor === Array) { this.roleNames = [] as any; for (let item of data["roleNames"]) this.roleNames.push(item); } this.id = data["id"]; } } static fromJS(data: any): UserDto { data = typeof data === 'object' ? data : {}; let result = new UserDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["userName"] = this.userName; data["name"] = this.name; data["surname"] = this.surname; data["emailAddress"] = this.emailAddress; data["isActive"] = this.isActive; data["fullName"] = this.fullName; data["lastLoginTime"] = this.lastLoginTime ? this.lastLoginTime.toISOString() : <any>undefined; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : <any>undefined; if (this.roleNames && this.roleNames.constructor === Array) { data["roleNames"] = []; for (let item of this.roleNames) data["roleNames"].push(item); } data["id"] = this.id; return data; } clone(): UserDto { const json = this.toJSON(); let result = new UserDto(); result.init(json); return result; } } export interface IUserDto { /** 用户名 */ userName: string; /** 名 */ name: string; /** 姓 */ surname: string; /** 邮箱地址 */ emailAddress: string; /** 是否启用 */ isActive: boolean; /** 全名 */ fullName: string | undefined; /** 最近登陆时间 */ lastLoginTime: moment.Moment | undefined; /** 注册时间 */ creationTime: moment.Moment; roleNames: string[] | undefined; id: number; } export class UserDtoPagedResultDto implements IUserDtoPagedResultDto { totalCount: number; items: UserDto[] | undefined; constructor(data?: IUserDtoPagedResultDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.totalCount = data["totalCount"]; if (data["items"] && data["items"].constructor === Array) { this.items = [] as any; for (let item of data["items"]) this.items.push(UserDto.fromJS(item)); } } } static fromJS(data: any): UserDtoPagedResultDto { data = typeof data === 'object' ? data : {}; let result = new UserDtoPagedResultDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["totalCount"] = this.totalCount; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJSON()); } return data; } clone(): UserDtoPagedResultDto { const json = this.toJSON(); let result = new UserDtoPagedResultDto(); result.init(json); return result; } } export interface IUserDtoPagedResultDto { totalCount: number; items: UserDto[] | undefined; } export class UserLockOutSettingsDto implements IUserLockOutSettingsDto { isEnabled: boolean; maxFailedAccessAttemptsBeforeLockout: number; defaultAccountLockoutSeconds: number; constructor(data?: IUserLockOutSettingsDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.isEnabled = data["isEnabled"]; this.maxFailedAccessAttemptsBeforeLockout = data["maxFailedAccessAttemptsBeforeLockout"]; this.defaultAccountLockoutSeconds = data["defaultAccountLockoutSeconds"]; } } static fromJS(data: any): UserLockOutSettingsDto { data = typeof data === 'object' ? data : {}; let result = new UserLockOutSettingsDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["isEnabled"] = this.isEnabled; data["maxFailedAccessAttemptsBeforeLockout"] = this.maxFailedAccessAttemptsBeforeLockout; data["defaultAccountLockoutSeconds"] = this.defaultAccountLockoutSeconds; return data; } clone(): UserLockOutSettingsDto { const json = this.toJSON(); let result = new UserLockOutSettingsDto(); result.init(json); return result; } } export interface IUserLockOutSettingsDto { isEnabled: boolean; maxFailedAccessAttemptsBeforeLockout: number; defaultAccountLockoutSeconds: number; } export class UserLoginInfoDto implements IUserLoginInfoDto { name: string | undefined; surname: string | undefined; userName: string | undefined; emailAddress: string | undefined; headLogo: string | undefined; id: number; constructor(data?: IUserLoginInfoDto) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.name = data["name"]; this.surname = data["surname"]; this.userName = data["userName"]; this.emailAddress = data["emailAddress"]; this.headLogo = data["headLogo"]; this.id = data["id"]; } } static fromJS(data: any): UserLoginInfoDto { data = typeof data === 'object' ? data : {}; let result = new UserLoginInfoDto(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["name"] = this.name; data["surname"] = this.surname; data["userName"] = this.userName; data["emailAddress"] = this.emailAddress; data["headLogo"] = this.headLogo; data["id"] = this.id; return data; } clone(): UserLoginInfoDto { const json = this.toJSON(); let result = new UserLoginInfoDto(); result.init(json); return result; } } export interface IUserLoginInfoDto { name: string | undefined; surname: string | undefined; userName: string | undefined; emailAddress: string | undefined; headLogo: string | undefined; id: number; } export class WechatUserInfoInput implements IWechatUserInfoInput { iv: string | undefined; encryptedData: string | undefined; constructor(data?: IWechatUserInfoInput) { if (data) { for (var property in data) { if (data.hasOwnProperty(property)) (<any>this)[property] = (<any>data)[property]; } } } init(data?: any) { if (data) { this.iv = data["iv"]; this.encryptedData = data["encryptedData"]; } } static fromJS(data: any): WechatUserInfoInput { data = typeof data === 'object' ? data : {}; let result = new WechatUserInfoInput(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["iv"] = this.iv; data["encryptedData"] = this.encryptedData; return data; } clone(): WechatUserInfoInput { const json = this.toJSON(); let result = new WechatUserInfoInput(); result.init(json); return result; } } export interface IWechatUserInfoInput { iv: string | undefined; encryptedData: string | undefined; } export class SwaggerException extends Error { message: string; status: number; response: string; headers: { [key: string]: any; }; result: any; constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) { super(); this.message = message; this.status = status; this.response = response; this.headers = headers; this.result = result; } protected isSwaggerException = true; static isSwaggerException(obj: any): obj is SwaggerException { return obj.isSwaggerException === true; } } function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): Observable<any> { if(result !== null && result !== undefined) return _observableThrow(result); else return _observableThrow(new SwaggerException(message, status, response, headers, null)); } function blobToText(blob: any): Observable<string> { return new Observable<string>((observer: any) => { if (!blob) { observer.next(""); observer.complete(); } else { let reader = new FileReader(); reader.onload = event => { observer.next((<any>event.target).result); observer.complete(); }; reader.readAsText(blob); } }); }
the_stack
import pino from 'pino' import { DirectusApplication, DirectusCollectibleTemplate, DirectusCollection, DirectusHomepage, DirectusLanguageTemplate, DirectusPackTemplate, DirectusSet, DirectusStatus, DirectusWebhook, } from '@algomart/schemas' import { HttpTransport } from '@algomart/shared/utils' import { CMSCacheCollectionModel, CMSCacheCollectibleTemplateModel, CMSCacheLanguageModel, CMSCachePackTemplateModel, CMSCacheSetModel, CMSCacheHomepageModel, CMSCacheApplicationModel, } from '@algomart/shared/models' // #region Directus Helpers interface ItemsResponse<T> { data: T[] meta?: { filter_count?: number total_count?: number } } interface ItemFilter { [key: string]: | string | string[] | number | number[] | boolean | boolean[] | Date | Date[] | ItemFilter | ItemFilter[] } interface ItemQuery<TItem> { fields?: (keyof TItem | string)[] search?: string sort?: string[] filter?: ItemFilter limit?: number offset?: number page?: number deep?: ItemFilter totalCount?: boolean filterCount?: boolean } function getParameters<TItem>(query?: ItemQuery<TItem>) { const parameters = {} if (query?.fields) { Object.assign(parameters, { fields: query.fields.join(',') }) } if (query?.search) { Object.assign(parameters, { search: query.search }) } if (query?.sort) { Object.assign(parameters, { sort: query.sort.join(',') }) } if (query?.limit) { Object.assign(parameters, { limit: query.limit }) } if (query?.offset) { Object.assign(parameters, { offset: query.offset }) } if (query?.page) { Object.assign(parameters, { page: query.page }) } if (query?.filter) { Object.assign(parameters, { filter: JSON.stringify(query.filter) }) } if (query?.deep) { Object.assign(parameters, { deep: JSON.stringify(query.deep) }) } if (query?.totalCount || query?.filterCount) { Object.assign(parameters, { meta: query.totalCount && query.filterCount ? '*' : query.totalCount ? 'total_count' : 'filter_count', }) } return parameters } // #endregion export interface DirectusAdapterOptions { cmsUrl: string gcpCdnUrl?: string accessToken: string } export class DirectusAdapter { logger: pino.Logger<unknown> http: HttpTransport constructor( private readonly options: DirectusAdapterOptions, logger: pino.Logger<unknown> ) { this.logger = logger.child({ context: this.constructor.name }) this.http = new HttpTransport(options.cmsUrl, undefined, { Authorization: `Bearer ${options.accessToken}`, }) this.testConnection() } async testConnection() { try { await this.ensureFilePermission() this.logger.info('Successfully connected to CMS') } catch (error) { this.logger.error(error, 'Failed to connect to CMS') } } async ensureFilePermission() { const permissions = await this.http .get<{ data: Array<{ id: number role: string | null collection: string action: 'create' | 'read' | 'update' | 'delete' fields: string[] }> }>('permissions', { params: { fields: 'id,role,collection,action,fields', 'filter[collection][_eq]': 'directus_files', 'filter[fields][_in]': '*', 'filter[action][_eq]': 'read', }, }) .then((response) => response.data) if (permissions.data.length === 0) { await this.http.post('permissions', { json: { collection: 'directus_files', fields: ['*'], action: 'read', role: null, }, }) } } private async findMany<TItem>( collection: string, query: ItemQuery<TItem> = {} ): Promise<ItemsResponse<TItem>> { const response = await this.http.get<ItemsResponse<TItem>>( `items/${collection}`, { params: getParameters(query), } ) return response.data } private async findPackTemplates(query: ItemQuery<DirectusPackTemplate> = {}) { const defaultQuery: ItemQuery<DirectusPackTemplate> = { filter: { status: { _eq: DirectusStatus.Published, }, }, limit: -1, fields: [ '*', 'pack_image.*', 'translations.*', 'nft_templates.*', 'nft_templates.translations.*', 'nft_templates.asset_file.*', 'nft_templates.translations.*', 'nft_templates.preview_audio.*', 'nft_templates.preview_image.*', 'nft_templates.preview_video.*', 'nft_templates.rarity.*', 'nft_templates.rarity.translations.*', ], } return await this.findMany<DirectusPackTemplate>('pack_templates', { ...defaultQuery, ...query, }) } private async findCollectibleTemplates( query: ItemQuery<DirectusCollectibleTemplate> = {} ) { const defaultQuery: ItemQuery<DirectusCollectibleTemplate> = { filter: { status: { _eq: DirectusStatus.Published, }, }, limit: -1, fields: [ 'id', 'total_editions', 'unique_code', 'preview_image.*', 'preview_video.*', 'preview_audio.*', 'asset_file.*', 'translations.*', 'rarity.code', 'rarity.color', 'rarity.translations.*', 'set.id', 'set.collection.id', 'collection', ], } return await this.findMany<DirectusCollectibleTemplate>('nft_templates', { ...defaultQuery, ...query, }) } private async findCollections(query: ItemQuery<DirectusCollection> = {}) { const defaultQuery: ItemQuery<DirectusCollection> = { filter: { status: { _eq: DirectusStatus.Published, }, }, limit: -1, fields: [ 'collection_image.*', 'id', 'nft_templates', 'reward_image.*', 'slug', 'translations.*', 'sets.id', 'sets.nft_templates', 'sets.slug', 'sets.translations.*', ], } return await this.findMany<DirectusCollection>('collections', { ...defaultQuery, ...query, }) } private async findLanguages(query: ItemQuery<DirectusLanguageTemplate> = {}) { const defaultQuery: ItemQuery<DirectusLanguageTemplate> = { limit: -1, fields: ['code', 'name', 'sort'], } return await this.findMany<DirectusLanguageTemplate>('languages', { ...defaultQuery, ...query, }) } private async findSets(query: ItemQuery<DirectusSet> = {}) { const defaultQuery: ItemQuery<DirectusSet> = { filter: { status: { _eq: DirectusStatus.Published, }, }, limit: -1, fields: [ 'id', 'status', 'sort', 'slug', 'collection.*', 'collection.translations.*', 'translations.*', 'nft_templates.*', ], } return await this.findMany<DirectusSet>('sets', { ...defaultQuery, ...query, }) } // #region directus sync methods private async syncCollection(collectionId) { const response = await this.findCollections({ filter: { id: { _eq: collectionId, }, status: { _eq: DirectusStatus.Published, }, }, }) if (response.data.length > 0) { await CMSCacheCollectionModel.upsert( response.data[0] as unknown as DirectusCollection ) } } private async syncCollectibleTemplate(collectibleId) { const response = await this.findCollectibleTemplates({ filter: { id: { _eq: collectibleId, }, status: { _eq: DirectusStatus.Published, }, }, }) if (response.data.length > 0) { await CMSCacheCollectibleTemplateModel.upsert( response.data[0] as unknown as DirectusCollectibleTemplate ) } } private async syncLanguage(languageCode) { const response = await this.findLanguages({ filter: { code: { _eq: languageCode, }, }, }) if (response.data.length > 0) { await CMSCacheLanguageModel.upsert( response.data[0] as unknown as DirectusLanguageTemplate ) } } private async syncPackTemplate(packId) { const response = await this.findPackTemplates({ filter: { id: { _eq: packId, }, status: { _eq: DirectusStatus.Published, }, }, }) if (response.data.length > 0) { await CMSCachePackTemplateModel.upsert( response.data[0] as unknown as DirectusPackTemplate ) } } private async syncCountries() { await this.syncApplication() } private async syncRarities() { await this.syncHomePage() const collectibleTemplates = await this.findCollectibleTemplates() for (const collectibleTemplate in collectibleTemplates) { await CMSCacheCollectibleTemplateModel.upsert( collectibleTemplate as unknown as DirectusCollectibleTemplate ) } } private async syncSet(setId) { const response = await this.findSets({ filter: { id: { _eq: setId, }, status: { _eq: DirectusStatus.Published, }, }, }) if (response.data.length > 0) { await CMSCacheSetModel.upsert(response.data[0] as unknown as DirectusSet) } } // #endregion async syncAllLanguages() { const response = await this.findLanguages() for (const language of response.data) { await CMSCacheLanguageModel.upsert(language) } } async syncAllPackTemplates() { const response = await this.findPackTemplates({ filter: { status: { _eq: DirectusStatus.Published, }, }, }) for (const packTemplate of response.data) { await CMSCachePackTemplateModel.upsert(packTemplate) } } async syncAllCollectibleTemplates() { const response = await this.findCollectibleTemplates({ filter: { status: { _eq: DirectusStatus.Published, }, }, }) for (const collectibleTemplate of response.data) { await CMSCacheCollectibleTemplateModel.upsert(collectibleTemplate) } } async syncAllCollections() { const response = await this.findCollections({ filter: { status: { _eq: DirectusStatus.Published, }, }, }) for (const collection of response.data) { await CMSCacheCollectionModel.upsert(collection) } } async syncAllSets() { const response = await this.findSets({ filter: { status: { _eq: DirectusStatus.Published, }, }, }) for (const set of response.data) { await CMSCacheSetModel.upsert(set) } } async syncHomePage() { const response = await this.http.get<{ data: DirectusHomepage }>( 'items/homepage', { params: getParameters({ fields: [ 'id', 'translations.*', 'upcoming_packs.*', 'upcoming_packs.pack_image.*', 'upcoming_packs.translations.*', 'upcoming_packs.nft_templates.*', 'upcoming_packs.nft_templates.asset_file.*', 'upcoming_packs.nft_templates.translations.*', 'upcoming_packs.nft_templates.preview_audio.*', 'upcoming_packs.nft_templates.preview_image.*', 'upcoming_packs.nft_templates.preview_video.*', 'upcoming_packs.nft_templates.rarity.*', 'upcoming_packs.nft_templates.rarity.translations.*', 'featured_pack.*', 'featured_pack.pack_image.*', 'featured_pack.translations.*', 'featured_pack.nft_templates.*', 'featured_pack.nft_templates.asset_file.*', 'featured_pack.nft_templates.translations.*', 'featured_pack.nft_templates.preview_audio.*', 'featured_pack.nft_templates.preview_image.*', 'featured_pack.nft_templates.preview_video.*', 'featured_pack.nft_templates.rarity.*', 'featured_pack.nft_templates.rarity.translations.*', ], deep: { hero_pack: { _filter: { status: { _eq: DirectusStatus.Published, }, }, }, featured_packs: { _filter: { status: { _eq: DirectusStatus.Published, }, }, }, featured_nfts: { _filter: { status: { _eq: DirectusStatus.Published, }, }, }, }, }), } ) const homepage = response.data.data // If the homepage has not yet been saved, it won't have an id set. if (homepage.id) { await CMSCacheHomepageModel.upsert(homepage as DirectusHomepage) } return null } async syncApplication() { const response = await this.http.get<{ data: DirectusApplication }>( 'items/application', { params: getParameters({ fields: [ 'id', 'currency', 'countries.*', 'countries.countries_code.*', 'countries.countries_code.translations.*', ], }), } ) const application = response.data.data await CMSCacheApplicationModel.upsert(application as DirectusApplication) return null } // #region webhook handlers async processWebhook(webhook: DirectusWebhook) { switch (webhook.event) { case 'items.create': return await this.processWebhookCreate(webhook) case 'items.update': return await this.processWebhookUpdate(webhook) case 'items.delete': return await this.processWebhookDelete(webhook) default: throw new Error(`unhandled directus webhook event: ${webhook.event}`) } } private async processWebhookCreate(webhook: DirectusWebhook) { switch (webhook.collection) { case 'application': return await this.syncApplication() case 'collections': return await this.syncCollection(webhook.key) case 'countries': // nothing to do for new countries. inserts are handled with application collection updates return null case 'homepage': return await this.syncHomePage() case 'languages': return await this.syncLanguage(webhook.key) case 'nft_templates': return await this.syncCollectibleTemplate(webhook.key) case 'pack_templates': return await this.syncPackTemplate(webhook.key) case 'rarities': // nothing to do for new rariteies. inserts are handled with collectible and homepage collection updates return null case 'sets': return await this.syncSet(webhook.key) default: throw new Error( `unhandled directus webhook items.create event: ${webhook.collection}` ) } } private async processWebhookUpdate(webhook: DirectusWebhook) { switch (webhook.collection) { case 'application': return await this.syncApplication() case 'collections': return await this.syncCollection(webhook.keys[0]) case 'countries': return await this.syncCountries() case 'homepage': return await this.syncHomePage() case 'languages': return await this.syncLanguage(webhook.keys[0]) case 'nft_templates': return await this.syncCollectibleTemplate(webhook.keys[0]) case 'pack_templates': return await this.syncPackTemplate(webhook.keys[0]) case 'rarities': return await this.syncRarities() case 'sets': return await this.syncSet(webhook.keys[0]) default: throw new Error( `unhandled directus webhook items.update event: ${webhook.collection}` ) } } private async processWebhookDelete(webhook: DirectusWebhook) { switch (webhook.collection) { // TODO: handle delete operations default: throw new Error( `unhandled directus webhook items.delete event: ${webhook.collection}` ) } } // #endregion }
the_stack
import * as React from "react"; import { CSSProperties } from "react"; import { getEngineProxyService } from "../../ide/engine-proxy"; import { Icon } from "../../../emu-ide/components/Icon"; import { SideBarPanelDescriptorBase } from "../../ide/side-bar/SideBarService"; import { SideBarPanelBase, SideBarProps } from "../../ide/SideBarPanelBase"; import { separatorLine, valueItemStyle } from "../../ide/utils/content-utils"; import { CambridgeZ88MachineState } from "./CambridgeZ88Core"; const TITLE = "BLINK Information"; const flagsStyle: CSSProperties = { display: "flex", flexDirection: "column", }; const flagRowStyle: CSSProperties = { display: "flex", flexDirection: "row", }; const nameStyle: CSSProperties = { display: "flex", justifyContent: "center", fontWeight: 600, height: 16, width: 20, }; function regNameStyle(width = 32): CSSProperties { return { flexShrink: 0, flexGrow: 0, width, }; } const regValueStyle: CSSProperties = { display: "flex", justifyContent: "center", alignItems: "center", height: 16, width: 20, marginRight: 8, color: "var(--hilited-color)", }; function flagValueStyle(width = 20): CSSProperties { return { display: "flex", justifyContent: "center", alignItems: "center", height: 16, width, }; } const decStyle: CSSProperties = { marginRight: 8, color: "var(--information-color)", }; /** * Displays the content of a register status value * @param name Status name * @param value Status value */ function stateRow2(name: string, title: string, value: number) { const regValue = value.toString(16).padStart(2, "0").toUpperCase(); return ( <div style={valueItemStyle}> <div style={regNameStyle()} title={title}> {name} </div> <div style={regValueStyle}>{regValue}</div> <div style={decStyle}>{`(${value})`}</div> </div> ); } /** * Displays the content of a keyboard line * @param line Line number * @param value Line value */ function kbLine(line: number, value: number) { function kbFlag(pos: number) { return ( <div style={flagValueStyle(16)} title={`line ${line}/bit ${pos}`}> <Icon iconName={ (value >> pos) & 0x01 ? "circle-large-outline" : "circle-large-filled" } width={10} height={10} fill="--hilited-color" /> </div> ); } return ( <div style={valueItemStyle}> <div style={regNameStyle(78)} title={`Keyboard line ${line}`}> {`KB line #${line}`} </div> {kbFlag(7)} {kbFlag(6)} {kbFlag(5)} {kbFlag(4)} {kbFlag(3)} {kbFlag(2)} {kbFlag(1)} {kbFlag(0)} </div> ); } /** * Displays a flag * @param value Flag value * @param set Name when flag set * @param clr Name when flag clear */ function flag(value: number, set: string, clr: string) { return ( <div style={flagValueStyle()} title={value ? `${set} (1) ` : `${clr} (0)`}> <Icon iconName={value ? "circle-large-filled" : "circle-large-outline"} width={10} height={10} fill="--hilited-color" /> </div> ); } /** * Displays the COM flags * @param bits Flags value */ function comRow(bits: number) { const regValue = bits.toString(16).padStart(2, "0").toUpperCase(); return ( <div style={valueItemStyle}> <div style={regNameStyle()}>COM</div> <div style={regValueStyle} title={`COM: ${regValue} (${bits})`}> {regValue} </div> <div style={flagsStyle}> <div style={flagRowStyle}> <div style={nameStyle} title="SRUN: Speaker source"> SR </div> <div style={nameStyle} title="SBIT: SRUN=0: 0=low, 1=high; SRUN=1: 0=3200 Hz, 1=TxD" > SB </div> <div style={nameStyle} title="OVERP: Set to overprogram EPROMs"> OV </div> <div style={nameStyle} title="RESTIM: Set to reset the RTC, clear to continue" > RE </div> <div style={nameStyle} title="PROGRAM: Set to enable EPROM programming" > PR </div> <div style={nameStyle} title="RAMS: Binding of lower 8K of segment 0"> RA </div> <div style={nameStyle} title="VPPON: Set to turn programming voltage ON" > VP </div> <div style={nameStyle} title="LCDON: Set to turn LCD ON, clear to turn LCD OFF" > LC </div> </div> <div style={flagRowStyle}> {flag(bits & 0x80, "TxD/3200Hz", "SBIT")} {flag( bits & 0x40, bits & 0x80 ? "TxD" : "high", bits & 0x80 ? "3200Hz" : "low" )} {flag(bits & 0x20, "high", "low")} {flag(bits & 0x10, "Reset the RTC", "Continue")} {flag(bits & 0x08, "enabled", "disabled")} {flag(bits & 0x04, "Bank $20", "Bank $00")} {flag(bits & 0x02, "on", "off")} {flag(bits & 0x01, "on", "off")} </div> </div> </div> ); } /** * Displays the INT flags * @param bits Flags value */ function intRow(bits: number) { const regValue = bits.toString(16).padStart(2, "0").toUpperCase(); return ( <div style={valueItemStyle}> <div style={regNameStyle()}>INT</div> <div style={regValueStyle} title={`INT: ${regValue} (${bits})`}> {regValue} </div> <div style={flagsStyle}> <div style={flagRowStyle}> <div style={nameStyle} title="KWAIT: If set, reading the keyboard will Snooze" > KW </div> <div style={nameStyle} title="A19: If set, an active high on A19 will exit Coma" > 19 </div> <div style={nameStyle} title="FLAP: If set, flap interrupts are enabled" > FL </div> <div style={nameStyle} title="UART: If set, UART interrupts are enabled" > UA </div> <div style={nameStyle} title="BTL: If set, battery low interrupts are enabled" > BT </div> <div style={nameStyle} title="KEY: If set, keyboard interrupts (Snooze or Coma) are enabl." > KE </div> <div style={nameStyle} title="TIME: If set, RTC interrupts are enabled" > TI </div> <div style={nameStyle} title="GINT: If clear, no interrupts get out of blink" > GI </div> </div> <div style={flagRowStyle}> {flag(bits & 0x80, "on", "off")} {flag(bits & 0x40, "on", "off")} {flag(bits & 0x20, "enabled", "disabled")} {flag(bits & 0x10, "enabled", "disabled")} {flag(bits & 0x08, "enabled", "disabled")} {flag(bits & 0x04, "enabled", "disabled")} {flag(bits & 0x02, "enabled", "disabled")} {flag(bits & 0x01, "enabled", "disabled")} </div> </div> </div> ); } /** * Displays the STA flags * @param bits Flags value */ function staRow(bits: number) { const regValue = bits.toString(16).padStart(2, "0").toUpperCase(); return ( <div style={valueItemStyle}> <div style={regNameStyle()}>STA</div> <div style={regValueStyle} title={`STA: ${regValue} (${regValue})`}> {bits.toString(16).padStart(2, "0").toUpperCase()} </div> <div style={flagsStyle}> <div style={flagRowStyle}> <div style={nameStyle} title="FLAPOPEN: If set, flap open else flap closed" > FO </div> <div style={nameStyle} title="A19: If set, high level on A19 occurred during coma" > 19 </div> <div style={nameStyle} title="FLAP: If set, positive edge has occurred on FLAPOPEN" > FL </div> <div style={nameStyle} title="UART: If set, an enabled UART interrupt is active" > UA </div> <div style={nameStyle} title="BTL: If set, battery low interrupts are enabled" > BT </div> <div style={nameStyle} title="KEY: If set, a column has gone low in snooze (or coma)" > KE </div> <div style={nameStyle} title="Unused"> -- </div> <div style={nameStyle} title="TIME: If set, an enabled TIME interrupt is active" > TI </div> </div> <div style={flagRowStyle}> {flag(bits & 0x80, "open", "closed")} {flag(bits & 0x40, "high", "low")} {flag(bits & 0x20, "pos. edge", "none")} {flag(bits & 0x10, "active", "inactive")} {flag(bits & 0x08, "active", "inactive")} {flag(bits & 0x04, "gone low", "none")} {flag(bits & 0x02, "n/a", "n/a")} {flag(bits & 0x01, "active", "inactive")} </div> </div> </div> ); } /** * ULA panel state */ type State = { machineState?: CambridgeZ88MachineState; }; /** * ULA information panel */ export default class BlinkInformationPanel extends SideBarPanelBase< SideBarProps<{}>, State > { renderContent() { const state = this.state?.machineState; return ( <> {comRow(state?.COM ?? 0)} {intRow(state?.INT ?? 0)} {staRow(state?.STA ?? 0)} {separatorLine(2)} {stateRow2("SR0", "Switch Register 0", state?.SR0 ?? 0)} {stateRow2("SR1", "Switch Register 1", state?.SR1 ?? 0)} {stateRow2("SR2", "Switch Register 2", state?.SR2 ?? 0)} {stateRow2("SR3", "Switch Register 3", state?.SR3 ?? 0)} {separatorLine()} {stateRow2("PB0", "PB0 Register", state?.PB0 ?? 0)} {stateRow2("PB1", "PB1 Register", state?.PB1 ?? 0)} {stateRow2("PB2", "PB2 Register", state?.PB2 ?? 0)} {stateRow2("PB3", "PB3 Register", state?.PB3 ?? 0)} {stateRow2("SBR", "SBR Register", state?.SBF ?? 0)} {separatorLine()} {stateRow2("TIM0", "TIM0 Register (5ms )", state?.TIM0 ?? 0)} {stateRow2("TIM1", "TIM1 Register (1 second)", state?.TIM1 ?? 0)} {stateRow2("TIM2", "TIM2 Register (1 minute)", state?.TIM2 ?? 0)} {stateRow2("TIM3", "TIM3 Register (256 minutes)", state?.TIM3 ?? 0)} {stateRow2("TIM4", "TIM4 Register (64K minutes)", state?.TIM4 ?? 0)} {separatorLine()} {kbLine(0, state?.KBLine0 ?? 0)} {kbLine(1, state?.KBLine1 ?? 0)} {kbLine(2, state?.KBLine2 ?? 0)} {kbLine(3, state?.KBLine3 ?? 0)} {kbLine(4, state?.KBLine4 ?? 0)} {kbLine(5, state?.KBLine5 ?? 0)} {kbLine(6, state?.KBLine6 ?? 0)} {kbLine(7, state?.KBLine7 ?? 0)} </> ); } protected async onRunEvent(): Promise<void> { const state = await getEngineProxyService().getCachedMachineState(); this.setState({ machineState: state as CambridgeZ88MachineState }); } } /** * Descriptor for the sample side bar panel */ export class BlinkInformationPanelDescriptor extends SideBarPanelDescriptorBase { /** * Panel title */ get title(): string { return TITLE; } /** * Creates a node that represents the contents of a side bar panel */ createContentElement(): React.ReactNode { return <BlinkInformationPanel descriptor={this} />; } }
the_stack
import * as childProcess from 'child_process'; import { AudioCodec, AudioDecoder, AudioEncoder, AudioFilter, Demuxer, Format, Muxer, SubtitleCodec, SubtitleDecoder, SubtitleEncoder, VideoCodec, VideoDecoder, VideoEncoder, VideoFilter } from './_types'; /** @public */ export enum LogLevel { Quiet = 'quiet', Panic = 'panic', Fatal = 'fatal', Error = 'error', Warning = 'warning', Info = 'info', Verbose = 'verbose', Debug = 'debug', Trace = 'trace', } /** @public */ export type InputSource = string | Uint8Array | Iterable<Uint8Array> | AsyncIterable<Uint8Array>; /** @public */ export type OutputDestination = string | NodeJS.WritableStream; /** @public */ export type ConcatSource = InputSource | { file: InputSource; duration?: number; inpoint?: number; outpoint?: number; }; /** @public */ export interface FFmpegCommand { /** * Adds an input to the conversion. * @param source - * @example * ```ts * const cmd = ffmpeg(); * cmd.input('input.avi'); * cmd.input(fs.createReadStream('input2.avi')); * cmd.output(); * const process = await cmd.spawn(); * await process.complete(); * ``` */ input(source: InputSource): FFmpegInput; /** * Concatenate media files using the `concat` demuxer. This can also be used with stream copy, so * it is much faster than the `concat` filter for most applications. * @param sources - The input sources to be concatenated, they can be in different formats but * they must have the same streams, codecs, timebases, etc... * {@link https://ffmpeg.org/ffmpeg-formats.html#concat-1} * {@link https://trac.ffmpeg.org/wiki/Concatenate} * @example * ```ts * const cmd = ffmpeg(); * cmd.concat(['file:chunk1.webm', 'file:chunk2.webm']); * cmd.output('complete_video.webm'); * const process = await cmd.spawn(); * await process.complete(); * ``` */ concat(sources: ConcatSource[], options?: ConcatOptions): FFmpegInput; /** * Adds an output to the conversion, multiple destinations are supported using * the `tee` protocol. You can use mixed destinations and multiple streams. * Both NodeJS WritableStreams and AsyncGenerators are fully supported. * @param destinations - A sequence of OutputDestinations to which the output * will be written. If no destinations are specified the conversion will run, * but any output data will be ignored. * @example * ```ts * const cmd = ffmpeg(); * cmd.input('input.avi'); * cmd.output(fs.createWriteStream('dest1.mkv'), 'dest2.mkv'); * const process = await cmd.spawn(); * await process.complete(); * ``` */ output(...destinations: OutputDestination[]): FFmpegOutput; /** * Add arguments, they will be placed before any input or output arguments. * @param args - */ args(...args: string[]): this; /** * Starts the conversion, this method is asynchronous so it must be `await`'ed. * @param options - See {@link SpawnOptions}. * @example * ```ts * const cmd = ffmpeg(); * cmd.input('input.avi'); * cmd.output('output.mp4'); * const process = await cmd.spawn(); * ``` */ spawn(options?: SpawnOptions): Promise<FFmpegProcess>; /** * Returns all the arguments with which ffmpeg will be spawned. */ getArgs(): string[]; } /** @public */ export interface ConcatOptions { safe?: boolean; protocols?: string[]; useDataURI?: boolean; // TODO: add support for using an intermediate file } /** @public */ export interface SpawnOptions { /** * Enable processing of FFmpeg's logs. When set, on each log message written by ffmpeg, depending * on the log level, the corresponding log function will be called. Note that with very verbose * log levels it may have a noticeable effect on performance. */ logger?: FFmpegLogger | false; /** * Enable dumping full command line args and logs to a specified file. * {@link https://ffmpeg.org/ffmpeg-all.html#Generic-options} * @defaultValue `false` */ report?: ReportOptions | boolean; /** * **EXPERIMENTAL** * @defaultValue `false` */ parseLogs?: boolean; /** Path to the ffmpeg executable. */ ffmpegPath?: string; /** * Add custom options that will be used to spawn the process. * {@link https://nodejs.org/docs/latest-v12.x/api/child_process.html#child_process_child_process_spawn_command_args_options} */ spawnOptions?: childProcess.SpawnOptions; } /** @public */ export interface FFmpegLogger { fatal?(message: string): void; error?(message: string): void; warning?(message: string): void; info?(message: string): void; verbose?(message: string): void; debug?(message: string): void; trace?(message: string): void; } /** @public */ export interface ReportOptions { /** * A path to the file the report will be written to, relative to the current working directory of * FFmpeg. When not given, FFmpeg will write the report to `ffmpeg-YYYYMMDD-HHMMSS.log` in its * working directory. */ file?: string; /** * Change the log level used for the report file, it will not interfere with logging. When not * given FFmpeg defaults to `LogLevel.Debug`. */ level?: LogLevel; } /** @public */ export interface FFmpegOptions { /** Change the log level used for FFmpeg's logs. */ level?: LogLevel; /** * Enable piping the conversion progress, if set to `false` {@link FFmpegProcess.progress} * will silently fail. * @defaultValue `true` */ progress?: boolean; /** * Whether to overwrite the output destinations if they already exist. Required * to be `true` for streaming outputs. * @defaultValue `true` */ overwrite?: boolean; } /** @public */ export interface FFmpegInput { /** * Get information about the input, this is especially helpful when working * with streams. If the source is a stream `options.probeSize` number of bytes * will be read and passed to ffprobe; those bytes will be kept in memory * until the input is used in conversion. * * @param options - * @example * ```ts * const cmd = ffmpeg(); * cmd.output('output.mp4'); * const input = cmd.input(fs.createReadStream('input.mkv')); * const info = await input.probe(); * console.log(`Video duration: ${info.duration}, format: ${info.format}`); * const process = await cmd.spawn(); * await process.complete(); * ``` * @alpha */ probe(options?: ProbeOptions): Promise<ProbeResult>; /** * Add input arguments, they will be placed before any additional arguments. * @param args - */ args(...args: string[]): this; /** * Select the input format. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param format - */ format(format: Format | Demuxer | (string & {})): this; /** * Select the codec for all streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ codec(codec: VideoCodec | VideoDecoder | AudioCodec | AudioDecoder | SubtitleCodec | SubtitleDecoder | (string & {})): this; /** * Select the codec for video streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ videoCodec(codec: VideoCodec | VideoDecoder | (string & {})): this; /** * Select the codec for audio streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ audioCodec(codec: AudioCodec | AudioDecoder | (string & {})): this; /** * Select the codec for subtitle streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ subtitleCodec(codec: SubtitleCodec | SubtitleDecoder | (string & {})): this; /** * Limit the duration of the data read from the input. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param duration - The limit for the duration in milliseconds. */ duration(duration: number): this; /** * Seeks in the input file to `start`. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param start - The position to seek to in milliseconds. */ start(start: number): this; /** * Adds `offset` to the input timestamps. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param offset - The offset in milliseconds. MAY be negative. */ offset(offset: number): this; /** Returns all the arguments for the input. */ getArgs(): string[]; /** Whether the input is a stream. */ readonly isStream: boolean; } /** @public */ export interface FFmpegOutput { /** * Add output arguments, they will be placed before any additional arguments. * @param args - */ args(...args: string[]): this; /** * Select the output format. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param format - */ format(format: Format | Muxer | (string & {})): this; /** * Select the codec for all streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ codec(codec: VideoCodec | VideoEncoder | AudioCodec | AudioEncoder | SubtitleCodec | SubtitleEncoder | (string & {})): this; /** * Select the codec for video streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ videoCodec(codec: VideoCodec | VideoEncoder | (string & {})): this; /** * Select the codec for audio streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ audioCodec(codec: AudioCodec | AudioEncoder | (string & {})): this; /** * Select the codec for subtitle streams. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param codec - */ subtitleCodec(codec: SubtitleCodec | SubtitleEncoder | (string & {})): this; /** * **UNSTABLE** * * Applies a filter to the video streams. * @param filter - The filter to apply. * @param options - Additional configuration for the filter. */ videoFilter(filter: VideoFilter | (string & {}), options?: Record<string, any> | any[]): this; /** * **UNSTABLE** * * Applies a filter to the video streams. * @param filter - The filter to apply. * @param options - Additional configuration for the filter. */ audioFilter(filter: AudioFilter | (string & {}), options?: Record<string, any> | any[]): this; /** * Limit the duration of the data written to the output. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param duration - The limit for the duration in milliseconds. */ duration(duration: number): this; /** * Decodes but discards the input until `start` is reached. * See {@link https://ffmpeg.org/ffmpeg-all.html#Main-options} * @param start - The number of milliseconds to discard. */ start(start: number): this; /** * Maps inputs' streams to output streams. This is an advanced option. * {@link https://ffmpeg.org/ffmpeg-all.html#Advanced-options} * {@link https://ffmpeg.org/ffmpeg-all.html#Stream-specifiers-1} * {@link https://ffmpeg.org/ffmpeg-all.html#Automatic-stream-selection} * @param stream - The stream specifier. * @example * ```ts * const cmd = ffmpeg(); * cmd.input('input0.mkv'); * cmd.input('input1.avi'); * cmd.output('output0.webm') * // Takes input0's video streams and input1's audio streams. * .map('0:v', '1:a'); * cmd.output('output1.webm') * // Streams will be mapped in the order they were specified * // here output1's first stream will be input0's second stream * // and its second stream will be input1's first stream. * .map('0:1', '1:0'); * ``` */ map(...streams: string[]): this; /** * Add metadata to a stream or an output, if a value is `undefined`, `null` or `''` (empty string), * the key will be deleted. Values * {@link https://ffmpeg.org/ffmpeg.html#Main-options} * @param metadata - The metadata to add to the stream or output. * @param stream - The stream to add metadata to, if not given `metadata` * will be added to the output file. */ metadata(metadata: Record<string, string | undefined | null>, stream?: string): this; /** Returns all the arguments for the output. */ getArgs(): string[]; /** Whether the output is using streams. */ readonly isStream: boolean; } /** * A snapshot of the current progress. * @public */ export interface Progress { /** * Total number of frames rendered. * * @remarks * A positive integer, or `undefined` when the inputs have no video streams. */ frames?: number; /** * Frames per second currently processing. * * @remarks * A positive float which has up to two decimal places, or `undefined` when when the inputs have * no video streams. */ fps?: number; /** * Average bitrate of the output **in kilobits per second**. * * @remarks * A positive float which has one decimal place, or `undefined` when unavailable. */ bitrate?: number; /** * Total size of the file rendered. * * @remarks * A positive integer, or `undefined` when unavailable. */ size?: number; /** * Total length of the file rendered, in milliseconds. * * @remarks * A positive integer, or `undefined` when unavailable. */ time?: number; /** Total number of frames duplicated. */ framesDuped?: number; /** Total number of frames dropped. */ framesDropped?: number; /** * Current speed of the conversion. * * @remarks * A positive float which has up to three decimal places, or `undefined` when unavailable. */ speed?: number; } /** @public */ export interface FFmpegProcess { /** Command line arguments used to spawn the process. */ readonly args: readonly string[]; /** Path of the running ffmpeg executable. */ readonly ffmpegPath: string; /** * **UNSTABLE** * @alpha */ readonly logs: Promise<Logs> | undefined; /** * Returns an AsyncGenerator representing the real-time progress of the conversion. * @example * ```ts * const process = await cmd.spawn(); * for await (const progress of process.progress()) { * console.log('Speed:', progress.speed); * } * ``` * Using NodeJS Streams: * ```ts * const process = await cmd.spawn(); * const progressStream = Readable.from(process.progress()); * progressStream.on('data', (progress) => { * console.log('Speed:', progress.speed); * }); * ``` */ progress(): AsyncGenerator<Progress, void, void>; /** * Returns a Promise which resolves when the process exits, or rejects when the process exits with * a non-zero status code. If the `ChildProcess` emits an `error` event, the Promise will be * rejected with that error. * @example * ```ts * const process = cmd.spawn(); * await process.complete(); * console.log('Conversion complete!'); * ``` * To handle errors: * ```ts * const process = await cmd.spawn(); * try { * await process.complete(); * console.log('Conversion complete!'); * } catch (e) { * console.error('Conversion failed!', error); * } * ``` */ complete(): Promise<void>; /** * Aborts the conversion allowing FFmpeg to finish the generated files correctly. * This waits for FFmpeg to exit but doesn't guarantee that FFmpeg will succeed, * any possible errors should still be handled. */ abort(): Promise<void>; /** Returns the underlying NodeJS' ChildProcess instance. */ unwrap(): childProcess.ChildProcess; /** Suspends the conversion, returns `true` if the operation succeeds or `false` if it fails. */ pause(): boolean; /** Resumes the conversion, returns `true` if the operation succeeds or `false` if it fails. */ resume(): boolean; } /* eslint-disable camelcase */ /** @alpha */ export interface RawProbeResult { format: RawProbeFormat; streams: RawProbeStream[]; chapters: RawProbeChapter[]; error?: RawProbeError; } /** @alpha */ export interface RawProbeError { code: number; string: string; } // https://github.com/FFmpeg/FFmpeg/blob/9d8f9b2e4094ae6b07a9f23ae044b802722b3b4e/fftools/ffprobe.c#L2807 /** @alpha */ export interface RawProbeFormat { [key: string]: any; filename?: string; nb_streams: number; nb_programs: number; format_name?: string; format_long_name?: string; start_time: string; duration: string; size?: string; bit_rate?: string; probe_score: number; tags?: Record<string, string>; } // https://github.com/FFmpeg/FFmpeg/blob/9d8f9b2e4094ae6b07a9f23ae044b802722b3b4e/fftools/ffprobe.c#L2485 /** @alpha */ export type RawProbeStream = { [key: string]: any; index: number; codec_name?: string; codec_long_name?: string; profile?: string; codec_type: 'video'; codec_time_base?: string; codec_tag_string: string; codec_tag: string; id?: string; r_frame_rate?: string; avg_frame_rate?: string; time_base?: string; start_pts?: string; start_time?: string; duration_ts?: string; duration?: string; bit_rate?: string; max_bit_rate?: string; bits_per_raw_sample?: number; nb_frames?: number; nb_read_frames?: number; nb_read_packets?: number; disposition?: RawProbeDisposition; width: number; height: number; coded_width?: number; coded_height?: number; closed_captions?: number; has_b_frames: number; sample_aspect_ratio?: string; display_aspect_ratio?: string; pix_fmt?: string; level: number; color_range?: string; color_space?: string; color_primaries?: string; chroma_location?: string; field_order?: string; timecode?: string; refs?: string; tags?: Record<string, string>; } | { [key: string]: any; index: number; codec_name?: string; codec_long_name?: string; profile?: string; codec_type: 'audio'; codec_time_base?: string; codec_tag_string: string; codec_tag: string; id?: string; r_frame_rate?: string; avg_frame_rate?: string; time_base?: string; start_pts?: string; start_time?: string; duration_ts?: string; duration?: string; bit_rate?: string; max_bit_rate?: string; bits_per_raw_sample?: number; nb_frames?: number; nb_read_frames?: number; nb_read_packets?: number; disposition?: RawProbeDisposition; sample_fmt?: string; sample_rate?: string; channels?: number; channel_layout?: string; bits_per_sample?: number; tags?: Record<string, string>; } | { [key: string]: any; index: number; codec_name?: string; codec_long_name?: string; profile?: string; codec_type: 'subtitle'; codec_time_base?: string; codec_tag_string: string; codec_tag: string; id?: string; r_frame_rate?: string; avg_frame_rate?: string; time_base?: string; start_pts?: string; start_time?: string; duration_ts?: string; duration?: string; bit_rate?: string; max_bit_rate?: string; bits_per_raw_sample?: number; nb_frames?: number; nb_read_frames?: number; nb_read_packets?: number; disposition?: RawProbeDisposition; width?: number; height?: number; tags?: Record<string, string>; } | { [key: string]: any; index: number; codec_name?: string; codec_long_name?: string; profile?: string; codec_type?: string; codec_time_base?: string; codec_tag_string: string; codec_tag: string; id?: string; r_frame_rate?: string; avg_frame_rate?: string; time_base?: string; start_pts?: string; start_time?: string; duration_ts?: string; duration?: string; bit_rate?: string; max_bit_rate?: string; bits_per_raw_sample?: number; nb_frames?: number; nb_read_frames?: number; nb_read_packets?: number; disposition?: RawProbeDisposition; tags?: Record<string, string>; }; /** @alpha */ export interface RawProbeDisposition { default: number; dub: number; original: number; comment: number; lyrics: number; karaoke: number; forced: number; hearing_impaired: number; visual_impaired: number; clean_effects: number; attached_pic: number; timed_thumbnails: number; } // https://github.com/FFmpeg/FFmpeg/blob/9d8f9b2e4094ae6b07a9f23ae044b802722b3b4e/fftools/ffprobe.c#L2782 /** @alpha */ export interface RawProbeChapter { id: number; time_base: string; start: number; start_time: string; end: number; end_time: string; tags?: Record<string, string>; } /* eslint-enable camelcase */ /** * **UNSTABLE**: `ProbeResult` is intended to have a simple API but it is still very unfinished, for * the time being using `.unwrap()` is necessary to retrieve any useful information from `probe()`. * * @alpha */ export interface ProbeResult { format?: Demuxer | Format | (string & {}); formatName?: string; start: number; duration: number; bitrate?: number; score: number; tags?: Map<string, string>; unwrap(): RawProbeResult; } /** @alpha */ export interface ProbeOptions { /** * Specify the number of bytes to probe, if not given it will not be specified in the command-line * arguments. */ probeSize?: number; /** * Specify the number of milliseconds to analyze, defaults to `5000`. */ analyzeDuration?: number; /** * Path to the `ffprobe` executable. */ ffprobePath?: string; /** * Specify the input format of the media to probe. */ format?: Demuxer | Format | (string & {}); /** * Add command line arguments to ffprobe, `args` is appended **after** other * arguments, but **before** source. */ args?: string[]; /** * Add custom options that will be used to spawn the process. * {@link https://nodejs.org/docs/latest-v12.x/api/child_process.html#child_process_child_process_spawn_command_args_options} * @example * ```ts * const info = await probe('video.mkv', { * spawnOptions: { * timeout: 5000 * } * }); * ``` */ spawnOptions?: childProcess.SpawnOptions; } // For now these interfaces are internal, they should have a similar shape // as probe() function/method. /** @alpha */ export interface LoggedFormat { file: string; name: string; start: number; duration?: number; bitrate?: number; metadata: Record<string, string>; } /** @alpha */ export interface LoggedStream { metadata: Record<string, string>; } /** @alpha */ export interface LoggedChapter { start: number; end: number; metadata: Record<string, string>; } /** @alpha */ export interface LoggedInput { format: LoggedFormat; streams: LoggedStream[]; chapters: LoggedChapter[]; } /** @alpha */ export interface Logs { inputs: LoggedInput[]; }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateProjectCommand, CreateProjectCommandInput, CreateProjectCommandOutput, } from "./commands/CreateProjectCommand"; import { DeleteProjectCommand, DeleteProjectCommandInput, DeleteProjectCommandOutput, } from "./commands/DeleteProjectCommand"; import { DescribeBundleCommand, DescribeBundleCommandInput, DescribeBundleCommandOutput, } from "./commands/DescribeBundleCommand"; import { DescribeProjectCommand, DescribeProjectCommandInput, DescribeProjectCommandOutput, } from "./commands/DescribeProjectCommand"; import { ExportBundleCommand, ExportBundleCommandInput, ExportBundleCommandOutput, } from "./commands/ExportBundleCommand"; import { ExportProjectCommand, ExportProjectCommandInput, ExportProjectCommandOutput, } from "./commands/ExportProjectCommand"; import { ListBundlesCommand, ListBundlesCommandInput, ListBundlesCommandOutput } from "./commands/ListBundlesCommand"; import { ListProjectsCommand, ListProjectsCommandInput, ListProjectsCommandOutput, } from "./commands/ListProjectsCommand"; import { UpdateProjectCommand, UpdateProjectCommandInput, UpdateProjectCommandOutput, } from "./commands/UpdateProjectCommand"; import { MobileClient } from "./MobileClient"; /** * <p> * AWS Mobile Service provides mobile app and website developers with capabilities * required to configure AWS resources and bootstrap their developer desktop projects * with the necessary SDKs, constants, tools and samples to make use of those resources. * </p> */ export class Mobile extends MobileClient { /** * <p> * Creates an AWS Mobile Hub project. * </p> */ public createProject( args: CreateProjectCommandInput, options?: __HttpHandlerOptions ): Promise<CreateProjectCommandOutput>; public createProject( args: CreateProjectCommandInput, cb: (err: any, data?: CreateProjectCommandOutput) => void ): void; public createProject( args: CreateProjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateProjectCommandOutput) => void ): void; public createProject( args: CreateProjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateProjectCommandOutput) => void), cb?: (err: any, data?: CreateProjectCommandOutput) => void ): Promise<CreateProjectCommandOutput> | void { const command = new CreateProjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Delets a project in AWS Mobile Hub. * </p> */ public deleteProject( args: DeleteProjectCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProjectCommandOutput>; public deleteProject( args: DeleteProjectCommandInput, cb: (err: any, data?: DeleteProjectCommandOutput) => void ): void; public deleteProject( args: DeleteProjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProjectCommandOutput) => void ): void; public deleteProject( args: DeleteProjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProjectCommandOutput) => void), cb?: (err: any, data?: DeleteProjectCommandOutput) => void ): Promise<DeleteProjectCommandOutput> | void { const command = new DeleteProjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Get the bundle details for the requested bundle id. * </p> */ public describeBundle( args: DescribeBundleCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeBundleCommandOutput>; public describeBundle( args: DescribeBundleCommandInput, cb: (err: any, data?: DescribeBundleCommandOutput) => void ): void; public describeBundle( args: DescribeBundleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeBundleCommandOutput) => void ): void; public describeBundle( args: DescribeBundleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeBundleCommandOutput) => void), cb?: (err: any, data?: DescribeBundleCommandOutput) => void ): Promise<DescribeBundleCommandOutput> | void { const command = new DescribeBundleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Gets details about a project in AWS Mobile Hub. * </p> */ public describeProject( args: DescribeProjectCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeProjectCommandOutput>; public describeProject( args: DescribeProjectCommandInput, cb: (err: any, data?: DescribeProjectCommandOutput) => void ): void; public describeProject( args: DescribeProjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeProjectCommandOutput) => void ): void; public describeProject( args: DescribeProjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeProjectCommandOutput) => void), cb?: (err: any, data?: DescribeProjectCommandOutput) => void ): Promise<DescribeProjectCommandOutput> | void { const command = new DescribeProjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Generates customized software development kit (SDK) and or tool packages * used to integrate mobile web or mobile app clients with backend AWS resources. * </p> */ public exportBundle( args: ExportBundleCommandInput, options?: __HttpHandlerOptions ): Promise<ExportBundleCommandOutput>; public exportBundle(args: ExportBundleCommandInput, cb: (err: any, data?: ExportBundleCommandOutput) => void): void; public exportBundle( args: ExportBundleCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ExportBundleCommandOutput) => void ): void; public exportBundle( args: ExportBundleCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExportBundleCommandOutput) => void), cb?: (err: any, data?: ExportBundleCommandOutput) => void ): Promise<ExportBundleCommandOutput> | void { const command = new ExportBundleCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Exports project configuration to a snapshot which can be downloaded and shared. * Note that mobile app push credentials are encrypted in exported projects, so they * can only be shared successfully within the same AWS account. * </p> */ public exportProject( args: ExportProjectCommandInput, options?: __HttpHandlerOptions ): Promise<ExportProjectCommandOutput>; public exportProject( args: ExportProjectCommandInput, cb: (err: any, data?: ExportProjectCommandOutput) => void ): void; public exportProject( args: ExportProjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ExportProjectCommandOutput) => void ): void; public exportProject( args: ExportProjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExportProjectCommandOutput) => void), cb?: (err: any, data?: ExportProjectCommandOutput) => void ): Promise<ExportProjectCommandOutput> | void { const command = new ExportProjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * List all available bundles. * </p> */ public listBundles(args: ListBundlesCommandInput, options?: __HttpHandlerOptions): Promise<ListBundlesCommandOutput>; public listBundles(args: ListBundlesCommandInput, cb: (err: any, data?: ListBundlesCommandOutput) => void): void; public listBundles( args: ListBundlesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListBundlesCommandOutput) => void ): void; public listBundles( args: ListBundlesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListBundlesCommandOutput) => void), cb?: (err: any, data?: ListBundlesCommandOutput) => void ): Promise<ListBundlesCommandOutput> | void { const command = new ListBundlesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Lists projects in AWS Mobile Hub. * </p> */ public listProjects( args: ListProjectsCommandInput, options?: __HttpHandlerOptions ): Promise<ListProjectsCommandOutput>; public listProjects(args: ListProjectsCommandInput, cb: (err: any, data?: ListProjectsCommandOutput) => void): void; public listProjects( args: ListProjectsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListProjectsCommandOutput) => void ): void; public listProjects( args: ListProjectsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListProjectsCommandOutput) => void), cb?: (err: any, data?: ListProjectsCommandOutput) => void ): Promise<ListProjectsCommandOutput> | void { const command = new ListProjectsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p> * Update an existing project. * </p> */ public updateProject( args: UpdateProjectCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateProjectCommandOutput>; public updateProject( args: UpdateProjectCommandInput, cb: (err: any, data?: UpdateProjectCommandOutput) => void ): void; public updateProject( args: UpdateProjectCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateProjectCommandOutput) => void ): void; public updateProject( args: UpdateProjectCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateProjectCommandOutput) => void), cb?: (err: any, data?: UpdateProjectCommandOutput) => void ): Promise<UpdateProjectCommandOutput> | void { const command = new UpdateProjectCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { assert } from 'chai'; import sinon from 'sinon'; import { createTVPropGetter, ResultDb, TestVariantStatus } from '../services/resultdb'; import { LoadingStage, TestLoader } from './test_loader'; const variant1 = { testId: 'a', variant: { def: { key1: 'val1' } }, variantHash: 'key1:val1', status: TestVariantStatus.UNEXPECTED, }; const variant2 = { testId: 'a', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.UNEXPECTED, }; const variant3 = { testId: 'a', variant: { def: { key1: 'val3' } }, variantHash: 'key1:val3', status: TestVariantStatus.UNEXPECTEDLY_SKIPPED, }; const variant4 = { testId: 'b', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.FLAKY, }; const variant5 = { testId: 'matched-id', variant: { def: { key1: 'val2', key2: 'val1' } }, variantHash: 'key1:val2|key2:val1', status: TestVariantStatus.FLAKY, }; const variant6 = { testId: 'c', variant: { def: { key1: 'val2', key2: 'val2' } }, variantHash: 'key1:val2|key2:val2', status: TestVariantStatus.EXONERATED, }; const variant7 = { testId: 'd', variant: { def: { key1: 'val1' } }, variantHash: 'key1:val1', status: TestVariantStatus.EXONERATED, }; const variant8 = { testId: 'd', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXPECTED, }; const variant9 = { testId: 'e', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXPECTED, }; const variant10 = { testId: 'f', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXPECTED, }; const variant11 = { testId: 'g', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXPECTED, }; const variant12 = { testId: 'matched-id', variant: { def: { key1: 'val2' } }, variantHash: 'key1:val2', status: TestVariantStatus.EXPECTED, }; describe('TestLoader', () => { let testLoader: TestLoader; let stub = sinon.stub(); const req = { invocations: ['invocation'], pageSize: 4 }; describe('when first page contains variants', () => { beforeEach(() => { stub = sinon.stub(); stub.onCall(0).resolves({ testVariants: [variant1, variant2, variant3, variant4], nextPageToken: 'page2' }); stub.onCall(1).resolves({ testVariants: [variant5, variant6, variant7], nextPageToken: 'page3' }); stub.onCall(2).resolves({ testVariants: [variant8, variant9, variant10, variant11], nextPageToken: 'page4' }); stub.onCall(3).resolves({ testVariants: [variant12], nextPageToken: undefined }); testLoader = new TestLoader(req, { queryTestVariants: stub, } as Partial<ResultDb> as ResultDb); }); it('should preserve loading progress', async () => { assert.strictEqual(testLoader.stage, LoadingStage.LoadingUnexpected); assert.strictEqual(stub.callCount, 0); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant1, variant2, variant3, variant4]); assert.deepEqual(testLoader.expectedTestVariants, []); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 1); assert.strictEqual(testLoader.stage, LoadingStage.LoadingFlaky); assert.strictEqual(stub.callCount, 1); assert.deepEqual(stub.getCall(0).args[0], { ...req, pageToken: '' }); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, []); assert.strictEqual(testLoader.stage, LoadingStage.LoadingExpected); assert.strictEqual(stub.callCount, 2); assert.deepEqual(stub.getCall(1).args[0], { ...req, pageToken: 'page2' }); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11]); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.LoadingExpected); assert.strictEqual(stub.callCount, 3); assert.deepEqual(stub.getCall(2).args[0], { ...req, pageToken: 'page3' }); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.Done); assert.strictEqual(stub.callCount, 4); assert.deepEqual(stub.getCall(3).args[0], { ...req, pageToken: 'page4' }); // Should not load when the iterator is exhausted. await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.Done); assert.strictEqual(stub.callCount, 4); }); it('should handle concurrent loadNextPage calls correctly', async () => { assert.strictEqual(testLoader.stage, LoadingStage.LoadingUnexpected); const loadReq1 = testLoader.loadNextTestVariants(); const loadReq2 = testLoader.loadNextTestVariants(); const loadReq3 = testLoader.loadNextTestVariants(); const loadReq4 = testLoader.loadNextTestVariants(); const loadReq5 = testLoader.loadNextTestVariants(); assert.isTrue(testLoader.isLoading); assert.strictEqual(testLoader.stage, LoadingStage.LoadingUnexpected); await loadReq1; assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant1, variant2, variant3, variant4]); assert.deepEqual(testLoader.expectedTestVariants, []); // loadReq2 has not finished loading yet. assert.isTrue(testLoader.isLoading); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 1); assert.strictEqual(testLoader.stage, LoadingStage.LoadingFlaky); await loadReq2; assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, []); // loadReq3 has not finished loading yet. assert.isTrue(testLoader.isLoading); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.LoadingExpected); await loadReq3; assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11]); // loadReq4 has not finished loading yet. assert.isTrue(testLoader.isLoading); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.LoadingExpected); await loadReq4; assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); // The list is exhausted, loadReq5 should not change the loading state. assert.isFalse(testLoader.isLoading); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.Done); await loadReq5; assert.deepEqual(testLoader.unexpectedTestVariants, [variant1, variant2]); assert.deepEqual(testLoader.nonExpectedTestVariants, [ variant1, variant2, variant3, variant4, variant5, variant6, variant7, ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); assert.isFalse(testLoader.isLoading); assert.deepEqual(testLoader.unfilteredUnexpectedVariantsCount, 2); assert.deepEqual(testLoader.unfilteredUnexpectedlySkippedVariantsCount, 1); assert.deepEqual(testLoader.unfilteredFlakyVariantsCount, 2); assert.strictEqual(testLoader.stage, LoadingStage.Done); assert.strictEqual(stub.callCount, 4); assert.deepEqual(stub.getCall(0).args[0], { ...req, pageToken: '' }); assert.deepEqual(stub.getCall(1).args[0], { ...req, pageToken: 'page2' }); assert.deepEqual(stub.getCall(2).args[0], { ...req, pageToken: 'page3' }); assert.deepEqual(stub.getCall(3).args[0], { ...req, pageToken: 'page4' }); }); it('loadFirstPageOfTestVariants should work correctly', async () => { const firstLoadPromise = testLoader.loadNextTestVariants(); assert.strictEqual(firstLoadPromise, testLoader.loadFirstPageOfTestVariants()); const secondLoadPromise = testLoader.loadNextTestVariants(); assert.notStrictEqual(secondLoadPromise, testLoader.loadFirstPageOfTestVariants()); }); it('should load at least one test variant that matches the filter', async () => { testLoader.filter = (v) => v.testId === 'matched-id'; await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, []); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant5]); assert.deepEqual(testLoader.expectedTestVariants, []); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, []); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant5]); assert.deepEqual(testLoader.expectedTestVariants, [variant12]); }); it('should load at least one test variant that matches the filter', async () => { testLoader.filter = (v) => v.testId === 'matched-id'; await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, []); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant5]); assert.deepEqual(testLoader.expectedTestVariants, []); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, []); assert.deepEqual(testLoader.nonExpectedTestVariants, [variant5]); assert.deepEqual(testLoader.expectedTestVariants, [variant12]); }); it('should stop loading at the final page when no test variants matches the filter', async () => { testLoader.filter = () => false; // Detect infinite loop and abort. const oldLoadNextTestVariants = testLoader.loadNextTestVariants.bind(testLoader); let callCount = 0; testLoader.loadNextTestVariants = (...params) => { callCount++; if (callCount > 10) { throw new Error('too many load next page calls'); } return oldLoadNextTestVariants(...params); }; await testLoader.loadNextTestVariants(); assert.strictEqual(testLoader.testVariantCount, 0); assert.strictEqual(testLoader.unfilteredTestVariantCount, 12); assert.strictEqual(testLoader.isLoading, false); assert.strictEqual(testLoader.stage, LoadingStage.Done); }); }); describe('when first page contains no variants', () => { beforeEach(() => { stub = sinon.stub(); stub.onCall(0).resolves({ nextPageToken: 'page2' }); stub.onCall(1).resolves({ testVariants: [variant8], nextPageToken: 'page3' }); stub.onCall(2).resolves({ testVariants: [variant9], nextPageToken: undefined }); testLoader = new TestLoader(req, { queryTestVariants: stub, } as Partial<ResultDb> as ResultDb); }); it('should correctly handle a response with 0 variants', async () => { assert.strictEqual(stub.callCount, 0); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.unexpectedTestVariants, []); assert.deepEqual(testLoader.nonExpectedTestVariants, []); assert.deepEqual(testLoader.expectedTestVariants, [variant8]); assert.strictEqual(testLoader.stage, LoadingStage.LoadingExpected); }); }); describe('when grouping test variants', () => { beforeEach(() => { stub = sinon.stub(); stub.onCall(0).resolves({ testVariants: [variant1, variant2, variant3, variant4, variant5, variant6, variant7], nextPageToken: 'page1', }); stub.onCall(1).resolves({ testVariants: [variant8, variant9, variant10, variant11, variant12] }); testLoader = new TestLoader(req, { queryTestVariants: stub, } as Partial<ResultDb> as ResultDb); }); it('should not return empty groups', async () => { // [] means there are no groups. [[]] means there is one empty group. assert.deepEqual(testLoader.groupedNonExpectedVariants, []); }); it('should group test variants correctly', async () => { testLoader.groupers = [['status', createTVPropGetter('status')]]; await testLoader.loadNextTestVariants(); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.groupedNonExpectedVariants, [ [variant1, variant2], [variant3], [variant4, variant5], [variant6, variant7], ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); }); it('should support multiple grouping keys', async () => { testLoader.groupers = [ ['status', createTVPropGetter('status')], ['v.key1', createTVPropGetter('v.key1')], ]; await testLoader.loadNextTestVariants(); await testLoader.loadNextTestVariants(); assert.deepEqual(testLoader.groupedNonExpectedVariants, [ [variant1], [variant2], [variant3], [variant4, variant5], [variant6], [variant7], ]); assert.deepEqual(testLoader.expectedTestVariants, [variant8, variant9, variant10, variant11, variant12]); }); }); });
the_stack
import _debug from 'debug' import forEach from 'lodash/forEach' import map from 'lodash/map' import omit from 'lodash/omit' import { HangUpAction } from '../actions/CallActions' import { MediaStreamAction, MediaTrackAction, MediaTrackPayload } from '../actions/MediaActions' import { RemovePeerAction } from '../actions/PeerActions' import { AddLocalStreamPayload, AddTrackPayload, PubTrackEventAction, RemoveLocalStreamPayload, RemoveTrackPayload, StreamAction, StreamType, StreamTypeCamera } from '../actions/StreamActions' import { HANG_UP, MEDIA_STREAM, MEDIA_TRACK, PEER_REMOVE, PUB_TRACK_EVENT, STREAM_REMOVE, STREAM_TRACK_ADD, STREAM_TRACK_REMOVE } from '../constants' import { PubTrack, PubTrackEvent, TrackEventType, TrackKind } from '../SocketEvent' import { createObjectURL, MediaStream, revokeObjectURL, config } from '../window' import { insertableStreamsCodec } from '../insertable-streams' import { audioProcessor } from '../audio' import { RecordSet, setChild, removeChild } from './recordSet' const debug = _debug('peercalls') export interface StreamsState { localStreams: { [t in StreamType]?: LocalStream } // pubStreamsKeysByPeerId contains a set of keys for pubStreams indexed by // the peerId. pubStreamsKeysByPeerId: RecordSet<string, string, undefined> // pubStreams contains PubStreams indexed by streamId. pubStreams: Record<string, PubStream> // remoteStreamsKeysByClientId contains a set of keys for remoteStreams // indexed by the clientId. remoteStreamsKeysByClientId: Record<string, Record<string, undefined>> // remoteStreams contains StreamWithURL indexed by streamId. remoteStreams: Record<string, StreamWithURL> } interface PubStream { streamId: string peerId: string pubTracks: { [t in TrackKind]?: PubTrack } } const defaultState: Readonly<StreamsState> = Object.freeze({ localStreams: {}, pubStreamsKeysByPeerId: {}, pubStreams: {}, remoteStreamsKeysByClientId: {}, remoteStreams: {}, }) function safeCreateObjectURL (stream: MediaStream) { try { return createObjectURL(stream) } catch (err) { return undefined } } export interface StreamWithURL { stream: MediaStream streamId: string url?: string } export interface LocalStream extends StreamWithURL { type: StreamType mirror: boolean } export interface PubTracks { streamId: string tracksByKind: Record<TrackKind, PubTrack> } function addLocalStream ( state: StreamsState, payload: AddLocalStreamPayload, ): StreamsState { const { stream } = payload debug('streams addLocalStream') const streamWithURL: LocalStream = { stream: payload.stream, streamId: payload.stream.id, type: payload.type, url: safeCreateObjectURL(stream), mirror: payload.type === StreamTypeCamera && !!stream.getVideoTracks().find(t => !notMirroredRegexp.test(t.label)), } const existingStream = state.localStreams[payload.type] if (existingStream) { stopStream(existingStream) } stream.getAudioTracks().forEach(track => { // We expect just one audio track in stream. audioProcessor.replaceTrack(payload.stream.id, track) }) return { ...state, localStreams: { ...state.localStreams, [payload.type]: streamWithURL, }, } } function removeLocalStream ( state: StreamsState, payload: RemoveLocalStreamPayload, ): StreamsState { debug('streams removeLocalStream') const { localStreams } = state const existing = localStreams[payload.streamType] if (!existing) { return state } audioProcessor.removeTrack(existing.stream.id) stopStream(existing) return { ...state, localStreams: omit(localStreams, [payload.streamType]), } } function removeTrack ( state: Readonly<StreamsState>, payload: RemoveTrackPayload, ): StreamsState { const { streamId, peerId, track } = payload debug('streams removeTrack', streamId, track.id) if (config.network === 'mesh') { // For mesh network, we don't need any special PubTrackEvent, so just act // as if we received the PubTrackEvent so we can associate the track with // the correct peer. state = pubTrack(state, { peerId, pubClientId: peerId, trackId: { id: track.id, streamId, }, kind: track.kind as TrackKind, type: TrackEventType.Remove, }) } const remoteStream = state.remoteStreams[streamId] if (!remoteStream) { debug('streams removeTrack stream not found', streamId) return state } // NOTE: we do not remove event listeners from the track because it is // possible that it was just temporarily muted. remoteStream.stream.removeTrack(track) if (track.kind === 'audio') { audioProcessor.removeTrack(streamId) } if (remoteStream.stream.getTracks().length === 0) { stopStream(remoteStream) const remoteStreams = omit(state.remoteStreams, streamId) const remoteStreamsKeysByClientId = removeChild( state.remoteStreamsKeysByClientId, peerId, streamId, ) return { ...state, remoteStreams, remoteStreamsKeysByClientId, } } // No need to update state when the existing stream only modified and not // removed. The <video> tag should handle this automatically. return state } function addTrack ( state: Readonly<StreamsState>, payload: AddTrackPayload, ): StreamsState { const { streamId, track, peerId, receiver } = payload let remoteStream = state.remoteStreams[streamId] if (config.network === 'mesh') { // For mesh network, we don't need any special PubTrackEvent, so just act // as if we received the PubTrackEvent so we can associate the track with // the correct peer. state = pubTrack(state, { peerId, pubClientId: peerId, trackId: { id: track.id, streamId, }, kind: track.kind as TrackKind, type: TrackEventType.Add, }) } const pubStream = state.pubStreams[streamId] const originalPeerId = pubStream ? pubStream.peerId : peerId insertableStreamsCodec.decrypt({ receiver, kind: track.kind as TrackKind, streamId, peerId: originalPeerId, }) if (track.kind === 'audio') { audioProcessor.addTrack(streamId, track) } const remoteStreamsKeysByClientId = setChild( state.remoteStreamsKeysByClientId, peerId, streamId, undefined, ) if (!remoteStream) { const stream = new MediaStream() remoteStream = { stream, streamId, url: safeCreateObjectURL(stream), } remoteStream.stream.addTrack(track) return { ...state, remoteStreamsKeysByClientId, remoteStreams: { ...state.remoteStreams, [streamId]: remoteStream, }, } } remoteStream.stream.addTrack(track) // No need to update state when the existing stream only modified and not // added. The <video> tag should handle this automatically. return { ...state, remoteStreamsKeysByClientId, } } function stopStream (s: StreamWithURL) { debug('streams stopStream()') s.stream.getTracks().forEach(track => stopTrack(track)) s.url && revokeObjectURL(s.url) } function stopTrack (track: MediaStreamTrack) { track.stop() track.onmute = null track.onunmute = null } function pubTrackAdd ( state: Readonly<StreamsState>, payload: PubTrackEvent, ): StreamsState { const { kind, peerId } = payload const { streamId } = payload.trackId const pubStream = state.pubStreams[streamId] || { streamId, peerId, pubTracks: {}, } const pubStreamsKeysByPeerId = setChild( state.pubStreamsKeysByPeerId, peerId, streamId, undefined, ) return { ...state, pubStreamsKeysByPeerId, pubStreams: { ...state.pubStreams, [streamId]: { ...pubStream, pubTracks: { ...pubStream.pubTracks, [kind]: payload, }, }, }, } } function pubTrackRemove ( state: Readonly<StreamsState>, payload: PubTrackEvent, ): StreamsState { const { peerId, kind } = payload const { streamId } = payload.trackId const pubStream = state.pubStreams[streamId] if (!pubStream) { // We have some kind of invalid state. debug('streams pubTrackRemove: stream not found', streamId, kind) return state } const pubTracks = omit(pubStream.pubTracks, kind) // Check if this stream has any other tracks left. if (Object.keys(pubTracks).length === 0) { return { ...state, pubStreamsKeysByPeerId: removeChild( state.pubStreamsKeysByPeerId, peerId, streamId, ), remoteStreams: omit(state.remoteStreams, streamId), } } return { ...state, pubStreams: { ...state.pubStreams, [streamId]: { ...pubStream, pubTracks, }, }, } } function pubTrack ( state: StreamsState, payload: PubTrackEvent, ): StreamsState { // Maintain association between track metadata and peerId. insertableStreamsCodec.postPubTrackEvent(payload) switch (payload.type) { case TrackEventType.Add: state = pubTrackAdd(state, payload) break case TrackEventType.Remove: state = pubTrackRemove(state, payload) break } return state } function removePeer( state: Readonly<StreamsState>, payload: RemovePeerAction['payload'], ): StreamsState { debug('streams removePeer: %o', payload) const streamIds = map( state.remoteStreamsKeysByClientId[payload.peerId], (_, streamId) => streamId, ) streamIds.forEach(streamId => { const stream = state.remoteStreams[streamId] if (stream) { stopStream(stream) } }) const remoteStreamsKeysByClientId = omit(state.remoteStreamsKeysByClientId, payload.peerId) const remoteStreams = omit(state.remoteStreams, streamIds) return { ...state, remoteStreamsKeysByClientId, remoteStreams, } } const notMirroredRegexp = /back/i function setLocalStreamMirror( state: StreamsState, payload: MediaTrackPayload, ): StreamsState { const { track, type } = payload const existingStream = state.localStreams[type] if ( track && track.kind === 'video' && type === StreamTypeCamera && existingStream ) { return { ...state, localStreams: { ...state.localStreams, [type]: { ...existingStream, mirror: !notMirroredRegexp.test(track.label), }, }, } } if (track && track.kind === 'audio') { audioProcessor.replaceTrack(type, track) } return state } export default function streams( state: StreamsState = defaultState, action: StreamAction | MediaStreamAction | MediaTrackAction | HangUpAction | PubTrackEventAction | RemovePeerAction, ): StreamsState { switch (action.type) { case STREAM_REMOVE: return removeLocalStream(state, action.payload) case STREAM_TRACK_ADD: return addTrack(state, action.payload) case STREAM_TRACK_REMOVE: return removeTrack(state, action.payload) case PUB_TRACK_EVENT: return pubTrack(state, action.payload) case PEER_REMOVE: return removePeer(state, action.payload) case HANG_UP: forEach(state.localStreams, ls => stopStream(ls!)) forEach(state.remoteStreams, rs => stopStream(rs)) // TODO reset insertableStreamsCodec context? return defaultState case MEDIA_STREAM: if (action.status === 'resolved') { return addLocalStream(state, action.payload) } else { return state } case MEDIA_TRACK: if (action.status === 'resolved') { return setLocalStreamMirror(state, action.payload) } else { return state } default: return state } }
the_stack
import { VariableIndex } from '../components/variableSubstitution/types'; import { Cancellable } from 'api/cancellablePromise'; import { checkExecutionStatus, closeStatement, ExecuteApiResponse, executeStatement, ExecutionHandle, ExecutionHistory } from 'apps/editor/execution/api'; import { EXECUTABLE_TRANSITIONED_TOPIC, EXECUTABLE_UPDATED_TOPIC, ExecutableTransitionedEvent, ExecutableUpdatedEvent } from 'apps/editor/execution/events'; import ExecutionResult from 'apps/editor/execution/executionResult'; import ExecutionLogs, { ExecutionError, ExecutionLogsRaw } from 'apps/editor/execution/executionLogs'; import Executor from 'apps/editor/execution/executor'; import sessionManager from 'apps/editor/execution/sessionManager'; import dataCatalog from 'catalog/dataCatalog'; import { ParsedSqlStatement } from 'parse/sqlStatementsParser'; import { hueWindow } from 'types/types'; import hueAnalytics from 'utils/hueAnalytics'; import huePubSub from 'utils/huePubSub'; import UUID from 'utils/string/UUID'; export enum ExecutionStatus { available = 'available', failed = 'failed', success = 'success', expired = 'expired', running = 'running', starting = 'starting', waiting = 'waiting', ready = 'ready', streaming = 'streaming', canceled = 'canceled', canceling = 'canceling', closed = 'closed' } export interface ExecutableRaw { executeEnded: number; executeStarted: number; handle?: ExecutionHandle; history?: ExecutionHistory; id: string; logs: ExecutionLogsRaw; lost: boolean; observerState: { [key: string]: unknown }; progress: number; status: ExecutionStatus; type: string; } export interface SqlExecutableRaw extends ExecutableRaw { database: string; parsedStatement: ParsedSqlStatement; } const BATCHABLE_STATEMENT_TYPES = /ALTER|ANALYZE|WITH|REFRESH|CREATE|DELETE|DROP|GRANT|INSERT|INVALIDATE|LOAD|SET|TRUNCATE|UPDATE|UPSERT|USE/i; const SELECT_END_REGEX = /([^;]*)([;]?[^;]*)/; const ERROR_REGEX = /line ([0-9]+)(:([0-9]+))?/i; const TABLE_DDL_REGEX = /(?:CREATE|DROP)\s+(?:TABLE|VIEW)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:`([^`]+)`|([^;\s]+))\..*/i; const DB_DDL_REGEX = /(?:CREATE|DROP)\s+(?:DATABASE|SCHEMA)\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?:`([^`]+)`|([^;\s]+))/i; const substituteVariables = (statement: string, variables: VariableIndex): string => { if (!Object.keys(variables).length) { return statement; } const variablesString = Object.values(variables) .map(variable => variable.name) .join('|'); return statement.replace( RegExp('([^\\\\])?\\${(' + variablesString + ')(=[^}]*)?}', 'g'), (match, p1, p2) => { const { value, type, meta } = variables[p2]; const pad = type === 'datetime-local' && value.length === 16 ? ':00' : ''; // Chrome drops the seconds from the timestamp when it's at 0 second. const isValuePresent = //If value is string there is a need to check whether it is empty typeof value === 'string' ? value : value !== undefined && value !== null; return p1 + (isValuePresent ? value + pad : meta.placeholder); } ); }; export default class SqlExecutable { id: string = UUID(); database: string; executor: Executor; handle?: ExecutionHandle; operationId?: string; history?: ExecutionHistory; status = ExecutionStatus.ready; progress = 0; result?: ExecutionResult; logs: ExecutionLogs; cancellables: Cancellable[] = []; notifyThrottle = -1; executeStarted = 0; executeEnded = 0; previousExecutable?: SqlExecutable; nextExecutable?: SqlExecutable; observerState: { [key: string]: unknown } = {}; lost = false; edited = false; parsedStatement: ParsedSqlStatement; constructor(options: { executor: Executor; database: string; parsedStatement: ParsedSqlStatement; }) { this.logs = new ExecutionLogs(this); this.executor = options.executor; this.database = options.database; this.parsedStatement = options.parsedStatement; } getLogs(): ExecutionLogs | undefined { return this.logs; } getResult(): ExecutionResult | undefined { return this.result; } setStatus(status: ExecutionStatus): void { const oldStatus = this.status; this.status = status; if (oldStatus !== status) { huePubSub.publish<ExecutableTransitionedEvent>(EXECUTABLE_TRANSITIONED_TOPIC, { executable: this, oldStatus: oldStatus, newStatus: status }); } this.notify(); } setProgress(progress: number): void { this.progress = progress; this.notify(); } getExecutionStatus(): ExecutionStatus { return this.status; } getExecutionTime(): number { return (this.executeEnded || Date.now()) - this.executeStarted; } notify(sync?: boolean): void { window.clearTimeout(this.notifyThrottle); if (sync) { huePubSub.publish<ExecutableUpdatedEvent>(EXECUTABLE_UPDATED_TOPIC, this); } else { this.notifyThrottle = window.setTimeout(() => { huePubSub.publish<ExecutableUpdatedEvent>(EXECUTABLE_UPDATED_TOPIC, this); }, 1); } } isReady(): boolean { return ( this.status === ExecutionStatus.ready || this.status === ExecutionStatus.closed || this.status === ExecutionStatus.canceled ); } isRunning(): boolean { return this.status === ExecutionStatus.running || this.status === ExecutionStatus.streaming; } isSuccess(): boolean { return this.status === ExecutionStatus.success || this.status === ExecutionStatus.available; } isFailed(): boolean { return this.status === ExecutionStatus.failed; } isPartOfRunningExecution(): boolean { return ( !this.isReady() || (!!this.previousExecutable && this.previousExecutable.isPartOfRunningExecution()) ); } async cancelBatchChain(wait?: boolean): Promise<void> { if (this.previousExecutable) { this.previousExecutable.nextExecutable = undefined; const cancelPromise = this.previousExecutable.cancelBatchChain(wait); if (wait) { await cancelPromise; } this.previousExecutable = undefined; } if (!this.isReady()) { if (wait) { await this.cancel(); } else { this.cancel(); } } if (this.nextExecutable) { this.nextExecutable.previousExecutable = undefined; const cancelPromise = this.nextExecutable.cancelBatchChain(wait); if (wait) { await cancelPromise; } this.nextExecutable = undefined; } this.notify(); } async execute(): Promise<void> { if (!this.isReady()) { return; } this.edited = false; this.executeStarted = Date.now(); this.setStatus(ExecutionStatus.running); this.setProgress(0); this.notify(true); try { hueAnalytics.log( 'notebook', 'execute/' + (this.executor.connector() ? this.executor.connector().dialect : '') ); try { const response = await this.internalExecute(); this.handle = response.handle; this.history = response.history; if (response.history) { this.operationId = response.history.uuid; } if ( response.handle.session_id && response.handle.session_type && response.handle.session_guid ) { sessionManager.updateSession({ type: response.handle.session_type, id: response.handle.session_id, session_id: response.handle.session_guid, properties: [] }); } } catch (err) { if (err && (err.message || typeof err === 'string')) { const adapted = this.adaptError((err.message && err.message) || err); this.logs.errors.push(adapted); this.logs.notify(); } throw err; } if (this.handle && this.handle.has_result_set && this.handle.sync) { this.result = new ExecutionResult(this); if (this.handle.result) { this.result.handleResultResponse(this.handle.result); } this.result.fetchRows(); } if (this.executor.isSqlAnalyzerEnabled && this.history) { huePubSub.publish('editor.upload.query', this.history.id); } this.checkStatus(); this.logs.fetchLogs(); } catch (err) { console.warn(err); this.setStatus(ExecutionStatus.failed); } } async checkStatus(statusCheckCount?: number): Promise<void> { if (!this.handle) { return; } let checkStatusTimeout = -1; let actualCheckCount = statusCheckCount || 0; if (!statusCheckCount) { this.addCancellable({ cancel: () => { window.clearTimeout(checkStatusTimeout); } }); } actualCheckCount++; const queryStatus = await checkExecutionStatus({ executable: this }); if (this.handle && typeof queryStatus.has_result_set !== 'undefined') { this.handle.has_result_set = queryStatus.has_result_set; } switch (queryStatus.status) { case ExecutionStatus.success: this.executeEnded = Date.now(); this.setStatus(queryStatus.status); this.setProgress(99); // TODO: why 99 here (from old code)? break; case ExecutionStatus.available: this.executeEnded = Date.now(); this.setStatus(queryStatus.status); this.setProgress(100); if (!this.result && this.handle && this.handle.has_result_set) { this.result = new ExecutionResult(this); this.result.fetchRows(); } if (this.nextExecutable) { if (!this.nextExecutable.isReady()) { await this.nextExecutable.reset(); } this.nextExecutable.execute(); } break; case ExecutionStatus.canceled: case ExecutionStatus.expired: this.executeEnded = Date.now(); this.setStatus(queryStatus.status); break; case ExecutionStatus.streaming: if (!queryStatus.result) { return; } if ((<hueWindow>window).WEB_SOCKETS_ENABLED) { huePubSub.publish('editor.ws.query.fetch_result', queryStatus.result); } else { if (!this.result) { this.result = new ExecutionResult(this, true); } this.result.handleResultResponse(queryStatus.result); } case ExecutionStatus.running: case ExecutionStatus.starting: case ExecutionStatus.waiting: this.setStatus(queryStatus.status); checkStatusTimeout = window.setTimeout( () => { this.checkStatus(statusCheckCount); }, actualCheckCount > 45 ? 5000 : 1000 ); break; case ExecutionStatus.failed: this.executeEnded = Date.now(); this.setStatus(queryStatus.status); if (queryStatus.message) { huePubSub.publish('hue.error', queryStatus.message); } break; default: this.executeEnded = Date.now(); this.setStatus(ExecutionStatus.failed); console.warn('Got unknown status ' + queryStatus.status); } } addCancellable(cancellable: Cancellable): void { this.cancellables.push(cancellable); } async internalExecute(): Promise<ExecuteApiResponse> { if (this.parsedStatement && /CREATE|DROP/i.test(this.parsedStatement.firstToken)) { let match = this.parsedStatement.statement.match(TABLE_DDL_REGEX); const path: Array<string> = []; if (match) { path.push(match[1] || match[2]); // group 1 backticked db name, group 2 regular db name } else { match = this.parsedStatement.statement.match(DB_DDL_REGEX); if (match) { path.push(match[1] || match[2]); // group 1 backticked db name, group 2 regular db name } else if (this.database) { path.push(this.database); } } if (path.length) { window.setTimeout(() => { dataCatalog .getEntry({ namespace: this.executor.namespace(), compute: this.executor.compute(), connector: this.executor.connector(), path: path }) .then(entry => { entry.clearCache({ cascade: true, silenceErrors: true }); }) .catch(); }, 5000); } } return await executeStatement({ executable: this, silenceErrors: true }); } adaptError(message: string): ExecutionError { const match = ERROR_REGEX.exec(message); if (match) { const row = parseInt(match[1]); const column = (match[3] && parseInt(match[3])) || 0; return { message, column: column || 0, row }; } return { message, column: 0, row: this.parsedStatement.location.first_line }; } canExecuteInBatch(): boolean { return this.parsedStatement && BATCHABLE_STATEMENT_TYPES.test(this.parsedStatement.firstToken); } getKey(): string { return this.database + '_' + this.parsedStatement.statement; } getRawStatement(): string { return this.parsedStatement.statement; } getStatement(): string { let statement = this.getRawStatement(); if ( this.parsedStatement.firstToken && this.parsedStatement.firstToken.toLowerCase() === 'select' && this.executor.defaultLimit && !isNaN(this.executor.defaultLimit()) && this.executor.defaultLimit() > 0 && /\sfrom\s/i.test(statement) && !/\slimit\s[0-9]/i.test(statement) ) { const endMatch = statement.match(SELECT_END_REGEX); if (endMatch) { statement = endMatch[1] + ' LIMIT ' + this.executor.defaultLimit(); if (endMatch[2]) { statement += endMatch[2]; } } } if (this.executor.variables) { statement = substituteVariables(statement, this.executor.variables); } return statement; } toJson(): string { return JSON.stringify({ id: this.id, parsedStatement: this.parsedStatement, statement: this.getStatement(), database: this.database }); } async cancel(): Promise<void> { if ( this.cancellables.length && (this.status === ExecutionStatus.running || this.status === ExecutionStatus.streaming) ) { hueAnalytics.log( 'notebook', 'cancel/' + (this.executor.connector() ? this.executor.connector().dialect : '') ); this.setStatus(ExecutionStatus.canceling); while (this.cancellables.length) { const cancellable = this.cancellables.pop(); if (cancellable) { await cancellable.cancel(); } } this.setStatus(ExecutionStatus.canceled); } } async reset(): Promise<void> { this.result = undefined; this.logs.reset(); if (!this.isReady()) { try { await this.close(); } catch (err) {} } this.handle = undefined; this.setProgress(0); this.setStatus(ExecutionStatus.ready); } static fromJs(executor: Executor, executableRaw: SqlExecutableRaw): SqlExecutable { const executable = new SqlExecutable({ database: executableRaw.database, executor: executor, parsedStatement: executableRaw.parsedStatement }); executable.executeEnded = executableRaw.executeEnded; executable.executeStarted = executableRaw.executeStarted; executable.handle = executableRaw.handle; executable.history = executableRaw.history; executable.id = executableRaw.id; if (executableRaw.logs.errors) { executable.logs.errors = executableRaw.logs.errors.map(error => executable.adaptError(error)); } executable.logs.jobs = executableRaw.logs.jobs; executable.lost = executableRaw.lost; executable.observerState = executableRaw.observerState || {}; executable.operationId = executableRaw.history && executableRaw.history.uuid; executable.progress = executableRaw.progress; executable.status = executableRaw.status; return executable; } toJs(): SqlExecutableRaw { const state = Object.assign({}, this.observerState); delete state.aceAnchor; return { executeEnded: this.executeEnded, executeStarted: this.executeStarted, handle: this.handle, history: this.history, id: this.id, logs: this.logs.toJs(), lost: this.lost, observerState: state, progress: this.progress, status: this.status, type: 'sqlExecutable', database: this.database, parsedStatement: this.parsedStatement }; } async close(): Promise<void> { while (this.cancellables.length) { const nextCancellable = this.cancellables.pop(); if (nextCancellable) { try { await nextCancellable.cancel(); } catch (err) { console.warn(err); } } } try { await closeStatement({ executable: this, silenceErrors: true }); } catch (err) { console.warn('Failed closing statement'); } this.setStatus(ExecutionStatus.closed); } async toContext(id?: string): Promise<ExecutableContext> { const session = await sessionManager.getSession({ type: this.executor.connector().id }); if (this.executor.snippet) { return { operationId: this.operationId, snippet: this.executor.snippet.toContextJson(this.getStatement()), notebook: JSON.stringify(await this.executor.snippet.parentNotebook.toJs()) }; } const snippet = { type: this.executor.connector().id, result: { handle: this.handle }, connector: this.executor.connector(), executor: this.executor.toJs(), defaultLimit: (this.executor.defaultLimit && this.executor.defaultLimit()) || null, status: this.status, id: id || UUID(), statement_raw: this.getRawStatement(), statement: this.getStatement(), lastExecuted: this.executeStarted, variables: [], compute: this.executor.compute(), namespace: this.executor.namespace(), database: this.database, properties: { settings: [] } }; const notebook = { type: `query-${this.executor.connector().id}`, snippets: [snippet], uuid: UUID(), name: '', isSaved: false, sessions: [session], editorWsChannel: (<hueWindow>window).WS_CHANNEL }; return { operationId: this.operationId, snippet: JSON.stringify(snippet), notebook: JSON.stringify(notebook) }; } } export interface ExecutableContext { operationId?: string; snippet: string; notebook: string; }
the_stack
import { Debugger } from 'debug'; import rawDebug from '../../debug'; import { LoopResolver, ArrayMapResolver, ConditionalResolver, EchoResolver, NoopResolver, PauseResolver, RepeaterResolver, StopResolver, SubFlowResolver, ThrowErrorResolver, WaitResolver, } from '../../resolver-library'; import { AnyValue, FlowedLogEntry, FlowStateEnum, FlowTransitionEnum, TaskResolverExecutor, TaskResolverMap, ValueMap } from '../../types'; import { FlowRunStatus, SerializedFlowRunStatus } from '../flow-run-status'; import { Task } from '../task'; import { TaskProcess } from '../task-process'; import { IFlow } from './iflow'; import { FlowManager } from '../flow-manager'; import { FlowSpec } from '../specs'; export abstract class FlowState implements IFlow { /** * Built-in resolver library. * @type {TaskResolverMap} */ protected static builtInResolvers: TaskResolverMap = { 'flowed::Noop': NoopResolver, 'flowed::Echo': EchoResolver, 'flowed::ThrowError': ThrowErrorResolver, 'flowed::Conditional': ConditionalResolver, 'flowed::Wait': WaitResolver, 'flowed::SubFlow': SubFlowResolver, 'flowed::Repeater': RepeaterResolver, 'flowed::Loop': LoopResolver, 'flowed::ArrayMap': ArrayMapResolver, 'flowed::Stop': StopResolver, 'flowed::Pause': PauseResolver, }; protected runStatus: FlowRunStatus; public constructor(runStatus: FlowRunStatus) { this.runStatus = runStatus; } public start( params: ValueMap, expectedResults: string[], resolvers: TaskResolverMap, context: ValueMap, options: ValueMap = {}, // eslint-disable-line @typescript-eslint/no-unused-vars ): Promise<ValueMap> { throw this.createTransitionError(FlowTransitionEnum.Start); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public finished(error: Error | boolean = false): void { throw this.createTransitionError(FlowTransitionEnum.Finished); } public pause(): Promise<ValueMap> { throw this.createTransitionError(FlowTransitionEnum.Pause); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public paused(error: Error | boolean = false): void { throw this.createTransitionError(FlowTransitionEnum.Paused); } public resume(): Promise<ValueMap> { throw this.createTransitionError(FlowTransitionEnum.Resume); } public stop(): Promise<ValueMap> { throw this.createTransitionError(FlowTransitionEnum.Stop); } // eslint-disable-next-line @typescript-eslint/no-unused-vars public stopped(error: Error | boolean = false): void { throw this.createTransitionError(FlowTransitionEnum.Stopped); } public reset(): void { throw this.createTransitionError(FlowTransitionEnum.Reset); } public abstract getStateCode(): FlowStateEnum; public execFinishResolve(): void { this.runStatus.finishResolve(this.runStatus.results); } public execFinishReject(error: Error): void { this.runStatus.finishReject(error); } public isRunning(): boolean { return this.runStatus.processManager.runningCount() > 0; } public setExpectedResults(expectedResults: string[]): void { // Check expected results that cannot be fulfilled const missingExpected = expectedResults.filter(r => !this.runStatus.taskProvisions.includes(r)); if (missingExpected.length > 0) { const msg = `The results [${missingExpected.join(', ')}] are not provided by any task`; if (this.runStatus.options.throwErrorOnUnsolvableResult) { throw new Error(msg); } else { this.log({ m: msg, l: 'w' }); } } this.runStatus.expectedResults = [...expectedResults]; } public getResults(): ValueMap { return this.runStatus.results; } public setResolvers(resolvers: TaskResolverMap): void { this.runStatus.resolvers = resolvers; } public setContext(context: ValueMap): void { this.runStatus.context = { $flowed: { getResolverByName: this.getResolverByName.bind(this), getResolvers: this.getResolvers.bind(this), processManager: this.runStatus.processManager, flow: this.runStatus.flow, }, ...context, }; } public setRunOptions(options: ValueMap): void { const defaultRunOptions = { debugKey: 'flow', instanceId: null, // @todo check if it would be better to move this field into logFields logFields: {}, }; this.runStatus.runOptions = Object.assign(defaultRunOptions, options); } public supplyParameters(params: ValueMap): void { for (const [paramCode, paramValue] of Object.entries(params)) { this.runStatus.state.supplyResult(paramCode, paramValue); } } public getSpec(): FlowSpec { return this.runStatus.spec; } public createFinishPromise(): Promise<ValueMap> { this.runStatus.finishPromise = new Promise<ValueMap>((resolve, reject) => { this.runStatus.finishResolve = resolve; this.runStatus.finishReject = reject; }); return this.runStatus.finishPromise; } public getResolverForTask(task: Task): TaskResolverExecutor { const name = task.getResolverName(); const resolver = this.getResolverByName(name); if (resolver === null) { throw new Error( `Task resolver '${name}' for task '${task.code}' has no definition. Defined custom resolvers are: [${Object.keys( this.runStatus.resolvers, ).join(', ')}].`, ); } return resolver; } public getResolverByName(name: string): TaskResolverExecutor | null { // Lookup for custom resolvers const resolvers = this.runStatus.resolvers; const hasCustomResolver = typeof resolvers[name] !== 'undefined'; if (hasCustomResolver) { return resolvers[name]; } // Lookup for plugin resolvers const hasPluginResolver = typeof FlowManager.plugins.resolvers[name] !== 'undefined'; if (hasPluginResolver) { return FlowManager.plugins.resolvers[name]; } // Lookup for built-in resolvers const hasBuiltInResolver = typeof FlowState.builtInResolvers[name] !== 'undefined'; if (hasBuiltInResolver) { return FlowState.builtInResolvers[name]; } return null; } public getResolvers(): TaskResolverMap { const customResolvers = this.runStatus.resolvers; const pluginResolvers = FlowManager.plugins.resolvers; const builtInResolver = FlowState.builtInResolvers; return { ...builtInResolver, ...pluginResolvers, ...customResolvers, }; } public supplyResult(resultName: string, result: AnyValue): void { // Checks if the task result is required by other tasks. // If it is not, it is likely a flow output value. const suppliesSomeTask = typeof this.runStatus.tasksByReq[resultName] !== 'undefined'; if (suppliesSomeTask) { const suppliedTasks = this.runStatus.tasksByReq[resultName]; const suppliedTaskCodes = Object.keys(suppliedTasks); for (const taskCode of suppliedTaskCodes) { const suppliedTask = suppliedTasks[taskCode]; suppliedTask.supplyReq(resultName, result); // @todo Possible optimization: supply all results first, then check ready tasks // @todo This 'if' could actually be a 'while', in case more than one instance of the same task get ready if (suppliedTask.isReadyToRun()) { this.runStatus.tasksReady.push(suppliedTask); } } } // If the result is required as flow output, it is provided const isExpectedResult = this.runStatus.expectedResults.indexOf(resultName) > -1; if (isExpectedResult) { this.runStatus.results[resultName] = result; } } public getStateInstance(state: FlowStateEnum): FlowState { return this.runStatus.states[state]; } public startReadyTasks(): void { const readyTasks = this.runStatus.tasksReady; this.runStatus.tasksReady = []; for (const task of readyTasks) { const taskResolver = this.runStatus.state.getResolverForTask(task); const process = this.runStatus.processManager.createProcess( task, taskResolver, this.runStatus.context, !!this.runStatus.options.resolverAutomapParams, !!this.runStatus.options.resolverAutomapResults, this.runStatus.id, this.debug as Debugger, this.log.bind(this), ); const errorHandler = (error: Error): void => { this.processFinished(process, error, true); }; process .run() .then(() => { this.processFinished(process, false, true); }, errorHandler) .catch(errorHandler); this.log({ n: this.runStatus.id, m: `Task '${task.code}(${task.getResolverName()})' started, params: %O`, mp: process.getParams(), e: 'TS', pid: process.pid, task: { code: task.code, type: task.getResolverName() }, }); } } public setState(newState: FlowStateEnum): void { const prevState = this.runStatus.state.getStateCode(); this.runStatus.state = this.getStateInstance(newState); this.log({ n: this.runStatus.id, m: `Changed flow state from '${prevState}' to '${newState}'`, l: 'd', e: 'FC' }); } public getSerializableState(): SerializedFlowRunStatus { throw this.createMethodError('getSerializableState'); } protected processFinished(process: TaskProcess, error: Error | boolean, stopFlowExecutionOnError: boolean): void { this.runStatus.processManager.removeProcess(process); const task = process.task; const taskCode = task.code; const taskSpec = task.spec; const taskProvisions = taskSpec.provides ?? []; const taskResults = task.getResults(); const hasDefaultResult = Object.prototype.hasOwnProperty.call(taskSpec, 'defaultResult'); if (error) { this.log({ n: this.runStatus.id, m: `Error in task '${taskCode}', results: %O`, mp: taskResults, l: 'e', e: 'TF', pid: process.pid, task: { code: task.code, type: task.getResolverName() }, }); } else { this.log({ n: this.runStatus.id, m: `Finished task '${taskCode}', results: %O`, mp: taskResults, e: 'TF', pid: process.pid, task: { code: task.code, type: task.getResolverName() }, }); } for (const resultName of taskProvisions) { if (Object.prototype.hasOwnProperty.call(taskResults, resultName)) { this.runStatus.state.supplyResult(resultName, taskResults[resultName]); } else if (hasDefaultResult) { // @todo add defaultResult to repeater task this.runStatus.state.supplyResult(resultName, taskSpec.defaultResult); } else { this.log({ n: this.runStatus.id, m: `Expected value '${resultName}' was not provided by task '${taskCode}' with resolver '${task.getResolverName()}'. Consider using the task field 'defaultResult' to provide values by default.`, l: 'w', }); } } this.runStatus.state.postProcessFinished(error, stopFlowExecutionOnError); } // eslint-disable-next-line @typescript-eslint/no-unused-vars protected postProcessFinished(error: Error | boolean, stopFlowExecutionOnError: boolean): void {} protected createTransitionError(transition: string): Error { return new Error(`Cannot execute transition ${transition} in current state ${this.getStateCode()}.`); } protected createMethodError(method: string): Error { return new Error(`Cannot execute method ${method} in current state ${this.getStateCode()}.`); } public debug(formatter: string, ...args: AnyValue[]): void { const scope = this && this.runStatus && typeof this.runStatus.runOptions.debugKey === 'string' ? this.runStatus.runOptions.debugKey : 'init'; rawDebug(scope)(formatter, ...args); } public static formatDebugMessage({ n, m, l, e }: { n?: number; m: string; mp?: ValueMap; l?: string; e?: string }): string { const levelIcon = l === 'w' ? '⚠️ ' : ''; const eventIcons = { FS: '▶ ', FF: '✔ ', TS: ' ‣ ', TF: ' ✓ ', FC: ' ⓘ ', FT: '◼ ', FP: '⏸ ' }; let eventIcon = (eventIcons as any)[e || ''] ?? ''; // eslint-disable-line @typescript-eslint/no-explicit-any if (e === 'TF' && ['e', 'f'].includes(l || '')) { eventIcon = ' ✗'; } else if (e === 'FF' && ['e', 'f'].includes(l || '')) { eventIcon = '✘'; } const icon = levelIcon + eventIcon; return `[${n}] ${icon}${m}`; } public static createLogEntry( { n, m, mp, l, e, pid, task }: { n?: number; m: string; mp?: ValueMap; l?: string; e?: string; pid?: number; task?: AnyValue }, flowStatus: FlowRunStatus | undefined, ): FlowedLogEntry { const formatLevel = (level: string | undefined) => { switch (level) { case 'f': return 'fatal'; case 'e': return 'error'; case 'w': return 'warning'; case 'i': return 'info'; case 'd': return 'debug'; case 't': return 'trace'; default: return 'info'; } }; const formatEvent = (event: string | undefined) => { switch (event) { case 'TS': return 'Task.Started'; case 'TF': return 'Task.Finished'; case 'FC': return 'Flow.StateChanged'; case 'FS': return 'Flow.Started'; case 'FF': return 'Flow.Finished'; case 'FT': return 'Flow.Stopped'; case 'FP': return 'Flow.Paused'; default: return 'General'; } }; const formatMsg = (templateMsg: string, param: ValueMap | undefined) => { if (param) { const paramStr = JSON.stringify(param); return templateMsg.replace('%O', paramStr.length > 100 ? paramStr.slice(0, 97) + '...' : paramStr); } return templateMsg; }; let auditLogEntry: FlowedLogEntry = { level: formatLevel(l), eventType: formatEvent(e), message: formatMsg(m, mp), timestamp: new Date(), extra: { pid, task, debugId: n, values: JSON.stringify(mp), }, }; if (flowStatus) { auditLogEntry.objectId = flowStatus.runOptions.instanceId; auditLogEntry = Object.assign(flowStatus.runOptions.logFields, auditLogEntry); } return auditLogEntry; } public log({ n, m, mp, l, e, pid, task }: { n?: number; m: string; mp?: ValueMap; l?: string; e?: string; pid?: number; task?: AnyValue }): void { this.debug(FlowState.formatDebugMessage({ n, m, mp, l, e }), [mp]); FlowManager.log(FlowState.createLogEntry({ n, m, mp, l, e, pid, task }, this.runStatus)); } }
the_stack
export type LuaVersion = '5.1' | '5.2' | '5.3' | 'LuaJIT' | 'PICO-8' | 'PICO-8-0.2.1' | 'PICO-8-0.2.2'; export interface Options { /** Explicitly tell the parser when the input ends. */ wait: boolean; /** Store comments as an array in the chunk object. */ comments: boolean; /** Track identifier scopes. */ scope: boolean; /** Store location information on each syntax node. */ locations: boolean; /** Store the start and end character locations on each syntax node. */ ranges: boolean; /** * A callback which will be invoked when a syntax node has been completed. * The node which has been created will be passed as the only parameter. */ onCreateNode: (node: ast.Node) => void; /** A callback which will be invoked when a new scope is created. */ onCreateScope: () => void; /** A callback which will be invoked when the current scope is destroyed. */ onDestroyScope: () => void; /** * A callback which will be invoked when a local variable is declared. * The identifier will be passed as the only parameter. */ onLocalDeclaration: (identifier: ast.Identifier) => void; /** * The version of Lua the parser will target; supported values are '5.1', '5.2', '5.3', * 'LuaJIT', 'PICO-8', 'PICO-8-0.2.1' and 'PICO-8-0.2.2'. */ luaVersion: LuaVersion; /** * Whether to allow code points ≥ U+0080 in identifiers, like LuaJIT does. * See 'Note on character encodings' below if you wish to use this option. * Note: setting luaVersion: 'LuaJIT' currently does not enable this option; this may change in the future. */ extendedIdentifiers: false; /** * Defines the relation between code points ≥ U+0080 appearing in parser input and raw bytes in source code, * and how Lua escape sequences in JavaScript strings should be interpreted. * See the Encoding modes section https://github.com/fstirlitz/luaparse#encoding-modes for more information. */ encodingMode: "pseudo-latin1" | "x-user-defined" | "none"; /** * This option should be reserved for testing but may be use if needed; * it overrides the `strictP8FileFormat` feature, making it possible to parse * snippets lacking the proper header and sections */ ignoreStrictP8FileFormat: boolean; } /** * The original luaparse describes a was to customize the building of the AST * (see https://fstirlitz.github.io/luaparse/#custom-ast) * * For that, this exposes the suite of functions that are called exactly before * finalizing a node. * * Reminder again that the `option.onCreateNode` callback should be preferred * (it is called after and with for parameter the result of the appropriate `ast.` * function, augmented by any location tracking). */ export namespace ast { interface Base<TType extends string> { type: TType; loc?: { start: { line: number; column: number; }; end: { line: number; column: number; }; }; range?: [number, number]; } type UnaryOperator = 'not' | '-' | '~' | '#' | '@' | '$' | '%'; type BinaryOperator = '+' | '-' | '*' | '%' | '^' | '/' | '//' | '&' | '|' | '~' | '<<' | '>>' | '..' | '>>>' | '<<>' | '>><' | '^^' | '\\'; type ComparisonOperator = '~=' | '==' | '<' | '<=' | '>' | '>=' | '!='; type IfStatementClauses = [IfClause, ...Array<ElseifClause | ElseClause>]; //#region node types definitions interface LabelStatement extends Base<"LabelStatement"> { label: Identifier; } interface BreakStatement extends Base<"BreakStatement"> { } interface GotoStatement extends Base<"GotoStatement"> { label: Identifier; } interface ReturnStatement extends Base<"ReturnStatement"> { arguments: Expression[]; } interface IfStatement extends Base<"IfStatement"> { clauses: IfStatementClauses; } interface IfClause extends Base<"IfClause"> { condition: Expression; body: Statement[]; } interface ElseifClause extends Base<"ElseifClause"> { condition: Expression; body: Statement[]; } interface ElseClause extends Base<"ElseClause"> { body: Statement[]; } interface WhileStatement extends Base<"WhileStatement"> { condition: Expression; body: Statement[]; } interface DoStatement extends Base<"DoStatement"> { body: Statement[]; } interface RepeatStatement extends Base<"RepeatStatement"> { condition: Expression; body: Statement[]; } interface LocalStatement extends Base<"LocalStatement"> { variables: Identifier[]; init: Expression[]; } interface AssignmentStatement extends Base<"AssignmentStatement"> { variables: Array<IndexExpression | MemberExpression | Identifier>; init: Expression[]; } interface AssignmentOperatorStatement extends Base<"AssignmentOperatorStatement"> { operator: BinaryOperator; variables: Array<IndexExpression | MemberExpression | Identifier>; init: Expression[]; } interface CallStatement extends Base<"CallStatement"> { expression: CallExpression | StringCallExpression | TableCallExpression; } interface FunctionDeclaration extends Base<"FunctionDeclaration"> { identifier: Identifier | MemberExpression | null; isLocal: boolean; parameters: Array<Identifier | VarargLiteral>; body: Statement[]; } interface ForNumericStatement extends Base<"ForNumericStatement"> { variable: Identifier; start: Expression; end: Expression; step: Expression | null; body: Statement[]; } interface ForGenericStatement extends Base<"ForGenericStatement"> { variables: Identifier[]; iterators: Expression[]; body: Statement[]; } interface Chunk extends Base<"Chunk"> { body: Statement[]; comments?: string[]; globals?: Identifier[]; } interface Identifier extends Base<"Identifier"> { name: string; isLocal?: boolean; } interface StringLiteral extends Base<"StringLiteral"> { value: string; raw: string; rawInterrupted?: string; } interface NumericLiteral extends Base<"NumericLiteral"> { value: number; raw: string; } interface BooleanLiteral extends Base<"BooleanLiteral"> { value: boolean; raw: string; } interface NilLiteral extends Base<"NilLiteral"> { value: null; raw: string; } interface VarargLiteral extends Base<"VarargLiteral"> { value: string; raw: string; } interface TableKey extends Base<"TableKey"> { key: Expression; value: Expression; } interface TableKeyString extends Base<"TableKeyString"> { key: Identifier; value: Expression; } interface TableValue extends Base<"TableValue"> { value: Expression; } interface TableConstructorExpression extends Base<"TableConstructorExpression"> { fields: Array<TableKey | TableKeyString | TableValue>; } interface UnaryExpression extends Base<"UnaryExpression"> { operator: UnaryOperator; argument: Expression; } interface BinaryExpression extends Base<"BinaryExpression"> { operator: BinaryOperator | ComparisonOperator; left: Expression; right: Expression; } interface LogicalExpression extends Base<"LogicalExpression"> { operator: 'or' | 'and'; left: Expression; right: Expression; } interface MemberExpression extends Base<"MemberExpression"> { indexer: '.' | ':'; identifier: Identifier; base: Expression; } interface IndexExpression extends Base<"IndexExpression"> { base: Expression; index: Expression; } interface CallExpression extends Base<"CallExpression"> { base: Expression; arguments: Expression[]; } interface TableCallExpression extends Base<"TableCallExpression"> { base: Expression; argument: Expression; } interface StringCallExpression extends Base<"StringCallExpression"> { base: Expression; argument: Expression; } interface Comment extends Base<"Comment"> { value: string; raw: string; rawInterrupted?: string; } //#endregion //#region node type aliases type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NilLiteral | VarargLiteral; type Expression = FunctionDeclaration | Identifier | Literal | TableConstructorExpression | BinaryExpression | LogicalExpression | UnaryExpression | MemberExpression | IndexExpression | CallExpression | TableCallExpression | StringCallExpression; type Statement = LabelStatement | BreakStatement | GotoStatement | ReturnStatement | IfStatement | WhileStatement | DoStatement | RepeatStatement | LocalStatement | AssignmentStatement | AssignmentOperatorStatement | CallStatement | FunctionDeclaration | ForNumericStatement | ForGenericStatement; type Node = Statement | Expression | IfClause | ElseifClause | ElseClause | Chunk | TableKey | TableKeyString | TableValue | Comment; //#endregion interface Token { type: tokenTypes; value: string; line: number; lineStart: number; range: [number, number]; } //#region node sketching function labelStatement(label: Identifier): LabelStatement; function breakStatement(): BreakStatement; function gotoStatement(label: Identifier): GotoStatement; function returnStatement(args: Expression[]): ReturnStatement; function ifStatement(clauses: IfStatementClauses): IfStatement; function ifClause(condition: Expression, body: Statement[]): IfClause; function elseifClause(condition: Expression, body: Statement[]): ElseifClause; function elseClause(body: Statement[]): ElseClause; function whileStatement(condition: Expression, body: Statement[]): WhileStatement; function doStatement(body: Statement[]): DoStatement; function repeatStatement(condition: Expression, body: Statement[]): RepeatStatement; function localStatement(variables: Identifier[], init: Expression[]): LocalStatement; function assignmentStatement(variables: Array<Identifier | IndexExpression | MemberExpression>, init: Expression[]): AssignmentStatement; function assignmentOperatorStatement(operator: BinaryOperator, variables: Array<Identifier | IndexExpression | MemberExpression>, init: Expression[]): AssignmentOperatorStatement; function callStatement(expression: CallExpression | StringCallExpression | TableCallExpression): CallStatement; function functionStatement(identifier: Identifier | MemberExpression | null, parameters: Array<Identifier | VarargLiteral>, isLocal: boolean, body: Statement[]): FunctionDeclaration; function forNumericStatement(variable: Identifier, start: Expression, end: Expression, step: Expression | null, body: Statement[]): ForNumericStatement; function forGenericStatement(variables: Identifier[], iterators: Expression[], body: Statement[]): ForGenericStatement; function chunk(body: Statement[]): Chunk; function identifier(name: string): Identifier; function literal(type: tokenTypes.StringLiteral, value: string, raw: string, rawInterrupted?: string): StringLiteral; function literal(type: tokenTypes.NumericLiteral, value: number, raw: string): NumericLiteral; function literal(type: tokenTypes.BooleanLiteral, value: boolean, raw: 'true' | 'false'): BooleanLiteral; function literal(type: tokenTypes.NilLiteral, value: null, raw: 'nil'): NilLiteral; function literal(type: tokenTypes.VarargLiteral, value: '...', raw: '...'): VarargLiteral; function tableKey(key: Expression, value: Expression): TableKey; function tableKeyString(key: Identifier, value: Expression): TableKeyString; function tableValue(value: Expression): TableValue; function tableConstructorExpression(fields: Array<TableKey | TableKeyString | TableValue>): TableConstructorExpression; function binaryExpression(operator: BinaryOperator | ComparisonOperator, left: Expression, right: Expression): BinaryExpression; function binaryExpression(operator: 'and' | 'or', left: Expression, right: Expression): LogicalExpression; function unaryExpression(operator: UnaryOperator, argument: Expression): UnaryExpression; function memberExpression(base: Expression, indexer: '.' | ':', identifier: Identifier): MemberExpression; function indexExpression(base: Expression, index: Expression): IndexExpression; function callExpression(base: Expression, args: Expression[]): CallExpression; function tableCallExpression(base: Expression, argument: Expression[]): TableCallExpression; function stringCallExpression(base: Expression, argument: Expression): StringCallExpression; function comment(value: string, raw: string, rawInterrupted?: string): Comment; //#endregion } // Keep this lower-case the same as in the luaparse.js file itself. export enum tokenTypes { EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8, NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64, NilLiteral = 128, VarargLiteral = 256, } export interface Parser { /** * The main parser. * @example * var parser = require('pico8parse'); * parser.parse('i = 0'); */ parse(code: string, options: Partial<Options> & { wait: true }): Parser; parse(code: string, options?: Partial<Options>): ast.Chunk; parse(options?: Partial<Options>): Parser; /** Write to the source code buffer without beginning the parse. */ write(segment: string): Parser; /** Send an EOF and begin parsing. */ end(segment?: string): ast.Chunk; /** * The lexer, or the tokenizer reads the input string character by character * and derives a token left-right. To be as efficient as possible the lexer * prioritizes the common cases such as identifiers. It also works with * character codes instead of characters as string comparisons was the * biggest bottleneck of the parser. * * If `options.comments` is enabled, all comments encountered will be stored * in an array which later will be appended to the chunk object. If disabled, * they will simply be disregarded. * * When the lexer has derived a valid token, it will be returned as an object * containing its value and as well as its position in the input string (this * is always enabled to provide proper debug messages). * * `lex()` starts lexing and returns the following token in the stream. */ lex(): ast.Token; } /** * This is temporary and may be changed * * prefer instanceof checking against this rather than the engine built-in SyntaxError * (see https://github.com/fstirlitz/luaparse/releases/tag/v0.3.1 and #67) */ export class SyntaxError extends Error { } export const version: string; /** * As this parser is a bit different from Lua's own, the error messages * will be different in some situations. * * This maps from an error key to a user-friendly string describing the error. * Each string may contain "%n" sequences to be interpolated with error-dependent * contextual information (n is an integer, counting from 1). * * @example { unexpected: 'unexpected %1 \'%2\' near \'%3\'', ... } */ export const errors: Record<string, string>; export const defaultOptions: Partial<Options>; export const versionFeatures: Record<LuaVersion, boolean>; export const parse: Parser['parse']; export const write: Parser['write']; export const end: Parser['end']; export const lex: Parser['lex']; // Note: names outside a module loader environment is still 'luaparse' export as namespace luaparse;
the_stack
import { IConfig, ParseFeRouteItem } from '@aora/types'; import { existsSync, lstatSync, mkdirSync, promises as fsp, readdirSync } from 'fs'; import * as esbuild from 'esbuild'; import * as path from 'path'; import { accessFile, getCwd, getFeDir, normalizeStartPath } from './cwd'; const debug = require('debug')('ssr:parse'); const cwd = getCwd(); const getPrefix = (prefix: IConfig['prefix']) => { return prefix ? normalizeStartPath(prefix) : prefix; }; export function createRouteId(file: string) { return normalizeSlashes(stripFileExtension(file)); } export function normalizeSlashes(file: string) { return file.split(path.win32.sep).join('/'); } function stripFileExtension(file: string) { return file.replace(/\.[a-z0-9]+$/i, ''); } const routeModuleExtensions = new Set(['.js', '.jsx', '.ts', '.tsx']); function visitFiles( dir: string, visitor: (file: string) => void, baseDir = dir, ): void { for (let filename of readdirSync(dir)) { let file = path.resolve(dir, filename); let stat = lstatSync(file); if (stat.isDirectory()) { visitFiles(file, visitor, baseDir); } else if (stat.isFile()) { visitor(path.relative(baseDir, file)); } } } export const normalizePath = (config: IConfig, path: string, base?: string) => { const prefix = getPrefix(config.prefix); // 移除 prefix 保证 path 跟路由表能够正确匹配 const baseName = base ?? prefix; if (baseName) { path = path.replace(baseName, ''); } if (path.startsWith('//')) { path = path.replace('//', '/'); } if (!path.startsWith('/')) { path = `/${path}`; } return path; }; export const normalizePublicPath = (path: string) => { // 兼容 /pre /pre/ 两种情况 if (!path.endsWith('/')) { path = `${path}/`; } return path; }; export const getOutputPublicPath = (publicPath: string, isDev: boolean) => { const path = normalizePublicPath(publicPath); console.log('isDev', isDev); return `${path}build/`; }; export const getImageOutputPath = (publicPath: string, isDev: boolean) => { const imagePath = 'images'; const normalizePath = normalizePublicPath(publicPath); return { publicPath: isDev ? `${normalizePath}${imagePath}` : `${normalizePath}build/${imagePath}`, imagePath, }; }; const parseFeRoutes = async (config: IConfig) => { const { dynamic } = config; const prefix = getPrefix(config.prefix); let routes = ''; let arr = getRoutes(config).map((r: any) => { return { component: `@/${r.file}`, path: path.join('/', r.path), webpackChunkName: r.id.slice('pages'.length + 1), id: r.id, index: r.index, }; }); debug('Before the result that parse web folder to routes is: ', arr); // React 场景 const accessReactApp = await accessFile( path.join(getFeDir(), './layouts/App.tsx'), ); const layoutFetch = await accessFile( path.join(getFeDir(), './layouts/fetch.ts'), ); const accessStore = await accessFile( path.join(getFeDir(), './store/index.ts'), ); const re = /"webpackChunkName":("(.+?)")/g; routes = ` // The file is provisional,don't depend on it export const FeRoutes = ${JSON.stringify(arr, (_key, value) => value === '' || value === undefined ? undefined : value, )} ${ accessReactApp ? 'export { default as App, fetch as layoutFetch } from "@/layouts/App.tsx"' : '' } ${ layoutFetch ? 'export { default as layoutFetch } from "@/layouts/fetch.ts"' : '' } ${accessStore ? 'export * from "@/store/index.ts"' : ''} ${prefix ? `export const PrefixRouterBase='${prefix}'` : ''} `; routes = routes.replace(/"component":("(.+?)")/g, (_global, _m1, m2) => { const currentWebpackChunkName = re.exec(routes)![2]; if (dynamic) { return `"component": function dynamicComponent () { return import(/* webpackChunkName: "${currentWebpackChunkName}" */ '${m2.replace( /\^/g, '"', )}') } `; } else { return `"component": require('${m2.replace(/\^/g, '"')}').default`; } }); re.lastIndex = 0; // routes = routes.replace(/"fetch":("(.+?)")/g, (_global, _m1, m2) => { // const currentWebpackChunkName = re.exec(routes)![2] // return `"fetch": () => import(/* webpackChunkName: "${currentWebpackChunkName}-fetch" */ '${m2.replace(/\^/g, '"')}')` // }) debug('After the result that parse web folder to routes is: ', routes); await writeRoutes(routes); }; type Route = { id: string; index?: boolean; path?: string; file: string }; const layoutPages = ['_document', '_app']; const isPageFile = (fileName: string) => { const { name, ext } = path.parse(fileName); return routeModuleExtensions.has(ext) && !layoutPages.includes(name); }; const pageDirName = 'pages'; export function getRoutes(_config: IConfig): Route[] { let files: { [routeId: string]: string } = {}; visitFiles(path.join(getFeDir(), pageDirName), (file) => { if (isPageFile(file)) { const routeId = createRouteId(path.join(pageDirName, file)); files[routeId] = path.join(pageDirName, file); return; } }); let routeIds = Object.keys(files).sort(byLongestFirst); let uniqueRoutes: Record<string, Route> = Object.create(null); // let uniqueRoutes = new Map<string, string>(); // let defineRoute = ( // path: string | undefined, // file: string, // optionsOrChildren: string, // ) => { // let options: any; // if (typeof optionsOrChildren === "function") { // // route(path, file, children) // options = {}; // // children = optionsOrChildren; // } else { // // route(path, file, options, children) // // route(path, file, options) // options = optionsOrChildren || {}; // } // let route: any = { // path: path ? path : undefined, // index: options.index ? true : undefined, // caseSensitive: options.caseSensitive ? true : undefined, // id: createRouteId(file), // // parentId: // // parentRoutes.length > 0 // // ? parentRoutes[parentRoutes.length - 1].id // // : undefined, // file // }; // newRoutes[route.id] = route; // // if (children) { // // parentRoutes.push(route); // // children(); // // parentRoutes.pop(); // // } // }; routeIds.forEach((routeId) => { const parentId = ''; let routePath: string | undefined = createRoutePath( routeId.slice((parentId || 'pages').length + 1), ); // let fullPath = createRoutePath(routeId.slice(pageDirName.length + 1)); let isIndexRoute = routeId.endsWith('/index'); // let uniqueRouteId = (fullPath || '') + (isIndexRoute ? '?index' : ''); if (isIndexRoute) { let invalidChildRoutes = routeIds.filter( (id) => findParentRouteId(routeIds, id) === routeId, ); if (invalidChildRoutes.length > 0) { throw new Error( `Child routes are not allowed in index routes. Please remove child routes of ${routeId}`, ); } // defineRoute(routePath, files[routeId], { // index: true // }); let route: any = { path: routePath ? routePath : '', index: true, // caseSensitive: options.caseSensitive ? true : undefined, id: createRouteId(files[routeId]), // parentId: // parentRoutes.length > 0 // ? parentRoutes[parentRoutes.length - 1].id // : undefined, file: files[routeId], }; uniqueRoutes[route.id] = route; } else { // defineRoute(routePath, files[routeId], () => { // defineNestedRoutes(defineRoute, routeId); // }); let route: any = { path: routePath ? routePath : '', // caseSensitive: options.caseSensitive ? true : undefined, id: createRouteId(files[routeId]), // parentId: // parentRoutes.length > 0 // ? parentRoutes[parentRoutes.length - 1].id // : undefined, file: files[routeId], }; uniqueRoutes[route.id] = route; } }); return Object.values(uniqueRoutes); } export function formatRoutes(config: IConfig, type: 'json' | 'jsx' = 'jsx') { const routes = getRoutes(config); if (type === 'json') { return JSON.stringify(routes || null, null, 2); } else { return formatRoutesAsJsx(routes); } } export function formatRoutesAsJsx(routes: any) { let output = '<Routes>'; function handleRoutesRecursive(level = 1): boolean { let indent = Array(level * 2) .fill(' ') .join(''); for (let route of routes) { output += '\n' + indent; output += `<Route${ route.path ? ` path=${JSON.stringify(route.path)}` : '' }${route.index ? ' index' : ''}${ route.file ? ` file=${JSON.stringify(route.file)}` : '' }>`; output = output.slice(0, -1) + ' />'; } return routes.length > 0; } handleRoutesRecursive(); output += '\n</Routes>'; return output; } function byLongestFirst(a: string, b: string): number { return b.length - a.length; } export function checkOutputDir() { const dir = path.resolve(cwd, './.aora'); if (!existsSync(dir)) { mkdirSync(dir); } } const writeRoutes = async (routes: string) => { checkOutputDir(); const routesCode = await esbuild.transform(routes, { format: 'esm', target: 'es6', keepNames: true, minifySyntax: true, // minify: true, }); await fsp.writeFile(path.resolve(cwd, './.aora/routes.js'), routesCode.code); // await fsp.writeFile(path.resolve(cwd, './.aora/routes.js'), routes); }; function findParentRouteId( routeIds: string[], childRouteId: string, ): string | undefined { return routeIds.find((id) => childRouteId.startsWith(`${id}/`)); } const renderRoutes = async ( pageDir: string, pathRecord: string[], route: ParseFeRouteItem, ): Promise<ParseFeRouteItem[]> => { let arr: ParseFeRouteItem[] = []; const pagesFolders = await fsp.readdir(pageDir); const prefixPath = pathRecord.join('/'); const aliasPath = `@/pages${prefixPath}`; const routeArr: ParseFeRouteItem[] = []; const fetchExactMatch = pagesFolders.filter((p) => p.includes('fetch')); for (const pageFiles of pagesFolders) { const abFolder = path.join(pageDir, pageFiles); const isDirectory = (await fsp.stat(abFolder)).isDirectory(); if (isDirectory) { // 如果是文件夹则递归下去, 记录路径 pathRecord.push(pageFiles); const childArr = await renderRoutes( abFolder, pathRecord, Object.assign({}, route), ); pathRecord.pop(); // 回溯 arr = arr.concat(childArr); } else { // 遍历一个文件夹下面的所有文件 if (!pageFiles.includes('render')) { continue; } // 拿到具体的文件 if (pageFiles.includes('render$')) { /* /news/:id */ route.path = `${prefixPath}/:${getDynamicParam(pageFiles)}`; route.component = `${aliasPath}/${pageFiles}`; let webpackChunkName = pathRecord.join('-'); if (webpackChunkName.startsWith('-')) { webpackChunkName = webpackChunkName.replace('-', ''); } route.webpackChunkName = `${webpackChunkName}-${getDynamicParam( pageFiles, ) .replace(/\/:\??/g, '-') .replace('?', '-optional')}`; } else if (pageFiles.includes('render')) { /* /news */ route.path = `${prefixPath}`; route.component = `${aliasPath}/${pageFiles}`; let webpackChunkName = pathRecord.join('-'); if (webpackChunkName.startsWith('-')) { webpackChunkName = webpackChunkName.replace('-', ''); } route.webpackChunkName = webpackChunkName; } if (fetchExactMatch.length >= 2) { // fetch文件数量 >=2 启用完全匹配策略 render$id => fetch$id, render => fetch const fetchPageFiles = `${ pageFiles.replace('render', 'fetch').split('.')[0] }.ts`; if (fetchExactMatch.includes(fetchPageFiles)) { route.fetch = `${aliasPath}/${fetchPageFiles}`; } } else if (fetchExactMatch.includes('fetch.ts')) { // 单 fetch 文件的情况 所有类型的 render 都对应该 fetch route.fetch = `${aliasPath}/fetch.ts`; } routeArr.push({ ...route }); } } routeArr.forEach((r) => { if (r.path?.includes('index')) { // /index 映射为 / if (r.path.split('/').length >= 3) { r.path = r.path.replace('/index', ''); } else { r.path = r.path.replace('index', ''); } } r.path && arr.push(r); }); return arr; }; const getDynamicParam = (url: string) => { return url .split('$') .filter((r) => r !== 'render' && r !== '') .map((r) => r.replace(/\.[\s\S]+/, '').replace('#', '?')) .join('/:'); }; export { parseFeRoutes }; let escapeStart = '['; let escapeEnd = ']'; // TODO: Cleanup and write some tests for this function export function createRoutePath(partialRouteId: string): string | undefined { let result = ''; let rawSegmentBuffer = ''; let inEscapeSequence = 0; let skipSegment = false; for (let i = 0; i < partialRouteId.length; i++) { let char = partialRouteId.charAt(i); let lastChar = i > 0 ? partialRouteId.charAt(i - 1) : undefined; let nextChar = i < partialRouteId.length - 1 ? partialRouteId.charAt(i + 1) : undefined; const isNewEscapeSequence = () => { return ( !inEscapeSequence && char === escapeStart && lastChar !== escapeStart ); }; const isCloseEscapeSequence = () => { return inEscapeSequence && char === escapeEnd && nextChar !== escapeEnd; }; const isStartOfLayoutSegment = () => char === '_' && nextChar === '_' && !rawSegmentBuffer; if (skipSegment) { if (char === '/' || char === '.' || char === path.win32.sep) { skipSegment = false; } continue; } if (isNewEscapeSequence()) { inEscapeSequence++; continue; } if (isCloseEscapeSequence()) { inEscapeSequence--; continue; } if (inEscapeSequence) { result += char; continue; } if (char === '/' || char === path.win32.sep || char === '.') { if (rawSegmentBuffer === 'index' && result.endsWith('index')) { result = result.replace(/\/?index$/, ''); } else { result += '/'; } rawSegmentBuffer = ''; continue; } if (isStartOfLayoutSegment()) { skipSegment = true; continue; } rawSegmentBuffer += char; if (char === '$') { result += typeof nextChar === 'undefined' ? '*' : ':'; continue; } result += char; } if (rawSegmentBuffer === 'index' && result.endsWith('index')) { result = result.replace(/\/?index$/, ''); } return result || undefined; }
the_stack
import { configureTestSuite } from '../test-utils/configure-suite'; import { waitForAsync, TestBed, fakeAsync, tick } from '@angular/core/testing'; import { IgxTreeNavigationComponent, IgxTreeScrollComponent } from './tree-samples.spec'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { UIInteractions, wait } from '../test-utils/ui-interactions.spec'; import { IgxTreeNavigationService } from './tree-navigation.service'; import { ElementRef, EventEmitter } from '@angular/core'; import { IgxTreeSelectionService } from './tree-selection.service'; import { TreeTestFunctions } from './tree-functions.spec'; import { IgxTreeService } from './tree.service'; import { IgxTreeComponent, IgxTreeModule } from './tree.component'; import { IgxTree, IgxTreeNode, IgxTreeSelectionType } from './common'; import { IgxTreeNodeComponent } from './tree-node/tree-node.component'; describe('IgxTree - Navigation #treeView', () => { configureTestSuite(); describe('Navigation - UI Tests', () => { let fix; let tree: IgxTreeComponent; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxTreeNavigationComponent, IgxTreeScrollComponent ], imports: [IgxTreeModule, NoopAnimationsModule] }).compileComponents(); })); beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeNavigationComponent); fix.detectChanges(); tree = fix.componentInstance.tree; })); describe('UI Interaction tests - None', () => { beforeEach(fakeAsync(() => { tree.selection = IgxTreeSelectionType.None; fix.detectChanges(); })); it('Initial tab index without focus SHOULD be 0 for all nodes and active input should be set correctly', () => { const visibleNodes = (tree as any).navService.visibleChildren; visibleNodes.forEach(node => { expect(node.header.nativeElement.tabIndex).toEqual(0); }); // Should render node with `node.active === true`, set through input, as active in the tree expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); expect(tree.nodes.toArray()[17].active).toBeTruthy(); tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); visibleNodes.forEach(node => { if (node !== tree.nodes.first) { expect(node.header.nativeElement.tabIndex).toEqual(-1); } else { expect(node.header.nativeElement.tabIndex).toEqual(0); } }); }); it('Should focus/activate correct node on ArrowDown/ArrowUp (+ Ctrl) key pressed', () => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); // ArrowDown + Ctrl should only focus the next visible node UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement, true, false, false, true); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); // ArrowDown should focus and activate the next visible node UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[28]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[28]); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.toArray()[28]); // ArrowUp + Ctrl should only focus the previous visible node UIInteractions.triggerKeyDownEvtUponElem('arrowup', tree.nodes.toArray()[28].nativeElement, true, false, false, true); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[28]); // ArrowUp should focus and activate the previous visible node UIInteractions.triggerKeyDownEvtUponElem('arrowup', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); }); it('Should focus and activate the first/last visible node on Home/End key press', () => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); tree.nodes.first.expand(); fix.detectChanges(); tree.nodes.toArray()[2].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('home', tree.nodes.toArray()[2].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); UIInteractions.triggerKeyDownEvtUponElem('end', tree.nodes.first.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.last); expect((tree as any).navService.activeNode).toEqual(tree.nodes.last); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.last); }); it('Should collapse/navigate to correct node on Arrow left key press', fakeAsync(() => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); // If node is collapsed and has no parents the focus and activation should not be moved on Arrow left key press tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); tick(); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowleft', tree.nodes.first.nativeElement); tick(); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); // If node is collapsed and has parent the focus and activation should be moved to the parent node on Arrow left key press tree.nodes.first.expand(); tick(); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement); tick(); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowleft', tree.nodes.first.nativeElement); tick(); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); // If node is expanded the node should collapse on Arrow left key press UIInteractions.triggerKeyDownEvtUponElem('arrowleft', tree.nodes.first.nativeElement); tick(); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.nodes.first.expanded).toBeFalsy(); })); it('Should expand/navigate to correct node on Arrow right key press', () => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); // If node has no children the focus and activation should not be moved on Arrow right key press tree.nodes.last.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.last.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.last); expect((tree as any).navService.activeNode).toEqual(tree.nodes.last); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.last); // If node is collapsed and has children the node should be expanded on Arrow right key press UIInteractions.triggerKeyDownEvtUponElem('home', tree.nodes.last.nativeElement); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.first.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.first); expect(tree.nodes.first.expanded).toBeTruthy(); // If node is expanded and has children the focus and activation should be moved to the first child on Arrow right key press UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.first.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[1]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[1]); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.toArray()[1]); }); it('Pressing Asterisk on focused node should expand all expandable nodes in the same group', () => { tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.first.nativeElement); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.first.nativeElement); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('*', tree.nodes.first.nativeElement); fix.detectChanges(); expect(tree.nodes.toArray()[2].expanded).toBeTruthy(); expect(tree.nodes.toArray()[12].expanded).toBeTruthy(); }); it('Pressing Enter should activate the focused node and not prevent the keydown event`s deafault behavior', () => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement, true, false, false, true); fix.detectChanges(); const mockEvent = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }); spyOn(mockEvent, 'preventDefault'); tree.nodes.toArray()[17].nativeElement.dispatchEvent(mockEvent); expect(mockEvent.preventDefault).not.toHaveBeenCalled(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.toArray()[17]); }); it('Should correctly set node`s selection state on Space key press', () => { spyOn(tree.activeNodeChanged, 'emit').and.callThrough(); // Space on None Selection Mode tree.selection = 'None'; tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement, true, false, false, true); fix.detectChanges(); spyOn((tree as any).selectionService, 'selectNode').and.callThrough(); spyOn((tree as any).selectionService, 'deselectNode').and.callThrough(); spyOn((tree as any).selectionService, 'selectMultipleNodes').and.callThrough(); UIInteractions.triggerKeyDownEvtUponElem('space', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect(tree.nodes.toArray()[17].selected).toBeFalsy(); expect((tree as any).selectionService.selectNode).toHaveBeenCalledTimes(0); expect((tree as any).selectionService.deselectNode).toHaveBeenCalledTimes(0); expect((tree as any).selectionService.selectMultipleNodes).toHaveBeenCalledTimes(0); expect((tree as any).navService.activeNode).not.toEqual(tree.nodes.toArray()[17]); // Space for select tree.selection = 'BiState'; UIInteractions.triggerKeyDownEvtUponElem('space', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect(tree.nodes.toArray()[17].selected).toBeTruthy(); expect((tree as any).selectionService.selectNode).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.deselectNode).toHaveBeenCalledTimes(0); expect((tree as any).selectionService.selectMultipleNodes).toHaveBeenCalledTimes(0); expect((tree as any).selectionService.selectNode).toHaveBeenCalledWith(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); expect(tree.activeNodeChanged.emit).toHaveBeenCalledWith(tree.nodes.toArray()[17]); // Space with Shift key UIInteractions.triggerKeyDownEvtUponElem('arrowup', tree.nodes.toArray()[17].nativeElement, true, false, false, true); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('space', tree.nodes.first.nativeElement, true, false, true, false); fix.detectChanges(); expect(tree.nodes.first.selected).toBeTruthy(); expect(tree.nodes.toArray()[17].selected).toBeTruthy(); expect((tree as any).selectionService.selectNode).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.deselectNode).toHaveBeenCalledTimes(0); expect((tree as any).selectionService.selectMultipleNodes).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.selectMultipleNodes).toHaveBeenCalledWith(tree.nodes.first); expect((tree as any).navService.activeNode).toEqual(tree.nodes.first); // Space for deselect UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.first.nativeElement, true, false, false, true); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('space', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect(tree.nodes.toArray()[17].selected).toBeFalsy(); expect((tree as any).selectionService.selectNode).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.deselectNode).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.selectMultipleNodes).toHaveBeenCalledTimes(1); expect((tree as any).selectionService.deselectNode).toHaveBeenCalledWith(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); }); }); describe('UI Interaction tests - Scroll to focused node', () => { beforeEach(fakeAsync(() => { fix = TestBed.createComponent(IgxTreeScrollComponent); fix.detectChanges(); tree = fix.componentInstance.tree; tree.selection = IgxTreeSelectionType.None; fix.detectChanges(); })); it('The tree container should be scrolled so that the focused node is in view', fakeAsync(() => { // set another node as active element, expect node to be in view tick(); const treeElement = tree.nativeElement; let targetNode = tree.nodes.last; let nodeElement = targetNode.nativeElement; let nodeRect = nodeElement.getBoundingClientRect(); let treeRect = treeElement.getBoundingClientRect(); // expect node is in view expect((treeRect.top > nodeRect.top) || (treeRect.bottom < nodeRect.bottom)).toBeFalsy(); targetNode = tree.nodes.first; nodeElement = targetNode?.header.nativeElement; targetNode.active = true; tick(); fix.detectChanges(); nodeRect = nodeElement.getBoundingClientRect(); treeRect = treeElement.getBoundingClientRect(); expect(treeElement.scrollTop).toBe(0); expect((treeRect.top > nodeRect.top) || (treeRect.bottom < nodeRect.bottom)).toBeFalsy(); let lastNodeIndex = 0; let nodeIndex = 0; for (let i = 0; i < 150; i++) { while (nodeIndex === lastNodeIndex) { nodeIndex = Math.floor(Math.random() * tree.nodes.length); } lastNodeIndex = nodeIndex; targetNode = tree.nodes.toArray()[nodeIndex]; nodeElement = targetNode.header.nativeElement; targetNode.active = true; tick(); fix.detectChanges(); tick(); fix.detectChanges(); // recalculate rectangles treeRect = treeElement.getBoundingClientRect(); nodeRect = targetNode.header.nativeElement.getBoundingClientRect(); expect((treeRect.top <= nodeRect.top) && (treeRect.bottom >= nodeRect.bottom)).toBeTruthy(); } })); }); describe('UI Interaction tests - Disabled Nodes', () => { beforeEach(fakeAsync(() => { tree.selection = IgxTreeSelectionType.None; fix.detectChanges(); fix.componentInstance.isDisabled = true; fix.detectChanges(); })); it('TabIndex on disabled node should be -1', () => { expect(tree.nodes.last.header.nativeElement.tabIndex).toEqual(-1); }); it('Should focus and activate the first/last enabled and visible node on Home/End key press', () => { tree.nodes.first.disabled = true; fix.detectChanges(); tree.nodes.toArray()[38].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('home', tree.nodes.first.nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); UIInteractions.triggerKeyDownEvtUponElem('end', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[38]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[38]); }); it('Should navigate to correct node on Arrow left/right key press', () => { // If a node is collapsed and has a disabled parent the focus and activation // should not be moved from the node on Arrow left key press tree.nodes.first.expanded = true; fix.detectChanges(); tree.nodes.toArray()[2].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); tree.nodes.first.disabled = true; fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowleft', tree.nodes.toArray()[2].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[2]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[2]); // If a node is expanded and all its children are disabled the focus and activation // should not be moved from the node on Arrow right key press UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.toArray()[2].nativeElement); fix.detectChanges(); tree.nodes.toArray()[2]._children.forEach(child => { child.disabled = true; }); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.toArray()[2].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[2]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[2]); // If a node is expanded and has enabled children the focus and activation // should be moved to the first enabled child on Arrow right key press tree.nodes.toArray()[4].disabled = false; fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowright', tree.nodes.toArray()[2].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[4]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[4]); }); it('Should navigate to the right node on Arrow up/down key press', () => { tree.nodes.toArray()[28].disabled = true; tree.nodes.toArray()[38].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowup', tree.nodes.toArray()[38].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[17]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[17]); UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.toArray()[17].nativeElement); fix.detectChanges(); expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[38]); expect((tree as any).navService.activeNode).toEqual(tree.nodes.toArray()[38]); }); it('Pressing Asterisk on focused node should expand only the enabled and expandable nodes in the same group', () => { tree.nodes.toArray()[17].disabled = true; tree.nodes.first.header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('*', tree.nodes.first.nativeElement); fix.detectChanges(); expect(tree.nodes.toArray()[17].expanded).toBeFalsy(); expect(tree.nodes.first.expanded).toBeTruthy(); expect(tree.nodes.toArray()[28].expanded).toBeTruthy(); expect(tree.nodes.toArray()[38].expanded).toBeTruthy(); expect(tree.nodes.last.expanded).toBeFalsy(); }); }); describe('UI Interaction tests - igxTreeNodeLink', () => { beforeEach(fakeAsync(() => { tree.selection = IgxTreeSelectionType.None; fix.detectChanges(); fix.componentInstance.showNodesWithDirective = true; fix.detectChanges(); })); it('Nodes with igxTreeNodeLink should have tabIndex -1', () => { expect(tree.nodes.toArray()[41].header.nativeElement.tabIndex).toEqual(-1); expect(tree.nodes.last.header.nativeElement.tabIndex).toEqual(-1); }); it('When focus falls on link with directive, document.activeElement should be link with directive', fakeAsync(() => { tree.nodes.toArray()[40].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('arrowdown', tree.nodes.toArray()[40].nativeElement); fix.detectChanges(); tick(); fix.detectChanges(); const linkNode = tree.nodes.toArray()[41].linkChildren.first.nativeElement; expect(linkNode.tabIndex).toEqual(0); // When focus falls on link with directive, parent has focused class (nav.service.focusedNode === link.parent) expect((tree as any).navService.focusedNode).toEqual(tree.nodes.toArray()[41]); expect(document.activeElement).toEqual(linkNode); })); it('Link with passed parent in ng-template outisde of node parent has proper ref to parent', () => { tree.nodes.toArray()[40].header.nativeElement.dispatchEvent(new Event('pointerdown')); fix.detectChanges(); tree.nodes.toArray()[46].expanded = true; fix.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('end', tree.nodes.toArray()[46].nativeElement); fix.detectChanges(); expect(tree.nodes.last.registeredChildren[0].tabIndex).toEqual(0); }); }); }); describe('IgxTreeNavigationSerivce - Unit Tests', () => { let selectionService: IgxTreeSelectionService; let treeService: IgxTreeService; let navService: IgxTreeNavigationService; let mockTree: IgxTree; let mockEmitter: EventEmitter<IgxTreeNode<any>>; let mockNodesLevel1: IgxTreeNodeComponent<any>[]; let mockNodesLevel2_1: IgxTreeNodeComponent<any>[]; let mockNodesLevel2_2: IgxTreeNodeComponent<any>[]; let mockNodesLevel3_1: IgxTreeNodeComponent<any>[]; let mockNodesLevel3_2: IgxTreeNodeComponent<any>[]; let allNodes: IgxTreeNodeComponent<any>[]; const mockQuery1: any = {}; const mockQuery2: any = {}; const mockQuery3: any = {}; const mockQuery4: any = {}; const mockQuery5: any = {}; const mockQuery6: any = {}; beforeEach(() => { selectionService = new IgxTreeSelectionService(); treeService = new IgxTreeService(); navService?.ngOnDestroy(); navService = new IgxTreeNavigationService(treeService, selectionService); mockNodesLevel1 = TreeTestFunctions.createNodeSpies(0, 3, null, [mockQuery2, mockQuery3, []], [mockQuery6, mockQuery3, []]); mockNodesLevel2_1 = TreeTestFunctions.createNodeSpies(1, 2, mockNodesLevel1[0], [mockQuery4, mockQuery5], [mockQuery4, mockQuery5]); mockNodesLevel2_2 = TreeTestFunctions.createNodeSpies(1, 1, mockNodesLevel1[1], [[]]); mockNodesLevel3_1 = TreeTestFunctions.createNodeSpies(2, 2, mockNodesLevel2_1[0], [[], []]); mockNodesLevel3_2 = TreeTestFunctions.createNodeSpies(2, 2, mockNodesLevel2_1[1], [[], []]); allNodes = [ mockNodesLevel1[0], mockNodesLevel2_1[0], ...mockNodesLevel3_1, mockNodesLevel2_1[1], ...mockNodesLevel3_2, mockNodesLevel1[1], ...mockNodesLevel2_2, mockNodesLevel1[2] ]; Object.assign(mockQuery1, TreeTestFunctions.createQueryListSpy(allNodes)); Object.assign(mockQuery2, TreeTestFunctions.createQueryListSpy(mockNodesLevel2_1)); Object.assign(mockQuery3, TreeTestFunctions.createQueryListSpy(mockNodesLevel2_2)); Object.assign(mockQuery4, TreeTestFunctions.createQueryListSpy(mockNodesLevel3_1)); Object.assign(mockQuery5, TreeTestFunctions.createQueryListSpy(mockNodesLevel3_2)); Object.assign(mockQuery6, TreeTestFunctions.createQueryListSpy([ mockNodesLevel2_1[0], ...mockNodesLevel3_1, mockNodesLevel2_1[1], ...mockNodesLevel3_2 ])); }); describe('IgxNavigationService', () => { beforeEach(() => { mockEmitter = jasmine.createSpyObj('emitter', ['emit']); mockTree = jasmine.createSpyObj('tree', [''], { selection: IgxTreeSelectionType.BiState, activeNodeChanged: mockEmitter, nodes: mockQuery1 }); navService.register(mockTree); }); it('Should properly register the specified tree', () => { navService = new IgxTreeNavigationService(treeService, selectionService); expect((navService as any).tree).toBeFalsy(); navService.register(mockTree); expect((navService as any).tree).toEqual(mockTree); }); it('Should properly calculate VisibleChildren collection', () => { navService.init_invisible_cache(); expect(navService.visibleChildren.length).toEqual(3); (Object.getOwnPropertyDescriptor(allNodes[0], 'expanded').get as jasmine.Spy<any>) .and.returnValue(true); navService.init_invisible_cache(); expect(navService.visibleChildren.length).toEqual(5); (Object.getOwnPropertyDescriptor(allNodes[0], 'disabled').get as jasmine.Spy<any>) .and.returnValue(true); navService.update_disabled_cache(allNodes[0]); expect(navService.visibleChildren.length).toEqual(4); allNodes.forEach(e => { (Object.getOwnPropertyDescriptor(e, 'disabled').get as jasmine.Spy<any>) .and.returnValue(true); navService.update_disabled_cache(e); }); expect(navService.visibleChildren.length).toEqual(0); mockTree.nodes = null; expect(navService.visibleChildren.length).toEqual(0); }); it('Should set activeNode and focusedNode correctly', () => { const someNode = { tabIndex: null, header: { nativeElement: jasmine.createSpyObj('nativeElement', ['focus']) } } as any; const someNode2 = { tabIndex: null, header: { nativeElement: jasmine.createSpyObj('nativeElement', ['focus']) } } as any; navService.focusedNode = someNode; expect(someNode.header.nativeElement.focus).toHaveBeenCalled(); expect(someNode.tabIndex).toBe(0); navService.setFocusedAndActiveNode(someNode2); expect(navService.activeNode).toEqual(someNode2); expect(someNode2.header.nativeElement.focus).toHaveBeenCalled(); expect(someNode2.tabIndex).toBe(0); expect(someNode.tabIndex).toBe(-1); expect(mockTree.activeNodeChanged.emit).toHaveBeenCalledTimes(1); expect(mockTree.activeNodeChanged.emit).toHaveBeenCalledWith(someNode2); // do not change active node when call w/ same node navService.focusedNode = navService.focusedNode; expect(mockTree.activeNodeChanged.emit).toHaveBeenCalledTimes(1); // handle call w/ null navService.focusedNode = null; expect(someNode2.tabIndex).toBe(-1); expect(mockTree.activeNodeChanged.emit).toHaveBeenCalledTimes(1); }); it('Should traverse visibleChildren on handleKeyDown', async () => { navService.init_invisible_cache(); const mockEvent1 = new KeyboardEvent('keydown', { key: 'arrowdown', bubbles: true }); spyOn(mockEvent1, 'preventDefault'); spyOn(navService, 'handleKeydown').and.callThrough(); navService.focusedNode = mockNodesLevel1[0]; navService.handleKeydown(mockEvent1); expect(mockEvent1.preventDefault).toHaveBeenCalled(); expect(navService.handleKeydown).toHaveBeenCalledTimes(1); expect(navService.focusedNode).toEqual(mockNodesLevel1[1]); const mockEvent2 = new KeyboardEvent('keydown', { key: 'arrowup', bubbles: true }); spyOn(mockEvent2, 'preventDefault'); navService.handleKeydown(mockEvent2); expect(mockEvent2.preventDefault).toHaveBeenCalled(); expect(navService.handleKeydown).toHaveBeenCalledTimes(2); expect(navService.focusedNode).toEqual(mockNodesLevel1[0]); const mockEvent3 = new KeyboardEvent('keydown', { key: 'arrowdown', bubbles: true, repeat: true }); spyOn(mockEvent3, 'preventDefault'); // when event is repeated, prevent default and wait navService.handleKeydown(mockEvent3); expect(navService.handleKeydown).toHaveBeenCalledTimes(3); expect(mockEvent3.preventDefault).toHaveBeenCalled(); // when event is repeating, node does not change immediately expect(navService.focusedNode).toEqual(mockNodesLevel1[0]); await wait(1); expect(navService.focusedNode).toEqual(mockNodesLevel1[1]); // does nothing if there is no focused node navService.focusedNode = null; const mockEvent4 = new KeyboardEvent('keydown', { key: 'arrowdown', bubbles: true, repeat: false }); spyOn(mockEvent4, 'preventDefault'); navService.handleKeydown(mockEvent4); expect(mockEvent4.preventDefault).not.toHaveBeenCalled(); // do not move focused node if on last node navService.focusedNode = allNodes[allNodes.length - 1]; navService.handleKeydown(mockEvent4); expect(navService.focusedNode).toEqual(allNodes[allNodes.length - 1]); }); it('Should update visible children on all relevant tree events', () => { const mockTreeService = jasmine.createSpyObj<IgxTreeService>('mockSelection', ['register', 'collapse', 'expand', 'collapsing'], { collapsingNodes: jasmine.createSpyObj<Set<IgxTreeNodeComponent<any>>>('mockCollpasingSet', ['add', 'delete', 'has'], { size: 0 }), expandedNodes: jasmine.createSpyObj<Set<IgxTreeNodeComponent<any>>>('mockExpandedSet', ['add', 'delete', 'has'], { size: 0 }), }); const mockElementRef = jasmine.createSpyObj<ElementRef>('mockElement', ['nativeElement'], { nativeElement: jasmine.createSpyObj<HTMLElement>('mockElement', ['focus'], { clientHeight: 300, scrollHeight: 300 }) }); const mockSelectionService = jasmine.createSpyObj<IgxTreeSelectionService>('mockSelection', ['selectNodesWithNoEvent', 'selectMultipleNodes', 'deselectNode', 'selectNode', 'register']); const nav = new IgxTreeNavigationService(mockTreeService, mockSelectionService); const lvl1Nodes = TreeTestFunctions.createNodeSpies(0, 5); const mockQuery = TreeTestFunctions.createQueryListSpy(lvl1Nodes); Object.assign(mockQuery, { changes: new EventEmitter<any>() }); spyOn(nav, 'init_invisible_cache'); spyOn(nav, 'update_disabled_cache'); spyOn(nav, 'update_visible_cache'); spyOn(nav, 'register'); const tree = new IgxTreeComponent(nav, mockSelectionService, mockTreeService, mockElementRef); tree.nodes = mockQuery; expect(nav.register).toHaveBeenCalledWith(tree); expect(nav.init_invisible_cache).not.toHaveBeenCalled(); expect(nav.update_disabled_cache).not.toHaveBeenCalled(); expect(nav.update_visible_cache).not.toHaveBeenCalled(); // not initialized tree.ngOnInit(); // manual call expect(nav.init_invisible_cache).not.toHaveBeenCalled(); expect(nav.update_disabled_cache).not.toHaveBeenCalled(); expect(nav.update_visible_cache).not.toHaveBeenCalled(); // nav service will now be updated after any of the following are emitted const emitNode = tree.nodes.first; tree.disabledChange.emit(emitNode); expect(nav.init_invisible_cache).not.toHaveBeenCalled(); expect(nav.update_disabled_cache).toHaveBeenCalledTimes(1); expect(nav.update_visible_cache).toHaveBeenCalledTimes(0); tree.disabledChange.emit(emitNode); expect(nav.update_disabled_cache).toHaveBeenCalledTimes(2); tree.nodeCollapsing.emit({ node: emitNode, owner: tree, cancel: false }); expect(nav.update_visible_cache).toHaveBeenCalledTimes(1); tree.nodeExpanding.emit({ node: emitNode, owner: tree, cancel: false }); expect(nav.update_visible_cache).toHaveBeenCalledTimes(2); // attach emitters to mock children lvl1Nodes.forEach(e => { e.expandedChange = new EventEmitter<boolean>(); e.openAnimationDone = new EventEmitter(); e.closeAnimationDone = new EventEmitter(); }); tree.ngAfterViewInit(); // inits cache on tree.ngAfterViewInit(); expect(nav.init_invisible_cache).toHaveBeenCalledTimes(1); // init cache when tree nodes collection changes; (tree.nodes as any).changes.emit(); expect(nav.init_invisible_cache).toHaveBeenCalledTimes(2); emitNode.expandedChange.emit(true); expect(nav.update_visible_cache).toHaveBeenCalledTimes(3); emitNode.expandedChange.emit(false); expect(nav.update_visible_cache).toHaveBeenCalledTimes(4); nav.ngOnDestroy(); tree.ngOnDestroy(); }); }); }); });
the_stack
import './style.scss' import { EventEmitter } from 'eventemitter3' import { Danmaku } from '@/player/danmaku/danmaku' import { Ui, UiString } from '@/player/ui' import { DanmakuLayerOptions, MakeDanmakuLayerOptions, } from '@/player/danmaku/danmakuLayer' import { QualityLevel, QualityLevelAdapter } from '@/player/qualityLevelAdapter' import { Hash, RandomID } from '@/player/utils' const DanPlayerVersion = '{DanPlayerVersion}' const icon = '//at.alicdn.com/t/font_1373341_eeojr5zqmon.js' const defaultColor = '#00a1d6' export enum ForceUse { Hls = 1, Dash } interface PlayerOptions { live: boolean volume: number autoplay: boolean uiFadeOutDelay: number width: number | string height: number | string src: string iconSrc: string forward: number backward: number extraButtons: HTMLElement[] | { [name: string]: () => void } danmaku: DanmakuLayerOptions fullScreen: boolean danmakuForm: boolean unique: boolean color: string beforeSendDanmaku?: (danmaku: Danmaku) => Promise<boolean> forceUse?: ForceUse ui: UiString preload: 'auto' | 'metadata' | 'none' timeFormat?: string pictureInPicture: boolean } export interface PlayerPublicOptions { // 是否启用直播模式,没有进度条,没有播放时间 live: boolean // 音量,0~1,默认为0.7 volume: number // 自动播放,根据浏览器的差异不一定有效 autoplay: boolean // ui 的隐藏时间,毫秒 uiFadeOutDelay: number // 视频寸尺 width: number | string height: number | string // 视频来源,也可以在<video src=""></video>的src设置 src: string iconSrc: string // 前进的秒数,毫秒 forward: number // 倒退的秒数,毫秒 backward: number // 扩展按钮 // extraButtons: { [name: string | HTMLElement]: () => void } extraButtons: HTMLElement[] // 弹幕层的配置 DanmakuLayerOptions danmaku: Partial<DanmakuLayerOptions> // 是否需要全屏 fullScreen: boolean // 是否显示播放器底部中间的弹幕输入框 danmakuForm: boolean // 唯一播放的播放器 unique: boolean // 播放器的亮色,包括:进度条、进度滑块、音量滑块、音量条 color: string // 发送弹幕前的事件 beforeSendDanmaku?: (danmaku: Danmaku) => Promise<boolean> // 强制启用hls.js或者dash.js // 多数用于移动平台,因为Android webview支持hls,导致不会使用hls.js // 丢失了hls.js提供的画质选项 forceUse?: ForceUse // ui 界面 多语言支持 ui?: UiString preload?: 'auto' | 'metadata' | 'none' timeFormat?: string pictureInPicture?: boolean } export enum VideoType { Normal = 'native', Hls = 'hls.js', Dash = 'dash.js', } function MakeDefaultOptions ({ autoplay = false, color = defaultColor, live = false, volume = 0.7, width = 600, height = 350, uiFadeOutDelay = 3000, extraButtons = [], src = '', iconSrc = icon, danmakuForm = true, fullScreen = true, beforeSendDanmaku = undefined, danmaku = {}, forward = 5, backward = 5, unique = false, forceUse = undefined, ui = undefined, preload = 'none', timeFormat, pictureInPicture = true, }: Partial<PlayerPublicOptions>): PlayerOptions { if (volume < 0 || volume > 1) { volume = 0.7 } const _ui = Object.assign(new UiString(), ui || {}) return { autoplay, color, live, height, danmaku: MakeDanmakuLayerOptions(danmaku), danmakuForm, fullScreen, src, iconSrc, forward, backward, uiFadeOutDelay, extraButtons, unique, volume, beforeSendDanmaku, width, forceUse, ui: _ui, preload, timeFormat, pictureInPicture, } } const template = `{video-layer} <div class="interactive-layer"> <canvas class="danmaku-layer"></canvas> <div class="bg-gradient show"></div> <div class="float danmaku-style-layer"></div> <div class="float volume-bar"> <div class="volume-num-label"></div> <div class="volume-column-bar"> <div class="bar-ui bar-full"></div> <div class="bar-ui bar-current"></div> <div class="bar-controller"></div> </div> </div> <div class="float quality-menu"></div> <div class="float loading show"></div> <div class="controller-bottom-bar"> <div class="progress-bar live-hide"> <div class="bar-full"></div> <div class="bar-buffer"></div> <div class="bar-current"></div> <div class="bar-controller"></div> </div> <div class="buttons"> <div class="left"> <div class="button intern-button play" data-on="danplayer-bofang" data-off="danplayer-zanting" data-on-title="{play}" data-off-title="{pause}"> <svg class="icon" aria-hidden="true"><use xlink:href="#danplayer-bofang"></use></svg> </div> <div class="time"></div> </div> <div class="middle danmaku-form"> <div class="button intern-button danmaku-style"> <svg class="icon"><use xlink:href="#danplayer-style"></use></svg> </div> <input placeholder="{danmakuInputHint}" tabindex="1"> <div class="send">{danmakuSend}</div> </div> <div class="right"> <div class="button intern-button volume" data-on="danplayer-yinliang" data-off="danplayer-jingyin" title="{volume}"> <svg class="icon"><use xlink:href="#danplayer-yinliang"></use></svg> </div> <div class="button intern-button toggle-danamaku" title="隐藏弹幕" data-on="danplayer-danmuguan" data-off="danplayer-danmukai" data-on-title="{showDanmaku}" data-off-title="{hideDanmaku}"> <svg class="icon"><use xlink:href="#danplayer-danmukai"></use></svg> </div> <div class="button quality" title="{switchQuality}"></div> <div class="button intern-button picture-in-picture"> <svg class="icon"><use xlink:href="#danplayer-pip"></use></svg> </div> <div class="button intern-button full-screen" data-on="danplayer-quanping" data-off="danplayer-zuixiaohua" data-on-title="{fullscreen}" data-off-title="{cancelFullscreen}"> <svg class="icon"><use xlink:href="#danplayer-quanping"></use></svg> </div> </div> </div> </div> </div>` export class Player extends EventEmitter { private static instances: Player[] = [] $root: HTMLElement $video: HTMLVideoElement type = VideoType.Normal // @ts-ignore public isSupportPictureInPicture: boolean = !!document.pictureInPictureEnabled public get isInPictureInPicture () { // @ts-ignore return this.$video === document.pictureInPictureElement } private readonly id: string private hls?: Hls private dash?: dashjs.MediaPlayerClass public ui: Ui clickEvent: 'touchstart' | 'click' = ('ontouchstart' in document.documentElement ? 'touchstart' : 'click') private adapter: QualityLevelAdapter private $style!: HTMLStyleElement // 尺寸 private _width: string = '' private _height: string = '' get width () { return this.$root.clientWidth } get height () { return this.$root.clientHeight } get isFullScreen () { return this._isFullScreen } private _duration: number = 0 private _loading = true private _paused = true private _isFullScreen: boolean = false get loading () { return this._loading } public options: PlayerOptions constructor ($e: HTMLElement, options?: Partial<PlayerPublicOptions>) { super() console.info(`DanPlayer v${DanPlayerVersion}`) options = options || {} this.options = MakeDefaultOptions(options) const hash = Hash(icon) if (!document.querySelector('script#danplayer-icon' + hash)) { const $icon = document.createElement('script') $icon.src = icon $icon.id = 'danplayer-icon' document.body.append($icon) } Player.instances.push(this) const parent = $e.parentElement as Element this.$root = document.createElement('div') this.id = RandomID() this.$root.setAttribute('data-style', this.id) this.$root.setAttribute('tabIndex', '0') this.$root.classList.add('danplayer') parent.insertBefore(this.$root, $e) let videoLayer if ($e.tagName.toLowerCase() === 'video') { $e.classList.add('video-layer') $e.removeAttribute('id') videoLayer = $e.outerHTML if (options && !('src' in options)) { options.src = $e.getAttribute('src') as string } } else { videoLayer = '<video class="video-layer"></video>' } this.$root.innerHTML = template.replace('{video-layer}', videoLayer) .replace('{volume}', this.options.ui.volume) .replace('{showDanmaku}', this.options.ui.showDanmaku) .replace('{hideDanmaku}', this.options.ui.hideDanmaku) .replace('{play}', this.options.ui.play) .replace('{pause}', this.options.ui.pause) .replace('{danmakuInputHint}', this.options.ui.danmakuInputHint) .replace('{danmakuSend}', this.options.ui.danmakuSend) .replace('{fullscreen}', this.options.ui.fullscreen) .replace('{cancelFullscreen}', this.options.ui.cancelFullscreen) .replace('{switchQuality}', this.options.ui.switchQuality) $e.remove() this.$root.addEventListener('contextmenu', (e: MouseEvent) => { e.stopPropagation() e.preventDefault() }) this.$root.addEventListener('keypress', (e: KeyboardEvent) => { console.log('keypress', e.key) if (e.key === 'Enter') { this.ui.show() this.ui.danmakuForm.focus() } else if (e.key === ' ') { this.toggle() e.stopPropagation() e.preventDefault() } }) this.$root.addEventListener('keydown', (e: KeyboardEvent) => { console.warn('keydown 1', e.key) const stop = e.key.startsWith('Arrow') if (!this.options.live) { if (e.key === 'ArrowLeft') { this.$video.currentTime -= this.options.backward } else if (e.key === 'ArrowRight') { this.$video.currentTime += this.options.forward } } if (e.key === 'ArrowUp') { this.ui.volume.up() } else if (e.key === 'ArrowDown') { this.ui.volume.down() } // console.warn('keydown 2', stop) if (stop) { e.stopPropagation() e.preventDefault() } }) document.addEventListener('fullscreenchange', () => { this._isFullScreen = document.fullscreenElement === this.$root this.ui.updateFullScreenButton() }) this.$root.addEventListener('mousemove', () => { this.$root.classList.remove('mouse-idle') if (!this.ui.isShow) { this.ui.show() this.ui.cancelHideUIDelay() } if (!this.paused && !this.ui.isMouseInUI) { this.ui.hideUIDelay().then(() => { this.$root.classList.add('mouse-idle') }) } }) this.$root.addEventListener('touchstart', () => { this.ui.show() this.ui.cancelHideUIDelay() }) this.$root.addEventListener('touchend', () => { this.ui.hideUIDelay() }) this.$root.addEventListener('mouseover', () => { if (this.ui.isShow) return this.$root.classList.remove('mouse-idle') this.ui.show() this.ui.cancelHideUIDelay() }) this.$root.addEventListener('mouseleave', () => { if (!this.ui.isShow) return this.ui.hide() this.ui.cancelHideUIDelay() }) this.$video = this.$root.querySelector('.video-layer') as HTMLVideoElement this.$video.removeAttribute('controls') this.$video.addEventListener('durationchange', () => { // console.log('视频长度', this.$video.duration) this._duration = this.$video.duration }) this.$video.setAttribute('preload', this.options.preload) this.$video.addEventListener('playing', () => this.ui.hideUIDelay()) this.$video.addEventListener('play', () => this.ui.updatePlayButton()) this.$video.addEventListener('pause', () => this.ui.updatePlayButton()) this.$video.addEventListener('error', () => this.errorHandler()) this.$video.addEventListener('loadedmetadata', () => { console.log('loadedmetadata') if (this.type === VideoType.Normal) { this.ui.qualitySelector.hideButton() } else { this.ui.qualitySelector.showButton() } }) if (!('width' in options)) { options.width = this.$video.clientWidth as number } if (!('height' in options)) { options.width = this.$video.clientHeight as number } if (!('autoplay' in options)) { options.autoplay = this.$video.hasAttribute('autoplay') } window.addEventListener('resize', () => this.resizeEvt(1000)) this.adapter = new QualityLevelAdapter() this.ui = new Ui(this) this.ui.show() this.ui.progressBar.init() this.ui.hideUIDelay() this.adapter.on(QualityLevelAdapter.Events.OnLoad, (levels: QualityLevel[]) => { this.ui.qualitySelector.updateLevel(levels) }) this.ui.qualitySelector.on('selectLevel', (level: QualityLevel) => { console.log('选择画质级别', level) this.ui.progressBar.resetProgressBar() this.adapter.changeLevelTo(level) }) this.updateUI() this.updateSrc().then() if (options?.forceUse) { this.errorHandler() } } private async updateSrc () { this.type = VideoType.Normal this.$video.src = this.options.src console.log('_set', { autoplay: this.options.autoplay, paused: this._paused, }) if (this.options.autoplay || !this.paused) { console.log('_set 播放') this.play() } } private updateUI () { this.ui.string = this.options.ui this.ui.insertExtraButtons() this.ui.update() this.ui.progressBar.resize() this.resize() if (this.$style) { this.$style.remove() } if (this.options.color !== defaultColor) { this.$style = document.createElement('style') as HTMLStyleElement this.$style.innerHTML = ` .danplayer[data-style="${this.id}"] .colors .selected{border-color:${this.options.color} !important} .danplayer[data-style="${this.id}"] .types .selected{color:${this.options.color} !important} .danplayer[data-style="${this.id}"] .quality-menu .current{color:${this.options.color} !important} .danplayer[data-style="${this.id}"] .volume-bar .bar-controller{background:${this.options.color} !important} .danplayer[data-style="${this.id}"] .volume-bar .bar-current{background:${this.options.color} !important} .danplayer[data-style="${this.id}"] .progress-bar .bar-controller{background:${this.options.color} !important} .danplayer[data-style="${this.id}"] .progress-bar .bar-current{background:${this.options.color} !important} ` this.$root.append(this.$style) } this.ui.qualitySelector.update() if (this.options.live) { this.$root.classList.add('live') } else { this.$root.classList.remove('live') } this.$video.volume = this.options.volume } set (options: Partial<PlayerPublicOptions>) { const srcHasChanged = options.src !== this.options.src options.ui = Object.assign({}, new UiString(), options.ui) options.danmaku = Object.assign({}, this.options.danmaku, options.danmaku) const newOptions = Object.assign({}, this.options, options) console.log('set', newOptions) const optionsHasChanged = JSON.stringify(newOptions) === JSON.stringify(this.options) if (srcHasChanged) { if (!options.forceUse) newOptions.forceUse = undefined } this.options = newOptions this.$video.setAttribute('preload', this.options.preload) if (srcHasChanged) { if (this.hls) { this.hls.detachMedia() this.hls = undefined } if (this.dash) { this.dash.reset() this.dash = undefined } this.ui.progressBar.reset() this.ui.qualitySelector.reset() this.updateSrc().then() } this.updateUI() if (optionsHasChanged) { this.emit('optionChanged', this) } console.log('set', options) if (options?.forceUse) { this.errorHandler() } } resize () { if (this.options.width) { if (typeof this.options.width === 'number' || parseInt(this.options.width).toString() === this.options.width) { this._width = this.options.width + 'px' } else { this._width = this.options.width } } if (this.options.height) { if (typeof this.options.height === 'number' || parseInt(this.options.height).toString() === this.options.height) { this._height = this.options.height + 'px' } else { this._height = this.options.height } } // console.log('resize options', this.options, { width: this._width, height: this._height }) if (!this._isFullScreen) { this.$root.style.width = this._width this.$root.style.height = this._height } this.ui.resize() } private delayResize: number = -1 private resizeEvt (ms: number) { window.clearTimeout(this.delayResize) this.delayResize = window.setTimeout(() => { this.resize() }, ms) } /** * 批量填充弹幕 */ fillDanmakus (array: Danmaku[]) { this.ui.danmakuLayer.danmakus.push(...array) } get currentTime () { return this.$video.currentTime } sendDanmaku (danmaku: Danmaku) { this.ui.danmakuLayer.send(danmaku) } clearDanmaku () { this.ui.danmakuLayer.clear() } get paused () { return this._paused } toggle () { if (this.paused) { this.play() } else { this.pause() } } play () { this._paused = false this.$video.play().then() if (this.options.unique) { Player.instances.forEach(player => { if (player !== this) { player.pause() } }) } } pause () { this._paused = true this.$video.pause() } /** * 当播放视频错误时 */ private async errorHandler () { console.error('video 视频资源 错误', this.$video.error) // if (!this.$video.error || this.$video.error.code !== 4) return console.log('errorHandler') if (this.options.forceUse === ForceUse.Hls || this.options.src.match(/\.m3u[8]/)) { console.log('errorHandler', 'hls.js') this.type = VideoType.Hls if (this.hls) this.hls.destroy() this.hls = new Hls() this.hls.attachMedia(this.$video) this.hls.loadSource(this.options.src) this.hls.config.capLevelToPlayerSize = true this.adapter.useHls(this.hls) } else if (this.options.forceUse === ForceUse.Dash || this.options.src.match(/\.mpd/)) { this.type = VideoType.Dash if (this.dash) this.dash.reset() this.dash = dashjs.MediaPlayer().create() this.dash.initialize(this.$video, this.options.src, !this.$video.paused) const setting = this.dash.getSettings() if (setting.streaming?.abr) setting.streaming.abr.limitBitrateByPortal = true this.dash.updateSettings(setting) this.adapter.useDash(this.dash) } if (!this.$video.paused) { this.$video.setAttribute('autoplay', '') this.$video.play() } } /** * 切换全屏模式 */ async toggleFullScreen () { if (!this.options.fullScreen) return this._isFullScreen = !this._isFullScreen if (this._isFullScreen) { this.$root.classList.add('full-screen') if (this.$root.requestFullscreen) { await this.$root.requestFullscreen() } else { // @ts-ignore if (this.$root.webkitRequestFullscreen) { // @ts-ignore await this.$root.webkitRequestFullscreen() } // @ts-ignore if (this.$root.mozRequestFullScreen) { // @ts-ignore await this.$root.mozRequestFullScreen() } // @ts-ignore if (this.$root.mozRequestFullScreen) { // @ts-ignore await this.$root.mozRequestFullScreen() } // @ts-ignore if (this.$root.msRequestFullscreen) { // @ts-ignore await this.$root.msRequestFullscreen() } } } else { if (document.exitFullscreen) { await document.exitFullscreen() } else { // @ts-ignore if (document.mozCancelFullScreen) { // @ts-ignore await document.mozCancelFullScreen() } // @ts-ignore if (document.webkitCancelFullScreen) { // @ts-ignore await document.webkitCancelFullScreen() } // @ts-ignore if (document.msExitFullscreen) { // @ts-ignore await document.msExitFullscreen() } } this.$root.classList.remove('full-screen') } this.resize() this.emit('toggleFullscreen') } /** * 切换 画中画 */ async togglePictureInPicture () { // @ts-ignore if (!this.isSupportPictureInPicture) return try { // @ts-ignore if (this.$video !== document.pictureInPictureElement) { // @ts-ignore await this.$video.requestPictureInPicture() } else { // @ts-ignore await document.exitPictureInPicture() } } catch (error) { } finally { } } /** * 销毁 */ destroy () { Player.instances.splice(Player.instances.indexOf(this), 1) this.ui.destroy() if (this.hls) { this.hls.detachMedia() } if (this.dash) { this.dash.reset() } if (this.$style) { this.$style.remove() } this.$root.remove() } get debug (): Object { let quality = '默认' const src = this.options.src if (this.type !== VideoType.Normal) { if (this.adapter.currentLevel) { quality = this.adapter.currentLevel.name } else { quality = '自动' } } return { id: this.id, width: this.width, height: this.height, type: this.type, src, quality, ui: this.ui.debug, } } }
the_stack
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { notificationTemplate } from "./notification-data-template"; import { NotificationModelsV4 } from "./notification-v4-models"; /** * The Notification API allows developers to manage and utilize the operations related to notification messages, * namely Registration of mobile apps and mobile app installation instances for receiving push notifications * Sending push notifications to set of users of a mobile app; addressed either by email address or the mobile app * instances. * Sending emails to a set of target recipients with an option to attach files. * * Error with HTTP status code 400 - "Invalid property" will be applicable for all operations, wherever applicable. * * * Limitations * This API cannot be accessed by subtenants. * * The service may decide to throttle API requests temporarily returning a 429 status code. * * *Generic Errors * The following generic error codes might occur at any of the specified operation. * Generic errors are prefixed with 'mdsp.core.generic.'. * * 204: noContent * * 400: invalidParameter * * 400: invalidRequestBodyProperty * * 400: missingParameter * * 400: missingRequestBodyProperty * * 401: unauthorized * * 403: forbidden * * 404: noMatch * * 409: conflict * * 429: tooManyRequests * * 500: internalServerError * * See the MindSphere API documentation generic errors page for more information. * * @export * @class ModelManagementClient * @extends {SdkClient} */ export class NotificationClientV4 extends SdkClient { private _baseUrl: string = "/api/notification/v4"; /** * * Email * * Sends an email notification to specified recipients with an option to attach files. * * Publishes the notification via email to the specified recipients, along with attachments as optional. * Maximum 5 files can be uploaded as attachments; where-in the total size of all attachments is limited to 8MB. * Only zip, csv, pdf and json file types are supported as attachments. * * @param {NotificationModelsV4.MulticastEmailNotificationRequestMetadata} metadata Content type must be <application/json>. The size of this attribute is limited to 250KB. * @param {NotificationModelsV4.Attachment[]} [attachments] File to be uploaded as attachment in email notification. This parameter must be provided for each file to be attached with the email. Maximum 5 files can be attached with one email request. * @returns {Promise<NotificationModelsV4.EmailJobResponse>} * * @memberOf NotificationClientV4 */ public async PostMulticastEmailNotificationJob( metadata: NotificationModelsV4.MulticastEmailNotificationRequestMetadata, attachments?: NotificationModelsV4.Attachment[] ): Promise<NotificationModelsV4.EmailJobResponse> { if (metadata === null || metadata === undefined) { throw new NotificationModelsV4.RequiredError( "metadata", "Required parameter metadata was null or undefined when calling PostMulticastEmailNotificationJobs." ); } const body = notificationTemplate(metadata, attachments); const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastEmailNotificationJobs`, body: body, multiPartFormData: true, additionalHeaders: { enctype: "multipart/form-data" }, }); return result as NotificationModelsV4.EmailJobResponse; } /** * * Email * * Shows the status of the triggered multicast email notification job. * * @param {string} id Job ID to fetch the details * @returns {Promise<NotificationModelsV4.MulticastEmailNotificationJob>} * * @memberOf NotificationClientV4 */ public async GetMulticastEmailNotificationJob( id: string ): Promise<NotificationModelsV4.MulticastEmailNotificationJob> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastEmailNotificationJobs/${id}`, }); return result as NotificationModelsV4.MulticastEmailNotificationJob; } /** * * Email * * Shows per recipent status of email dispatch status. * * @param {string} id Job ID to fetch the details * @param {{ page?: number; size?: number }} [params] page: specfies the page index, size: elements in a page (max:50) * @returns {Promise<NotificationModelsV4.NotificationDispatchStatus>} * * @memberOf NotificationClientV4 */ public async GetMulticastEmailNotificationJobsDeliveries( id: string, params?: { page?: number; size?: number } ): Promise<NotificationModelsV4.NotificationDispatchStatus> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastEmailNotificationJobs/${id}/deliveries?${toQueryString(parameters)}`, }); return result as NotificationModelsV4.NotificationDispatchStatus; } /** * SMS * * Sends an SMS notification to specified recipients. * * Publishes the notification via sms to the specified recipients. * The message is scanned for any vulnerabilities before dispatching it to the recipients. * A single SMS message can contain up to 140 bytes of information where-in the character quota * depends on the encoding scheme. For example, an SMS message can contain: * 160 GSM characters * 140 ASCII characters * 70 UCS-2 characters * If the message size exceeds 140 bytes, it will be split into multiple messages and sent. * When message is split into multiple messages, each partial message will be billed as a sinlge unit. * Eg. If a message size is 200 bytes; then this it be billed as 2 units. * Maximum size limit for a message is 1500 bytes. * * @param {NotificationModelsV4.MulticastSMSNotificationJobRequest} metadata * @returns {Promise<NotificationModelsV4.SMSJobResponse>} * * @memberOf NotificationClientV4 */ public async PostMulticastSMSNotificationJob( metadata: NotificationModelsV4.MulticastSMSNotificationJobRequest ): Promise<NotificationModelsV4.SMSJobResponse> { if (metadata === null || metadata === undefined) { throw new NotificationModelsV4.RequiredError( "metadata", "Required parameter metadata was null or undefined when calling PostMulticastSMSNotificationJobs." ); } const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastSMSNotificationJobs`, body: metadata, }); return result as NotificationModelsV4.SMSJobResponse; } /** * * SMS * * Shows the status of the triggered multicast sms notification job. * * @param {string} id Job ID to fetch the details * @returns {Promise<NotificationModelsV4.MulticastSMSNotificationJob>} * * @memberOf NotificationClientV4 */ public async GetMulticastSMSNotificationJob(id: string): Promise<NotificationModelsV4.MulticastSMSNotificationJob> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastSMSNotificationJobs/${id}`, }); return result as NotificationModelsV4.MulticastSMSNotificationJob; } /** * * * SMS * * Shows detailed delivery information of an sms job. * * @param {string} id Job ID to fetch the details * @param {{ page?: number; size?: number }} [params] page: specfies the page index, size: elements in a page (max:50) * @returns {Promise<NotificationModelsV4.NotificationDispatchStatusSMS>} * * @memberOf NotificationClientV4 */ public async GetMulticastSMSNotificationJobsDeliveries( id: string, params?: { page?: number; size?: number } ): Promise<NotificationModelsV4.NotificationDispatchStatusSMS> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastSMSNotificationJobs/${id}/deliveries?${toQueryString(parameters)}`, }); return result as NotificationModelsV4.NotificationDispatchStatusSMS; } /** * * Push * * Sends a push notification to selected mobile app instances. * * Publishes the notification via Mobile Push to the selected mobile app instances. * The developer can choose to address recipients using their mobile device ids or using the * recipient’s email address. When a recipient is addressed using their email address, * the Notification Service sends the notifications to all app instances registered with that email address. * * @param {NotificationModelsV4.MulticastPushNotificationJobsRequest} job * @returns {Promise<NotificationModelsV4.SMSJobResponse>} * * @memberOf NotificationClientV4 */ public async PostMulticastPushNotificationJob( job: NotificationModelsV4.MulticastPushNotificationJobsRequest ): Promise<NotificationModelsV4.SMSJobResponse> { if (job === null || job === undefined) { throw new NotificationModelsV4.RequiredError( "job", "Required parameter job was null or undefined when calling PostMulticastSMSNotificationJobs." ); } const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastPushNotificationJobs`, body: job, }); return result as NotificationModelsV4.SendResponse; } /** * ! !important! : in April 2021 there was no support in MindSphere for this method. This was reported * ! to the developer team and should eventually start working. * * @param {string} id * @returns {Promise<NotificationModelsV4.SendResponse>} * * @memberOf NotificationClientV4 */ public async GetMulticastPushNotificationJob(id: string): Promise<NotificationModelsV4.SendResponse> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/multicastPushNotificationJobs/${id}`, }); return result as NotificationModelsV4.SendResponse; } /** * * Mobile Apps * * Register a new mobile app. * * A mobile app developer should use this api to register a mobile app with the Notification Service. * This resource represents a mobile app in Notification Service. * Either an iOS or Android configuration can be chosen for the app. * Registration of the mobile app allows the developer to configure necessary push notification provider credentials. * App Configuration details are masked and not displayed in response owing to security reasons. * * @param {NotificationModelsV4.AppRegistrationRequest} appData * @returns {Promise<NotificationModelsV4.AppRegistrationResponse>} * * @memberOf NotificationClientV4 */ public async PostMobileApp( appData: NotificationModelsV4.AppRegistrationRequest ): Promise<NotificationModelsV4.AppRegistrationResponse> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), body: appData, baseUrl: `${this._baseUrl}/mobileApps`, }); return result as NotificationModelsV4.AppRegistrationRequest; } /** * * Mobile Apps * * Show all registered apps for a tenant. * App Configuration details are masked and not displayed in response owing to security reasons. * * @param {{ * page?: number; * size?: number; * }} [params] * @returns {Promise<NotificationModelsV4.PagedAppRegistrationResponse>} * * @memberOf NotificationClientV4 */ public async GetMobileApps(params?: { page?: number; size?: number; }): Promise<NotificationModelsV4.PagedAppRegistrationResponse> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/mobileApps?${toQueryString(parameters)}`, }); return result as NotificationModelsV4.PagedAppRegistrationResponse; } /** * * Mobile Apps * * Edit a registered mobile app. * App Configuration details are masked and not displayed in response * for security reasons. * * @param {string} id * @param {NotificationModelsV4.AppRegistrationUpdateRequest} appData * @returns {Promise<NotificationModelsV4.AppRegistrationResponse>} * * @memberOf NotificationClientV4 */ public async PatchMobileApp( id: string, appData: NotificationModelsV4.AppRegistrationUpdateRequest ): Promise<NotificationModelsV4.AppRegistrationResponse> { const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), body: appData, baseUrl: `${this._baseUrl}/mobileApps/${id}`, }); return result as NotificationModelsV4.AppRegistrationResponse; } /** * * Mobile Apps * * Deregister an existing registered mobile app. * * Deregistration of a mobile app involves deletion of all saved credentials and other configuration. * Any pending notification jobs which depend on this configuration will be terminated, * marked with a failed status and the notifications will not be dispatched to the intended recipients. * * @param {string} id * * @memberOf NotificationClientV4 */ public async DeleteMobileApp(id: string) { await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/mobileApps/${id}`, noResponse: true, }); } /** * * Mobile Apps * * Registers a new mobile installation instance with a registered mobile app. * * Registration is invoked when a mobile app is installed on a device and user details can be updated * by the developer based on login. * If the instance is already registered, existing instance entry shall be updated. * Push notification token detail is masked and not displayed in response owing to security reasons. * * @param {string} id * @param {NotificationModelsV4.AppInstanceRequest} appInstanceData * @returns {Promise<NotificationModelsV4.AppInstanceResponse>} * * @memberOf NotificationClientV4 */ public async PostMobileAppInstance( id: string, appInstanceData: NotificationModelsV4.AppInstanceRequest ): Promise<NotificationModelsV4.AppInstanceResponse> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), body: appInstanceData, baseUrl: `${this._baseUrl}/mobileApps/${id}/instances`, }); return result as NotificationModelsV4.AppInstanceResponse; } /** * * Mobile Apps * * Show all registered mobile app instances for a given mobile app. * Push notification token detail is masked and not displayed in response for security reasons. * * @param {string} id * @param {{ * page?: number; * size?: number; * }} [params] * @returns {Promise<NotificationModelsV4.PagedAppInstanceResponse>} * * @memberOf NotificationClientV4 */ public async GetMobileAppsInstances( id: string, params?: { page?: number; size?: number; } ): Promise<NotificationModelsV4.PagedAppInstanceResponse> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/mobileApps/${id}/instances?${toQueryString(parameters)}`, }); return result as NotificationModelsV4.PagedAppInstanceResponse; } /** * * * Mobile Apps * * Edit a specific mobile app instance registration. * Push notification token detail is masked and not displayed in response owing to security reasons. * * @param {string} id * @param {string} instanceid * @param {NotificationModelsV4.AppInstancePatchRequest} mobileAppInstanceData * @returns {Promise<NotificationModelsV4.AppInstanceResponse>} * * @memberOf NotificationClientV4 */ public async PatchMobileAppInstance( id: string, instanceid: string, mobileAppInstanceData: NotificationModelsV4.AppInstancePatchRequest ): Promise<NotificationModelsV4.AppInstanceResponse> { const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), body: mobileAppInstanceData, baseUrl: `${this._baseUrl}/mobileApps/${id}/instances/${instanceid}`, }); return result as NotificationModelsV4.AppInstanceResponse; } /** * * Mobile Apps * * Delete a specific mobile app instance registration. * * Deregistration of a mobile app involves deletion of the corresponding push notification token. * Any pending notification jobs which depend on this configuration will be terminated, * marked with a failed status and the notifications will not be dispatched to the mobile app instance. * * @param {string} id * @param {string} instanceid * * @memberOf NotificationClientV4 */ public async DeleteMobileAppsInstance(id: string, instanceid: string) { await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/mobileApps/${id}/instances/${instanceid}`, noResponse: true, }); } }
the_stack
import { TwilioCliError, env as utilsEnv } from 'flex-dev-utils'; import * as fs from 'flex-dev-utils/dist/fs'; import createTest, { mockGetPkg } from '../framework'; import FlexPlugin from '../../sub-commands/flex-plugin'; import DoneCallback = jest.DoneCallback; describe('SubCommands/FlexPlugin', () => { const { env } = process; beforeEach(() => { jest.resetAllMocks(); jest.restoreAllMocks(); process.env = { ...env }; }); it('should have flag as own property', () => { expect(FlexPlugin.hasOwnProperty('flags')).toEqual(true); }); it('should set internal args', async () => { const cmd1 = await createTest(FlexPlugin)('--arg1', '--', '--internal1'); const cmd2 = await createTest(FlexPlugin)('--', '--internal2'); const cmd3 = await createTest(FlexPlugin)('--'); const cmd4 = await createTest(FlexPlugin)('--', '--internal4a', '--internal4b'); // @ts-ignore expect(cmd1.internalScriptArgs).toEqual(['--internal1']); // @ts-ignore expect(cmd2.internalScriptArgs).toEqual(['--internal2']); // @ts-ignore expect(cmd3.internalScriptArgs).toEqual([]); // @ts-ignore expect(cmd4.internalScriptArgs).toEqual(['--internal4a', '--internal4b']); }); it('should test isPluginFolder to be false if no package.json is found', async () => { const cmd = await createTest(FlexPlugin)(); const checkAFileExists = jest.spyOn(fs, 'checkAFileExists').mockReturnValue(false); const result = cmd.isPluginFolder(); expect(result).toEqual(false); expect(checkAFileExists).toHaveBeenCalledTimes(1); }); it('should test isPluginFolder to be false if package was not found in package.json', async () => { const cmd = await createTest(FlexPlugin)(); const checkAFileExists = jest.spyOn(fs, 'checkAFileExists').mockReturnValue(true); mockGetPkg(cmd, { dependencies: {}, devDependencies: { 'not-a-valid-package': '', }, }); const result = cmd.isPluginFolder(); expect(result).toEqual(false); expect(checkAFileExists).toHaveBeenCalledTimes(1); }); it('should test isPluginFolder to be true if script is found in dependencies', async () => { const cmd = await createTest(FlexPlugin)(); const checkAFileExists = jest.spyOn(fs, 'checkAFileExists').mockReturnValue(true); mockGetPkg(cmd, { dependencies: { '@twilio/flex-ui': '', }, devDependencies: {}, }); const result = cmd.isPluginFolder(); expect(result).toEqual(true); expect(checkAFileExists).toHaveBeenCalledTimes(1); }); it('should test isPluginFolder to be true if both scripts found in devDependencies', async () => { const cmd = await createTest(FlexPlugin)(); const checkAFileExists = jest.spyOn(fs, 'checkAFileExists').mockReturnValue(true); mockGetPkg(cmd, { dependencies: {}, devDependencies: { 'flex-plugin-scripts': '', '@twilio/flex-ui': '', }, }); const result = cmd.isPluginFolder(); expect(result).toEqual(true); expect(checkAFileExists).toHaveBeenCalledTimes(1); }); it('should tet doRun throws exception', async (done) => { const cmd = await createTest(FlexPlugin)(); try { await cmd.doRun(); } catch (e) { expect(e.message).toContain(' must be implemented'); done(); } }); it('should call setEnvironment', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'doRun').mockResolvedValue('any'); await cmd.run(); expect(process.env.SKIP_CREDENTIALS_SAVING).toEqual('true'); expect(process.env.TWILIO_ACCOUNT_SID).toBeDefined(); expect(process.env.TWILIO_AUTH_TOKEN).toBeDefined(); expect(process.env.DEBUG).toBeUndefined(); }); it('should set debug env to true', async () => { const cmd = await createTest(FlexPlugin)('-l', 'debug'); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'doRun').mockResolvedValue('any'); await cmd.run(); expect(process.env.DEBUG).toEqual('true'); }); it('should run the main command successfully', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'setupEnvironment').mockReturnThis(); jest.spyOn(cmd, 'doRun').mockResolvedValue(null); await cmd.run(); expect(cmd.checkForUpdate).toHaveBeenCalledTimes(1); expect(cmd.pluginsApiToolkit).toBeDefined(); expect(cmd.pluginsClient).toBeDefined(); expect(cmd.pluginVersionsClient).toBeDefined(); expect(cmd.configurationsClient).toBeDefined(); expect(cmd.isPluginFolder).toHaveBeenCalledTimes(1); expect(cmd.setupEnvironment).toHaveBeenCalledTimes(1); expect(cmd.doRun).toHaveBeenCalledTimes(1); }); it('should return raw format', async () => { const cmd = await createTest(FlexPlugin)('--json'); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'setupEnvironment').mockReturnThis(); jest.spyOn(cmd, 'doRun').mockResolvedValue({ object: 'result' }); await cmd.run(); // @ts-ignore expect(cmd._logger.info).toHaveBeenCalledWith('{"object":"result"}'); }); it('should not return raw format', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'setupEnvironment').mockReturnThis(); jest.spyOn(cmd, 'doRun').mockResolvedValue({ object: 'result' }); await cmd.run(); // @ts-ignore expect(cmd._logger.info).not.toHaveBeenCalledWith('{"object":"result"}'); }); it('should throw exception if script needs to run in plugin directory but is not', async (done) => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(false); jest.spyOn(cmd, 'doRun').mockResolvedValue(null); try { await cmd.run(); } catch (e) { expect(e instanceof TwilioCliError).toEqual(true); expect(e.message).toContain('flex plugin directory'); done(); } }); it('should return null for builderVersion if script is not found', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: {}, dependencies: {}, }); expect(cmd.builderVersion).toBeNull(); }); it('should return version from dependencies', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: {}, dependencies: { 'flex-plugin-scripts': '1.2.3', }, }); expect(cmd.builderVersion).toEqual(1); }); it('should return version from devDependencies', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: { 'flex-plugin-scripts': '^2.3.4-beta.0', }, dependencies: {}, }); expect(cmd.builderVersion).toEqual(2); }); it('should return null if invalid version', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: { 'flex-plugin-scripts': 'not-a-semver', }, dependencies: {}, }); expect(cmd.builderVersion).toBeNull(); }); it('should quit if builder version is incorrect', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'builderVersion', 'get').mockReturnValue(3); jest.spyOn(cmd, 'checkCompatibility', 'get').mockReturnValue(true); jest.spyOn(cmd, 'exit').mockReturnThis(); jest.spyOn(cmd, 'doRun').mockReturnThis(); await cmd.run(); // @ts-ignore expect(cmd.exit).toHaveBeenCalledTimes(1); expect(cmd.exit).toHaveBeenCalledWith(1); }); it('should not quit if builder version is correct', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'checkForUpdate').mockReturnThis(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'builderVersion', 'get').mockReturnValue(4); jest.spyOn(cmd, 'checkCompatibility', 'get').mockReturnValue(true); jest.spyOn(cmd, 'exit').mockReturnThis(); jest.spyOn(cmd, 'doRun').mockReturnThis(); await cmd.run(); // @ts-ignore expect(cmd.exit).not.toHaveBeenCalled(); }); it('should have compatibility set to false', async () => { const cmd = await createTest(FlexPlugin)(); expect(cmd.checkCompatibility).toEqual(false); }); it('should set region in config client if flag is passed in', async () => { const cmd = await createTest(FlexPlugin)('--region', 'stage'); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'builderVersion', 'get').mockReturnValue(4); jest.spyOn(cmd, 'doRun').mockReturnThis(); await cmd.run(); expect(cmd.flexConfigurationClient).toHaveProperty('options.region', 'stage'); }); it('should not set a region in config client if flag is not passed in', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(cmd, 'isPluginFolder').mockReturnValue(true); jest.spyOn(cmd, 'builderVersion', 'get').mockReturnValue(4); jest.spyOn(cmd, 'doRun').mockReturnThis(); await cmd.run(); expect(cmd.flexConfigurationClient).not.toHaveProperty('options.region'); }); describe('setupEnvironment', () => { const username = 'test-username'; const password = 'test-password'; const id = 'testProfile'; const setupMocks = (cmd: FlexPlugin) => { // @ts-ignore cmd.currentProfile = { id }; // @ts-ignore jest.spyOn(cmd, 'twilioClient', 'get').mockReturnValue({ username, password }); jest.spyOn(utilsEnv, 'setTwilioProfile'); jest.spyOn(utilsEnv, 'setDebug'); jest.spyOn(utilsEnv, 'persistTerminal'); jest.spyOn(utilsEnv, 'setRegion'); }; it('should setup environment', async () => { const cmd = await createTest(FlexPlugin)(); setupMocks(cmd); cmd.setupEnvironment(); expect(process.env.SKIP_CREDENTIALS_SAVING).toEqual('true'); expect(process.env.TWILIO_ACCOUNT_SID).toEqual(username); expect(process.env.TWILIO_AUTH_TOKEN).toEqual(password); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledTimes(1); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledWith(id); expect(utilsEnv.setDebug).not.toHaveBeenCalled(); expect(utilsEnv.persistTerminal).not.toHaveBeenCalled(); expect(utilsEnv.setRegion).not.toHaveBeenCalled(); }); it('should setup environment as debug level', async () => { const cmd = await createTest(FlexPlugin)('-l', 'debug'); setupMocks(cmd); cmd.setupEnvironment(); expect(process.env.SKIP_CREDENTIALS_SAVING).toEqual('true'); expect(process.env.TWILIO_ACCOUNT_SID).toEqual(username); expect(process.env.TWILIO_AUTH_TOKEN).toEqual(password); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledTimes(1); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledWith(id); expect(utilsEnv.setDebug).toHaveBeenCalledTimes(1); expect(utilsEnv.persistTerminal).toHaveBeenCalledTimes(1); expect(utilsEnv.setRegion).not.toHaveBeenCalled(); }); it('should setup environment and twilio region', async () => { const cmd = await createTest(FlexPlugin)('--region', 'stage'); setupMocks(cmd); cmd.setupEnvironment(); expect(process.env.SKIP_CREDENTIALS_SAVING).toEqual('true'); expect(process.env.TWILIO_ACCOUNT_SID).toEqual(username); expect(process.env.TWILIO_AUTH_TOKEN).toEqual(password); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledTimes(1); expect(utilsEnv.setTwilioProfile).toHaveBeenCalledWith(id); expect(utilsEnv.setDebug).not.toHaveBeenCalled(); expect(utilsEnv.persistTerminal).not.toHaveBeenCalled(); expect(utilsEnv.setRegion).toHaveBeenCalledWith('stage'); }); }); describe('pkg', () => { it('should set default empty object if devDep or dep not set', async () => { const cmd = await createTest(FlexPlugin)(); jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: null, dependencies: null, }); expect(cmd.pkg.dependencies).toEqual({}); expect(cmd.pkg.devDependencies).toEqual({}); }); it('should have devDep and dep', async () => { const cmd = await createTest(FlexPlugin)(); const dep = { package1: '123' }; const devDep = { package2: '234' }; jest.spyOn(fs, 'readJsonFile').mockReturnValue({ devDependencies: devDep, dependencies: dep, }); expect(cmd.pkg.dependencies).toEqual(dep); expect(cmd.pkg.devDependencies).toEqual(devDep); }); }); describe('client initialization', () => { const callAndVerifyNotInitialized = async (method: string, done: DoneCallback) => { const cmd = await createTest(FlexPlugin)(); try { // eslint-disable-next-line @typescript-eslint/no-unused-vars const client = cmd[method]; } catch (e) { expect(e.message).toContain('is not initialized'); done(); } }; const callAndVerifyInitialized = async (method: string) => { const cmd = await createTest(FlexPlugin)(); const client = `the-${method}-client`; cmd[`_${method}`] = client; expect(cmd[method]).toEqual(client); }; it('should throw error if _pluginsApiToolkit is undefined', async (done) => { await callAndVerifyNotInitialized('pluginsApiToolkit', done); }); it('should get _pluginsApiToolkit', async () => { await callAndVerifyInitialized('pluginsApiToolkit'); }); it('should throw error if _pluginsClient is undefined', async (done) => { await callAndVerifyNotInitialized('pluginsClient', done); }); it('should throw error if _pluginsClient is undefined', async () => { await callAndVerifyInitialized('pluginsClient'); }); it('should throw error if _pluginVersionsClient is undefined', async (done) => { await callAndVerifyNotInitialized('pluginVersionsClient', done); }); it('should get _pluginVersionsClient', async () => { await callAndVerifyInitialized('pluginVersionsClient'); }); it('should throw error if _configurationsClient is undefined', async (done) => { await callAndVerifyNotInitialized('configurationsClient', done); }); it('should get _configurationsClient', async () => { await callAndVerifyInitialized('configurationsClient'); }); it('should throw error if _releasesClient is undefined', async (done) => { await callAndVerifyNotInitialized('releasesClient', done); }); it('should get _releasesClient', async () => { await callAndVerifyInitialized('releasesClient'); }); it('should throw error if _flexConfigurationClient is undefined', async (done) => { await callAndVerifyNotInitialized('flexConfigurationClient', done); }); it('should get _flexConfigurationClient', async () => { await callAndVerifyInitialized('flexConfigurationClient'); }); it('should throw error if _serverlessClient is undefined', async (done) => { await callAndVerifyNotInitialized('serverlessClient', done); }); it('should get _serverlessClient', async () => { await callAndVerifyInitialized('serverlessClient'); }); }); });
the_stack
import * as OriginSequelize from 'sequelize'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { BeforeCreate, Sequelize } from '../../../src'; import { Column, Model, Table } from '../../../src'; import { Hook } from '../../models/Hook'; import { createSequelize } from '../../utils/sequelize'; const expect = chai.expect; chai.use(sinonChai); describe('hook', () => { let sequelize: Sequelize; before(() => { sequelize = createSequelize(false); }); beforeEach(() => { return sequelize.sync({ force: true }); }); it('should throw on non-static hooks', () => { expect(() => { @Table // eslint-disable-next-line @typescript-eslint/no-unused-vars class User extends Model { @Column firstName: string; @Column lastName: string; @BeforeCreate nonStaticHookFunction(): void { // nonStaticHookFunction } } }).to.throw(Error, /not a static method/); }); it('should throw on methods with reserved names', () => { expect(() => { @Table // eslint-disable-next-line @typescript-eslint/no-unused-vars class User extends Model { @Column firstName: string; @Column lastName: string; @BeforeCreate static beforeCreate(): void { // beforeCreate } } }).to.throw(Error, /name is reserved/); }); it('should install all hooks', () => { const beforeValidateHookStub = sinon.stub(Hook, 'beforeValidateHook'); const afterValidateHookStub = sinon.stub(Hook, 'afterValidateHook'); const validationFailedHookStub = sinon.stub(Hook, 'validationFailedHook'); const beforeCreateHookStub = sinon.stub(Hook, 'beforeCreateHook'); const afterCreateHookStub = sinon.stub(Hook, 'afterCreateHook'); const beforeDestroyHookStub = sinon.stub(Hook, 'beforeDestroyHook'); const afterDestroyHookStub = sinon.stub(Hook, 'afterDestroyHook'); const beforeRestoreHookStub = sinon.stub(Hook, 'beforeRestoreHook'); const afterRestoreHookStub = sinon.stub(Hook, 'afterRestoreHook'); const beforeUpdateHookStub = sinon.stub(Hook, 'beforeUpdateHook'); const afterUpdateHookStub = sinon.stub(Hook, 'afterUpdateHook'); const beforeBulkCreateHookStub = sinon.stub(Hook, 'beforeBulkCreateHook'); const afterBulkCreateHookStub = sinon.stub(Hook, 'afterBulkCreateHook'); const beforeBulkDestroyHookStub = sinon.stub(Hook, 'beforeBulkDestroyHook'); const afterBulkDestroyHookStub = sinon.stub(Hook, 'afterBulkDestroyHook'); const beforeBulkRestoreHookStub = sinon.stub(Hook, 'beforeBulkRestoreHook'); const afterBulkRestoreHookStub = sinon.stub(Hook, 'afterBulkRestoreHook'); const beforeBulkUpdateHookStub = sinon.stub(Hook, 'beforeBulkUpdateHook'); const afterBulkUpdateHookStub = sinon.stub(Hook, 'afterBulkUpdateHook'); const beforeFindHookStub = sinon.stub(Hook, 'beforeFindHook'); const beforeFindAfterExpandIncludeAllHookStub = sinon.stub( Hook, 'beforeFindAfterExpandIncludeAllHook' ); const beforeFindAfterOptionsHookStub = sinon.stub(Hook, 'beforeFindAfterOptionsHook'); const afterFindHookStub = sinon.stub(Hook, 'afterFindHook'); const beforeCountHookStub = sinon.stub(Hook, 'beforeCountHook'); const beforeBulkSyncHookStub = sinon.stub(Hook, 'beforeBulkSyncHook'); const afterBulkSyncHookStub = sinon.stub(Hook, 'afterBulkSyncHook'); const beforeConnectHookStub = sinon.stub(Hook, 'beforeConnectHook'); const afterConnectHookStub = sinon.stub(Hook, 'afterConnectHook'); const beforeDefineHookStub = sinon.stub(Hook, 'beforeDefineHook'); const afterDefineHookStub = sinon.stub(Hook, 'afterDefineHook'); const beforeInitHookStub = sinon.stub(Hook, 'beforeInitHook'); const afterInitHookStub = sinon.stub(Hook, 'afterInitHook'); // some hooks are only available in Sequelize v4 let beforeSaveHookStub: sinon.SinonStub; let afterSaveHookStub: sinon.SinonStub; let beforeUpsertHookStub: sinon.SinonStub; let afterUpsertHookStub: sinon.SinonStub; if (OriginSequelize['version'].split('.')[0] === '4') { beforeSaveHookStub = sinon.stub(Hook, 'beforeSaveHook'); afterSaveHookStub = sinon.stub(Hook, 'afterSaveHook'); beforeUpsertHookStub = sinon.stub(Hook, 'beforeUpsertHook'); afterUpsertHookStub = sinon.stub(Hook, 'afterUpsertHook'); } const beforeValidateHookWithNameStub = sinon.stub(Hook, 'beforeValidateHookWithName'); const afterValidateHookWithNameStub = sinon.stub(Hook, 'afterValidateHookWithName'); const validationFailedHookWithNameStub = sinon.stub(Hook, 'validationFailedHookWithName'); const beforeCreateHookWithNameStub = sinon.stub(Hook, 'beforeCreateHookWithName'); const afterCreateHookWithNameStub = sinon.stub(Hook, 'afterCreateHookWithName'); const beforeDestroyHookWithNameStub = sinon.stub(Hook, 'beforeDestroyHookWithName'); const afterDestroyHookWithNameStub = sinon.stub(Hook, 'afterDestroyHookWithName'); const beforeRestoreHookWithNameStub = sinon.stub(Hook, 'beforeRestoreHookWithName'); const afterRestoreHookWithNameStub = sinon.stub(Hook, 'afterRestoreHookWithName'); const beforeUpdateHookWithNameStub = sinon.stub(Hook, 'beforeUpdateHookWithName'); const afterUpdateHookWithNameStub = sinon.stub(Hook, 'afterUpdateHookWithName'); const beforeBulkCreateHookWithNameStub = sinon.stub(Hook, 'beforeBulkCreateHookWithName'); const afterBulkCreateHookWithNameStub = sinon.stub(Hook, 'afterBulkCreateHookWithName'); const beforeBulkDestroyHookWithNameStub = sinon.stub(Hook, 'beforeBulkDestroyHookWithName'); const afterBulkDestroyHookWithNameStub = sinon.stub(Hook, 'afterBulkDestroyHookWithName'); const beforeBulkRestoreHookWithNameStub = sinon.stub(Hook, 'beforeBulkRestoreHookWithName'); const afterBulkRestoreHookWithNameStub = sinon.stub(Hook, 'afterBulkRestoreHookWithName'); const beforeBulkUpdateHookWithNameStub = sinon.stub(Hook, 'beforeBulkUpdateHookWithName'); const afterBulkUpdateHookWithNameStub = sinon.stub(Hook, 'afterBulkUpdateHookWithName'); const beforeFindHookWithNameStub = sinon.stub(Hook, 'beforeFindHookWithName'); const beforeFindAfterExpandIncludeAllHookWithNameStub = sinon.stub( Hook, 'beforeFindAfterExpandIncludeAllHookWithName' ); const beforeFindAfterOptionsHookWithNameStub = sinon.stub( Hook, 'beforeFindAfterOptionsHookWithName' ); const afterFindHookWithNameStub = sinon.stub(Hook, 'afterFindHookWithName'); const beforeCountHookWithNameStub = sinon.stub(Hook, 'beforeCountHookWithName'); // some hooks are only available in Sequelize v4 let beforeSaveHookWithNameStub: sinon.SinonStub; let afterSaveHookWithNameStub: sinon.SinonStub; let beforeUpsertHookWithNameStub: sinon.SinonStub; let afterUpsertHookWithNameStub: sinon.SinonStub; if (OriginSequelize['version'].split('.')[0] === '4') { beforeSaveHookWithNameStub = sinon.stub(Hook, 'beforeSaveHookWithName'); afterSaveHookWithNameStub = sinon.stub(Hook, 'afterSaveHookWithName'); beforeUpsertHookWithNameStub = sinon.stub(Hook, 'beforeUpsertHookWithName'); afterUpsertHookWithNameStub = sinon.stub(Hook, 'afterUpsertHookWithName'); } sequelize.addModels([Hook]); // Sequelize provides no public API to retrieve existing hooks. We are relying on an // implementation detail: that the addHook method works by adding the specified // function to the Model’s options.hooks object. // // We are not testing that the hooks are called: that’s in Sequelize’s domain. Our job // is to ensure that the hooks are installed. expect(Hook['options'].hooks['beforeValidate']).to.include(beforeValidateHookStub); expect(Hook['options'].hooks['afterValidate']).to.include(afterValidateHookStub); expect(Hook['options'].hooks['validationFailed']).to.include(validationFailedHookStub); expect(Hook['options'].hooks['beforeCreate']).to.include(beforeCreateHookStub); expect(Hook['options'].hooks['afterCreate']).to.include(afterCreateHookStub); expect(Hook['options'].hooks['beforeDestroy']).to.include(beforeDestroyHookStub); expect(Hook['options'].hooks['afterDestroy']).to.include(afterDestroyHookStub); expect(Hook['options'].hooks['beforeRestore']).to.include(beforeRestoreHookStub); expect(Hook['options'].hooks['afterRestore']).to.include(afterRestoreHookStub); expect(Hook['options'].hooks['beforeUpdate']).to.include(beforeUpdateHookStub); expect(Hook['options'].hooks['afterUpdate']).to.include(afterUpdateHookStub); expect(Hook['options'].hooks['beforeBulkCreate']).to.include(beforeBulkCreateHookStub); expect(Hook['options'].hooks['afterBulkCreate']).to.include(afterBulkCreateHookStub); expect(Hook['options'].hooks['beforeBulkDestroy']).to.include(beforeBulkDestroyHookStub); expect(Hook['options'].hooks['afterBulkDestroy']).to.include(afterBulkDestroyHookStub); expect(Hook['options'].hooks['beforeBulkRestore']).to.include(beforeBulkRestoreHookStub); expect(Hook['options'].hooks['afterBulkRestore']).to.include(afterBulkRestoreHookStub); expect(Hook['options'].hooks['beforeBulkUpdate']).to.include(beforeBulkUpdateHookStub); expect(Hook['options'].hooks['afterBulkUpdate']).to.include(afterBulkUpdateHookStub); expect(Hook['options'].hooks['beforeFind']).to.include(beforeFindHookStub); expect(Hook['options'].hooks['beforeFindAfterExpandIncludeAll']).to.include( beforeFindAfterExpandIncludeAllHookStub ); expect(Hook['options'].hooks['beforeFindAfterOptions']).to.include( beforeFindAfterOptionsHookStub ); expect(Hook['options'].hooks['afterFind']).to.include(afterFindHookStub); expect(Hook['options'].hooks['beforeCount']).to.include(beforeCountHookStub); expect(Hook['options'].hooks['beforeBulkSync']).to.include(beforeBulkSyncHookStub); expect(Hook['options'].hooks['afterBulkSync']).to.include(afterBulkSyncHookStub); expect(Hook['options'].hooks['beforeConnect']).to.include(beforeConnectHookStub); expect(Hook['options'].hooks['afterConnect']).to.include(afterConnectHookStub); expect(Hook['options'].hooks['beforeDefine']).to.include(beforeDefineHookStub); expect(Hook['options'].hooks['afterDefine']).to.include(afterDefineHookStub); expect(Hook['options'].hooks['beforeInit']).to.include(beforeInitHookStub); expect(Hook['options'].hooks['afterInit']).to.include(afterInitHookStub); if (OriginSequelize['version'].split('.')[0] === '4') { expect(Hook['options'].hooks['beforeSave']).to.include(beforeSaveHookStub); expect(Hook['options'].hooks['afterSave']).to.include(afterSaveHookStub); expect(Hook['options'].hooks['beforeUpsert']).to.include(beforeUpsertHookStub); expect(Hook['options'].hooks['afterUpsert']).to.include(afterUpsertHookStub); } // Named hooks expect(Hook['options'].hooks['beforeValidate']).to.deep.include({ name: 'myBeforeValidateHook', fn: beforeValidateHookWithNameStub, }); expect(Hook['options'].hooks['afterValidate']).to.deep.include({ name: 'myAfterValidateHook', fn: afterValidateHookWithNameStub, }); expect(Hook['options'].hooks['validationFailed']).to.deep.include({ name: 'myValidationFailedHook', fn: validationFailedHookWithNameStub, }); expect(Hook['options'].hooks['beforeCreate']).to.deep.include({ name: 'myBeforeCreateHook', fn: beforeCreateHookWithNameStub, }); expect(Hook['options'].hooks['afterCreate']).to.deep.include({ name: 'myAfterCreateHook', fn: afterCreateHookWithNameStub, }); expect(Hook['options'].hooks['beforeDestroy']).to.deep.include({ name: 'myBeforeDestroyHook', fn: beforeDestroyHookWithNameStub, }); expect(Hook['options'].hooks['afterDestroy']).to.deep.include({ name: 'myAfterDestroyHook', fn: afterDestroyHookWithNameStub, }); expect(Hook['options'].hooks['beforeRestore']).to.deep.include({ name: 'myBeforeRestoreHook', fn: beforeRestoreHookWithNameStub, }); expect(Hook['options'].hooks['afterRestore']).to.deep.include({ name: 'myAfterRestoreHook', fn: afterRestoreHookWithNameStub, }); expect(Hook['options'].hooks['beforeUpdate']).to.deep.include({ name: 'myBeforeUpdateHook', fn: beforeUpdateHookWithNameStub, }); expect(Hook['options'].hooks['afterUpdate']).to.deep.include({ name: 'myAfterUpdateHook', fn: afterUpdateHookWithNameStub, }); expect(Hook['options'].hooks['beforeBulkCreate']).to.deep.include({ name: 'myBeforeBulkCreateHook', fn: beforeBulkCreateHookWithNameStub, }); expect(Hook['options'].hooks['afterBulkCreate']).to.deep.include({ name: 'myAfterBulkCreateHook', fn: afterBulkCreateHookWithNameStub, }); expect(Hook['options'].hooks['beforeBulkDestroy']).to.deep.include({ name: 'myBeforeBulkDestroyHook', fn: beforeBulkDestroyHookWithNameStub, }); expect(Hook['options'].hooks['afterBulkDestroy']).to.deep.include({ name: 'myAfterBulkDestroyHook', fn: afterBulkDestroyHookWithNameStub, }); expect(Hook['options'].hooks['beforeBulkRestore']).to.deep.include({ name: 'myBeforeBulkRestoreHook', fn: beforeBulkRestoreHookWithNameStub, }); expect(Hook['options'].hooks['afterBulkRestore']).to.deep.include({ name: 'myAfterBulkRestoreHook', fn: afterBulkRestoreHookWithNameStub, }); expect(Hook['options'].hooks['beforeBulkUpdate']).to.deep.include({ name: 'myBeforeBulkUpdateHook', fn: beforeBulkUpdateHookWithNameStub, }); expect(Hook['options'].hooks['afterBulkUpdate']).to.deep.include({ name: 'myAfterBulkUpdateHook', fn: afterBulkUpdateHookWithNameStub, }); expect(Hook['options'].hooks['beforeFind']).to.deep.include({ name: 'myBeforeFindHook', fn: beforeFindHookWithNameStub, }); expect(Hook['options'].hooks['beforeFindAfterExpandIncludeAll']).to.deep.include({ name: 'myBeforeFindAfterExpandIncludeAllHook', fn: beforeFindAfterExpandIncludeAllHookWithNameStub, }); expect(Hook['options'].hooks['beforeFindAfterOptions']).to.deep.include({ name: 'myBeforeFindAfterOptionsHook', fn: beforeFindAfterOptionsHookWithNameStub, }); expect(Hook['options'].hooks['afterFind']).to.deep.include({ name: 'myAfterFindHook', fn: afterFindHookWithNameStub, }); expect(Hook['options'].hooks['beforeCount']).to.deep.include({ name: 'myBeforeCountHook', fn: beforeCountHookWithNameStub, }); if (OriginSequelize['version'].split('.')[0] === '4') { expect(Hook['options'].hooks['beforeSave']).to.deep.include({ name: 'myBeforeSaveHook', fn: beforeSaveHookWithNameStub, }); expect(Hook['options'].hooks['afterSave']).to.deep.include({ name: 'myAfterSaveHook', fn: afterSaveHookWithNameStub, }); expect(Hook['options'].hooks['beforeUpsert']).to.deep.include({ name: 'myBeforeUpsertHook', fn: beforeUpsertHookWithNameStub, }); expect(Hook['options'].hooks['afterUpsert']).to.deep.include({ name: 'myAfterUpsertHook', fn: afterUpsertHookWithNameStub, }); } }); });
the_stack
declare namespace gsap { // GSAP specific interface CSSProperties { [key: string]: any; alpha: TweenValue; autoAlpha: TweenValue; rotate: TweenValue; rotateX: TweenValue; rotateY: TweenValue; rotateZ: TweenValue; rotation: TweenValue; rotationX: TweenValue; rotationY: TweenValue; rotationZ: TweenValue; scale: TweenValue; scaleX: TweenValue; scaleY: TweenValue; skew: TweenValue; skewX: TweenValue; skewY: TweenValue; smoothOrigin: BooleanValue; svgOrigin: TweenValue; translateX: TweenValue; translateY: TweenValue; translateZ: TweenValue; x: TweenValue; xPercent: TweenValue; y: TweenValue; yPercent: TweenValue; z: TweenValue; } interface CSSProperties { alignContent: TweenValue; alignItems: TweenValue; alignSelf: TweenValue; alignmentBaseline: TweenValue; animation: TweenValue; animationDelay: TweenValue; animationDirection: TweenValue; animationDuration: TweenValue; animationFillMode: TweenValue; animationIterationCount: TweenValue; animationName: TweenValue; animationPlayState: TweenValue; animationTimingFunction: TweenValue; backfaceVisibility: TweenValue; background: TweenValue; backgroundAttachment: TweenValue; backgroundClip: TweenValue; backgroundColor: TweenValue; backgroundImage: TweenValue; backgroundOrigin: TweenValue; backgroundPosition: TweenValue; backgroundPositionX: TweenValue; backgroundPositionY: TweenValue; backgroundRepeat: TweenValue; backgroundSize: TweenValue; baselineShift: TweenValue; border: TweenValue; borderBottom: TweenValue; borderBottomColor: TweenValue; borderBottomLeftRadius: TweenValue; borderBottomRightRadius: TweenValue; borderBottomStyle: TweenValue; borderBottomWidth: TweenValue; borderCollapse: TweenValue; borderColor: TweenValue; borderImage: TweenValue; borderImageOutset: TweenValue; borderImageRepeat: TweenValue; borderImageSlice: TweenValue; borderImageSource: TweenValue; borderImageWidth: TweenValue; borderLeft: TweenValue; borderLeftColor: TweenValue; borderLeftStyle: TweenValue; borderLeftWidth: TweenValue; borderRadius: TweenValue; borderRight: TweenValue; borderRightColor: TweenValue; borderRightStyle: TweenValue; borderRightWidth: TweenValue; borderSpacing: TweenValue; borderStyle: TweenValue; borderTop: TweenValue; borderTopColor: TweenValue; borderTopLeftRadius: TweenValue; borderTopRightRadius: TweenValue; borderTopStyle: TweenValue; borderTopWidth: TweenValue; borderWidth: TweenValue; bottom: TweenValue; boxShadow: TweenValue; boxSizing: TweenValue; breakAfter: TweenValue; breakBefore: TweenValue; breakInside: TweenValue; captionSide: TweenValue; caretColor: TweenValue; clear: TweenValue; clip: TweenValue; clipPath: TweenValue; clipRule: TweenValue; color: TweenValue; colorInterpolationFilters: TweenValue; columnCount: TweenValue; columnFill: TweenValue; columnGap: TweenValue; columnRule: TweenValue; columnRuleColor: TweenValue; columnRuleStyle: TweenValue; columnRuleWidth: TweenValue; columnSpan: TweenValue; columnWidth: TweenValue; columns: TweenValue; content: TweenValue; counterIncrement: TweenValue; counterReset: TweenValue; cssFloat: TweenValue; cssText: TweenValue; cursor: TweenValue; direction: TweenValue; display: TweenValue; dominantBaseline: TweenValue; emptyCells: TweenValue; enableBackground: TweenValue; fill: TweenValue; fillOpacity: TweenValue; fillRule: TweenValue; filter: TweenValue; flex: TweenValue; flexBasis: TweenValue; flexDirection: TweenValue; flexFlow: TweenValue; flexGrow: TweenValue; flexShrink: TweenValue; flexWrap: TweenValue; floodColor: TweenValue; floodOpacity: TweenValue; font: TweenValue; fontFamily: TweenValue; fontFeatureSettings: TweenValue; fontKerning: TweenValue; fontSize: TweenValue; fontSizeAdjust: TweenValue; fontStretch: TweenValue; fontStyle: TweenValue; fontSynthesis: TweenValue; fontVariant: TweenValue; fontVariantCaps: TweenValue; fontVariantEastAsian: TweenValue; fontVariantLigatures: TweenValue; fontVariantNumeric: TweenValue; fontVariantPosition: TweenValue; fontWeight: TweenValue; gap: TweenValue; glyphOrientationHorizontal: TweenValue; glyphOrientationVertical: TweenValue; grid: TweenValue; gridArea: TweenValue; gridAutoColumns: TweenValue; gridAutoFlow: TweenValue; gridAutoRows: TweenValue; gridColumn: TweenValue; gridColumnEnd: TweenValue; gridColumnGap: TweenValue; gridColumnStart: TweenValue; gridGap: TweenValue; gridRow: TweenValue; gridRowEnd: TweenValue; gridRowGap: TweenValue; gridRowStart: TweenValue; gridTemplate: TweenValue; gridTemplateAreas: TweenValue; gridTemplateColumns: TweenValue; gridTemplateRows: TweenValue; height: TweenValue; hyphens: TweenValue; imageOrientation: TweenValue; imageRendering: TweenValue; imeMode: TweenValue; justifyContent: TweenValue; justifyItems: TweenValue; justifySelf: TweenValue; kerning: TweenValue; layoutGrid: TweenValue; layoutGridChar: TweenValue; layoutGridLine: TweenValue; layoutGridMode: TweenValue; layoutGridType: TweenValue; left: TweenValue; letterSpacing: TweenValue; lightingColor: TweenValue; lineBreak: TweenValue; lineHeight: TweenValue; listStyle: TweenValue; listStyleImage: TweenValue; listStylePosition: TweenValue; listStyleType: TweenValue; margin: TweenValue; marginBottom: TweenValue; marginLeft: TweenValue; marginRight: TweenValue; marginTop: TweenValue; marker: TweenValue; markerEnd: TweenValue; markerMid: TweenValue; markerStart: TweenValue; mask: TweenValue; maskComposite: TweenValue; maskImage: TweenValue; maskPosition: TweenValue; maskRepeat: TweenValue; maskSize: TweenValue; maskType: TweenValue; maxHeight: TweenValue; maxWidth: TweenValue; minHeight: TweenValue; minWidth: TweenValue; msContentZoomChaining: TweenValue; msContentZoomLimit: TweenValue; msContentZoomLimitMax: any; msContentZoomLimitMin: any; msContentZoomSnap: TweenValue; msContentZoomSnapPoints: TweenValue; msContentZoomSnapType: TweenValue; msContentZooming: TweenValue; msFlowFrom: TweenValue; msFlowInto: TweenValue; msFontFeatureSettings: TweenValue; msGridColumn: any; msGridColumnAlign: TweenValue; msGridColumnSpan: any; msGridColumns: TweenValue; msGridRow: any; msGridRowAlign: TweenValue; msGridRowSpan: any; msGridRows: TweenValue; msHighContrastAdjust: TweenValue; msHyphenateLimitChars: TweenValue; msHyphenateLimitLines: any; msHyphenateLimitZone: any; msHyphens: TweenValue; msImeAlign: TweenValue; msOverflowStyle: TweenValue; msScrollChaining: TweenValue; msScrollLimit: TweenValue; msScrollLimitXMax: any; msScrollLimitXMin: any; msScrollLimitYMax: any; msScrollLimitYMin: any; msScrollRails: TweenValue; msScrollSnapPointsX: TweenValue; msScrollSnapPointsY: TweenValue; msScrollSnapType: TweenValue; msScrollSnapX: TweenValue; msScrollSnapY: TweenValue; msScrollTranslation: TweenValue; msTextCombineHorizontal: TweenValue; msTextSizeAdjust: any; msTouchAction: TweenValue; msTouchSelect: TweenValue; msUserSelect: TweenValue; msWrapFlow: TweenValue; msWrapMargin: any; msWrapThrough: TweenValue; objectFit: TweenValue; objectPosition: TweenValue; opacity: TweenValue; order: TweenValue; orphans: TweenValue; outline: TweenValue; outlineColor: TweenValue; outlineOffset: TweenValue; outlineStyle: TweenValue; outlineWidth: TweenValue; overflow: TweenValue; overflowAnchor: TweenValue; overflowWrap: TweenValue; overflowX: TweenValue; overflowY: TweenValue; padding: TweenValue; paddingBottom: TweenValue; paddingLeft: TweenValue; paddingRight: TweenValue; paddingTop: TweenValue; pageBreakAfter: TweenValue; pageBreakBefore: TweenValue; pageBreakInside: TweenValue; penAction: TweenValue; perspective: TweenValue; perspectiveOrigin: TweenValue; placeContent: TweenValue; placeItems: TweenValue; placeSelf: TweenValue; pointerEvents: TweenValue; position: TweenValue; quotes: TweenValue; resize: TweenValue; right: TweenValue; rotate: TweenValue; rowGap: TweenValue; rubyAlign: TweenValue; rubyOverhang: TweenValue; rubyPosition: TweenValue; scale: TweenValue; scrollBehavior: TweenValue; stopColor: TweenValue; stopOpacity: TweenValue; stroke: TweenValue; strokeDasharray: TweenValue; strokeDashoffset: TweenValue; strokeLinecap: TweenValue; strokeLinejoin: TweenValue; strokeMiterlimit: TweenValue; strokeOpacity: TweenValue; strokeWidth: TweenValue; tabSize: TweenValue; tableLayout: TweenValue; textAlign: TweenValue; textAlignLast: TweenValue; textAnchor: TweenValue; textCombineUpright: TweenValue; textDecoration: TweenValue; textDecorationColor: TweenValue; textDecorationLine: TweenValue; textDecorationStyle: TweenValue; textEmphasis: TweenValue; textEmphasisColor: TweenValue; textEmphasisPosition: TweenValue; textEmphasisStyle: TweenValue; textIndent: TweenValue; textJustify: TweenValue; textKashida: TweenValue; textKashidaSpace: TweenValue; textOrientation: TweenValue; textOverflow: TweenValue; textShadow: TweenValue; textTransform: TweenValue; textUnderlinePosition: TweenValue; top: TweenValue; touchAction: TweenValue; transform: TweenValue; transformBox: TweenValue; transformOrigin: TweenValue; transformStyle: TweenValue; transition: TweenValue; transitionDelay: TweenValue; transitionDuration: TweenValue; transitionProperty: TweenValue; transitionTimingFunction: TweenValue; translate: TweenValue; unicodeBidi: TweenValue; userSelect: TweenValue; verticalAlign: TweenValue; visibility: TweenValue; /** @deprecated */ webkitAlignContent: TweenValue; /** @deprecated */ webkitAlignItems: TweenValue; /** @deprecated */ webkitAlignSelf: TweenValue; /** @deprecated */ webkitAnimation: TweenValue; /** @deprecated */ webkitAnimationDelay: TweenValue; /** @deprecated */ webkitAnimationDirection: TweenValue; /** @deprecated */ webkitAnimationDuration: TweenValue; /** @deprecated */ webkitAnimationFillMode: TweenValue; /** @deprecated */ webkitAnimationIterationCount: TweenValue; /** @deprecated */ webkitAnimationName: TweenValue; /** @deprecated */ webkitAnimationPlayState: TweenValue; /** @deprecated */ webkitAnimationTimingFunction: TweenValue; /** @deprecated */ webkitAppearance: TweenValue; /** @deprecated */ webkitBackfaceVisibility: TweenValue; /** @deprecated */ webkitBackgroundClip: TweenValue; /** @deprecated */ webkitBackgroundOrigin: TweenValue; /** @deprecated */ webkitBackgroundSize: TweenValue; /** @deprecated */ webkitBorderBottomLeftRadius: TweenValue; /** @deprecated */ webkitBorderBottomRightRadius: TweenValue; webkitBorderImage: TweenValue; /** @deprecated */ webkitBorderRadius: TweenValue; /** @deprecated */ webkitBorderTopLeftRadius: TweenValue; /** @deprecated */ webkitBorderTopRightRadius: TweenValue; /** @deprecated */ webkitBoxAlign: TweenValue; webkitBoxDirection: TweenValue; /** @deprecated */ webkitBoxFlex: TweenValue; /** @deprecated */ webkitBoxOrdinalGroup: TweenValue; webkitBoxOrient: TweenValue; /** @deprecated */ webkitBoxPack: TweenValue; /** @deprecated */ webkitBoxShadow: TweenValue; /** @deprecated */ webkitBoxSizing: TweenValue; webkitColumnBreakAfter: TweenValue; webkitColumnBreakBefore: TweenValue; webkitColumnBreakInside: TweenValue; webkitColumnCount: any; webkitColumnGap: any; webkitColumnRule: TweenValue; webkitColumnRuleColor: any; webkitColumnRuleStyle: TweenValue; webkitColumnRuleWidth: any; webkitColumnSpan: TweenValue; webkitColumnWidth: any; webkitColumns: TweenValue; /** @deprecated */ webkitFilter: TweenValue; /** @deprecated */ webkitFlex: TweenValue; /** @deprecated */ webkitFlexBasis: TweenValue; /** @deprecated */ webkitFlexDirection: TweenValue; /** @deprecated */ webkitFlexFlow: TweenValue; /** @deprecated */ webkitFlexGrow: TweenValue; /** @deprecated */ webkitFlexShrink: TweenValue; /** @deprecated */ webkitFlexWrap: TweenValue; /** @deprecated */ webkitJustifyContent: TweenValue; webkitLineClamp: TweenValue; /** @deprecated */ webkitMask: TweenValue; /** @deprecated */ webkitMaskBoxImage: TweenValue; /** @deprecated */ webkitMaskBoxImageOutset: TweenValue; /** @deprecated */ webkitMaskBoxImageRepeat: TweenValue; /** @deprecated */ webkitMaskBoxImageSlice: TweenValue; /** @deprecated */ webkitMaskBoxImageSource: TweenValue; /** @deprecated */ webkitMaskBoxImageWidth: TweenValue; /** @deprecated */ webkitMaskClip: TweenValue; /** @deprecated */ webkitMaskComposite: TweenValue; /** @deprecated */ webkitMaskImage: TweenValue; /** @deprecated */ webkitMaskOrigin: TweenValue; /** @deprecated */ webkitMaskPosition: TweenValue; /** @deprecated */ webkitMaskRepeat: TweenValue; /** @deprecated */ webkitMaskSize: TweenValue; /** @deprecated */ webkitOrder: TweenValue; /** @deprecated */ webkitPerspective: TweenValue; /** @deprecated */ webkitPerspectiveOrigin: TweenValue; webkitTapHighlightColor: TweenValue; /** @deprecated */ webkitTextFillColor: TweenValue; /** @deprecated */ webkitTextSizeAdjust: TweenValue; /** @deprecated */ webkitTextStroke: TweenValue; /** @deprecated */ webkitTextStrokeColor: TweenValue; /** @deprecated */ webkitTextStrokeWidth: TweenValue; /** @deprecated */ webkitTransform: TweenValue; /** @deprecated */ webkitTransformOrigin: TweenValue; /** @deprecated */ webkitTransformStyle: TweenValue; /** @deprecated */ webkitTransition: TweenValue; /** @deprecated */ webkitTransitionDelay: TweenValue; /** @deprecated */ webkitTransitionDuration: TweenValue; /** @deprecated */ webkitTransitionProperty: TweenValue; /** @deprecated */ webkitTransitionTimingFunction: TweenValue; webkitUserModify: TweenValue; webkitUserSelect: TweenValue; webkitWritingMode: TweenValue; whiteSpace: TweenValue; widows: TweenValue; width: TweenValue; willChange: TweenValue; wordBreak: TweenValue; wordSpacing: TweenValue; wordWrap: TweenValue; writingMode: TweenValue; zIndex: TweenValue; zoom: TweenValue; } interface CSSVars extends Partial<CSSProperties> { } interface TweenVars extends CSSVars { css?: CSSVars; } // TODO: Add types interface GSCache { [key: string]: any; } } declare namespace gsap.plugins { interface CSSPlugin extends Plugin {} interface CSSPluginClass extends CSSPlugin { new(): PluginScope & CSSPlugin; prototype: PluginScope & CSSPlugin; } const css: CSSPluginClass; } interface Element { _gsap: gsap.GSCache; } declare const CSSPlugin: gsap.plugins.CSSPlugin; declare module "gsap/CSSPlugin" { export const CSSPlugin: gsap.plugins.CSSPlugin; export { CSSPlugin as default }; } declare module "gsap/src/CSSPlugin" { export * from "gsap/CSSPlugin"; export { CSSPlugin as default } from "gsap/CSSPlugin"; } declare module "gsap" { export * from "gsap/CSSPlugin"; } declare module "gsap/all" { export * from "gsap/CSSPlugin"; } declare module "gsap-trial/CSSPlugin" { export * from "gsap/CSSPlugin"; export { CSSPlugin as default } from "gsap/CSSPlugin"; } declare module "gsap-trial/src/CSSPlugin" { export * from "gsap/CSSPlugin"; export { CSSPlugin as default } from "gsap/CSSPlugin"; } declare module "gsap-trial" { export * from "gsap/CSSPlugin"; } declare module "gsap-trial/all" { export * from "gsap/CSSPlugin"; }
the_stack
import { buildRights, IUser, KYCStatus, Role, UserStatus, UserRegistrationData, EmailConfirmationResponse } from '@energyweb/origin-backend-core'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { expect } from 'chai'; import request from 'supertest'; import { DatabaseService } from '@energyweb/origin-backend-utils'; import { bootstrapTestInstance, registerAndLogin } from './origin-backend'; import { omit } from './utils'; import { UserService } from '../src/pods/user/user.service'; import { OrganizationService } from '../src/pods/organization/organization.service'; import { EmailConfirmationService } from '../src/pods/email-confirmation/email-confirmation.service'; export const userToRegister: UserRegistrationData = { title: 'Mr', firstName: 'John', lastName: 'Rambo', email: 'john@example.com', password: 'FirstBlood2', telephone: '+11' }; describe('User e2e tests', () => { let app: INestApplication; let databaseService: DatabaseService; let userService: UserService; let organizationService: OrganizationService; let emailConfirmationService: EmailConfirmationService; before(async () => { ({ app, databaseService, userService, organizationService, emailConfirmationService } = await bootstrapTestInstance()); await app.init(); }); beforeEach(async () => { await databaseService.truncate('user', 'organization', 'email_confirmation'); }); after(async () => { await app.close(); }); it('should be able to register user', async () => { await request(app.getHttpServer()) .post(`/user/register`) .send(userToRegister) .expect((res) => { const user = res.body as IUser; expect(user.email).equals(userToRegister.email); expect(user.organization).to.be.undefined; expect(user.rights).equals(buildRights([Role.OrganizationAdmin])); expect(user.status).equals(UserStatus.Pending); expect(user.kycStatus).equals(KYCStatus.Pending); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((user as any).password).to.be.undefined; }); let accessToken: string; await request(app.getHttpServer()) .post('/auth/login') .send({ username: userToRegister.email, password: userToRegister.password }) .expect((res) => ({ accessToken } = res.body)); const registeredUser = await userService.findOne({ email: userToRegister.email }); registeredUser.status = UserStatus.Active; await userService.update(registeredUser.id, registeredUser); await request(app.getHttpServer()) .get(`/user/me`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const user = res.body as IUser; expect(user.email).equals(userToRegister.email); }); }); it('should not be able to register user with password which doesn`t match requirements', async () => { const newUserToRegister: UserRegistrationData = { ...userToRegister, password: 'test' }; await request(app.getHttpServer()) .post(`/user/register`) .send(newUserToRegister) .expect(HttpStatus.BAD_REQUEST); }); it('should not be able to register user with the same email', async () => { await request(app.getHttpServer()) .post(`/user/register`) .send(userToRegister) .expect(HttpStatus.CREATED); const otherUserWithSameEmail: UserRegistrationData = { ...userToRegister, firstName: 'Samuel', lastName: 'Trautman' }; await request(app.getHttpServer()) .post(`/user/register`) .send(otherUserWithSameEmail) .expect(HttpStatus.CONFLICT); }); it('should not be able to register user with missing input data', async () => { await request(app.getHttpServer()) .post(`/user/register`) .send(omit(userToRegister, 'password')) .expect(HttpStatus.BAD_REQUEST); }); it('user should be able to get his user data', async () => { const { accessToken, user } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser, Role.OrganizationDeviceManager] ); await request(app.getHttpServer()) .get(`/user/${user.id}`) .set('Authorization', `Bearer ${accessToken}`) .expect(HttpStatus.OK); }); it('user should not be able to get user data of another user', async () => { const { user } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationUser, Role.OrganizationDeviceManager ]); const { accessToken: accessToken2 } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser, Role.OrganizationDeviceManager], 'differentOrganization', 'differentOrganization' ); await request(app.getHttpServer()) .get(`/user/${user.id}`) .set('Authorization', `Bearer ${accessToken2}`) .expect(HttpStatus.UNAUTHORIZED); }); it('admin/support agent should be able to get user data of another user', async () => { const { accessToken } = await registerAndLogin(app, userService, organizationService, [ Role.Admin ]); const { user } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser, Role.OrganizationDeviceManager], 'differentOrganization', 'differentOrganization' ); await request(app.getHttpServer()) .get(`/user/${user.id}`) .set('Authorization', `Bearer ${accessToken}`) .expect(HttpStatus.OK); }); it('org admin should be able to get user data of another user', async () => { const { accessToken } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationAdmin ]); const { user } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationUser, Role.OrganizationDeviceManager ]); await request(app.getHttpServer()) .get(`/user/${user.id}`) .set('Authorization', `Bearer ${accessToken}`) .expect(HttpStatus.OK); }); it('org admin should not be able to get user data from another organization', async () => { const { accessToken } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationAdmin ]); const { user } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser, Role.OrganizationDeviceManager], 'differentOrganization', 'differentOrganization' ); await request(app.getHttpServer()) .get(`/user/${user.id}`) .set('Authorization', `Bearer ${accessToken}`) .expect(HttpStatus.UNAUTHORIZED); }); it('new user should have confirmation token set', async () => { const { user } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationUser ]); const { confirmed, token, expiryTimestamp } = await emailConfirmationService.get(user.id); expect(confirmed).to.be.false; expect(token.length).to.equal(128); expect(expiryTimestamp).to.be.above(0); }); it('user should be able to confirm email', async () => { const { user, accessToken } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser] ); const { token } = await emailConfirmationService.get(user.id); await request(app.getHttpServer()) .get(`/user/me`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const { emailConfirmed } = res.body as IUser; expect(emailConfirmed).to.be.false; }); await request(app.getHttpServer()) .put(`/user/confirm-email/${token}`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const response = res.text as EmailConfirmationResponse; expect(response).equals(EmailConfirmationResponse.Success); }); await request(app.getHttpServer()) .get(`/user/me`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const { emailConfirmed } = res.body as IUser; expect(emailConfirmed).to.be.true; }); }); it('user should be able to re-request confirmation email', async () => { const { accessToken } = await registerAndLogin(app, userService, organizationService, [ Role.OrganizationUser ]); await request(app.getHttpServer()) .put(`/user/re-send-confirm-email`) .set('Authorization', `Bearer ${accessToken}`) .expect(HttpStatus.OK); }); it('user should not be able to re-confirm confirmed email', async () => { const { user, accessToken } = await registerAndLogin( app, userService, organizationService, [Role.OrganizationUser] ); const { token } = await emailConfirmationService.get(user.id); await request(app.getHttpServer()) .put(`/user/confirm-email/${token}`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const response = res.text as EmailConfirmationResponse; expect(response).equals(EmailConfirmationResponse.Success); }); await request(app.getHttpServer()) .put(`/user/confirm-email/${token}`) .set('Authorization', `Bearer ${accessToken}`) .expect((res) => { const response = res.text as EmailConfirmationResponse; expect(response).equals(EmailConfirmationResponse.AlreadyConfirmed); }); }); });
the_stack
import * as vscode from "vscode"; import { Mutex } from "await-semaphore"; import CancellationToken from "./CancellationToken"; import { getAssistantMode, setAssistantMode, AssistantMode, } from "./AssistantMode"; import { AssistantDiagnostic } from "./AssistantDiagnostic"; import { debounce, getAPIKey } from "./utils"; import setState from "../binary/requests/setState"; import getValidator, { DocumentValidator } from "./DocumentValidator"; import getAssistantDiagnostics from "./requests/getAssistantDiagnostics"; import getCompilerDiagnostics from "./requests/getCompilerDiagnostics"; import AssistantCodeActionProvider from "./AssistantCodeActionProvider"; import getValidLanguages from "./requests/getValidLanguages"; import TabNineDiagnostic from "./TabNineDiagnostic"; import { ASSISTANT_IGNORE_REFRESH_COMMAND, ASSISTANT_MODE_TOGGLE_COMMAND, EDIT_DISTANCE, PASTE_COMMAND, PASTE_THRESHOLD, TABNINE_DIAGNOSTIC_CODE, } from "./globals"; import { initAssistantThreshold, getBackgroundThreshold, } from "./handleAssistantThreshold"; const decorationType = vscode.window.createTextEditorDecorationType({ border: "#3794FF 2px", borderStyle: "none none solid none", }); const changesTrackMap = new Map<vscode.Uri, vscode.Position>(); export function setDecorators( diagnostics: vscode.Diagnostic[] | undefined ): void { const editor = vscode.window.activeTextEditor; const decorationsArray: vscode.DecorationOptions[] = diagnostics?.map(({ range }) => ({ range })) || []; if (editor) { editor.setDecorations(decorationType, decorationsArray); } } function setStatusBarMessage(message?: string, timeout = 30000): void { if (!message?.length) { return; } vscode.window.setStatusBarMessage(`${message}`, timeout); } const mutex: Mutex = new Mutex(); const cancellationToken = new CancellationToken(); function getRelevantRange( document: vscode.TextDocument, visibleRanges: vscode.Range[] ): vscode.Range | undefined { const firstEditingPosition = changesTrackMap.get(document.uri); const visibleRange = visibleRanges.reduce((accumulator, currentValue) => accumulator.union(currentValue) ); return ( firstEditingPosition && visibleRange.intersection( new vscode.Range(firstEditingPosition, visibleRange.end) ) ); } async function refreshDiagnostics( document: vscode.TextDocument, diagnosticsCollection: vscode.DiagnosticCollection, visibleRanges: vscode.Range[] ): Promise<void> { cancellationToken.cancel(); const lock = await mutex.acquire(); cancellationToken.reset(); cancellationToken.registerCallback(setStatusBarMessage); try { let foundDiagnostics = 0; const relevantRange = getRelevantRange(document, visibleRanges); if (!relevantRange) { return; } const start = document.offsetAt(relevantRange.start); const end = document.offsetAt(relevantRange.end); const threshold = getAssistantMode() === AssistantMode.Background ? getBackgroundThreshold() : PASTE_THRESHOLD; const code = document.getText(); const apiKey = await getAPIKey(); if (cancellationToken.isCancelled()) { return; } const assistantDiagnostics: | AssistantDiagnostic[] | undefined = await getAssistantDiagnostics( code, document.fileName, { start, end }, threshold, EDIT_DISTANCE, apiKey, cancellationToken ); if (cancellationToken.isCancelled()) { return; } const newDiagnostics: TabNineDiagnostic[] = []; assistantDiagnostics?.forEach((assistantDiagnostic) => { const choices = assistantDiagnostic.completionList.filter( (completion) => completion.value !== assistantDiagnostic.reference ); const choicesString = choices.map( (completion) => `${completion.message} '${completion.value}'\t${completion.score}%` ); if (choices.length > 0) { const prevReferencesLocationsInRange = assistantDiagnostic.references.filter( (r) => r.start < assistantDiagnostic.range.start ); const prevDiagnosticsForReferenceInRange = newDiagnostics.filter( (diag) => prevReferencesLocationsInRange.includes(diag.assistantRange) ); // If we are in paste mode and one of the previous reference was ok (no suggestions), don't suggest things on this reference. if ( getAssistantMode() === AssistantMode.Background || prevReferencesLocationsInRange.length === 0 || // no references before this point (prevReferencesLocationsInRange.length > 0 && prevDiagnosticsForReferenceInRange.length > 0) ) { // there are references before this point. and we have diagnostics for them const vscodeRange = new vscode.Range( document.positionAt(assistantDiagnostic.range.start), document.positionAt(assistantDiagnostic.range.end) ); const vscodeReferencesRange: vscode.Range[] = assistantDiagnostic.references.map( (r) => new vscode.Range( document.positionAt(r.start), document.positionAt(r.end) ) ); const diagnostic = new TabNineDiagnostic( vscodeRange, `${choicesString.join("\n")}`, choices, assistantDiagnostic.reference, vscodeReferencesRange, assistantDiagnostic.range, assistantDiagnostic.responseId, threshold, vscode.DiagnosticSeverity.Information ); diagnostic.code = TABNINE_DIAGNOSTIC_CODE; newDiagnostics.push(diagnostic); foundDiagnostics += 1; } } }); if (newDiagnostics.length > 0) { void setState({ ValidatorState: { num_of_diagnostics: newDiagnostics.length, num_of_locations: assistantDiagnostics?.length || 0, }, }); } if ( diagnosticsCollection.get(document.uri)?.length !== newDiagnostics.length ) { setDecorators(newDiagnostics); diagnosticsCollection.set(document.uri, newDiagnostics); } const message = foundDiagnostics ? `${foundDiagnostics}` : ""; console.log(message); setStatusBarMessage("$(pass)"); } catch (e: unknown) { setStatusBarMessage(); console.error(`tabnine assistant: error: `, e); } finally { lock(); } } const debouncedRefreshDiagnostics = debounce(refreshDiagnostics); function refreshDiagnosticsOrPrefetch( document: vscode.TextDocument, tabNineDiagnostics: vscode.DiagnosticCollection ) { if (getAssistantMode() === AssistantMode.Background) { if (vscode.window.activeTextEditor) { void refreshDiagnostics( document, tabNineDiagnostics, vscode.window.activeTextEditor.visibleRanges ); } } else { // prefetch diagnostics (getAssistantMode() == Mode.Paste) void getCompilerDiagnostics(document.getText(), document.fileName); } } let currentRange: { range: vscode.Range; length: number } | null = null; let inPaste = false; export default async function registerAssistant( context: vscode.ExtensionContext, pasteDisposable: vscode.Disposable ): Promise<void> { const tabnineDiagnostics = vscode.languages.createDiagnosticCollection( "tabnine" ); context.subscriptions.push(tabnineDiagnostics); const documentValidator = await getValidator(); initAssistantThreshold(context); registerRefreshCommand(context, documentValidator, tabnineDiagnostics); registerAssistantModeToggle(tabnineDiagnostics, documentValidator); // handleActiveEditorChanged(context, documentValidator, tabnineDiagnostics); handleVisibleRangeChange(context, documentValidator, tabnineDiagnostics); pasteDisposable.dispose(); registerPasteCommand(context, documentValidator, tabnineDiagnostics); // For AssistantMode.Paste handlePasteChange(context, tabnineDiagnostics, documentValidator); // For AssistantMode.Background handleTextChange(context, tabnineDiagnostics, documentValidator); void handleCodeAction(context); // if ( // getAssistantMode() === AssistantMode.Background && // vscode.window.activeTextEditor && // documentValidator.isValid(vscode.window.activeTextEditor.document) // ) { // refreshDiagnosticsOrPrefetch( // vscode.window.activeTextEditor.document, // tabnineDiagnostics // ); // } } function registerRefreshCommand( context: vscode.ExtensionContext, documentValidator: DocumentValidator, tabnineDiagnostics: vscode.DiagnosticCollection ) { context.subscriptions.push( vscode.commands.registerCommand(ASSISTANT_IGNORE_REFRESH_COMMAND, () => { const editor = vscode.window.activeTextEditor; if (editor) { const { document, visibleRanges } = editor; if (documentValidator.isValid(document)) { if (getAssistantMode() === AssistantMode.Paste) { if (currentRange) { void refreshDiagnostics(document, tabnineDiagnostics, [ currentRange?.range, ]); } } else { void refreshDiagnostics( document, tabnineDiagnostics, visibleRanges ); } } } }) ); } function registerAssistantModeToggle( tabNineDiagnostics: vscode.DiagnosticCollection, validator: DocumentValidator ) { vscode.commands.registerCommand(ASSISTANT_MODE_TOGGLE_COMMAND, () => { cancellationToken.cancel(); if (vscode.window.activeTextEditor) { tabNineDiagnostics.delete(vscode.window.activeTextEditor.document.uri); } setDecorators([]); const newMode = getAssistantMode() === AssistantMode.Background ? AssistantMode.Paste : AssistantMode.Background; setAssistantMode(newMode); if (getAssistantMode() === AssistantMode.Paste) { void vscode.window.showInformationMessage("tabnine assistant paste mode"); console.log("paste validation mode"); } else { void vscode.window.showInformationMessage( "tabnine assistant background mode" ); console.log("background validation mode"); } if ( vscode.window.activeTextEditor && validator.isValid(vscode.window.activeTextEditor.document) ) { refreshDiagnosticsOrPrefetch( vscode.window.activeTextEditor.document, tabNineDiagnostics ); } }); } // function handleActiveEditorChanged( // context: vscode.ExtensionContext, // validator: DocumentValidator, // tabNineDiagnostics: vscode.DiagnosticCollection // ) { // context.subscriptions.push( // vscode.window.onDidChangeActiveTextEditor((editor) => { // if (editor && validator.isValid(editor.document)) { // if (getAssistantMode() === AssistantMode.Background) { // void refreshDiagnostics( // editor.document, // tabNineDiagnostics, // editor.visibleRanges // ); // } else { // // prefetch diagnostics // void getCompilerDiagnostics( // editor.document.getText(), // editor.document.fileName // ); // } // } // }) // ); // } function handleVisibleRangeChange( context: vscode.ExtensionContext, validator: DocumentValidator, tabNineDiagnostics: vscode.DiagnosticCollection ) { context.subscriptions.push( vscode.window.onDidChangeTextEditorVisibleRanges((event) => { if ( getAssistantMode() === AssistantMode.Background && validator.isValid(event.textEditor.document) ) { debouncedRefreshDiagnostics( event.textEditor.document, tabNineDiagnostics, event.textEditor.visibleRanges ); } }) ); } function registerPasteCommand( context: vscode.ExtensionContext, validator: DocumentValidator, tabNineDiagnostics: vscode.DiagnosticCollection ) { context.subscriptions.push( vscode.commands.registerCommand( PASTE_COMMAND, async (textEditor: vscode.TextEditor) => { inPaste = true; const { start } = textEditor.selection; await vscode.commands.executeCommand( "editor.action.clipboardPasteAction" ); const { end } = textEditor.selection; if (vscode.window.activeTextEditor) { const { document } = vscode.window.activeTextEditor; const isValidExt = validator.isValid(document); if (!isValidExt || getAssistantMode() === AssistantMode.Background) { inPaste = false; return; } currentRange = { range: new vscode.Range(start, end), length: document.offsetAt(end) - document.offsetAt(start), }; inPaste = false; tabNineDiagnostics.delete(document.uri); setDecorators([]); void refreshDiagnostics(document, tabNineDiagnostics, [ currentRange.range, ]); } } ) ); } function handlePasteChange( context: vscode.ExtensionContext, assistantDiagnostics: vscode.DiagnosticCollection, validator: DocumentValidator ) { context.subscriptions.push( vscode.workspace.onDidChangeTextDocument((event) => { if ( getAssistantMode() === AssistantMode.Paste && !inPaste && validator.isValid(event.document) ) { let firstPosition: vscode.Position | null = null; let delta = 0; event.contentChanges.forEach((cc) => { if (firstPosition === null) { firstPosition = cc.range.start; } else if (cc.range.start.isBefore(firstPosition)) { firstPosition = cc.range.start; } if (currentRange !== null) { if ( cc.range.start.isAfterOrEqual(currentRange.range.start) && cc.range.end.isBefore(currentRange.range.end) && !( cc.range.start.isEqual(currentRange.range.start) && cc.range.end.isEqual(currentRange.range.end) ) ) { delta += -cc.rangeLength + (cc.text.length || 0); } else { currentRange = null; } } }); if (firstPosition !== null && currentRange !== null) { const diagnostics = assistantDiagnostics .get(event.document.uri) ?.filter((d) => d.range.end.isBefore(firstPosition as vscode.Position) ); assistantDiagnostics.set(event.document.uri, diagnostics); setDecorators(diagnostics); if (delta !== 0) { const newLength = currentRange.length + delta; const newEndPos = event.document.positionAt( event.document.offsetAt(currentRange.range.start) + newLength ); currentRange = { range: new vscode.Range(currentRange.range.start, newEndPos), length: newLength, }; } debouncedRefreshDiagnostics(event.document, assistantDiagnostics, [ currentRange.range, ]); } else { assistantDiagnostics.delete(event.document.uri); setDecorators([]); } } }) ); } function handleTextChange( context: vscode.ExtensionContext, assistantDiagnostics: vscode.DiagnosticCollection, validator: DocumentValidator ) { context.subscriptions.push( vscode.workspace.onDidChangeTextDocument((event) => { if ( getAssistantMode() === AssistantMode.Background && validator.isValid(event.document) && event.contentChanges.length ) { const firstChangeStartPosition = event.contentChanges .map((change) => change.range.start) .reduce((first: vscode.Position | null, current) => { if (first === null) { return current; } if (current.isBefore(first)) { return current; } return first; }, null); if (firstChangeStartPosition !== null) { const diagnostics = assistantDiagnostics .get(event.document.uri) ?.filter((d) => d.range.end.isBefore(firstChangeStartPosition)); assistantDiagnostics.set(event.document.uri, diagnostics); if ( assistantDiagnostics.get(event.document.uri)?.length !== diagnostics?.length ) { setDecorators(diagnostics); } if (!changesTrackMap.has(event.document.uri)) { changesTrackMap.set(event.document.uri, firstChangeStartPosition); } } else { assistantDiagnostics.delete(event.document.uri); setDecorators([]); } if (vscode.window.activeTextEditor) { debouncedRefreshDiagnostics( vscode.window.activeTextEditor.document, assistantDiagnostics, vscode.window.activeTextEditor.visibleRanges ); } } }) ); } async function handleCodeAction(context: vscode.ExtensionContext) { const validLanguages = await getValidLanguages(); context.subscriptions.push( vscode.languages.registerCodeActionsProvider( validLanguages, new AssistantCodeActionProvider(), { providedCodeActionKinds: AssistantCodeActionProvider.providedCodeActionKinds, } ) ); }
the_stack
import { ASJsonLdProfileContentType, isASLink } from "../activitystreams"; import { Activity, ASLink, ASObject, Collection, isActivity, LDObject, Place, } from "../types"; import { HasLinkPrefetchResult, LinkPrefetchFailure, LinkPrefetchResult, LinkPrefetchSuccess, } from "../types"; import { createHttpOrHttpsRequest } from "../util"; import { debuglog, first } from "../util"; import { encodeHtmlEntities } from "../util"; import { isProbablyAbsoluteUrl } from "../util"; import { readableToString } from "../util"; import { sendRequest } from "../util"; import { ensureArray } from "../util"; import { flatten } from "../util"; import { distbinBodyTemplate } from "./partials"; import { everyPageHead } from "./partials"; import { sanitize } from "./sanitize"; import { internalUrlRewriter } from "./url-rewriter"; import * as fs from 'fs'; import { highlightAuto } from "highlight.js" import { IncomingMessage, ServerResponse } from "http"; import * as marked from "marked"; import * as url from "url"; import { createLogger } from "../logger"; const logger = createLogger(__filename); const failedToFetch = Symbol("is this a Link that distbin failed to fetch?"); // Highlighting const highlightCss = fs.readFileSync(require.resolve('highlight.js/styles/github.css'), 'utf-8'); marked.setOptions({ highlight (code) { return highlightAuto(code).value; } }); // create handler to to render a single activity to a useful page export const createHandler = ({ apiUrl, activityId, externalUrl, internalUrl, }: { apiUrl: string; activityId: string; externalUrl: string; internalUrl: string; }) => { return async (req: IncomingMessage, res: ServerResponse) => { const activityUrl = apiUrl + req.url; const activityRes = await sendRequest( createHttpOrHttpsRequest(activityUrl), ); if (activityRes.statusCode !== 200) { // proxy res.writeHead(activityRes.statusCode, activityRes.headers); activityRes .pipe( res, { end: true }, ) .on("finish", res.end); return; } const incomingActivity = JSON.parse(await readableToString(activityRes)); const activityWithoutDescendants = activityWithUrlsRelativeTo( incomingActivity, externalUrl, ); const repliesUrls = ensureArray(activityWithoutDescendants.replies).map( (repliesUrl: string) => { return url.resolve(activityUrl, repliesUrl); }, ); const descendants = flatten( await Promise.all( repliesUrls.map(repliesUrl => fetchDescendants( repliesUrl, internalUrlRewriter(internalUrl, externalUrl), ), ), ), ); const activity = Object.assign(activityWithoutDescendants, { replies: descendants, }); const ancestors = await fetchReplyAncestors( externalUrl, activity, internalUrlRewriter(internalUrl, externalUrl), ); async function fetchDescendants( repliesUrl: string, urlRewriter: (u: string) => string, ) { const repliesCollectionResponse = await sendRequest( createHttpOrHttpsRequest(urlRewriter(repliesUrl)), ); if (repliesCollectionResponse.statusCode !== 200) { return { name: `Failed to fetch replies at ${repliesUrl} (code ${ repliesCollectionResponse.statusCode })`, }; } const repliesCollection = JSON.parse( await readableToString(repliesCollectionResponse), ); if (repliesCollection.totalItems <= 0) { return repliesCollection; } repliesCollection.items = await Promise.all( repliesCollection.items.map(async (replyActivity: Activity) => { // activity with resolved .replies collection const withAbsoluteUrls = activityWithUrlsRelativeTo( replyActivity, repliesUrl, ); const { replies } = withAbsoluteUrls; const nextRepliesUrl = typeof replies === "string" ? replies : Array.isArray(replies) && replies.length && replies[0]; return Object.assign(withAbsoluteUrls, { replies: typeof nextRepliesUrl === "string" ? await fetchDescendants(nextRepliesUrl, urlRewriter) : replies, }); }), ); return repliesCollection; } res.writeHead(200, { "content-type": "text/html", }); res.end(` <!doctype html> <head> ${everyPageHead()} <style> .primary-activity main { font-size: 1.2em; } .primary-activity.at-least-viewport-height { min-height: calc(100vh - 5.5em); } .primary-activity { margin: 1rem auto; } ${createActivityCss()} </style> </head> ${distbinBodyTemplate({ externalUrl })(` ${renderAncestorsSection(ancestors, externalUrl)} <div class="primary-activity"> ${renderObject(activity, externalUrl)} </div> ${renderDescendantsSection( ensureArray(activity.replies)[0], externalUrl, )} <script> (function () { var primary = document.querySelector('.primary-activity'); if ( ! isElementInViewport(primary)) { primary.classList.add('at-least-viewport-height') primary.scrollIntoView() } // offset // document.body.scrollTop = document.body.scrollTop - 2 * parseFloat(getComputedStyle(primary).fontSize) // https://bit.ly/1jThLtH function isElementInViewport (el) { var rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); } }()); </script> `)} `); }; }; // todo sandbox .content like /* <iframe sandbox width=100% height=100% srcdoc="${encodeHtmlEntities(activity.object.content)}" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" ></iframe> */ export const renderActivity = (activity: Activity, externalUrl: string) => renderObject(activity, externalUrl); type URLString = string; const href = (linkable: URLString | ASLink | ASObject): string => { if (typeof linkable === "string") { return linkable; } if (isASLink(linkable)) { return linkable.href; } if (linkable.url) { return href(first(linkable.url)); } return; }; export function renderObject(activity: ASObject, externalUrl: string) { const object = isActivity(activity) && typeof activity.object === "object" ? activity.object : activity; const published = object.published; const generator = formatGenerator(activity); const location = formatLocation(activity); const attributedTo = formatAttributedTo(activity); const tags = formatTags(activity); const activityUrl = ensureArray(activity.url)[0]; const activityObject = isActivity(activity) && ensureArray(activity.object).filter( (o: ASObject | string) => typeof o === "object", )[0]; const mainHtml = (() => { try { const maybeMarkdown = activity.content ? activity.content : activityObject && typeof activityObject === "object" && activityObject.content ? activityObject.content : activity.name || activity.url ? `<a href="${activity.url}">${activity.url}</a>` : activity.id ? `<a href="${activity.id}">${activity.id}</a>` : ""; const html = marked(maybeMarkdown); const sanitized = sanitize(html); return sanitized; } catch (error) { logger.error("Error rendering activity object.", activity, error); return `<p>distbin failed to render this</p>`; } })(); return ` <article class="activity-item"> <header> ${attributedTo || ""} </header> ${ activity.name ? `<h1>${activity.name}</h1>` : activityObject && typeof activityObject === "object" && activityObject.name ? `<h1>${activityObject.name}</h1>` : "" } <main>${mainHtml}</main> ${ tags ? ` <div class="activity-tags"> ${tags} </div> ` : "" } <div class="activity-attachments"> ${ensureArray( isActivity(activity) && typeof activity.object === "object" && activity.object.attachment, ) .map((attachment: ASObject & HasLinkPrefetchResult) => { if (!attachment) { return ""; } switch (attachment.type) { case "Link": const prefetch: LinkPrefetchResult = attachment["https://distbin.com/ns/linkPrefetch"]; if (prefetch.type === "LinkPrefetchFailure") { return; } const linkPrefetchSuccess = prefetch as LinkPrefetchSuccess; if ( !( linkPrefetchSuccess && linkPrefetchSuccess.supportedMediaTypes ) ) { return ""; } if ( linkPrefetchSuccess.supportedMediaTypes.find((m: string) => m.startsWith("image/"), ) ) { return ( linkPrefetchSuccess.link && ` <img src="${linkPrefetchSuccess.link.href}" /> ` ); } break; default: break; } return ""; }) .filter(Boolean) .join("\n")} </div> ${/* TODO add byline */ ""} <footer> <div class="activity-footer-bar"> <span> <a href="${activityUrl && encodeHtmlEntities(href(activityUrl))}">${ published ? formatDate(new Date(Date.parse(published))) : "permalink" }</a> </span> &nbsp; <span> <a href="${externalUrl}?inReplyTo=${encodeHtmlEntities( href(activityUrl), )}">reply</a> </span> &nbsp; <span class="action-show-raw"> <details> <summary>{&hellip;}</summary> <pre><code>${encodeHtmlEntities( JSON.stringify(activity, null, 2), )}</code></pre> </details> </span> ${generator ? `&nbsp;via ${generator}` : ""} ${ location ? `&nbsp;<span class="action-location">${location}</span>` : "" } </div> </footer> </article> `; } function formatTags(o: ASObject) { const tags = ensureArray( (isActivity(o) && typeof o.object === "object" && o.object.tag) || o.tag, ).filter(Boolean); return tags .map(renderTag) .filter(Boolean) .join("&nbsp;"); function renderTag(tag: ASObject) { const text = tag.name || tag.id || first(tag.url); if (!text) { return; } const safeText = encodeHtmlEntities(text); const tagUrl = tag.url || tag.id || (isProbablyAbsoluteUrl(text) ? text : ""); let rendered; if (tagUrl) { rendered = `<a href="${encodeHtmlEntities( tagUrl, )}" class="activity-tag">${safeText}</a>`; } else { rendered = `<span class="activity-tag">${safeText}</span>`; } return rendered; } } function formatAttributedTo(activity: ASObject | Activity) { const attributedTo = activity.attributedTo || (isActivity(activity) && typeof activity.object === "object" && activity.object.attributedTo); if (!attributedTo) { return; } let formatted = ""; let authorUrl; if (typeof attributedTo === "string") { formatted = encodeHtmlEntities(attributedTo); } else if (typeof attributedTo === "object") { formatted = encodeHtmlEntities( attributedTo.name || first(attributedTo.url), ); authorUrl = attributedTo.url; } if (authorUrl) { formatted = `<a rel="author" href="${encodeHtmlEntities( href(first(authorUrl)), )}">${formatted}</a>`; } if (!formatted) { return; } return ` <address class="activity-attributedTo">${formatted}</address> `; } function formatLocation(activity: ASObject) { const location: Place = activity && activity.location; if (!location) { return; } let imgUrl; let linkTo; if (location.latitude && location.longitude) { imgUrl = [ `https://maps.googleapis.com/maps/api/staticmap?`, `center=${location.latitude},${ location.longitude }&zoom=11&size=480x300&sensor=false`, ].join(""); linkTo = `https://www.openstreetmap.org/search?query=${location.latitude},${ location.longitude }`; } else if (location.name) { // use name as center, don't specify zoom imgUrl = `https://maps.googleapis.com/maps/api/staticmap?center=${ location.name }&size=480x300&sensor=false`; linkTo = `https://www.openstreetmap.org/search?query=${location.name}`; } const glyph = ` <a class="glyph" ${ location.name ? `title="${encodeHtmlEntities(location.name)}"` : "" }> &#127757; </a> `; if (!imgUrl) { return glyph; } return ` <details> <summary> ${glyph} </summary> <ul> ${location.latitude ? `<li>latitude: ${location.latitude}</li>` : ""} ${location.longitude ? `<li>longitude: ${location.longitude}</li>` : ""} ${ location.altitude ? `<li>altitude: ${location.altitude}${location.units || "m"}</li>` : "" } ${ location.radius ? `<li>radius: ${location.radius}${location.units || "m"}</li>` : "" } ${location.accuracy ? `<li>accuracy: ${location.accuracy}%</li>` : ""} </ul> <div class="activity-location-map"> <a href="${linkTo}" target="_blank"> <img src="${imgUrl}" /> </a> </div> </details> `; } function formatGenerator(o: ASObject) { const object: ASObject = isActivity(o) && typeof o.object === "object" && o.object; const generator = object && object.generator; if (!generator) { return ""; } let generatorText; if (typeof generator === "object") { if (generator.name) { generatorText = generator.name; } else if (generator.id) { generatorText = generator.id; } let generatorUrl; if (generator.url) { generatorUrl = generator.url; } else if (generator.id) { generatorUrl = generator.id; } if (generatorUrl) { return `<a target="_blank" href="${generatorUrl}">${generatorText}</a>`; } } if (generatorText) { return generatorText; } return ""; } export const createActivityCss = () => { return ` .ancestors, .descendants { border-left: 1px solid #efefef; padding-left: 1em; } .activity-item main, .activity-item .activity-attachments, .activity-item .activity-attributedTo { margin: 1rem auto; /* intended to be same as <p> to force same margins even if main content is not a p */ } .activity-item .activity-attributedTo { font-style: normal; } .activity-item .activity-tag { display: inline-block; padding: 0.5em; border: 1px solid #eee; } .activity-footer-bar { line-height: 1em; } .activity-footer-bar .glyph { vertical-align: text-bottom; } .activity-footer-bar a { text-decoration: none; } .activity-footer-bar details, .activity-footer-bar details > summary { display: inline } .activity-footer-bar details > summary { cursor: pointer; } .activity-footer-bar details[open] { display: block; } .activity-item .activity-footer-bar, .activity-item .activity-footer-bar a { color: rgba(0, 0, 0, 0.3) } .activity-item .activity-attachments img { max-width: 100%; } .activity-location-map img { width: 100%; } .action-show-raw pre { color: initial } code { background-color: rgba(0, 0, 0, 0.05); display: inline-block; } ${highlightCss} `; }; class ASObjectWithFetchedReplies extends ASObject { public replies: Collection<ASObjectWithFetchedReplies>; } function renderDescendantsSection( replies: Collection<ASObjectWithFetchedReplies>, externalUrl: string, ) { let inner = ""; if (replies.totalItems === 0) { return ""; } if (!replies.items && replies.name) { inner = replies.name; } else if (replies.items.length === 0) { inner = "uh... totalItems > 0 but no items included. #TODO"; } else { inner = replies.items .map( (a: ASObjectWithFetchedReplies) => ` ${renderObject(a, externalUrl)} ${renderDescendantsSection(a.replies, externalUrl)} `, ) .join(""); } return ` <div class="descendants"> ${inner} </div> `; } // Render a single ancestor activity function renderAncestor( ancestor: Activity | LinkPrefetchFailure, externalUrl: string, ): string { if (ancestor.type === "LinkPrefetchFailure") { const linkFetchFailure = ancestor as LinkPrefetchFailure; const linkHref = linkFetchFailure.link.href; // assume its a broken link return ` <article class="activity-item"> <a href="${linkHref}">${linkHref}</a> (${linkFetchFailure.error || "couldn't fetch more info"}) </article> `; } return renderObject(ancestor, externalUrl); } // Render an item and its ancestors for each ancestor in the array. // This results in a nested structure conducive to indent-styling function renderAncestorsSection( ancestors: Array<Activity | LinkPrefetchFailure> = [], externalUrl: string, ): string { if (!ancestors.length) { return ""; } const [ancestor, ...olderAncestors] = ancestors; return ` <div class="ancestors"> ${ olderAncestors.length ? renderAncestorsSection(olderAncestors, externalUrl) : "" } ${renderAncestor(ancestor, externalUrl)} </div> `; } async function fetchReplyAncestors( baseUrl: string, activity: Activity, urlRewriter: (u: string) => string, ): Promise<Array<Activity | LinkPrefetchFailure>> { const inReplyTo = flatten( ensureArray(activity.object) .filter((o: object | string): o is object => typeof o === "object") .map((o: Activity) => ensureArray(o.inReplyTo)), )[0]; const parentUrl = inReplyTo && url.resolve(baseUrl, href(inReplyTo)); if (!parentUrl) { return []; } let parent: Activity; try { parent = activityWithUrlsRelativeTo( await fetchActivity(urlRewriter(parentUrl)), parentUrl, ); } catch (err) { switch (err.code) { case "ECONNREFUSED": case "ENOTFOUND": case "ENETUNREACH": // don't recurse since we can't fetch the parent return [ new LinkPrefetchFailure({ error: err, link: { href: parentUrl, type: "Link", }, }), ]; } throw err; } // #TODO support limiting at some reasonable amount of depth to avoid too big const ancestorsOfParent = await fetchReplyAncestors( baseUrl, parent, urlRewriter, ); const ancestorsOrFailures = [parent, ...ancestorsOfParent]; return ancestorsOrFailures; } async function fetchActivity(activityUrl: string) { const activityUrlOrRedirect = activityUrl; let activityResponse = await sendRequest( createHttpOrHttpsRequest( Object.assign(url.parse(activityUrlOrRedirect), { headers: { accept: `${ASJsonLdProfileContentType}, text/html`, }, }), ), ); let redirectsLeft = 3; /* eslint-disable no-labels */ followRedirects: while (redirectsLeft > 0) { switch (activityResponse.statusCode) { case 301: case 302: const resolvedUrl = url.resolve( activityUrl, ensureArray(activityResponse.headers.location)[0], ); activityResponse = await sendRequest( createHttpOrHttpsRequest( Object.assign(url.parse(resolvedUrl), { headers: { accept: `${ASJsonLdProfileContentType}, text/html`, }, }), ), ); redirectsLeft--; continue followRedirects; case 406: // unacceptable. Server doesn't speak a content-type I know. return { url: activityUrl, }; case 200: // cool break followRedirects; default: logger.warn( "unexpected fetchActivity statusCode", activityResponse.statusCode, activityUrl, ); break followRedirects; } } /* eslint-enable no-labels */ const resContentType = activityResponse.headers["content-type"] ? // strip off params like charset, profile, etc ensureArray(activityResponse.headers["content-type"])[0] .split(";")[0] .toLowerCase() : undefined; switch (resContentType) { case "application/json": case "application/activity+json": case "application/ld+json": const a = JSON.parse(await readableToString(activityResponse)); // ensure there is a .url value return Object.assign(a, { url: a.url || activityUrl, }); case "text/html": // Make an activity-like thing return { url: activityUrl, // TODO parse <title> for .name ? }; default: throw new Error( "Unexpected fetched activity content-type: " + resContentType + " " + activityUrl + " ", ); } } const isRelativeUrl = (u: string) => u && !url.parse(u).host; // given an activity with some URL values as maybe relative URLs, // return the activity with them made absolute URLs // TODO: use json-ld logic for this incl e.g. @base function activityWithUrlsRelativeTo( activity: Activity, relativeTo: string, ): Activity { interface IUrlUpdates { replies?: typeof activity.replies; url?: typeof activity.url; } const updates: IUrlUpdates = {}; const resolveUrl = (baseUrl: string, relativeUrl: string): string => { // prepend '.' to baseUrl can have subpath and not get dropped const resolved = url.resolve(baseUrl, `.${relativeUrl}`); return resolved; }; if (activity.replies) { updates.replies = (replies => { if (typeof replies === "string" && isRelativeUrl(replies)) { return resolveUrl(relativeTo, replies); } return replies; })(activity.replies); } if (activity.url) { updates.url = ensureArray(activity.url).map(u => { if (typeof u === "string" && isRelativeUrl(u)) { return resolveUrl(relativeTo, u); } if (isASLink(u) && isRelativeUrl(u.href)) { return Object.assign({}, u, { href: resolveUrl(relativeTo, u.href), }); } return u; }); } const withAbsoluteUrls = Object.assign({}, activity, updates); return withAbsoluteUrls; } function formatDate(date: Date, relativeTo = new Date()) { const MONTH_STRINGS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const diffMs = date.getTime() - relativeTo.getTime(); let dateString; // Future if (diffMs > 0) { throw new Error("formatDate cannot format dates in the future"); } // Just now (0s) if (diffMs > -1000) { return "1s"; } // Less than 60s ago -> 5s if (diffMs > -60 * 1000) { return Math.round((-1 * diffMs) / 1000) + "s"; } // Less than 1h ago -> 5m if (diffMs > -60 * 60 * 1000) { return Math.round((-1 * diffMs) / (1000 * 60)) + "m"; } // Less than 24h ago -> 5h if (diffMs > -60 * 60 * 24 * 1000) { return Math.round((-1 * diffMs) / (1000 * 60 * 60)) + "hrs"; } // >= 24h ago -> 6 Jul dateString = date.getDate() + " " + MONTH_STRINGS[date.getMonth()]; // or like 6 Jul 2012 if the year if its different than the relativeTo year if (date.getFullYear() !== relativeTo.getFullYear()) { dateString += " " + date.getFullYear(); } return dateString; }
the_stack
import { join as pathJoin } from 'path'; import { get as _get, isPlainObject as _isPlainObject } from 'lodash'; import { Logger, SfdxError, Messages } from '@salesforce/core'; import { SfdxProject } from '@salesforce/core'; import { MdRetrieveApi, MdRetrieveOptions } from '../mdapi/mdapiRetrieveApi'; import MetadataRegistry = require('./metadataRegistry'); import { createOutputDir, cleanupOutputDir, getSourceElementsFromSourcePath } from './sourceUtil'; import { toManifest, createManifest } from './manifestUtils'; import { toArray } from './parseManifestEntriesArray'; import MdapiConvertApi = require('./mdapiConvertApi'); import * as syncCommandHelper from './syncCommandHelper'; import { SourceOptions } from './types'; import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter'; import { AggregateSourceElements } from './aggregateSourceElements'; import { MdapiPullApi } from './sourcePullApi'; import { SourceElementsResolver } from './sourceElementsResolver'; import SourceConvertApi = require('./sourceConvertApi'); Messages.importMessagesDirectory(__dirname); export interface SourceRetrieveOptions extends SourceOptions { ignorewarnings?: boolean; apiversion?: string; packagenames?: string[]; wait?: number; } export interface SourceRetrieveOutput { inboundFiles: Array<{ state: string; fullName: string; type: string; filePath: string; }>; warnings?: string[]; packages?: Array<{ name: string; path: string; }>; } /** * API for retrieving metadata from an org and updating a local SFDX project. */ export class SourceRetrieve { private defaultPackagePath; private logger: Logger; private projectPath: string; private tmpOutputDir: string; private swa: SourceWorkspaceAdapter; constructor(private org) { this.projectPath = org.force.config.getProjectPath(); this.defaultPackagePath = org.config.getAppConfig().defaultPackagePath; } // Retrieves metadata from an org based on the retrieve options specified. public async retrieve(options: SourceRetrieveOptions): Promise<SourceRetrieveOutput> { this.logger = await Logger.child('SourceRetrieve'); // Only put SWA in stateless mode when sourcepath param is used. const mode = options.sourcepath && SourceWorkspaceAdapter.modes.STATELESS; const swaOptions: SourceWorkspaceAdapter.Options = { org: this.org, metadataRegistryImpl: MetadataRegistry, defaultPackagePath: this.defaultPackagePath, fromConvert: false, sourceMode: mode, sourcePaths: options.sourcepath && options.sourcepath.split(','), }; this.swa = await SourceWorkspaceAdapter.create(swaOptions); let results; try { this.tmpOutputDir = await createOutputDir('sourceRetrieve'); if (options.sourcepath) { this.logger.info(`Retrieving metadata in sourcepath '${options.sourcepath}' from org: '${this.org.name}'`); results = await this.retrieveFromSourcePath(options); } else if (options.manifest) { this.logger.info(`Retrieving metadata in manifest '${options.manifest}' from org: '${this.org.name}'`); results = await this.retrieveFromManifest(options); } else if (options.packagenames) { this.logger.info(`Retrieving metadata in package(s) '${options.packagenames}' from org: '${this.org.name}'`); results = await this.retrieveFromManifest(options); } else if (options.metadata) { this.logger.info(`Retrieving metadata '${options.metadata}' from org: '${this.org.name}'`); results = await this.retrieveFromMetadata(options); } } finally { await cleanupOutputDir(this.tmpOutputDir); // Delete the sourcePathInfos.json for this org. Ideally, we never create it but // until then, this is necessary. this.org.getSourcePathInfos().delete(); } return results; } // Retrieve specific source paths from an org and update the project. private async retrieveFromSourcePath(options: SourceRetrieveOptions): Promise<SourceRetrieveOutput> { // Parse the sourcepath parameter for metadata files and build a map of AggregateSourceElements const aggregateSourceElements = await getSourceElementsFromSourcePath(options.sourcepath, this.swa); // Create a manifest and update the options with the manifest file. options.manifest = await this.createManifest(aggregateSourceElements, options, this.tmpOutputDir); // Now that we have a package.xml, the rest is just a retrieve using the manifest. return this.retrieveFromManifest(options, aggregateSourceElements); } private async retrieveFromMetadata(options: SourceRetrieveOptions): Promise<SourceRetrieveOutput> { // toManifest will also tack the manifest onto the options await toManifest(this.org, options, this.tmpOutputDir); // Now that we have a package.xml, the rest is just a retrieve using the manifest. return this.retrieveFromManifest(options); } // Retrieve metadata specified in a manifest file (package.xml) from an org and update the project. private async retrieveFromManifest( options: SourceRetrieveOptions, aggregateSourceElements?: AggregateSourceElements ): Promise<SourceRetrieveOutput> { const results: SourceRetrieveOutput = { inboundFiles: [], packages: [], warnings: [] }; const project = SfdxProject.getInstance(); const defaultPackage = project.getDefaultPackage(); // Get AggregateSourceElements (ASEs) from the manifest so we can split into // multiple requests per package. if (!aggregateSourceElements) { if (options.manifest) { const sourceElementsResolver = new SourceElementsResolver(this.org, this.swa); aggregateSourceElements = await sourceElementsResolver.getSourceElementsFromManifest(options.manifest); } else { // This happens when only packages are retrieved aggregateSourceElements = new AggregateSourceElements(); } // Always add the default package, else new things in the org may not be processed correctly. if (!aggregateSourceElements.has(defaultPackage.name)) { aggregateSourceElements.set(defaultPackage.name, null); } } let shouldRetrievePackages = !!options.packagenames; for (const [pkgName, aseMap] of aggregateSourceElements) { this.logger.info('retrieving package:', pkgName); project.setActivePackage(pkgName); let tmpPkgOutputDir: string; try { // Create a temp directory tmpPkgOutputDir = await createOutputDir('sourceRetrieve_pkg'); let ases: AggregateSourceElements; // Create a new manifest for this package in the tmp dir. if (aseMap && options.sourcepath) { ases = new AggregateSourceElements().set(pkgName, aseMap); options.manifest = await this.createManifest(ases, options, tmpPkgOutputDir); } // Set Retrieve options for MdRetrieveApi const retrieveOptions: MdRetrieveOptions = Object.assign(MdRetrieveApi.getDefaultOptions(), { apiversion: options.apiversion, forceoverwrite: true, // retrieve always overwrites retrievetargetdir: tmpPkgOutputDir, unpackaged: options.manifest, wait: options.wait, }); // Only retrieve packages once if the param was set. if (shouldRetrievePackages) { retrieveOptions.packagenames = Array.isArray(options.packagenames) ? options.packagenames.join() : options.packagenames; shouldRetrievePackages = false; } // Retrieve the files from the org const res = await new MdRetrieveApi(this.org).retrieve(retrieveOptions); if (options.packagenames) { // Convert the packages to source format and copy them to the project in their // own directory. E.g. For a package named "fooPkg" and project named "myProject": // source would be copied to: myProject/fooPkg/ const packageNames: string[] = retrieveOptions.packagenames.split(','); const projectPath = await SfdxProject.resolveProjectPath(); const mdapiConvertApi = new MdapiConvertApi(); // Turn off the active package directory when converting retrieved // packages or it will prevent proper decomposition. // See behavior of AggregateSourceElement.shouldIgnorePath() try { project.setActivePackage(null); for (const _pkgName of packageNames) { const destPath = pathJoin(projectPath, _pkgName); const pkgPath = pathJoin(retrieveOptions.retrievetargetdir, _pkgName); this.logger.info(`Converting metadata in package: ${pkgPath} to: ${destPath}`); results.packages.push({ name: _pkgName, path: destPath }); mdapiConvertApi.root = pkgPath; mdapiConvertApi.outputDirectory = destPath; await mdapiConvertApi.convertSource(this.org); } } finally { project.setActivePackage(pkgName); } } // Convert to source format and update the local project. if (SourceRetrieve.isRetrieveSuccessful(res)) { // Only do this if unpackaged source was retrieved (i.e., a manifest was created). // retrieveOptions.unpackaged will be undefined when only packages were retrieved. if (retrieveOptions.unpackaged) { const mdapiPull = await MdapiPullApi.create({ org: this.org, adapter: this.swa }); // Extracts the source from package.xml in the temp dir, creates a Map of AggregateSourceElements // and updates the local project with the files from the temp dir. const sourceElements = await mdapiPull._syncDownSource(res, retrieveOptions, this.swa); // Build a simple object representation of what was changed in the local project. const { inboundFiles, warnings } = await this.processResults(res, sourceElements); if (results.inboundFiles.length > 0) { // Could be duplicates with multiple package directories so don't add inbound files twice const filePaths = results.inboundFiles.map((file) => file.filePath); for (const inboundFile of inboundFiles) { if (!filePaths.includes(inboundFile.filePath)) { results.inboundFiles.push(inboundFile); } } } else { results.inboundFiles = results.inboundFiles.concat(inboundFiles); } if (warnings) { results.warnings = results.warnings.concat(warnings); } } } else { // If fileProperties is an object, it means no results were retrieved so don't throw an error if (!_isPlainObject(res.fileProperties)) { let errMsgExtra = ''; if (res.messages) { errMsgExtra = `\nDue to: ${res.messages.problem}`; } throw SfdxError.create('salesforce-alm', 'source_retrieve', 'SourceRetrieveError', [errMsgExtra]); } } } finally { await cleanupOutputDir(tmpPkgOutputDir); } } return results; } private async createManifest( aggregateSourceElements: AggregateSourceElements, options: SourceOptions, outputDirPath: string ): Promise<string> { // Convert aggregateSourceElements to an array of this format: { type: 'ApexClass', name: 'MyClass' } // for use by ManifestApi.createManifest(). const mdFullPairs = SourceConvertApi.getUpdatedSourceTypeNamePairs( aggregateSourceElements.getAllSourceElements(), this.swa.metadataRegistry ); // Create a manifest and update the options with the manifest file. const manifest = await createManifest(this.org, options, mdFullPairs, outputDirPath); return manifest.file; } // eslint-disable-next-line @typescript-eslint/require-await private async processResults(result, sourceElements: AggregateSourceElements) { const inboundFiles = []; sourceElements.getAllWorkspaceElements().forEach((workspaceElement) => { syncCommandHelper.createDisplayRows(inboundFiles, workspaceElement.toObject(), this.projectPath); }); const output: SourceRetrieveOutput = { inboundFiles }; // If there are warning messages along with successes, display them (i.e., partial success). if (result.messages) { output.warnings = toArray(result.messages); } return output; } public static isRetrieveSuccessful(result): boolean { return result && result.success && _get(result, 'status') === 'Succeeded' && Array.isArray(result.fileProperties); } }
the_stack
import type {Buffer} from 'node:buffer' import {expectType, expectError} from 'tsd' import type {Node, Parent, Literal} from 'unist' import type {VFile} from 'vfile' import { unified, Plugin, Processor, FrozenProcessor, TransformCallback } from './index.js' expectType<Processor>(unified()) expectType<FrozenProcessor>(unified().freeze()) interface ExamplePluginSettings { example: string } const pluginWithoutOptions: Plugin<void[]> = function (options) { expectType<void>(options) } // Explicitly typed plugins. unified().use(pluginWithoutOptions) expectError(unified().use(pluginWithoutOptions, {})) expectError(unified().use(pluginWithoutOptions, '')) const pluginWithOptionalOptions: Plugin<[ExamplePluginSettings?]> = function ( options ) { expectType<ExamplePluginSettings | undefined>(options) } unified().use(pluginWithOptionalOptions) expectError(unified().use(pluginWithOptionalOptions, {})) unified().use(pluginWithOptionalOptions, {example: ''}) const pluginWithOptions: Plugin<[ExamplePluginSettings]> = function (options) { expectType<ExamplePluginSettings>(options) } expectError(unified().use(pluginWithOptions)) expectError(unified().use(pluginWithOptions, {})) unified().use(pluginWithOptions, {example: ''}) const pluginWithSeveralOptions: Plugin<[ExamplePluginSettings, number]> = function (options, value) { expectType<ExamplePluginSettings>(options) expectType<number>(value) } expectError(unified().use(pluginWithSeveralOptions)) expectError(unified().use(pluginWithSeveralOptions, {})) expectError(unified().use(pluginWithSeveralOptions, {example: ''})) unified().use(pluginWithSeveralOptions, {example: ''}, 1) // Implicitly typed plugins. const pluginWithImplicitOptions = (options?: ExamplePluginSettings) => { expectType<ExamplePluginSettings | undefined>(options) } unified().use(pluginWithImplicitOptions) expectError(unified().use(pluginWithImplicitOptions, {})) unified().use(pluginWithImplicitOptions, {example: ''}) // Using many different forms to pass options. unified() .use(pluginWithOptions, {example: ''}) .use([pluginWithOptions, {example: ''}]) .use([[pluginWithOptions, {example: ''}]]) .use({ plugins: [[pluginWithOptions, {example: ''}]] }) // Using booleans to turn on or off plugins. unified() .use(pluginWithoutOptions, true) .use(pluginWithoutOptions, false) .use([pluginWithoutOptions, true]) .use([pluginWithoutOptions, false]) .use([ [pluginWithoutOptions, true], [pluginWithoutOptions, false] ]) .use({ plugins: [ [pluginWithoutOptions, true], [pluginWithoutOptions, false] ] }) // Plugins setting parsers/compilers unified().use(function () { // Function. this.Parser = (doc, file) => { expectType<string>(doc) expectType<VFile>(file) return {type: ''} } // Class. this.Parser = class P { constructor(doc: string, file: VFile) { // Looks useless but ensures this class is assignable expectType<string>(doc) expectType<VFile>(file) } parse() { return {type: 'x'} } } // Function. this.Compiler = (tree, file) => { expectType<Node>(tree) expectType<VFile>(file) return '' } this.Compiler = class C { constructor(node: Node, file: VFile) { // Looks useless but ensures this class is assignable expectType<Node>(node) expectType<VFile>(file) } compile() { return '' } } }) // Plugins returning a transformer. unified() .use(() => (tree, file, next) => { expectType<Node>(tree) expectType<VFile>(file) expectType<TransformCallback>(next) setImmediate(next) }) .use(() => async (tree, file) => { expectType<Node>(tree) expectType<VFile>(file) return {type: 'x'} }) .use(() => () => ({type: 'x'})) .use(() => () => undefined) .use(() => () => { /* Empty */ }) .use(() => (x) => { if (x) { throw new Error('x') } }) // Plugins bound to a certain node. // A small subset of mdast. interface MdastRoot extends Parent { type: 'root' children: MdastFlow[] } type MdastFlow = MdastParagraph interface MdastParagraph extends Parent { type: 'paragraph' children: MdastPhrasing[] } type MdastPhrasing = MdastText interface MdastText extends Literal { type: 'text' value: string } // A small subset of hast. interface HastRoot extends Parent { type: 'root' children: HastChild[] } type HastChild = HastElement | HastText interface HastElement extends Parent { type: 'element' tagName: string properties: Record<string, unknown> children: HastChild[] } interface HastText extends Literal { type: 'text' value: string } const explicitPluginWithInputTree: Plugin<void[], MdastRoot> = () => (tree, file) => { expectType<MdastRoot>(tree) expectType<VFile>(file) } const explicitPluginWithTrees: Plugin<void[], MdastRoot, HastRoot> = () => (tree, file) => { expectType<MdastRoot>(tree) expectType<VFile>(file) return { type: 'root', children: [ { type: 'element', tagName: 'a', properties: {}, children: [{type: 'text', value: 'a'}] } ] } } unified().use(explicitPluginWithInputTree) unified().use([explicitPluginWithInputTree]) unified().use({plugins: [explicitPluginWithInputTree], settings: {}}) unified().use(() => (tree: MdastRoot) => { expectType<MdastRoot>(tree) }) unified().use([ () => (tree: MdastRoot) => { expectType<MdastRoot>(tree) } ]) unified().use({ plugins: [ () => (tree: MdastRoot) => { expectType<MdastRoot>(tree) } ], settings: {} }) unified().use(explicitPluginWithTrees) unified().use([explicitPluginWithTrees]) unified().use({plugins: [explicitPluginWithTrees], settings: {}}) unified().use(() => (_: MdastRoot) => ({ type: 'root', children: [{type: 'text', value: 'a'}] })) unified().use([ () => (_: MdastRoot) => ({ type: 'root', children: [{type: 'text', value: 'a'}] }) ]) unified().use({ plugins: [ () => (_: MdastRoot) => ({ type: 'root', children: [{type: 'text', value: 'a'}] }) ], settings: {} }) // Input and output types. interface ReactNode { kind: string } const someMdast: MdastRoot = { type: 'root', children: [{type: 'paragraph', children: [{type: 'text', value: 'a'}]}] } const someHast: HastRoot = { type: 'root', children: [ { type: 'element', tagName: 'a', properties: {}, children: [{type: 'text', value: 'a'}] } ] } const remarkParse: Plugin<void[], string, MdastRoot> = () => { /* Empty */ } const remarkStringify: Plugin<void[], MdastRoot, string> = () => { /* Empty */ } const rehypeParse: Plugin<void[], string, HastRoot> = () => { /* Empty */ } const rehypeStringify: Plugin<void[], HastRoot, string> = () => { /* Empty */ } const rehypeStringifyBuffer: Plugin<void[], HastRoot, Buffer> = () => { /* Empty */ } const explicitRemarkPlugin: Plugin<void[], MdastRoot> = () => { /* Empty */ } const implicitPlugin: Plugin<void[]> = () => { /* Empty */ } const remarkRehype: Plugin<void[], MdastRoot, HastRoot> = () => { /* Empty */ } const explicitRehypePlugin: Plugin<void[], HastRoot> = () => { /* Empty */ } const rehypeReact: Plugin<void[], HastRoot, ReactNode> = () => { /* Empty */ } // If a plugin is defined with string as input and a node as output, it // configures a parser. expectType<MdastRoot>(unified().use(remarkParse).parse('')) expectType<HastRoot>(unified().use(rehypeParse).parse('')) expectType<Node>(unified().parse('')) // No parser. // If a plugin is defined with a node as input and a non-node as output, it // configures a compiler. expectType<string>(unified().use(remarkStringify).stringify(someMdast)) expectType<string>(unified().use(rehypeStringify).stringify(someHast)) expectType<Buffer>(unified().use(rehypeStringifyBuffer).stringify(someHast)) expectType<unknown>(unified().stringify(someHast)) // No compiler. expectType<ReactNode>(unified().use(rehypeReact).stringify(someHast)) expectError(unified().use(remarkStringify).stringify(someHast)) expectError(unified().use(rehypeStringify).stringify(someMdast)) // Compilers configure the output of `process`, too. expectType<VFile>(unified().use(remarkStringify).processSync('')) expectType<VFile>(unified().use(rehypeStringify).processSync('')) expectType<VFile>(unified().use(rehypeStringifyBuffer).processSync('')) expectType<VFile>(unified().processSync('')) expectType<VFile & {result: ReactNode}>( unified().use(rehypeReact).processSync('') ) // A parser plugin defines the input of `.run`: expectType<MdastRoot>(unified().use(remarkParse).runSync(someMdast)) expectError(unified().use(remarkParse).runSync(someHast)) // A compiler plugin defines the input/output of `.run`: expectError(unified().use(rehypeStringify).runSync(someMdast)) // As a parser and a compiler are set, it can be assumed that the input of `run` // is the result of the parser, and the output is the input of the compiler. expectType<HastRoot>( unified().use(remarkParse).use(rehypeStringify).runSync(someMdast) ) // Probably hast expected. expectError(unified().use(rehypeStringify).runSync(someMdast)) unified() .use(rehypeStringify) .run(someHast) .then((thing) => { expectType<HastRoot>(thing) }) unified() .use(rehypeStringify) .run(someHast, (error, thing) => { expectType<Error | null | undefined>(error) expectType<HastRoot | undefined>(thing) }) // A compiler plugin defines the output of `.process`: expectType<VFile & {result: ReactNode}>( unified().use(rehypeReact).processSync('') ) expectType<VFile & {result: ReactNode}>( unified().use(remarkParse).use(rehypeReact).processSync('') ) unified() .use(rehypeReact) .process('') .then((file) => { expectType<VFile & {result: ReactNode}>(file) }) unified() .use(rehypeReact) .process('', (error, thing) => { expectType<Error | null | undefined>(error) expectType<(VFile & {result: ReactNode}) | undefined>(thing) }) // Plugins work! unified() .use(remarkParse) .use(explicitRemarkPlugin) .use(implicitPlugin) .use(remarkRehype) .use(implicitPlugin) .use(rehypeStringify) .freeze() // Parsers define the input of transformers. unified().use(() => (node) => { expectType<Node>(node) }) unified() .use(remarkParse) .use(() => (node) => { expectType<MdastRoot>(node) }) unified() .use(rehypeParse) .use(() => (node) => { expectType<HastRoot>(node) }) unified() // Using a parser plugin also defines the current tree (see next). .use(remarkParse) // A plugin following a typed parser receives the defined AST. // If it doesn’t resolve anything, that AST remains for the next plugin. .use(() => (node) => { expectType<MdastRoot>(node) }) // A plugin that returns a certain AST, defines it for the next plugin. .use(() => (node) => { expectType<MdastRoot>(node) return someHast }) .use(() => (node) => { expectType<HastRoot>(node) }) .use(rehypeStringify) // Using two parsers or compilers is fine. The last one sticks. const p1 = unified().use(remarkParse).use(rehypeParse) expectType<HastRoot>(p1.parse('')) const p2 = unified().use(remarkStringify).use(rehypeStringify) expectError(p2.stringify(someMdast)) // Using mismatched explicit plugins is fine (for now). unified() .use(explicitRemarkPlugin) .use(explicitRehypePlugin) .use(explicitRemarkPlugin) expectType<HastRoot>( unified() .use(explicitRemarkPlugin) .use(remarkRehype) .use(explicitRehypePlugin) .runSync(someMdast) ) /* eslint-enable @typescript-eslint/no-floating-promises */
the_stack
import * as vscode from 'vscode'; import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter'; import { ExtensionCommands } from '../../ExtensionCommands'; import { FabricSmartContractDefinition, FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, IFabricEnvironmentConnection, LogType, IFabricGatewayConnection, FabricGatewayRegistry, EnvironmentType, FabricGatewayRegistryEntry, EnvironmentFlags } from 'ibm-blockchain-platform-common'; import { URL } from 'url'; import { FabricEnvironmentManager } from '../fabric/environments/FabricEnvironmentManager'; import { SettingConfigurations } from '../configurations'; import { ExtensionUtil } from '../util/ExtensionUtil'; import { UserInputUtil, IBlockchainQuickPickItem } from '../commands/UserInputUtil'; import { FabricGatewayConnectionManager } from '../fabric/FabricGatewayConnectionManager'; import { LocalMicroEnvironment } from '../fabric/environments/LocalMicroEnvironment'; import { LocalMicroEnvironmentManager } from '../fabric/environments/LocalMicroEnvironmentManager'; export abstract class FabricDebugConfigurationProvider implements vscode.DebugConfigurationProvider { static readonly debugEvent: string = 'contractDebugging'; // As we can't detect when a debug session has restarted but instead started, stopped and changed (which includes start/stop), we never set environmentName to undefined. // Instead, we always set environmentName when a user starts a new debug session. // In places such as submitTransaction, we should check there is a correct debug session (with the debugEvent config value) before ever attempting to read environmentName. static environmentName: string; static orgName: string; public static async getInstantiatedChaincode(chaincodeName: string): Promise<FabricSmartContractDefinition> { // Determine what smart contracts are instantiated already // Assume Local Fabric has one peer const connection: IFabricEnvironmentConnection = await this.getConnection(); const allInstantiatedContracts: FabricSmartContractDefinition[] = await connection.getAllCommittedSmartContractDefinitions(); const smartContractVersionName: FabricSmartContractDefinition = allInstantiatedContracts.find((contract: FabricSmartContractDefinition) => { return contract.name === chaincodeName; }); return smartContractVersionName; } public static async connectToGateway(): Promise<boolean> { const gatewayConnection: IFabricGatewayConnection = FabricGatewayConnectionManager.instance().getConnection(); // Get connected gateway registry entry const fabricGatewayRegistryEntry: FabricGatewayRegistryEntry = await FabricGatewayConnectionManager.instance().getGatewayRegistryEntry(); if (!gatewayConnection) { // Connect to local_fabric gateway before submitting/evaluating transaction const runtimeGateway: FabricGatewayRegistryEntry = await FabricGatewayRegistry.instance().get(`${FabricDebugConfigurationProvider.environmentName} - ${FabricDebugConfigurationProvider.orgName} Gateway`); // Assume one runtime gateway registry entry await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_GATEWAY, runtimeGateway); if (!FabricGatewayConnectionManager.instance().getConnection()) { // either the user cancelled or ther was an error so don't carry on return false; } } else if (fabricGatewayRegistryEntry && fabricGatewayRegistryEntry.name !== `${FabricDebugConfigurationProvider.environmentName} - ${FabricDebugConfigurationProvider.orgName} Gateway`) { // Connect to the gateway the user selected initially (for their chosen org) const runtimeGateway: FabricGatewayRegistryEntry = await FabricGatewayRegistry.instance().get(`${FabricDebugConfigurationProvider.environmentName} - ${FabricDebugConfigurationProvider.orgName} Gateway`); await vscode.commands.executeCommand(ExtensionCommands.DISCONNECT_GATEWAY); await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_GATEWAY, runtimeGateway); if (!FabricGatewayConnectionManager.instance().getConnection()) { // either the user cancelled or ther was an error so don't carry on return false; } } return true; } private static async getConnection(): Promise<IFabricEnvironmentConnection> { // check we are connected to the a local fabric let connection: IFabricEnvironmentConnection = FabricEnvironmentManager.instance().getConnection(); if (connection) { let environmentRegistryEntry: FabricEnvironmentRegistryEntry = FabricEnvironmentManager.instance().getEnvironmentRegistryEntry(); if (environmentRegistryEntry.name !== FabricDebugConfigurationProvider.environmentName || environmentRegistryEntry.environmentType !== EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT) { await vscode.commands.executeCommand(ExtensionCommands.DISCONNECT_ENVIRONMENT); environmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricDebugConfigurationProvider.environmentName); await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry); } connection = FabricEnvironmentManager.instance().getConnection(); } else { const environmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricDebugConfigurationProvider.environmentName); await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry); connection = FabricEnvironmentManager.instance().getConnection(); } if (!connection) { throw new Error(`Could not create connection to ${FabricDebugConfigurationProvider.environmentName}`); } return connection; } private runtime: LocalMicroEnvironment; public async resolveDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration> { const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance(); try { // If we're running on Eclipse Che, this is not a supported feature. if (ExtensionUtil.isChe()) { outputAdapter.log(LogType.ERROR, 'Debugging smart contracts is not supported in Eclipse Che or Red Hat CodeReady Workspaces.'); return; } const localFabricEnabled: boolean = ExtensionUtil.getExtensionLocalFabricSetting(); if (!localFabricEnabled) { outputAdapter.log(LogType.ERROR, `Setting '${SettingConfigurations.EXTENSION_LOCAL_FABRIC}' must be set to 'true' to enable debugging.`); return; } const localRuntimes: IBlockchainQuickPickItem<LocalMicroEnvironment>[] = []; const environmentEntries: FabricEnvironmentRegistryEntry[] = await FabricEnvironmentRegistry.instance().getAll([EnvironmentFlags.LOCAL]); // Get only local entries for (const entry of environmentEntries) { const runtime: LocalMicroEnvironment = await LocalMicroEnvironmentManager.instance().ensureRuntime(entry.name, undefined, entry.numberOfOrgs); const isRunning: boolean = await runtime.isRunning(); if (isRunning) { localRuntimes.push({label: entry.name, data: runtime}); } } if (localRuntimes.length === 0) { outputAdapter.log(LogType.ERROR, `No local environments found for debugging.`); return; } const chosenEnvironment: IBlockchainQuickPickItem<LocalMicroEnvironment> = await UserInputUtil.showQuickPickItem('Select a local environment to debug', localRuntimes) as IBlockchainQuickPickItem<LocalMicroEnvironment>; if (!chosenEnvironment) { return; } this.runtime = chosenEnvironment.data; FabricDebugConfigurationProvider.environmentName = this.runtime.getName(); if (!config.env) { config.env = {}; } let chaincodeVersion: string; let chaincodeName: string; if (config.env.CORE_CHAINCODE_ID_NAME) { // User has edited their debug configuration - use their version chaincodeName = config.env.CORE_CHAINCODE_ID_NAME.split(':')[0]; chaincodeVersion = config.env.CORE_CHAINCODE_ID_NAME.split(':')[1]; } else { const nameAndVersion: {name: string, version: string } = await this.getChaincodeNameAndVersion(folder); if (!nameAndVersion || !nameAndVersion.name || !nameAndVersion.version) { // User probably cancelled the prompt for the name. return; } chaincodeName = nameAndVersion.name; chaincodeVersion = nameAndVersion.version; } const replaceRegex: RegExp = /@.*?\//; chaincodeName = chaincodeName.replace(replaceRegex, ''); const smartContract: FabricSmartContractDefinition = await FabricDebugConfigurationProvider.getInstantiatedChaincode(chaincodeName); if (smartContract) { const isContainerRunning: boolean = await this.runtime.isRunning([smartContract.name, smartContract.version]); if (isContainerRunning) { await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'IBM Blockchain Platform Extension', cancellable: false }, async (progress: vscode.Progress<{ message: string }>) => { progress.report({ message: 'Removing chaincode container' }); await this.runtime.killChaincode([smartContract.name, smartContract.version]); }); } } config.env.CORE_CHAINCODE_ID_NAME = `${chaincodeName}:${chaincodeVersion}`; // Allow the language specific class to resolve the configuration. const resolvedConfig: vscode.DebugConfiguration = await this.resolveDebugConfigurationInner(folder, config, token); if (!resolvedConfig) { // Cancel if user hasn't selected an org to debug for. // Will this break anything else? return; } // Launch a *new* debug session with the resolved configuration. // If we leave the name in there, it uses the *old* launch.json configuration with the *new* debug // configuration provider, for example a fabric:go configuration with the go debug configuration // provider. This results in errors and we need to just force it to use our configuration as-is. delete resolvedConfig.name; // We need this in order to differentiate between debug events resolvedConfig.debugEvent = FabricDebugConfigurationProvider.debugEvent; // If the user is connected to a gateway, we should probably disconnect so that if they submit transactions from the tree or command (but not the debug bar). // This will ensure that they submit transactions from the correct gateway. const connected: boolean = await FabricDebugConfigurationProvider.connectToGateway(); if (!connected) { return; } await vscode.commands.executeCommand('setContext', 'blockchain-debug', true); vscode.debug.startDebugging(folder, resolvedConfig); // Cancel the current debug session - the user will never know! return undefined; } catch (error) { outputAdapter.log(LogType.ERROR, `Failed to launch debug: ${error.message}`); return; } } protected abstract async getChaincodeNameAndVersion(folder: vscode.WorkspaceFolder | undefined): Promise<{name: string, version: string}>; protected async getChaincodeAddress(): Promise<string> { // Need to strip off the protocol (grpc:// or grpcs://). if (this.runtime.numberOfOrgs > 1) { const orgNames: string[] = await this.runtime.getAllOrganizationNames(false); const mspName: string = await UserInputUtil.showQuickPick('Select the organization to debug for', orgNames) as string; if (!mspName) { FabricDebugConfigurationProvider.orgName = undefined; return; } const _orgName: string = mspName.substr(0, mspName.indexOf('MSP')); // Strip off 'MSP' so it makes getting the gateway easier. FabricDebugConfigurationProvider.orgName = _orgName; } else { FabricDebugConfigurationProvider.orgName = 'Org1'; // It is unlikely this will change. } const url: string = await this.runtime.getPeerChaincodeURL(FabricDebugConfigurationProvider.orgName); const parsedURL: URL = new URL(url); return parsedURL.host; } protected abstract async resolveDebugConfigurationInner(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): Promise<vscode.DebugConfiguration>; }
the_stack
import * as React from "react"; import { int, innerHeight, innerWidth, outerHeight, outerWidth, parseBounds } from '../utils'; import { DraggerProps } from "./type"; const doc = document type ListenType = 'drag' | 'resize'; var speed = 0; var timer: any = 0; var autoScrolling = false; var autoY = 0; var currentHeight = 0; const ScollPostion = () => { var t = 0, l = 0, w = 0, h = 0; if (document.documentElement && document.documentElement.scrollTop) { t = document.documentElement.scrollTop; l = document.documentElement.scrollLeft; w = document.documentElement.scrollWidth; h = document.documentElement.scrollHeight; } else if (document.body) { t = document.body.scrollTop; l = document.body.scrollLeft; w = document.body.scrollWidth; h = document.body.scrollHeight; } return { top: t, left: l, width: w, height: h }; } export class Dragger extends React.Component<DraggerProps, {}> { parent: any; self: any; ListenMove = (type: ListenType) => { /** 保证用户在移动元素的时候不会选择到元素内部的东西 */ doc.body.style.userSelect = 'none' if (type === 'resize') { doc.addEventListener('mouseup', this.onResizeEnd); doc.addEventListener('mousemove', this.onResizing); return } doc.addEventListener('mousemove', this.move); doc.addEventListener('mouseup', this.onDragEnd); } unListenMove = (type: ListenType) => { doc.body.style.userSelect = '' if (type === 'resize') { doc.removeEventListener('mousemove', this.onResizing) doc.removeEventListener('mouseup', this.onResizeEnd) return } doc.removeEventListener('mousemove', this.move) doc.removeEventListener('mouseup', this.onDragEnd) } constructor(props: DraggerProps) { super(props) this.parent = null; this.self = null; } /** * 初始变量设置 */ static defaultProps = { allowX: true, allowY: true, isUserMove: true } state = { /** x轴位移,单位是px */ x: this.props.x || 0, /** y轴位移,单位是px */ y: this.props.y || 0, /**鼠标点击元素的原始位置,单位是px */ originX: 0, originY: 0, isUserMove: true, /**已经移动的位移,单位是px */ lastX: 0, lastY: 0, /**堆叠的层级 */ zIndex: 1, w: this.props.w || 0, h: this.props.h || 0, lastW: 0, lastH: 0 } move = (event: any) => { let { lastX, lastY } = this.state; /* event.client - this.state.origin 表示的是移动的距离, * elX表示的是原来已经有的位移 */ let deltaX, deltaY; if (event.type.indexOf('mouse') >= 0) { deltaX = (event as MouseEvent).clientX - this.state.originX + lastX deltaY = (event as MouseEvent).clientY - this.state.originY + lastY } else { deltaX = (event as TouchEvent).touches[0].clientX - this.state.originX + lastX deltaY = (event as TouchEvent).touches[0].clientY - this.state.originY + lastY } const { bounds } = this.props if (bounds) { /** * 如果用户指定一个边界,那么在这里处理 */ let NewBounds = typeof bounds !== 'string' ? parseBounds(bounds) : bounds; /** * 网格式移动范围设定,永远移动 n 的倍数 * 注意:设定移动范围的时候,一定要在判断bounds之前,否则会造成bounds不对齐 */ const { grid } = this.props if (Array.isArray(grid) && grid.length === 2) { deltaX = Math.round(deltaX / grid[0]) * grid[0] deltaY = Math.round(deltaY / grid[1]) * grid[1] } if (this.props.bounds === 'parent') { NewBounds = { left: int(this.parent.style.paddingLeft) + int(this.self.style.marginLeft) - this.self.offsetLeft, top: int(this.parent.style.paddingTop) + int(this.self.style.marginTop) - this.self.offsetTop, right: innerWidth(this.parent) - outerWidth(this.self) - this.self.offsetLeft + int(this.parent.style.paddingRight) - int(this.self.style.marginRight), bottom: innerHeight(this.parent) - outerHeight(this.self) - this.self.offsetTop + int(this.parent.style.paddingBottom) - int(this.self.style.marginBottom) } } /** * 保证不超出右边界和底部 * keep element right and bot can not cross the bounds */ if (NewBounds !== 'parent') deltaX = Math.min(deltaX, NewBounds.right) if (NewBounds !== 'parent') deltaY = Math.min(deltaY, NewBounds.bottom) /** * 保证不超出左边和上边 * keep element left and top can not cross the bounds */ if (NewBounds !== 'parent') deltaX = Math.max(deltaX, NewBounds.left) if (NewBounds !== 'parent') deltaY = Math.max(deltaY, NewBounds.top) } /**如果设置了x,y限制 */ deltaX = this.props.allowX ? deltaX : 0 deltaY = this.props.allowY ? deltaY : 0 /** * 调整手感 * 无论是向上移动还是向下移动,全部都是根据重力中心 * */ const height = (this.refs['dragger'] as HTMLDivElement).getClientRects()[0].height; const upNdown = this.state.y - deltaY; const fixY = deltaY + (upNdown >= 0 ? 0 : height / 2); if (!autoScrolling) { /**移动时回调,用于外部控制 */ if (this.props.onMove) this.props.onMove(event, deltaX, fixY) // console.log('del', deltaY); this.setState({ x: deltaX, y: deltaY, }) } if (autoScrolling && speed < 0) { clearInterval(timer); timer = 0; this.setState({//恢复的时候,要设定所有数据是当前的数据 y: this.state.y, lastY: this.state.y, originY: event.clientY, originX: event.clientX }) if (this.props.onMove) this.props.onMove(event, this.state.x, this.state.y) window.scrollTo(0, ScollPostion().top); autoScrolling = false; speed = 0; autoY = 0; } if (autoScrolling) { const check = event.clientY - this.state.originY; speed = check / 3; this.setState({ x: deltaX, lastY: this.state.y, originY: event.clientY, originX: event.clientX }) } if (!autoScrolling && event.clientY > 650) { const totalHeight = document.body.clientHeight - window.innerHeight console.log(totalHeight) autoScrolling = true; currentHeight = ScollPostion().top; timer = setInterval(() => { autoY += speed; if (this.state.y > document.body.clientHeight - 200) clearInterval(timer); window.scrollTo(0, currentHeight + autoY); this.setState({ y: this.state.y + speed, lastY: this.state.y + speed, originY: event.clientY, originX: event.clientX }) if (this.props.onMove) this.props.onMove(event, this.state.x, this.state.y + speed) }) } } onDragStart = (event: any) => { if (this.props.handle) { if (event.target.id !== 'dragact-handle') return } /** * 把监听事件的回掉函数,绑定在document上 * 当设置边界的时候,用户鼠标会离开元素的范围 * 绑定在document上可以使得其依旧能够监听 * 如果绑定在元素上,则鼠标离开元素,就不会再被监听了 */ if (event.type.indexOf('mouse') >= 0) { this.ListenMove('drag'); } else { doc.addEventListener('touchmove', this.move) doc.addEventListener('touchend', this.onDragEnd) } if (this.props.bounds === 'parent' && /**为了让 这段代码不会重复执行 */ (typeof this.parent === 'undefined' || this.parent === null)) { /** * 在这里我们将父节点缓存下来,保证当用户鼠标离开拖拽区域时,我们仍然能获取到父节点 * what we do here is * making sure that we still can retrieve our parent when user's mouse left this node. */ this.parent = (event as any).currentTarget.offsetParent //todo /** * 我们自己 * ourself */ this.self = event.currentTarget } this.props.onDragStart && this.props.onDragStart(this.state.x, this.state.y) let originX, originY; if (event.type.indexOf('mouse') >= 0) { originX = (event as MouseEvent).clientX originY = (event as MouseEvent).clientY } else { originX = (event as TouchEvent).touches[0].clientX originY = (event as TouchEvent).touches[0].clientY } // console.log(originY, this.state.y) this.setState({ originX: originX, originY: originY, lastX: this.state.x, lastY: this.state.y, zIndex: 10 }) } onDragEnd = (event: any) => { /** 取消用户选择限制,用户可以重新选择 */ clearInterval(timer); speed = 0; autoScrolling = false; autoY = 0; currentHeight = 0; this.parent = null this.self = null if (event.type.indexOf('mouse') >= 0) { this.unListenMove('drag'); } else { doc.removeEventListener('touchmove', this.move) doc.removeEventListener('touchend', this.onDragEnd) } this.setState({ zIndex: 1 }) this.props.onDragEnd && this.props.onDragEnd(event, this.state.x, this.state.y) } onResizeStart = (event: React.MouseEvent<HTMLSpanElement>) => { /** 保证用户在移动元素的时候不会选择到元素内部的东西 */ this.ListenMove('resize'); let originX, originY; originX = event.clientX originY = event.clientY this.props.onResizeStart && this.props.onResizeStart(event, this.state.w, this.state.h); this.setState({ originX: originX, originY: originY, zIndex: 2, lastW: this.state.w, lastH: this.state.h }) event.stopPropagation(); } onResizing = (event: any) => { /* event.client - this.state.origin 表示的是移动的距离, * elX表示的是原来已经有的位移 */ let deltaX, deltaY; if (event.type.indexOf('mouse') >= 0) { deltaX = (event as MouseEvent).clientX - this.state.originX deltaY = (event as MouseEvent).clientY - this.state.originY } else { deltaX = (event as TouchEvent).touches[0].clientX - this.state.originX deltaY = (event as TouchEvent).touches[0].clientY - this.state.originY } /**移动时回调,用于外部控制 */ this.props.onResizing && this.props.onResizing(event, this.state.w, this.state.h); this.setState({ w: deltaX + this.state.lastW, h: deltaY + this.state.lastH }) } onResizeEnd = (event: any) => { this.unListenMove('resize'); this.props.onResizeEnd && this.props.onResizeEnd(event, this.state.w, this.state.h); } componentWillReceiveProps(nextProps: DraggerProps) { /** * 外部props 改变的时候更新元素的内部位置 * 这个api设计其实很不好 * 以后可能会修改掉 */ const { isUserMove } = nextProps if (!isUserMove) { if (typeof nextProps.x === 'number' && typeof nextProps.y === 'number') { this.setState({ x: nextProps.x, y: nextProps.y, lastX: nextProps.x, lastY: nextProps.y, w: nextProps.w, h: nextProps.h }) } } } mixin = () => { var dragMix = {}; if (this.props.canDrag === void 666 || this.props.canDrag === true) { dragMix = { onMouseDown: this.onDragStart, onTouchStart: this.onDragStart, onTouchEnd: this.onDragEnd, onMouseUp: this.onDragEnd } } var resizeMix = {} if (this.props.canResize === void 666 || this.props.canDrag === true) { resizeMix = { onMouseDown: this.onResizeStart, onMouseUp: this.onResizeEnd } } return { dragMix, resizeMix }; } render() { var { x, y, w, h } = this.state var { style, className, canResize } = this.props if (!this.props.isUserMove) { /**当外部设置其props的x,y初始属性的时候,我们在这里设置元素的初始位移 */ x = this.props.x ? this.props.x : 0; y = this.props.y ? this.props.y : 0; if (style) { w = (style as any).width ? (style as any).width : w; h = (style as any).height ? (style as any).height : h; } } if (style) { //使得初始化的时候,不会有从0-1缩放动画 w = w === 0 ? (style as any).width : w; h = h === 0 ? (style as any).height : h; } const { dragMix, resizeMix } = this.mixin(); /**主要是为了让用户定义自己的className去修改css */ const fixedClassName = typeof className === 'undefined' ? '' : className + ' ' return ( <div className={`${fixedClassName}WrapDragger`} ref={'dragger'} style={{ ...style, touchAction: 'none!important', transform: `translate3d(${x}px,${y}px,0px)`, width: w, height: h, }} {...dragMix} > {this.props.children ? React.Children.only(this.props.children) : null} {canResize !== false ? <span {...resizeMix} style={{ position: 'absolute', width: 10, height: 10, right: 2, bottom: 2, cursor: 'se-resize', borderRight: '2px solid rgba(15,15,15,0.2)', borderBottom: '2px solid rgba(15,15,15,0.2)' }} /> : null} </div> ) } }
the_stack
* @file Side panel for displaying/editing layer details. */ import 'neuroglancer/ui/layer_side_panel.css'; import svg_cursor from 'ikonate/icons/cursor.svg'; import {changeLayerName, changeLayerType, deleteLayer, layerTypes, ManagedUserLayer, SelectedLayerState, UserLayer} from 'neuroglancer/layer'; import {ElementVisibilityFromTrackableBoolean} from 'neuroglancer/trackable_boolean'; import {CachedWatchableValue, observeWatchable} from 'neuroglancer/trackable_value'; import {LAYER_SIDE_PANEL_DEFAULT_LOCATION, UserLayerSidePanelState} from 'neuroglancer/ui//layer_side_panel_state'; import {popDragStatus, pushDragStatus} from 'neuroglancer/ui/drag_and_drop'; import {DRAG_OVER_CLASSNAME, DragSource, SidePanel, SidePanelManager} from 'neuroglancer/ui/side_panel'; import {RefCounted} from 'neuroglancer/util/disposable'; import {KeyboardEventBinder, registerActionListener} from 'neuroglancer/util/keyboard_bindings'; import {EventActionMap} from 'neuroglancer/util/mouse_bindings'; import {CheckboxIcon} from 'neuroglancer/widget/checkbox_icon'; import {makeDeleteButton} from 'neuroglancer/widget/delete_button'; import {TabView} from 'neuroglancer/widget/tab_view'; const layerNameInputEventMap = EventActionMap.fromObject({ 'escape': {action: 'cancel'}, }); export class LayerNameWidget extends RefCounted { element = document.createElement('input'); constructor(public layer: ManagedUserLayer) { super(); const {element} = this; element.classList.add('neuroglancer-layer-side-panel-name'); element.spellcheck = false; element.autocomplete = 'off'; const keyboardHandler = this.registerDisposer(new KeyboardEventBinder(element, layerNameInputEventMap)); keyboardHandler.allShortcutsAreGlobal = true; registerActionListener(element, 'cancel', event => { this.updateView(); element.blur(); event.stopPropagation(); event.preventDefault(); }); element.title = 'Rename layer'; this.registerDisposer(layer.layerChanged.add(() => this.updateView())); element.addEventListener('change', () => this.updateModel()); element.addEventListener('blur', () => this.updateModel()); this.updateView(); } private updateView() { this.element.value = this.layer.name; } private updateModel() { changeLayerName(this.layer, this.element.value); } } export class LayerTypeWidget extends RefCounted { element = document.createElement('select'); private measureElement = document.createElement('div'); constructor(public layer: UserLayer) { super(); const {element, measureElement} = this; element.classList.add('neuroglancer-layer-side-panel-type'); measureElement.classList.add('neuroglancer-layer-side-panel-type-measure'); element.title = 'Change layer type'; document.body.appendChild(measureElement); for (const [layerType, layerConstructor] of layerTypes) { if (layerConstructor.type !== layerType) continue; const option = document.createElement('option'); option.textContent = layerConstructor.typeAbbreviation; option.value = layerType; element.appendChild(option); } element.addEventListener('change', () => { const newType = element.value; const layerConstructor = layerTypes.get(newType)!; changeLayerType(this.layer.managedLayer, layerConstructor); }); this.updateView(); } private updateView() { const selectedName = this.layer.type; const {element, measureElement} = this; measureElement.textContent = (this.layer.constructor as typeof UserLayer).typeAbbreviation; element.value = selectedName; element.style.width = `${measureElement.offsetWidth}px`; } disposed() { this.measureElement.remove(); } } class LayerSidePanel extends SidePanel { tabView: TabView; layer: UserLayer; constructor(sidePanelManager: SidePanelManager, public panelState: UserLayerSidePanelState) { super(sidePanelManager, panelState.location); const layer = this.layer = panelState.layer; const {element} = this; const {titleBar} = this.addTitleBar({}); titleBar.classList.add('neuroglancer-layer-side-panel-title'); titleBar.appendChild(this.registerDisposer(new LayerTypeWidget(layer)).element); titleBar.appendChild(this.registerDisposer(new LayerNameWidget(layer.managedLayer)).element); this.registerDisposer(observeWatchable(visible => { element.dataset.neuroglancerLayerVisible = visible.toString(); }, { get value() { return layer.managedLayer.visible; }, changed: layer.managedLayer.layerChanged, })); const pickButton = this.registerDisposer(new CheckboxIcon( { get value() { return layer.managedLayer.pickEnabled; }, set value(value: boolean) { layer.managedLayer.pickEnabled = value; }, changed: layer.managedLayer.layerChanged, }, { svg: svg_cursor, enableTitle: 'Spatial object selection: disabled', disableTitle: 'Spatial object selection: enabled' })); this.registerDisposer(new ElementVisibilityFromTrackableBoolean( { get value() { return layer.managedLayer.supportsPickOption; }, changed: layer.managedLayer.layerChanged, }, pickButton.element)); titleBar.appendChild(pickButton.element); const pinWatchable = { get value() { return panelState !== layer.panels.panels[0]; }, set value(value: boolean) { if (value) { panelState.pin(); } else { panelState.unpin(); } }, changed: layer.manager.root.layerManager.layersChanged, }; titleBar.appendChild(this.registerDisposer(new CheckboxIcon(pinWatchable, { // Note: \ufe0e forces text display, as otherwise the pin icon // may as an emoji with color. text: '📌\ufe0e', enableTitle: 'Pin panel to this layer', disableTitle: 'Unpin panel to this layer', })) .element); this.registerDisposer(observeWatchable(pinned => { element.dataset.neuroglancerLayerPanelPinned = pinned.toString(); }, pinWatchable)); titleBar.appendChild(makeDeleteButton({ title: 'Delete layer', onClick: () => { deleteLayer(this.layer.managedLayer); } })); this.tabView = new TabView( { makeTab: id => layer.tabs.options.get(id)!.getter(), selectedTab: panelState.selectedTab, tabs: this.registerDisposer(new CachedWatchableValue({ get value() { return panelState.tabs.map(id => ({ id, label: layer.tabs.options.get(id)!.label, })); }, changed: panelState.tabsChanged, })), handleTabElement: (id: string, element: HTMLElement) => { element.draggable = true; element.addEventListener('dragstart', (event: DragEvent) => { event.stopPropagation(); event.dataTransfer!.setData('neuroglancer-side-panel', ''); let message = 'Drag tab to dock as new panel to the left/right/top/bottom of another panel'; const hasOtherPanel = panelState.panels.panels.find(p => p !== panelState && p.location.visible); if (hasOtherPanel) { message += `, or move tab to other ${JSON.stringify(layer.managedLayer.name)} panel`; } pushDragStatus(element, 'drag', message); this.sidePanelManager.startDrag( { dropAsNewPanel: location => { this.panelState.splitOffTab( id, {...LAYER_SIDE_PANEL_DEFAULT_LOCATION, ...location}); }, canDropAsTabs: target => { if ((target instanceof LayerSidePanel) && target.layer === this.layer && target !== this) { return 1; } return 0; }, dropAsTab: target => { this.panelState.moveTabTo(id, (target as LayerSidePanel).panelState); }, }, event); }); element.addEventListener('dragend', (event: DragEvent) => { event; popDragStatus(element, 'drag'); this.sidePanelManager.endDrag(); }); }, }, this.visibility); this.tabView.element.style.flex = '1'; this.tabView.element.classList.add('neuroglancer-layer-side-panel-tab-view'); this.tabView.element.style.position = 'relative'; this.tabView.element.appendChild(this.makeTabDropZone()); this.addBody(this.tabView.element); // Hide panel automatically if there are no tabs to display (because they have all been moved to // another panel). this.registerDisposer(panelState.tabsChanged.add(() => { if (panelState.tabs.length === 0) { this.location.visible = false; } })); } makeDragSource(): DragSource { return { ...super.makeDragSource(), canDropAsTabs: target => { if ((target instanceof LayerSidePanel) && target.layer === this.layer && target !== this) { return this.panelState.tabs.length; } return 0; }, dropAsTab: target => { this.panelState.mergeInto((target as LayerSidePanel).panelState); }, }; } private makeTabDropZone() { const element = document.createElement('div'); element.className = 'neuroglancer-side-panel-drop-zone'; element.style.position = 'absolute'; element.style.left = '20px'; element.style.right = '20px'; element.style.bottom = '20px'; element.style.top = '20px'; element.addEventListener('dragenter', event => { const {dragSource} = this.sidePanelManager; const numTabs = dragSource?.canDropAsTabs?.(this); if (!numTabs) return; element.classList.add(DRAG_OVER_CLASSNAME); pushDragStatus( element, 'drop', `Move ${numTabs} ${numTabs === 1 ? 'tab' : 'tabs'} to this panel`); event.preventDefault(); }); element.addEventListener('dragleave', () => { popDragStatus(element, 'drop'); element.classList.remove(DRAG_OVER_CLASSNAME); }); element.addEventListener('dragover', event => { const {dragSource} = this.sidePanelManager; if (!dragSource?.canDropAsTabs?.(this)) return; event.preventDefault(); }); element.addEventListener('drop', event => { popDragStatus(element, 'drop'); const {dragSource} = this.sidePanelManager; if (!dragSource?.canDropAsTabs?.(this)) return; element.classList.remove(DRAG_OVER_CLASSNAME); dragSource.dropAsTab!(this); event.preventDefault(); event.stopPropagation(); }); return element; } } export class LayerSidePanelManager extends RefCounted { placeholderSelectedLayerPanel: (() => void)|undefined; layerSidePanels = new Map<UserLayerSidePanelState, {generation: number, unregister: (() => void)}>(); private generation = 0; private layersNeedUpdate = true; constructor( public sidePanelManager: SidePanelManager, public selectedLayerState: SelectedLayerState) { super(); const handleUpdate = () => { this.layersNeedUpdate = true; this.sidePanelManager.display.scheduleRedraw(); }; this.registerDisposer(selectedLayerState.changed.add(handleUpdate)); this.registerDisposer(selectedLayerState.layerManager.layersChanged.add(handleUpdate)); this.registerDisposer(sidePanelManager.beforeRender.add(() => this.update())); } private getSelectedUserLayer() { return this.selectedLayerState.layer?.layer ?? undefined; } private update() { if (!this.layersNeedUpdate) return; const {layerManager} = this.selectedLayerState; let generation = ++this.generation; this.layersNeedUpdate = false; const {layerSidePanels} = this; const ensurePanel = (panelState: UserLayerSidePanelState) => { let existing = layerSidePanels.get(panelState); if (existing === undefined) { existing = { generation, unregister: this.sidePanelManager.registerPanel({ location: panelState.location, makePanel: () => new LayerSidePanel(this.sidePanelManager, panelState) }) }; layerSidePanels.set(panelState, existing); } else { existing.generation = generation; } }; // Add selected layer panel { const layer = this.getSelectedUserLayer(); const {location} = this.selectedLayerState; if (layer === undefined || !location.visible) { if (this.placeholderSelectedLayerPanel === undefined) { this.placeholderSelectedLayerPanel = this.sidePanelManager.registerPanel( {location, makePanel: () => new SidePanel(this.sidePanelManager, location)}); } } else { this.placeholderSelectedLayerPanel?.(); this.placeholderSelectedLayerPanel = undefined; const panelState = layer.panels.panels[0]; panelState.location.value = location.value; ensurePanel(panelState); } } // Add extra layer panels for (const layer of layerManager.managedLayers) { const userLayer = layer.layer; if (userLayer === null) continue; const {panels} = userLayer.panels; for (let i = 1, length = panels.length; i < length; ++i) { ensurePanel(panels[i]); } } for (const [panelState, existing] of layerSidePanels) { if (existing.generation === generation) continue; existing.unregister(); layerSidePanels.delete(panelState); } } disposed() { this.placeholderSelectedLayerPanel?.(); for (const {unregister} of this.layerSidePanels.values()) { unregister(); } } }
the_stack
import * as vscode from 'vscode'; import * as util from './util'; interface CellPosition { line: number, column: number, row: number } export class TableEditor { editor: vscode.TextEditor; tableRange: vscode.Range; tableLineNumbers: number[]|undefined; selectedCellPosition: CellPosition; constructor(editor:vscode.TextEditor) { this.editor = editor; this.tableLineNumbers = util.tableIsSelected(this.editor); this.tableRange = this._tableRange(); this.selectedCellPosition = this.selectedCellColumn(); } public async reformat() { this.tableLineNumbers = util.tableIsSelected(this.editor); const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); const insertText = this._generateTableString(cellContents, hasHeader); const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); } public async createEmptyGrid() { let [row, column] = util.tableSizeIsSelected(this.editor); const inputResult = await vscode.window.showQuickPick(["With Header", "Without Header"]) if (!inputResult) { return } const header = (inputResult === "With Header"); if (header) { row += 1; } const contentsLine = new Array(column).fill(""); // ""-filled array: ["", "", "".....] const cellContents = new Array(row).fill(contentsLine); // []-filled array: [["", ""], ["", ""], ["", ""].....] const insertText = this._generateTableString(cellContents, header); const curLine = this.editor.selection.start.line; const curLineRange = this.editor.document.lineAt(curLine).range; const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { editBuilder.replace(curLineRange, insertText); }, editOptions); const newPos = new vscode.Position(curLine+1, 2); this.editor.selection = new vscode.Selection(newPos, newPos); } public async dataToTable() { if (this.editor.selection.isEmpty) { return } const selection = this.editor.selection; const startPos = new vscode.Position(selection.start.line, 0); const endLine = selection.end.line; const endLastChar = this.editor.document.lineAt(endLine).range.end.character; const endPos = new vscode.Position(endLine, endLastChar); const data = this.editor.document.getText(new vscode.Range(startPos, endPos)); const dataLines = data.split(/\r\n|\r|\n/); // First, we will parse the selected csv format string. let cellContents:string[][] = []; for (let i = 0; i < dataLines.length; i++) { const dataLine = dataLines[i]; const contents = dataLine.split(","); cellContents.push([]); for (let j = 0; j < contents.length; j++) { let content = contents[j]; content = content.trim(); content = content.replace(/(\s)\s*/g, "$1"); cellContents[i].push(content); } } const inputResult = await vscode.window.showQuickPick(["With Header", "Without Header"]) if (!inputResult) { return } const header = (inputResult == "With Header"); const insertText = this._generateTableString(cellContents, header); const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { editBuilder.replace(new vscode.Range(startPos, endPos), insertText); }, editOptions); const newPos = new vscode.Position(startPos.line+1, 2); this.editor.selection = new vscode.Selection(newPos, newPos); } private _generateTableString(cellContents:string[][], header:boolean):string { // Record the maximum number of characters in each column in an array (At least three.) let cellStrLengthList:number[] = []; for (let i = 0; i < cellContents.length; i++) { for (let j = 0; j < cellContents[i].length; j++) { if (j > cellStrLengthList.length-1) { cellStrLengthList.push(3) } const content = cellContents[i][j]; const rows = content.split(/\r\n|\r|\n/); for (let k = 0; k < rows.length; k++) { const row = rows[k]; let strCount = util.countTextWidth(row); if (rows.length > 1) { strCount -= 1; } cellStrLengthList[j] = Math.max(cellStrLengthList[j], strCount); } } } // GenerateGrid let gridRow:string = ""; let headerRow:string = ""; for (let i = 0; i < cellStrLengthList.length; i++) { const width = cellStrLengthList[i] + 2; gridRow += `+${"-".repeat(width)}`; // +----- headerRow += `+${"=".repeat(width)}`; // +===== } gridRow += `+`; // +-----+----+---+ headerRow += `+`; // +=====+====+===+ let insertTextLines:string[] = []; for (let i = 0; i < cellContents.length; i++) { if (i == 0) { insertTextLines.push(gridRow); // +-----+----+---+ // roof } let multiLineCell:string[][] = []; const columnContents = cellContents[i]; for (let columnIndex = 0; columnIndex < columnContents.length; columnIndex++) { const cellText = columnContents[columnIndex]; const cellTextSplit = cellText.split(/\r\n|\r|\n/); if (columnIndex == 0) { for (let j = 0; j < cellTextSplit.length; j++) { multiLineCell.push([]); // []-filled array:[[], [].....] } } for (let lineIndex = 0; lineIndex < cellTextSplit.length; lineIndex++) { const contentLine = cellTextSplit[lineIndex]; multiLineCell[lineIndex].push(contentLine) } } for (let lineIndex = 0; lineIndex < multiLineCell.length; lineIndex++) { let cellRow:string = ""; const lineTextList = multiLineCell[lineIndex]; for (let columnIndex = 0; columnIndex < cellStrLengthList.length; columnIndex++) { const textMaxWidth = cellStrLengthList[columnIndex]; let content = lineTextList[columnIndex]; if (columnIndex < lineTextList.length) { const strCount = util.countTextWidth(content); const missingSpaces = `${" ".repeat(textMaxWidth-strCount+1)}`; if (multiLineCell.length > 1) { cellRow += `|${content}${missingSpaces} `; // || ABC } else { cellRow += `| ${content}${missingSpaces}`; // | ABC } } else { cellRow += `|${" ".repeat(textMaxWidth+2)}`; // |..... } } cellRow += `|`; // | ABC | DE | F | insertTextLines.push(cellRow); // | ABC | DE | F | } if (i == 0 && header) { insertTextLines.push(headerRow); // +=====+====+===+ } else { insertTextLines.push(gridRow); // +-----+----+---+ } } return insertTextLines.join("\n"); } private _hasHeader(): boolean { if (!this.tableLineNumbers) { return false } // Various regular expressions const regGridHeaderLine = /^\+=(=|\+)+=\+$/; for (let i = 0; i < this.tableLineNumbers.length; i++) { const tableLine = this.tableLineNumbers[i]; let lineText = this.editor.document.lineAt(tableLine).text; lineText = lineText.trim(); const gridHeaderLineMatch = regGridHeaderLine.exec(lineText); if (gridHeaderLineMatch) { return true } } return false } private _getCellContents(): string[][] { if (!this.tableLineNumbers) { return [] } // Various regular expressions const regContentsLine = /^(\+)?\|.+\|(\+)?$/; const regCellContents = /(?<=\|(\+|-)?([<>^v])*) (?<content>([^|]|(\*\|\*)|(\`\|\`))*?) (?=([<>^v])*(\+|-)?\|)/g; let curLineKind:("contents"|undefined); const cellContents:string[][] = []; for (let i = 0; i < this.tableLineNumbers.length; i++) { const tableLine = this.tableLineNumbers[i]; let lineText = this.editor.document.lineAt(tableLine).text; lineText = lineText.trim(); const contentsLine = regContentsLine.exec(lineText); if (!contentsLine) { curLineKind = undefined; continue } if (curLineKind != "contents") { cellContents.push([]); } let columnIndex = 0; var match; while (match = regCellContents.exec(lineText)) { if (!match?.groups) { continue } let content = match.groups["content"]; content = content.trim(); content = content.replace(/(\s)\s*/g, "$1"); if (curLineKind != "contents") { cellContents[cellContents.length-1].push(content); } else { let prevContent = cellContents[cellContents.length-1][columnIndex]; if (!prevContent) { prevContent = ` `; } else if (!prevContent.startsWith(" ")) { prevContent = ` ${prevContent}`; } cellContents[cellContents.length-1][columnIndex] = `${prevContent}\n ${content}`; columnIndex += 1; } } curLineKind = "contents"; } return cellContents } private _tableRange(): vscode.Range { if (this.tableLineNumbers) { const startPos = new vscode.Position(this.tableLineNumbers[0], 0); const endLine = this.tableLineNumbers[this.tableLineNumbers.length-1]; const endLastChar = this.editor.document.lineAt(endLine).range.end.character; const endPos = new vscode.Position(endLine, endLastChar); return new vscode.Range(startPos, endPos); } else { const startPos = new vscode.Position(0, 0); const endPos = new vscode.Position(0, 0); return new vscode.Range(startPos, endPos); } } public isSelectedFirstGrid(): boolean { const curLine = this.editor.selection.start.line; const tableRange = this._tableRange(); const tableStartLine = tableRange.start.line; return (curLine == tableStartLine) } public isSelectedLastGrid(): boolean { const curLine = this.editor.selection.end.line; const tableRange = this._tableRange(); const tableLastLine = tableRange.end.line; return (curLine == tableLastLine) } public selectedCellColumn():CellPosition { const curLine = this.editor.selection.start.line; const curChar = this.editor.selection.start.character; const lineText = this.editor.document.lineAt(curLine).text; const regContentsLine = /^\+?\|.+\|\+?$/; const regCellContents = /(?<=\|)(?<cell>(\+|-)?([<>v^])* .*? ([<>v^])*(\+|-)?)(?=\|)/g; let column = -1; let row = -1; if (!regContentsLine.exec(lineText) || !this.tableLineNumbers) { const selectedCell:CellPosition = { line: curLine, column: column, row: row } return selectedCell } // Column Index let match; while (match = regCellContents.exec(lineText)) { if (!match?.groups) { continue } column += 1; const matchIndex = match.index; const cellText = match.groups["cell"]; const lastIndex = matchIndex + cellText.length; if (curChar <= lastIndex) { break } } // Row Index let curLineKind:("contents"|undefined); for (let i = 0; i < this.tableLineNumbers.length; i++) { const lineNumber = this.tableLineNumbers[i]; const lineText = this.editor.document.lineAt(lineNumber).text; if (!regContentsLine.exec(lineText)) { curLineKind = undefined; continue } if (!curLineKind) { row += 1; curLineKind = "contents"; } if (lineNumber >= curLine) { break } } const selectedCell:CellPosition = { line: curLine, column: column, row: row } return selectedCell } public selectCellContent(cellPosition:CellPosition, offset?:("top"|"buttom"|"left"|"right"), offsetType?:("cellIndex"|"lineNumber")) { if (!this.tableLineNumbers) { return } let lineNumber = cellPosition.line; let rowIndex = cellPosition.row; let columnIndex = cellPosition.column; if (rowIndex == -1) { rowIndex = 0; } if (columnIndex == -1) { columnIndex = 0; } let curLine = lineNumber; if (offset == "top") { curLine -= 1; rowIndex -= 1; } else if (offset == "buttom") { curLine += 1; rowIndex += 1; } else if (offset == "right") { columnIndex += 1; } else if (offset == "left") { columnIndex -= 1; } // Calc Row Number let lineText = ""; const regContentsLine = /^\|.+\|$/; if (offsetType == "cellIndex") { let curRowIndex = -1; let curLineKind:("contents"|undefined); for (let i = 0; i < this.tableLineNumbers.length; i++) { const curLineNumber = this.tableLineNumbers[i]; const lineText = this.editor.document.lineAt(curLineNumber).text; if (!regContentsLine.exec(lineText)) { curLineKind = undefined; continue } if (!curLineKind) { curRowIndex += 1; curLineKind = "contents"; } if (curRowIndex >= rowIndex) { lineNumber = curLineNumber; break } } lineText = this.editor.document.lineAt(lineNumber).text; } else { let matchedContentsLine = false; if (offset == "top" || offset == "buttom") { while (this.tableLineNumbers.includes(curLine)) { lineText = this.editor.document.lineAt(curLine).text; if (!regContentsLine.exec(lineText)) { if (offset == "top") { curLine -= 1; } else if (offset == "buttom") { curLine += 1; } } else { matchedContentsLine = true; lineNumber = curLine; break } } } if (!matchedContentsLine) { lineText = this.editor.document.lineAt(lineNumber).text; } } // Get Column Index (match.index) const regCellContents = /(?<=\|)(?<cell> ([^|]|(\*\|\*)|(\`\|\`))* )(?=\|)/g; let curColumn = 0; let match; while (match = regCellContents.exec(lineText)) { if (curColumn >= columnIndex) { break } curColumn += 1; } if (!match?.groups) { return } const matchIndex = match.index; const cellText = match.groups["cell"]; // Index of characters to select const regAllSpaces = /^(\s+)$/; const regWord = /^(\s*)(.*?)\s*$/; const allSpaceMatch = regAllSpaces.exec(cellText); const wordMatch = regWord.exec(cellText); let wordFirstIndex = 0; let wordLastIndex = 0; if (allSpaceMatch) { wordFirstIndex = matchIndex + 1; wordLastIndex = wordFirstIndex; } else if (wordMatch) { const cellSpeces = wordMatch[1]; const cellWordText = wordMatch[2]; wordFirstIndex = matchIndex + wordMatch.index + cellSpeces.length; wordLastIndex = wordFirstIndex + cellWordText.length; } // Range const newPosStart = new vscode.Position(lineNumber, wordFirstIndex); const newPosEnd = new vscode.Position(lineNumber, wordLastIndex); this.editor.selection = new vscode.Selection(newPosStart, newPosEnd) } public async selectionChange(moveTo:("top"|"buttom"|"right"|"left")) { await this.reformat(); this.selectCellContent(this.selectedCellPosition, moveTo); } public async addNewLine() { const curLine = this.editor.selection.start.line; const curTextLine = this.editor.document.lineAt(curLine); const lineText = curTextLine.text; const lineEndPosition = curTextLine.range.end; const regCellContents = /(?<=\|)( .*? )(?=\|)/g; const emptyRow = lineText.replace(regCellContents, " "); const insertText = `\n${emptyRow}`; const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { editBuilder.replace(lineEndPosition, insertText); }, editOptions); await this.reformat(); this.selectCellContent(this.selectedCellPosition, "buttom"); } public async addRow() { if (!this.tableLineNumbers) { return } const curLine = this.editor.selection.start.line; let startIndex = this.tableLineNumbers.indexOf(curLine); if (startIndex == -1) { return } else if (startIndex == 0) { startIndex += 1; } const regGridLine = /^\+(-|=)(\1|\+)+\1\+$/; let insertRowLineNumber = startIndex; for (let i = startIndex; i < this.tableLineNumbers.length; i++) { const tableLine = this.tableLineNumbers[i]; const lineText = this.editor.document.lineAt(tableLine).text; const gridLineMatch = regGridLine.exec(lineText); if (gridLineMatch) { insertRowLineNumber = this.tableLineNumbers[i]; break } } // Get information about the content const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); const insertRowIndex = this.selectedCellPosition.row + 1; cellContents.splice(insertRowIndex, 0, [""]); // Updating a table const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const insertText = this._generateTableString(cellContents, hasHeader); const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); // Select a cell this.tableLineNumbers = util.tableIsSelected(this.editor); this.selectedCellPosition.column = 0; this.selectedCellPosition.line = insertRowLineNumber; this.selectCellContent(this.selectedCellPosition, "buttom", "cellIndex"); } public async removeRow() { await this.reformat(); this.selectCellContent(this.selectedCellPosition); } public async moveRow(moveTo:("top"|"bottom")) { if (!this.tableLineNumbers) { return } const numOfTimesToMove = this._getNumberOfTimesToMove(moveTo); // Get information about the content const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); // Rowの入れ替え const row_from = this.selectedCellPosition.row; let row_to = row_from + numOfTimesToMove; if (row_to < 0) { row_to = 0; } else if (row_to > cellContents.length-1) { row_to = cellContents.length - 1; } const moveRowContents = cellContents[row_from]; cellContents.splice(row_from, 1); // 要素(行)を削除 cellContents.splice(row_to, 0, moveRowContents); // 要素(行)を追加 // Updating a table const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const insertText = this._generateTableString(cellContents, hasHeader); const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); // Select a cell this.selectedCellPosition.row = row_to; this.selectCellContent(this.selectedCellPosition); } public async addColumn() { if (!this.tableLineNumbers) { return } // Locate the operator. let addLastColumn = util.isSelectingLastChara(); const curLine = this.editor.selection.start.line; const curLineText = this.editor.document.lineAt(curLine).text; const regContents = /(?<=\|)(\+?)( .*? )(\+?)(?=\|)/g; let match; let afterOperator; while (match = regContents.exec(curLineText)) { if (match[3]) { afterOperator = match[3]; break } } // Get information about the content const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); // Make sure that each line has a newline. let newLineCount:number[] = []; for (var i = 0; i < cellContents.length; i++) { newLineCount.push(0); const rowContents = cellContents[i] for (let j = 0; j < rowContents.length; j++) { const cellContent = rowContents[j]; const lineCount = cellContent.split(/\r\n|\r|\n/).length; newLineCount[i] = Math.max(newLineCount[i], lineCount); } } // Add a column to each row. let insertColumnIndex = this.selectedCellPosition.column; if (afterOperator || addLastColumn) { insertColumnIndex += 1; } for (var i = 0; i < cellContents.length; i++) { const rowContents = cellContents[i]; if (newLineCount[i] > 1) { rowContents.splice(insertColumnIndex, 0, `${"\n".repeat(newLineCount[i]-1)}`); // 要素を追加 } else { rowContents.splice(insertColumnIndex, 0, ""); // 要素を追加 } } // Updating a table const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const insertText = this._generateTableString(cellContents, hasHeader); const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); // Select a cell if (curLineText.startsWith("+|")) { this.selectedCellPosition.column = 0; } else if (afterOperator || addLastColumn) { this.selectedCellPosition.column += 1; } this.selectCellContent(this.selectedCellPosition); } public async removeColumn() { if (!this.tableLineNumbers) { return } // Get information about the content const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); const delColumnIndex = this.selectedCellPosition.column; for (var i = 0; i < cellContents.length; i++) { const rowContents = cellContents[i] rowContents.splice(delColumnIndex, 1); // 要素を削除 } // Updating a table const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const insertText = this._generateTableString(cellContents, hasHeader); const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); // Select a cell const curColumn = this.selectedCellPosition.column if (curColumn > 0) { this.selectedCellPosition.column -= 1; } else { this.selectedCellPosition.column = 0; } this.selectCellContent(this.selectedCellPosition); } public async moveColumn(moveTo:("right"|"left")) { if (!this.tableLineNumbers) { return } const numOfTimesToMove = this._getNumberOfTimesToMove(moveTo); // Get information about the content const cellContents:string[][] = this._getCellContents(); const hasHeader:boolean = this._hasHeader(); // Columnの入れ替え const column_from = this.selectedCellPosition.column; let column_to = column_from + numOfTimesToMove; if (column_to < 0) { column_to = 0; } else if (column_to > cellContents[0].length-1) { column_to = cellContents[0].length - 1; } for (var i = 0; i < cellContents.length; i++) { const rowContents = cellContents[i]; const moveColumnContent = rowContents[column_from]; rowContents.splice(column_from, 1); // 要素を削除 rowContents.splice(column_to, 0, moveColumnContent); // 要素を追加 } // Updating a table const editOptions = {undoStopBefore: false, undoStopAfter: false} await this.editor.edit((editBuilder) => { const insertText = this._generateTableString(cellContents, hasHeader); const tableRange = this._tableRange(); editBuilder.replace(tableRange, insertText); }, editOptions); // Select a cell this.selectedCellPosition.column = column_to; this.selectCellContent(this.selectedCellPosition); } private _getNumberOfTimesToMove(moveTo:("top"|"bottom"|"right"|"left")):number { let checkChar = ""; if (moveTo == "top") { checkChar = "^"; } else if (moveTo == "bottom") { checkChar = "v"; } else if (moveTo == "right") { checkChar = ">"; } else if (moveTo == "left") { checkChar = "<"; } const curLine = this.editor.selection.start.line; const curLineCharList = this.editor.document.lineAt(curLine).text.split(""); let curChar = this.editor.selection.start.character - 1; let numOfTimesToMove = 0; while (curChar >= 0) { if (checkChar != curLineCharList[curChar]) { break } numOfTimesToMove += 1; curChar -= 1; } if (moveTo == "right" || moveTo == "bottom") { return numOfTimesToMove } else { return -numOfTimesToMove } } }
the_stack
import { tortillaBeforeAll, tortillaBeforeEach } from './tests-helper'; import './custom-matchers'; import * as Fs from 'fs-extra'; import * as Tmp from 'tmp'; import { Paths } from '../src/paths'; let context: any = {}; describe('Dump', () => { beforeAll(() => { tortillaBeforeAll.bind(context)(); context.dumpFile = Tmp.tmpNameSync(); context.readDumpFile = parse => { const dumpContent = Fs.readFileSync(context.dumpFile).toString(); return parse ? JSON.parse(dumpContent) : dumpContent; }; }); beforeEach(tortillaBeforeEach.bind(context)); afterEach(() => { Fs.removeSync(context.dumpFile); }); describe('create()', () => { it('should dump all branches which has at least a single release', () => { const testBranches = ['foo', 'bar', 'baz']; testBranches.forEach(branchName => { context.git(['checkout', '-b', branchName]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release`]); context.git(['checkout', 'master']); }); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/branches-dump.json'); }); it('should track history branch from remotes/origin if not exists', () => { const testBranches = ['foo', 'bar', 'baz']; testBranches.forEach(branchName => { context.git(['checkout', '-b', branchName]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release`]); context.git(['checkout', 'master']); }); context.git(['push', 'origin', '--all']); testBranches.forEach(branchName => { context.git(['branch', '-D', `${branchName}-history`]) }); context.tortilla(['dump', 'create', context.dumpFile]); testBranches.forEach(branchName => { expect(() => { context.git(['rev-parse', `${branchName}-history`]); }).not.toThrowError(); }); }); it('should dump all releases - sorted by chronological order', () => { context.tortilla(['release', 'bump', 'minor', '-m', 'master release 1']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 2']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 3']); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/releases-dump.json'); }); it('should dump all manuals - views should have no headers nor footers', () => { const comments = ['foo', 'bar', 'baz']; comments.forEach((comment, index) => { const step = index + 1; context.tortilla(['step', 'tag', '-m', comment]); context.tortilla(['step', 'edit', step]); Fs.writeFileSync(`${Paths.manuals.templates}/step${step}.tmpl`, comment); context.tortilla(['manual', 'render', step]); context.git(['add', '.']); context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); }); context.tortilla(['release', 'bump', 'minor', '-m', 'master release']); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/manuals-dump.json'); }); it('should dump distinct manuals for 2 different releases', () => { context.tortilla(['step', 'edit', '--root']); Fs.writeFileSync(`${Paths.manuals.templates}/root.tmpl`, 'release 1'); context.git(['add', Paths.manuals.templates]) context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 1']); context.tortilla(['step', 'edit', '--root']); Fs.writeFileSync(`${Paths.manuals.templates}/root.tmpl`, 'release 2'); context.git(['add', Paths.manuals.templates]) context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 2']); context.tortilla(['step', 'edit', '--root']); Fs.writeFileSync(`${Paths.manuals.templates}/root.tmpl`, 'release 3'); context.git(['add', Paths.manuals.templates]) context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 3']); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/distinct-dump.json'); }); it('should dump all - mixed scenario', () => { // Manuals dump const comments = ['foo', 'bar', 'baz']; comments.forEach((comment, index) => { const step = index + 1; context.tortilla(['step', 'tag', '-m', comment]); context.tortilla(['step', 'edit', step]); Fs.writeFileSync(`${Paths.manuals.templates}/step${step}.tmpl`, comment); context.tortilla(['manual', 'render', step]); context.git(['add', '.']); context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); }); const testBranches = ['foo', 'bar', 'baz']; testBranches.forEach(branchName => { context.git(['checkout', '-b', branchName]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release 1`]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release 2`]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release 3`]); context.git(['checkout', 'master']); }); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/mixed-dump.json'); }); it('should be able to filter branches', () => { const testBranches = ['foo', 'bar', 'baz', 'qux']; testBranches.forEach(branchName => { context.git(['checkout', '-b', branchName]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release`]); context.git(['checkout', 'master']); }); context.tortilla(['dump', 'create', context.dumpFile, '--filter', 'foo bar baz']); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/branches-dump.json'); }); it('should be able to reject branches', () => { const testBranches = ['foo', 'bar', 'baz', 'qux']; testBranches.forEach(branchName => { context.git(['checkout', '-b', branchName]); context.tortilla(['release', 'bump', 'minor', '-m', `${branchName} release`]); context.git(['checkout', 'master']); }); context.tortilla(['dump', 'create', context.dumpFile, '--reject', 'qux']); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/branches-dump.json'); }); it('should create dirs recursively if output not dir not exist', () => { const out = `${context.dumpFile}/foo/bar/baz.json`; context.tortilla(['dump', 'create', out]); expect(context.exists(out, 'file')).toBeTruthy(); }); it('should create a tutorial.json file inside dir if already exists', () => { Fs.mkdirSync(context.dumpFile); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.exists(`${context.dumpFile}/tutorial.json`, 'file')); }); it('should create a dump file for a tutorial which includes submodules', () => { const submodule = `${context.testDir}/module`; context.tortilla(['step', 'edit', '--root']); context.tortilla(['create', 'submodule', '-o', submodule], { env: { GIT_EDITOR: true } }); // Create submodule and release initial version context.scopeEnv(() => { context.exec('sh', ['-c', 'echo foo > file'], { cwd: submodule }); context.git(['add', 'file'], { cwd: submodule }); context.tortilla(['step', 'push', '-m', 'add file'], { cwd: submodule }); context.tortilla(['step', 'tag', '-m', 'how to add file'], { cwd: submodule }); context.tortilla(['release', 'bump', 'minor', '-m', 'release foo'], { cwd: submodule }); }, { TORTILLA_CWD: submodule }); // Amend submodule and release initial version context.git(['submodule', 'add', './module']); context.git(['add', '.']); context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); context.setPromptAnswers(['master@0.1.0']); context.tortilla(['release', 'bump', 'minor', '-m', 'release foo']); context.tortilla(['step', 'edit', '--root']); // Release a second version of the submodule context.scopeEnv(() => { context.git(['checkout', 'master']); context.tortilla(['step', 'edit', '1.1'], { cwd: submodule }); context.exec('sh', ['-c', 'echo bar > file'], { cwd: submodule }); context.git(['add', 'file'], { cwd: submodule }); context.git(['commit', '--amend'], { cwd: submodule, env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue'], { cwd: submodule }); context.tortilla(['release', 'bump', 'major', '-m', 'release bar'], { cwd: submodule }); }, { TORTILLA_CWD: submodule }); // Release a second version of the main module context.git(['add', '.']); context.git(['commit', '--amend'], { env: { GIT_EDITOR: true } }); context.git(['rebase', '--continue']); context.setPromptAnswers(['master@1.0.0']); context.tortilla(['release', 'bump', 'major', '-m', 'release bar']); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/submodules-dump.json'); }); it.only('should dump keywords for each chapter', () => { let pack pack = Fs.readJsonSync(Paths.npm.package); pack.keywords = ['tutorial', 'master', 'chapter 1', 'release 1']; Fs.writeFileSync(Paths.npm.package, JSON.stringify(pack, null, 2)); context.git(['add', Paths.npm.package]); context.tortilla(['step', 'tag', '-m', 'chapter I']); pack = Fs.readJsonSync(Paths.npm.package); pack.keywords = ['tutorial', 'master', 'chapter 2', 'release 1']; Fs.writeFileSync(Paths.npm.package, JSON.stringify(pack, null, 2)); context.git(['add', Paths.npm.package]); context.tortilla(['step', 'tag', '-m', 'chapter II']); pack = Fs.readJsonSync(Paths.npm.package); pack.keywords = ['tutorial', 'master', 'chapter 3', 'release 1']; Fs.writeFileSync(Paths.npm.package, JSON.stringify(pack, null, 2)); context.git(['add', Paths.npm.package]); context.tortilla(['step', 'tag', '-m', 'chapter III']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 1']); context.tortilla(['dump', 'create', context.dumpFile]); expect(context.readDumpFile()).toContainSameContentAsFile('dumps/keywords-dump.json'); }); }); describe('diffReleases()', () => { it('should print the differences between 2 specified releases based on given dump file', () => { context.tortilla(['release', 'bump', 'minor', '-m', 'master release 1']); Fs.writeFileSync(`${context.cwd()}/foo`, 'foo'); context.git(['add', `${context.cwd()}/foo`]); context.tortilla(['step', 'push', '-m', 'added foo']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 2']); Fs.writeFileSync(`${context.cwd()}/bar`, 'bar'); context.git(['add', `${context.cwd()}/bar`]); context.tortilla(['step', 'push', '-m', 'added bar']); context.tortilla(['release', 'bump', 'minor', '-m', 'master release 3']); context.tortilla(['dump', 'create', context.dumpFile]); const diff = context.tortilla(['dump', 'diff-releases', context.dumpFile, 'master@0.1.0', 'master@0.3.0']); expect(diff).toContainSameContentAsFile('releases.diff'); }); it('should handle changes in binary files', () => { const dumpPath = context.resolveInputPath('dumps/binary-dump.json'); let diff; // Binary added diff = context.tortilla(['dump', 'diff-releases', dumpPath, 'master@0.1.0', 'master@0.2.0']); expect(diff).toEqual(context.trimIndents(` diff --git a/img.png b/img.png new file mode 100644 index 0000000..4f8375a Binary files /dev/null and b/img.png differ `)); // Binary renamed diff = context.tortilla(['dump', 'diff-releases', dumpPath, 'master@0.2.0', 'master@0.3.0']); expect(diff).toEqual(context.trimIndents(` diff --git a/img.png b/re_img.png similarity index 100% rename from img.png rename to re_img.png `)); // Binary removed diff = context.tortilla(['dump', 'diff-releases', dumpPath, 'master@0.3.0', 'master@0.4.0']); expect(diff).toEqual(context.trimIndents(` diff --git a/re_img.png b/re_img.png deleted file mode 100644 index 4f8375a..0000000 Binary files a/re_img.png and /dev/null differ `)); }) }); });
the_stack
import React, { useCallback, useMemo, useRef } from "react"; import { AreaClosed, Bar, Line, LinePath } from "@visx/shape"; import { curveMonotoneX } from "@visx/curve"; import { scaleLinear, scaleTime } from "@visx/scale"; import { AxisBottom, AxisLeft } from "@visx/axis"; import { defaultStyles, TooltipWithBounds, useTooltip } from "@visx/tooltip"; import { GridColumns, GridRows } from "@visx/grid"; import { localPoint } from "@visx/event"; import { LinearGradient } from "@visx/gradient"; import { bisector, extent, max } from "d3-array"; import { timeFormat } from "d3-time-format"; import { NormalizedMetricsData } from "./types"; var globalData: NormalizedMetricsData[]; export const background = "#3b697800"; export const background2 = "#20405100"; export const accentColor = "#949eff"; export const accentColorDark = "#949eff"; // util const formatDate = timeFormat("%H:%M:%S %b %d, '%y"); const hourFormat = timeFormat("%H:%M"); const dayFormat = timeFormat("%b %d"); // map resolutions to formats const formats: { [range: string]: (date: Date) => string } = { "1H": hourFormat, "6H": hourFormat, "1D": hourFormat, "1M": dayFormat, }; // accessors const getDate = (d: NormalizedMetricsData) => new Date(d.date * 1000); const getValue = (d: NormalizedMetricsData) => d?.value && Number(d.value?.toFixed(4)); const bisectDate = bisector<NormalizedMetricsData, Date>( (d) => new Date(d.date * 1000) ).left; export type AreaProps = { data: NormalizedMetricsData[]; dataKey: string; hpaEnabled?: boolean; hpaData?: NormalizedMetricsData[]; resolution: string; width: number; height: number; margin?: { top: number; right: number; bottom: number; left: number }; }; const AreaChart: React.FunctionComponent<AreaProps> = ({ data, dataKey, hpaEnabled = false, hpaData = [], resolution, width, height, margin = { top: 0, right: 0, bottom: 0, left: 0 }, }) => { globalData = data; const { showTooltip, hideTooltip, tooltipData, tooltipTop, tooltipLeft, } = useTooltip<{ data: NormalizedMetricsData; tooltipHpaData: NormalizedMetricsData; }>(); const svgContainer = useRef(); // bounds const innerWidth = width - margin.left - margin.right - 40; const innerHeight = height - margin.top - margin.bottom - 20; const isHpaEnabled = hpaEnabled && !!hpaData.length; // scales const dateScale = useMemo( () => scaleTime({ range: [margin.left, innerWidth + margin.left], domain: extent( [...globalData, ...(isHpaEnabled ? hpaData : [])], getDate ) as [Date, Date], }), [margin.left, width, height, data, hpaData, isHpaEnabled] ); const valueScale = useMemo( () => scaleLinear({ range: [innerHeight + margin.top, margin.top], domain: [ 0, 1.25 * max([...globalData, ...(isHpaEnabled ? hpaData : [])], getValue), ], nice: true, }), [margin.top, width, height, data, hpaData, isHpaEnabled] ); // tooltip handler const handleTooltip = useCallback( ( event: React.TouchEvent<SVGRectElement> | React.MouseEvent<SVGRectElement> ) => { const isHpaEnabled = hpaEnabled && !!hpaData.length; const { x } = localPoint(event) || { x: 0 }; const x0 = dateScale.invert(x); const index = bisectDate(globalData, x0, 1); const d0 = globalData[index - 1]; const d1 = globalData[index]; let d = d0; if (d1 && getDate(d1)) { d = x0.valueOf() - getDate(d0).valueOf() > getDate(d1).valueOf() - x0.valueOf() ? d1 : d0; } const hpaIndex = bisectDate(hpaData, x0, 1); // Get new index without min value to be sure that data exists for HPA const hpaIndex2 = bisectDate(hpaData, x0); if (!isHpaEnabled || hpaIndex !== hpaIndex2) { showTooltip({ tooltipData: { data: d, tooltipHpaData: undefined }, tooltipLeft: x || 0, tooltipTop: valueScale(getValue(d)) || 0, }); return; } const tooltipHpaData0 = hpaData[hpaIndex - 1]; const tooltipHpaData1 = hpaData[hpaIndex]; let tooltipHpaData = tooltipHpaData0; if (tooltipHpaData1 && getDate(tooltipHpaData1)) { tooltipHpaData = x0.valueOf() - getDate(tooltipHpaData0).valueOf() > getDate(tooltipHpaData1).valueOf() - x0.valueOf() ? tooltipHpaData1 : tooltipHpaData0; } const container: SVGSVGElement = svgContainer.current; let point = container.createSVGPoint(); // @ts-ignore point.x = (event as any)?.clientX || 0; // @ts-ignore point.y = (event as any)?.clientY || 0; point = point?.matrixTransform(container.getScreenCTM().inverse()); showTooltip({ tooltipData: { data: d, tooltipHpaData }, tooltipLeft: x || 0, tooltipTop: point.y || 0, }); }, [ showTooltip, valueScale, dateScale, width, height, data, hpaData, svgContainer, hpaEnabled, ] ); if (width == 0 || height == 0 || width < 10) { return null; } const hpaGraphTooltipGlyphPosition = (hpaEnabled && tooltipData?.tooltipHpaData && valueScale(getValue(tooltipData?.tooltipHpaData))) || null; const dataGraphTooltipGlyphPosition = (tooltipData?.data && valueScale(getValue(tooltipData.data))) || 0; return ( <div> <svg width={width} height={height} ref={svgContainer}> <rect x={0} y={0} width={width} height={height} fill="url(#area-background-gradient)" rx={14} /> <LinearGradient id="area-background-gradient" from={background} to={background2} /> <LinearGradient id="area-gradient" from={accentColor} to={accentColor} toOpacity={0} /> <GridRows left={margin.left} scale={valueScale} width={innerWidth} strokeDasharray="1,3" stroke="white" strokeOpacity={0.2} pointerEvents="none" /> <GridColumns top={margin.top} scale={dateScale} height={innerHeight} strokeDasharray="1,3" stroke="white" strokeOpacity={0.2} pointerEvents="none" /> <AreaClosed<NormalizedMetricsData> data={data} x={(d) => dateScale(getDate(d)) ?? 0} y={(d) => valueScale(getValue(d)) ?? 0} height={innerHeight} yScale={valueScale} strokeWidth={1} stroke="url(#area-gradient)" fill="url(#area-gradient)" curve={curveMonotoneX} /> {isHpaEnabled && ( <LinePath<NormalizedMetricsData> stroke="#ffffff" strokeWidth={2} data={hpaData} x={(d) => dateScale(getDate(d)) ?? 0} y={(d) => valueScale(getValue(d)) ?? 0} strokeDasharray="6,4" strokeOpacity={1} pointerEvents="none" /> )} <AxisLeft left={10} scale={valueScale} hideAxisLine={true} hideTicks={true} tickLabelProps={() => ({ fill: "white", fontSize: 11, textAnchor: "start", fillOpacity: 0.4, dy: 0, })} /> <AxisBottom top={height - 20} scale={dateScale} tickFormat={formats[resolution]} hideAxisLine={true} hideTicks={true} tickLabelProps={() => ({ fill: "white", fontSize: 11, textAnchor: "middle", fillOpacity: 0.4, })} /> <Bar x={margin.left} y={margin.top} width={innerWidth} height={innerHeight} fill="transparent" rx={14} onTouchStart={handleTooltip} onTouchMove={handleTooltip} onMouseMove={handleTooltip} onMouseLeave={() => hideTooltip()} /> {tooltipData && ( <g> <Line from={{ x: tooltipLeft, y: margin.top }} to={{ x: tooltipLeft, y: innerHeight + margin.top }} stroke={accentColorDark} strokeWidth={2} pointerEvents="none" strokeDasharray="5,2" /> <circle cx={tooltipLeft} cy={dataGraphTooltipGlyphPosition + 1} r={4} fill="black" fillOpacity={0.1} stroke="black" strokeOpacity={0.1} strokeWidth={2} pointerEvents="none" /> <circle cx={tooltipLeft} cy={dataGraphTooltipGlyphPosition} r={4} fill={accentColorDark} stroke="white" strokeWidth={2} pointerEvents="none" /> {isHpaEnabled && hpaGraphTooltipGlyphPosition !== null && ( <> <circle cx={tooltipLeft} cy={hpaGraphTooltipGlyphPosition + 1} r={4} fill="black" fillOpacity={0.1} stroke="black" strokeOpacity={0.1} strokeWidth={2} pointerEvents="none" /> <circle cx={tooltipLeft} cy={hpaGraphTooltipGlyphPosition} r={4} fill={accentColorDark} stroke="white" strokeWidth={2} pointerEvents="none" /> </> )} </g> )} </svg> {tooltipData && ( <div> <TooltipWithBounds key={Math.random()} top={tooltipTop - 12} left={tooltipLeft + 12} style={{ ...defaultStyles, background: "#26272f", color: "#aaaabb", textAlign: "center", }} > {formatDate(getDate(tooltipData.data))} <div style={{ color: accentColor }}> {dataKey}: {getValue(tooltipData.data)} </div> {isHpaEnabled && hpaGraphTooltipGlyphPosition !== null && ( <div style={{ color: "#FFF" }}> Autoscaling Threshold: {getValue(tooltipData.tooltipHpaData)} </div> )} </TooltipWithBounds> </div> )} </div> ); }; export default AreaChart;
the_stack
import { BadRequestException, Injectable, Logger, NotFoundException, UnprocessableEntityException } from '@nestjs/common'; import { UserPayload } from '../auth/get-user.decorator'; import { CreateReservationDto, CreateReservationProductDto } from './reservation.dto'; import { CreateDocumentDefinition, Model, Types } from 'mongoose'; import { Reservation } from './reservation.schema'; import { InjectModel } from '@nestjs/mongoose'; import { UsersService } from '../users/users.service'; import { Product } from '../products/product.schema'; import { Ticket } from '../seats/ticket.schema'; import { checkCompletedLogin, checkStaffPermission, getSkipLimit } from '../common/utils'; import { Seat } from '../seats/seat.schema'; import { Stripe } from 'stripe'; import { AppGateway } from '../socket/app.gateway'; import { PromotionsService } from '../promotions/promotions.service'; import { Promotion } from '../promotions/promotion.schema'; import { User } from '../users/user.schema'; import { NotificationsService } from '../notifications/notifications.service'; import { MailerService } from '@nestjs-modules/mailer'; import { ShowTime } from '../show-times/show-time.schema'; import { Movie } from '../movies/movie.schema'; import { generateQRCode } from '../common/qrcode'; import { PaginationDto } from '../common/pagination.dto'; export type CreatedReservation = Omit<Reservation, 'show_time'> & { show_time: Omit<ShowTime, 'movie'> & { movie: Movie } }; @Injectable() export class ReservationsService { private readonly logger = new Logger('ReservationsService'); constructor( @InjectModel(Reservation.name) private readonly reservationModel: Model<Reservation>, @InjectModel(Product.name) private readonly productModel: Model<Product>, @InjectModel(Ticket.name) private readonly ticketModel: Model<Ticket>, @InjectModel(ShowTime.name) private readonly showTimeModel: Model<ShowTime>, private readonly usersService: UsersService, private readonly appGateway: AppGateway, private readonly promotionsService: PromotionsService, private readonly notificationsService: NotificationsService, private readonly mailerService: MailerService, ) {} async createReservation( userPayload: UserPayload, dto: CreateReservationDto, ): Promise<Reservation> { this.logger.debug(`createReservation: ${JSON.stringify(dto)}`); const user = checkCompletedLogin(userPayload); this.logger.debug(`[1] completed login`); const products = await this.checkProduct(dto.products); this.logger.debug(`[2] check product`); const card = await this.usersService.getCardById(userPayload, dto.pay_card_id); this.logger.debug(`[3] check card`); const ticketIds = dto.ticket_ids.map(id => new Types.ObjectId(id)); const tickets = await this.checkSeats(ticketIds); this.logger.debug(`[4] check tickets`); const original_price = ReservationsService.calculateOriginalPrice(products, tickets); const { total_price, promotion } = await this.applyPromotionIfNeeded(original_price, dto.promotion_id, user); this.logger.debug(`[5] ${dto.promotion_id} ${original_price} -> ${total_price}`); const paymentIntent = await this.usersService.charge( card, total_price, 'vnd', ); this.logger.debug(`[6] charged`); const reservation = await this.saveAndUpdate({ dto, total_price, user, paymentIntent, ticketIds, promotion, original_price, }); const data: Record<string, Reservation> = ticketIds.reduce( (acc, e) => ({ ...acc, [e.toHexString()]: reservation, }), {}, ); this.appGateway.server .to(`reservation:${dto.show_time_id}`) .emit('reserved', data); this.sendMailAndPushNotification({ user, reservation, dto, tickets }); this.logger.debug(`[8] returns...`); return reservation; } private sendMailAndPushNotification( info: { user: User, reservation: CreatedReservation, dto: CreateReservationDto, tickets: Ticket[], } ) { const { user, reservation, dto, tickets } = info; this.logger.debug(`>>>>>>>>>>>>>> ${JSON.stringify(reservation)}`); this.notificationsService .pushNotification(user, reservation) .catch((e) => this.logger.debug(`Push notification error: ${e}`)); generateQRCode( { reservation_id: reservation._id.toHexString(), show_time_id: reservation.show_time._id.toHexString(), ticket_ids: tickets.map(t => t._id.toHexString()), user_id: reservation.user._id.toHexString(), } ).then(qrcode => this.mailerService.sendMail( { to: dto.email, subject: `Tickets for movie: ${reservation.show_time.movie.title}`, template: 'mail', context: { reservation: reservation.toJSON(), tickets: tickets.map(t => t.toJSON()) }, attachments: [ { filename: 'qrcode.png', content: qrcode.split('base64,')[1], encoding: 'base64' } as any, ] } ) ).then(() => this.logger.debug(`Send mail success`)) .catch((e) => this.logger.debug(`Send mail failed: ${e}`)); } private static calculateOriginalPrice(products: { product: Product; quantity: number }[], tickets: Ticket[]) { const price = tickets.reduce((acc, e) => acc + e.price, 0) + products.reduce((acc, e) => acc + e.product.price * e.quantity, 0); return Math.ceil(price); } private async saveAndUpdate( info: { dto: CreateReservationDto, total_price: number, user: User, paymentIntent: Stripe.PaymentIntent, ticketIds: any[], promotion: Promotion | null, original_price: number, } ): Promise<CreatedReservation> { const { dto, original_price, paymentIntent, user, total_price, ticketIds, promotion } = info; const session = await this.ticketModel.db.startSession(); try { session.startTransaction(); const doc: Omit<CreateDocumentDefinition<Reservation>, '_id'> = { email: dto.email, is_active: true, original_price, phone_number: dto.phone_number, products: dto.products.map(p => ({ id: new Types.ObjectId(p.product_id), quantity: p.quantity, })), total_price, show_time: new Types.ObjectId(dto.show_time_id), user: user._id, payment_intent_id: paymentIntent.id, }; if (promotion) { doc.promotion_id = promotion._id; } // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore let reservation = await this.reservationModel.create( // eslint-disable-next-line @typescript-eslint/ban-ts-ignore [doc], // @ts-ignore { session }, ).then(v => v[0]); for (const id of ticketIds) { const updated = await this.ticketModel.findOneAndUpdate( { _id: id, reservation: null }, { reservation: reservation._id }, { session }, ); if (!updated) { throw new Error(`Ticket already reserved`); } } if (promotion) { await this.promotionsService.markUsed(promotion, user); } reservation = await reservation .populate('user') .populate({ path: 'show_time', populate: [ { path: 'movie' }, { path: 'theatre' }, ], }) .execPopulate(); await session.commitTransaction(); session.endSession(); this.logger.debug(`[7] done ${JSON.stringify(reservation)}`); return reservation; } catch (e) { await session.abortTransaction(); session.endSession(); this.logger.debug(`[7] error ${e}`); throw new UnprocessableEntityException(e.message ?? `Cannot create reservation`); } } private async checkProduct(products: CreateReservationProductDto[]): Promise<{ product: Product; quantity: number }[]> { const productWithQuantity: { product: Product, quantity: number }[] = []; for (const p of products) { const product = await this.productModel.findById(p.product_id); if (!product) { throw new NotFoundException(`Not found product with id: ${p.product_id}`); } productWithQuantity.push({ product, quantity: p.quantity }); } return productWithQuantity; } private async checkSeats(ticketIds: any[]): Promise<Ticket[]> { // const invalidTickets = await this.ticketModel.find({ // $and: [ // { _id: { $in: ticketIds } }, // { reservation: { $ne: null } }, // ] // }).populate('seat'); const tickets = await this.ticketModel.find({ _id: { $in: ticketIds } }).populate('seat'); const invalidTickets = tickets.filter(t => !!t.reservation); if (invalidTickets.length > 0) { const seats = invalidTickets.map(t => { const seat = (t.seat as Seat); return `${seat.row}${seat.column}`; }).join(', '); throw new UnprocessableEntityException(`Tickets already reserved: ${seats}`); } return tickets; } private async applyPromotionIfNeeded( original_price: number, promotion_id: string | null | undefined, user: User ): Promise<{ total_price: number; promotion: Promotion | null }> { let total_price = original_price; let promotion: Promotion | null = null; if (promotion_id) { promotion = await this.promotionsService.checkValid(promotion_id, user); if (promotion) { total_price = total_price * (1 - promotion.discount); } else { throw new BadRequestException('Invalid promotion'); } } return { total_price: Math.ceil(total_price), promotion }; } async getReservations(userPayload: UserPayload, dto: PaginationDto) { const { _id } = checkCompletedLogin(userPayload); const { skip, limit } = getSkipLimit(dto); const results = await this.reservationModel.aggregate([ { $match: { user: new Types.ObjectId(_id) } }, { $sort: { createdAt: -1 } }, { $skip: skip }, { $limit: limit }, { $lookup: { from: 'show_times', localField: 'show_time', foreignField: '_id', as: 'show_time', } }, { $unwind: '$show_time' }, { $lookup: { from: 'movies', localField: 'show_time.movie', foreignField: '_id', as: 'show_time.movie', } }, { $unwind: '$show_time.movie' }, { $lookup: { from: 'theatres', localField: 'show_time.theatre', foreignField: '_id', as: 'show_time.theatre', } }, { $unwind: '$show_time.theatre' }, { $lookup: { from: 'promotions', localField: 'promotion_id', foreignField: '_id', as: 'promotion_id', } }, { $unwind: { path: '$promotion_id', preserveNullAndEmptyArrays: true, } }, { $lookup: { from: 'products', localField: 'products.id', foreignField: '_id', as: 'product_objects', } }, { $lookup: { from: 'tickets', localField: '_id', foreignField: 'reservation', as: 'tickets', } }, { $lookup: { from: 'seats', localField: 'tickets.seat', foreignField: '_id', as: 'seats', }, }, ]).exec(); return results.map(item => { item.products = item.product_objects?.map(prodObj => { return { product_id: prodObj, quantity: item.products.find(p => p.id.toHexString() === prodObj._id.toHexString()).quantity, }; }) ?? []; delete item.product_objects; item.tickets = item.tickets?.map(ticket => { ticket.seat = item.seats.find(s => s._id.toHexString() === ticket.seat.toHexString()); return ticket; }) ?? []; delete item.seats; return item; }); // return await this.reservationModel // .find({ user: _id }) // .sort({ createdAt: -1 }) // .skip(skip) // .limit(limit) // .populate({ // path: 'show_time', // populate: [ // { path: 'movie' }, // { path: 'theatre' }, // ], // }) // .populate({ // path: 'products', // populate: 'id' // }) // .populate('promotion_id') // .exec(); } async getQrCode(id: string, userPayload: UserPayload): Promise<string> { const reservation = await this.reservationModel.findById(id).populate('show_time'); const tickets = await this.ticketModel.find({ reservation: reservation._id }); return generateQRCode( { reservation_id: reservation._id.toHexString(), show_time_id: reservation.show_time._id.toHexString(), ticket_ids: tickets.map(t => t._id.toHexString()), user_id: checkCompletedLogin(userPayload)._id.toHexString(), } ) } async seed() { const rs: Reservation[] = await this.reservationModel .find({}, { original_price: 1, total_price: 1 }) .exec(); return rs; // for (const r of rs) { // if (Number.isSafeInteger(r.original_price) && Number.isSafeInteger(r.total_price)) { // continue; // } // // this.logger.debug(r); // await this.reservationModel.updateOne({_id: r._id}, { // original_price: Math.ceil(r.original_price), // total_price: Math.ceil(r.total_price), // }); // } // // return 'DONE'; } async getReservationsByShowTimeId(show_time_id: string, userPayload: UserPayload) { const showTime = await this.showTimeModel.findById(show_time_id); if (!showTime) { throw new NotFoundException(); } checkStaffPermission(userPayload, showTime.theatre._id.toString()); const results = await this.reservationModel.aggregate([ { $match: { show_time: showTime._id } }, { $sort: { createdAt: -1 } }, { $lookup: { from: 'show_times', localField: 'show_time', foreignField: '_id', as: 'show_time', } }, { $unwind: '$show_time' }, { $lookup: { from: 'movies', localField: 'show_time.movie', foreignField: '_id', as: 'show_time.movie', } }, { $unwind: '$show_time.movie' }, { $lookup: { from: 'theatres', localField: 'show_time.theatre', foreignField: '_id', as: 'show_time.theatre', } }, { $unwind: '$show_time.theatre' }, { $lookup: { from: 'promotions', localField: 'promotion_id', foreignField: '_id', as: 'promotion_id', } }, { $unwind: { path: '$promotion_id', preserveNullAndEmptyArrays: true, } }, { $lookup: { from: 'products', localField: 'products.id', foreignField: '_id', as: 'product_objects', } }, { $lookup: { from: 'tickets', localField: '_id', foreignField: 'reservation', as: 'tickets', } }, { $lookup: { from: 'seats', localField: 'tickets.seat', foreignField: '_id', as: 'seats', }, }, { $lookup: { from: 'users', localField: 'user', foreignField: '_id', as: 'user', }, }, { $unwind: '$user' }, ]).exec(); return results.map(item => { item.products = item.product_objects?.map(prodObj => { return { product_id: prodObj, quantity: item.products.find(p => p.id.toHexString() === prodObj._id.toHexString()).quantity, }; }) ?? []; delete item.product_objects; item.tickets = item.tickets?.map(ticket => { ticket.seat = item.seats.find(s => s._id.toHexString() === ticket.seat.toHexString()); return ticket; }) ?? []; delete item.seats; return item; }); } async getReservationById(userPayload: UserPayload, id: string) { const user = checkCompletedLogin(userPayload); const match = user.role === 'USER' ? { $and: [ { _id: new Types.ObjectId(id) }, { user: new Types.ObjectId(user.id) }, ], } : { _id: new Types.ObjectId(id) }; const results = await this.reservationModel.aggregate([ { $match: match, }, { $limit: 1 }, { $lookup: { from: 'show_times', localField: 'show_time', foreignField: '_id', as: 'show_time', } }, { $unwind: '$show_time' }, { $lookup: { from: 'movies', localField: 'show_time.movie', foreignField: '_id', as: 'show_time.movie', } }, { $unwind: '$show_time.movie' }, { $lookup: { from: 'theatres', localField: 'show_time.theatre', foreignField: '_id', as: 'show_time.theatre', } }, { $unwind: '$show_time.theatre' }, { $lookup: { from: 'promotions', localField: 'promotion_id', foreignField: '_id', as: 'promotion_id', } }, { $unwind: { path: '$promotion_id', preserveNullAndEmptyArrays: true, } }, { $lookup: { from: 'products', localField: 'products.id', foreignField: '_id', as: 'product_objects', } }, { $lookup: { from: 'tickets', localField: '_id', foreignField: 'reservation', as: 'tickets', } }, { $lookup: { from: 'seats', localField: 'tickets.seat', foreignField: '_id', as: 'seats', }, }, ]).exec(); const item = results?.[0]; if (!item) { throw new NotFoundException(`Reservation with id ${id} not found`); } try { checkStaffPermission(userPayload, item.show_time.theatre._id.toString()); } catch (e) { throw new BadRequestException(e.message); } item.products = item.product_objects?.map(prodObj => { return { product_id: prodObj, quantity: item.products.find(p => p.id.toHexString() === prodObj._id.toHexString()).quantity, }; }) ?? []; delete item.product_objects; item.tickets = item.tickets?.map(ticket => { ticket.seat = item.seats.find(s => s._id.toHexString() === ticket.seat.toHexString()); return ticket; }) ?? []; delete item.seats; return item; } }
the_stack
import { expect } from 'chai'; import { GitProcess, IGitExecutionOptions, IGitResult } from 'dugite'; import { nextVersion, shouldUpdateSupported, updateSupported } from '../script/release/version-bumper'; import * as utils from '../script/release/version-utils'; import * as sinon from 'sinon'; import { ifdescribe } from './spec-helpers'; const { promises: fs } = require('fs'); const path = require('path'); const fixtureDir = path.resolve(__dirname, 'fixtures', 'version-bumper', 'fixture_support.md'); const readFile = fs.readFile; const writeFile = fs.writeFile; class GitFake { branches: { [key: string]: string[], }; constructor () { this.branches = {}; } setBranch (channel: string): void { this.branches[channel] = []; } setVersion (channel: string, latestTag: string): void { const tags = [latestTag]; if (channel === 'alpha') { const versionStrs = latestTag.split(`${channel}.`); const latest = parseInt(versionStrs[1]); for (let i = latest; i >= 1; i--) { tags.push(`${versionStrs[0]}${channel}.${latest - i}`); } } this.branches[channel] = tags; } // eslint-disable-next-line @typescript-eslint/no-unused-vars exec (args: string[], path: string, options?: IGitExecutionOptions | undefined): Promise<IGitResult> { let stdout = ''; const stderr = ''; const exitCode = 0; // handle for promoting from current master HEAD let branch = 'stable'; const v = (args[2] === 'HEAD') ? 'stable' : args[3]; if (v.includes('nightly')) branch = 'nightly'; if (v.includes('alpha')) branch = 'alpha'; if (v.includes('beta')) branch = 'beta'; if (!this.branches[branch]) this.setBranch(branch); stdout = this.branches[branch].join('\n'); return Promise.resolve({ exitCode, stdout, stderr }); } } describe('version-bumper', () => { describe('makeVersion', () => { it('makes a version with a period delimeter', () => { const components = { major: 2, minor: 0, patch: 0 }; const version = utils.makeVersion(components, '.'); expect(version).to.equal('2.0.0'); }); it('makes a version with a period delimeter and a partial pre', () => { const components = { major: 2, minor: 0, patch: 0, pre: ['nightly', 12345678] }; const version = utils.makeVersion(components, '.', utils.preType.PARTIAL); expect(version).to.equal('2.0.0.12345678'); }); it('makes a version with a period delimeter and a full pre', () => { const components = { major: 2, minor: 0, patch: 0, pre: ['nightly', 12345678] }; const version = utils.makeVersion(components, '.', utils.preType.FULL); expect(version).to.equal('2.0.0-nightly.12345678'); }); }); describe('updateSupported', () => { let restore: any; before(async () => { restore = await readFile(fixtureDir, 'utf8'); }); afterEach(async () => { await writeFile(fixtureDir, restore, 'utf8'); }); it('updates correctly when a new stable version is promoted from beta', async () => { const version = '4.0.0'; const currentVersion = '4.0.0-beta.29'; if (shouldUpdateSupported('stable', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('4.x.y\n* 3.x.y\n* 2.x.y'); }); it('should not update when a new stable patch version is promoted', async () => { const version = '3.0.1'; const currentVersion = '3.0.0'; if (shouldUpdateSupported('stable', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('3.x.y\n* 2.x.y\n* 1.x.y'); }); it('should not update when a new stable minor version is promoted', async () => { const version = '3.1.0'; const currentVersion = '3.0.0'; if (shouldUpdateSupported('minor', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('3.x.y\n* 2.x.y\n* 1.x.y'); }); it('should not update when a new beta.1 version is promoted', async () => { const version = '5.0.0-beta.1'; const currentVersion = '4.0.0-beta.29'; if (shouldUpdateSupported('beta', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('3.x.y\n* 2.x.y\n* 1.x.y'); }); it('should not update when a new beta.12 version is promoted', async () => { const version = '4.0.0-beta.12'; const currentVersion = '4.0.0-beta.11'; if (shouldUpdateSupported('beta', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('3.x.y\n* 2.x.y\n* 1.x.y'); }); it('should update when a new major nightly version is promoted', async () => { const version = '4.0.0-nightly.19950901'; const currentVersion = '3.0.0-nightly.19950828'; if (shouldUpdateSupported('nightly', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('4.x.y\n* 3.x.y\n* 2.x.y'); }); it('should not update when a new nightly version is promoted', async () => { const version = '3.0.0-nightly.19950901'; const currentVersion = '3.0.0-nightly.19950828'; if (shouldUpdateSupported('nightly', currentVersion, version)) { await updateSupported(version, fixtureDir); } const contents = await readFile(fixtureDir, 'utf8'); expect(contents).to.contain('3.x.y\n* 2.x.y\n* 1.x.y'); }); }); // On macOS Circle CI we don't have a real git environment due to running // gclient sync on a linux machine. These tests therefore don't run as expected. ifdescribe(!(process.platform === 'linux' && process.arch.indexOf('arm') === 0) && process.platform !== 'darwin')('nextVersion', () => { describe('bump versions', () => { const nightlyPattern = /[0-9.]*(-nightly.(\d{4})(\d{2})(\d{2}))$/g; const betaPattern = /[0-9.]*(-beta[0-9.]*)/g; it('bumps to nightly from stable', async () => { const version = 'v2.0.0'; const next = await nextVersion('nightly', version); const matches = next.match(nightlyPattern); expect(matches).to.have.lengthOf(1); }); it('bumps to nightly from beta', async () => { const version = 'v2.0.0-beta.1'; const next = await nextVersion('nightly', version); const matches = next.match(nightlyPattern); expect(matches).to.have.lengthOf(1); }); it('bumps to nightly from nightly', async () => { const version = 'v2.0.0-nightly.19950901'; const next = await nextVersion('nightly', version); const matches = next.match(nightlyPattern); expect(matches).to.have.lengthOf(1); }); it('bumps to a nightly version above our switch from N-0-x to N-x-y branch names', async () => { const version = 'v2.0.0-nightly.19950901'; const next = await nextVersion('nightly', version); // If it starts with v8 then we didn't bump above the 8-x-y branch expect(next.startsWith('v8')).to.equal(false); }); it('throws error when bumping to beta from stable', () => { const version = 'v2.0.0'; return expect( nextVersion('beta', version) ).to.be.rejectedWith('Cannot bump to beta from stable.'); }); // TODO ELECTRON 15: Re-enable after Electron 15 alpha has released it.skip('bumps to beta from nightly', async () => { const version = 'v2.0.0-nightly.19950901'; const next = await nextVersion('beta', version); const matches = next.match(betaPattern); expect(matches).to.have.lengthOf(1); }); it('bumps to beta from beta', async () => { const version = 'v2.0.0-beta.8'; const next = await nextVersion('beta', version); expect(next).to.equal('2.0.0-beta.9'); }); it('bumps to beta from beta if the previous beta is at least beta.10', async () => { const version = 'v6.0.0-beta.15'; const next = await nextVersion('beta', version); expect(next).to.equal('6.0.0-beta.16'); }); it('bumps to stable from beta', async () => { const version = 'v2.0.0-beta.1'; const next = await nextVersion('stable', version); expect(next).to.equal('2.0.0'); }); it('bumps to stable from stable', async () => { const version = 'v2.0.0'; const next = await nextVersion('stable', version); expect(next).to.equal('2.0.1'); }); it('bumps to minor from stable', async () => { const version = 'v2.0.0'; const next = await nextVersion('minor', version); expect(next).to.equal('2.1.0'); }); it('bumps to stable from nightly', async () => { const version = 'v2.0.0-nightly.19950901'; const next = await nextVersion('stable', version); expect(next).to.equal('2.0.0'); }); it('throws on an invalid version', () => { const version = 'vI.AM.INVALID'; return expect( nextVersion('beta', version) ).to.be.rejectedWith(`Invalid current version: ${version}`); }); it('throws on an invalid bump type', () => { const version = 'v2.0.0'; return expect( nextVersion('WRONG', version) ).to.be.rejectedWith('Invalid bump type.'); }); }); }); // If we don't plan on continuing to support an alpha channel past Electron 15, // these tests will be removed. Otherwise, integrate into the bump versions tests describe('bump versions - alpha channel', () => { const alphaPattern = /[0-9.]*(-alpha[0-9.]*)/g; const betaPattern = /[0-9.]*(-beta[0-9.]*)/g; const sandbox = sinon.createSandbox(); const gitFake = new GitFake(); beforeEach(() => { const wrapper = (args: string[], path: string, options?: IGitExecutionOptions | undefined) => gitFake.exec(args, path, options); sandbox.replace(GitProcess, 'exec', wrapper); }); afterEach(() => { gitFake.branches = {}; sandbox.restore(); }); it('bumps to alpha from nightly', async () => { const version = 'v2.0.0-nightly.19950901'; gitFake.setVersion('nightly', version); const next = await nextVersion('alpha', version); const matches = next.match(alphaPattern); expect(matches).to.have.lengthOf(1); }); it('throws error when bumping to alpha from stable', () => { const version = 'v2.0.0'; return expect( nextVersion('alpha', version) ).to.be.rejectedWith('Cannot bump to alpha from stable.'); }); it('bumps to alpha from alpha', async () => { const version = 'v2.0.0-alpha.8'; gitFake.setVersion('alpha', version); const next = await nextVersion('alpha', version); expect(next).to.equal('2.0.0-alpha.9'); }); it('bumps to alpha from alpha if the previous alpha is at least alpha.10', async () => { const version = 'v6.0.0-alpha.15'; gitFake.setVersion('alpha', version); const next = await nextVersion('alpha', version); expect(next).to.equal('6.0.0-alpha.16'); }); it('bumps to beta from alpha', async () => { const version = 'v2.0.0-alpha.8'; gitFake.setVersion('alpha', version); const next = await nextVersion('beta', version); const matches = next.match(betaPattern); expect(matches).to.have.lengthOf(1); expect(next).to.equal('2.0.0-beta.1'); }); }); });
the_stack
import {HeapSnapshotContents} from '../common/interfaces'; const enum ParserState { // The parser has encountered an error and can no longer proceed. ERROR = 0, // Special mode for the snapshot line. SNAPSHOT_LINE, // Waiting for the beginning of an array property, e.g. "field":[ ARRAY_PROPERTY_BEGIN, // Waiting for more numbers in an array property, or the end of the array property. NUMBER_ARRAY, // Waiting for more strings in an array property. STRING_ARRAY, // Waiting for end of snapshot. END } export const enum DataTypes { SNAPSHOT = 1, NODES = 2, EDGES = 3, STRINGS = 4 } type ParserEvent = SnapshotEvent | NumbersEvent | StringsEvent; interface SnapshotEvent { type: DataTypes.SNAPSHOT; data: HeapSnapshotContents; } interface NumbersEvent { type: DataTypes.NODES | DataTypes.EDGES; data: number[]; } interface StringsEvent { type: DataTypes.STRINGS; data: string[]; } const SNAPSHOT_PROP_NAME = `{"snapshot":`; function onSnapshotChunk() { } /** * Streaming parser for heap snapshots. * * Here's how the snapshot is streamed from Chrome (newlines included!): * * {"snapshot":{"meta":{"node_fields":["type","name","id","self_size","edge_count","trace_node_id"],"node_types":[["hidden","array","string","object","code","closure","regexp","number","native","synthetic","concatenated string","sliced string"],"string","number","number","number","number","number"],"edge_fields":["type","name_or_index","to_node"],"edge_types":[["context","element","property","internal","hidden","shortcut","weak"],"string_or_number","node"],"trace_function_info_fields":["function_id","name","script_name","script_id","line","column"],"trace_node_fields":["id","function_info_index","count","size","children"],"sample_fields":["timestamp_us","last_assigned_id"]},"node_count":931835,"edge_count":4713209,"trace_function_count":0}, * "nodes":[9,1,1,0,6,0 * ,9,2,3,0,17,0 * [etc] * ], * "edges":[1,1,6 * ,1,1,22824 * [etc] * ], * "trace_function_infos":[], * "trace_tree":[], * "samples":[], * "strings":["<dummy>", * "[string value, which may have newlines! \ is escape character]", * "98272"]} * * The parser assumes the snapshot is in this format, and that the first chunk contains the entire "snapshot" property. */ export default class HeapSnapshotParser { public static FromString(data: string): HeapSnapshotParser { const rv = new HeapSnapshotParser(); rv.addSnapshotChunk(data); return rv; } private _state: ParserState = ParserState.SNAPSHOT_LINE; private _error: Error = null; private _activeProperty: string = null; private _pendingEvents: ParserEvent[] = []; private _pendingReads: { resolve: (e: ParserEvent) => void, reject: (e: Error) => void }[] = []; private _buffer: string = ""; private _onSnapshotChunk: (chunk: string, end: boolean) => void = onSnapshotChunk; public set onSnapshotChunk(v: (chunk: string, end: boolean) => void) { this._onSnapshotChunk = v; } /** * Adds another snapshot chunk to parse. * @param chunk */ public addSnapshotChunk(chunk: string): void { this._buffer += chunk; this._parse(); this._onSnapshotChunk(chunk, this._state === ParserState.END); } private _parse(): void { const chunk = this._buffer; const chunkLen = chunk.length; let chunkPosition = 0; outerLoop: while (!this.hasErrored() && chunkPosition < chunkLen) { switch (this._state) { case ParserState.SNAPSHOT_LINE: { // Expecting: {"snapshot":{[object here]},\n const beginString = chunk.slice(chunkPosition, chunkPosition + SNAPSHOT_PROP_NAME.length); if (beginString !== SNAPSHOT_PROP_NAME) { this._raiseError(new Error(`Unable to find "snapshot" property in first chunk.`)); break outerLoop; } chunkPosition += SNAPSHOT_PROP_NAME.length; let startIndex = chunkPosition; let endingIndex = -1; for (; chunkPosition < chunkLen; chunkPosition++) { if (chunk[chunkPosition] === "\n") { // - 1 to cut off the comma endingIndex = chunkPosition - 1; chunkPosition++; break; } } if (endingIndex === -1) { this._raiseError(new Error(`Unable to find whole "snapshot" object in first snapshot chunk.`)); break outerLoop; } try { const snapshot: HeapSnapshotContents = JSON.parse(chunk.slice(startIndex, endingIndex)); this._pendingEvents.push({ type: DataTypes.SNAPSHOT, data: snapshot }); this._state = ParserState.ARRAY_PROPERTY_BEGIN; } catch (e) { this._raiseError(e); break outerLoop; } break; } case ParserState.ARRAY_PROPERTY_BEGIN: { const start = chunkPosition; for (; chunkPosition < chunk.length && chunk[chunkPosition] !== "["; chunkPosition++) { // Wait. } if (chunkPosition >= chunk.length) { this._raiseError(new Error(`Unable to locate the beginning of a property.`)); break outerLoop; } // Skip over "[". chunkPosition++; // [start, chunkPosition) should be string `"propname":[` this._activeProperty = chunk.slice(start + 1, chunkPosition - 3); if (this._activeProperty === "strings") { this._state = ParserState.STRING_ARRAY; } else { this._state = ParserState.NUMBER_ARRAY; } break; } case ParserState.NUMBER_ARRAY: { const start = chunkPosition; let lastNewline = start; numberForLoop: for (; chunkPosition < chunkLen; chunkPosition++) { switch (chunk[chunkPosition]) { case "]": // End of array. break numberForLoop; case "\n": lastNewline = chunkPosition; break; } } const arrayEnded = chunkPosition !== chunkLen; // [start, end) is either: // - "" if the array is zero-length, // - "9,3,4,5\n,1,2,3[etc]" if this is the start of the array, // - ",1,2,3,4" if this is the middle of the array // It does not contain the "]" character. const end = arrayEnded ? chunkPosition : lastNewline; if (start !== end) { const beginningComma = chunk[start] === ","; const numberChunk = chunk.slice(beginningComma ? start + 1 : start, end); const numbers: number[] = JSON.parse(`[${numberChunk}]`); switch (this._activeProperty) { case "nodes": this._pendingEvents.push({ type: DataTypes.NODES, data: numbers }); break; case "edges": this._pendingEvents.push({ type: DataTypes.EDGES, data: numbers }); break; } } if (arrayEnded) { // Skip "]". chunkPosition++; switch (chunk[chunkPosition]) { case ",": this._state = ParserState.ARRAY_PROPERTY_BEGIN; // Skip , and \n chunkPosition += 2; break; case "}": this._state = ParserState.END; break; default: this._raiseError(new Error(`Unrecognized end-of-array character: ${chunk[chunkPosition]}`)); break; } break; } else { // Skip \n chunkPosition = lastNewline + 1; break outerLoop; } } case ParserState.STRING_ARRAY: { const start = chunkPosition; let escaped = false; let lastStringEnding = start; let isInString = false; // Look for unescaped "]", which ends the array. stringWhile: while (chunkPosition < chunkLen) { switch (chunk[chunkPosition]) { case '"': if (!escaped) { isInString = !isInString; if (!isInString) { lastStringEnding = chunkPosition; } } escaped = false; break; case ']': if (!isInString) { break stringWhile; } escaped = false; break; case '\\': // Flip, for sequences of "\" (e.g. an actual \ character) escaped = !escaped; break; default: escaped = false; break; } chunkPosition++; } const arrayEnded = chunkPosition !== chunkLen; // [start, end) is either: // - "" if the array is zero-length, // - "9,3,4,5\n,1,2,3[etc]" if this is the start of the array, // - ",1,2,3,4" if this is the middle of the array // It does not contain the "]" character. const end = arrayEnded ? chunkPosition : lastStringEnding + 1; if (start !== end) { const beginningComma = chunk[start] === ","; const stringChunk = chunk.slice(beginningComma ? start + 1 : start, end); const strings: string[] = JSON.parse(`[${stringChunk}]`); this._pendingEvents.push({ type: DataTypes.STRINGS, data: strings }); } if (arrayEnded) { // Skip "]". chunkPosition++; switch (chunk[chunkPosition]) { case ",": this._state = ParserState.ARRAY_PROPERTY_BEGIN; break; case "}": this._state = ParserState.END; break; default: this._raiseError(new Error(`Unrecognized end-of-array character: ${chunk[chunkPosition]}`)); break; } } else { chunkPosition = lastStringEnding + 1; break outerLoop; } break; } case ParserState.END: if (chunk[chunkPosition] !== '}') { this._raiseError(new Error(`Unexpected end of snapshot: ${chunk[chunkPosition]}`)); break outerLoop; } chunkPosition++; this._pendingEvents.push(null); break outerLoop; case ParserState.ERROR: break outerLoop; default: this._raiseError(new Error(`Invalid state: ${this._state}`)); break outerLoop; } } if (chunkPosition < chunkLen && this._state !== ParserState.STRING_ARRAY && this._state !== ParserState.NUMBER_ARRAY && !this.hasErrored()) { this._raiseError(new Error(`Parsing error: Did not consume whole chunk!`)); } if (chunkPosition < chunkLen) { this._buffer = chunk.slice(chunkPosition); } else { this._buffer = ""; } this._processPendingPromises(); } private _processPendingPromises(): void { const hasErrored = this.hasErrored(); while (!hasErrored && this._pendingReads.length > 0 && this._pendingEvents.length > 0) { this._pendingReads.shift().resolve(this._pendingEvents.shift()); } if (hasErrored) { for (const promise of this._pendingReads) { promise.reject(this._error); } this._pendingReads = []; } else if (this._pendingEvents.length === 0 && this._state === ParserState.END) { for (const promise of this._pendingReads) { promise.resolve(null); } this._pendingReads = []; } } private _raiseError(e: Error): void { this._error = e; this._state = ParserState.ERROR; this._processPendingPromises(); } public hasErrored(): boolean { return this._state === ParserState.ERROR; } public read(): Promise<ParserEvent> { if (this._pendingEvents.length > 0) { return Promise.resolve(this._pendingEvents.shift()); } else { return new Promise<ParserEvent>((resolve, reject) => { this._pendingReads.push({resolve, reject}); }); } } }
the_stack
var Enumerable: any = require('linq'); import Mongoose = require("mongoose"); import {ClassType} from './classtype'; import {IEntityService} from '../interfaces/entity-service'; import {MetaData} from '../metadata/metadata'; import {MetaUtils} from '../metadata/utils'; import {Decorators, RelationDecorators} from '../constants'; import {DecoratorType} from '../enums/decorator-type'; import {IAssociationParams} from '../decorators/interfaces/association-params'; import {IDecoratorParams} from '../decorators/interfaces/decorator-params'; import {pathRepoMap} from '../dynamic/model-entity'; let _config: any = {}; let _securityConfig: any = {}; let _entityService: Map<String, IEntityService> = new Map<String, IEntityService>(); let _relationsCache: any = {}; export var workerResponse = '__worker'; export class ProcessStatus { static success: string = "SUCCESS"; static failure: string = "FAILURE"; } export class resources { static userDatabase: string = '_database'; } export function config(config?: any) { if (!(config === undefined)) { _config = config; } return _config; } export function securityConfig(securityConf?: any) { if (!(securityConf === undefined)) { _securityConfig = securityConf; } return _securityConfig; } export function entityService(entityType:string, entityService?: IEntityService): IEntityService { if (!_entityService[entityType] && entityService) { _entityService[entityType] = entityService; } return _entityService[entityType]; } //export function sqlEntityService(sqlEntityService?: IEntityService): IEntityService { // if (!(sqlEntityService === undefined)) { // _sqlEntityService = sqlEntityService; // } // return _sqlEntityService; //} export function getDesignType(target: Object|Function, prop: string) { return (<any>Reflect).getMetadata("design:type", target, prop); } export function getDesignParamType(target: Object | Function, prop: string, parameterIndex: number) { return (<any>Reflect).getMetadata("design:paramtypes", target, prop); } export function activator<T>(cls: ClassType<T>, args?: Array<any>): T { return new (Function.prototype.bind.apply(cls, [null].concat(args))); //function F(): void { // return <any>cls.constructor.apply(this, args); //} //F.prototype = <any>cls.constructor.prototype; //return new F(); } export function isRelationDecorator(decorator: string) { return decorator === Decorators.ONETOMANY || decorator === Decorators.MANYTOONE || decorator === Decorators.MANYTOMANY || decorator === Decorators.ONETOONE; } /** * Get all the metadata of all the decorators of all the models referencing current target, i.e. (rel = target relation name) * @param target like UserModel (function of prototype) * */ export function getAllRelationsForTarget(target: Object): Array<MetaData> { if (!target) { throw TypeError; } //global.models.CourseModel.decorator.manytomany.students var name = getResourceNameFromModel(target); if (!name) { return null; } var metaForRelations = MetaUtils.getMetaDataForDecorators(RelationDecorators); return Enumerable.from(metaForRelations) .selectMany(keyVal => keyVal.metadata) .where(x => (<IAssociationParams>(<MetaData>x).params).rel === name) .toArray(); } /** * Get all the metadata of all the decorators of all the models referencing current target, i.e. (rel = target relation name) * @param target like UserModel (function of prototype) * */ export function getAllRelationsForTargetInternal(target: Object): Array<MetaData> { if (!target) { throw TypeError; } let targerKey = typeof target === 'function' ? (<Function>target).prototype : target; if (_relationsCache[targerKey.constructor.name]) { return _relationsCache[targerKey.constructor.name]; } //global.models.CourseModel.decorator.manytomany.students var meta = MetaUtils.getMetaData(target); if (!meta) { return null; } let relations = Enumerable.from(meta) .where((x: any) => { return RelationDecorators.indexOf((<MetaData>x).decorator) !== -1; }) .toArray(); _relationsCache[targerKey.constructor.name] = relations; return relations; } export function getRepoPathForChildIfDifferent(target: Object, prop: string) { if (!target) { throw TypeError; } //global.models.CourseModel.decorator.manytomany.students var meta = MetaUtils.getMetaData(target); if (!meta) { return null; } var type = Enumerable.from(meta).where(x => x.decoratorType == DecoratorType.CLASS).select(x => x.decorator).firstOrDefault(); var res = Enumerable.from(meta) .where((x: any) => { var met = <MetaData>x; return (RelationDecorators.indexOf(met.decorator) !== -1 && met.propertyKey === prop); }) .toArray(); if (res.length == 0) return null; meta = MetaUtils.getMetaData((<IAssociationParams>res[0].params).itemType); var childType = Enumerable.from(meta).where(x => x.decoratorType == DecoratorType.CLASS).firstOrDefault(); //if (type == childType.decorator) // return null; var repoPath; var param = <IDecoratorParams>childType.params; repoPath = Enumerable.from(pathRepoMap).where(keyVal => pathRepoMap[keyVal.key].schemaName == param.name).select(x => x.key).firstOrDefault(); return repoPath; } //@document({ name: 'blogs', isStrict: false }) //export class BlogModel //this will return 'blogs' export function getResourceNameFromModel(object: Object): string { var meta = MetaUtils.getMetaData(object, Decorators.DOCUMENT); if (!meta || !meta[0] || !meta[0].params) { return null; } return meta[0].params.name; } //@document({ name: 'blogs', isStrict: false }) //export class BlogModel //this will return 'blogs' //if calling from repo w/o object you will atleast know the name of all resources export function getAllResourceNames(): Array<string> { var resources = []; var meta = MetaUtils.getMetaDataForDecorators([Decorators.REPOSITORY]); return Enumerable.from(meta) .select(x => { return (<MetaData>x.metadata[0]).params.path; }) .toArray(); } export function getPrimaryKeyMetadata(target: Object) { var meta = MetaUtils.getMetaData(target, Decorators.FIELD); return Enumerable.from(meta) .where(keyval => keyval.params && keyval.params.primary) // keyval = {[key(propName): string]: Metadata}; .select(keyVal => keyVal) .firstOrDefault(); } export function isPromise(object: any) { if (object && (object['then'] instanceof Function || object['promiseDispatch'] instanceof Function)) return true; return false; } export function isJSON(val: any) { if (val && val.toString() == "[object Object]") return true; return false; } export function getFunctionArgs(func) { return (func + '') .replace(/[/][/].*$/mg, '') // strip single-line comments .replace(/\s+/g, '') // strip white space .replace(/[/][*][^/*]*[*][/]/g, '') // strip multi-line comments .split('){', 1)[0].replace(/^[^(]*[(]/, '') // extract the parameters .replace(/=[^,]+/g, '') // strip any ES6 defaults .split(',').filter(Boolean); // split & filter [""] } export function mapArgsWithParams(argsArray, paramsArray) { let initialValue = {}; initialValue[argsArray[0]] = paramsArray[0]; let chain = argsArray.reduce((prev, value, index) => { let z = {}; z[value] = paramsArray[index]; return Object.assign(prev, z) }, initialValue); return chain; } export function getMethodArgs(method, params): any { let args = getFunctionArgs(method); let argObject = mapArgsWithParams(args, params); return argObject; } //export function getAllRelationalMetaDataForField(target: Object, propertyKey?: string): Array<MetaData> { // if (!target) { // throw TypeError; // } // propertyKey = propertyKey || CLASSDECORATOR_PROPKEY; // var metaKey = MetadataHelper.getMetaKey(target); // if (!metadataRoot.get(metaKey)) { // return null; // } // return Enumerable.from(metadataRoot.get(metaKey)) // .where((keyVal: any) => Utils.isRelationDecorator(keyVal.key)) // .selectMany(keyval => keyval.value) // keyval = {[key(decoratorName): string]: {[key(propName)]: Metadata}}; // .where(keyVal => keyVal.key === propertyKey) // keyval = {[key(propName): string]: Metadata}; // .select(keyVal => keyVal.value) // keyval = {[key(propName): string]: Metadata}; // .toArray(); //} //var authenticateByToken = expressJwt({ // secret: SecurityConfig.SecurityConfig.tokenSecretkey, // credentialsRequired: true, // getToken: function fromHeaderOrQuerystring(req) { // if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { // return req.headers.authorization.split(' ')[1]; // } else if (req.query && req.query.token) { // return req.query.token; // } else if (req.cookies && req.cookies.authorization) { // return req.cookies.authorization; // } // return null; // } //}); //export function ensureLoggedIn() { // if (Config.Security.isAutheticationEnabled == SecurityConfig.AuthenticationEnabled[SecurityConfig.AuthenticationEnabled.disabled]) { // return function (req, res, next) { // next(); // } // } // //by token // if (Config.Security.authenticationType == SecurityConfig.AuthenticationType[SecurityConfig.AuthenticationType.TokenBased]) { // return authenticateByToken; // } // //by password // if (Config.Security.authenticationType == SecurityConfig.AuthenticationType[SecurityConfig.AuthenticationType.passwordBased]) { // return loggedIn(); // } // return function (req, res, next) { // next(); // } //}
the_stack
import 'jest-rdf'; import { Readable } from 'stream'; import arrayifyStream from 'arrayify-stream'; import { SparqlEndpointFetcher } from 'fetch-sparql-endpoint'; import { DataFactory } from 'n3'; import type { Quad } from 'rdf-js'; import { BasicRepresentation } from '../../../../src/http/representation/BasicRepresentation'; import { RepresentationMetadata } from '../../../../src/http/representation/RepresentationMetadata'; import { SparqlDataAccessor } from '../../../../src/storage/accessors/SparqlDataAccessor'; import { INTERNAL_QUADS } from '../../../../src/util/ContentTypes'; import { ConflictHttpError } from '../../../../src/util/errors/ConflictHttpError'; import { NotFoundHttpError } from '../../../../src/util/errors/NotFoundHttpError'; import { NotImplementedHttpError } from '../../../../src/util/errors/NotImplementedHttpError'; import { UnsupportedMediaTypeHttpError } from '../../../../src/util/errors/UnsupportedMediaTypeHttpError'; import type { Guarded } from '../../../../src/util/GuardedStream'; import { SingleRootIdentifierStrategy } from '../../../../src/util/identifiers/SingleRootIdentifierStrategy'; import { guardedStreamFrom } from '../../../../src/util/StreamUtil'; import { CONTENT_TYPE_TERM, LDP, RDF } from '../../../../src/util/Vocabularies'; const { literal, namedNode, quad } = DataFactory; jest.mock('fetch-sparql-endpoint'); function simplifyQuery(query: string | string[]): string { if (Array.isArray(query)) { query = query.join(' '); } return query.replace(/\n/gu, ' ').trim(); } describe('A SparqlDataAccessor', (): void => { const endpoint = 'http://test.com/sparql'; const base = 'http://test.com/'; const identifierStrategy = new SingleRootIdentifierStrategy(base); let accessor: SparqlDataAccessor; let metadata: RepresentationMetadata; let data: Guarded<Readable>; let fetchTriples: jest.Mock<Promise<Readable>>; let fetchUpdate: jest.Mock<Promise<void>>; let triples: Quad[]; let fetchError: any; let updateError: any; beforeEach(async(): Promise<void> => { metadata = new RepresentationMetadata(); data = guardedStreamFrom( [ quad(namedNode('http://name'), namedNode('http://pred'), literal('value')) ], ); triples = [ quad(namedNode('this'), namedNode('a'), namedNode('triple')) ]; // Makes it so the `SparqlEndpointFetcher` will always return the contents of the `triples` array fetchTriples = jest.fn(async(): Promise<Readable> => { if (fetchError) { throw fetchError; } return Readable.from(triples); }); fetchUpdate = jest.fn(async(): Promise<void> => { if (updateError) { throw updateError; } }); (SparqlEndpointFetcher as any).mockImplementation((): any => ({ fetchTriples, fetchUpdate, })); // This needs to be last so the fetcher can be mocked first accessor = new SparqlDataAccessor(endpoint, identifierStrategy); }); it('can only handle quad data.', async(): Promise<void> => { let representation = new BasicRepresentation(data, metadata, true); await expect(accessor.canHandle(representation)).rejects.toThrow(UnsupportedMediaTypeHttpError); representation = new BasicRepresentation(data, 'newInternalType', false); await expect(accessor.canHandle(representation)).rejects.toThrow(UnsupportedMediaTypeHttpError); representation = new BasicRepresentation(data, INTERNAL_QUADS, false); metadata.contentType = INTERNAL_QUADS; await expect(accessor.canHandle(representation)).resolves.toBeUndefined(); }); it('returns the corresponding quads when data is requested.', async(): Promise<void> => { const result = await accessor.getData({ path: 'http://identifier' }); await expect(arrayifyStream(result)).resolves.toBeRdfIsomorphic([ quad(namedNode('this'), namedNode('a'), namedNode('triple')), ]); expect(fetchTriples).toHaveBeenCalledTimes(1); expect(fetchTriples.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchTriples.mock.calls[0][1])).toBe(simplifyQuery( 'CONSTRUCT { ?s ?p ?o. } WHERE { GRAPH <http://identifier> { ?s ?p ?o. } }', )); }); it('returns the corresponding metadata when requested.', async(): Promise<void> => { metadata = await accessor.getMetadata({ path: 'http://identifier' }); expect(metadata.quads()).toBeRdfIsomorphic([ quad(namedNode('this'), namedNode('a'), namedNode('triple')), quad(namedNode('http://identifier'), CONTENT_TYPE_TERM, literal(INTERNAL_QUADS)), ]); expect(fetchTriples).toHaveBeenCalledTimes(1); expect(fetchTriples.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchTriples.mock.calls[0][1])).toBe(simplifyQuery( 'CONSTRUCT { ?s ?p ?o. } WHERE { GRAPH <meta:http://identifier> { ?s ?p ?o. } }', )); }); it('does not set the content-type for container metadata.', async(): Promise<void> => { metadata = await accessor.getMetadata({ path: 'http://container/' }); expect(metadata.quads()).toBeRdfIsomorphic([ quad(namedNode('this'), namedNode('a'), namedNode('triple')), ]); expect(fetchTriples).toHaveBeenCalledTimes(1); expect(fetchTriples.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchTriples.mock.calls[0][1])).toBe(simplifyQuery( 'CONSTRUCT { ?s ?p ?o. } WHERE { GRAPH <meta:http://container/> { ?s ?p ?o. } }', )); }); it('requests the container data to find its children.', async(): Promise<void> => { triples = [ quad(namedNode('http://container/'), LDP.terms.contains, namedNode('http://container/child')) ]; const children = []; for await (const child of accessor.getChildren({ path: 'http://container/' })) { children.push(child); } expect(children).toHaveLength(1); expect(children[0].identifier.value).toBe('http://container/child'); expect(fetchTriples).toHaveBeenCalledTimes(1); expect(fetchTriples.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchTriples.mock.calls[0][1])).toBe(simplifyQuery( 'CONSTRUCT { ?s ?p ?o. } WHERE { GRAPH <http://container/> { ?s ?p ?o. } }', )); }); it('throws 404 if no metadata was found.', async(): Promise<void> => { // Clear triples array triples = []; await expect(accessor.getMetadata({ path: 'http://identifier' })).rejects.toThrow(NotFoundHttpError); expect(fetchTriples).toHaveBeenCalledTimes(1); expect(fetchTriples.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchTriples.mock.calls[0][1])).toBe(simplifyQuery( 'CONSTRUCT { ?s ?p ?o. } WHERE { GRAPH <meta:http://identifier> { ?s ?p ?o. } }', )); }); it('overwrites the metadata when writing a container and updates parent.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/container/' }, { [RDF.type]: [ LDP.terms.Resource, LDP.terms.Container ]}); await expect(accessor.writeContainer({ path: 'http://test.com/container/' }, metadata)).resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <meta:http://test.com/container/> { ?s ?p ?o. } };', 'INSERT DATA {', ' GRAPH <meta:http://test.com/container/> {', ' <http://test.com/container/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Resource>.', ' <http://test.com/container/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Container>.', ' }', ' GRAPH <http://test.com/> { <http://test.com/> <http://www.w3.org/ns/ldp#contains> <http://test.com/container/>. }', '}', ])); }); it('does not write containment triples when writing to a root container.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/' }, { [RDF.type]: [ LDP.terms.Resource, LDP.terms.Container ]}); await expect(accessor.writeContainer({ path: 'http://test.com/' }, metadata)).resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <meta:http://test.com/> { ?s ?p ?o. } };', 'INSERT DATA {', ' GRAPH <meta:http://test.com/> {', ' <http://test.com/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Resource>.', ' <http://test.com/> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Container>.', ' }', '}', ])); }); it('overwrites the data and metadata when writing a resource and updates parent.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/container/resource' }, { [RDF.type]: [ LDP.terms.Resource ]}); await expect(accessor.writeDocument({ path: 'http://test.com/container/resource' }, data, metadata)) .resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <http://test.com/container/resource> { ?s ?p ?o. } };', 'DELETE WHERE { GRAPH <meta:http://test.com/container/resource> { ?s ?p ?o. } };', 'INSERT DATA {', ' GRAPH <meta:http://test.com/container/resource> { <http://test.com/container/resource> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Resource>. }', ' GRAPH <http://test.com/container/> { <http://test.com/container/> <http://www.w3.org/ns/ldp#contains> <http://test.com/container/resource>. }', ' GRAPH <http://test.com/container/resource> { <http://name> <http://pred> "value". }', '}', ])); }); it('overwrites the data and metadata when writing an empty resource.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/container/resource' }, { [RDF.type]: [ LDP.terms.Resource ]}); const empty = guardedStreamFrom([]); await expect(accessor.writeDocument({ path: 'http://test.com/container/resource' }, empty, metadata)) .resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <http://test.com/container/resource> { ?s ?p ?o. } };', 'DELETE WHERE { GRAPH <meta:http://test.com/container/resource> { ?s ?p ?o. } };', 'INSERT DATA {', ' GRAPH <meta:http://test.com/container/resource> { <http://test.com/container/resource> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/ns/ldp#Resource>. }', ' GRAPH <http://test.com/container/> { <http://test.com/container/> <http://www.w3.org/ns/ldp#contains> <http://test.com/container/resource>. }', '}', ])); }); it('removes all references when deleting a resource.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/container/' }, { [RDF.type]: [ LDP.terms.Resource, LDP.terms.Container ]}); await expect(accessor.deleteResource({ path: 'http://test.com/container/' })).resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <http://test.com/container/> { ?s ?p ?o. } };', 'DELETE WHERE { GRAPH <meta:http://test.com/container/> { ?s ?p ?o. } };', 'DELETE DATA { GRAPH <http://test.com/> { <http://test.com/> <http://www.w3.org/ns/ldp#contains> <http://test.com/container/>. } }', ])); }); it('does not try to remove containment triples when deleting a root container.', async(): Promise<void> => { metadata = new RepresentationMetadata({ path: 'http://test.com/' }, { [RDF.type]: [ LDP.terms.Resource, LDP.terms.Container ]}); await expect(accessor.deleteResource({ path: 'http://test.com/' })).resolves.toBeUndefined(); expect(fetchUpdate).toHaveBeenCalledTimes(1); expect(fetchUpdate.mock.calls[0][0]).toBe(endpoint); expect(simplifyQuery(fetchUpdate.mock.calls[0][1])).toBe(simplifyQuery([ 'DELETE WHERE { GRAPH <http://test.com/> { ?s ?p ?o. } };', 'DELETE WHERE { GRAPH <meta:http://test.com/> { ?s ?p ?o. } }', ])); }); it('errors when trying to write to a metadata document.', async(): Promise<void> => { const result = accessor.writeDocument({ path: 'meta:http://test.com/container/resource' }, data, metadata); await expect(result).rejects.toThrow(ConflictHttpError); await expect(result).rejects.toThrow('Not allowed to create NamedNodes with the metadata extension.'); }); it('errors when writing triples in a non-default graph.', async(): Promise<void> => { data = guardedStreamFrom( [ quad(namedNode('http://name'), namedNode('http://pred'), literal('value'), namedNode('badGraph!')) ], ); const result = accessor.writeDocument({ path: 'http://test.com/container/resource' }, data, metadata); await expect(result).rejects.toThrow(NotImplementedHttpError); await expect(result).rejects.toThrow('Only triples in the default graph are supported.'); }); it('errors when the SPARQL endpoint fails during reading.', async(): Promise<void> => { fetchError = 'error'; await expect(accessor.getMetadata({ path: 'http://identifier' })).rejects.toBe(fetchError); fetchError = new Error('read error'); await expect(accessor.getMetadata({ path: 'http://identifier' })).rejects.toThrow(fetchError); fetchError = undefined; }); it('errors when the SPARQL endpoint fails during writing.', async(): Promise<void> => { const identifier = { path: 'http://test.com/container/' }; metadata = new RepresentationMetadata(identifier); updateError = 'error'; await expect(accessor.writeContainer(identifier, metadata)).rejects.toBe(updateError); updateError = new Error('write error'); await expect(accessor.writeContainer(identifier, metadata)).rejects.toThrow(updateError); updateError = undefined; }); });
the_stack
namespace annie { /** * 显示对象抽象类,不能直接实例化。一切显示对象的基类,包含了显示对象需要的一切属性 * DisplayObject 类本身不包含任何用于在屏幕上呈现内容的 API。 * 因此,如果要创建 DisplayObject 类的自定义子类,您将需要扩展其中一个具有在屏幕 * 上呈现内容的 API 的子类,如 Shape、Sprite、Bitmap、TextField 或 MovieClip 类。 * @class annie.DisplayObject * @since 1.0.0 * @extends annie.EventDispatcher */ export abstract class DisplayObject extends EventDispatcher { // events: /** * annie.DisplayObject显示对象加入到舞台事件 * @event ADD_TO_STAGE * @since 1.0.0 */ /** * annie.DisplayObject显示对象从舞台移出事件 * @event REMOVE_TO_STAGE * @since 1.0.0 */ /** * annie.DisplayObject显示对象 循环帧事件 * @event ENTER_FRAME * @since 1.0.0 */ //MouseEvent /** * annie.DisplayObject鼠标或者手指按下事件 * @event MOUSE_DOWN * @since 1.0.0 */ /** * annie.DisplayObject鼠标或者手指抬起事件 * @event MOUSE_UP * @since 1.0.0 */ /** * annie.DisplayObject鼠标或者手指单击 * @event CLICK * @type {string} */ /** * annie.DisplayObject鼠标或者手指移动事件 * @event MOUSE_MOVE * @since 1.0.0 */ /** * annie.DisplayObject鼠标或者手指移入到显示对象上里触发的事件 * @event MOUSE_OVER * @since 1.0.0 */ /** * annie.DisplayObject鼠标或者手指移出显示对象边界触发的事件 * @event MOUSE_OUT * @since 1.0.0 */ // /** * @method DisplayObject * @since 1.0.0 * @public */ constructor() { super(); this._instanceType = "annie.DisplayObject"; } //更新信息对象是否更新矩阵 a2x_ua 是否更新Alpha a2x_uf 是否更新滤镜 protected a2x_um: boolean = false; protected a2x_ua: boolean = false; /** * 此显示对象所在的舞台对象,如果此对象没有被添加到显示对象列表中,此对象为空。 * @property stage * @public * @since 1.0.0 * @type {Stage} * @default null; * @readonly * */ public stage: Stage = null; /** * 显示对象的父级 * @property parent * @since 1.0.0 * @public * @type {annie.Sprite} * @default null * @readonly */ public parent: Sprite = null; //显示对象在显示列表上的最终表现出来的透明度,此透明度会继承父级的透明度依次相乘得到最终的值 public _cAlpha: number = 1; //显示对象上对显示列表上的最终合成的矩阵,此矩阵会继承父级的显示属性依次相乘得到最终的值 public _cMatrix: Matrix = new Matrix(); /** * 是否可以接受点击事件,如果设置为false,此显示对象将无法接收到点击事件 * @property mouseEnable * @type {boolean} * @public * @since 1.0.0 * @default false */ public mouseEnable: boolean = true; /** * 每一个显示对象都可以给他命一个名字,这样我们在查找子级的时候就可以直接用this.getChildrndByName("name")获取到这个对象的引用 * @property name * @since 1.0.0 * @public * @type {string} * @default "" */ public name: string = ""; /** * 显示对象位置x * @property x * @public * @since 1.0.0 * @type {number} * @default 0 */ public get x(): number { return this._x; } public set x(value: number) { let s = this; if (value != s._x) { s._x = value; s.a2x_um = true; } s._changeTransformInfo[0] = true; } private _x: number = 0; protected _offsetX: number = 0; protected _offsetY: number = 0; /** * 显示对象位置y * @property y * @public * @since 1.0.0 * @type {number} * @default 0 */ public get y(): number { return this._y; } public set y(value: number) { let s = this; if (value != s._y) { s._y = value; s.a2x_um = true; } s._changeTransformInfo[1] = true; } private _y: number = 0; /** * 显示对象x方向的缩放值 * @property scaleX * @public * @since 1.0.0 * @type {number} * @default 1 */ public get scaleX(): number { return this._scaleX; } public set scaleX(value: number) { let s = this; if (value != s._scaleX) { s._scaleX = value; s.a2x_um = true; } s._changeTransformInfo[2] = true; } private _scaleX: number = 1; /** * 显示对象y方向的缩放值 * @property scaleY * @public * @since 1.0.0 * @type {number} * @default 1 */ public get scaleY(): number { return this._scaleY; } public set scaleY(value: number) { let s = this; if (value != s._scaleY) { s._scaleY = value; s.a2x_um = true; } s._changeTransformInfo[3] = true; } private _scaleY: number = 1; /** * 显示对象旋转角度 * @property rotation * @public * @since 1.0.0 * @type {number} * @default 0 */ public get rotation(): number { return this._rotation; } public set rotation(value: number) { let s = this; if (value != s._rotation || s._skewX != 0 || s._skewY != 0) { s._rotation = value; s._skewX = 0; s._skewY = 0; s.a2x_um = true; } s._changeTransformInfo[4] = true; } private _rotation: number = 0; /** * 显示对象透明度 * @property alpha * @public * @since 1.0.0 * @type {number} * @default 1 */ public get alpha(): number { return this._alpha; } public set alpha(value: number) { let s = this; if (value != s._alpha) { s._alpha = value; s.a2x_ua = true; } s._changeTransformInfo[5] = true; } private _alpha: number = 1; /** * 显示对象x方向的斜切值 * @property skewX * @public * @since 1.0.0 * @type {number} * @default 0 */ public get skewX(): number { return this._skewX; } public set skewX(value: number) { let s = this; if (value != s._skewX || s._rotation != 0) { s._skewX = value; s._rotation = 0; s.a2x_um = true; } s._changeTransformInfo[4] = true; } private _skewX: number = 0; /** * 显示对象y方向的斜切值 * @property skewY * @public * @since 1.0.0 * @type {number} * @default 0 */ public get skewY(): number { return this._skewY; } public set skewY(value: number) { let s = this; if (value != s._skewY || s._rotation != 0) { s._skewY = value; s._rotation = 0; s.a2x_um = true; } s._changeTransformInfo[4] = true; } private _skewY: number = 0; /** * 显示对象上x方向的缩放或旋转点 * @property anchorX * @public * @since 1.0.0 * @type {number} * @default 0 */ public get anchorX(): number { return this._anchorX; } public set anchorX(value: number) { let s = this; if (value != s._anchorX) { s._anchorX = value; s.a2x_um = true; } } private _anchorX: number = 0; /** * 显示对象上y方向的缩放或旋转点 * @property anchorY * @public * @since 1.0.0 * @type {number} * @default 0 */ public get anchorY(): number { return this._anchorY; } public set anchorY(value: number) { let s: any = this; if (value != s._anchorY) { s._anchorY = value; s.a2x_um = true; } } private _anchorY: number = 0; /** * 显未对象是否可见 * @property visible * @public * @since 1.0.0 * @type {boolean} * @default 0 */ public get visible() { return this._visible; } public set visible(value: boolean) { let s = this; if (value != s._visible) { s._cp = true; s._visible = value; } } public _visible: boolean = true; /** * 显示对象的变形矩阵 * @property matrix * @public * @since 1.0.0 * @type {annie.Matrix} * @default null */ public get matrix(): Matrix { return this._matrix }; private _matrix: Matrix = new Matrix(); /** * 显示对象的遮罩, 是一个Shape显示对象或是一个只包含shape显示对象的MovieClip * @property mask * @public * @since 1.0.0 * @type {annie.DisplayObject} * @default null */ public get mask(): DisplayObject { return this._mask; } public set mask(value: DisplayObject) { let s = this; if (value != s._mask) { if (value instanceof annie.DisplayObject) { value._isUseToMask++; } else { if (s._mask instanceof annie.DisplayObject) { s._mask._isUseToMask--; } } s._mask = value; } } private _mask: DisplayObject = null; //是否自己的父级发生的改变 public _cp: boolean = true; /** *将全局坐标转换到本地坐标值 * @method globalToLocal * @since 1.0.0 * @public * @param {annie.Point} point * @return {annie.Point} */ public globalToLocal(point: Point, bp: Point = null): Point { return this._cMatrix.invert().transformPoint(point.x, point.y, bp); } /** *将本地坐标转换到全局坐标值 * @method localToGlobal * @public * @since 1.0.0 * @param {annie.Point} point * @return {annie.Point} */ public localToGlobal(point: Point, bp: Point = null): Point { return this._cMatrix.transformPoint(point.x, point.y, bp); } //为了 hitTestPoint,localToGlobal,globalToLocal等方法不复新不重复生成新的点对象而节约内存 public static _p1: Point = new Point(); public static _p2: Point = new Point(); public static _p3: Point = new Point(); public static _p4: Point = new Point(); protected _isUseToMask: number = 0; /** * annie.Sprite显示容器的接受鼠标点击的区域。一但设置,容器里所有子级将不会触发任何鼠标相关的事件。 * 相当于 mouseChildren=false,但在有大量子级显示对象的情况下,此方法的性能搞出mouseChildren几个数量级,建议使用。 * @property hitArea * @param {annie.Rectangle} rect * @since 3.0.1 */ public set hitArea(rect: annie.Rectangle) { this._hitArea = rect; } public get hitArea(): annie.Rectangle { return this._hitArea; } private _hitArea: annie.Rectangle = null; /** * 点击碰撞测试,就是舞台上的一个point是否在显示对象内,在则返回该对象,不在则返回null * @method hitTestPoint * @public * @since 1.0.0 * @param {annie.Point} hitPoint 要检测碰撞的点 * @param {boolean} isGlobalPoint 是不是全局坐标的点,默认false是本地坐标 * @return {annie.DisplayObject} */ public hitTestPoint(hitPoint: Point, isGlobalPoint: boolean = false): DisplayObject { let s = this; if (!s.visible || !s.mouseEnable) return null; let p: any; if (isGlobalPoint) { p = s.globalToLocal(hitPoint, DisplayObject._p1); } else { p = hitPoint; } //如果有设置鼠标活动区域,则优先使用活动区域 if (s._hitArea) { if (s._hitArea.isPointIn(p)) { return s; } } if (s._bounds.width == 0 || s._bounds.height == 0) { return null; } if (s._bounds.isPointIn(p)) { return s; } return null; } public getBounds(): Rectangle { return this._bounds; } /** * 获取对象形变后外切矩形 * 可以从这个方法中读取到此显示对象变形后x方向上的宽和y方向上的高 * @method getDrawRect * @public * @since 1.0.0 * @return {annie.Rectangle} */ public getDrawRect(matrix: annie.Matrix = null, bounds: annie.Rectangle = null): void { let s = this; if (matrix == void 0) { matrix = s.matrix; } if (bounds == void 0) { bounds = s.getBounds(); } let x: number = bounds.x, y: number = bounds.y, w: number = bounds.width, h: number = bounds.height; matrix.transformPoint(x, y, DisplayObject._p1); matrix.transformPoint(x + w, y, DisplayObject._p2); matrix.transformPoint(x + w, y + h, DisplayObject._p3); matrix.transformPoint(x, y + h, DisplayObject._p4); Rectangle.createFromPoints(DisplayObject._transformRect, DisplayObject._p1, DisplayObject._p2, DisplayObject._p3, DisplayObject._p4); } protected _updateMatrix(): void { let s = this, cm: Matrix, pcm: Matrix, ca: number, pca: number; let isHadParent: boolean = s.parent instanceof annie.Sprite; cm = s._cMatrix; ca = s._cAlpha; if (isHadParent) { pcm = s.parent._cMatrix; pca = s.parent._cAlpha; } if (s.a2x_um) { s._matrix.createBox(s._x, s._y, s._scaleX, s._scaleY, s._rotation, s._skewX, s._skewY, s._anchorX, s._anchorY); } if (s._cp) { s.a2x_um = s.a2x_ua = true; } else { if (isHadParent) { let PUI = s.parent; if (PUI.a2x_um) { s.a2x_um = true; } if (PUI.a2x_ua) { s.a2x_ua = true; } } } if (s.a2x_um) { cm.setFrom(s._matrix); if (isHadParent) { cm.prepend(pcm); } } if (s.a2x_ua) { ca = s._alpha; if (isHadParent) { ca *= pca } } s._cp = false; s._cAlpha = ca; } public _draw(ctx:any):void{} protected _render(renderObj: IRender | any): void { let s = this; if (s._visible && s._cAlpha > 0) { let ctx = CanvasRender._ctx, tm; tm = s._cMatrix; if (ctx.globalAlpha != s._cAlpha) { ctx.globalAlpha = s._cAlpha } ctx.setTransform(tm.a, tm.b, tm.c, tm.d, tm.tx, tm.ty); if (s.isNeedDraw) { s._draw(ctx); } } } /** * 获取或者设置显示对象在父级里的x方向的宽,不到必要不要用此属性获取高 * 如果你要同时获取宽高,建议使用 getWH()方法获取宽和高 * @property width * @public * @since 1.0.3 * @return {number} */ public get width(): number { this._updateMatrix(); this.getDrawRect(); return DisplayObject._transformRect.width; } public set width(value: number) { let s = this; s._updateMatrix(); s.getDrawRect(); let w = DisplayObject._transformRect.width; if (w > 0) { let sx = value / w; s.scaleX *= sx; } else { s.scaleX = 1; } } /** * 获取宽高 * @method getWH * @since 1.1.0 * @return {{w: number; h: number}} */ public getWH(): { w: number, h: number } { this._updateMatrix(); this.getDrawRect(); return {w: DisplayObject._transformRect.width, h: DisplayObject._transformRect.height}; } /** * 获取或者设置显示对象在父级里的y方向的高,不到必要不要用此属性获取高 * 如果你要同时获取宽高,建议使用getWH()方法获取宽和高 * @property height * @public * @since 1.0.3 * @return {number} */ public get height(): number { this._updateMatrix(); this.getDrawRect(); return DisplayObject._transformRect.height; } public set height(value: number) { let s = this; s._updateMatrix(); s.getDrawRect(); let h = DisplayObject._transformRect.height; if (h > 0) { let sy = value / h; s.scaleY *= sy; } else { s.scaleY = 1; } } public static _transformRect: Rectangle = new annie.Rectangle(); protected _bounds: Rectangle = new Rectangle(); public isNeedDraw:boolean=false; protected _checkDrawBounds() { let s = this; //检查所有bounds矩阵是否在可视范围里 if (s.stage) { s.getDrawRect(s._cMatrix, s._bounds); let dtr = DisplayObject._transformRect; s.isNeedDraw = Rectangle.testRectCross(dtr, s.stage.renderObj.viewPort); } } //每个Flash文件生成的对象都有一个自带的初始化信息 private _a2x_res_obj: any = {}; public destroy(): void { let s: any = this; s._a2x_res_obj = null; s.mask = null; s.parent = null; s.stage = null; s._bounds = null; s._matrix = null; s._cMatrix = null; super.destroy(); } //这里为什么要用undefined呢,这样可以知道一个对象是否从未添加到舞台过 public _isOnStage: boolean = undefined; public _onRemoveEvent(isReSetMc: boolean): void { //如果有音乐,则关闭音乐 let s = this; s._isOnStage = false; s.dispatchEvent(annie.Event.REMOVE_TO_STAGE); } public _onAddEvent(): void { let s = this; s._isOnStage = true; s.dispatchEvent(annie.Event.ADD_TO_STAGE); } public _onUpdateFrame(mcSpeed: number = 1, isOffCanvas: boolean = false): void { if (this._visible && !isOffCanvas) { this.dispatchEvent(annie.Event.ENTER_FRAME); } } private _changeTransformInfo: Array<boolean> = [false, false, false, false, false, false]; /** * 如果你在mc更改了对象的x y scale rotation alpha,最后想还原,不再需要自我控制,可以调用这方法 * @method clearCustomTransform * @param transId{number} //0->x,1->y,2->scaleX,3->scaleY,4->rotation,5->alpha,-1->all * @public * @since 3.1.0 */ public clearCustomTransform(transId: number = -1) { let s = this; if (transId = -1) { for (let i = 0; i < 6; i++) { s._changeTransformInfo[i] = false; } } else { s._changeTransformInfo[transId] = false; } } public clearBounds() { this._bounds.x = 0; this._bounds.y = 0; this._bounds.width = 0; this._bounds.height = 0; } } }
the_stack
import { T, Val, FnVal } from "./common"; import { Option, Some, None } from "./option"; import { Result, Ok, Err } from "./result"; type MappedBranches<T, U> = | (T extends Option<infer V> ? OptionMapped<V, U> : never) | (T extends Result<infer V, infer E> ? ResultMapped<V, E, U> : never); type ChainedBranches<T, U> = | Branch<T, U>[] | [...Branch<T, U>[], DefaultBranch<U>]; type BranchCondition<T> = | Mapped<T, boolean> | (T extends { [T]: boolean } ? MonadCondition<T> : Condition<T>); type Branch<T, U> = [BranchCondition<T>, BranchResult<T, U>]; type Mapped<T, U> = (val: T) => U; type Wide<T> = T extends [...infer U] ? U[number][] : Partial<T>; type BranchResult<T, U> = U | ((val: T) => U); type DefaultBranch<U> = () => U; interface OptionMapped<T, U> { Some?: MonadMapped<T, U>; None?: DefaultBranch<U>; _?: DefaultBranch<U>; } interface ResultMapped<T, E, U> { Ok?: MonadMapped<T, U>; Err?: MonadMapped<E, U>; _?: DefaultBranch<U>; } type Condition<T> = T extends object ? { [K in keyof T]?: BranchCondition<T[K]> } : T; type MonadCondition<T> = T extends Option<infer U> ? Some<MonadCondition<U>> | None : T extends Result<infer U, infer E> ? Ok<MonadCondition<U>> | Err<MonadCondition<E>> : Wide<T>; type MonadMapped<T, U> = | Mapped<T, U> | ChainedBranches<T, U> | MappedBranches<T, U>; /** * Concisely determine what action should be taken for a given input value. * * ### Mapped Matching * * Mapped matching is possible on `Option` and `Result` types. Passing any * other type will throw an invalid pattern error. * * ``` * const num = Option(10); * const res = match(num, { * Some: (n) => n + 1, * None: () => 0, * }); * * assert.equal(res, 11); * ``` * * You can nest mapped matching patterns and provide defaults. If a default is * not found in the current level it will fall back to the previous level. When * no suitable match or default is found, an exhausted error is thrown. * * ``` * function nested(val: Result<Option<number>, string>): string { * return match(val, { * Ok: { Some: (num) => `found ${num}` }, * _: () => "nothing", * }); * } * * assert.equal(nested(Ok(Some(10))), "found 10"); * assert.equal(nested(Ok(None)), "nothing"); * assert.equal(nested(Err("Not a number")), "nothing"); * ``` * * ### Combined Matching * * Mapped Matching and Chained Matching can be combined. A match chain can be * provided instead of a function for `Some`, `Ok` and `Err`. E.g. * * ``` * function matchNum(val: Option<number>): string { * return match(val, { * Some: [ * [5, "5"], * [(x) => x < 10, "< 10"], * [(x) => x > 20, "> 20"], * ], * _: () => "none or not matched", * }); * } * * assert.equal(matchNum(Some(5)), "5"); * assert.equal(matchNum(Some(7)), "< 10"); * assert.equal(matchNum(Some(25)), "> 20"); * assert.equal(matchNum(Some(15)), "none or not matched"); * assert.equal(matchNum(None), "none or not matched"); * ``` * * ### Async * * A `condition` is always a sync function. The `result` can be an async * function, providing that all branches return an async function. * * ### Chained Matching * * Chained matching is possible on any type. Branches are formed by associating * a `condition` with a `result`, and the chain is an array of branches. The * last item in a chain may be a function (called to determine the default * result when no branches match). * * A `condition` can be a: * - primitive (to test for equality) * - filter function which returns a boolean (to use a custom test) * - partial object/array of `conditions` (to test for matching keys) * - `Some`, `Ok` or `Err` containing a `condition` which is not a filter * function (and which does not included a nested filter function). * - function wrapped with `Fn` (to test for equality) * - `_` or `Default` (to match any value at this position) * * A `result` can be: * - any non-function value to be used as the result * - a function which returns the result when called * - a function wrapped with `Fn` to be used as the result * * If no branch matches and there is no default available, an exhausted error * is thrown. * * #### Primitive * * The branch succeeds if the `condition` is strictly equal to the provided * value. * * ``` * function matchNum(num: number): string { * return match(num, [ * [5, "five"], * [10, "ten"], * [15, (x) => `fifteen (${x})`], // result function * () => "other", * ]); * } * * assert.equal(matchNum(5), "five"); * assert.equal(matchNum(10), "ten"); * assert.equal(matchNum(15), "fifteen (15)"); * assert.equal(matchNum(20), "other"); * ``` * * #### Filter Function * * The branch succeeds if the `condition` returns true. * * ``` * function matchNum(num: number): string { * return match(num, [ * [5, "five"], // Primitive Match * [(x) => x < 20, "< 20"], * [(x) => x > 30, "> 30"], * () => "other", * ]); * } * * assert.equal(matchNum(5), "five"); * assert.equal(matchNum(15), "< 20"); * assert.equal(matchNum(50), "> 30"); * assert.equal(matchNum(25), "other"); * ``` * * #### Object * * The branch succeeds if all the keys in `condition` match those in the * provided value. Using `_` allows any value (even undefined), but the key * must still be present. * * * ``` * interface ExampleObj { * a: number; * b?: { c: number }; * o?: number; * } * * function matchObj(obj: ExampleObj): string { * return match(obj, [ * [{ a: 5 }, "a = 5"], * [{ b: { c: 5 } }, "c = 5"], * [{ a: 10, o: _ }, "a = 10, o = _"], * [{ a: 15, b: { c: (n) => n > 10 } }, "a = 15; c > 10"], * () => "other", * ]); * } * * assert.equal(matchObj({ a: 5 }), "a = 5"); * assert.equal(matchObj({ a: 50, b: { c: 5 } }), "c = 5"); * assert.equal(matchObj({ a: 10 }), "other"); * assert.equal(matchObj({ a: 10, o: 1 }), "a = 10, o = _"); * assert.equal(matchObj({ a: 15, b: { c: 20 } }), "a = 15; c > 10"); * assert.equal(matchObj({ a: 8, b: { c: 8 }, o: 1 }), "other"); * ``` * * #### Array * * The branch succeeds if all the indexes in `condition` match those in the * provided value. Using `_` allows any value (even undefined), but the index * must still be present. * * ``` * function matchArr(arr: number[]): string { * return match(arr, [ * [[1], "1"], * [[2, (x) => x > 10], "2, > 10"], * [[_, 6, 9, _], (a) => a.join(", ")], * () => "other", * ]); * } * * assert.equal(matchArr([1, 2, 3]), "1"); * assert.equal(matchArr([2, 12, 6]), "2, > 10"); * assert.equal(matchArr([3, 6, 9]), "other"); * assert.equal(matchArr([3, 6, 9, 12]), "3, 6, 9, 12"); * assert.equal(matchArr([2, 4, 6]), "other"); * ``` * * #### Some, Ok and Err * * The branch succeeds if the wrapping monad (e.g. `Some`) is the same as the * provided value and the inner `condition` matches the inner value. * * **Note:** Filter functions are not called for any condition wrapped in a * monad. See the section on Combined Matching for a way to match inner values. * * ``` * type NumberMonad = Option<number> | Result<number, number>; * * function matchMonad(val: NumberMonad): string { * return match(val, [ * [Some(1), "Some"], * [Ok(1), "Ok"], * [Err(1), "Err"], * () => "None", * ]); * } * * assert.equal(matchMonad(Some(1)), "Some"); * assert.equal(matchMonad(Ok(1)), "Ok"); * assert.equal(matchMonad(Err(1)), "Err"); * assert.equal(matchMonad(None), "None"); * ``` * * #### Fn (function as value) * * This wrapper distinguishes between a function to be called and a function to * be treated as a value. It is needed where the function value could be confused * with a filter function or result function. * * ``` * const fnOne = () => 1; * const fnTwo = () => 2; * const fnDefault = () => "fnDefault"; * * function matchFn(fnVal: (...args: any) => any): () => string { * return match(fnVal, [ * [Fn(fnOne), () => () => "fnOne"], // Manual result wrapper * [Fn(fnTwo), Fn(() => "fnTwo")], // Fn result wrapper * () => fnDefault, * ]); * } * * assert.equal(matchFn(fnOne)(), "fnOne"); * assert.equal(matchFn(fnTwo)(), "fnTwo"); * assert.equal(matchFn(() => 0)(), "fnDefault"); * ``` */ export function match<T, U>( val: T, pattern: MappedBranches<T, U> | ChainedBranches<T, U> ): U { return matchDispatch(val, pattern, Default); } match.compile = compile; export type match = typeof match; /** * Compile a `match` pattern to a new function. This can improve performance * by re-using the same pattern object on every invocation. * * #### Mapped Match * * ``` * const matchSome = match.compile({ * Some: (n: number) => `got some ${n}`, * None: () => "got none", * }); * * assert.equal(matchSome(Some(1)), "got some 1"); * assert.equal(matchSome(None), "got none"); * ``` * * #### Chained Match * * ``` * const matchNum = match.compile([ * [1, "got 1"], * [2, "got 2"], * [(n) => n > 100, "got > 100"], * () => "default", * ]); * * assert.equal(matchNum(1), "got 1"); * assert.equal(matchNum(2), "got 2"); * assert.equal(matchNum(5), "default"); * assert.equal(matchNum(150), "got > 100"); * ``` * * #### Advanced Types * * The compiler can't always infer the correct input type from the pattern. In * these cases we need to provide them: * * ``` * type ResOpt = Result<Option<string>, number>; * const matchResOpt = match.compile<ResOpt, string>({ * Ok: { Some: (s) => `some ${s}` }, * _: () => "default", * }); * * assert.equal(matchResOpt(Ok(Some("test"))), "some test"); * assert.equal(matchResOpt(Ok(None)), "default"); * assert.equal(matchResOpt(Err(1)), "default"); * ``` */ function compile<T, U>( pattern: MappedBranches<T, U> | ChainedBranches<T, U> ): (val: T) => U; function compile<T, U>( pattern: MappedBranches<Option<T>, U> ): (val: Option<T>) => U; function compile<T, E, U>( pattern: MappedBranches<Result<T, E>, U> ): (val: Result<T, E>) => U; function compile<T, U>( pattern: MappedBranches<T, U> | ChainedBranches<T, U> ): (val: T) => U { return (val) => match(val, pattern); } /** * The `Default` (or `_`) value. Used as a marker to indicate "any value". */ export const Default: any = () => { throw new Error("Match failed (exhausted)"); }; export type Default = any; /** * The `_` value. Used as a marker to indicate "any value". */ export const _ = Default; export type _ = any; /** * Creates a wrapper for a function so that it will be treated as a value * within a chained matching block. See `match` for more information about * when this needs to be used. */ export function Fn<T extends (...args: any) => any>(fn: T): () => T { const val: any = () => throwFnCalled(); (val as any)[FnVal] = fn; return val; } export type Fn<T> = { (): never; [FnVal]: T }; function matchMapped<T, U>( val: T, pattern: OptionMapped<any, U> & ResultMapped<any, any, U>, defaultBranch: DefaultBranch<U> ): U { if (Option.is(val)) { if (val[T]) { if (pattern.Some) { if (typeof pattern.Some === "function") { return pattern.Some(val[Val]); } else { return matchDispatch( val[Val], pattern.Some, typeof pattern._ === "function" ? pattern._ : defaultBranch ); } } } else if (typeof pattern.None === "function") { return pattern.None(); } } else if (Result.is(val)) { const Branch = val[T] ? pattern.Ok : pattern.Err; if (Branch) { if (typeof Branch === "function") { return Branch(val[Val]); } else { return matchDispatch( val[Val], Branch, typeof pattern._ === "function" ? pattern._ : defaultBranch ); } } } else { throwInvalidPattern(); } return typeof pattern._ === "function" ? pattern._() : defaultBranch(); } function matchChained<T, U>( val: T, pattern: ChainedBranches<T, U>, defaultBranch: DefaultBranch<U> ): U { for (const branch of pattern) { if (typeof branch === "function") { return (branch as Fn<U>)[FnVal] ? (branch as Fn<U>)[FnVal] : branch(); } else { const [cond, result] = branch; if (matches(cond, val, true)) { if (typeof result === "function") { return (result as Fn<U>)[FnVal] ? (result as Fn<U>)[FnVal] : (result as (val: T) => U)(val); } else { return result; } } } } return defaultBranch(); } function matches<T>( cond: BranchCondition<T>, val: T, evaluate: boolean ): boolean { if (cond === Default || cond === val) { return true; } if (typeof cond === "function") { return (cond as Fn<T>)[FnVal] ? (cond as Fn<T>)[FnVal] === val : evaluate && (cond as (val: T) => boolean)(val); } if (isObjectLike(cond)) { if (T in cond) { return ( (cond as any).isLike(val) && matches((cond as any)[Val], (val as any)[Val], false) ); } if (isObjectLike(val) && Array.isArray(cond) === Array.isArray(val)) { for (const key of Object.keys(cond)) { if ( !(key in val) || !matches((cond as any)[key], (val as any)[key], evaluate) ) { return false; } } return true; } } return false; } function matchDispatch<T, U>( val: T, pattern: ChainedBranches<T, U> | MappedBranches<T, U>, defaultBranch: DefaultBranch<U> ): U { if (Array.isArray(pattern)) { return matchChained(val, pattern, defaultBranch); } else if (isObjectLike(pattern)) { return matchMapped(val, pattern, defaultBranch); } throwInvalidPattern(); } function isObjectLike(value: unknown): value is Record<string | number, any> { return value !== null && typeof value === "object"; } function throwInvalidPattern(): never { throw new Error("Match failed (invalid pattern)"); } function throwFnCalled(): never { throw new Error("Match error (wrapped function called)"); }
the_stack
import "should"; import * as sinon from "sinon"; import { MonitoringMode, MonitoredItemCreateRequest, DataChangeFilter, DataChangeTrigger, DeadbandType, PublishRequest, PublishResponse, DataChangeNotification } from "node-opcua-service-subscription"; import { StatusCodes } from "node-opcua-status-code"; import { TimestampsToReturn } from "node-opcua-service-read"; import { DataType, VariantArrayType, Variant } from "node-opcua-variant"; import { DataValue } from "node-opcua-data-value"; import { AttributeIds } from "node-opcua-data-model"; import { NodeId, coerceNodeId } from "node-opcua-nodeid"; import { AddressSpace, Namespace, SessionContext, UAVariable } from "node-opcua-address-space"; import { get_mini_nodeset_filename } from "node-opcua-address-space/testHelpers"; import { MonitoredItem, Subscription, ServerEngine, ServerSidePublishEngine, SubscriptionState } from ".."; // tslint:disable-next-line: no-var-requires const { getFakePublishEngine } = require("./helper_fake_publish_engine"); const mini_nodeset_filename = get_mini_nodeset_filename(); const doDebug = false; const now = new Date().getTime(); const fake_publish_engine = getFakePublishEngine(); let dataSourceFrozen = false; function freeze_data_source() { dataSourceFrozen = true; } function unfreeze_data_source() { dataSourceFrozen = false; } // eslint-disable-next-line import/order const describe = require("node-opcua-leak-detector").describeWithLeakDetector; describe("Subscriptions and MonitoredItems and triggering", function (this: any) { /*** * 5.12.1.6 Triggering model ToC * The MonitoredItems Service allows the addition of items that are reported only when some other item * (the triggering item) triggers. This is done by creating links between the triggered items and the * items to report. The monitoring mode of the items to report is set to sampling-only so that it will * sample and queue Notifications without reporting them. Figure 18 illustrates this concept. * * The triggering mechanism is a useful feature that allows Clients to reduce the data volume on the * wire by configuring some items to sample frequently but only report when some other Event happens * The following triggering behaviors are specified. * If the monitoring mode of the triggering item is SAMPLING, * then it is not reported when the triggering item triggers the items to report. * If the monitoring mode of the triggering item is REPORTING, * then it is reported when the triggering item triggers the items to report. * If the monitoring mode of the triggering item is DISABLED, * then the triggering item does not trigger the items to report. * If the monitoring mode of the item to report is SAMPLING, * then it is reported when the triggering item triggers the items to report. * If the monitoring mode of the item to report is REPORTING, * this effectively causes the triggering item to be ignored. All notifications of the items to report * are sent after the publishing interval expires. * If the monitoring mode of the item to report is DISABLED, * then there will be no sampling of the item to report and therefore no notifications to report. * * The first trigger shall occur when the first notification is queued for the triggering item after the * creation of the link. Clients create and delete triggering links between a triggering item and a set * of items to report. If the MonitoredItem that represents an item to report is deleted before its * associated triggering link is deleted, the triggering link is also deleted, but the triggering * item is otherwise unaffected. * * Deletion of a MonitoredItem should not be confused with the removal of the Attribute that it monitors. * If the Node that contains the Attribute being monitored is deleted, the MonitoredItem generates a * Notification with a StatusCode Bad_NodeIdUnknown that indicates the deletion, but the MonitoredItem is not deleted. */ this.timeout(Math.max(300000, this._timeout)); let addressSpace: AddressSpace; let namespace: Namespace; let engine: ServerEngine; // eslint-disable-next-line @typescript-eslint/no-this-alias const test = this; before(async () => { engine = new ServerEngine({ applicationUri: "uri" }); await new Promise<void>((resolve) => { engine.initialize({ nodeset_filename: mini_nodeset_filename }, () => { resolve(); }); }); addressSpace = engine.addressSpace!; namespace = addressSpace.getOwnNamespace(); function addVar(varName: string, value: number) { namespace.addVariable({ organizedBy: "RootFolder", nodeId: "s=Static_" + varName, browseName: "Static_" + varName, dataType: "UInt32", value: { dataType: DataType.UInt32, value } }); } addVar("V1", 1); addVar("V2", 1); addVar("V3", 1); addVar("V4", 1); addVar("V5", 1); }); const namespaceSimulationIndex = 1; const nodeIdV1 = coerceNodeId("s=Static_V1", namespaceSimulationIndex); const nodeIdV2 = coerceNodeId("s=Static_V2", namespaceSimulationIndex); const nodeIdV3 = coerceNodeId("s=Static_V3", namespaceSimulationIndex); const nodeIdV4 = coerceNodeId("s=Static_V4", namespaceSimulationIndex); const nodeIdV5 = coerceNodeId("s=Static_V5", namespaceSimulationIndex); after(async () => { if (engine) { await engine.shutdown(); engine.dispose(); } }); beforeEach(() => { test.clock = sinon.useFakeTimers(now); }); function multipleIncrement(nodeIds: NodeId[]) { nodeIds.map((nodeId: NodeId) => { const variable = addressSpace.findNode(nodeId) as UAVariable; const dataValue = variable.readValue(); variable.setValueFromSource({ dataType: DataType.UInt32, value: dataValue.value.value + 1 }); }); } function install_spying_samplingFunc(nodeId: NodeId) { const spy_samplingEventCall = sinon.spy((oldValue, callback) => { const variable = addressSpace.findNode(nodeId) as UAVariable; const dataValue = variable.readValue(); callback(null, dataValue); }); return spy_samplingEventCall; } let subscription: Subscription; let serverSidePublishEngine: ServerSidePublishEngine; let send_response_for_request_spy: sinon.SinonSpy; beforeEach(() => { serverSidePublishEngine = new ServerSidePublishEngine({}); send_response_for_request_spy = sinon.spy(serverSidePublishEngine, "_send_response_for_request"); subscription = new Subscription({ id: 1234, publishingInterval: 100, maxKeepAliveCount: 20, lifeTimeCount: 1000, publishEngine: serverSidePublishEngine }); serverSidePublishEngine.add_subscription(subscription); subscription.state.should.equal(SubscriptionState.CREATING); send_response_for_request_spy.callCount.should.equal(0); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3, nodeIdV4]); subscription.on("monitoredItem", (monitoredItem) => { monitoredItem.samplingFunc = install_spying_samplingFunc(monitoredItem.node.nodeId); }); }); afterEach(() => { subscription.terminate(); subscription.dispose(); serverSidePublishEngine.shutdown(); serverSidePublishEngine.dispose(); }); afterEach(() => { test.clock.restore(); }); function installMonitoredItem(nodeId: NodeId, clientHandle: number, monitoringMode: MonitoringMode) { const monitoredItemCreateRequest = new MonitoredItemCreateRequest({ itemToMonitor: { nodeId, attributeId: AttributeIds.Value }, monitoringMode, requestedParameters: { clientHandle, discardOldest: true, queueSize: 1, samplingInterval: 100, filter: null } }); const createResult = subscription.createMonitoredItem(addressSpace, TimestampsToReturn.Both, monitoredItemCreateRequest); return createResult; } const invalidMonitoredItemId = 0xdeadbeef; function waitInitialNotification() { send_response_for_request_spy.resetHistory(); const fakeRequest0 = new PublishRequest({ subscriptionAcknowledgements: [] }); serverSidePublishEngine._on_PublishRequest(fakeRequest0); test.clock.tick(100); if (doDebug) { // tslint:disable-next-line: no-console console.log(send_response_for_request_spy.callCount); // tslint:disable-next-line: no-console console.log(send_response_for_request_spy.getCall(0).args[1].toString()); } while (send_response_for_request_spy.callCount === 0) { test.clock.tick(100); } send_response_for_request_spy.callCount.should.eql(1); const publishResponse = send_response_for_request_spy.getCall(0).args[1] as PublishResponse; return publishResponse; } function waitNextNotification() { send_response_for_request_spy.resetHistory(); test.clock.tick(100); const fakeRequest1 = new PublishRequest({ subscriptionAcknowledgements: [] }); serverSidePublishEngine._on_PublishRequest(fakeRequest1); while (send_response_for_request_spy.callCount === 0) { test.clock.tick(100); } if (doDebug) { // tslint:disable-next-line: no-console console.log(send_response_for_request_spy.callCount); // tslint:disable-next-line: no-console console.log(send_response_for_request_spy.getCall(0).args[1].toString()); } send_response_for_request_spy.callCount.should.eql(1); const publishResponse = send_response_for_request_spy.getCall(0).args[1] as PublishResponse; return publishResponse; } it("STG-1 should return BadNothingToDo if linksToAdd and linksToRemove are empty", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const result = subscription.setTriggering(createResult1.monitoredItemId, [], []); result.statusCode.should.eql(StatusCodes.BadNothingToDo); }); it("STG-2 should return BadMonitoredItemIdInvalid if triggeringItem is not found", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const result = subscription.setTriggering(invalidMonitoredItemId, [createResult1.monitoredItemId], []); result.statusCode.should.eql(StatusCodes.BadMonitoredItemIdInvalid); }); it("STG-3 should return Good if triggeringItem is found and all other monitoredItem are found - add", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Reporting); const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); }); it("STG-4 should return Good if triggeringItem is found and all other monitoredItem are found - remove", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Reporting); const result0 = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); const result1 = subscription.setTriggering( createResult1.monitoredItemId, [], [createResult2.monitoredItemId, createResult3.monitoredItemId] ); result1.statusCode.should.eql(StatusCodes.Good); result1.removeResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result1.addResults.should.eql([]); }); it("STG-5 If the monitoring mode of the triggering item is SAMPLING, then it is not reported when the triggering item triggers the items to report.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Sampling); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Sampling); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Sampling); const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); }); it("STG-6 If the monitoring mode of the triggering item is REPORTING, then it is reported when the triggering item triggers the items to report.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Sampling); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Sampling); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); // wait initial notification on itm 1 const publishedResponse0 = waitInitialNotification(); { publishedResponse0.notificationMessage.notificationData!.length.should.eql(1); const notifs0 = (publishedResponse0.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs0.length.should.eql(1); } const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse = waitNextNotification(); publishResponse.notificationMessage.notificationData!.length.should.eql(1); const notifs = (publishResponse.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; // console.log(publishResponse.notificationMessage.toString()); notifs.length.should.eql(3); notifs[0].clientHandle.should.eql(1); notifs[1].clientHandle.should.eql(2); notifs[2].clientHandle.should.eql(3); // ----------------------------- REMOVE ONE LINKED ITEM const result1 = subscription.setTriggering(createResult1.monitoredItemId, [], [createResult2.monitoredItemId]); result1.statusCode.should.eql(StatusCodes.Good); result1.removeResults.should.eql([StatusCodes.Good]); result1.addResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse1 = waitNextNotification(); publishResponse1.notificationMessage.notificationData!.length.should.eql(1); const notifs1 = (publishResponse1.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs1.length.should.eql(2); notifs1[0].clientHandle.should.eql(1); notifs1[1].clientHandle.should.eql(3); }); it("STG-7 If the monitoring mode of the triggering item is DISABLED, then the triggering item does not trigger the items to report.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Disabled); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Sampling); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Sampling); const publishedResponse0 = waitInitialNotification(); { publishedResponse0.notificationMessage.notificationData!.length.should.eql(0); } const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse = waitNextNotification(); publishResponse.notificationMessage.notificationData!.length.should.eql(0); }); it("STG-8 If the monitoring mode of the item to report is SAMPLING, then it is reported when the triggering item triggers the items to report.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Sampling); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Sampling); const publishedResponse0 = waitInitialNotification(); { publishedResponse0.notificationMessage.notificationData!.length.should.eql(1); const notifs0 = (publishedResponse0.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs0.length.should.eql(1); } const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse = waitNextNotification(); publishResponse.notificationMessage.notificationData!.length.should.eql(1); const notifs = (publishResponse.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs.length.should.eql(3); notifs[0].clientHandle.should.eql(1); notifs[1].clientHandle.should.eql(2); notifs[2].clientHandle.should.eql(3); }); it( "STG-9 If the monitoring mode of the item to report is REPORTING, this effectively causes the triggering item to be" + "ignored. All notifications of the items to report are sent after the publishing interval expires.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Sampling); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Reporting); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishedResponse0 = waitInitialNotification(); { publishedResponse0.notificationMessage.notificationData!.length.should.eql(1); const notifs0 = (publishedResponse0.notificationMessage.notificationData![0] as DataChangeNotification) .monitoredItems!; notifs0.length.should.eql(2); notifs0[0].clientHandle.should.eql(2); notifs0[1].clientHandle.should.eql(3); } const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse = waitNextNotification(); publishResponse.notificationMessage.notificationData!.length.should.eql(1); const notifs = (publishResponse.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs.length.should.eql(2); notifs[0].clientHandle.should.eql(2); notifs[1].clientHandle.should.eql(3); } ); it( "STG-10 If the monitoring mode of the item to report is DISABLED," + " then there will be no sampling of the item to report and therefore no notifications to report.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Disabled); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Disabled); const publishedResponse0 = waitInitialNotification(); { publishedResponse0.notificationMessage.notificationData!.length.should.eql(1); const notifs0 = (publishedResponse0.notificationMessage.notificationData![0] as DataChangeNotification) .monitoredItems!; notifs0.length.should.eql(1); } const result = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); result.statusCode.should.eql(StatusCodes.Good); result.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result.removeResults.should.eql([]); multipleIncrement([nodeIdV1, nodeIdV2, nodeIdV3]); test.clock.tick(100); const publishResponse = waitNextNotification(); publishResponse.notificationMessage.notificationData!.length.should.eql(1); const notifs = (publishResponse.notificationMessage.notificationData![0] as DataChangeNotification).monitoredItems!; notifs.length.should.eql(1); notifs[0].clientHandle.should.eql(1); } ); it("STG-11 SetTriggering: Remove the same link twice.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Reporting); const result0 = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [] ); const result1 = subscription.setTriggering(createResult1.monitoredItemId, [], [createResult3.monitoredItemId]); result1.statusCode.should.eql(StatusCodes.Good); result1.removeResults.should.eql([StatusCodes.Good]); result1.addResults.should.eql([]); const result2 = subscription.setTriggering(createResult1.monitoredItemId, [], [createResult3.monitoredItemId]); result2.statusCode.should.eql(StatusCodes.Good); result2.removeResults.should.eql([StatusCodes.BadMonitoredItemIdInvalid]); result2.addResults.should.eql([]); }); it("STG-12 SetTriggering: LinksToAdd and LinksToRemove are both empty.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const result0 = subscription.setTriggering(createResult1.monitoredItemId, [], []); result0.statusCode.should.eql(StatusCodes.BadNothingToDo); }); it("STG-13 SetTriggering: Specify the same item in both linksToAdd and linksToRemove.", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const createResult2 = installMonitoredItem(nodeIdV2, 2, MonitoringMode.Reporting); const createResult3 = installMonitoredItem(nodeIdV3, 3, MonitoringMode.Reporting); const result1 = subscription.setTriggering( createResult1.monitoredItemId, [createResult2.monitoredItemId, createResult3.monitoredItemId], [createResult2.monitoredItemId, createResult3.monitoredItemId] ); result1.statusCode.should.eql(StatusCodes.Good); result1.addResults.should.eql([StatusCodes.Good, StatusCodes.Good]); result1.removeResults.should.eql([StatusCodes.BadMonitoredItemIdInvalid, StatusCodes.BadMonitoredItemIdInvalid]); }); it("STG-14 triggeringItem and linked items cannot be the same - add", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const result1 = subscription.setTriggering(createResult1.monitoredItemId, [createResult1.monitoredItemId], []); result1.statusCode.should.eql(StatusCodes.Good); result1.addResults.should.eql([StatusCodes.BadMonitoredItemIdInvalid]); result1.removeResults.should.eql([]); }); it("STG-15 triggeringItem and linked items cannot be the same - remove", () => { const createResult1 = installMonitoredItem(nodeIdV1, 1, MonitoringMode.Reporting); const result1 = subscription.setTriggering(createResult1.monitoredItemId, [], [createResult1.monitoredItemId]); result1.statusCode.should.eql(StatusCodes.Good); result1.addResults.should.eql([]); result1.removeResults.should.eql([StatusCodes.BadMonitoredItemIdInvalid]); }); });
the_stack
import { calculateChannelId, simpleEthAllocation, serializeState, SignedState, OpenChannel, objectiveId, } from '@statechannels/wallet-core'; import {ChannelResult} from '@statechannels/client-api-schema'; import _ from 'lodash'; import {Channel} from '../../../models/channel'; import {addHash} from '../../../state-utils'; import {alice, bob, charlie} from '../fixtures/signing-wallets'; import {alice as aliceP, bob as bobP, charlie as charlieP} from '../fixtures/participants'; import {seedAlicesSigningWallet} from '../../../db/seeds/1_signing_wallet_seeds'; import {stateSignedBy, stateWithHashSignedBy} from '../fixtures/states'; import {channel, withSupportedState} from '../../../models/__test__/fixtures/channel'; import {stateVars} from '../fixtures/state-vars'; import {ObjectiveModel} from '../../../models/objective'; import {defaultTestWalletConfig} from '../../../config'; import {DBAdmin} from '../../../db-admin/db-admin'; import {WALLET_VERSION} from '../../../version'; import {PushMessageError} from '../../../errors/engine-error'; import {MultiThreadedEngine, Engine, defaultTestEngineConfig} from '../..'; import {createLogger} from '../../../logger'; const dropNonVariables = (s: SignedState): any => _.pick(s, 'appData', 'outcome', 'isFinal', 'turnNum', 'stateHash', 'signatures'); jest.setTimeout(20_000); let engine: Engine; let multiThreadedEngine: MultiThreadedEngine; beforeAll(async () => { const logger = createLogger(defaultTestWalletConfig()); await DBAdmin.migrateDatabase(defaultTestWalletConfig()); engine = await Engine.create(defaultTestEngineConfig(), logger); multiThreadedEngine = await MultiThreadedEngine.create( defaultTestEngineConfig({workerThreadAmount: 2}), logger ); }); afterAll(async () => { await engine.destroy(); await multiThreadedEngine.destroy(); }); beforeEach(async () => seedAlicesSigningWallet(engine.knex)); it("doesn't throw on an empty message", () => { return expect(engine.pushMessage({walletVersion: WALLET_VERSION})).resolves.not.toThrow(); }); const zero = 0; const four = 4; const five = 5; const six = 6; it('does not set the status of an objective if it already exists', async () => { // TODO: We pass in a signed state to avoid https://github.com/statechannels/statechannels/issues/3525 const channelToInsert = channel({vars: [stateWithHashSignedBy([alice()])()]}); const {channelId} = await Channel.query(engine.knex).insert(channelToInsert); const objective: OpenChannel = { type: 'OpenChannel', participants: [], data: { targetChannelId: channelId, fundingStrategy: 'Direct', role: 'app', }, }; const inserted = await ObjectiveModel.insert(objective, engine.knex, 'approved'); //Sanity check: We expect the objective to be approved since we used the 'approved' parameter expect(inserted.status).toBe('approved'); await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [], objectives: [objective], }); const latest = await ObjectiveModel.forId(objectiveId(objective), engine.knex); // The status should still be approved after we receive the message in a payload expect(latest.status).toBe('approved'); }); it('stores states contained in the message, in a single channel model', async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [ stateSignedBy([alice()])({turnNum: five}), stateSignedBy([alice(), bob()])({turnNum: four}), ]; await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: signedStates.map(s => serializeState(s)), }); const channelsAfter = await Channel.query(engine.knex).select(); expect(channelsAfter).toHaveLength(1); expect(channelsAfter[0].vars).toHaveLength(2); // The Channel model adds the state hash before persisting expect(channelsAfter[0].vars).toMatchObject(signedStates.map(s => dropNonVariables(s))); }); it('ignores duplicate states', async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [ stateSignedBy([alice()])({turnNum: five}), stateSignedBy([alice(), bob()])({turnNum: four}), ]; // First call should add the states await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: signedStates.map(s => serializeState(s)), }); // Second call should be ignored await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: signedStates.map(s => serializeState(s)), }); const channelsAfter = await Channel.query(engine.knex).select(); expect(channelsAfter).toHaveLength(1); expect(channelsAfter[0].vars).toHaveLength(2); // The Channel model adds the state hash before persisting expect(channelsAfter[0].vars).toMatchObject(signedStates.map(s => dropNonVariables(s))); }); it('throws for channels with different chain id', async () => { let signedState = serializeState(stateSignedBy([alice()])({turnNum: five})); signedState = {...signedState, chainId: engine.store.chainNetworkID + 'deadbeef'}; await expect( engine.pushMessage({walletVersion: WALLET_VERSION, signedStates: [signedState]}) ).rejects.toThrow(); }); it('adds signatures to existing states', async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedByAlice = stateSignedBy([alice()])({turnNum: five}); const signedByBob = stateSignedBy([bob()])({turnNum: five}); await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(signedByAlice)], }); await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(signedByBob)], }); const channelsAfter = await Channel.query(engine.knex).select(); expect(channelsAfter).toHaveLength(1); expect(channelsAfter[0].vars).toHaveLength(1); const signatures = channelsAfter[0].supported?.signatures.map(s => s.signer); expect(signatures).toContain(alice().address); expect(signatures).toContain(bob().address); }); const expectResults = async ( p: Promise<{channelResults: ChannelResult[]}>, channelResults: Partial<ChannelResult>[] ): Promise<void> => { await expect(p.then(data => data.channelResults)).resolves.toHaveLength(channelResults.length); await expect(p).resolves.toMatchObject({channelResults}); }; describe('channel results', () => { it("returns a 'proposed' channel result when receiving the first state from a peer", async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [serializeState(stateSignedBy([bob()])({turnNum: zero}))]; await expectResults(engine.pushMessage({walletVersion: WALLET_VERSION, signedStates}), [ {turnNum: zero, status: 'proposed'}, ]); }); it("returns a 'running' channel result when receiving a state in a channel that is now running", async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const {channelId} = await Channel.query(engine.knex).insert( withSupportedState()({vars: [stateVars({turnNum: 8})]}) ); return expectResults( engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(stateSignedBy([bob()])({turnNum: 9}))], }), [{channelId, turnNum: 9, status: 'running'}] ); }); it("returns a 'closing' channel result when receiving a state in a channel that is now closing", async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const participants = [aliceP(), bobP(), charlieP()]; const vars = [stateVars({turnNum: 9})]; const channel = withSupportedState([alice(), bob(), charlie()])({vars, participants}); const {channelId} = await Channel.query(engine.knex).insert(channel); const signedStates = [stateSignedBy([bob()])({turnNum: 10, isFinal: true, participants})]; return expectResults( engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: signedStates.map(ss => serializeState(ss)), }), [{channelId, turnNum: 10, status: 'closing'}] ); }); it("returns a 'closed' channel result when receiving a state in a channel that is now closed", async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [ serializeState(stateSignedBy([alice(), bob()])({turnNum: 9, isFinal: true})), ]; const result = engine.pushMessage({walletVersion: WALLET_VERSION, signedStates}); return expectResults(result, [{turnNum: 9, status: 'closed'}]); }); it('stores states for multiple channels', async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [ stateSignedBy([alice(), bob()])({turnNum: five}), stateSignedBy([alice(), bob()])({turnNum: six, channelNonce: 567, appData: '0x0f00'}), ]; const p = engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: signedStates.map(s => serializeState(s)), }); await expectResults(p, [{turnNum: five}, {turnNum: six, appData: '0x0f00'}]); const channelsAfter = await Channel.query(engine.knex).select(); expect(channelsAfter).toHaveLength(2); expect(channelsAfter[0].vars).toHaveLength(1); // The Channel model adds the state hash before persisting const stateVar = signedStates[1]; const record = await Channel.forId(calculateChannelId(stateVar), engine.knex); expect(record.vars[0]).toMatchObject(dropNonVariables(stateVar)); }); }); it("Doesn't store stale states", async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [serializeState(stateSignedBy([alice(), bob()])({turnNum: five}))]; await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates, }); const afterFirst = await Channel.query(engine.knex).select(); expect(afterFirst).toHaveLength(1); expect(afterFirst[0].vars).toHaveLength(1); expect(afterFirst[0].supported).toBeTruthy(); expect(afterFirst[0].supported?.turnNum).toEqual(five); await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(stateSignedBy()({turnNum: four}))], }); const afterSecond = await Channel.query(engine.knex).select(); expect(afterSecond[0].vars).toHaveLength(1); expect(afterSecond).toMatchObject(afterFirst); await engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(stateSignedBy()({turnNum: six}))], }); const afterThird = await Channel.query(engine.knex).select(); expect(afterThird[0].vars).toHaveLength(2); }); it("doesn't store states for unknown signing addresses", async () => { await DBAdmin.truncateDataBaseFromKnex(engine.knex, ['signing_wallets']); const signedStates = [serializeState(stateSignedBy([alice(), bob()])({turnNum: five}))]; return expect(engine.pushMessage({walletVersion: WALLET_VERSION, signedStates})).rejects.toThrow( PushMessageError ); }); describe('when the application protocol returns an action', () => { it('signs the postfund setup when the prefund setup is supported', async () => { const state = stateSignedBy()({outcome: simpleEthAllocation([])}); const c = channel({vars: [addHash(state)]}); await Channel.query(engine.knex).insert(c); await ObjectiveModel.insert( { type: 'OpenChannel', participants: c.participants, data: { targetChannelId: c.channelId, fundingStrategy: 'Fake', // Could also be Direct, funding is empty role: 'app', }, }, engine.knex, 'approved' ); expect(c.latestSignedByMe?.turnNum).toEqual(0); expect(c.supported).toBeUndefined(); const {channelId} = c; const p = engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(stateSignedBy([bob()])(state))], }); await expectResults(p, [{channelId, status: 'opening'}]); await expect(p).resolves.toMatchObject({ outbox: [{method: 'MessageQueued', params: {data: {signedStates: [{turnNum: 3}]}}}], }); const updatedC = await Channel.forId(channelId, engine.knex); expect(updatedC.protocolState).toMatchObject({ latestSignedByMe: {turnNum: 3}, supported: {turnNum: 0}, }); }); it('forms a conclusion proof when the peer wishes to close the channel', async () => { const turnNum = 6; const state = stateSignedBy()({outcome: simpleEthAllocation([]), turnNum}); const c = channel({vars: [addHash(state)]}); await Channel.query(engine.knex).insert(c); const {channelId} = c; const finalState = {...state, isFinal: true, turnNum: turnNum + 1}; const p = engine.pushMessage({ walletVersion: WALLET_VERSION, signedStates: [serializeState(stateSignedBy([bob()])(finalState))], objectives: [ { type: 'CloseChannel', participants: [], data: { targetChannelId: channelId, fundingStrategy: 'Direct', txSubmitterOrder: [1, 0], }, }, ], }); await expectResults(p, [{channelId, status: 'closed'}]); await expect(p).resolves.toMatchObject({ outbox: [ { method: 'MessageQueued', params: {data: {signedStates: [{turnNum: turnNum + 1, isFinal: true}]}}, }, ], }); const updatedC = await Channel.forId(channelId, engine.knex); expect(updatedC.protocolState).toMatchObject({ latestSignedByMe: {turnNum: turnNum + 1}, supported: {turnNum: turnNum + 1}, }); }); }); describe('when there is a request provided', () => { it('has nothing in the outbox if there is no request added', async () => { await expect( engine.pushMessage({walletVersion: WALLET_VERSION, requests: []}) ).resolves.toMatchObject({ outbox: [], }); }); it('appends message with single state to the outbox satisfying a GetChannel request', async () => { // Set up test by adding a single state into the DB via pushMessage call const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [serializeState(stateSignedBy([bob()])({turnNum: zero}))]; await engine.pushMessage({walletVersion: WALLET_VERSION, signedStates}); // Get the channelId of that which was added const [{channelId}] = await Channel.query(engine.knex).select(); // Expect a GetChannel request to produce an outbound message with all states await expect( engine.pushMessage({ walletVersion: WALLET_VERSION, requests: [{type: 'GetChannel', channelId}], }) ).resolves.toMatchObject({ outbox: [ { method: 'MessageQueued', params: {data: {signedStates}}, }, ], }); }); it('appends message with multiple states to the outbox satisfying a GetChannel request', async () => { const channelsBefore = await Channel.query(engine.knex).select(); expect(channelsBefore).toHaveLength(0); const signedStates = [ stateSignedBy([alice()])({turnNum: five}), stateSignedBy([alice(), bob()])({turnNum: four}), ].map(s => serializeState(s)); await engine.pushMessage({walletVersion: WALLET_VERSION, signedStates}); // Get the channelId of that which was added const [{channelId}] = await Channel.query(engine.knex).select(); // Expect a GetChannel request to produce an outbound message with all states await expect( engine.pushMessage({ walletVersion: WALLET_VERSION, requests: [{type: 'GetChannel', channelId}], }) ).resolves.toMatchObject({ outbox: [ { method: 'MessageQueued', params: {data: {signedStates: expect.arrayContaining(signedStates)}}, }, ], }); }); });
the_stack