text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { SecurityIdentity } from "@webiny/api-security/types";
import useGqlHandler from "./useGqlHandler";
import * as mocks from "./mocks/form.mocks";
class Mock {
public name: string;
constructor(prefix = "") {
this.name = `${prefix}name`;
}
}
interface MockSubmissionData {
firstName: string;
lastName: string;
email: string;
}
interface MockSubmissionMeta {
ip: string;
}
class MockSubmission {
public data: MockSubmissionData;
public meta: MockSubmissionMeta;
public constructor(prefix = "") {
this.data = {
firstName: `${prefix}first-name`,
lastName: `${prefix}last-name`,
email: `${prefix}email@gmail.com`
};
this.meta = {
ip: "150.129.183.18"
};
}
}
const NOT_AUTHORIZED_RESPONSE = (operation: string) => ({
data: {
formBuilder: {
[operation]: {
data: null,
error: {
code: "SECURITY_NOT_AUTHORIZED",
data: null,
message: "Not authorized!"
}
}
}
}
});
const identityA: SecurityIdentity = {
id: "a",
type: "test",
displayName: "Aa"
};
const identityB: SecurityIdentity = {
id: "b",
type: "test",
displayName: "Bb"
};
describe("Forms Submission Security Test", () => {
const handlerA = useGqlHandler({
permissions: [{ name: "content.i18n" }, { name: "fb.*" }],
identity: identityA
});
beforeEach(async () => {
try {
await handlerA.install();
} catch (ex) {
console.log("formSubmissionSecurity.test.ts");
console.log(ex.message);
}
});
test(`"listFormSubmissions" only returns entries to which the identity has access to`, async () => {
// Create form as Identity A
const [createFormA] = await handlerA.createForm({ data: new Mock("A1-") });
/**
* Make sure form is created
*/
expect(createFormA).toEqual({
data: {
formBuilder: {
createForm: {
data: {
id: expect.any(String),
formId: expect.any(String),
version: 1,
createdOn: expect.stringMatching(/^20/),
savedOn: expect.stringMatching(/^20/),
layout: [],
fields: [],
locked: false,
published: false,
publishedOn: null,
name: "A1-name",
overallStats: {
conversionRate: 0,
submissions: 0,
views: 0
},
stats: {
submissions: 0,
views: 0
},
status: "draft",
triggers: null,
settings: {
reCaptcha: {
settings: {
enabled: null,
secretKey: null,
siteKey: null
}
}
},
ownedBy: {
id: identityA.id,
displayName: identityA.displayName,
type: identityA.type
},
createdBy: {
id: identityA.id,
displayName: identityA.displayName,
type: identityA.type
}
},
error: null
}
}
}
});
const { data: formA } = createFormA.data.formBuilder.createForm;
// Let's add some fields.
const [updateFormRevisionResponse] = await handlerA.updateRevision({
revision: formA.id,
data: {
fields: mocks.fields
}
});
expect(updateFormRevisionResponse).toEqual({
data: {
formBuilder: {
updateRevision: {
data: {
...formA,
savedOn: expect.stringMatching(/^20/),
fields: expect.any(Array)
},
error: null
}
}
}
});
const [publishFormRevisionResponse] = await handlerA.publishRevision({
revision: formA.id
});
expect(publishFormRevisionResponse).toEqual({
data: {
formBuilder: {
publishRevision: {
data: {
...formA,
savedOn: expect.stringMatching(/^20/),
fields: expect.any(Array),
status: "published",
published: true,
publishedOn: expect.stringMatching(/^20/),
locked: true
},
error: null
}
}
}
});
// Create form as Identity B (this guy can only access his own forms)
const handlerB = useGqlHandler({
permissions: [{ name: "content.i18n" }, { name: "fb.*", own: true }],
identity: identityB
});
const [createFormB] = await handlerB.createForm({ data: new Mock("B1-") });
const { data: formB } = createFormB.data.formBuilder.createForm;
// Let's add some fields.
await handlerB.updateRevision({
revision: formB.id,
data: {
fields: mocks.fields
}
});
await handlerB.publishRevision({ revision: formB.id });
// Create submissions
// NOTE: response variables are unused but left here for debugging purposes!
for (let a = 1; a <= 3; a++) {
const [createFormSubmissionResponse] = await handlerA.createFormSubmission({
revision: formA.id,
...new MockSubmission(`A${a}-`)
});
expect(createFormSubmissionResponse).toEqual({
data: {
formBuilder: {
createFormSubmission: {
data: expect.any(Object),
error: null
}
}
}
});
}
for (let b = 1; b <= 2; b++) {
const [createFormSubmissionResponse] = await handlerB.createFormSubmission({
revision: formB.id,
...new MockSubmission(`B${b}-`)
});
expect(createFormSubmissionResponse).toEqual({
data: {
formBuilder: {
createFormSubmission: {
data: expect.any(Object),
error: null
}
}
}
});
}
/*
await handlerA.createFormSubmission({
revision: formA.id,
...new MockSubmission("A1-")
});
await handlerA.createFormSubmission({
revision: formA.id,
...new MockSubmission("A2-")
});
await handlerA.createFormSubmission({
revision: formA.id,
...new MockSubmission("A3-")
});
await handlerB.createFormSubmission({
revision: formB.id,
...new MockSubmission("B1-")
});
await handlerB.createFormSubmission({
revision: formB.id,
...new MockSubmission("B2-")
});
*/
await handlerA.until(
() => handlerA.listFormSubmissions({ form: formA.id }).then(([data]) => data),
({ data }: any) => data.formBuilder.listFormSubmissions.data.length === 3,
{
name: "list form A submissions"
}
);
await handlerA.until(
() => handlerA.listFormSubmissions({ form: formB.id }).then(([data]) => data),
({ data }: any) => data.formBuilder.listFormSubmissions.data.length === 2,
{
name: "list form B submissions"
}
);
// Identity A should have access to submissions in Form A
const [AlistA1] = await handlerA.listFormSubmissions({ form: formA.id });
expect(AlistA1.data.formBuilder.listFormSubmissions.data.length).toBe(3);
// Identity A should also have access to submissions in Form B
const [AlistB1] = await handlerA.listFormSubmissions({ form: formB.id });
expect(AlistB1.data.formBuilder.listFormSubmissions.data.length).toBe(2);
// Identity B should NOT have access to submissions in Form A
const [BlistA1] = await handlerB.listFormSubmissions({ form: formA.id });
expect(BlistA1).toMatchObject(NOT_AUTHORIZED_RESPONSE("listFormSubmissions"));
// Identity B should have access to submissions in Form B
const [BlistB1] = await handlerB.listFormSubmissions({ form: formB.id });
expect(BlistB1.data.formBuilder.listFormSubmissions.data.length).toBe(2);
// Identity should NOT have access to submissions in its own form,
// if `submissions: "no"` is set on the permission.
const handlerC = useGqlHandler({
permissions: [{ name: "content.i18n" }, { name: "fb.*", submissions: "no" }],
identity: identityA
});
const [ClistA1] = await handlerC.listFormSubmissions({ form: formA.id });
expect(ClistA1).toMatchObject(NOT_AUTHORIZED_RESPONSE("listFormSubmissions"));
});
}); | the_stack |
import {
Component,
OnDestroy,
Output,
EventEmitter,
OnChanges,
SimpleChanges,
Input,
AfterViewInit,
ViewChild
} from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonResponseService } from '../../../shared/services/common-response.service';
import { environment } from './../../../../environments/environment';
import { LoggerService } from '../../../shared/services/logger.service';
import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
import { VulnTrendGraphComponent } from '../vuln-trend-graph/vuln-trend-graph.component';
import { PermissionGuardService } from '../../../core/services/permission-guard.service';
import { UtilsService } from '../../../shared/services/utils.service';
import { AssetTilesService } from '../../../core/services/asset-tiles.service';
@Component({
selector: 'app-vuln-report-trend',
templateUrl: './vuln-report-trend.component.html',
styleUrls: ['./vuln-report-trend.component.css'],
providers: []
})
export class VulnReportTrendComponent implements OnDestroy, OnChanges, AfterViewInit {
@ViewChild( VulnTrendGraphComponent ) child;
vulnReportSubscription: Subscription;
subscriptionToAssetGroup: Subscription;
vulnNotesSubscription: Subscription;
selectedAssetGroup;
agName;
selectedMonth = 0;
graphResponse = 0;
notesData = [];
notesStatus = 'Please wait, we\'re fetching your notes';
notesResponse = 0;
adminAccess = false;
months = [1, 2, 3, 6, 12];
graphData;
currentFilters = '3,4,5';
parentWidth;
infoActive: true;
maxVal: any = [0, 0];
axisValues = {
y0: [],
y1: []
};
@Input() filter: any;
@Output() emitError = new EventEmitter();
@Output() infoState = new EventEmitter();
constructor(
private commonResponseService: CommonResponseService,
private logger: LoggerService,
private assetGroupObservableService: AssetGroupObservableService,
private permissions: PermissionGuardService,
private utils: UtilsService,
private assetTileService: AssetTilesService
) {
this.adminAccess = this.permissions.checkAdminPermission();
this.subscriptionToAssetGroup = this.assetGroupObservableService
.getAssetGroup()
.subscribe(assetGroupName => {
if (assetGroupName) {
this.selectedAssetGroup = assetGroupName;
this.setAgNameFromSelectedAssetGroup(this.selectedAssetGroup);
this.selectedMonth = 0;
this.updateComponent();
}
});
}
ngAfterViewInit() {
const ele = document.getElementById('graphParent');
if (ele) {
this.parentWidth = ele.clientWidth;
}
}
ngOnChanges(changes: SimpleChanges) {
try {
const DataChange = changes['filter'];
if (DataChange && DataChange.currentValue ) {
this.currentFilters = DataChange.currentValue.severity;
const prev = DataChange.previousValue;
if ((JSON.stringify(DataChange.currentValue) !== JSON.stringify(prev)) && !DataChange.firstChange) {
this.updateComponent();
}
}
} catch (e) {
this.logger.log('error', e);
}
}
updateComponent() {
if (this.vulnReportSubscription) {
this.vulnReportSubscription.unsubscribe();
}
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
this.notesData = [];
this.graphResponse = 0;
this.notesStatus = 'Please wait, we\'re fetching your notes';
this.notesResponse = 0;
this.maxVal = [0, 0];
this.axisValues = {
y0: [],
y1: []
};
this.getData();
}
getData() {
const todayDate = new Date();
const previousDate = new Date();
previousDate.setMonth(previousDate.getMonth() - this.months[this.selectedMonth]);
const graphPayload = {
'ag': this.selectedAssetGroup,
'filter': { 'severity': this.currentFilters },
'from': previousDate.toISOString(),
'to': todayDate.toISOString()
};
const graphQueryParam = {};
try {
const vulnReportGraphUrl = environment.vulnReportGraph.url;
const vulnReportGraphMethod = environment.vulnReportGraph.method;
this.vulnReportSubscription = this.commonResponseService.getData(
vulnReportGraphUrl, vulnReportGraphMethod, graphPayload, graphQueryParam).subscribe(
response => {
try {
if (!response.data.trend.length) {
this.graphResponse = -1;
this.emitError.emit();
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
} else {
this.graphData = response.data.trend;
this.graphResponse = 1;
this.processData(this.graphData);
if (this.notesData.length) {
this.updateNotePlot();
}
}
} catch (e) {
this.graphResponse = -1;
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
this.emitError.emit();
this.logger.log('error', e);
}
},
error => {
this.graphResponse = -1;
this.emitError.emit();
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
this.logger.log('error', error);
});
} catch (e) {
this.logger.log('error', e);
this.graphResponse = -1;
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
this.emitError.emit();
}
this.fetchNotesData();
}
fetchNotesData() {
try {
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
this.notesData = [];
this.infoState.emit(true);
this.notesStatus = 'Please wait, we\'re fetching your notes';
this.notesResponse = 0;
const previousDate = new Date();
previousDate.setMonth(previousDate.getMonth() - this.months[this.selectedMonth]);
const notesQueryParam = {
'ag': this.selectedAssetGroup,
'from': previousDate.toISOString().substring(0, 10)
};
const notesPayload = {};
const vulnReportNotesUrl = environment.getVulnTrendNotes.url;
const vulnReportNotesMethod = environment.getVulnTrendNotes.method;
this.vulnNotesSubscription = this.commonResponseService.getData(
vulnReportNotesUrl, vulnReportNotesMethod, notesPayload, notesQueryParam).subscribe(
response => {
try {
this.notesResponse = 1;
this.notesStatus = 'Click on the graph to add or edit notes';
this.processNotes(response.notes);
if (this.graphResponse === 1 ) {
this.updateNotePlot();
}
} catch (e) {
this.logger.log('error', e);
this.notesResponse = -1;
this.notesStatus = 'We\'re unable to fetch your notes';
this.infoState.emit(false);
}
},
error => {
this.logger.log('error', error);
this.notesResponse = -1;
this.notesStatus = 'We\'re unable to fetch your notes';
this.infoState.emit(false);
});
} catch (e) {
this.logger.log('error', e);
this.notesResponse = -1;
this.notesStatus = 'We\'re unable to fetch your notes';
this.infoState.emit(false);
}
}
processNotes(notes) {
const notesArr = [];
let cnt = 0;
for (let i = 0; i < notes.length; i++ ) {
for ( let j = 0; j < notes[i].data.length; j++ ) {
const obj = {type: notes[i].type};
Object.assign(obj, notes[i].data[j]);
notesArr.push(obj);
}
}
notesArr.sort( function (a, b) {
return (new Date(a.date)).getTime() - (new Date(b.date)).getTime();
});
this.notesData = [];
const notesObj = {};
for (let p = 0; p < notesArr.length; p++) {
notesArr[p].label = ++cnt;
notesObj[notesArr[p].date] = { data: [], date: notesArr[p].date, dateStr: (notesArr[p].date).substring(0, 5) };
}
for (let x = 0; x < notesArr.length; x++) {
notesObj[notesArr[x].date]['data'].push(notesArr[x]);
}
for (let y = 0; y < Object.keys(notesObj).length; y++) {
this.notesData[y] = notesObj[Object.keys(notesObj)[y]];
}
}
processData(data) {
// Make the display label of date
const newData = data;
for ( let i = 0; i < newData.length ; i++ ) {
const date = this.utils.getDateAndTime(newData[i].date); //new Date(newData[i].date);
newData[i].date = date;
let day = '0' + date.getDate().toString();
day = day.slice(-2);
let month = '0' + (1 + date.getMonth()).toString();
month = month.slice(-2);
newData[i].dateStr = month + '/' + day;
}
// Sort data wrt increasing date
newData.sort(function(a, b) {return (a.date.getTime() > b.date.getTime()) ? 1 : ((b.date.getTime() > a.date.getTime()) ? -1 : 0); } );
}
onResize() {
try {
const ele = document.getElementById('graphParent');
if (ele) {
this.parentWidth = ele.clientWidth;
}
} catch (e) {
this.logger.log('error', e);
}
}
setAgNameFromSelectedAssetGroup(selectedAssetGroup) {
this.assetTileService
.getAssetGroupDisplayName(selectedAssetGroup)
.subscribe(
response => {
setTimeout(() => {
this.agName = response as string;
}, 0);
},
error => {
this.logger.log(
'error',
'error in getting asset group display name - ' + error
);
}
);
}
ngOnDestroy() {
if (this.vulnReportSubscription) {
this.vulnReportSubscription.unsubscribe();
}
if (this.vulnNotesSubscription) {
this.vulnNotesSubscription.unsubscribe();
}
}
updateNotePlot() {
if (this.notesData.length) {
this.infoActive = true;
this.infoState.emit(this.infoActive);
this.processData(this.notesData);
}
}
} | the_stack |
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Utils, PathRegion, Helpable } from './Utils';
import * as d3 from 'd3';
import * as FontAwesome from 'react-fontawesome';
import * as tubeMap from './tubemap';
// import Graph from './Graph';
// import * as tubeMap from 'sequenceTubeMap/frontend/app/scripts/tubemap';
const greys = [
'#d9d9d9',
'#bdbdbd',
// '#737373',
'#969696'
// '#525252'
// '#000000'
];
export interface TubeMapProps {
graph: any;
gam: any;
pos: PathRegion[];
width: number;
sequentialId: number;
exon: any[];
changeSubPathAnnotation: () => void;
selectNodeId: (id: number) => void;
subPathAnnotation: boolean;
selectUniqueColor: (
path: string,
type: string
) => { [key: string]: string | boolean };
nodeWidthOpt?: number;
changeGam: (gam: boolean) => void;
annotations?: any;
nodeCoverages?: {[key: number]: number[]};
metaNodeCoverages?: any;
}
export interface TubeMapState {
nodeId?: number;
initialize: boolean;
mergeNodes: boolean;
nodeWidthOpt: number;
showReads: boolean;
softClips: boolean;
changedExonVisibility: boolean;
subPathAnnotation: boolean;
sequentialId: number;
pathNameDict: any[];
}
class TubeMap extends React.Component<TubeMapProps, TubeMapState> {
constructor(props: TubeMapProps) {
super(props);
this.setInitFlag = this.setInitFlag.bind(this);
this.setNodeWidth = this.setNodeWidth.bind(this);
this.setMergeNodes = this.setMergeNodes.bind(this);
this.changeSubPathAnnotation = this.changeSubPathAnnotation.bind(this);
this.changeNodeId = this.changeNodeId.bind(this);
this.changeGam = this.changeGam.bind(this);
this.selectNodeId = this.selectNodeId.bind(this);
this.fadeout = this.fadeout.bind(this);
this.fadein = this.fadein.bind(this);
this.clickDownload = this.clickDownload.bind(this);
this.readNameDownload = this.readNameDownload.bind(this);
this.state = {
initialize: false,
mergeNodes: true,
nodeWidthOpt: 3,
showReads: false,
softClips: true,
changedExonVisibility: false,
subPathAnnotation: props.subPathAnnotation,
sequentialId: 0,
pathNameDict: []
};
}
help() {
return (
<div>
<h3>SequenceTubeMap</h3>
<a href="https://github.com/vgteam/sequenceTubeMap">
{'https://github.com/vgteam/sequenceTubeMap'}
</a>
</div>
);
}
link(): string {
return '';
}
changeSubPathAnnotation() {
this.setState({ subPathAnnotation: !this.state.subPathAnnotation });
this.props.changeSubPathAnnotation();
}
changeGam() {
if (this.state.showReads) {
this.setState({ showReads: !this.state.showReads });
tubeMap.setShowReadsFlag(!this.state.showReads);
} else {
this.setState({ showReads: !this.state.showReads });
this.setState({ mergeNodes: false });
tubeMap.setMergeNodesFlag(false);
tubeMap.setShowReadsFlag(!this.state.showReads);
}
this.props.changeGam(!this.state.showReads);
}
setInitFlag() {
this.setState({ initialize: !this.state.initialize });
}
setMergeNodes() {
if (this.state.mergeNodes) {
this.setState({ mergeNodes: !this.state.mergeNodes });
tubeMap.setMergeNodesFlag(!this.state.mergeNodes);
} else {
this.setState({ mergeNodes: !this.state.mergeNodes });
this.setState({ showReads: false });
this.props.changeGam(false);
tubeMap.setShowReadsFlag(false);
tubeMap.setMergeNodesFlag(!this.state.mergeNodes);
}
}
setNodeWidth(event: any) {
this.setState({ nodeWidthOpt: Number(event.target.value) });
tubeMap.setNodeWidthOption(Number(event.target.value));
}
componentDidMount() {
this.fadeout();
this.setInitFlag();
}
componentWillReceiveProps(props: TubeMapProps) {
if (
props.graph !== '' &&
props.graph.path !== undefined &&
this.state.initialize &&
this.state.sequentialId !== props.sequentialId
) {
this.setState({ sequentialId: props.sequentialId });
d3
.select('#svg')
.selectAll('*')
.remove();
d3.select('#svg').attr('width', 100);
const graph = props.graph;
const gam = this.state.showReads ? graph.gam || {} : {}; // JSON.parse(props.gam);
const bed = props.exon;
const nodes = tubeMap.vgExtractNodes(graph);
const path = graph.path.concat(graph.genes);
const tracks = this.vgExtractTracks(path);
const nodeCoverages = props.nodeCoverages;
const metaNodeCoverages = props.metaNodeCoverages;
// const reads = this.vgExtractTracks(graph.genes);
const reads = tubeMap
.vgExtractReads(nodes, tracks, gam)
.map((alignment, index) => {
alignment.reverse_read_color = alignment.forward_read_color =
greys[index % greys.length];
return alignment;
});
this.createTubeMap(nodes, tracks, reads, bed, nodeCoverages, metaNodeCoverages);
}
}
vgExtractTracks(vg: any) {
const result = [];
vg.forEach((path, index) => {
const sequence = [];
let isCompletelyReverse = true;
path.mapping.forEach(pos => {
if (
pos.position.hasOwnProperty('is_reverse') &&
pos.position.is_reverse === true
) {
sequence.push(`-${pos.position.node_id}`);
} else {
sequence.push(`${pos.position.node_id}`);
isCompletelyReverse = false;
}
});
if (isCompletelyReverse) {
sequence.reverse();
sequence.forEach((node, index2) => {
sequence[index2] = node.substr(1);
});
}
const track: { [key: string]: any } = this.props.selectUniqueColor(
path.name,
path.type
);
track['id'] = index;
track['sequence'] = sequence;
if (path.hasOwnProperty('feature')) track['feature'] = 'gene';
if (path.hasOwnProperty('freq')) track['freq'] = path.freq;
if (path.hasOwnProperty('name')) track['name'] = path.name;
if (path.hasOwnProperty('indexOfFirstBase')) {
track['indexOfFirstBase'] = Number(path.indexOfFirstBase);
track['coordinate'] = path.mapping.map(
node => node.position.coordinate
);
}
// where within node does read start
track['firstNodeOffset'] = 0;
if (path.mapping[0].position.hasOwnProperty('offset')) {
track['firstNodeOffset'] = path.mapping[0].position.offset;
}
result.push(track);
});
return result;
}
/*
componentWillUpdate() {
if (
this.props.graph !== '' &&
this.props.graph.path !== undefined &&
this.state.initialize // &&
// this.props.graph !== props.graph
) {
const graph = this.props.graph;
const gam = JSON.parse(this.props.gam);
const nodes = tubeMap.vgExtractNodes(graph);
const tracks = tubeMap.vgExtractTracks(graph);
const reads = tubeMap.vgExtractReads(nodes, tracks, gam);
this.createTubeMap(nodes, tracks, reads);
}
}
*/
createTubeMap(nodes: any, tracks: any, reads: any, bed: any, nodeCoverages?: any, metaNodeCoverages?: any) {
// console.log(this.state);
// console.info('bed: ', bed);
tubeMap.create({
svgID: '#svg',
clickableNodes: true,
firstTrackLinear: true,
fillNodes: false,
bed,
nodes,
tracks,
reads,
nodeCoverages,
metaNodeCoverages,
});
if (!this.state.changedExonVisibility) {
tubeMap.changeExonVisibility(); //
this.setState({ changedExonVisibility: true });
}
tubeMap.setShowReadsFlag(this.state.showReads);
tubeMap.setMergeNodesFlag(this.state.mergeNodes);
tubeMap.setNodeWidthOption(this.state.nodeWidthOpt);
tubeMap.setSoftClipsFlag(this.state.softClips);
tubeMap.setColorSet('haplotypeColors', 'plainColors');
this.fadein();
}
readNameDownload() {
const gam = this.props.graph.gam; // || {} : {};
if (gam !== {} && gam !== undefined) {
// const readNames = gam.map(a => a.name ).join('\n');
const fasta = gam.map(a => `>${a.name}\n${a.sequence}`).join('\n');
var svgBlob = new Blob([fasta], {type: 'text/plain'});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement('a');
downloadLink.href = svgUrl;
downloadLink.download = this.props.pos[0].toString() + '.fasta';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
clickDownload() {
var source = document.getElementById('svg').outerHTML;
// var svgData = $("#tubeMap")[0].outerHTML;
// add name spaces.
if (!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)) {
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"');
}
if (!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)) {
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/xlink"');
}
// add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;
var svgBlob = new Blob([source], {type: 'image/svg+xml;charset=utf-8'});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement('a');
downloadLink.href = svgUrl;
downloadLink.download = this.props.pos[0].toString() + '.svg';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
changeNodeId(event: any) {
this.setState({ nodeId: event.target.value });
}
selectNodeId() {
this.props.selectNodeId(this.state.nodeId);
}
fadeout() {
var svg = d3.select('#svg'),
width = +svg.attr('width'),
height = +svg.attr('height');
var filter = svg
.append('rect')
.attr('class', 'rect')
.attr('width', width)
.attr('height', height)
.attr('fill', 'gray')
.attr('fill-opacity', 0.5);
}
fadein() {
var svg = d3.select('#svg'),
width = +svg.attr('width'),
height = +svg.attr('height');
var filter = svg.selectAll('.rect').remove();
}
render() {
return (
<div>
<div className="tubeMapSVG">
<svg id="svg" />
</div>
<div className="legendWrapper" style={{ display: 'flex' }}>
<div id="legendDiv" />
{this.props.annotations}
</div>
<div id="tubeMapConfig" className="form-group">
<div className="input-group">
<span className="input-group-prepend">
<div className="input-group-text">
<input
name="MergeNodes"
type="checkbox"
title="Merge redundant nodes"
disabled={false}
checked={this.state.mergeNodes}
onChange={this.setMergeNodes}
/>
</div>
</span>
<label className="form-control" style={{ 'height': 'auto' }}>MergeNodes</label>
<span className="input-group-prepend">
<div className="input-group-text">
<input
name="subPathAnnotation"
type="checkbox"
title="Add gene annotations as path"
disabled={false}
checked={this.state.subPathAnnotation}
onChange={this.changeSubPathAnnotation}
/>
</div>
</span>
<label className="form-control" style={{ 'height': 'auto' }}>Annotations</label>
<span className="input-group-prepend">
<div className="input-group-text">
<input
name="alignments"
type="checkbox"
title="Add alignments as reads"
disabled={false}
checked={this.state.showReads}
onChange={this.changeGam}
/>
</div>
</span>
<label className="form-control d-inline-flex" style={{ 'height': 'auto' }}>Alignments
<button className="btn btn-primary-outline" style={{padding: '0 5px', marginLeft: '10px'}} onClick={this.readNameDownload}>
<FontAwesome name="download" />
</button>
</label>
<select
value={this.state.nodeWidthOpt}
onChange={this.setNodeWidth}
className="form-control"
title="Design of tubemap: show all nucleotides or compressed design"
style={{ width: '200px', display: 'inline-block', height: '45px' }}>
<option value={0}>all sequence</option>
<option value={1}>compressed</option>
<option value={2}>compressed proportional</option>
<option value={3}>compressed proportional(small)</option>
</select>
<button className="btn btn-primary" style={{ height: '45px', margin: 0}} onClick={this.clickDownload}><FontAwesome name="download" /></button>
</div>
</div>
<div id="nodeInformation">
<div className="form-group" style={{ display: 'none' }}>
<label>uuid: </label>
<input
type="text"
name="nodeId"
id="hgvmNodeID"
className="form-control"
value={this.state.nodeId}
onChange={this.changeNodeId}
/>
<button id="hgvmPostButton" onClick={this.selectNodeId} />
</div>
</div>
</div>
);
}
}
export default TubeMap; | the_stack |
import { defineConfig, generateId, includesArray } from '@agile-ts/utils';
export class Logger {
public config: LoggerConfigInterface;
// Key/Name identifier of the Logger
public key?: LoggerKey;
// Whether the Logger is active and can log something
public isActive: boolean;
// Registered Logger Categories (type of log messages)
public loggerCategories: { [key: string]: LoggerCategoryInterface } = {};
// Registered watcher callbacks
public watchers: {
[key: string]: LoggerWatcherConfigInterface;
} = {};
/**
* Practical class for handling advanced logging
* with e.g. different types of logs or filtering.
*
* @public
* @param config - Configuration object
*/
constructor(config: CreateLoggerConfigInterface = {}) {
config = defineConfig(config, {
prefix: '',
allowedTags: [],
canUseCustomStyles: true,
active: true,
level: 0,
timestamp: false,
});
this.isActive = config.active as any;
this.config = {
timestamp: config.timestamp as any,
prefix: config.prefix as any,
canUseCustomStyles: config.canUseCustomStyles as any,
level: config.level as any,
allowedTags: config.allowedTags as any,
};
// Assign default Logger categories to the Logger
this.createLoggerCategory({
key: 'log',
level: Logger.level.LOG,
});
this.createLoggerCategory({
key: 'debug',
customStyle: 'color: #656565;',
prefix: 'Debug',
level: Logger.level.DEBUG,
});
this.createLoggerCategory({
key: 'info',
customStyle: 'color: #6c69a0;',
prefix: 'Info',
level: Logger.level.INFO,
});
this.createLoggerCategory({
key: 'success',
customStyle: 'color: #00b300;',
prefix: 'Success',
level: Logger.level.SUCCESS,
});
this.createLoggerCategory({
key: 'warn',
prefix: 'Warn',
level: Logger.level.WARN,
});
this.createLoggerCategory({
key: 'error',
prefix: 'Error',
level: Logger.level.ERROR,
});
this.createLoggerCategory({
key: 'table',
level: Logger.level.TABLE,
});
}
/**
* Default log levels of the Logger.
*
* The log level determines which type of logs can be logged.
*
* @public
*/
static get level() {
return {
DEBUG: 2,
LOG: 5,
TABLE: 5,
INFO: 10,
SUCCESS: 15,
WARN: 20,
ERROR: 50,
};
}
/**
* Lays the foundation for a conditional log.
*
* logger.if.something.do_whatever (e.g. logger.if.tag('jeff').log('hello jeff'))
*
* @public
*/
public get if() {
return {
/**
* Only performs the following action (tag().followingAction)
* if all specified tags are allowed to be logged.
*
* @public
* @param tags - Tags required to be allowed to perform the following action.
*/
tag: (tags: string[]) => this.tag(tags),
};
}
/**
* Only performs the following action (tag().followingAction)
* if all specified tags are allowed to be logged.
*
* @internal
* @param tags - Tags required to be allowed to perform the following action.
*/
private tag(tags: string[]): DefaultLogMethodsInterface {
return this.logIfCondition(includesArray(this.config.allowedTags, tags));
}
/**
* Returns an object containing the default log methods
* (log, debug, table, info, success, warn error)
* if the specified condition is true.
*
* @internal
* @param condition - Condition
* @private
*/
private logIfCondition(condition: boolean): DefaultLogMethodsInterface {
const defaultLoggerCategories = Object.keys(Logger.level).map(
(loggerCategory) => loggerCategory.toLowerCase()
);
// Build object representing the default log categories
const finalObject: DefaultLogMethodsInterface = {} as any;
for (const loggerCategory of defaultLoggerCategories) {
finalObject[loggerCategory] = condition
? (...data) => this[loggerCategory](...data) // Wrapping into method to preserve the this scope of the Logger
: () => {
/* do nothing */
};
}
return finalObject;
}
/**
* Prints to stdout with newline.
*
* @public
* @param data - Data to be logged.
*/
public log(...data: any[]) {
this.invokeConsole(data, 'log', 'log');
}
/**
* The 'logger.debug()' function is an alias for 'logger.log()'.
*
* @public
* @param data - Data to be logged.
*/
public debug(...data: any[]) {
this.invokeConsole(
data,
'debug',
typeof console.debug !== 'undefined' ? 'debug' : 'log'
);
}
/**
* The 'logger.info()' function is an alias for 'logger.log()'.
*
* @public
* @param data - Data to be logged.
*/
public info(...data: any[]) {
this.invokeConsole(
data,
'info',
typeof console.info !== 'undefined' ? 'info' : 'log'
);
}
/**
* The 'logger.success()' function is an alias for 'logger.log()'.
*
* @public
* @param data - Data to be logged.
*/
public success(...data: any[]) {
this.invokeConsole(data, 'success', 'log');
}
/**
* The 'logger.warn()' function is an alias for 'logger.error()'.
*
* @public
* @param data - Data to be logged.
*/
public warn(...data: any[]) {
this.invokeConsole(
data,
'warn',
typeof console.warn !== 'undefined' ? 'warn' : 'log'
);
}
/**
* Prints to stderr with newline.
*
* @public
* @param data - Data to be logged.
*/
public error(...data: any[]) {
this.invokeConsole(
data,
'error',
typeof console.error !== 'undefined' ? 'error' : 'log'
);
}
/**
* Prints the specified object in a visual table.
*
* @public
* @param data - Data to be logged.
*/
public table(...data: any[]) {
this.invokeConsole(
data,
'table',
typeof console.table !== 'undefined' ? 'table' : 'log'
);
}
/**
* Prints a log message based on the specified logger category.
*
* @public
* @param loggerCategory - Key/Name identifier of the Logger category.
* @param data - Data to be logged.
*/
public custom(loggerCategory: string, ...data: any[]) {
this.invokeConsole(data, loggerCategory, 'log');
}
/**
* Internal method for logging the specified data
* into the 'console' based on the provided logger category.
*
* @internal
* @param data - Data to be logged.
* @param loggerCategoryKey - Key/Name identifier of the Logger category.
* @param consoleLogType - What type of log to invoke the console with (console[consoleLogType]).
*/
private invokeConsole(
data: any[],
loggerCategoryKey: LoggerCategoryKey,
consoleLogType: ConsoleLogType
) {
const loggerCategory = this.getLoggerCategory(loggerCategoryKey);
if (!this.isActive || loggerCategory.level < this.config.level) return;
// Build log prefix
const buildPrefix = (): string => {
let prefix = '';
if (this.config.timestamp)
prefix = prefix.concat(`[${Date.now().toString()}] `);
if (this.config.prefix) prefix = prefix.concat(this.config.prefix);
if (loggerCategory.prefix)
prefix = prefix.concat(' ' + loggerCategory.prefix);
if (this.config.prefix || loggerCategory.prefix)
prefix = prefix.concat(':');
return prefix;
};
// Add created log prefix to the data array
if (typeof data[0] === 'string')
data[0] = buildPrefix().concat(' ').concat(data[0]);
else data.unshift(buildPrefix());
// Call watcher callbacks
for (const key in this.watchers) {
const watcher = this.watchers[key];
if (loggerCategory.level >= watcher.level) {
watcher.callback(loggerCategory, data);
}
}
// Init custom styling provided by the Logger category
if (this.config.canUseCustomStyles && loggerCategory.customStyle) {
const newLogs: any[] = [];
let didStyle = false;
for (const log of data) {
if (
!didStyle && // Because only one string part of a log can be styled
typeof log === 'string'
) {
newLogs.push(`%c${log}`);
newLogs.push(loggerCategory.customStyle);
didStyle = true;
} else {
newLogs.push(log);
}
}
data = newLogs;
}
// Handle table log
if (consoleLogType === 'table') {
for (const log of data)
console[typeof log === 'object' ? 'table' : 'log'](log);
}
// Handle 'normal' log
else {
console[consoleLogType](...data);
}
}
/**
* Creates a new Logger category and assigns it to the Logger.
*
* @public
* @param loggerCategory - Logger category to be added to the Logger.
*/
public createLoggerCategory(loggerCategory: CreateLoggerCategoryInterface) {
loggerCategory = {
prefix: '',
level: 0,
...loggerCategory,
};
this.loggerCategories[loggerCategory.key] = loggerCategory as any;
}
/**
* Retrieves a single Logger category with the specified key/name identifier from the Logger.
*
* If the to retrieve Logger category doesn't exist, `undefined` is returned.
*
* @public
* @param categoryKey - Key/Name identifier of the Logger category.
*/
public getLoggerCategory(categoryKey: LoggerCategoryKey) {
return this.loggerCategories[categoryKey];
}
/**
* Fires on each logged message of the Logger.
*
* @public
* @param callback - A function to be executed on each logged message of the Logger.
* @param config - Configuration object
*/
public watch(
callback: LoggerWatcherCallback,
config: WatcherMethodConfigInterface = {}
): this {
config = defineConfig(config, {
key: generateId(),
level: 0,
});
this.watchers[config.key as any] = {
callback,
level: config.level as any,
};
return this;
}
/**
* Assigns the specified log level to the Logger.
*
* The Logger level determines which Logger categories (log message types) can be logged.
* By default, the logger supports a various number of levels,
* which are represented in 'Logger.level'.
*
* @public
* @param level - Level
*/
public setLevel(level: number): this {
this.config.level = level;
return this;
}
}
export type LoggerCategoryKey = string | number;
export type LoggerKey = string | number;
export interface LoggerConfigInterface {
/**
* Prefix to be added before each log message.
* @default ''
*/
prefix: string;
/**
* Whether custom styles can be applied to the log messages.
* @default true
*/
canUseCustomStyles: boolean;
/**
* Handles which Logger categories (log message types) can be logged.
* @default 0
*/
level: number;
/**
* Whether to append the current timestamp before each log message.
* @default false
*/
timestamp: boolean;
/**
* Array of tags that must be included in a conditional log to be logged.
* @default []
*/
allowedTags: LoggerKey[];
}
export interface CreateLoggerConfigInterface {
/**
* Whether the Logger is allowed to log a message.
* @default true
*/
active?: boolean;
/**
* Prefix to be added before each log message.
* @default ''
*/
prefix?: string;
/**
* Whether custom styles can be applied to the log messages.
* @default true
*/
canUseCustomStyles?: boolean;
/**
* Handles which Logger categories (log message types) can be logged.
* @default 0
*/
level?: number;
/**
* Whether to append the current timestamp before each log message.
* @default false
*/
timestamp?: boolean;
/**
* Array of tags that must be included in a conditional log to be logged.
* @default []
*/
allowedTags?: LoggerKey[];
}
export type ConsoleLogType =
| 'log'
| 'warn'
| 'error'
| 'table'
| 'info'
| 'debug';
export interface LoggerCategoryInterface {
/**
* Key/Name identifier of the Logger category.
* @default undefined
*/
key: LoggerCategoryKey;
/**
* CSS Styles to be applied to the log messages of this category.
* @default ''
*/
customStyle?: string;
/**
* Prefix to be written before each Log message of this category.
* @default ''
*/
prefix: string;
/**
* From which level the log messages of this category can be logged.
* @default 0
*/
level: number;
}
export interface CreateLoggerCategoryInterface {
/**
* Key/Name identifier of the Logger category.
* @default undefined
*/
key: LoggerCategoryKey;
/**
* CSS Styles to be applied to the log messages of this category.
* @default ''
*/
customStyle?: string;
/**
* Prefix to be written before each Log message of this category.
* @default ''
*/
prefix?: string;
/**
* From which level the log messages of this category can be logged.
* @default 0
*/
level?: number;
}
export type LoggerWatcherCallback = (
loggerCategory: LoggerCategoryInterface,
data: any[]
) => void;
export interface LoggerWatcherConfigInterface {
/**
* Callback method to be fired on each log action.
*/
callback: LoggerWatcherCallback;
/**
* From which level the watcher callback should be fired.
*/
level: number;
}
export interface WatcherMethodConfigInterface {
/**
* Key/Name identifier of the watcher callback.
* @default generated id
*/
key?: string;
/**
* From which level the watcher callback should be fired.
* @default 0
*/
level?: number;
}
export interface DefaultLogMethodsInterface {
log: (...data: any) => void;
debug: (...data: any) => void;
info: (...data: any) => void;
success: (...data: any) => void;
warn: (...data: any) => void;
error: (...data: any) => void;
table: (...data: any) => void;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* BGP information that must be configured into the routing stack to
* establish BGP peering. This information must specify the peer ASN
* and either the interface name, IP address, or peer IP address.
* Please refer to RFC4273.
*
* To get more information about RouterBgpPeer, see:
*
* * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/routers)
* * How-to Guides
* * [Google Cloud Router](https://cloud.google.com/router/docs/)
*
* ## Example Usage
* ### Router Peer Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const peer = new gcp.compute.RouterPeer("peer", {
* advertisedRoutePriority: 100,
* interface: "interface-1",
* peerAsn: 65513,
* peerIpAddress: "169.254.1.2",
* region: "us-central1",
* router: "my-router",
* });
* ```
* ### Router Peer Disabled
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const peer = new gcp.compute.RouterPeer("peer", {
* advertisedRoutePriority: 100,
* enable: false,
* interface: "interface-1",
* peerAsn: 65513,
* peerIpAddress: "169.254.1.2",
* region: "us-central1",
* router: "my-router",
* });
* ```
* ### Router Peer Bfd
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const peer = new gcp.compute.RouterPeer("peer", {
* advertisedRoutePriority: 100,
* bfd: {
* minReceiveInterval: 1000,
* minTransmitInterval: 1000,
* multiplier: 5,
* sessionInitializationMode: "ACTIVE",
* },
* interface: "interface-1",
* peerAsn: 65513,
* peerIpAddress: "169.254.1.2",
* region: "us-central1",
* router: "my-router",
* });
* ```
*
* ## Import
*
* RouterBgpPeer can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:compute/routerPeer:RouterPeer default projects/{{project}}/regions/{{region}}/routers/{{router}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/routerPeer:RouterPeer default {{project}}/{{region}}/{{router}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/routerPeer:RouterPeer default {{region}}/{{router}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:compute/routerPeer:RouterPeer default {{router}}/{{name}}
* ```
*/
export class RouterPeer extends pulumi.CustomResource {
/**
* Get an existing RouterPeer 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?: RouterPeerState, opts?: pulumi.CustomResourceOptions): RouterPeer {
return new RouterPeer(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:compute/routerPeer:RouterPeer';
/**
* Returns true if the given object is an instance of RouterPeer. 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 RouterPeer {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === RouterPeer.__pulumiType;
}
/**
* User-specified flag to indicate which mode to use for advertisement.
* Valid values of this enum field are: `DEFAULT`, `CUSTOM`
* Default value is `DEFAULT`.
* Possible values are `DEFAULT` and `CUSTOM`.
*/
public readonly advertiseMode!: pulumi.Output<string | undefined>;
/**
* User-specified list of prefix groups to advertise in custom
* mode, which can take one of the following options:
* * `ALL_SUBNETS`: Advertises all available subnets, including peer VPC subnets.
* * `ALL_VPC_SUBNETS`: Advertises the router's own VPC subnets.
* * `ALL_PEER_VPC_SUBNETS`: Advertises peer subnets of the router's VPC network.
*/
public readonly advertisedGroups!: pulumi.Output<string[] | undefined>;
/**
* User-specified list of individual IP ranges to advertise in
* custom mode. This field can only be populated if advertiseMode
* is `CUSTOM` and is advertised to all peers of the router. These IP
* ranges will be advertised in addition to any specified groups.
* Leave this field blank to advertise no custom IP ranges.
* Structure is documented below.
*/
public readonly advertisedIpRanges!: pulumi.Output<outputs.compute.RouterPeerAdvertisedIpRange[] | undefined>;
/**
* The priority of routes advertised to this BGP peer.
* Where there is more than one matching route of maximum
* length, the routes with the lowest priority value win.
*/
public readonly advertisedRoutePriority!: pulumi.Output<number | undefined>;
/**
* BFD configuration for the BGP peering.
* Structure is documented below.
*/
public readonly bfd!: pulumi.Output<outputs.compute.RouterPeerBfd>;
/**
* The status of the BGP peer connection. If set to false, any active session
* with the peer is terminated and all associated routing information is removed.
* If set to true, the peer connection can be established with routing information.
* The default is true.
*/
public readonly enable!: pulumi.Output<boolean | undefined>;
/**
* Name of the interface the BGP peer is associated with.
*/
public readonly interface!: pulumi.Output<string>;
/**
* IP address of the interface inside Google Cloud Platform.
* Only IPv4 is supported.
*/
public readonly ipAddress!: pulumi.Output<string>;
/**
* The resource that configures and manages this BGP peer. * 'MANAGED_BY_USER' is the default value and can be managed by
* you or other users * 'MANAGED_BY_ATTACHMENT' is a BGP peer that is configured and managed by Cloud Interconnect,
* specifically by an InterconnectAttachment of type PARTNER. Google automatically creates, updates, and deletes this type
* of BGP peer when the PARTNER InterconnectAttachment is created, updated, or deleted.
*/
public /*out*/ readonly managementType!: pulumi.Output<string>;
/**
* Name of this BGP peer. The name must be 1-63 characters long,
* and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `a-z?` which
* means the first character must be a lowercase letter, and all
* following characters must be a dash, lowercase letter, or digit,
* except the last character, which cannot be a dash.
*/
public readonly name!: pulumi.Output<string>;
/**
* Peer BGP Autonomous System Number (ASN).
* Each BGP interface may use a different value.
*/
public readonly peerAsn!: pulumi.Output<number>;
/**
* IP address of the BGP interface outside Google Cloud Platform.
* Only IPv4 is supported.
*/
public readonly peerIpAddress!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Region where the router and BgpPeer reside.
* If it is not provided, the provider region is used.
*/
public readonly region!: pulumi.Output<string>;
/**
* The name of the Cloud Router in which this BgpPeer will be configured.
*/
public readonly router!: pulumi.Output<string>;
/**
* Create a RouterPeer 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: RouterPeerArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: RouterPeerArgs | RouterPeerState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as RouterPeerState | undefined;
inputs["advertiseMode"] = state ? state.advertiseMode : undefined;
inputs["advertisedGroups"] = state ? state.advertisedGroups : undefined;
inputs["advertisedIpRanges"] = state ? state.advertisedIpRanges : undefined;
inputs["advertisedRoutePriority"] = state ? state.advertisedRoutePriority : undefined;
inputs["bfd"] = state ? state.bfd : undefined;
inputs["enable"] = state ? state.enable : undefined;
inputs["interface"] = state ? state.interface : undefined;
inputs["ipAddress"] = state ? state.ipAddress : undefined;
inputs["managementType"] = state ? state.managementType : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["peerAsn"] = state ? state.peerAsn : undefined;
inputs["peerIpAddress"] = state ? state.peerIpAddress : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["router"] = state ? state.router : undefined;
} else {
const args = argsOrState as RouterPeerArgs | undefined;
if ((!args || args.interface === undefined) && !opts.urn) {
throw new Error("Missing required property 'interface'");
}
if ((!args || args.peerAsn === undefined) && !opts.urn) {
throw new Error("Missing required property 'peerAsn'");
}
if ((!args || args.peerIpAddress === undefined) && !opts.urn) {
throw new Error("Missing required property 'peerIpAddress'");
}
if ((!args || args.router === undefined) && !opts.urn) {
throw new Error("Missing required property 'router'");
}
inputs["advertiseMode"] = args ? args.advertiseMode : undefined;
inputs["advertisedGroups"] = args ? args.advertisedGroups : undefined;
inputs["advertisedIpRanges"] = args ? args.advertisedIpRanges : undefined;
inputs["advertisedRoutePriority"] = args ? args.advertisedRoutePriority : undefined;
inputs["bfd"] = args ? args.bfd : undefined;
inputs["enable"] = args ? args.enable : undefined;
inputs["interface"] = args ? args.interface : undefined;
inputs["ipAddress"] = args ? args.ipAddress : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["peerAsn"] = args ? args.peerAsn : undefined;
inputs["peerIpAddress"] = args ? args.peerIpAddress : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["router"] = args ? args.router : undefined;
inputs["managementType"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(RouterPeer.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering RouterPeer resources.
*/
export interface RouterPeerState {
/**
* User-specified flag to indicate which mode to use for advertisement.
* Valid values of this enum field are: `DEFAULT`, `CUSTOM`
* Default value is `DEFAULT`.
* Possible values are `DEFAULT` and `CUSTOM`.
*/
advertiseMode?: pulumi.Input<string>;
/**
* User-specified list of prefix groups to advertise in custom
* mode, which can take one of the following options:
* * `ALL_SUBNETS`: Advertises all available subnets, including peer VPC subnets.
* * `ALL_VPC_SUBNETS`: Advertises the router's own VPC subnets.
* * `ALL_PEER_VPC_SUBNETS`: Advertises peer subnets of the router's VPC network.
*/
advertisedGroups?: pulumi.Input<pulumi.Input<string>[]>;
/**
* User-specified list of individual IP ranges to advertise in
* custom mode. This field can only be populated if advertiseMode
* is `CUSTOM` and is advertised to all peers of the router. These IP
* ranges will be advertised in addition to any specified groups.
* Leave this field blank to advertise no custom IP ranges.
* Structure is documented below.
*/
advertisedIpRanges?: pulumi.Input<pulumi.Input<inputs.compute.RouterPeerAdvertisedIpRange>[]>;
/**
* The priority of routes advertised to this BGP peer.
* Where there is more than one matching route of maximum
* length, the routes with the lowest priority value win.
*/
advertisedRoutePriority?: pulumi.Input<number>;
/**
* BFD configuration for the BGP peering.
* Structure is documented below.
*/
bfd?: pulumi.Input<inputs.compute.RouterPeerBfd>;
/**
* The status of the BGP peer connection. If set to false, any active session
* with the peer is terminated and all associated routing information is removed.
* If set to true, the peer connection can be established with routing information.
* The default is true.
*/
enable?: pulumi.Input<boolean>;
/**
* Name of the interface the BGP peer is associated with.
*/
interface?: pulumi.Input<string>;
/**
* IP address of the interface inside Google Cloud Platform.
* Only IPv4 is supported.
*/
ipAddress?: pulumi.Input<string>;
/**
* The resource that configures and manages this BGP peer. * 'MANAGED_BY_USER' is the default value and can be managed by
* you or other users * 'MANAGED_BY_ATTACHMENT' is a BGP peer that is configured and managed by Cloud Interconnect,
* specifically by an InterconnectAttachment of type PARTNER. Google automatically creates, updates, and deletes this type
* of BGP peer when the PARTNER InterconnectAttachment is created, updated, or deleted.
*/
managementType?: pulumi.Input<string>;
/**
* Name of this BGP peer. The name must be 1-63 characters long,
* and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `a-z?` which
* means the first character must be a lowercase letter, and all
* following characters must be a dash, lowercase letter, or digit,
* except the last character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* Peer BGP Autonomous System Number (ASN).
* Each BGP interface may use a different value.
*/
peerAsn?: pulumi.Input<number>;
/**
* IP address of the BGP interface outside Google Cloud Platform.
* Only IPv4 is supported.
*/
peerIpAddress?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Region where the router and BgpPeer reside.
* If it is not provided, the provider region is used.
*/
region?: pulumi.Input<string>;
/**
* The name of the Cloud Router in which this BgpPeer will be configured.
*/
router?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a RouterPeer resource.
*/
export interface RouterPeerArgs {
/**
* User-specified flag to indicate which mode to use for advertisement.
* Valid values of this enum field are: `DEFAULT`, `CUSTOM`
* Default value is `DEFAULT`.
* Possible values are `DEFAULT` and `CUSTOM`.
*/
advertiseMode?: pulumi.Input<string>;
/**
* User-specified list of prefix groups to advertise in custom
* mode, which can take one of the following options:
* * `ALL_SUBNETS`: Advertises all available subnets, including peer VPC subnets.
* * `ALL_VPC_SUBNETS`: Advertises the router's own VPC subnets.
* * `ALL_PEER_VPC_SUBNETS`: Advertises peer subnets of the router's VPC network.
*/
advertisedGroups?: pulumi.Input<pulumi.Input<string>[]>;
/**
* User-specified list of individual IP ranges to advertise in
* custom mode. This field can only be populated if advertiseMode
* is `CUSTOM` and is advertised to all peers of the router. These IP
* ranges will be advertised in addition to any specified groups.
* Leave this field blank to advertise no custom IP ranges.
* Structure is documented below.
*/
advertisedIpRanges?: pulumi.Input<pulumi.Input<inputs.compute.RouterPeerAdvertisedIpRange>[]>;
/**
* The priority of routes advertised to this BGP peer.
* Where there is more than one matching route of maximum
* length, the routes with the lowest priority value win.
*/
advertisedRoutePriority?: pulumi.Input<number>;
/**
* BFD configuration for the BGP peering.
* Structure is documented below.
*/
bfd?: pulumi.Input<inputs.compute.RouterPeerBfd>;
/**
* The status of the BGP peer connection. If set to false, any active session
* with the peer is terminated and all associated routing information is removed.
* If set to true, the peer connection can be established with routing information.
* The default is true.
*/
enable?: pulumi.Input<boolean>;
/**
* Name of the interface the BGP peer is associated with.
*/
interface: pulumi.Input<string>;
/**
* IP address of the interface inside Google Cloud Platform.
* Only IPv4 is supported.
*/
ipAddress?: pulumi.Input<string>;
/**
* Name of this BGP peer. The name must be 1-63 characters long,
* and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `a-z?` which
* means the first character must be a lowercase letter, and all
* following characters must be a dash, lowercase letter, or digit,
* except the last character, which cannot be a dash.
*/
name?: pulumi.Input<string>;
/**
* Peer BGP Autonomous System Number (ASN).
* Each BGP interface may use a different value.
*/
peerAsn: pulumi.Input<number>;
/**
* IP address of the BGP interface outside Google Cloud Platform.
* Only IPv4 is supported.
*/
peerIpAddress: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Region where the router and BgpPeer reside.
* If it is not provided, the provider region is used.
*/
region?: pulumi.Input<string>;
/**
* The name of the Cloud Router in which this BgpPeer will be configured.
*/
router: pulumi.Input<string>;
} | the_stack |
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0";
import { LuaArray, LuaObj, ipairs, lualength, pairs, unpack } from "@wowts/lua";
import { concat, insert, sort } from "@wowts/table";
import { GetUnitName, UnitGUID, UnitIsUnit } from "@wowts/wow-mock";
import { AceModule } from "@wowts/tsaddon";
import { OvaleClass } from "../Ovale";
import { Tracer, DebugTools } from "./debug";
import { binaryInsertUnique, binaryRemove } from "../tools/array";
import { LRUCache } from "../tools/cache";
import { OptionUiGroup } from "../ui/acegui-helpers";
function dumpMapping(t: LuaObj<LuaArray<string>>, output: LuaArray<string>) {
for (const [key, array] of pairs(t)) {
const size = lualength(array);
if (size > 1) {
insert(output, ` ${key}: {`);
for (const [, value] of ipairs(array)) {
insert(output, ` ${value},`);
}
insert(output, ` },`);
} else if (size == 1) {
insert(output, ` ${key}: ${array[1]},`);
}
}
}
export class Guids {
private module: AceModule & AceEvent;
private tracer: Tracer;
private guidByUnit: LuaObj<string> = {};
private unitByGUID: LuaObj<LuaArray<string>> = {};
private nameByUnit: LuaObj<string> = {};
private unitByName: LuaObj<LuaArray<string>> = {};
private nameByGUID: LuaObj<string> = {};
private guidByName: LuaObj<LuaArray<string>> = {};
private ownerGUIDByGUID: LuaObj<string> = {};
private unusedGUIDCache: LRUCache<string>;
private childUnitByUnit: LuaObj<LuaObj<boolean>> = {};
private petUnitByUnit: LuaObj<string> = {};
// eventfulUnits is an ordered array of unit IDs that receive unit events.
private eventfulUnits: LuaArray<string> = {};
private unitPriority: LuaObj<number> = {};
unitAuraUnits: LuaObj<boolean> = {};
petGUID: LuaObj<boolean> = {};
private debugGUIDs: OptionUiGroup = {
type: "group",
name: "GUID",
args: {
guid: {
type: "input",
name: "GUID",
multiline: 25,
width: "full",
get: () => {
const output: LuaArray<string> = {};
insert(output, "Unit by GUID = {");
dumpMapping(this.unitByGUID, output);
insert(output, "}\n");
insert(output, "Unit by Name = {");
dumpMapping(this.unitByName, output);
insert(output, "}\n");
insert(output, "GUID by Name = {");
dumpMapping(this.guidByName, output);
insert(output, "}\n");
insert(output, "Unused GUIDs = {");
const guids = this.unusedGUIDCache.asArray();
sort(guids);
for (const [, guid] of ipairs(guids)) {
insert(output, ` ${guid}`);
}
insert(output, "}");
return concat(output, "\n");
},
},
},
};
constructor(private ovale: OvaleClass, debug: DebugTools) {
debug.defaultOptions.args["guid"] = this.debugGUIDs;
this.module = ovale.createModule(
"OvaleGUID",
this.handleInitialize,
this.handleDisable,
aceEvent
);
this.tracer = debug.create(this.module.GetName());
/* Cache the last 100 unreferenced GUIDs to retain their
* name mappings.
*/
this.unusedGUIDCache = new LRUCache<string>(100);
this.petUnitByUnit["player"] = "pet";
insert(this.eventfulUnits, "player");
insert(this.eventfulUnits, "vehicle");
insert(this.eventfulUnits, "pet");
for (let i = 1; i <= 40; i += 1) {
const unit = `raid${i}`;
const petUnit = `raidpet${i}`;
this.petUnitByUnit[unit] = petUnit;
insert(this.eventfulUnits, unit);
insert(this.eventfulUnits, petUnit);
}
for (let i = 1; i <= 4; i += 1) {
const unit = `party${i}`;
const petUnit = `partypet${i}`;
this.petUnitByUnit[unit] = petUnit;
insert(this.eventfulUnits, unit);
insert(this.eventfulUnits, petUnit);
}
for (let i = 1; i <= 3; i += 1) {
const unit = `arena${i}`;
const petUnit = `arenapet${i}`;
this.petUnitByUnit[unit] = petUnit;
insert(this.eventfulUnits, unit);
insert(this.eventfulUnits, petUnit);
}
for (let i = 1; i <= 5; i += 1) {
insert(this.eventfulUnits, `boss{i}`);
}
insert(this.eventfulUnits, "target");
insert(this.eventfulUnits, "focus");
for (const [priority, unit] of ipairs(this.eventfulUnits)) {
this.unitAuraUnits[unit] = true;
this.unitPriority[unit] = priority;
}
}
private handleInitialize = () => {
this.module.RegisterEvent(
"ARENA_OPPONENT_UPDATE",
this.handleArenaOpponentUpdated
);
this.module.RegisterEvent(
"GROUP_ROSTER_UPDATE",
this.handleGroupRosterUpdated
);
this.module.RegisterEvent(
"INSTANCE_ENCOUNTER_ENGAGE_UNIT",
this.handleInstanceEncounterEngageUnit
);
this.module.RegisterEvent("PLAYER_ENTERING_WORLD", (event) =>
this.updateAllUnits()
);
this.module.RegisterEvent(
"PLAYER_FOCUS_CHANGED",
this.handlePlayerFocusChanged
);
this.module.RegisterEvent(
"PLAYER_TARGET_CHANGED",
this.handlePlayerTargetChanged
);
this.module.RegisterEvent(
"UNIT_NAME_UPDATE",
this.handleUnitNameUpdate
);
this.module.RegisterEvent("UNIT_PET", this.handleUnitPet);
this.module.RegisterEvent("UNIT_TARGET", this.handleUnitTarget);
};
private handleDisable = () => {
this.module.UnregisterEvent("ARENA_OPPONENT_UPDATE");
this.module.UnregisterEvent("GROUP_ROSTER_UPDATE");
this.module.UnregisterEvent("INSTANCE_ENCOUNTER_ENGAGE_UNIT");
this.module.UnregisterEvent("PLAYER_ENTERING_WORLD");
this.module.UnregisterEvent("PLAYER_FOCUS_CHANGED");
this.module.UnregisterEvent("PLAYER_TARGET_CHANGED");
this.module.UnregisterEvent("UNIT_NAME_UPDATE");
this.module.UnregisterEvent("UNIT_PET");
this.module.UnregisterEvent("UNIT_TARGET");
};
private handleArenaOpponentUpdated = (
event: string,
unitId: string,
eventType: string
) => {
if (eventType != "cleared" || this.guidByUnit[unitId]) {
this.tracer.debug(event, unitId, eventType);
this.updateUnitWithTarget(unitId);
}
};
private handleGroupRosterUpdated = (event: string) => {
this.tracer.debug(event);
this.updateAllUnits();
this.module.SendMessage("Ovale_GroupChanged");
};
private handleInstanceEncounterEngageUnit = (event: string) => {
this.tracer.debug(event);
for (let i = 1; i <= 5; i += 1) {
this.updateUnitWithTarget(`boss${i}`);
}
};
private handlePlayerFocusChanged = (event: string) => {
this.tracer.debug(event);
this.updateUnitWithTarget("focus");
};
private handlePlayerTargetChanged = (event: string, cause: string) => {
this.tracer.debug(event, cause);
this.updateUnit("target");
};
private handleUnitNameUpdate = (event: string, unitId: string) => {
this.tracer.debug(event, unitId);
this.updateUnit(unitId);
};
private handleUnitPet = (event: string, unit: string) => {
this.tracer.debug(event, unit);
const petUnit = this.getPetUnitByUnit(unit);
this.addChildUnit(unit, petUnit);
this.updateUnitWithTarget(petUnit);
const petGUID = this.guidByUnit[petUnit];
if (petGUID) {
const guid = this.guidByUnit[unit];
this.tracer.debug("Ovale_PetChanged", guid, unit, petGUID, petUnit);
this.mapOwnerGUIDToGUID(guid, petGUID);
this.module.SendMessage(
"Ovale_PetChanged",
guid,
unit,
petGUID,
petUnit
);
}
this.module.SendMessage("Ovale_GroupChanged");
};
private handleUnitTarget = (event: string, unit: string) => {
if (unit != "player" && !UnitIsUnit(unit, "player")) {
this.tracer.debug(event, unit);
const targetUnit = this.getTargetUnitByUnit(unit);
this.addChildUnit(unit, targetUnit);
this.updateUnit(targetUnit);
}
};
private updateAllUnits = () => {
for (const [, unitId] of ipairs(this.eventfulUnits)) {
this.updateUnitWithTarget(unitId);
}
};
getUnitGUID(unitId: string): string | undefined {
return this.guidByUnit[unitId] || UnitGUID(unitId);
}
getUnitByGUID(guid: string) {
if (guid && this.unitByGUID[guid]) {
return unpack(this.unitByGUID[guid]);
}
return [undefined];
}
getUnitName(unitId: string) {
if (unitId) {
return this.nameByUnit[unitId] || GetUnitName(unitId, true);
}
return undefined;
}
getUnitByName(name: string) {
if (name && this.unitByName[name]) {
return unpack(this.unitByName[name]);
}
return undefined;
}
getNameByGUID(guid: string) {
if (guid) {
return this.nameByGUID[guid];
}
return undefined;
}
getGUIDByName(name: string) {
if (name && this.guidByName[name]) {
return unpack(this.guidByName[name]);
}
return [];
}
getOwnerGUIDByGUID = (guid: string) => {
return this.ownerGUIDByGUID[guid];
};
getPetUnitByUnit = (unit: string) => {
return this.petUnitByUnit[unit] || `${unit}pet`;
};
getTargetUnitByUnit = (unit: string) => {
return (unit == "player" && "target") || `${unit}target`;
};
private addChildUnit = (unit: string, childUnit: string) => {
const t = this.childUnitByUnit[unit] || {};
if (!t[childUnit]) {
t[childUnit] = true;
this.childUnitByUnit[unit] = t;
}
};
private getUnitPriority = (unit: string) => {
const t = this.unitPriority;
let priority = t[unit];
if (!priority) {
priority = lualength(t) + 1;
t[unit] = priority;
}
return priority;
};
private compareUnit = (a: string, b: string) => {
return this.getUnitPriority(a) < this.getUnitPriority(b);
};
private mapOwnerGUIDToGUID = (ownerGUID: string, guid: string) => {
this.ownerGUIDByGUID[guid] = ownerGUID;
if (ownerGUID == this.ovale.playerGUID) {
this.petGUID[guid] = true;
}
};
private mapNameToUnit = (name: string, unit: string) => {
this.nameByUnit[unit] = name;
const t = this.unitByName[name] || {};
binaryInsertUnique(t, unit, this.compareUnit);
this.unitByName[name] = t;
};
private unmapNameToUnit = (name: string, unit: string) => {
delete this.nameByUnit[unit];
const t = this.unitByName[name] || {};
if (t) {
binaryRemove(t, unit, this.compareUnit);
if (lualength(t) == 0) {
delete this.unitByName[name];
}
}
};
private mapNameToGUID = (name: string, guid: string) => {
this.nameByGUID[guid] = name;
const t = this.guidByName[name] || {};
binaryInsertUnique(t, guid);
this.guidByName[name] = t;
};
private unmapNameToGUID = (name: string, guid: string) => {
delete this.nameByGUID[guid];
const t = this.guidByName[name] || {};
if (t) {
binaryRemove(t, guid);
if (lualength(t) == 0) {
delete this.guidByName[name];
}
}
};
private mapGUIDToUnit = (guid: string, unit: string) => {
this.guidByUnit[unit] = guid;
const t = this.unitByGUID[guid] || {};
binaryInsertUnique(t, unit, this.compareUnit);
this.unitByGUID[guid] = t;
// This GUID has a unit ID, so remove it from the cache.
this.unusedGUIDCache.remove(guid);
};
private unmapGUIDToUnit = (guid: string, unit: string) => {
delete this.guidByUnit[unit];
const t = this.unitByGUID[guid] || {};
if (t) {
binaryRemove(t, unit, this.compareUnit);
if (lualength(t) == 0) {
delete this.unitByGUID[unit];
/* This GUID has no more unit IDs associated with it, so
* put it the cache for eventual garbage collection.
*/
const evictedGUID = this.unusedGUIDCache.put(guid);
// Garbage-collect mappings for GUID evicted from cache.
if (evictedGUID) {
const name = this.nameByGUID[evictedGUID];
if (name) {
this.unmapNameToGUID(name, evictedGUID);
}
delete this.ownerGUIDByGUID[evictedGUID];
delete this.petGUID[evictedGUID];
this.module.SendMessage("Ovale_UnusedGUID", evictedGUID);
}
}
}
};
private unmapUnit = (unit: string) => {
const children = this.childUnitByUnit[unit];
if (children) {
for (const [childUnit] of pairs(children)) {
delete children[childUnit];
// recursively remove child units
this.unmapUnit(childUnit);
}
}
const guid = this.guidByUnit[unit];
if (guid) {
this.unmapGUIDToUnit(guid, unit);
}
const name = this.nameByUnit[unit];
if (name) {
this.unmapNameToUnit(name, unit);
}
};
private updateUnit = (
unit: string,
guid?: string | undefined,
changed?: LuaObj<string>
) => {
guid = guid || UnitGUID(unit);
const name = GetUnitName(unit, true);
if (guid && name) {
let updated = false;
const oldGUID = this.guidByUnit[unit];
const oldName = this.nameByUnit[unit];
if (guid != oldGUID) {
if (oldGUID) {
this.unmapGUIDToUnit(oldGUID, unit);
}
this.tracer.debug(`'${unit}' is '${guid}'`);
this.mapGUIDToUnit(guid, unit);
updated = true;
this.ovale.refreshNeeded[guid] = true;
}
if (name != oldName) {
if (oldName) {
this.unmapNameToUnit(oldName, unit);
if (guid == oldGUID) {
// unit has same GUID, but the name changed
this.unmapNameToGUID(oldName, guid);
}
}
this.tracer.debug(`'${unit}' is '${name}'`);
this.mapNameToUnit(name, unit);
updated = true;
}
if (updated) {
const nameByGUID = this.nameByGUID[guid];
if (!nameByGUID) {
this.tracer.debug(`'${guid}' is '${name}'`);
this.mapNameToGUID(name, guid);
} else if (name != nameByGUID) {
this.tracer.debug(`'${guid}' changed names to '${name}'`);
this.mapNameToGUID(name, guid);
}
if (changed) {
changed[guid] = unit;
} else {
this.tracer.debug("Ovale_UnitChanged", unit, guid, name);
this.module.SendMessage(
"Ovale_UnitChanged",
unit,
guid,
name
);
}
}
} else {
// unit is gone
this.unmapUnit(unit);
}
};
private updateUnitWithTarget = (
unit: string,
guid?: string,
changed?: LuaObj<string>
) => {
this.updateUnit(unit, guid, changed);
const targetUnit = this.getTargetUnitByUnit(unit);
const targetGUID = this.getUnitGUID(targetUnit);
if (targetGUID) {
this.addChildUnit(unit, targetUnit);
this.updateUnit(targetUnit, targetGUID, changed);
}
};
} | the_stack |
"use strict";
import "jest-environment-puppeteer";
import Flash from "../helpers/flash";
import { IFlash, IMarket } from "../types/types";
import {
toDefaultView,
toReporting,
toInitialReporting
} from "../helpers/navigation-helper";
import {
createCategoricalMarket,
createScalarMarket,
createYesNoMarket
} from "../helpers/create-markets";
import { UnlockedAccounts } from "../constants/accounts";
import { waitNextBlock } from "../helpers/wait-new-block";
jest.setTimeout(30000);
let flash: IFlash = new Flash();
describe("Categorical Initial Report", () => {
beforeAll(async () => {
await toDefaultView();
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await toReporting();
const market: IMarket = await createCategoricalMarket(4);
await flash.setMarketEndTime(market.id);
await flash.pushDays(1); // put market in designated reporting state
await waitNextBlock();
await toInitialReporting(market.id);
});
it("report on outcome_1", async () => {
await expect(page).toClick("button", {
text: "outcome_1",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_2", async () => {
await expect(page).toClick("button", {
text: "outcome_2",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_3", async () => {
await expect(page).toClick("button", {
text: "outcome_3",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_4", async () => {
await expect(page).toClick("button", {
text: "outcome_4",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
});
describe("Categorical Open Report", () => {
beforeAll(async () => {
await toDefaultView();
await waitNextBlock(2);
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.CONTRACT_OWNER
);
await waitNextBlock(2);
const market: IMarket = await createCategoricalMarket(4);
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.SECONDARY_ACCOUNT
);
await toReporting();
await flash.setMarketEndTime(market.id);
await flash.pushDays(5); // put market in open reporting state
await waitNextBlock(2);
await toInitialReporting(market.id);
});
it("report on outcome_1", async () => {
await expect(page).toClick("button", {
text: "outcome_1",
timeout: 10000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_2", async () => {
await expect(page).toClick("button", {
text: "outcome_2",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_3", async () => {
await expect(page).toClick("button", {
text: "outcome_3",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on outcome_4", async () => {
await expect(page).toClick("button", {
text: "outcome_4",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit",
timeout: 1000
});
});
});
describe("YesNo Initial Report", () => {
beforeAll(async () => {
await toDefaultView();
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await toReporting();
const market: IMarket = await createYesNoMarket();
await flash.setMarketEndTime(market.id);
await flash.pushDays(1); // put market in designated reporting state
await waitNextBlock();
await toInitialReporting(market.id);
});
it("report on yes", async () => {
await expect(page).toClick("button", {
text: "Yes",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on No", async () => {
await expect(page).toClick("button", {
text: "No",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
});
describe("YesNo Open Report", () => {
beforeAll(async () => {
await toDefaultView();
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.CONTRACT_OWNER
);
await waitNextBlock(2);
const market: IMarket = await createYesNoMarket();
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.SECONDARY_ACCOUNT
);
await toReporting();
await flash.setMarketEndTime(market.id);
await flash.pushDays(5); // put market in open reporting state
await waitNextBlock(2);
await toInitialReporting(market.id);
});
it("report on yes", async () => {
await expect(page).toClick("button", {
text: "Yes",
timeout: 10000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on No", async () => {
await expect(page).toClick("button", {
text: "No",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
});
describe("Scalar Initial Report", () => {
beforeAll(async () => {
await toDefaultView();
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await toReporting();
const market: IMarket = await createScalarMarket();
await flash.setMarketEndTime(market.id);
await flash.pushDays(1); // put market in designated reporting state
await waitNextBlock();
await toInitialReporting(market.id);
});
it("report on 10", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "10", {
timeout: 10000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on 0", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "0");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on -10", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "-10");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on 5.01", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "5.01");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on -5.01", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "-5.01");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
});
describe("Scalar Open Report", () => {
beforeAll(async () => {
await toDefaultView();
});
afterAll(async () => {
flash.dispose();
});
beforeEach(async () => {
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.CONTRACT_OWNER
);
await waitNextBlock(2);
const market: IMarket = await createScalarMarket();
await page.evaluate(
account => window.integrationHelpers.updateAccountAddress(account),
UnlockedAccounts.SECONDARY_ACCOUNT
);
await toReporting();
await flash.setMarketEndTime(market.id);
await flash.pushDays(5); // put market in open reporting state
await waitNextBlock(2);
await toInitialReporting(market.id);
});
it("report on 10", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "10");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on 0", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "0");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on -10", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "-10");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on 5.01", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "5.01");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on -5.01", async () => {
await expect(page).toFill("#sr__input--outcome-scalar", "-5.01");
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
it("report on Invalid", async () => {
await expect(page).toClick("button", {
text: "Market is invalid",
timeout: 1000
});
await expect(page).toClick("button", {
text: "Review"
});
await expect(page).toClick("button", {
text: "Submit"
});
});
}); | the_stack |
module android.view{
import Log = android.util.Log;
import Pools = android.util.Pools;
import MotionEvent = android.view.MotionEvent;
import KeyEvent = android.view.KeyEvent;
/**
* Helper for tracking the velocity of touch events, for implementing
* flinging and other such gestures.
*
* Use {@link #obtain} to retrieve a new instance of the class when you are going
* to begin tracking. Put the motion events you receive into it with
* {@link #addMovement(MotionEvent)}. When you want to determine the velocity call
* {@link #computeCurrentVelocity(int)} and then call {@link #getXVelocity(int)}
* and {@link #getYVelocity(int)} to retrieve the velocity for each pointer id.
*/
export class VelocityTracker{
private static TAG = "VelocityTracker";
private static DEBUG = Log.VelocityTracker_DBG;
private static localLOGV = VelocityTracker.DEBUG;
private static NUM_PAST = 10;
private static MAX_AGE_MILLISECONDS = 200;
private static POINTER_POOL_CAPACITY = 20;
private static sPool = new Pools.SynchronizedPool<VelocityTracker>(2);
private static sRecycledPointerListHead:Pointer;
private static sRecycledPointerCount = 0;
private mPointerListHead:Pointer;
private mLastTouchIndex = 0;
private mGeneration = 0;
private mNext:VelocityTracker;
/**
* Retrieve a new VelocityTracker object to watch the velocity of a
* motion. Be sure to call {@link #recycle} when done. You should
* generally only maintain an active object while tracking a movement,
* so that the VelocityTracker can be re-used elsewhere.
*
* @return Returns a new VelocityTracker.
*/
static obtain():VelocityTracker {
let instance = VelocityTracker.sPool.acquire();
return (instance != null) ? instance : new VelocityTracker();
}
/**
* Return a VelocityTracker object back to be re-used by others. You must
* not touch the object after calling this function.
*/
recycle() {
this.clear();
VelocityTracker.sPool.release(this);
}
setNextPoolable(element:VelocityTracker) {
this.mNext = element;
}
getNextPoolable():VelocityTracker {
return this.mNext;
}
constructor(){
this.clear();
}
/**
* Reset the velocity tracker back to its initial state.
*/
clear() {
VelocityTracker.releasePointerList(this.mPointerListHead);
this.mPointerListHead = null;
this.mLastTouchIndex = 0;
}
/**
* Add a user's movement to the tracker. You should call this for the
* initial {@link MotionEvent#ACTION_DOWN}, the following
* {@link MotionEvent#ACTION_MOVE} events that you receive, and the
* final {@link MotionEvent#ACTION_UP}. You can, however, call this
* for whichever events you desire.
*
* @param ev The MotionEvent you received and would like to track.
*/
addMovement(ev:MotionEvent) {
let historySize = ev.getHistorySize();
const pointerCount = ev.getPointerCount();
const lastTouchIndex = this.mLastTouchIndex;
const nextTouchIndex = (lastTouchIndex + 1) % VelocityTracker.NUM_PAST;
const finalTouchIndex = (nextTouchIndex + historySize) % VelocityTracker.NUM_PAST;
const generation = this.mGeneration++;
this.mLastTouchIndex = finalTouchIndex;
// Update pointer data.
let previousPointer:Pointer = null;
for (let i = 0; i < pointerCount; i++){
const pointerId = ev.getPointerId(i);
// Find the pointer data for this pointer id.
// This loop is optimized for the common case where pointer ids in the event
// are in sorted order. However, we check for this case explicitly and
// perform a full linear scan from the start if needed.
let nextPointer:Pointer;
if (previousPointer == null || pointerId < previousPointer.id) {
previousPointer = null;
nextPointer = this.mPointerListHead;
} else {
nextPointer = previousPointer.next;
}
let pointer:Pointer;
for (;;) {
if (nextPointer != null) {
const nextPointerId = nextPointer.id;
if (nextPointerId == pointerId) {
pointer = nextPointer;
break;
}
if (nextPointerId < pointerId) {
nextPointer = nextPointer.next;
continue;
}
}
// Pointer went down. Add it to the list.
// Write a sentinel at the end of the pastTime trace so we will be able to
// tell when the trace started.
pointer = VelocityTracker.obtainPointer();
pointer.id = pointerId;
pointer.pastTime[lastTouchIndex] = Number.MIN_VALUE;
pointer.next = nextPointer;
if (previousPointer == null) {
this.mPointerListHead = pointer;
} else {
previousPointer.next = pointer;
}
break;
}
pointer.generation = generation;
previousPointer = pointer;
const pastX = pointer.pastX;
const pastY = pointer.pastY;
const pastTime = pointer.pastTime;
historySize = ev.getHistorySize(pointerId);
for (let j = 0; j < historySize; j++) {
const touchIndex = (nextTouchIndex + j) % VelocityTracker.NUM_PAST;
pastX[touchIndex] = ev.getHistoricalX(i, j);
pastY[touchIndex] = ev.getHistoricalY(i, j);
pastTime[touchIndex] = ev.getHistoricalEventTime(i, j);
}
pastX[finalTouchIndex] = ev.getX(i);
pastY[finalTouchIndex] = ev.getY(i);
pastTime[finalTouchIndex] = ev.getEventTime();
}
// Find removed pointers.
previousPointer = null;
for (let pointer = this.mPointerListHead; pointer != null; ) {
const nextPointer = pointer.next;
if (pointer.generation != generation) {
// Pointer went up. Remove it from the list.
if (previousPointer == null) {
this.mPointerListHead = nextPointer;
} else {
previousPointer.next = nextPointer;
}
VelocityTracker.releasePointer(pointer);
} else {
previousPointer = pointer;
}
pointer = nextPointer;
}
}
/**
* Compute the current velocity based on the points that have been
* collected. Only call this when you actually want to retrieve velocity
* information, as it is relatively expensive. You can then retrieve
* the velocity with {@link #getXVelocity()} and
* {@link #getYVelocity()}.
*
* @param units The units you would like the velocity in. A value of 1
* provides pixels per millisecond, 1000 provides pixels per second, etc.
* @param maxVelocity The maximum velocity that can be computed by this method.
* This value must be declared in the same unit as the units parameter. This value
* must be positive.
*/
computeCurrentVelocity(units:number, maxVelocity=Number.MAX_SAFE_INTEGER) {
const lastTouchIndex = this.mLastTouchIndex;
for (let pointer = this.mPointerListHead; pointer != null; pointer = pointer.next) {
const pastTime = pointer.pastTime;
// Search backwards in time for oldest acceptable time.
// Stop at the beginning of the trace as indicated by the sentinel time Long.MIN_VALUE.
let oldestTouchIndex = lastTouchIndex;
let numTouches = 1;
const minTime = pastTime[lastTouchIndex] - VelocityTracker.MAX_AGE_MILLISECONDS;
while (numTouches < VelocityTracker.NUM_PAST) {
const nextOldestTouchIndex = (oldestTouchIndex + VelocityTracker.NUM_PAST - 1) % VelocityTracker.NUM_PAST;
const nextOldestTime = pastTime[nextOldestTouchIndex];
if (nextOldestTime < minTime) { // also handles end of trace sentinel
break;
}
oldestTouchIndex = nextOldestTouchIndex;
numTouches += 1;
}
// If we have a lot of samples, skip the last received sample since it is
// probably pretty noisy compared to the sum of all of the traces already acquired.
if (numTouches > 3) {
numTouches -= 1;
}
// Kind-of stupid.
const pastX = pointer.pastX;
const pastY = pointer.pastY;
const oldestX = pastX[oldestTouchIndex];
const oldestY = pastY[oldestTouchIndex];
const oldestTime = pastTime[oldestTouchIndex];
let accumX = 0;
let accumY = 0;
for (let i = 1; i < numTouches; i++) {
const touchIndex = (oldestTouchIndex + i) % VelocityTracker.NUM_PAST;
const duration = (pastTime[touchIndex] - oldestTime);
if (duration == 0) continue;
let delta = pastX[touchIndex] - oldestX;
let velocity = (delta / duration) * units; // pixels/frame.
accumX = (accumX == 0) ? velocity : (accumX + velocity) * .5;
delta = pastY[touchIndex] - oldestY;
velocity = (delta / duration) * units; // pixels/frame.
accumY = (accumY == 0) ? velocity : (accumY + velocity) * .5;
}
if (accumX < -maxVelocity) {
accumX = - maxVelocity;
} else if (accumX > maxVelocity) {
accumX = maxVelocity;
}
if (accumY < -maxVelocity) {
accumY = - maxVelocity;
} else if (accumY > maxVelocity) {
accumY = maxVelocity;
}
pointer.xVelocity = accumX;
pointer.yVelocity = accumY;
if (VelocityTracker.localLOGV) {
Log.v(VelocityTracker.TAG, "Pointer " + pointer.id
+ ": Y velocity=" + accumX +" X velocity=" + accumY + " N=" + numTouches);
}
}
}
/**
* Retrieve the last computed X velocity. You must first call
* {@link #computeCurrentVelocity(int)} before calling this function.
*
* @param id Which pointer's velocity to return.
* @return The previously computed X velocity.
*/
getXVelocity(id=0):number {
let pointer = this.getPointer(id);
return pointer != null ? pointer.xVelocity : 0;
}
/**
* Retrieve the last computed Y velocity. You must first call
* {@link #computeCurrentVelocity(int)} before calling this function.
*
* @param id Which pointer's velocity to return.
* @return The previously computed Y velocity.
*/
getYVelocity(id=0):number {
let pointer = this.getPointer(id);
return pointer != null ? pointer.yVelocity : 0;
}
private getPointer(id:number):Pointer {
for (let pointer = this.mPointerListHead; pointer != null; pointer = pointer.next) {
if (pointer.id == id) {
return pointer;
}
}
return null;
}
private static obtainPointer():Pointer {
if (VelocityTracker.sRecycledPointerCount != 0) {
let element = VelocityTracker.sRecycledPointerListHead;
VelocityTracker.sRecycledPointerCount -= 1;
VelocityTracker.sRecycledPointerListHead = element.next;
element.next = null;
return element;
}
return new Pointer();
}
private static releasePointer(pointer:Pointer) {
if (VelocityTracker.sRecycledPointerCount < VelocityTracker.POINTER_POOL_CAPACITY) {
pointer.next = VelocityTracker.sRecycledPointerListHead;
VelocityTracker.sRecycledPointerCount += 1;
VelocityTracker.sRecycledPointerListHead = pointer;
}
}
private static releasePointerList(pointer:Pointer) {
if (pointer != null) {
let count = VelocityTracker.sRecycledPointerCount;
if (count >= VelocityTracker.POINTER_POOL_CAPACITY) {
return;
}
let tail = pointer;
for (;;) {
count += 1;
if (count >= VelocityTracker.POINTER_POOL_CAPACITY) {
break;
}
let next = tail.next;
if (next == null) {
break;
}
tail = next;
}
tail.next = VelocityTracker.sRecycledPointerListHead;
VelocityTracker.sRecycledPointerCount = count;
VelocityTracker.sRecycledPointerListHead = pointer;
}
}
}
class Pointer {
next:Pointer;
id=0;
xVelocity=0;
yVelocity=0;
pastX = androidui.util.ArrayCreator.newNumberArray((<any>VelocityTracker).NUM_PAST);
pastY = androidui.util.ArrayCreator.newNumberArray((<any>VelocityTracker).NUM_PAST);
pastTime = androidui.util.ArrayCreator.newNumberArray((<any>VelocityTracker).NUM_PAST);// uses Long.MIN_VALUE as a sentinel
generation = 0;
}
} | the_stack |
import TestCase from '../testcase';
let redoKey = 'ctrl+r';
describe('basic multiline tests', function() {
it('tests basic multiline insertion and movement', async function() {
let t = new TestCase(['']);
t.sendKeys('ione');
t.sendKey('esc');
t.sendKeys('otwo');
t.sendKey('esc');
t.expect(['one', 'two']);
// test j and k
t.sendKeys('kxjx');
t.expect(['on', 'to']);
// don't go off the edge!
t.sendKeys('kkkxjjjx');
t.expect(['o', 'o']);
await t.done();
});
it('tests that the final line never goes away', async function() {
let t = new TestCase(['unos', 'dos', 'tres', 'quatro']);
t.sendKeys('$jjjx');
t.expect(['unos', 'dos', 'tres', 'quatr']);
await t.done();
});
it('tests column -1 works', async function() {
let t = new TestCase(['unos', 'dos', 'tres', 'quatro']);
t.sendKeys('$A');
t.sendKey('down');
t.sendKey('down');
t.sendKey('down');
t.sendKey('backspace');
t.expect(['unos', 'dos', 'tres', 'quatr']);
await t.done();
});
it('tests o and O edge cases', async function() {
let t = new TestCase(['a', 's', 'd', 'f']);
t.sendKeys('Oo');
t.expect(['o', 'a', 's', 'd', 'f']);
t.sendKey('esc');
t.sendKeys('u');
t.expect(['a', 's', 'd', 'f']);
await t.done();
t = new TestCase(['a', 's', 'd', 'f']);
t.sendKeys('5joO');
t.expect(['a', 's', 'd', 'f', 'O']);
t.sendKey('esc');
t.sendKeys('u');
t.expect(['a', 's', 'd', 'f']);
await t.done();
t = new TestCase(['a', 's', 'd', 'f']);
t.sendKeys('oO');
t.expect(['a', 'O', 's', 'd', 'f']);
t.sendKey('esc');
t.sendKeys('u');
t.expect(['a', 's', 'd', 'f']);
await t.done();
t = new TestCase(['a', 's', 'd', 'f']);
t.sendKeys('5jOo');
t.expect(['a', 's', 'd', 'o', 'f']);
t.sendKey('esc');
t.sendKeys('u');
t.expect(['a', 's', 'd', 'f']);
await t.done();
});
it('tests o and O undo and redo', async function() {
let threeRows = [
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
] },
] },
];
let t = new TestCase(threeRows);
t.sendKeys('Oo');
t.expect([
'o',
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
'o',
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
await t.done();
t = new TestCase(threeRows);
t.sendKeys('oO');
t.expect([
{ text: 'top row', children: [
'O',
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
{ text: 'top row', children: [
'O',
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
await t.done();
t = new TestCase(threeRows);
t.sendKeys('jOo');
t.expect([
{ text: 'top row', children: [
'o',
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
{ text: 'top row', children: [
'o',
{ text: 'middle row', children : [
'bottom row',
] },
] },
]);
await t.done();
t = new TestCase(threeRows);
t.sendKeys('joO');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'O',
'bottom row',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'O',
'bottom row',
] },
] },
]);
await t.done();
t = new TestCase(threeRows);
t.sendKeys('2jOo');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'o',
'bottom row',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'o',
'bottom row',
] },
] },
]);
await t.done();
t = new TestCase(threeRows);
t.sendKeys('2joO');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'O',
] },
] },
]);
t.sendKey('esc');
t.sendKeys('u');
t.expect(threeRows);
t.sendKey(redoKey);
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'O',
] },
] },
]);
await t.done();
});
it('skips collapsed children', async function() {
let t = new TestCase([
{ text: 'a', collapsed: true, children: [
's', 'd',
] },
'f',
]);
t.sendKeys('oo');
t.expect([
{ text: 'a', collapsed: true, children: [
's', 'd',
] },
'o',
'f',
]);
await t.done();
});
it('tricky -1 col case', async function() {
let t = new TestCase([
'a row',
'another row',
'a third row',
]);
t.sendKeys('$jx');
t.expect([
'a row',
'another ro',
'a third row',
]);
t.sendKeys('d0x');
t.expect([
'a row',
'',
'a third row',
]);
// tricky -1 on empty row case
t.sendKeys('j$k');
t.sendKeys('iab');
t.expect([
'a row',
'ab',
'a third row',
]);
await t.done();
});
it('tests basic deletion', async function() {
let t = new TestCase([
'a row',
'another row',
'a third row',
]);
t.sendKeys('ddjdd');
t.expect([
'another row',
]);
t.sendKeys('ux');
t.expect([
'another row',
' third row',
]);
await t.done();
});
it('tests deletion moves cursor properly', async function() {
let t = new TestCase([
{ text: 'here', children: [
{ text: 'and', children: [
'there',
] },
] },
'down here',
]);
t.sendKeys('G');
t.expectCursor(4, 0);
t.sendKeys('dd');
t.expectCursor(3, 0);
await t.done();
t = new TestCase([
{ text: 'here', children: [
{ text: 'and', collapsed: true, children: [
'there',
] },
] },
'down here',
]);
t.sendKeys('G');
t.expectCursor(4, 0);
t.sendKeys('dd');
t.expectCursor(2, 0);
await t.done();
});
it('cursor moves correctly when last sibling is deleted', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('3jdd');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
] },
] },
'another row',
]);
t.sendKeys('x');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'ottom row',
] },
] },
'another row',
]);
t.sendKeys('2u');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
await t.done();
});
it('cursor moves correctly when first sibling is deleted', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('2jdd');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('x');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'ottomest row',
] },
] },
'another row',
]);
t.sendKeys('2u');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
await t.done();
});
it('creates a new row when last sibling is deleted', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('dd');
t.expect([ 'another row' ]);
// automatically creates a new row
t.sendKeys('dd');
t.expect([ '' ]);
t.sendKeys('u');
t.expect([ 'another row' ]);
// brings back everything!
t.sendKeys('u');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
await t.done();
});
it('handles deletion of everything', async function() {
let t = new TestCase([ 'row', 'row', 'row your boat' ]);
t.sendKeys('4dd');
t.expect(['']);
t.sendKey('u');
t.expect([ 'row', 'row', 'row your boat' ]);
await t.done();
});
it('basic change row works', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('cc');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([
{ text: 'a row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
// should paste properly
t.sendKeys('p');
t.expect([
{ text: 'a row', children: [
'top row',
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
await t.done();
});
it('basic recursive change row works', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
'another row',
]);
t.sendKeys('cr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([ 'a row', 'another row' ]);
t.sendKeys('u');
await t.done();
});
it('change recursive works on row with children', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
]);
t.sendKeys('cr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([ 'a row' ]);
t.sendKeys('u');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children : [
'bottom row',
'bottomest row',
] },
] },
]);
await t.done();
});
it('tests recursive change on children', async function() {
let t = new TestCase([
{ text: 'top row', children: [
'middle row',
'bottom row',
] },
]);
t.sendKeys('jcr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([
{ text: 'top row', children: [
'a row',
'bottom row',
] },
]);
t.sendKey('u');
t.sendKeys('jcr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([
{ text: 'top row', children: [
'middle row',
'a row',
] },
]);
await t.done();
});
it('tests cursor returns to where it was', async function() {
let t = new TestCase([
'top row',
'middle row',
'bottom row',
]);
t.sendKeys('dd');
t.sendKeys('jj');
t.sendKeys('ux');
t.expect([
'op row',
'middle row',
'bottom row',
]);
await t.done();
});
it('tests cursor returns to where it was after undo+redo+undo', async function() {
let t = new TestCase([
'top row',
'middle row',
'bottom row',
]);
t.sendKeys('dd');
t.sendKeys('jj');
t.sendKeys('u');
t.sendKey('ctrl+r');
t.sendKeys('ux');
t.expect([
'op row',
'middle row',
'bottom row',
]);
await t.done();
});
it('tests redo in tricky case removing last row', async function() {
let t = new TestCase([ 'a row' ]);
t.sendKeys('cr');
t.sendKeys('new row');
t.sendKey('esc');
t.expect([ 'new row' ]);
t.sendKeys('u');
t.sendKey('ctrl+r');
t.sendKeys('x');
t.expect([ 'new ro' ]);
t.sendKeys('uu');
t.expect([ 'a row' ]);
t.sendKey('ctrl+r');
t.expect([ 'new row' ]);
t.sendKey('ctrl+r');
t.expect([ 'new ro' ]);
await t.done();
});
it('tests new row creation works', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children: [
'bottom row',
] },
] },
]);
t.sendKeys('jjcr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children: [
'a row',
] },
] },
]);
await t.done();
});
it('tests changing too many rows works', async function() {
let t = new TestCase([
{ text: 'top row', children: [
{ text: 'middle row', children: [
'bottom row',
] },
] },
]);
t.sendKeys('jj2cr');
t.sendKeys('a row');
t.sendKey('esc');
t.expect([
{ text: 'top row', children: [
{ text: 'middle row', children: [
'a row',
] },
] },
]);
await t.done();
});
it('tests deleting too many rows works', async function() {
let t = new TestCase([
{ text: 'parent row', children: [
'child row 1',
'child row 2',
] },
]);
t.sendKeys('j3dd');
t.expect([ 'parent row' ]);
t.sendKeys('u');
t.expect([
{ text: 'parent row', children: [
'child row 1',
'child row 2',
] },
]);
await t.done();
});
it('tests undo on change', async function() {
let t = new TestCase([
{ text: 'parent row', children: [
'child row 1',
{ text: 'child row 2', children: [
'baby 1',
'baby 2',
'baby 3',
] },
] },
]);
t.sendKeys('2j2cr'); // despite the 2cr, deletes only one, but deletes all the children
t.sendKeys('deleted');
t.sendKey('esc');
t.expect([
{ text: 'parent row', children: [
'child row 1',
'deleted',
] },
]);
t.sendKeys('u');
t.expect([
{ text: 'parent row', children: [
'child row 1',
{ text: 'child row 2', children: [
'baby 1',
'baby 2',
'baby 3',
] },
] },
]);
await t.done();
});
it('tests redo in tricky case making sure redo re-creates the same row', async function() {
let t = new TestCase([ 'a row' ]);
t.sendKeys('cr');
t.sendKeys('new row');
t.sendKey('esc');
t.expect([ 'new row' ]);
t.sendKeys('u');
t.sendKey('ctrl+r');
t.sendKeys('x');
t.expect([ 'new ro' ]);
t.sendKeys('uu');
t.expect([ 'a row' ]);
// to demonstrate we're not relying on getId behavior
t.docStore.getId = (() => {
let id = 100;
return async function() {
id++;
return id;
};
})();
t.sendKey('ctrl+r');
t.expect([ 'new row' ]);
t.sendKey('ctrl+r');
t.expect([ 'new ro' ]);
await t.done();
});
it('tests redo in tricky case making sure redo paste re-creates the same row', async function() {
let t = new TestCase([ 'a row' ]);
t.sendKeys('yyp');
t.expect([
'a row',
'a row',
]);
t.sendKeys('u');
t.sendKey('ctrl+r');
t.sendKeys('x');
t.expect([
'a row',
' row',
]);
t.sendKeys('uu');
t.expect([ 'a row' ]);
// to demonstrate we're not relying on getId behavior
t.docStore.getId = (() => {
let id = 100;
return async function() {
id++;
return id;
};
})();
t.sendKey('ctrl+r');
t.expect([
'a row',
'a row',
]);
t.sendKey('ctrl+r');
t.expect([
'a row',
' row',
]);
await t.done();
});
it('tests deleting viewroot', async function() {
let t = new TestCase([
{ text: 'here', children: [
'there',
] },
]);
t.sendKeys('j');
t.sendKey('enter');
t.expectViewRoot(2);
t.sendKeys('dd');
t.expectViewRoot(1);
await t.done();
});
it('tests editing viewroot', async function() {
let t = new TestCase([
{ text: 'here', children: [
'there',
] },
]);
t.sendKeys('j');
t.sendKey('enter');
t.expectViewRoot(2);
t.sendKeys('dd');
t.expectViewRoot(1);
await t.done();
});
it('cannot do new line above at view root', async function() {
let t = new TestCase([
{ text: 'here', children: [
'there',
] },
]);
t.sendKeys('j');
t.sendKey('enter');
t.sendKeys('O');
t.expect([
{ text: 'here', children: [
'there',
] },
]);
await t.done();
});
}); | the_stack |
import {Component, OnInit, OnDestroy, ElementRef, ViewChild, Input, OnChanges} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {AssetGroupObservableService} from '../../../core/services/asset-group-observable.service';
import {AutorefreshService} from '../../services/autorefresh.service';
import {SelectComplianceDropdown} from '../../services/select-compliance-dropdown.service';
import {MultilineChartService} from '../../services/multilinechart.service';
import {environment} from './../../../../environments/environment';
import {IssueFilterService} from './../../services/issue-filter.service';
import * as _ from 'lodash';
import {UtilsService} from '../../../shared/services/utils.service';
import { DomainTypeObservableService } from '../../../core/services/domain-type-observable.service';
@Component({
selector: 'app-inventory-container',
templateUrl: './inventory-container.component.html',
styleUrls: ['./inventory-container.component.css'],
providers: [MultilineChartService, AutorefreshService, IssueFilterService],
// tslint:disable-next-line:use-host-property-decorator
host: {
'(window:resize)': 'onResize($event)'
}
})
export class InventoryContainerComponent implements OnInit, OnChanges, OnDestroy {
@ViewChild('widget') widgetContainer: ElementRef;
@Input() targetType: any;
widgetWidth: number;
widgetHeight: number;
selectedAssetGroup: string;
errorMessages;
durationParams: any;
autoRefresh: boolean;
complianceDropdowns: any = ['Applications'];
searchDropdownData: any = {};
selectedDD = '';
currentObj: any = {};
filterArr: any = [];
selectedComplianceDropdown: any = {
'Applications': ''
};
private error = false;
private dataLoaded = false;
graphData: any;
colorSet: any = [];
errorMessage: any;
showerror = false;
showloader = false;
showdata = false;
filterTypeOptions = [];
filterTypeLabels = [];
filterTagOptions = [];
filterTagLabels = [];
currentFilterType;
filters = [];
filtersObject = {};
routeTo = 'asset-list';
private complianceDropdownSubscription: Subscription;
private subscriptionToAssetGroup: Subscription;
private multilineChartSubscription: Subscription;
private applicationSubscription: Subscription;
private filterTypesSubscription: Subscription;
subscriptionDomain: Subscription;
selectedDomain: any;
private autorefreshInterval;
@Input() pageLevel: number;
constructor(
private utils: UtilsService,
private multilineChartService: MultilineChartService,
private assetGroupObservableService: AssetGroupObservableService,
private autorefreshService: AutorefreshService,
private selectComplianceDropdown: SelectComplianceDropdown,
private issueFilterService: IssueFilterService,
private domainObservableService: DomainTypeObservableService) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.selectedAssetGroup = assetGroupName;
});
this.subscriptionDomain = this.domainObservableService.getDomainType().subscribe(domain => {
this.selectedDomain = domain;
this.getApplications();
this.deleteFilters();
});
this.complianceDropdownSubscription = this.selectComplianceDropdown.getCompliance().subscribe(
filtersObject => {
this.filtersObject = filtersObject;
this.updateComponent();
});
}
ngOnChanges() {
this.updateComponent();
}
onResize() {
const element = document.getElementById('inv');
if (element) {
this.widgetWidth = parseInt((window.getComputedStyle(element, null).getPropertyValue('width')).split('px')[0], 10);
}
}
ngOnInit() {
this.durationParams = this.autorefreshService.getDuration();
this.durationParams = parseInt(this.durationParams, 10);
this.autoRefresh = this.autorefreshService.autoRefresh;
const afterLoad = this;
if (this.autoRefresh !== undefined) {
if ((this.autoRefresh === true ) || (this.autoRefresh.toString() === 'true')) {
this.autorefreshInterval = setInterval(function() {
afterLoad.getIssues();
}, this.durationParams);
}
}
this.getApplications();
setTimeout(() => {
this.widgetWidth = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('width'), 10);
this.widgetHeight = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('height'), 10);
this.getIssues();
}, 0);
}
updateComponent() {
this.showdata = false;
this.showloader = false;
this.error = false;
this.getIssues();
}
getIssues() {
if (this.multilineChartSubscription) {
this.multilineChartSubscription.unsubscribe();
}
const queryParameters = {
'ag': this.selectedAssetGroup,
'type': this.targetType,
'filter': this.filtersObject,
'domain': this.selectedDomain
};
this.colorSet = ['#645ec5', '#26ba9d', '#289cf7'];
if (queryParameters.type !== undefined) {
this.multilineChartSubscription = this.multilineChartService.getDataDiffNew(queryParameters).subscribe(
response => {
try {
if (response[0][0].values.length < 1) {
this.showerror = true;
this.showloader = true;
this.error = true;
this.errorMessage = 'noDataAvailable';
} else {
this.showerror = false;
this.showloader = true;
this.error = false;
this.graphData = response[0];
this.showdata = true;
}
} catch (error) {
this.errorMessage = 'jsError';
this.handleError(error);
}
},
error => {
this.handleError(error);
this.showerror = true;
this.showloader = true;
this.errorMessage = 'apiResponseError';
}
);
}
}
handleError(error) {
this.dataLoaded = false;
this.error = true;
}
getApplications(): void {
if (this.applicationSubscription) {
this.applicationSubscription.unsubscribe();
}
const queryParams = {
'filterId': 3
};
const issueFilterUrl = environment.issueFilter.url;
const issueFilterMethod = environment.issueFilter.method;
this.applicationSubscription = this.issueFilterService.getFilters(queryParams, issueFilterUrl, issueFilterMethod).subscribe(
(response) => {
this.filterTypeLabels = _.map(response[0].response, 'optionName');
this.filterTypeOptions = response[0].response;
});
}
changeFilterType(filterType) {
this.currentFilterType = filterType;
this.filterTypesSubscription = this.issueFilterService.getFilters({
'ag': this.selectedAssetGroup
},
(environment.base + this.utils.getParamsFromUrlSnippet(this.currentFilterType.optionURL).url),
'GET')
.subscribe((response) => {
this.filterTagOptions = response[0].response;
this.filterTagLabels = _.map(response[0].response, 'name');
});
}
changeFilterTag(filterTag) {
if (this.currentFilterType) {
this.utils.addOrReplaceElement(this.filters, {
typeName: this.currentFilterType.optionName,
typeValue: this.currentFilterType.optionValue,
tagName: filterTag.name,
tagValue: filterTag.id,
key: this.currentFilterType.optionName,
value: filterTag.name
}, (el) => {
return el.key === this.currentFilterType.optionName;
});
this.selectComplianceDropdown.updateCompliance(this.utils.arrayToObject(this.filters, 'typeValue', 'tagValue'));
this.currentFilterType = null;
}
this.utils.clickClearDropdown();
}
changedDropdown(val) {
let option = _.find(this.filterTypeOptions, {optionName: val.id});
if (option) {
this.changeFilterType(option);
} else {
option = _.find(this.filterTagOptions, {name: val.id});
this.changeFilterTag(option);
}
}
deleteFilters(event?) {
try {
if (!event) {
this.filters = [];
} else {
if (event.clearAll) {
this.filters = [];
} else {
this.filters.splice(event.index, 1);
}
this.selectComplianceDropdown.updateCompliance(this.utils.arrayToObject(this.filters, 'typeValue', 'tagValue'));
}
} catch (error) {
}
}
ngOnDestroy() {
try {
this.subscriptionToAssetGroup.unsubscribe();
this.complianceDropdownSubscription.unsubscribe();
if (this.multilineChartSubscription) {
this.multilineChartSubscription.unsubscribe();
}
if (this.applicationSubscription) {
this.applicationSubscription.unsubscribe();
}
this.subscriptionDomain.unsubscribe();
if (this.filterTypesSubscription) {
this.filterTypesSubscription.unsubscribe();
}
clearInterval(this.autorefreshInterval);
} catch (error) {
}
}
} | the_stack |
import React = require("react");
var ReactDOM = require('react-dom');
import csx = require('./base/csx');
import {BaseComponent} from "./ui";
import * as ui from "./ui";
import * as utils from "../common/utils";
import * as styles from "./styles/styles";
import * as state from "./state/state";
import * as commands from "./commands/commands";
import {connect} from "react-redux";
import {Icon} from "./components/icon";
import * as tabRegistry from "./tabs/v2/tabRegistry";
import {tabState,tabStateChanged} from "./tabs/v2/appTabsContainer";
import * as typestyle from "typestyle";
import {extend} from "./base/csx";
let {inputBlackStyleBase} = styles.Input;
const inputBlackClassName = typestyle.style(inputBlackStyleBase);
export let inputCodeStyle = {
fontFamily: 'monospace',
}
export let searchOptionsLabelStyle = {
color: 'grey',
fontSize: '1.5rem',
fontWeight: 'bold',
cursor:'pointer',
paddingLeft: '5px',
paddingRight: '5px',
}
let labelStyle = {
color: 'grey',
padding: '4px'
}
export interface Props {
// connected using redux
findQuery?: FindOptions;
selectedTabIndex?: number;
}
export interface State {
}
@connect((state: state.StoreState): Props => {
return {
findQuery: state.findOptions,
};
})
export class FindAndReplace extends BaseComponent<Props, State>{
componentDidMount() {
this.disposible.add(commands.findAndReplace.on(() => {
/** Find input might not be there if current tab doesn't support search */
if (!this.findInput()){
return;
}
// if not shown and the current tab is an editor we should load the selected text from the editor (if any)
if (!state.getState().findOptions.isShown) {
let codeEditor = tabState.getFocusedCodeEditorIfAny();
if (codeEditor){
const selectedString = codeEditor.getSelectionSearchString();
if (selectedString) {
state.setFindOptionsQuery(selectedString);
this.findInput().value = selectedString;
}
}
}
state.setFindOptionsIsShown(true);
this.findInput().select();
this.replaceInput() && this.replaceInput().select();
this.findInput().focus();
}));
this.disposible.add(commands.esc.on(() => {
state.setFindOptionsIsShown(false);
this.findInput() && this.findInput().focus();
}));
this.disposible.add(tabStateChanged.on(()=>{
this.forceUpdate();
}));
}
refs: {
[string: string]: any;
find: JSX.Element;
replace: JSX.Element;
regex: {refs:{input: JSX.Element}};
caseInsensitive: {refs:{input: JSX.Element}};
fullWord: {refs:{input: JSX.Element}};
}
findInput = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.find);
replaceInput = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.replace);
regexInput = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.regex.refs.input);
caseInsensitiveInput = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.caseInsensitive.refs.input);
fullWordInput = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.fullWord.refs.input);
replaceWith = () => this.replaceInput().value;
// searchLocation = (): HTMLInputElement=> ReactDOM.findDOMNode(this.refs.find);
render() {
let shownStyle = this.props.findQuery.isShown ? {} : { display: 'none' };
/** Detect advanced find needed or not */
let tab = tabState.getSelectedTab();
let searchSupport = tab && tabRegistry.getTabConfigByUrl(tab.url).searchSupport;
let advancedFind = searchSupport && searchSupport == tabRegistry.TabSearchSupport.Advanced;
/** For Find and Replace Multi ... completely bail out */
if (!tab || !searchSupport) {
return <noscript/>;
}
if (!advancedFind){
return (
<div style={csx.extend(csx.horizontal,shownStyle)}>
<div style={extend(csx.flex, csx.vertical)}>
<div style={extend(csx.horizontal, csx.center, styles.padded1)}>
<input tabIndex={1} ref="find"
placeholder="Find"
className={inputBlackClassName}
style={extend(inputCodeStyle, csx.flex)}
onKeyDown={this.findKeyDownHandler}
onChange={this.findChanged} defaultValue={this.props.findQuery.query}/>
</div>
</div>
</div>
);
}
return (
<div style={extend(csx.vertical,shownStyle)}>
<div style={extend(csx.horizontal,shownStyle)}>
<div style={extend(csx.flex, csx.vertical)}>
<div style={extend(csx.horizontal, csx.center, styles.padded1)}>
<input tabIndex={1} ref="find"
placeholder="Find"
className={inputBlackClassName}
style={csx.extend(inputCodeStyle, csx.flex)}
onKeyDown={this.findKeyDownHandler}
onChange={this.findChanged} defaultValue={this.props.findQuery.query}/>
</div>
<div style={extend(csx.horizontal, csx.center, styles.padded1)}>
<input tabIndex={2} ref="replace"
placeholder="Replace"
className={inputBlackClassName}
style={csx.extend(inputCodeStyle, csx.flex)}
onKeyDown={this.replaceKeyDownHandler} />
</div>
</div>
<div style={csx.centerCenter}>
<div style={csx.extend(csx.horizontal, csx.aroundJustified, styles.padded1)}>
<label style={extend(csx.horizontal,csx.center)}>
<ui.Toggle
tabIndex={3}
ref="regex"
onChange={this.handleRegexChange}/>
<span style={searchOptionsLabelStyle as any}>
.*
</span>
</label>
<label style={extend(csx.horizontal,csx.center)}>
<ui.Toggle
tabIndex={4}
ref="caseInsensitive"
onChange={this.handleCaseSensitiveChange}/>
<span style={searchOptionsLabelStyle as any}>
Aa
</span>
</label>
<label style={extend(csx.horizontal,csx.center)}>
<ui.Toggle
tabIndex={5}
ref="fullWord"
onKeyDown={this.fullWordKeyDownHandler}
onChange={this.handleFullWordChange}/>
<span style={searchOptionsLabelStyle as any}>
<Icon name="text-width"/>
</span>
</label>
</div>
</div>
</div>
<div style={styles.Tip.root}>
<span style={styles.Tip.keyboardShortCutStyle}>Esc</span> to exit
{' '}<span style={styles.Tip.keyboardShortCutStyle}>Enter</span> to find/replace next
{' '}<span style={styles.Tip.keyboardShortCutStyle}>Shift + Enter</span> to find/replace previous
{' '}<span style={styles.Tip.keyboardShortCutStyle}>{commands.modName} + Enter</span> to replace all
</div>
</div>
);
}
/** Tab key is only called on key down :) */
findKeyDownHandler = (e:React.SyntheticEvent<any>) => {
let {tab,shift,enter,mod} = ui.getKeyStates(e);
if (shift && tab) {
this.fullWordInput() && this.fullWordInput().focus();
e.preventDefault();
return;
}
if (!state.getState().findOptions.query){
return;
}
if (mod && enter && !shift) { // Because `shift` is used by jump tab mode
commands.replaceAll.emit({newText:this.replaceWith()});
return;
}
if (shift && enter) {
commands.findPrevious.emit({});
return;
}
if (enter) {
commands.findNext.emit({});
return;
}
};
replaceKeyDownHandler = (e:React.SyntheticEvent<any>) => {
let {tab,shift,enter,mod} = ui.getKeyStates(e);
if (!state.getState().findOptions.query){
return;
}
if (mod && enter) {
commands.replaceAll.emit({newText:this.replaceWith()});
return;
}
// The cursor.replace function in code mirror focuses the editor *with a delay* :-/
let focusBackOnReplaceInput = () => setTimeout(()=>this.replaceInput().focus(),50);
if (shift && enter) {
commands.replacePrevious.emit({newText:this.replaceWith()});
focusBackOnReplaceInput();
return;
}
if (enter) {
commands.replaceNext.emit({newText:this.replaceWith()});
focusBackOnReplaceInput();
return;
}
};
fullWordKeyDownHandler = (e:React.SyntheticEvent<any>) => {
let {tab,shift,enter} = ui.getKeyStates(e);
if (tab && !shift) {
this.findInput().focus();
e.preventDefault();
return;
}
};
handleSearchKeys(e: React.SyntheticEvent<any>) {
}
findChanged = utils.debounce(() => {
let val = this.findInput().value;
state.setFindOptionsQuery(val)
},200);
handleRegexChange = (e) => {
let val: boolean = e.target.checked;
state.setFindOptionsIsRegex(val);
}
handleCaseSensitiveChange = (e) => {
let val: boolean = e.target.checked;
state.setFindOptionsIsCaseSensitive(val);
}
handleFullWordChange = (e) => {
let val: boolean = e.target.checked;
state.setFindOptionsIsFullWord(val);
}
componentWillUpdate(nextProps: Props, nextState: State) {
if (nextProps.findQuery.isShown !== this.props.findQuery.isShown) {
tabState.debouncedResize();
}
}
} | the_stack |
import Token from '../src/models/Token'
import { BigNumber, Wallet, constants, providers } from 'ethers'
import {
Chain,
Hop
} from '../src/index'
import { formatUnits, parseUnits } from 'ethers/lib/utils'
import { privateKey } from './config'
import * as addresses from '@hop-protocol/core/addresses'
// @ts-ignore
import pkg from '../package.json'
describe('sdk setup', () => {
const hop = new Hop('kovan')
const signer = new Wallet(privateKey)
it('should return version', () => {
expect(hop.version).toBe(pkg.version)
})
})
describe.skip('hop bridge token transfers', () => {
const hop = new Hop('kovan')
const signer = new Wallet(privateKey)
it(
'send token from L1 -> L2',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Ethereum, Chain.Optimism)
console.log('tx hash:', tx?.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'send token from L2 -> L2',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Optimism, Chain.Gnosis)
console.log('tx hash:', tx?.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'send token from L2 -> L1',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Gnosis, Chain.Ethereum)
console.log('tx hash:', tx?.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
})
describe.skip('tx watcher', () => {
const hop = new Hop('mainnet')
const signer = new Wallet(privateKey)
it(
'receive events on token transfer from L1 -> L2 Polygon (no swap)',
async () => {
const txHash =
'0xb92c61e0a1e674eb4c9a52cc692c92709c8a4e4cb66fb22eb7cd9a958cf33a70'
console.log('tx hash:', txHash)
await new Promise(resolve => {
let sourceReceipt: any = null
let destinationReceipt: any = null
hop
.watch(txHash, Token.USDC, Chain.Ethereum, Chain.Polygon)
.on('receipt', (data: any) => {
const { receipt, chain } = data
if (chain.equals(Chain.Ethereum)) {
sourceReceipt = receipt
console.log('got source transaction receipt')
}
if (chain.equals(Chain.Polygon)) {
destinationReceipt = receipt
console.log('got destination transaction receipt')
}
if (sourceReceipt && destinationReceipt) {
resolve(null)
}
})
.on('error', (err: Error) => {
console.error(err)
// expect(err).toBeFalsy()
})
})
},
120 * 1000
)
it(
'receive events on token transfer from L1 -> L2 Gnosis (swap)',
async () => {
/*
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Ethereum, Chain.Gnosis)
*/
const txHash =
'0xda9be66e99f9b668de873aeb7b82dc0d7870188862cbf86c52a00d7f61be0be4'
console.log('tx hash:', txHash)
console.log('waiting for receipts')
await new Promise(resolve => {
let sourceReceipt: any = null
let destinationReceipt: any = null
hop
.watch(txHash, Token.USDC, Chain.Ethereum, Chain.Gnosis)
.on('receipt', (data: any) => {
const { receipt, chain } = data
if (chain.equals(Chain.Ethereum)) {
sourceReceipt = receipt
console.log('got source transaction receipt')
}
if (chain.equals(Chain.Gnosis)) {
destinationReceipt = receipt
console.log('got destination transaction receipt')
}
if (sourceReceipt && destinationReceipt) {
resolve(null)
}
})
.on('error', (err: Error) => {
console.error(err)
})
})
},
120 * 1000
)
it.skip(
'receive events on token transfer from L2 -> L2',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Gnosis, Chain.Optimism)
const txHash = tx?.hash
console.log('tx hash:', txHash)
console.log('waiting for receipts')
await new Promise(resolve => {
let sourceReceipt: any = null
let destinationReceipt: any = null
hop
.watch(txHash, Token.USDC, Chain.Gnosis, Chain.Optimism)
.on('receipt', (data: any) => {
const { receipt, chain } = data
if (chain.equals(Chain.Gnosis)) {
sourceReceipt = receipt
console.log(
'got source transaction receipt:',
receipt.transactionHash
)
}
if (chain.equals(Chain.Optimism)) {
destinationReceipt = receipt
console.log(
'got destination transaction receipt:',
receipt.transactionHash
)
}
if (sourceReceipt && destinationReceipt) {
resolve(null)
}
})
})
expect(txHash).toBeTruthy()
},
120 * 1000
)
it.skip(
'(mainnet) receive events on token transfer from L2 Gnosis -> L2 Polygon',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const txHash =
'0x439ae4839621e13317933e1fa4ca9adab359074090e00e3db1105a982cf9a6ac'
await new Promise(resolve => {
let sourceReceipt: any = null
let destinationReceipt: any = null
hop
.watch(txHash, Token.USDC, Chain.Gnosis, Chain.Polygon, false, {
destinationHeadBlockNumber: 14779300 // estimate
})
.on('receipt', (data: any) => {
const { receipt, chain } = data
if (chain.equals(Chain.Gnosis)) {
sourceReceipt = receipt
console.log(
'got source transaction receipt:',
receipt.transactionHash
)
expect(sourceReceipt.transactionHash).toBe(
'0x439ae4839621e13317933e1fa4ca9adab359074090e00e3db1105a982cf9a6ac'
)
}
if (chain.equals(Chain.Polygon)) {
destinationReceipt = receipt
console.log(
'got destination transaction receipt:',
receipt.transactionHash
)
expect(destinationReceipt.transactionHash).toBe(
'0xdcdf05b4171610bab3b69465062e29fab4d6ea3a70ea761336d1fa566dede4a7'
)
}
if (sourceReceipt && destinationReceipt) {
resolve(null)
}
})
})
expect(txHash).toBeTruthy()
},
300 * 1000
)
it(
'receive events on token transfer from L2 -> L1',
async () => {
const tokenAmount = parseUnits('0.1', 18)
const tx = await hop
.connect(signer)
.bridge(Token.USDC)
.send(tokenAmount, Chain.Ethereum, Chain.Gnosis)
console.log('tx hash:', tx?.hash)
console.log('waiting for receipts')
await new Promise(resolve => {
let sourceReceipt: any = null
let destinationReceipt: any = null
hop
.watch(tx.hash, Token.USDC, Chain.Ethereum, Chain.Gnosis)
.on('receipt', (data: any) => {
const { receipt, chain } = data
if (chain.equals(Chain.Ethereum)) {
sourceReceipt = receipt
console.log('got source transaction receipt')
}
if (chain.equals(Chain.Gnosis)) {
destinationReceipt = receipt
console.log('got destination transaction receipt')
}
if (sourceReceipt && destinationReceipt) {
resolve(null)
}
})
})
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'getAmountOut - L2 -> L2',
async () => {
const tokenAmount = parseUnits('1', 18)
const amountOut = await hop
.connect(signer)
.bridge(Token.USDC)
.getAmountOut(tokenAmount, Chain.Gnosis, Chain.Optimism)
expect(Number(formatUnits(amountOut.toString(), 18))).toBeGreaterThan(0)
},
10 * 1000
)
})
describe.skip('canonical bridge transfers', () => {
const hop = new Hop('kovan')
const signer = new Wallet(privateKey)
it(
'deposit token from L1 -> Gnosis L2 canonical bridge',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Gnosis)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).deposit(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'withdraw token from Gnosis L2 canonical bridge -> L1',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Gnosis)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).withdraw(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'deposit token from L1 -> Optimism L2 canonical bridge',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Optimism)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).deposit(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'withdraw token from Optimism L2 canonical bridge -> L1',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Optimism)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).withdraw(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'deposit token from L1 -> Arbitrum L2 canonical bridge',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Arbitrum)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).deposit(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
it(
'withdraw token from Arbitrum L2 canonical bridge -> L1',
async () => {
const bridge = hop.canonicalBridge(Token.USDC, Chain.Arbitrum)
const tokenAmount = parseUnits('0.1', 18)
const tx = await bridge.connect(signer).withdraw(tokenAmount)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
},
120 * 1000
)
})
describe.skip('liqudity provider', () => {
const hop = new Hop('kovan')
const signer = new Wallet(privateKey)
it('should add liqudity on Gnosis', async () => {
const bridge = hop.bridge(Token.USDC)
const tokenAmount = parseUnits('0.1', 18)
const amount0Desired = tokenAmount
const amount1Desired = tokenAmount
const tx = await bridge
.connect(signer)
.addLiquidity(amount0Desired, amount1Desired, Chain.Gnosis)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
})
it('should remove liqudity on Gnosis', async () => {
const bridge = hop.bridge(Token.USDC)
const liqudityTokenAmount = parseUnits('0.1', 18)
const tx = await bridge
.connect(signer)
.removeLiquidity(liqudityTokenAmount, Chain.Gnosis)
console.log('tx:', tx.hash)
expect(tx.hash).toBeTruthy()
})
})
describe('custom addresses', () => {
it('should set custom addresses', () => {
const address = '0x1111111111111111111111111111111111111111'
const newAddresses = Object.assign({}, addresses)
newAddresses.mainnet.bridges.USDC.gnosis.l2CanonicalToken = address
const sdk = new Hop('mainnet')
sdk.setConfigAddresses(newAddresses.mainnet)
expect(sdk.getL2CanonicalTokenAddress('USDC', 'gnosis')).toBe(address)
const bridge = sdk.bridge('USDC')
expect(bridge.getL2CanonicalTokenAddress('USDC', 'gnosis')).toBe(address)
})
})
describe('approve addresses', () => {
const sdk = new Hop('mainnet')
const bridge = sdk.bridge('USDC')
it('get send approval address (L1 -> L2)', () => {
const approvalAddress = bridge.getSendApprovalAddress(
Chain.Ethereum
)
const expectedAddress = addresses.mainnet.bridges.USDC.ethereum.l1Bridge
expect(approvalAddress).toBe(expectedAddress)
})
it('get send approval address (L2 -> L2)', () => {
const approvalAddress = bridge.getSendApprovalAddress(
Chain.Polygon
)
const expectedAddress = addresses.mainnet.bridges.USDC.polygon.l2AmmWrapper
expect(approvalAddress).toBe(expectedAddress)
})
})
describe('custom chain providers', () => {
it('should set custom chain provider', () => {
const sdk = new Hop('mainnet')
const bridge = sdk.bridge('USDC')
let provider = bridge.getChainProvider('polygon')
const currentUrl = 'https://polygon-rpc.com'
const newUrl = 'https://polygon-rpc2.com'
expect((provider as any).connection.url).toBe(currentUrl)
const newProvider = new providers.StaticJsonRpcProvider(newUrl)
sdk.setChainProvider('polygon', newProvider)
provider = bridge.getChainProvider('polygon')
expect((provider as any).connection.url).toBe(newUrl)
})
it('should set multiple custom chain provider', () => {
const sdk = new Hop('mainnet')
const bridge = sdk.bridge('USDC')
let polygonProvider = bridge.getChainProvider('polygon')
let gnosisProvider = bridge.getChainProvider('gnosis')
const currentPolygonUrl = 'https://polygon-rpc.com'
const currentGnosisUrl = 'https://rpc.gnosischain.com/'
const newPolygonUrl = 'https://polygon-rpc2.com'
const newGnosisUrl = 'https://rpc.gnosischain2.com'
expect((polygonProvider as any).connection.url).toBe(currentPolygonUrl)
expect((gnosisProvider as any).connection.url).toBe(currentGnosisUrl)
sdk.setChainProviders({
polygon: new providers.StaticJsonRpcProvider(newPolygonUrl),
gnosis: new providers.StaticJsonRpcProvider(newGnosisUrl)
})
polygonProvider = bridge.getChainProvider('polygon')
gnosisProvider = bridge.getChainProvider('gnosis')
expect((polygonProvider as any).connection.url).toBe(newPolygonUrl)
expect((gnosisProvider as any).connection.url).toBe(newGnosisUrl)
})
})
describe.skip('getSendData', () => {
it('available liquidity', async () => {
const sdk = new Hop('mainnet')
const bridge = sdk.bridge('USDC')
const availableLiquidityBn = await bridge.getFrontendAvailableLiquidity(
Chain.Arbitrum,
Chain.Ethereum
)
const sendData = await bridge.getSendData(
'1000000000',
Chain.Arbitrum,
Chain.Ethereum
)
const requiredLiquidity = Number(
formatUnits(sendData.requiredLiquidity.toString(), 6)
)
const availableLiquidity = Number(
formatUnits(availableLiquidityBn.toString(), 6)
)
expect(availableLiquidity).toBeGreaterThan(0)
expect(requiredLiquidity).toBeGreaterThan(0)
expect(availableLiquidity).toBeGreaterThan(requiredLiquidity)
})
})
describe('getSupportedAssets', () => {
it('should return list of supported assets per chain', () => {
const hop = new Hop('mainnet')
const assets = hop.getSupportedAssets()
expect(assets).toBeTruthy()
})
})
describe.only('get call data only (no signer connected)', () => {
it('should return call data for L1->L2 ETH send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('ETH')
const amount = parseUnits('0.01', 18)
const sourceChain = 'ethereum'
const destinationChain = 'gnosis'
const recipient = constants.AddressZero
const txObj = await bridge.populateSendTx(amount, sourceChain, destinationChain, {
recipient
})
expect(txObj.value).toBeTruthy()
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for L1->L2 USDC send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('150', 6)
const sourceChain = 'ethereum'
const destinationChain = 'gnosis'
const recipient = constants.AddressZero
const txObj = await bridge.populateSendTx(amount, sourceChain, destinationChain, {
recipient
})
expect(txObj.value).toBeFalsy()
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for L2->L2 USDC send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('1', 6)
const sourceChain = 'gnosis'
const destinationChain = 'polygon'
const recipient = constants.AddressZero
const txObj = await bridge.populateSendTx(amount, sourceChain, destinationChain, {
recipient
})
expect(txObj.value).toBeFalsy()
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for L2->L1 USDC send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('150', 6)
const sourceChain = 'gnosis'
const destinationChain = 'ethereum'
const recipient = constants.AddressZero
const txObj = await bridge.populateSendTx(amount, sourceChain, destinationChain, {
recipient
})
expect(txObj.value).toBeFalsy()
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for add liquidity call', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const sourceChain = 'gnosis'
const amount = parseUnits('1', 6)
const txObj = await bridge.populateSendApprovalTx(amount, sourceChain)
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for add liquidity call', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const chain = 'gnosis'
const amm = await bridge.getAmm(chain)
const amount0 = parseUnits('1', 6)
const amount1 = parseUnits('1', 6)
const minToMint = BigNumber.from(0)
const txObj = await amm.populateAddLiquidityTx(amount0, amount1, minToMint)
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
it('should return call data for remove liquidity call', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const chain = 'gnosis'
const amm = await bridge.getAmm(chain)
const lpTokenAmount = parseUnits('1', 18)
const amount0Min = BigNumber.from(0)
const amount1Min = BigNumber.from(0)
const txObj = await amm.populateRemoveLiquidityTx(lpTokenAmount, amount0Min, amount1Min)
expect(txObj.data).toBeTruthy()
expect(txObj.to).toBeTruthy()
}, 30 * 1000)
})
describe.skip('get estimated gas (no signer connected)', () => {
it('should return estimated gas for L1->L2 send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('1', 6)
const sourceChain = 'ethereum'
const destinationChain = 'gnosis'
const recipient = constants.AddressZero
const estimatedGas = await bridge.estimateSendGasLimit(amount, sourceChain, destinationChain, {
recipient
})
expect(estimatedGas.gt(0)).toBeTruthy()
})
it('should return estimated gas for L2->L2 send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('1', 6)
const sourceChain = 'gnosis'
const destinationChain = 'polygon'
const recipient = constants.AddressZero
const estimatedGas = await bridge.estimateSendGasLimit(amount, sourceChain, destinationChain, {
recipient
})
expect(estimatedGas.gt(0)).toBeTruthy()
})
it('should return estimated gas for L2->L1 send', async () => {
const hop = new Hop('mainnet')
const bridge = hop.bridge('USDC')
const amount = parseUnits('100', 6)
const sourceChain = 'gnosis'
const destinationChain = 'ethereum'
const recipient = constants.AddressZero
const estimatedGas = await bridge.estimateSendGasLimit(amount, sourceChain, destinationChain, {
recipient
})
expect(estimatedGas.gt(0)).toBeTruthy()
})
}) | the_stack |
(function ():void {
const parseDuration:IParseDuration = require("parse-duration");
enum NodeType {
Element = 1,
Attribute = 2,
Text = 3,
Comment = 8
}
interface IProcessingConfigurationItem {
tag?: string;
id?: string;
cssClass?: string;
pre: (element:HTMLElement) => void;
post: (element:HTMLElement) => void;
}
/**
* Type of object used to configure the behavior of tply for a given animation.
*/
interface IConfiguration {
types?: [{
name: string,
properties?: any,
styleClasses?: string,
style?: string
}];
processing?:IProcessingConfigurationItem[];
shouldScrollDown?:boolean;
insertedClass?:string;
}
interface IElementProcessorCallback extends Function {
(element:Node | void): void;
}
interface IElementProcessor {
(context:AnimationContext): void;
}
interface IVoidCallback {
():void;
}
/**
* This class is in charge of keeping track of the cancellation state of a given
* animation. Since some animations can be super long, there may arise a need to cancel
* one at some time or another.
*/
class Status {
private _isCancelled:boolean = false;
private _isFinished:boolean = false;
private cancellationListeners:Array<() => void> = [];
private finishedListeners:Array<() => void> = [];
public cancel(callback?:IVoidCallback):void {
if (typeof callback !== "undefined") {
this.registerCancellationListener(callback);
}
this._isCancelled = true;
}
public registerCancellationListener(listener:() => void):void {
this.cancellationListeners.push(listener);
}
public registerFinishedListener(listener:() => void):void {
this.finishedListeners.push(listener);
}
public onCancel():void {
this.cancellationListeners.forEach((listener:() => void):void => {
listener();
});
}
public onFinish():void {
this._isFinished = true;
this.finishedListeners.forEach((listener:() => void):void => {
listener();
});
}
public get isCancelled():boolean {
return this._isCancelled;
}
public get isFinished():boolean {
return this._isFinished;
}
}
class AnimationContext {
private _rootContext:AnimationContext;
private _status:Status;
private _config:IConfiguration;
private _rootFrom:Node;
private _from:Node;
private _rootTo:HTMLElement;
private _to:HTMLElement;
private _callback:IElementProcessorCallback;
private _extra:any;
private _insertedChars:Array<HTMLElement> = [];
private _cursor:HTMLElement;
constructor(status:Status,
config:IConfiguration,
rootFrom:Node,
from:Node,
rootTo:HTMLElement,
to:HTMLElement,
callback:IElementProcessorCallback,
insertedChars = [],
extra:any = null,
cursor:HTMLElement = null,
rootContext:AnimationContext = null) {
this._status = status;
this._config = config;
this._rootFrom = rootFrom;
this._from = from;
this._rootTo = rootTo;
this._to = to;
this._callback = callback;
this._insertedChars = insertedChars;
this._extra = extra;
this._cursor = cursor;
this._rootContext = rootContext;
}
public clone():AnimationContext {
return new AnimationContext(
this._status,
this._config,
this._rootFrom,
this._from,
this._rootTo,
this._to,
this._callback,
this._insertedChars,
this._extra,
this._cursor,
this._rootContext);
}
public withRootContext(context:AnimationContext):AnimationContext {
const clone = this.clone();
clone._rootContext = context;
context._rootContext = context;
return clone;
}
public withFrom(root:Node):AnimationContext {
const clone = this.clone();
clone._from = root;
return clone;
}
public withTo(node:HTMLElement):AnimationContext {
const clone = this.clone();
clone._to = node;
return clone;
}
public withCallback(callback:IElementProcessorCallback):AnimationContext {
const clone = this.clone();
clone._callback = callback;
return clone;
}
public withExtra(extra:any):AnimationContext {
const clone = this.clone();
clone._extra = extra;
return clone;
}
get status():Status {
return this._status;
}
get config():IConfiguration {
return this._config;
}
/**
* This is the node which we are currently cloning and animating
* into the destination. It is located somewhere within the template
* element.
* @returns {Node}
*/
get from():Node {
return this._from;
}
get fromAsElement():HTMLElement {
return <HTMLElement> this._from;
}
get fromAsCharacterData():CharacterData {
return <CharacterData> this._from;
}
/**
* This is the element INTO which we are cloning and animating
* an element.
* @returns {HTMLElement}
*/
get to():HTMLElement {
return this._to;
}
get callback():IElementProcessorCallback {
return this._callback;
}
get extra():any {
return this._extra;
}
get rootFrom():Node {
return this._rootFrom;
}
get rootTo():HTMLElement {
return this._rootTo;
}
public get insertedChars():Array<HTMLElement> {
return this._insertedChars;
}
public get cursor():HTMLElement {
return this._rootContext._cursor;
}
set cursor(value:HTMLElement) {
this._rootContext._cursor = value;
}
}
const innerText = function (element:HTMLElement):string {
return element.innerText || element.textContent;
};
const setInnerText = function (element:HTMLElement, text:string):void {
if (typeof element.innerText !== "undefined") {
element.innerText = text;
} else {
element.textContent = text;
}
};
const asynchronouslyProcessNodes = function (context:AnimationContext,
processFn:(item:Node, callback:() => void) => void,
callbackParam:Node = null):void {
let index = 0;
const processNextItem = function ():void {
if (index < context.from.childNodes.length) {
processFn(context.from.childNodes[index++], processNextItem);
} else {
context.callback(callbackParam);
}
};
processNextItem();
};
const stripWhitespace = function (text:string):string {
return text.replace(/\n/, "").replace(/\s\s+/g, " ");
};
const removeChildren = function (element:HTMLElement):void {
element.innerHTML = "";
};
/**
* Wraps a given function in another one, which is responsible for calling
* the original one if the original one needs to be executed.
* @param original - A function to wrap.
* @param wrapper - Function that should be called in place of the original one,
* has the same parameters as the original one, with an additional parameter at the
* end, which is the original function. Do with the original function as you wish -
* call or don't - up to you.
* @returns - Function with the same signature as the original one.
*/
let wrapFunction = function<T> (original:T, wrapper:Function):T {
return <T> <any> function ():void {
const argsArray = Array.prototype.slice.call(arguments);
argsArray.push(original);
wrapper.apply(this, argsArray);
};
};
let isDefined = function (object:any) {
return typeof object !== "undefined";
};
let ignoreCaseEquals = function (left:string, right:string):boolean {
return left.toLowerCase() === right.toLowerCase();
};
let matchElement = function (element:HTMLElement, processingItem:IProcessingConfigurationItem) {
if (isDefined(processingItem.tag)) {
if (!ignoreCaseEquals(element.tagName, processingItem.tag)) {
return false;
}
}
if (isDefined(processingItem.id)) {
if (element.id !== processingItem.id) {
return false;
}
}
if (isDefined(processingItem.cssClass)) {
if (!element.classList.contains(processingItem.cssClass)) {
return false;
}
}
return true;
};
/**
* Wraps a processor that does animation with some extra logic which enables us to
* pre- and post- process elements, style them, and give them extra attributes defined
* by the configuration. Additionally, stops the animation if it is cancelled.
* @param processFn
*/
let makeProcessor = function (processFn:IElementProcessor):IElementProcessor {
return function (context:AnimationContext):void {
if (context.status.isCancelled) {
context.status.onCancel();
// not calling the callback effectively
// stops the animation - this is deliberate.
return;
}
let callBackProxy = context.callback;
for (let i = 0; i < context.fromAsElement.attributes.length; i++) {
if (!Array.isArray(context.config.types)) {
break;
}
for (let j = 0; j < context.config.types.length; j++) {
if (context.from.attributes[i].name === "data-type") {
if (context.from.attributes[i].value === context.config.types[j].name) {
for (let propName in context.config.types[j].properties) {
if (context.config.types[j].properties.hasOwnProperty(propName)) {
context.fromAsElement.setAttribute(propName, context.config.types[j].properties[propName]);
}
}
if (typeof context.config.types[j].styleClasses !== "undefined") {
context.fromAsElement.classList.add(context.config.types[j].styleClasses);
}
context.fromAsElement.setAttribute(
"style",
context.fromAsElement.getAttribute("style") + ";" + context.config.types[j].style);
}
}
}
}
if (Array.isArray(context.config.processing)) {
for (let k = 0; k < context.config.processing.length; k++) {
if (matchElement(context.fromAsElement, context.config.processing[k])) {
if (typeof context.config.processing[k].pre === "function") {
context.config.processing[k].pre(context.fromAsElement);
}
if (typeof context.config.processing[k].post === "function") {
callBackProxy = wrapFunction<IElementProcessorCallback>(
callBackProxy,
function (element:HTMLElement, originalCallback:IElementProcessorCallback):void {
context.config.processing[k].post(element);
originalCallback(element);
});
}
}
}
}
processFn(context.withCallback(callBackProxy));
};
};
/**
* Appends a clone of an HTML Element to another one, conditionally removing
* all of its children.
* @param root - The element to which the clone will be appended.
* @param node - The element to clone and append.
* @param desiredTag - The desired tag that the clone should be (ie. 'div', 'a', 'span', etc.)
* @param deepCopy - If true, copy the children too, if false do not copy the children.
*/
const append = function (root:HTMLElement,
node:HTMLElement,
desiredTag:string = null,
deepCopy:boolean = false):HTMLElement {
let clone = <HTMLElement> node.cloneNode(true);
if (!deepCopy) {
clone.innerHTML = "";
}
if (desiredTag !== null) {
const clonedInnerHtml = clone.innerHTML;
clone = document.createElement(desiredTag);
clone.innerHTML = clonedInnerHtml;
for (let i = 0; i < node.attributes.length; i++) {
clone.setAttribute(node.attributes[i].name, node.attributes[i].value);
}
clone.className = node.className;
}
root.appendChild(clone);
return clone;
};
const scrollDown = function (config:IConfiguration):void {
if (config.shouldScrollDown) {
window.scroll(0, document.documentElement.offsetHeight);
}
};
const mapFirstCharToInterval = function (context:AnimationContext, text:string):number {
const referenceTypeNode:HTMLElement = context.extra || context.from;
const defaultCharInterval = "50ms";
const defaultPeriodInterval = "500ms";
const defaultCommaInterval = "300ms";
const defaultEndInterval = "0ms";
const defaultWordInterval = "0ms";
let dataCharInterval = null;
let dataPeriodInterval = null;
let dataCommaInterval = null;
let dataEndInterval = null;
let dataWordInterval = null;
if (typeof referenceTypeNode.getAttribute === "function") {
dataCharInterval = referenceTypeNode.getAttribute("data-char-interval");
dataPeriodInterval = referenceTypeNode.getAttribute("data-period-interval");
dataCommaInterval = referenceTypeNode.getAttribute("data-comma-interval");
dataEndInterval = referenceTypeNode.getAttribute("data-end-interval");
dataWordInterval = referenceTypeNode.getAttribute("data-word-interval");
}
const charInterval = parseDuration(dataCharInterval || defaultCharInterval);
const periodInterval = parseDuration(dataPeriodInterval || defaultPeriodInterval);
const commaInterval = parseDuration(dataCommaInterval || defaultCommaInterval);
const endInterval = parseDuration(dataEndInterval || defaultEndInterval);
const wordInterval = parseDuration(dataWordInterval || defaultWordInterval);
const char = text[0];
if (text.length === 1) {
return endInterval;
} else if (char === "." || char === "?" || char === "!") {
return Math.max(charInterval, periodInterval);
} else if (char === " ") {
return Math.max(wordInterval, charInterval);
} else if (char === ",") {
return Math.max(charInterval, commaInterval);
}
return charInterval;
};
const createCharacterElement = function (char:string):Node {
const charElement = document.createElement("span");
charElement.classList.add("character");
setInnerText(charElement, char);
return charElement;
};
/**
* This is where the magic happens - here we type out text into an HTML Element.
*/
const writeText = function (context:AnimationContext, text:string):void {
if (text === "" || text === " ") {
context.callback(null);
return;
}
if (context.status.isCancelled) {
context.status.onCancel();
return;
}
const charElement = createCharacterElement(text[0]);
const interval = mapFirstCharToInterval(context, text);
const continueWriting = function ():void {
writeText(context, text.slice(1));
scrollDown(context.config);
};
context.to.appendChild(charElement);
context.insertedChars.push(<HTMLElement> charElement);
if (interval === 0) {
continueWriting();
} else {
setTimeout(continueWriting, interval);
}
};
const getCursor = function (context:AnimationContext):HTMLElement {
const cursor = document.createElement("div");
cursor.style.display = "inline-block";
cursor.style.width = "0.5em";
cursor.style.height = "1em";
cursor.style.backgroundColor = "black";
cursor.style.marginLeft = "3px";
cursor.classList.add("cursor");
if (context.cursor !== null) {
context.cursor.parentNode.removeChild(context.cursor);
}
context.cursor = cursor;
return cursor;
};
const createTypeDestination = function ():HTMLElement {
const destination = document.createElement("span");
return destination;
};
const processTypeNode = function (context:AnimationContext):void {
switch (context.from.nodeType) {
case NodeType.Element:
makeProcessor(function (context) {
let appendedRoot = append(context.to, context.fromAsElement);
context.callback(appendedRoot);
})(context.withCallback(function (appendedRoot:HTMLElement) {
asynchronouslyProcessNodes(
context,
function (node:Node, callback:IVoidCallback):void {
processTypeNode(
context
.withTo(appendedRoot)
.withFrom(node)
.withCallback(callback)
.withExtra(context.extra || context.from));
});
}));
break;
case NodeType.Text:
const cursor = getCursor(context);
const destination = createTypeDestination();
context.to.appendChild(destination);
context.to.appendChild(cursor);
writeText(
context
.withTo(destination),
stripWhitespace(context.fromAsCharacterData.data));
break;
default:
context.callback(null);
break;
}
};
const processWaitNode = function (context:AnimationContext):void {
const duration = parseDuration(innerText(context.fromAsElement));
setTimeout(
function ():void {
context.callback(null);
},
duration);
};
const processClearParentNode = function (context:AnimationContext):void {
removeChildren(context.to);
context.callback(null);
};
const processClearAllNode = function (context:AnimationContext):void {
removeChildren(context.rootTo);
context.callback(null);
};
const processRepeatNode = function (context:AnimationContext):void {
const repeatAttr = context.fromAsElement.getAttribute("data-repeat");
let repeats = 1;
if (repeatAttr === "infinite") {
repeats = -1;
} else if (typeof repeatAttr !== "undefined") {
repeats = parseInt(repeatAttr, 10);
}
let index = 0;
const clone = append(context.to, context.fromAsElement);
const processAgain = function ():void {
if (index++ < repeats || repeats === -1) {
asynchronouslyProcessNodes(
context.withCallback(processAgain),
function (node:Node, callback:IVoidCallback):void {
processNode(context.withFrom(node).withCallback(callback).withTo(clone));
});
} else {
context.callback(null);
}
};
processAgain();
};
const processDeleteNode = function (context:AnimationContext) {
let count = 0;
const charDeleteCount = parseInt(context.fromAsElement.getAttribute("data-chars"), 10);
const ignoreWhitespace = context.fromAsElement.getAttribute("data-ignore-whitespace") || "false";
let deleteChar = function () {
if (count == charDeleteCount) {
context.callback(null);
return;
}
let index = context.insertedChars.length - 1;
let currentChar = context.insertedChars[index];
currentChar.parentElement.removeChild(currentChar);
context.insertedChars.pop();
if (!/\s+/.test(innerText(currentChar))) {
count++;
}
setTimeout(deleteChar, 100);
};
deleteChar();
};
const processDeleteWordsNode = function (context:AnimationContext) {
let count = 0;
const wordDeleteCount = parseInt(context.fromAsElement.getAttribute("data-words"), 10);
let deleteChar = function () {
if (count == wordDeleteCount) {
context.callback(null);
return;
}
let index = context.insertedChars.length - 1;
let currentChar = context.insertedChars[index];
currentChar.parentElement.removeChild(currentChar);
context.insertedChars.pop();
if (/\s+/.test(innerText(currentChar))) {
count++;
}
setTimeout(deleteChar, 100);
};
deleteChar();
};
const processors:{[key:string]:IElementProcessor} = {
"type": makeProcessor(processTypeNode),
"wait": makeProcessor(processWaitNode),
"clearparent": makeProcessor(processClearParentNode),
"clearall": makeProcessor(processClearAllNode),
"repeat": makeProcessor(processRepeatNode),
"delete": makeProcessor(processDeleteNode),
"deletewords": makeProcessor(processDeleteWordsNode)
};
const processDefaultNode = makeProcessor(function (context:AnimationContext):void {
const noAnimateContents = context.fromAsElement.getAttribute("data-ignore-tply") === "true";
const clone = append(context.to, context.fromAsElement, null, noAnimateContents);
clone.classList.add(context.config.insertedClass || "fadein");
if (noAnimateContents) {
context.callback(clone);
} else {
runAnimation(context.withTo(clone));
}
});
const processNode = function (context:AnimationContext):void {
switch (context.from.nodeType) {
case NodeType.Element:
const tag = context.fromAsElement.tagName.toLowerCase();
const matchingProcessor = processors[tag] || processDefaultNode;
matchingProcessor(context);
break;
case NodeType.Text:
context.to.appendChild(document.createTextNode(context.fromAsCharacterData.data));
scrollDown(context.config);
context.callback(null);
break;
default:
scrollDown(context.config);
context.callback(null);
break;
}
};
const runAnimation = function (context:AnimationContext):void {
asynchronouslyProcessNodes(
context,
function (node:Node, callback:IVoidCallback):void {
processNode(
context
.withFrom(node.cloneNode(true))
.withCallback(callback));
},
context.to);
};
(<any> window).tply = (<any> window).tply || {
animate: function (from:HTMLElement,
to:HTMLElement,
conf:IConfiguration = {},
callback:() => void = () => null):Status {
const cancellation = new Status();
let context = new AnimationContext(
cancellation,
conf,
from,
from,
to,
to,
function () {
cancellation.onFinish();
callback();
});
context = context.withRootContext(context);
runAnimation(context);
return cancellation;
}
};
})(); | the_stack |
import config from '../util/config'
import logger from '../util/logger'
import { counter } from '../util/id'
import { bits } from './bit'
import { Middleware } from './middleware'
import { State, ICallback } from './state'
import { Conditions, ConditionInput } from './condition'
import {
Message,
TextMessage,
CatchAllMessage,
ServerMessage,
EnterMessage,
LeaveMessage,
TopicMessage
} from './message'
import { NLUCriteria, NLUResultsRaw } from './nlu'
export enum ProcessKey { listen, understand, serve, act }
export type ProcessKeys = keyof typeof ProcessKey
/** Branch matcher function interface, resolved value must be truthy. */
export interface IMatcher { (input: any): Promise<any> | any }
/** Called at the end of middleware with status of match. */
export interface IDone { (matched: boolean): void }
/** Attributes for branch. */
export interface IBranch {
id?: string
force?: boolean
processKey?: ProcessKeys
[key: string]: any
}
/** Alias for acceptable branch action types. */
export type action = ICallback | string
/**
* Process message in state and decide whether to act on it.
* @param action Accepts an on-match callback, or creates one to execute a bit,
* by passing its key. The callback be given the final state.
* @param meta Any additional key/values to define the branch, such as 'id'
*/
export abstract class Branch implements IBranch {
id: string
/** Action to take on matching input. */
callback: ICallback
/** Force matching on this branch regardless of other matched branches. */
force: boolean = false
/** The thought process collection the branch should be applied. */
processKey: ProcessKeys = 'listen'
/** The result of branch matcher on input. */
match?: any
/** Status of match. */
matched?: boolean
[key: string]: any
/** Create a Branch */
constructor (
action: action,
atts: IBranch = {}
) {
this.callback = (typeof action === 'string')
? (state) => bits.run(action, state)
: action
this.id = (atts.id) ? atts.id : counter('branch')
for (let key in atts) this[key] = atts[key]
}
/**
* Determine if this branch should trigger the callback.
* Note that the method must be async, custom matcher will be promise wrapped.
* Abstract input has no enforced type, but resolved result MUST be truthy.
*/
abstract matcher (input: any): Promise<any>
/** Get the branch type, allows filtering processing. */
get type () {
return this.constructor.name
}
/**
* Runs the matcher, then middleware and callback if matched.
* Middleware can intercept and prevent the callback from executing.
* If the state has already matched on prior branch, it will not match again
* unless forced to, with the branch's `force` property.
* @param b State containing message to process
* @param middleware Executes before the branch callback if matched
* @param done Called after middleware (optional), with match status
*/
async execute (
b: State,
middleware: Middleware,
done: IDone = () => null
) {
if (!b.matched || this.force) {
this.match = await Promise.resolve(this.matcher(b.message))
this.matched = (this.match) ? true : false
if (this.matched) {
b.setMatchingBranch(this)
await middleware.execute(b, (b) => {
logger.debug(`[branch] executing ${this.constructor.name} callback, ID ${this.id}`)
return Promise.resolve(this.callback(b))
}).then(() => {
logger.debug(`[branch] ${this.id} execute done (${(this.matched) ? 'matched' : 'no match'})`)
return Promise.resolve(done(true))
}).catch((err: Error) => {
logger.error(`[branch] ${this.id} middleware error, ${err.message}`)
return Promise.resolve(done(false))
})
} else {
await Promise.resolve(done(false))
}
}
return b
}
}
/** Branch to match on any CatchAll type */
export class CatchAllBranch extends Branch {
processKey: ProcessKeys = 'act'
/** Accepts only super args, matcher is fixed */
constructor (action: action, options?: IBranch) {
super(action, options)
}
/** Matching function looks for any CatchAll */
async matcher (msg: Message) {
if (msg instanceof CatchAllMessage) {
logger.debug(`[branch] message "${msg}" matched catch all ID ${this.id}`)
return msg
}
return undefined
}
}
/** Custom branch using unique matching function */
export class CustomBranch extends Branch {
/** Accepts custom function to test message */
constructor (
public customMatcher: IMatcher,
action: action,
options?: IBranch
) {
super(action, options)
}
/** Standard matcher method routes to custom matching function */
async matcher (msg: Message) {
const match = await Promise.resolve(this.customMatcher(msg))
if (match) {
logger.debug(`[branch] message "${msg}" matched custom branch ID ${this.id}`)
}
return match
}
}
/** Text branch uses basic regex matching */
export class TextBranch extends Branch {
processKey: ProcessKeys = 'listen'
conditions: Conditions
/** Create text branch for regex pattern */
constructor (
input: Conditions | ConditionInput,
callback: action,
options?: IBranch
) {
super(callback, options)
try {
this.conditions = (input instanceof Conditions)
? input
: new Conditions(input)
} catch (err) {
logger.error(`[branch] failed creating branch with input: ${JSON.stringify(input)}: \n${err.stack}`)
throw err
}
}
/**
* Match message text against regex or composite conditions.
* Resolves with either single match result or cumulative condition success.
*/
async matcher (msg: Message) {
this.conditions.exec(msg.toString())
const match = this.conditions.match
if (match) {
logger.debug(`[branch] message "${msg.toString()}" matched branch ${this.id} conditions`)
}
return match
}
}
/**
* Text Direct Branch pre-matches the text for bot name prefix.
* If matched on the direct pattern (name prefix) it runs the branch matcher on
* a clone of the message with the prefix removed, this allows conditions like
* `is` to operate on the body of the message, without failing due to a prefix.
*/
export class TextDirectBranch extends TextBranch {
processKey: ProcessKeys = 'listen'
async matcher (msg: TextMessage) {
if (directPattern().exec(msg.toString())) {
const indirectMessage = msg.clone()
indirectMessage.text = msg.text.replace(directPattern(), '')
return super.matcher(indirectMessage)
} else {
return false
}
}
}
/**
* Natural language branch uses NLU result to match on intent, entities and/or
* sentiment of optional score threshold. NLU must be trained to provide intent.
*/
export class NLUBranch extends Branch {
processKey: ProcessKeys = 'understand'
match: NLUResultsRaw | undefined
/** Create natural language branch for NLU matching. */
constructor (
public criteria: NLUCriteria,
callback: action,
options?: IBranch
) {
super(callback, options)
}
/** Match on message's NLU attributes */
async matcher (msg: TextMessage) {
if (!msg.nlu) {
logger.error(`[branch] NLU attempted matching without NLU, ID ${this.id}`)
return undefined
}
const match = msg.nlu.matchAllCriteria(this.criteria)
if (match) {
logger.debug(`[branch] NLU matched language branch ID ${this.id}`)
return match
}
return undefined
}
}
/** Natural Language Direct Branch pre-matches the text for bot name prefix. */
export class NLUDirectBranch extends NLUBranch {
processKey: ProcessKeys = 'understand'
async matcher (msg: TextMessage) {
if (directPattern().exec(msg.toString())) {
return super.matcher(msg)
} else {
return undefined
}
}
}
/** Wild card object for validating any key/value data at path. */
export interface IServerBranchCriteria {
[path: string]: any
}
/** Server branch matches data in a message received on the server. */
export class ServerBranch extends Branch {
processKey: ProcessKeys = 'serve'
match: any
/** Create server branch for data matching. */
constructor (
public criteria: IServerBranchCriteria,
callback: action,
options?: IBranch
) {
super(callback, options)
}
/**
* Match on any exact or regex values at path of key in criteria.
* Will also match on empty data if criteria is an empty object.
*/
async matcher (msg: ServerMessage) {
const match: { [path: string]: any } = {}
if (
Object.keys(this.criteria).length === 0 &&
(
typeof msg.data === 'undefined' ||
Object.keys(msg.data).length === 0
)
) {
return match
} else {
if (!msg.data) {
logger.error(`[branch] server branch attempted matching without data, ID ${this.id}`)
return undefined
}
}
for (let path in this.criteria) {
const valueAtPath = path.split('.').reduce((pre, cur) => {
return (typeof pre !== 'undefined') ? pre[cur] : undefined
}, msg.data)
if (
this.criteria[path] instanceof RegExp &&
this.criteria[path].exec(valueAtPath)
) match[path] = this.criteria[path].exec(valueAtPath)
else if (
this.criteria[path] === valueAtPath ||
this.criteria[path].toString() === valueAtPath
) match[path] = valueAtPath
}
if (Object.keys(match).length) {
logger.debug(`[branch] Data matched server branch ID ${this.id}`)
return match
}
return undefined
}
}
/**
* Build a regular expression that matches text prefixed with the bot's name.
* - matches when alias is substring of name
* - matches when name is substring of alias
*/
export function directPattern () {
let name = config.get('name') || ''
let alias = config.get('alias') || ''
name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
alias = alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
if (!alias.length) return new RegExp(`^\\s*[@]?${name}[:,]?\\s*`, 'i')
if (name.length > alias.length) {
return new RegExp(`^\\s*[@]?(?:${name}[:,]?|${alias}[:,]?)\\s*`, 'i')
}
return new RegExp(`^\\s*[@]?(?:${alias}[:,]?|${name}[:,]?)\\s*`, 'i')
}
/** Build a regular expression for bot's name combined with another regex. */
export function directPatternCombined (regex: RegExp) {
const regexWithoutModifiers = regex.toString().split('/')
regexWithoutModifiers.shift()
const modifiers = regexWithoutModifiers.pop()
const pattern = regexWithoutModifiers.join('/')
let name = config.get('name') || ''
let alias = config.get('alias') || ''
name = name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
alias = alias.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
if (!alias.length) {
return new RegExp(`^\\s*[@]?${name}[:,]?\\s*(?:${pattern})`, modifiers)
}
if (name.length > alias.length) {
return new RegExp(`^\\s*[@]?(?:${name}[:,]?|${alias}[:,]?)\\s*(?:${pattern})`, modifiers)
}
return new RegExp(`^\\s*[@]?(?:${alias}[:,]?|${name}[:,]?)\\s*(?:${pattern})`, modifiers)
}
/** Interface for collections of thought process branches. */
export interface IBranches {
listen?: { [id: string]: TextBranch | CustomBranch }
understand?: { [id: string]: NLUBranch | CustomBranch }
serve?: { [id: string]: ServerBranch | CustomBranch }
act?: { [id: string]: CatchAllBranch }
}
/** Creates and collects branches for each thought process. */
export class BranchController implements IBranches {
listen: { [id: string]: TextBranch | CustomBranch }
understand: { [id: string]: NLUBranch | CustomBranch }
serve: { [id: string]: ServerBranch | CustomBranch }
act: { [id: string]: CatchAllBranch }
/** Create branch controller (branches can be cloned, created or empty). */
constructor (init: BranchController | IBranches = {}) {
this.listen = (init.listen)
? Object.assign({}, init.listen)
: {}
this.understand = (init.understand)
? Object.assign({}, init.understand)
: {}
this.serve = (init.serve)
? Object.assign({}, init.serve)
: {}
this.act = (init.act)
? Object.assign({}, init.act)
: {}
}
/** Check if any branches have been added. */
exist (type?: ProcessKeys) {
if (type) return (Object.keys(this[type]).length)
if (Object.keys(this.listen).length) return true
if (Object.keys(this.understand).length) return true
if (Object.keys(this.serve).length) return true
if (Object.keys(this.act).length) return true
return false
}
/** Remove all but forced branches from process, return remaining size. */
forced (processKey: ProcessKeys) {
for (let id in this[processKey]) {
if (!this[processKey][id].force) delete this[processKey][id]
}
return Object.keys(this[processKey]).length
}
/** Add branch to thought process by it's class default or given key. */
add (branch: Branch, processKey?: ProcessKeys) {
if (!processKey) processKey = branch.processKey
this[processKey][branch.id] = branch
return branch.id
}
/** Empty thought process branch collections. */
reset () {
for (let key in ProcessKey) {
if (isNaN(Number(key))) this[key as ProcessKeys] = {}
}
}
/** Create text branch with provided regex, action and options */
text (
condition: ConditionInput,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new TextBranch(condition, action, atts))
}
/** Create text branch pre-matched on the bot name as prefix. */
direct (
condition: ConditionInput,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new TextDirectBranch(condition, action, atts))
}
/** Create custom branch with provided matcher, action and optional meta. */
custom (
matcher: IMatcher,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new CustomBranch(matcher, action, atts), 'listen')
}
/** Create a branch that triggers when no other branch matches. */
catchAll (
action: ICallback | string,
atts?: IBranch
) {
return this.add(new CatchAllBranch(action, atts))
}
/** Create a natural language branch to match on NLU result attributes. */
NLU (
criteria: NLUCriteria,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new NLUBranch(criteria, action, atts))
}
/** Create a natural language branch pre-matched on the bot name as prefix. */
directNLU (
criteria: NLUCriteria,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new NLUDirectBranch(criteria, action, atts))
}
/** Create a natural language branch with custom matcher. */
customNLU (
matcher: IMatcher,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new CustomBranch(matcher, action, atts), 'understand')
}
/** Create a branch that triggers when user joins a room. */
enter (
action: ICallback | string,
atts?: IBranch
) {
return this.custom((msg: Message) => {
return msg instanceof EnterMessage
}, action, atts)
}
/** Create a branch that triggers when user leaves a room. */
leave (
action: ICallback | string,
atts?: IBranch
) {
return this.custom((msg: Message) => {
return msg instanceof LeaveMessage
}, action, atts)
}
/** Create a branch that triggers when user changes the topic. */
topic (
action: ICallback | string,
atts?: IBranch
) {
return this.custom((msg: Message) => {
return msg instanceof TopicMessage
}, action, atts)
}
/** Create a branch that triggers when server message matches criteria. */
server (
criteria: IServerBranchCriteria,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new ServerBranch(criteria, action, atts))
}
/** Create a server branch with custom matcher. */
customServer (
matcher: IMatcher,
action: ICallback | string,
atts?: IBranch
) {
return this.add(new CustomBranch(matcher, action, atts), 'serve')
}
}
export const branches = new BranchController()
export default branches | the_stack |
import {
AfterViewChecked,
AfterViewInit,
ChangeDetectorRef,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
HostBinding,
Input,
NgZone,
OnDestroy,
Output,
} from '@angular/core';
@Component({
selector: '[soho-monthview]', // eslint-disable-line
template: `<ng-content></ng-content>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SohoMonthViewComponent implements AfterViewChecked, AfterViewInit, OnDestroy {
@HostBinding('class.monthview') isMonthView = true;
@HostBinding('attr.data-init') dataInit = false;
@Input() set monthviewOptions(monthviewOptions: SohoMonthViewOptions | undefined) {
this._monthviewOptions = monthviewOptions;
if (this.jQueryElement) {
this.markForRefresh();
}
}
get monthviewOptions(): SohoMonthViewOptions | undefined {
if (this.monthview) {
return this.monthview.settings;
}
return this._monthviewOptions;
}
/**
* The name of the locale to use for this instance. If not set the current locale will be used.
*/
@Input() set locale(locale: string) {
(this._monthviewOptions as any).locale = locale;
if (this.monthview) {
this.monthview.settings.locale = locale;
this.markForRefresh();
}
}
get locale(): string {
if (this.monthview) {
return (this.monthview as any).settings.locale;
}
return (this._monthviewOptions as any).locale;
}
/**
* Initial month to show.
*/
@Input() set month(month: number | undefined) {
(this._monthviewOptions as any).month = month;
if (this.monthview) {
this.monthview.settings.month = month;
this.markForRefresh();
}
}
get month(): number | undefined {
if (this.monthview) {
return this.monthview.settings.month;
}
return (this._monthviewOptions as any).month;
}
/**
* Initial year to show.
*/
@Input() set year(year: number | undefined) {
(this._monthviewOptions as any).year = year;
if (this.monthview) {
this.monthview.settings.year = year;
this.markForRefresh();
}
}
get year(): number | undefined {
if (this.monthview) {
return this.monthview.settings.year;
}
return (this._monthviewOptions as any).year;
}
/**
* The initial selected day to show.
*/
@Input() set day(day: number | undefined) {
(this._monthviewOptions as any).day = day;
if (this.monthview) {
this.monthview.settings.day = day;
this.markForRefresh();
}
}
get day(): number | undefined {
if (this.monthview) {
return this.monthview.settings.day;
}
return (this._monthviewOptions as any).day;
}
/**
* The date to highlight as selected/today.
*/
@Input() set activeDate(activeDate: number | undefined) {
(this._monthviewOptions as any).activeDate = activeDate;
if (this.monthview) {
this.monthview.settings.activeDate = activeDate;
this.markForRefresh();
}
}
get activeDate(): number | undefined {
if (this.monthview) {
return this.monthview.settings.activeDate;
}
return (this._monthviewOptions as any).activeDate;
}
/**
* The date to highlight as selected/today (as an array for islamic)
*/
@Input() set activeDateIslamic(activeDateIslamic: number | undefined) {
(this._monthviewOptions as any).activeDateIslamic = activeDateIslamic;
if (this.monthview) {
this.monthview.settings.activeDateIslamic = activeDateIslamic;
this.markForRefresh();
}
}
get activeDateIslamic(): number | undefined {
if (this.monthview) {
return this.monthview.settings.activeDateIslamic;
}
return (this._monthviewOptions as any).activeDateIslamic;
}
/**
* Is it in a popup (datepicker using it)
*/
@Input() set isPopup(isPopup: boolean | undefined) {
(this._monthviewOptions as any).isPopup = isPopup;
if (this.monthview) {
this.monthview.settings.isPopup = isPopup;
this.markForRefresh();
}
}
get isPopup(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.isPopup;
}
return (this._monthviewOptions as any).isPopup;
}
/**
* If true, will set it as inPage month view.
*/
@Input() set inPage(inPage: boolean | undefined) {
(this._monthviewOptions as any).inPage = inPage;
if (this.monthview) {
this.monthview.settings.inPage = inPage;
this.markForRefresh();
}
}
get inPage(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.inPage;
}
return (this._monthviewOptions as any).inPage;
}
/**
* If true, will set the month-year title as button for inPage.
*/
@Input() set inPageTitleAsButton(inPageTitleAsButton: boolean | undefined) {
(this._monthviewOptions as any).inPageTitleAsButton = inPageTitleAsButton;
if (this.monthview) {
this.monthview.settings.inPageTitleAsButton = inPageTitleAsButton;
this.markForRefresh();
}
}
get inPageTitleAsButton(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.inPageTitleAsButton;
}
return (this._monthviewOptions as any).inPageTitleAsButton;
}
/**
* If true, will set to be toggleable.
*/
@Input() set inPageToggleable(inPageToggleable: boolean | undefined) {
(this._monthviewOptions as any).inPageToggleable = inPageToggleable;
if (this.monthview) {
this.monthview.settings.inPageToggleable = inPageToggleable;
this.markForRefresh();
}
}
get inPageToggleable(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.inPageToggleable;
}
return (this._monthviewOptions as any).inPageToggleable;
}
/**
* If true, will init as expanded
*/
@Input() set inPageExpanded(inPageExpanded: boolean | undefined) {
(this._monthviewOptions as any).inPageExpanded = inPageExpanded;
if (this.monthview) {
this.monthview.settings.inPageExpanded = inPageExpanded;
this.markForRefresh();
}
}
get inPageExpanded(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.inPageExpanded;
}
return (this._monthviewOptions as any).inPageExpanded;
}
/**
* Set first day of the week. '1' would be Monday.
*/
@Input() set firstDayOfWeek(firstDayOfWeek: number | undefined) {
(this._monthviewOptions as any).settingsfirstDayOfWeek = firstDayOfWeek;
if (this.monthview) {
this.monthview.settings.firstDayOfWeek = firstDayOfWeek;
this.markForRefresh();
}
}
get firstDayOfWeek(): number | undefined {
if (this.monthview) {
return this.monthview.settings.firstDayOfWeek;
}
return (this._monthviewOptions as any).settings.firstDayOfWeek;
}
/**
* If true the today button is shown on the header.
*/
@Input() set showToday(showToday: boolean | undefined) {
(this._monthviewOptions as any).showToday = showToday;
if (this.monthview) {
this.monthview.settings.showToday = showToday;
this.markForRefresh();
}
}
get showToday(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.showToday;
}
return (this._monthviewOptions as any).showToday;
}
/**
* Indicates this is a month picker on the month and week view.
* Has some slight different behavior.
*/
@Input() set isMonthPicker(isMonthPicker: boolean | undefined) {
(this._monthviewOptions as any).isMonthPicker = isMonthPicker;
if (this.monthview) {
this.monthview.settings.isMonthPicker = isMonthPicker;
this.markForRefresh();
}
}
get isMonthPicker(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.isMonthPicker;
}
return (this._monthviewOptions as any).isMonthPicker;
}
/**
* If false the year and month switcher will be disabled.
*/
@Input() set showMonthYearPicker(showMonthYearPicker: boolean | undefined) {
(this._monthviewOptions as any).showMonthYearPicker = showMonthYearPicker;
if (this.monthview) {
this.monthview.settings.showMonthYearPicker = showMonthYearPicker;
this.markForRefresh();
}
}
get showMonthYearPicker(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.showMonthYearPicker;
}
return (this._monthviewOptions as any).showMonthYearPicker;
}
/**
* Shows the legend below the table.
*/
@Input() set showLegend(showLegend: boolean | undefined) {
(this._monthviewOptions as any).showLegend = showLegend;
if (this.monthview) {
this.monthview.settings.showLegend = showLegend;
this.markForRefresh();
}
}
get showLegend(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.showLegend;
}
return (this._monthviewOptions as any).showLegend;
}
/**
* Legend Build up.
*/
@Input() set legend(legend: SohoMonthViewLegend[] | undefined) {
(this._monthviewOptions as any).legend = legend;
if (this.monthview) {
this.monthview.settings.legend = legend
this.markForRefresh();
}
}
get legend(): SohoMonthViewLegend[] | undefined {
if (this.monthview) {
return this.monthview.settings.legend;
}
return (this._monthviewOptions as any).legend;
}
/**
* If true the days portion of the calendar will be hidden.
* Usefull for Month/Year only formats.
*/
@Input() set hideDays(hideDays: boolean | undefined) {
(this._monthviewOptions as any).hideDays = hideDays;
if (this.monthview) {
this.monthview.settings.hideDays = hideDays;
this.markForRefresh();
}
}
get hideDays(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.hideDays;
}
return (this._monthviewOptions as any).hideDays;
}
/**
* Disable dates in various ways.
* For example `{minDate: 'M/d/yyyy', maxDate: 'M/d/yyyy'}`.
* Dates should be in format M/d/yyyy
*/
@Input() set disable(disable: SohoDatePickerDisable | undefined) {
(this._monthviewOptions as any).settings.disable = disable;
if (this.jQueryElement) {
this.markForRefresh();
}
}
get disable(): SohoDatePickerDisable | undefined {
if (this.monthview) {
return (this.monthview as any).settings.disable;
}
return this.disable;
}
/**
* The number of years ahead to show in the month/year picker should total 9 with yearsBack.
*/
@Input() set yearsBack(yearsBack: number | undefined) {
(this._monthviewOptions as any).yearsBack = yearsBack;
if (this.monthview) {
this.monthview.settings.yearsBack = yearsBack;
this.markForRefresh();
}
}
get yearsBack(): number | undefined {
if (this.monthview) {
return this.monthview.settings.yearsBack;
}
return (this._monthviewOptions as any).yearsBack;
}
/**
* The number of years back to show in the month/year picker should total 9 with yearsAhead.
*/
@Input() set yearsAhead(yearsAhead: number | undefined) {
(this._monthviewOptions as any).yearsAhead = yearsAhead;
if (this.monthview) {
this.monthview.settings.yearsAhead = yearsAhead;
this.markForRefresh();
}
}
get yearsAhead(): number | undefined {
if (this.monthview) {
return this.monthview.settings.yearsAhead;
}
return (this._monthviewOptions as any).yearsAhead;
}
/**
* Range between two dates with various options.
*/
@Input() set range(range: SohoMonthViewRange[] | undefined) {
(this._monthviewOptions as any).range = range;
if (this.monthview) {
this.monthview.settings.range = range;
this.markForRefresh();
}
}
get range(): SohoMonthViewRange[] | undefined {
if (this.monthview) {
return this.monthview.settings.range;
}
return (this._monthviewOptions as any).range;
}
/**
* If true the month days can be clicked to select
*/
@Input() set selectable(selectable: boolean | undefined) {
(this._monthviewOptions as any).selectable = selectable;
if (this.monthview) {
this.monthview.settings.selectable = selectable;
this.markForRefresh();
}
}
get selectable(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.selectable;
}
return (this._monthviewOptions as any).selectable;
}
/**
* Callback that fires when a month day is clicked.
*/
@Input() set onSelected(onSelected: boolean | undefined) {
(this._monthviewOptions as any).onSelected = onSelected;
if (this.monthview) {
this.monthview.settings.onSelected = onSelected;
this.markForRefresh();
}
}
get onSelected(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.onSelected;
}
return (this._monthviewOptions as any).onSelected;
}
/**
* Callback that fires when a key is pressed down.
*/
@Input() set onKeyDown(onKeyDown: boolean | undefined) {
(this._monthviewOptions as any).onKeyDown = onKeyDown;
if (this.monthview) {
this.monthview.settings.onKeyDown = onKeyDown;
this.markForRefresh();
}
}
get onKeyDown(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.onKeyDown;
}
return (this._monthviewOptions as any).onKeyDown;
}
/**
* If true the Next Previous buttons will shown on the header.
*/
@Input() set showNextPrevious(showNextPrevious: boolean | undefined) {
(this._monthviewOptions as any).showNextPrevious = showNextPrevious;
if (this.monthview) {
this.monthview.settings.showNextPrevious = showNextPrevious;
this.markForRefresh();
}
}
get showNextPrevious(): boolean | undefined {
if (this.monthview) {
return this.monthview.settings.showNextPrevious;
}
return (this._monthviewOptions as any).showNextPrevious;
}
/**
* Call back for when the view changer is changed.
*/
@Input() set changeViewCallback(changeViewCallback: Function | undefined) {
(this._monthviewOptions as any).onChangeView = changeViewCallback;
if (this.monthview) {
this.monthview.settings.onChangeView = changeViewCallback;
this.markForRefresh();
}
}
get changeViewCallback(): Function | undefined {
if (this.monthview) {
return this.monthview.settings.onChangeView;
}
return (this._monthviewOptions as any).onChangeView;
}
@Input() set attributes(attributes: Array<Object> | Object | undefined) {
(this.monthview as any).settings.attributes = attributes;
if (this.jQueryElement) {
this.markForRefresh();
}
}
get attributes(): Array<Object> | Object | undefined {
if (this.monthview) {
return this.monthview.settings.attributes;
}
return this.attributes;
}
// -------------------------------------
// Component Output
// -------------------------------------
@Output() monthRendered = new EventEmitter<SohoMonthViewRenderEvent>();
@Output() selected = new EventEmitter<SohoMonthViewSelectedEvent>();
/**
* Local variables
*/
private jQueryElement?: JQuery;
private monthview?: SohoMonthView | null;
private _monthviewOptions?: SohoMonthViewOptions = {};
private updateRequired?: boolean;
constructor(
private element: ElementRef,
private ngZone: NgZone,
public ref: ChangeDetectorRef
) { }
ngAfterViewInit() {
this.ngZone.runOutsideAngular(() => {
// Wrap the element in a jQuery selector.
this.jQueryElement = jQuery(this.element.nativeElement);
// Add listeners to emit events
this.jQueryElement
.on('monthrendered', (_e: any, args: SohoMonthViewRenderEvent) => this.onMonthViewRenderedEvent(args))
.on('selected', (_e: any, event: SohoMonthViewSelectedEvent) => this.onMonthViewSelectedEvent(event));
// Initialize the Soho control.
this.jQueryElement.monthview(this._monthviewOptions);
this.monthview = this.jQueryElement.data('monthview');
});
}
ngAfterViewChecked() {
if (!this.monthview || !this.jQueryElement) {
return;
}
if (this.updateRequired) {
this.updated();
this.updateRequired = false;
}
}
onMonthViewRenderedEvent(event: SohoMonthViewRenderEvent) {
this.ngZone.runOutsideAngular(() => this.monthRendered.emit(event));
}
onMonthViewSelectedEvent(event: SohoMonthViewSelectedEvent) {
this.ngZone.runOutsideAngular(() => this.selected.emit(event));
}
/**
* Handle updated settings and values.
*/
updated() {
this.ngZone.runOutsideAngular(() => (this.monthview as any).updated());
}
/**
* Mark the components as requiring a rebuild after the next update.
*/
markForRefresh() {
this.updateRequired = true;
this.ref.markForCheck();
}
/**
* Tear down the markup for the monthview
*/
teardown(): void {
if (this.monthview) {
this.ngZone.runOutsideAngular(() => (this.monthview as any).teardown());
}
}
/**
* Destroy the markup and any other resources.
*/
destroy() {
this.ngZone.runOutsideAngular(() => {
if (this.jQueryElement) {
this.jQueryElement.off();
}
if (this.monthview) {
this.monthview.destroy();
this.monthview = null;
}
});
}
/**
* Cleanup just before Angular destroys the component.
* Unsubscribe observables, detach event handlers and remove other resources to avoid memory leaks.
*/
ngOnDestroy() {
this.destroy();
}
} | the_stack |
export const SPARTACUS_SCOPE = `@spartacus/`;
export const SPARTACUS_SCHEMATICS = `@spartacus/schematics`;
export const SPARTACUS_CORE = `@spartacus/core`;
export const SPARTACUS_STOREFRONTLIB = `@spartacus/storefront`;
export const SPARTACUS_ASSETS = `@spartacus/assets`;
export const SPARTACUS_STYLES = `@spartacus/styles`;
export const SPARTACUS_SETUP = `@spartacus/setup`;
export const SPARTACUS_SETUP_SSR = `@spartacus/setup/ssr`;
export const CORE_SPARTACUS_SCOPES: string[] = [
SPARTACUS_CORE,
SPARTACUS_ASSETS,
SPARTACUS_SCHEMATICS,
SPARTACUS_STOREFRONTLIB,
SPARTACUS_STYLES,
SPARTACUS_SETUP,
];
export const FEATURES_LIBS_SKIP_SCOPES = [SPARTACUS_SCOPE];
export const SPARTACUS_ASM = `@spartacus/asm`;
export const SPARTACUS_ASM_ROOT = `@spartacus/asm/root`;
export const SPARTACUS_ASM_ASSETS = `@spartacus/asm/assets`;
export const SPARTACUS_CART = `@spartacus/cart`;
export const SPARTACUS_CART_BASE = `@spartacus/cart/base`;
export const SPARTACUS_CART_BASE_ROOT = `@spartacus/cart/base/root`;
export const SPARTACUS_CART_BASE_ASSETS = `@spartacus/cart/base/assets`;
export const MINI_CART_ENTRY_POINT = `@spartacus/cart/base/components/mini-cart`;
export const ADD_TO_CART_ENTRY_POINT = `@spartacus/cart/base/components/add-to-cart`;
export const SPARTACUS_CART_IMPORT_EXPORT = `@spartacus/cart/import-export`;
export const SPARTACUS_CART_IMPORT_EXPORT_ROOT = `@spartacus/cart/import-export/root`;
export const SPARTACUS_CART_IMPORT_EXPORT_ASSETS = `@spartacus/cart/import-export/assets`;
export const SPARTACUS_QUICK_ORDER = `@spartacus/cart/quick-order`;
export const SPARTACUS_CART_QUICK_ORDER_CORE = `@spartacus/cart/quick-order/core`;
export const SPARTACUS_CART_QUICK_ORDER_ROOT = `@spartacus/cart/quick-order/root`;
export const SPARTACUS_CART_QUICK_ORDER_COMPONENTS = `@spartacus/cart/quick-order/components`;
export const SPARTACUS_QUICK_ORDER_ROOT = `@spartacus/cart/quick-order/root`;
export const SPARTACUS_QUICK_ORDER_ASSETS = `@spartacus/cart/quick-order/assets`;
export const SPARTACUS_CART_SAVED_CART_COMPONENTS = `@spartacus/cart/saved-cart/components`;
export const SPARTACUS_CART_SAVED_CART_CORE = `@spartacus/cart/saved-cart/core`;
export const SPARTACUS_CART_SAVED_CART_ROOT = `@spartacus/cart/saved-cart/root`;
export const SPARTACUS_SAVED_CART = `@spartacus/cart/saved-cart`;
export const SPARTACUS_SAVED_CART_ROOT = `@spartacus/cart/saved-cart/root`;
export const SPARTACUS_SAVED_CART_ASSETS = `@spartacus/cart/saved-cart/assets`;
export const SPARTACUS_CART_WISHLIST = `@spartacus/cart/wish-list`;
export const SPARTACUS_CART_WISHLIST_ROOT = `@spartacus/cart/wish-list/root`;
export const SPARTACUS_CART_WISHLIST_ASSETS = `@spartacus/cart/wish-list/assets`;
export const ADD_TO_WISHLIST_ENTRY_POINT = `@spartacus/cart/wish-list/components/add-to-wishlist`;
export const SPARTACUS_CHECKOUT = `@spartacus/checkout`;
export const SPARTACUS_CHECKOUT_BASE = `@spartacus/checkout/base`;
export const SPARTACUS_CHECKOUT_BASE_ASSETS = `@spartacus/checkout/base/assets`;
export const SPARTACUS_CHECKOUT_BASE_OCC = `@spartacus/checkout/base/occ`;
export const SPARTACUS_CHECKOUT_BASE_CORE = `@spartacus/checkout/base/core`;
export const SPARTACUS_CHECKOUT_BASE_ROOT = `@spartacus/checkout/base/root`;
export const SPARTACUS_CHECKOUT_BASE_COMPONENTS = `@spartacus/checkout/base/components`;
export const SPARTACUS_CHECKOUT_B2B = `@spartacus/checkout/b2b`;
export const SPARTACUS_CHECKOUT_B2B_ASSETS = `@spartacus/checkout/b2b/assets`;
export const SPARTACUS_CHECKOUT_B2B_OCC = `@spartacus/checkout/b2b/occ`;
export const SPARTACUS_CHECKOUT_B2B_CORE = `@spartacus/checkout/b2b/core`;
export const SPARTACUS_CHECKOUT_B2B_ROOT = `@spartacus/checkout/b2b/root`;
export const SPARTACUS_CHECKOUT_B2B_COMPONENTS = `@spartacus/checkout/b2b/components`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT = `@spartacus/checkout/scheduled-replenishment`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT_ASSETS = `@spartacus/checkout/scheduled-replenishment/assets`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT_OCC = `@spartacus/checkout/scheduled-replenishment/occ`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT_CORE = `@spartacus/checkout/scheduled-replenishment/core`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT_ROOT = `@spartacus/checkout/scheduled-replenishment/root`;
export const SPARTACUS_CHECKOUT_SCHEDULED_REPLENISHMENT_COMPONENTS = `@spartacus/checkout/scheduled-replenishment/components`;
export const SPARTACUS_CHECKOUT_OLD_OCC = `@spartacus/checkout/occ`;
export const SPARTACUS_CHECKOUT_OLD_CORE = `@spartacus/checkout/core`;
export const SPARTACUS_CHECKOUT_OLD_ROOT = `@spartacus/checkout/root`;
export const SPARTACUS_CHECKOUT_OLD_COMPONENTS = `@spartacus/checkout/components`;
export const SPARTACUS_ORDER = `@spartacus/order`;
export const SPARTACUS_ORDER_ROOT = `@spartacus/order/root`;
export const SPARTACUS_ORDER_ASSETS = `@spartacus/order/assets`;
export const SPARTACUS_ORGANIZATION = `@spartacus/organization`;
export const SPARTACUS_ADMINISTRATION = `@spartacus/organization/administration`;
export const SPARTACUS_ORGANIZATION_ADMINISTRATION_ROOT = `@spartacus/organization/administration/root`;
export const SPARTACUS_ORGANIZATION_ADMINISTRATION_CORE = `@spartacus/organization/administration/core`;
export const SPARTACUS_ORGANIZATION_ADMINISTRATION_COMPONENTS = `@spartacus/organization/administration/components`;
export const SPARTACUS_ORGANIZATION_ADMINISTRATION_ASSETS = `@spartacus/organization/administration/assets`;
export const SPARTACUS_ORGANIZATION_ORDER_APPROVAL = `@spartacus/organization/order-approval`;
export const SPARTACUS_ORGANIZATION_ORDER_APPROVAL_ROOT = `@spartacus/organization/order-approval/root`;
export const SPARTACUS_ORGANIZATION_ORDER_APPROVAL_ASSETS = `@spartacus/organization/order-approval/assets`;
export const SPARTACUS_PRODUCT = `@spartacus/product`;
export const SPARTACUS_PRODUCT_VARIANTS_COMPONENTS = `@spartacus/product/variants/components`;
export const SPARTACUS_PRODUCT_VARIANTS_ROOT = `@spartacus/product/variants/root`;
export const SPARTACUS_BULK_PRICING = `@spartacus/product/bulk-pricing`;
export const SPARTACUS_BULK_PRICING_ROOT = `@spartacus/product/bulk-pricing/root`;
export const SPARTACUS_BULK_PRICING_ASSETS = `@spartacus/product/bulk-pricing/assets`;
export const SPARTACUS_IMAGE_ZOOM = `@spartacus/product/image-zoom`;
export const SPARTACUS_IMAGE_ZOOM_ROOT = `@spartacus/product/image-zoom/root`;
export const SPARTACUS_IMAGE_ZOOM_ASSETS = `@spartacus/product/image-zoom/assets`;
export const SPARTACUS_VARIANTS = `@spartacus/product/variants`;
export const SPARTACUS_VARIANTS_ROOT = `@spartacus/product/variants/root`;
export const SPARTACUS_VARIANTS_ASSETS = `@spartacus/product/variants/assets`;
export const SPARTACUS_PRODUCT_CONFIGURATOR = `@spartacus/product-configurator`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_COMMON = `@spartacus/product-configurator/common`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_ASSETS = `@spartacus/product-configurator/common/assets`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_TEXTFIELD = `@spartacus/product-configurator/textfield`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_RULEBASED = `@spartacus/product-configurator/rulebased`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_TEXTFIELD_ROOT = `@spartacus/product-configurator/textfield/root`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_RULEBASED_ROOT = `@spartacus/product-configurator/rulebased/root`;
export const SPARTACUS_PRODUCT_CONFIGURATOR_RULEBASED_CPQ = `@spartacus/product-configurator/rulebased/cpq`;
export const SPARTACUS_QUALTRICS = `@spartacus/qualtrics`;
export const SPARTACUS_QUALTRICS_COMPONENTS = `@spartacus/qualtrics/components`;
export const SPARTACUS_QUALTRICS_ROOT = `@spartacus/qualtrics/root`;
export const SPARTACUS_SMARTEDIT = `@spartacus/smartedit`;
export const SPARTACUS_SMARTEDIT_ROOT = `@spartacus/smartedit/root`;
export const SPARTACUS_STOREFINDER = `@spartacus/storefinder`;
export const SPARTACUS_STOREFINDER_ROOT = `@spartacus/storefinder/root`;
export const SPARTACUS_STOREFINDER_ASSETS = `@spartacus/storefinder/assets`;
export const SPARTACUS_TRACKING = `@spartacus/tracking`;
export const SPARTACUS_TMS_CORE = `@spartacus/tracking/tms/core`;
export const SPARTACUS_TMS_GTM = `@spartacus/tracking/tms/gtm`;
export const SPARTACUS_TMS_AEP = `@spartacus/tracking/tms/aep`;
export const SPARTACUS_PERSONALIZATION = `@spartacus/tracking/personalization`;
export const SPARTACUS_PERSONALIZATION_ROOT = `@spartacus/tracking/personalization/root`;
export const SPARTACUS_USER = `@spartacus/user`;
export const SPARTACUS_USER_ACCOUNT = `@spartacus/user/account`;
export const SPARTACUS_USER_ACCOUNT_ASSETS = `@spartacus/user/account/assets`;
export const SPARTACUS_USER_ACCOUNT_OCC = `@spartacus/user/account/occ`;
export const SPARTACUS_USER_ACCOUNT_CORE = `@spartacus/user/account/core`;
export const SPARTACUS_USER_ACCOUNT_ROOT = `@spartacus/user/account/root`;
export const SPARTACUS_USER_ACCOUNT_COMPONENTS = `@spartacus/user/account/components`;
export const SPARTACUS_USER_PROFILE = `@spartacus/user/profile`;
export const SPARTACUS_USER_PROFILE_OCC = `@spartacus/user/profile/occ`;
export const SPARTACUS_USER_PROFILE_CORE = `@spartacus/user/profile/core`;
export const SPARTACUS_USER_PROFILE_COMPONENTS = `@spartacus/user/profile/components`;
export const SPARTACUS_USER_PROFILE_ASSETS = `@spartacus/user/profile/assets`;
export const SPARTACUS_USER_PROFILE_ROOT = `@spartacus/user/profile/root`;
export const SPARTACUS_CDS = `@spartacus/cds`;
export const SPARTACUS_CDC = `@spartacus/cdc`;
export const SPARTACUS_CDC_ROOT = `@spartacus/cdc/root`;
export const SPARTACUS_DIGITAL_PAYMENTS = `@spartacus/digital-payments`;
export const SPARTACUS_DIGITAL_PAYMENTS_ASSETS = `@spartacus/digital-payments/assets`;
export const SPARTACUS_EPD_VISUALIZATION = `@spartacus/epd-visualization`;
export const SPARTACUS_EPD_VISUALIZATION_ROOT = `@spartacus/epd-visualization/root`;
export const SPARTACUS_EPD_VISUALIZATION_ASSETS = `@spartacus/epd-visualization/assets`;
/***** Scopes end *****/
/***** File structure start *****/
export const SPARTACUS_ROUTING_MODULE = 'app-routing';
export const SPARTACUS_MODULE = 'spartacus';
export const SPARTACUS_FEATURES_MODULE = 'spartacus-features';
export const SPARTACUS_FEATURES_NG_MODULE = 'SpartacusFeaturesModule';
export const SPARTACUS_CONFIGURATION_MODULE = 'spartacus-configuration';
/***** File structure end *****/
/***** Feature name start *****/
export const ASM_FEATURE_NAME = 'ASM';
export const CART_BASE_FEATURE_NAME = 'Cart';
export const CART_IMPORT_EXPORT_FEATURE_NAME = 'Import-Export';
export const CART_QUICK_ORDER_FEATURE_NAME = 'Quick-Order';
export const CART_WISHLIST_FEATURE_NAME = 'WishList';
export const CART_SAVED_CART_FEATURE_NAME = 'Saved-Cart';
export const CHECKOUT_BASE_FEATURE_NAME = 'Checkout';
export const CHECKOUT_B2B_FEATURE_NAME = 'Checkout-B2B';
export const CHECKOUT_SCHEDULED_REPLENISHMENT_FEATURE_NAME =
'Checkout-Scheduled-Replenishment';
export const ORDER_FEATURE_NAME = 'Order';
export const ORGANIZATION_ADMINISTRATION_FEATURE_NAME = 'Administration';
export const ORGANIZATION_ORDER_APPROVAL_FEATURE_NAME = 'Order-Approval';
export const PRODUCT_BULK_PRICING_FEATURE_NAME = 'Bulk-Pricing';
export const PRODUCT_IMAGE_ZOOM_FEATURE_NAME = 'Image-Zoom';
export const PRODUCT_VARIANTS_FEATURE_NAME = 'Product-Variants';
export const PRODUCT_CONFIGURATOR_TEXTFIELD_FEATURE_NAME =
'Textfield-Configurator';
export const PRODUCT_CONFIGURATOR_VC_FEATURE_NAME = 'VC-Configurator';
export const PRODUCT_CONFIGURATOR_CPQ_FEATURE_NAME = 'CPQ-Configurator';
export const QUALTRICS_FEATURE_NAME = 'Qualtrics';
export const SMARTEDIT_FEATURE_NAME = 'SmartEdit';
export const STOREFINDER_FEATURE_NAME = 'Store-Finder';
export const TRACKING_PERSONALIZATION_FEATURE_NAME = 'Personalization';
export const TRACKING_TMS_GTM_FEATURE_NAME = 'TMS-GTM';
export const TRACKING_TMS_AEP_FEATURE_NAME = 'TMS-AEPL';
export const USER_ACCOUNT_FEATURE_NAME = 'User-Account';
export const USER_PROFILE_FEATURE_NAME = 'User-Profile';
export const CDC_FEATURE_NAME = 'CDC';
export const CDS_FEATURE_NAME = 'CDS';
export const DIGITAL_PAYMENTS_FEATURE_NAME = 'Digital-Payments';
export const EPD_VISUALIZATION_FEATURE_NAME = 'EPD-Visualization';
/***** Feature name end *****/ | the_stack |
class WebGLRenderer extends Renderer {
canvas: HTMLCanvasElement;
gl: WebGLRenderingContext;
offsetLocation: any;
positionLocation: any;
texCoordLocation: any;
uScaleLocation: any;
uNumFramesLocation: any;
uFrameLocation: any;
objectUVBuffer: any;
texCoordBuffer: any;
tileBuffer: any;
tileShader: any;
uLightBuffer: any;
litOffsetLocation: any;
litScaleLocation: any;
u_colorTable: any; // [0x8000];
u_intensityColorTable: any; // [65536];
u_paletteRGB: any; // vec3 [256];
lightBufferTexture: any;
floorLightShader: any;
textures: {[key: string]: any} = {}; // WebGL texture cache
newTexture(key: string, img: any, doCache: boolean=true): any {
var gl = this.gl
var texture = this.gl.createTexture();
this.gl.bindTexture(this.gl.TEXTURE_2D, texture);
// Set the parameters so we can render any size image.
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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
// Upload the image into the texture.
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
if(doCache)
this.textures[key] = texture
return texture
}
getTexture(name: string): any {
var texture = this.textures[name]
if(texture !== undefined)
return texture
return null
}
getTextureFromHack(name: string): any {
// TODO: hack (ideally it should already be in textures)
if(this.textures[name] === undefined) {
if(images[name] !== undefined) {
// generate a new texture
return this.newTexture(name, images[name].img)
}
return null
}
return this.textures[name]
}
// create a texture from an array-like thing into a 3-component Float32Array using only the R component
// TODO: find a better format to store data in textures
textureFromArray(arr: any, size: number=256): any {
var buf = new Float32Array(size*size*4)
for(var i = 0; i < arr.length; i++) {
buf[i*4] = arr[i]
}
var gl = this.gl
var texture = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D, texture)
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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.FLOAT, buf)
return texture
}
// create a texture from a Uint8Array with RGB components
textureFromColorArray(arr: any, width: number): any {
var gl = this.gl
var texture = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D, texture)
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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, width, 1, 0, gl.RGB, gl.UNSIGNED_BYTE, arr)
return texture
}
init(): void {
this.canvas = document.getElementById("cnv") as HTMLCanvasElement
// TODO: hack
heart.canvas = this.canvas
heart.ctx = null
heart._bg = null
var gl = this.canvas.getContext("webgl") || this.canvas.getContext("experimental-webgl")
if(!gl) {
alert("error getting WebGL context")
return
}
this.gl = gl
if(!gl.getExtension("OES_texture_float"))
throw "no texture float extension"
this.gl.clearColor(0.75, 0.75, 0.75, 1.0);
this.gl.enable(this.gl.DEPTH_TEST);
this.gl.depthFunc(this.gl.LEQUAL);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
// enable alpha blending
this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
this.gl.enable(this.gl.BLEND);
// set up tile shader
this.tileShader = this.getProgram(this.gl, "2d-vertex-shader", "2d-fragment-shader")
this.gl.useProgram(this.tileShader)
// set up uniforms/attributes
this.positionLocation = gl.getAttribLocation(this.tileShader, "a_position")
this.offsetLocation = gl.getUniformLocation(this.tileShader, "u_offset")
var resolutionLocation = gl.getUniformLocation(this.tileShader, "u_resolution")
gl.uniform2f(resolutionLocation, this.canvas.width, this.canvas.height)
this.texCoordLocation = gl.getAttribLocation(this.tileShader, "a_texCoord")
this.uNumFramesLocation = gl.getUniformLocation(this.tileShader, "u_numFrames")
this.uFrameLocation = gl.getUniformLocation(this.tileShader, "u_frame")
//this.uOffsetLocation = gl.getUniformLocation(this.tileShader, "u_uOffset")
this.uScaleLocation = gl.getUniformLocation(this.tileShader, "u_scale")
// provide texture coordinates for the rectangle.
this.texCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
0.0, 1.0,
1.0, 0.0,
1.0, 1.0]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(this.texCoordLocation);
gl.vertexAttribPointer(this.texCoordLocation, 2, gl.FLOAT, false, 0, 0);
this.objectUVBuffer = gl.createBuffer()
//this.tileBuffer = this.rectangleBuffer(this.gl, 0, 0, 80, 36)
this.tileBuffer = this.rectangleBuffer(this.gl, 0, 0, 1, 1)
gl.enableVertexAttribArray(this.positionLocation);
gl.vertexAttribPointer(this.positionLocation, 2, gl.FLOAT, false, 0, 0);
// set up floor light shader
if(Config.engine.doFloorLighting) {
this.floorLightShader = this.getProgram(this.gl, "2d-vertex-shader", "2d-lighting-fragment-shader")
gl.useProgram(this.floorLightShader)
this.litOffsetLocation = gl.getUniformLocation(this.floorLightShader, "u_offset")
this.litScaleLocation = gl.getUniformLocation(this.floorLightShader, "u_scale")
this.uLightBuffer = gl.getUniformLocation(this.floorLightShader, "u_lightBuffer")
var litResolutionLocation = gl.getUniformLocation(this.floorLightShader, "u_resolution")
var litPositionLocation = gl.getAttribLocation(this.floorLightShader, "a_position")
gl.uniform2f(litResolutionLocation, this.canvas.width, this.canvas.height)
var litTexCoordLocation = gl.getAttribLocation(this.floorLightShader, "a_texCoord")
gl.enableVertexAttribArray(litTexCoordLocation);
gl.vertexAttribPointer(litTexCoordLocation, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(litPositionLocation);
gl.vertexAttribPointer(litPositionLocation, 2, gl.FLOAT, false, 0, 0);
// upload ancillery textures
this.u_colorTable = gl.getUniformLocation(this.floorLightShader, "u_colorTable")
this.u_intensityColorTable = gl.getUniformLocation(this.floorLightShader, "u_intensityColorTable")
this.u_paletteRGB = gl.getUniformLocation(this.floorLightShader, "u_paletteRGB")
// upload color tables
// TODO: have it in a typed array anyway
var _colorTable = getFileJSON("colorTable.json")
gl.activeTexture(gl.TEXTURE2)
this.textureFromArray(_colorTable)
gl.uniform1i(this.u_colorTable, 2)
// intensityColorTable
var _intensityColorTable = Lighting.intensityColorTable
var intensityColorTable = new Uint8Array(65536)
for(var i = 0; i < 65536; i++)
intensityColorTable[i] = _intensityColorTable[i]
gl.activeTexture(gl.TEXTURE3)
this.textureFromArray(intensityColorTable)
gl.uniform1i(this.u_intensityColorTable, 3)
// paletteRGB
var _colorRGB = getFileJSON("color_rgb.json")
var paletteRGB = new Uint8Array(256*3)
for(var i = 0; i < 256; i++) {
paletteRGB[i*3 + 0] = _colorRGB[i][0]
paletteRGB[i*3 + 1] = _colorRGB[i][1]
paletteRGB[i*3 + 2] = _colorRGB[i][2]
}
gl.activeTexture(gl.TEXTURE4)
this.textureFromColorArray(paletteRGB, 256)
gl.uniform1i(this.u_paletteRGB, 4)
// set up light buffer texture
gl.activeTexture(gl.TEXTURE1)
this.lightBufferTexture = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D, this.lightBufferTexture)
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.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.uniform1i(this.uLightBuffer, 1) // bind the light buffer texture to the shader
gl.activeTexture(gl.TEXTURE0)
gl.useProgram(this.tileShader)
}
}
rectangleBuffer(gl: WebGLRenderingContext, x: number, y: number, width: number, height: number) {
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
var x1 = x;
var x2 = x + width;
var y1 = y;
var y2 = y + height;
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
x1, y1,
x2, y1,
x1, y2,
x1, y2,
x2, y1,
x2, y2]), gl.STATIC_DRAW);
return buffer
}
getShader(gl: WebGLRenderingContext, id: string) {
var el: any = document.getElementById(id) // TODO
var source = el.text
var shader = gl.createShader(el.type === "x-shader/x-fragment" ? gl.FRAGMENT_SHADER : gl.VERTEX_SHADER)
gl.shaderSource(shader, source)
gl.compileShader(shader)
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log("An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader))
return null
}
return shader
}
getProgram(gl: WebGLRenderingContext, vid: string, fid: string) {
var fsh = this.getShader(gl, fid)
var vsh = this.getShader(gl, vid)
var program = gl.createProgram()
gl.attachShader(program, vsh)
gl.attachShader(program, fsh)
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.log("Unable to initialize the shader program.");
return null
}
return program
}
color(r: number, g: number, b: number, a: number=255): void {
//heart.graphics.setColor(r, g, b, a)
}
rectangle(x: number, y: number, w: number, h: number, filled: boolean=true): void {
//heart.graphics.rectangle(filled ? "fill" : "stroke", x, y, w, h)
}
text(txt: string, x: number, y: number): void {
//heart.graphics.print(txt, x, y)
}
image(img: HTMLImageElement|HeartImage, x: number, y: number, w?: number, h?: number): void {
//heart.graphics.draw(img, x, y, w, h)
}
clear(r: number, g: number, b: number): void {
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT)
}
renderLitFloor(tilemap: string[][], useColorTable: boolean=true) {
// iniitalize color tables if necessary (TODO: hack, should be initialized elsewhere)
if(useColorTable) {
if(Lighting.colorLUT === null) {
Lighting.colorLUT = getFileJSON("color_lut.json")
Lighting.colorRGB = getFileJSON("color_rgb.json")
}
}
var gl = this.gl
// use floor light shader
gl.useProgram(this.floorLightShader)
// bind buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.tileBuffer)
gl.uniform2f(this.litScaleLocation, 80, 36)
// bind light buffer texture in texture unit 0
gl.activeTexture(gl.TEXTURE1)
gl.bindTexture(gl.TEXTURE_2D, this.lightBufferTexture)
// allocate texture for tile image
//gl.activeTexture(gl.TEXTURE1)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, 80, 36, 0, gl.ALPHA, gl.FLOAT, null)
// use tile texture unit
//gl.activeTexture(gl.TEXTURE0)
// construct light buffer
var lightBuffer = new Float32Array(80*36)
var lastTexture = null
// reverse i to draw in the order Fallout 2 normally does
// otherwise there will be artifacts in the light rendering
// due to tile sizes being different and not overlapping properly
for(var i = tilemap.length - 1; i >= 0; i--) {
for(var j = 0; j < tilemap[0].length; j++) {
var tile = tilemap[j][i]
if(tile === "grid000") continue
var img = "art/tiles/" + tile
var scr = tileToScreen(i, j)
if(scr.x+TILE_WIDTH < cameraX || scr.y+TILE_HEIGHT < cameraY ||
scr.x >= cameraX+SCREEN_WIDTH || scr.y >= cameraY+SCREEN_HEIGHT)
continue
if(img !== lastTexture) {
gl.activeTexture(gl.TEXTURE0)
// TODO: uses hack
var texture = this.getTextureFromHack(img)
if(!texture) {
console.log("skipping tile without a texture: " + img)
continue
}
gl.bindTexture(gl.TEXTURE_2D, texture)
lastTexture = img
}
// compute lighting
// TODO: how correct is this?
var hex = hexFromScreen(scr.x - 13,
scr.y + 13)
var isTriangleLit = Lighting.initTile(hex)
var framebuffer
var intensity_
if(isTriangleLit)
framebuffer = Lighting.computeFrame()
// render tile
for(var y = 0; y < 36; y++) {
for(var x = 0; x < 80; x++) {
if(isTriangleLit) {
intensity_ = framebuffer[160 + 80*y + x]
}
else { // uniformly lit
intensity_ = Lighting.vertices[3]
}
// blit to the light buffer
lightBuffer[y*80 + x] = intensity_ //(x%2 && y%2) ? 0.5 : 0.25 //Math.max(0.25, intensity_/65536)
}
}
// update light buffer texture
gl.activeTexture(gl.TEXTURE1)
//gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 80, 36, 0, gl.RGBA, gl.UNSIGNED_BYTE, lightBuffer)
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 80, 36, gl.ALPHA, gl.FLOAT, lightBuffer)
// draw
gl.uniform2f(this.litOffsetLocation, scr.x - cameraX, scr.y - cameraY)
gl.drawArrays(gl.TRIANGLES, 0, 6)
}
}
gl.activeTexture(gl.TEXTURE0)
// use normal shader
gl.useProgram(this.tileShader)
}
drawTileMap(tilemap: TileMap, offsetY: number): void {
var gl = this.gl
gl.bindBuffer(gl.ARRAY_BUFFER, this.tileBuffer)
gl.uniform1f(this.uNumFramesLocation, 1)
gl.uniform1f(this.uFrameLocation, 0)
gl.uniform2f(this.uScaleLocation, 80, 36)
for(var i = 0; i < tilemap.length; i++) {
for(var j = 0; j < tilemap[0].length; j++) {
var tile = tilemap[j][i]
if(tile === "grid000") continue
var img = "art/tiles/" + tile
var scr = tileToScreen(i, j)
scr.y += offsetY
if(scr.x+TILE_WIDTH < cameraX || scr.y+TILE_HEIGHT < cameraY ||
scr.x >= cameraX+SCREEN_WIDTH || scr.y >= cameraY+SCREEN_HEIGHT)
continue
// TODO: uses hack
var texture = this.getTextureFromHack(img)
if(!texture) {
console.log("skipping tile without a texture: " + img)
continue
}
gl.bindTexture(gl.TEXTURE_2D, texture)
// draw
gl.uniform2f(this.offsetLocation, scr.x - cameraX, scr.y - cameraY)
gl.drawArrays(gl.TRIANGLES, 0, 6)
}
}
}
renderRoof(roof: TileMap): void {
this.drawTileMap(roof, -96)
}
renderFloor(floor: TileMap): void {
if(Config.engine.doFloorLighting)
this.renderLitFloor(floor)
else
this.drawTileMap(floor, 0)
}
renderObject(obj: Obj): void {
var renderInfo = this.objectRenderInfo(obj)
if(!renderInfo || !renderInfo.visible)
return
// TODO: uses hack
var texture = this.getTextureFromHack(obj.art)
if(!texture) {
console.log("no texture for object")
return
}
var gl = this.gl
// draw
gl.bindTexture(gl.TEXTURE_2D, texture)
gl.uniform1f(this.uNumFramesLocation, renderInfo.artInfo.totalFrames)
gl.uniform1f(this.uFrameLocation, renderInfo.spriteFrameNum)
gl.uniform2f(this.offsetLocation, renderInfo.x - cameraX, renderInfo.y - cameraY) // pos
gl.uniform2f(this.uScaleLocation, renderInfo.uniformFrameWidth, renderInfo.uniformFrameHeight) // size
gl.drawArrays(gl.TRIANGLES, 0, 6)
}
} | the_stack |
import {
types,
getEnv,
flow,
getRoot,
detach,
destroy,
isAlive,
Instance
} from 'mobx-state-tree';
import debounce from 'lodash/debounce';
import {ServiceStore} from './service';
import {FormItemStore, IFormItemStore, SFormItemStore} from './formItem';
import {Api, ApiObject, fetchOptions, Payload} from '../types';
import {ServerError} from '../utils/errors';
import {
getVariable,
setVariable,
deleteVariable,
cloneObject,
createObject,
difference,
guid,
isEmpty,
mapObject,
keyToPath
} from '../utils/helper';
import isEqual from 'lodash/isEqual';
import flatten from 'lodash/flatten';
import {getStoreById, removeStore} from './manager';
import {filter} from '../utils/tpl';
export const FormStore = ServiceStore.named('FormStore')
.props({
inited: false,
validated: false,
submited: false,
submiting: false,
savedData: types.frozen(),
// items: types.optional(types.array(types.late(() => FormItemStore)), []),
canAccessSuperData: true,
persistData: types.optional(types.union(types.string, types.boolean), ''),
restError: types.optional(types.array(types.string), []) // 没有映射到表达项上的 errors
})
.views(self => {
function getItems() {
const formItems: Array<IFormItemStore> = [];
// 查找孩子节点中是 formItem 的表单项
const pool = self.children.concat();
while (pool.length) {
const current = pool.shift()!;
if (current.storeType === FormItemStore.name) {
formItems.push(current);
} else {
pool.push(...current.children);
}
}
return formItems;
}
return {
get loading() {
return self.saving || self.fetching;
},
get items() {
return getItems();
},
get errors() {
let errors: {
[propName: string]: Array<string>;
} = {};
getItems().forEach(item => {
if (!item.valid) {
errors[item.name] = Array.isArray(errors[item.name])
? errors[item.name].concat(item.errors)
: item.errors.concat();
}
});
return errors;
},
getValueByName(
name: string,
canAccessSuperData = self.canAccessSuperData
) {
return getVariable(self.data, name, canAccessSuperData);
},
getPristineValueByName(name: string) {
return getVariable(self.pristine, name);
},
getItemById(id: string) {
return getItems().find(item => item.itemId === id);
},
getItemByName(name: string) {
return getItems().find(item => item.name === name);
},
getItemsByName(name: string) {
return getItems().filter(item => item.name === name);
},
get valid() {
return (
getItems().every(item => item.valid) &&
(!self.restError || !self.restError.length)
);
},
get validating() {
return getItems().some(item => item.validating);
},
get isPristine() {
return isEqual(self.pristine, self.data);
},
get modified() {
if (self.savedData) {
return self.savedData !== self.data;
}
return !this.isPristine;
},
get persistKey() {
return `${location.pathname}/${self.path}/${
typeof self.persistData === 'string'
? filter(self.persistData, self.data)
: self.persistData
}`;
}
};
})
.actions(self => {
function setValues(values: object, tag?: object, replace?: boolean) {
self.updateData(values, tag, replace);
// 如果数据域中有数据变化,就都reset一下,去掉之前残留的验证消息
self.items.forEach(item => item.reset());
// 同步 options
syncOptions();
}
function setValueByName(
name: string,
value: any,
isPristine: boolean = false,
force: boolean = false
) {
// 没有变化就不跑了。
const origin = getVariable(self.data, name, false);
const prev = self.data;
const data = cloneObject(self.data);
if (value !== origin) {
if (prev.__prev) {
// 基于之前的 __prev 改
const prevData = cloneObject(prev.__prev);
setVariable(prevData, name, origin);
Object.defineProperty(data, '__prev', {
value: prevData,
enumerable: false,
configurable: false,
writable: false
});
} else {
Object.defineProperty(data, '__prev', {
value: {...prev},
enumerable: false,
configurable: false,
writable: false
});
}
} else if (!force) {
return;
}
setVariable(data, name, value);
if (isPristine) {
const pristine = cloneObject(self.pristine);
setVariable(pristine, name, value);
self.pristine = pristine;
}
if (!data.__pristine) {
Object.defineProperty(data, '__pristine', {
value: self.pristine,
enumerable: false,
configurable: false,
writable: false
});
}
self.data = data;
// 同步 options
syncOptions();
}
function deleteValueByName(name: string) {
const prev = self.data;
const data = cloneObject(self.data);
if (prev.__prev) {
// 基于之前的 __prev 改
const prevData = cloneObject(prev.__prev);
setVariable(prevData, name, getVariable(prev, name));
Object.defineProperty(data, '__prev', {
value: prevData,
enumerable: false,
configurable: false,
writable: false
});
} else {
Object.defineProperty(data, '__prev', {
value: {...prev},
enumerable: false,
configurable: false,
writable: false
});
}
deleteVariable(data, name);
self.data = data;
}
function trimValues() {
let data = mapObject(self.data, (item: any) =>
typeof item === 'string' ? item.trim() : item
);
self.updateData(data);
}
const syncOptions = debounce(
() => self.items.forEach(item => item.syncOptions(undefined, self.data)),
250,
{
trailing: true,
leading: false
}
);
function setRestError(errors: string[]) {
self.restError.replace(errors);
}
function addRestError(msg: string | Array<string>) {
const msgs: Array<string> = Array.isArray(msg) ? msg : [msg];
msgs.forEach(msg => {
self.restError.push(msg);
});
}
function clearRestError() {
setRestError([]);
}
const saveRemote: (
api: Api,
data?: object,
options?: fetchOptions
) => Promise<any> = flow(function* saveRemote(
api: Api,
data: object,
options: fetchOptions = {}
) {
clearRestError();
try {
options = {
method: 'post', // 默认走 post
...options
};
if (options && options.beforeSend) {
let ret = options.beforeSend(data);
if (ret && ret.then) {
ret = yield ret;
}
if (ret === false) {
return;
}
}
self.markSaving(true);
const json: Payload = yield getEnv(self).fetcher(api, data, options);
// 失败也同样修改数据,如果有数据的话。
if (!isEmpty(json.data) || json.ok) {
self.updatedAt = Date.now();
setValues(
json.data,
json.ok
? {
__saved: Date.now()
}
: undefined,
!!(api as ApiObject).replaceData
);
}
if (!json.ok) {
// 验证错误
if (json.status === 422 && json.errors) {
handleRemoteError(json.errors);
self.updateMessage(
json.msg ??
self.__(options && options.errorMessage) ??
self.__('Form.validateFailed'),
true
);
} else {
self.updateMessage(
json.msg ?? self.__(options && options.errorMessage),
true
);
}
throw new ServerError(self.msg, json);
} else {
updateSavedData();
if (options && options.onSuccess) {
const ret = options.onSuccess(json);
if (ret && ret.then) {
yield ret;
}
}
self.markSaving(false);
self.updateMessage(
json.msg ?? self.__(options && options.successMessage)
);
self.msg &&
getEnv(self).notify(
'success',
self.msg,
json.msgTimeout !== undefined
? {
closeButton: true,
timeout: json.msgTimeout
}
: undefined
);
return json.data;
}
} catch (e) {
self.markSaving(false);
if (!isAlive(self) || self.disposed) {
return;
}
if (e.type === 'ServerError') {
const result = (e as ServerError).response;
getEnv(self).notify(
'error',
e.message,
result.msgTimeout !== undefined
? {
closeButton: true,
timeout: result.msgTimeout
}
: undefined
);
} else {
getEnv(self).notify('error', e.message);
}
throw e;
}
});
function handleRemoteError(errors: {[propName: string]: string}) {
Object.keys(errors).forEach((key: string) => {
const item = self.getItemById(key);
const items = self.getItemsByName(key);
if (item) {
item.setError(errors[key]);
delete errors[key];
} else if (items.length) {
// 通过 name 直接找到的
items.forEach(item => item.setError(errors[key], 'remote'));
delete errors[key];
} else {
// 尝试通过path寻找
const items = getItemsByPath(key);
if (Array.isArray(items) && items.length) {
items.forEach(item => item.setError(`${errors[key]}`));
delete errors[key];
}
}
});
// 没有映射上的error信息加在msg后显示出来
!isEmpty(errors) &&
setRestError(Object.keys(errors).map(key => String(errors[key])));
}
const getItemsByPath = (key: string) => {
const paths = keyToPath(key);
const len = paths.length;
return paths.reduce(
(stores: any[], path, idx) => {
if (Array.isArray(stores) && stores.every(s => s.getItemsByName)) {
const items = flatten(
stores.map(s => s.getItemsByName(path))
).filter(i => i);
const subStores = items
.map(item => item?.getSubStore?.())
.filter(i => i);
return subStores.length && idx < len - 1 ? subStores : items;
}
return null;
},
[self]
);
};
const submit: (
fn?: (values: object) => Promise<any>,
hooks?: Array<() => Promise<any>>,
failedMessage?: string
) => Promise<any> = flow(function* submit(
fn: any,
hooks?: Array<() => Promise<any>>,
failedMessage?: string
) {
self.submited = true;
self.submiting = true;
try {
let valid = yield validate(hooks);
// 如果不是valid,而且有包含不是remote的报错的表单项时,不可提交
if (
(!valid &&
self.items.some(item =>
item.errorData.some(e => e.tag !== 'remote')
)) ||
self.restError.length
) {
let msg = failedMessage ?? self.__('Form.validateFailed');
const env = getEnv(self);
// 同时也列出所有表单项报错,方便在很长的表单中知道是哪个字段的问题
// 支持在env中配hideValidateFailedDetail来隐藏所有表单项报错
failedMessage == null &&
!env.hideValidateFailedDetail &&
self.items.forEach(item => {
item.errorData.forEach(errorData => {
msg = `${msg}\n${errorData.msg}`;
});
});
msg && env.notify('error', msg);
throw new Error(msg);
}
if (fn) {
const diff = difference(self.data, self.pristine);
const result = yield fn(
createObject(
createObject(self.data.__super, {
diff: diff,
__diff: diff,
pristine: self.pristine
}),
self.data
)
);
return result ?? self.data;
}
return self.data;
} finally {
self.submiting = false;
}
});
const validate: (
hooks?: Array<() => Promise<any>>,
forceValidate?: boolean
) => Promise<boolean> = flow(function* validate(
hooks?: Array<() => Promise<any>>,
forceValidate?: boolean
) {
self.validated = true;
const items = self.items.concat();
for (let i = 0, len = items.length; i < len; i++) {
let item = items[i] as IFormItemStore;
// 验证过,或者是 unique 的表单项,或者强制验证,或者有远端校验api
if (
!item.validated ||
item.unique ||
forceValidate ||
!!item.validateApi
) {
yield item.validate(self.data);
}
}
if (hooks && hooks.length) {
for (let i = 0, len = hooks.length; i < len; i++) {
yield hooks[i]();
}
}
return self.valid;
});
const validateFields: (fields: Array<string>) => Promise<boolean> = flow(
function* validateFields(fields: Array<string>) {
const items = self.items.concat();
let result: Array<boolean> = [];
for (let i = 0, len = items.length; i < len; i++) {
let item = items[i] as IFormItemStore;
if (~fields.indexOf(item.name)) {
result.push(yield item.validate(self.data));
}
}
return result.every(item => item);
}
);
function clearErrors() {
const items = self.items.concat();
items.forEach(item => item.reset());
}
function reset(cb?: (data: any) => void, resetData: boolean = true) {
if (resetData) {
self.data = self.pristine;
}
// 值可能变了,重新验证一次。
self.validated = false;
self.submited = false;
self.items.forEach(item => item.reset());
cb && cb(self.data);
}
function clear(cb?: (data: any) => void) {
const toClear: any = {};
self.items.forEach(item => {
if (item.name && item.type !== 'hidden') {
setVariable(toClear, item.name, item.resetValue);
}
});
setValues(toClear);
self.validated = false;
self.submited = false;
self.items.forEach(item => item.reset());
cb && cb(self.data);
}
function setCanAccessSuperData(value: boolean = true) {
self.canAccessSuperData = value;
}
function setInited(value: boolean) {
self.inited = value;
}
function setPersistData(value = '') {
self.persistData = value;
}
const setLocalPersistData = debounce(
() => localStorage.setItem(self.persistKey, JSON.stringify(self.data)),
250,
{
trailing: true,
leading: false
}
);
function getLocalPersistData() {
let data = localStorage.getItem(self.persistKey);
if (data) {
self.updateData(JSON.parse(data));
}
}
function clearLocalPersistData() {
localStorage.removeItem(self.persistKey);
}
function updateSavedData() {
self.savedData = self.data;
}
return {
setInited,
setValues,
setValueByName,
trimValues,
submit,
validate,
validateFields,
clearErrors,
saveRemote,
reset,
syncOptions,
setCanAccessSuperData,
deleteValueByName,
getLocalPersistData,
setLocalPersistData,
clearLocalPersistData,
setPersistData,
clear,
updateSavedData,
handleRemoteError,
getItemsByPath,
setRestError,
addRestError,
clearRestError,
beforeDestroy() {
syncOptions.cancel();
setLocalPersistData.cancel();
}
};
});
export type IFormStore = Instance<typeof FormStore>;
export {IFormItemStore}; | the_stack |
import moment = require('moment');
import { browser, protractor } from 'protractor'
import { BrowserHelper, ElementHelper } from 'topcoder-testing-lib';
import * as appconfig from '../../config/app-config.json';
import { logger } from '../../logger/logger';
import TcElement from '../../node_modules/topcoder-testing-lib/dist/src/tc-element';
import { TcElementImpl } from '../../node_modules/topcoder-testing-lib/dist/src/tc-element-impl';
import { ConfigHelper } from '../../utils/config-helper';
import { LoginPageHelper } from '../login/login.helper';
/**
* Wait until condition return true
* @param func function for checking condition
* @param extraMessage extra error message when timeout
* @param isPageLoad wait for loading page
*/
const waitUntil = async (
func: () => any,
extraMessage: string,
isPageLoad: boolean
) => {
await BrowserHelper.waitUntil(
func,
isPageLoad
? appconfig.Timeout.PageLoad
: appconfig.Timeout.ElementVisibility,
(isPageLoad
? appconfig.LoggerErrors.PageLoad
: appconfig.LoggerErrors.ElementVisibilty) +
'.' +
extraMessage
);
};
const alertBoxXpath = '//div[@class="s-alert-box-inner"]/span';
const closeIconXpath = '//span[@class="s-alert-close"]';
const projectTableXpath = '//div[@class="flex-data"]';
const customerProjectsXpath = '//div[@class="project-header-details"]';
const contentWrapperXpath = '//div[@class="twoColsLayout-contentInner"]';
const milestoneXpath = "//th[contains(text(),'MILESTONE')]";
const addNewMilestonesXpath = "//button[contains(text(),'Add New Milestone')]";
export const CommonHelper = {
/**
* Log in browser
* @param username user name
* @param password password
*/
async login(username: string, password: string) {
await BrowserHelper.initialize();
await BrowserHelper.maximize();
await LoginPageHelper.open();
await LoginPageHelper.login(username, password);
},
/**
* Log out browser
*/
async logout() {
try {
await LoginPageHelper.logout();
} catch (e) {
await BrowserHelper.restart();
await this.listenersCleanup();
}
},
/**
* Wait until the element becomes visible
* @param {TcElementImpl} tcElement element
* @param {TcElementImpl} extraMessage extra message
* @param {Boolean} isPageLoad is loading page
*/
async waitUntilVisibilityOf(
func: () => TcElement,
extraMessage: string,
isPageLoad: boolean
) {
await waitUntil(
() => async () => {
try {
return await func().isDisplayed();
} catch {
// element is not attached to the DOM of a page.
return false;
}
},
extraMessage,
isPageLoad
);
},
/**
* Wait until the element is present
* @param {TcElementImpl} tcElement element
* @param {TcElementImpl} extraMessage extra message
* @param {Boolean} isPageLoad is loading page
*/
async waitUntilPresenceOf(
func: () => TcElement,
extraMessage: string,
isPageLoad: boolean
) {
await BrowserHelper.waitUntil(
() => async () => {
try {
return await func().isPresent();
} catch {
// element is not attached to the DOM of a page.
return false;
}
},
isPageLoad
? appconfig.Timeout.PageLoad
: appconfig.Timeout.ElementPresence,
(isPageLoad
? appconfig.LoggerErrors.PageLoad
: appconfig.LoggerErrors.ElementPresence) +
'.' +
extraMessage
);
},
/**
* Wait for Page to be displayed
*/
async waitForPageDisplayed() {
const rootId = ElementHelper.getElementById('root');
await CommonHelper.waitUntilVisibilityOf(
() => rootId,
'Wait for home page',
true
);
return rootId;
},
/**
* Fill Input Field with value
* @param el target element
* @param value value to fill
*/
async fillInputField(el: TcElementImpl, value: string) {
await el.click();
await el.clear();
await el.sendKeys(value);
},
/**
* Select input by its containing text
* @param text desired text value
*/
async selectInputByContainingText(text: string) {
const selectedOption = ElementHelper.getElementContainingText(text);
await selectedOption.click();
},
/**
* Get element that contain text
* @param tag tag
* @param text text contain
* @param parent parent element
*/
findElementByText(tag: string, text: string, parent?: TcElementImpl) {
return ElementHelper.getElementByXPath(
'//' + tag + '[contains(text(), "' + text + '")]',
parent
);
},
/**
* Find desired value from dropdown menu
* @param text search value
* @param parent (optional) parent element
*/
async findTextFromDropDown(text: string, parent?: TcElementImpl) {
const xpath = `//div[contains(text(), "${text}")]`;
const dropDowns = await ElementHelper.getAllElementsByXPath(xpath, parent);
return dropDowns;
},
/**
* Compare given url to current page's url
* @param url expected page url
*/
async verifyPageUrl(url: string) {
const currentUrl = await BrowserHelper.getCurrentUrl();
expect(currentUrl).toContain(url);
},
/**
* Navigate to All Projects Page
*/
async navigateToAllProjectsPage() {
await BrowserHelper.open(ConfigHelper.getAllProjectsUrl());
await CommonHelper.waitForPageDisplayed();
},
/**
* Append date time to given input text
* @param inputText input text
*/
appendDate(inputText: string) {
return `${inputText}-${moment().format()}`;
},
/**
* Get Project Title
*/
projectTitle() {
return ElementHelper.getElementByClassName('_1Iqc2q');
},
/**
* Get Page Title
*/
pageTitle() {
return ElementHelper.getElementByClassName('TopBarContainer');
},
/**
* Get Loading Indicator
*/
loadingIndicator() {
return ElementHelper.getElementByClassName('loading-indicator');
},
/**
* Get Loading Indicator
*/
get projectList() {
return ElementHelper.getElementByXPath(projectTableXpath)
},
/**
* Get Content Wrapper
*/
get contentWrapper() {
return ElementHelper.getElementByXPath(contentWrapperXpath)
},
/**
* Wait for project title to appear
*/
async waitForProjectTitle() {
await CommonHelper.waitUntilVisibilityOf(
() => this.projectTitle(),
'Wait for project title',
true
);
logger.info('My Project Page Loaded');
},
/**
* Wait for page title to appear
*/
async waitForPageTitle() {
await CommonHelper.waitUntilVisibilityOf(
() => this.pageTitle(),
'Wait for project title',
true
);
logger.info('Home Page Loaded');
},
/**
* Get recent project title element
* @param isCustomer true if current logged in user had customer role
*/
async firstProject(isCustomer = false) {
const projectClassName = isCustomer ? 'project-header-details' : 'project-title'
const titles = await ElementHelper.getAllElementsByClassName(projectClassName);
return titles[0];
},
/**
* Navigate to first Project From Dashboard
* @param isCustomer true if current logged in user had customer role
*/
async goToRecentlyCreatedProject(isCustomer = false) {
await BrowserHelper.open(ConfigHelper.getHomePageUrl());
await BrowserHelper.sleep(5000);
isCustomer ? await this.waitForCustomerProjects() : await this.waitForProjectsToGetLoaded();
const testElement = await this.firstProject(isCustomer);
await testElement.click();
},
/**
* Wait until element visibility and click
*/
async waitAndClickElement(targetEl: TcElementImpl) {
await BrowserHelper.waitUntilVisibilityOf(targetEl);
await targetEl.click();
},
/**
* Necessary input format for calendar input
*/
dateFormat() {
return '00YYYYMMDD';
},
/**
* Get Create Phase Page title
*/
get createPhasePageTitle() {
return ElementHelper.getElementByClassName('_2edGvU');
},
/**
* Wait for Page Element to be displayed
*/
async waitForElementToGetDisplayed(webElement: TcElement) {
await CommonHelper.waitUntilVisibilityOf(
() => webElement,
'Wait for Element To get Displayed',
true
);
return webElement;
},
/**
* Get Alert Box
*/
get getAlertBox() {
return ElementHelper.getElementByXPath(alertBoxXpath);
},
/**
* Checks if element is present or not on page
*
* @param identifierType Type of Identifier
* @param identifierValue Identifier Value to search
*
* @returns Either True or False
*/
async isElementPresent(identifierType: string, identifierValue: string) {
let isElementPresent = true;
let webElement: TcElementImpl;
try {
switch (identifierType.toLowerCase()) {
case 'xpath': webElement = ElementHelper.getElementByXPath(identifierValue); break;
}
const isElementDisplayed = await webElement.isDisplayed();
const isElementEnabled = await webElement.isEnabled();
isElementPresent = (isElementDisplayed && isElementEnabled) ? true : false;
} catch (error) {
isElementPresent = false;
}
return isElementPresent;
},
/**
* Get Join Project Button
*/
get joinProjectButton() {
return ElementHelper.getElementByButtonText('Join project');
},
getDate(incrementBy = 0) {
let dd: string;
let mm: string;
let yyyy: string;
const today = new Date();
if (incrementBy === 0) {
dd = today.getDate().toString();
mm = (today.getMonth() + 1).toString();
yyyy = today.getFullYear().toString();
} else {
const incrementalDate = new Date();
incrementalDate.setDate(incrementalDate.getDate() + incrementBy);
dd = incrementalDate.getDate().toString();
mm = (incrementalDate.getMonth() + 1).toString();
yyyy = incrementalDate.getFullYear().toString();
}
return [dd, mm, yyyy];
},
/**
* Checks if element is present or not on page
*
* @param identifierType Type of Identifier
* @param identifierValue Identifier Value to search
*
* @returns Either True or False
*/
async waitForElementToBeVisible(identifierType: string, identifierValue: string, verifyText = false) {
let webElement: TcElementImpl;
let count = 0;
while (true) {
try {
switch (identifierType.toLowerCase()) {
case 'xpath': webElement = ElementHelper.getElementByXPath(identifierValue); break;
}
const isElementDisplayed = await webElement.isDisplayed();
const isElementEnabled = await webElement.isEnabled();
const text = (await webElement.getText()).trim();
let textVerification = true;
if (verifyText) {
textVerification = text.length !== 0 ? true : false;
}
if (isElementDisplayed && isElementEnabled && textVerification) {
break;
}
} catch (error) {
continue;
}
if (count > appconfig.Timeout.PageLoad) {
break;
}
await BrowserHelper.sleep(100);
count++;
}
return webElement;
},
/**
* Get Alert Message And Close Popup
*
* @returns Alert Message
*/
async getAlertMessageAndClosePopup() {
await this.waitForElementToBeVisible('xpath', alertBoxXpath, true);
const message = await this.getAlertBox.getText();
try {
await ElementHelper.getElementByXPath(closeIconXpath).click();
} catch (Error) { logger.info("Popup already closed.") }
await BrowserHelper.sleep(500);
return message;
},
/**
* Matches element text from the list of elements and clicks on that element
*
* @param list List of Elements
* @param value Value to match with element text
*/
async searchTextFromListAndClick(list: any, value: string, clickUsingActions = false) {
const isClicked = false;
const size = list.length
for (let index = 0; index < size; index++) {
await list[index].getText().then(async (text: string) => {
if (text === value) {
if (clickUsingActions) {
browser.actions().mouseMove(list[index]).sendKeys(protractor.Key.ENTER).perform();
} else {
list[index].click();
}
await BrowserHelper.sleep(1000);
logger.info(`Clicked on ${value}`);
}
})
if (isClicked) {
break;
}
}
},
async waitForProjectsToGetLoaded() {
await this.waitForElementToBeVisible('xpath', projectTableXpath, true);
},
async waitForCustomerProjects() {
await this.waitForElementToBeVisible('xpath', customerProjectsXpath, true);
},
async waitForListToGetLoaded(identifierType: string, identifierValue: string, listSize = 1) {
let webElementsList: any;
let count = 0;
while (true) {
try {
switch (identifierType.toLowerCase()) {
case 'xpath': webElementsList = await ElementHelper.getAllElementsByXPath(identifierValue); break;
}
const size = await webElementsList.length;
if (size > listSize) {
break;
}
} catch (error) {
continue;
}
if (count > appconfig.Timeout.PageLoad) {
break;
}
await BrowserHelper.sleep(100);
count++;
}
},
async listenersCleanup() {
logger.info(`Running ${this.listenersCleanup.name} ...`);
const exitListeners = process.listeners("exit");
const exitListenersFn = exitListeners.map((f) => f.toString());
exitListeners.forEach((listener: any, index: number) => {
if (exitListenersFn.indexOf(listener.toString()) !== index) {
process.removeListener('exit', listener);
}
});
logger.info(`\tDone!`);
},
/**
* Wait for milestone page loads
*/
async waitForMilestones() {
await this.waitForElementToBeVisible('xpath', milestoneXpath, true);
},
/**
* Wait for add new milestones button loads
*/
async waitForAddNewMilestones() {
await this.waitForElementToBeVisible('xpath', addNewMilestonesXpath, true);
}
}; | the_stack |
import { configure } from "mobx";
import { types, Instance } from "mobx-state-tree";
import {
Field,
Form,
IAnyFormAccessor,
FieldAccessor,
RepeatingForm,
RepeatingFormAccessor,
SubForm,
converters,
} from "../src";
// "always" leads to trouble during initialization.
configure({ enforceActions: "observed" });
test("a simple warning", async () => {
const M = types.model("M", {
foo: types.string,
bar: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
bar: new Field(converters.string),
});
const o = M.create({ foo: "FOO", bar: "BAR" });
const state = form.state(o, {
backend: { save: async () => null },
getWarning: (accessor: any) =>
accessor.path === "/foo" ? "Please reconsider" : undefined,
});
const fooField = state.field("foo");
const barField = state.field("bar");
expect(fooField.raw).toEqual("FOO");
expect(fooField.isWarningFree).toBeFalsy();
expect(fooField.warning).toEqual("Please reconsider");
expect(barField.raw).toEqual("BAR");
expect(barField.isWarningFree).toBeTruthy();
expect(barField.warning).toBeUndefined();
expect(state.isWarningFree).toBeFalsy();
// warnings don't make a form invalid
const result2 = state.validate();
expect(result2).toBeTruthy();
const isSaved = await state.save();
// warnings are not cleared by a save...
expect(fooField.warning).toEqual("Please reconsider");
// ...and don't prevent a save
expect(isSaved).toBeTruthy();
});
test("a simple error", async () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
});
const o = M.create({ foo: "FOO" });
// we need to define a process as ignoreGetError is enabled automatically
// otherwise
async function process(node: Instance<typeof M>, path: string) {
return {
updates: [],
accessUpdates: [],
errorValidations: [],
warningValidations: [],
};
}
const state = form.state(o, {
backend: { save: async () => null, process },
getError: (accessor: any) =>
accessor.path === "/foo" ? "Wrong" : undefined,
});
const fooField = state.field("foo");
const result2 = state.validate();
expect(result2).toBeFalsy();
const isSaved = await state.save();
expect(fooField.raw).toEqual("FOO");
expect(fooField.error).toEqual("Wrong");
expect(state.isWarningFree).toBeTruthy();
expect(isSaved).toBeFalsy();
});
test("client side errors trumps getError", () => {
const M = types.model("M", {
foo: types.string,
});
// The validator expects "correct"
const form = new Form(M, {
foo: new Field(converters.string, {
validators: [(value) => value !== "correct" && "Wrong"],
}),
});
const o = M.create({ foo: "not correct" });
// the getErrors expects uppercase
const state = form.state(o, {
getError: (accessor: any) =>
accessor instanceof FieldAccessor &&
accessor.raw !== accessor.raw.toUpperCase()
? "Not uppercase"
: undefined,
});
const field = state.field("foo");
// The getErrors hook already fills in the error
expect(field.error).toEqual("Not uppercase");
// Form validation should trump the old error
const result1 = state.validate();
expect(field.error).toEqual("Wrong");
expect(result1).toBeFalsy();
field.setRaw("correct");
const result2 = state.validate();
// We fix one error, the other remains
expect(field.error).toEqual("Not uppercase");
expect(result2).toBeFalsy();
});
test("both errors and warnings", () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
});
const o = M.create({ foo: "FOO" });
const state = form.state(o, {
getError: (accessor: any) =>
accessor.path === "/foo" ? "Wrong" : undefined,
getWarning: (accessor: any) =>
accessor.path === "/foo" ? "Please reconsider" : undefined,
});
const fooField = state.field("foo");
expect(fooField.raw).toEqual("FOO");
expect(fooField.error).toEqual("Wrong");
expect(fooField.warning).toEqual("Please reconsider");
expect(fooField.isWarningFree).toBeFalsy();
expect(state.isWarningFree).toBeFalsy();
});
test("warning in repeating form", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.array(N),
});
const form = new Form(M, {
foo: new RepeatingForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: [{ bar: "correct" }, { bar: "incorrect" }] });
const state = form.state(o, {
getWarning: (accessor: any) =>
accessor.path === "/foo/1/bar" ? "Please reconsider" : undefined,
});
const forms = state.repeatingForm("foo");
const barField1 = forms.index(0).field("bar");
const barField2 = forms.index(1).field("bar");
expect(barField1.raw).toEqual("correct");
expect(barField1.isWarningFree).toBeTruthy();
expect(barField1.warning).toBeUndefined();
expect(barField2.raw).toEqual("incorrect");
expect(barField2.isWarningFree).toBeFalsy();
expect(barField2.warning).toEqual("Please reconsider");
expect(forms.isWarningFree).toBeFalsy();
expect(state.isWarningFree).toBeFalsy();
});
test("warning in subform field", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.string,
sub: N,
});
const form = new Form(M, {
foo: new Field(converters.string),
sub: new SubForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: "FOO", sub: { bar: "BAR" } });
const state = form.state(o, {
getWarning: (accessor: any) =>
accessor.path === "/sub/bar" ? "Please reconsider" : undefined,
});
const fooField = state.field("foo");
const subForm = state.subForm("sub");
const barField = state.subForm("sub").field("bar");
expect(fooField.raw).toEqual("FOO");
expect(fooField.isWarningFree).toBeTruthy();
expect(fooField.warning).toBeUndefined();
expect(barField.raw).toEqual("BAR");
expect(barField.isWarningFree).toBeFalsy();
expect(barField.warning).toEqual("Please reconsider");
expect(subForm.isWarningFree).toBeFalsy();
expect(state.isWarningFree).toBeFalsy();
});
test("error on repeating form", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.array(N),
});
const form = new Form(M, {
foo: new RepeatingForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: [] });
const state = form.state(o, {
getError: (accessor: any) =>
accessor instanceof RepeatingFormAccessor && accessor.length === 0
? "Empty"
: undefined,
});
const result1 = state.validate();
const repeatingForms = state.repeatingForm("foo");
expect(repeatingForms.error).toEqual("Empty");
expect(state.isWarningFree).toBeTruthy();
expect(result1).toBeFalsy();
repeatingForms.push({ bar: "BAR" });
const result2 = state.validate();
expect(repeatingForms.error).toBeUndefined();
expect(result2).toBeTruthy();
});
test("warning on repeating form", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.array(N),
});
const form = new Form(M, {
foo: new RepeatingForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: [] });
const state = form.state(o, {
getWarning: (accessor: any) => {
if (accessor instanceof RepeatingFormAccessor) {
expect(accessor.path).toEqual("/foo");
}
return accessor instanceof RepeatingFormAccessor && accessor.length === 0
? "Empty"
: undefined;
},
});
const repeatingForms = state.repeatingForm("foo");
expect(repeatingForms.isWarningFree).toBeFalsy();
expect(repeatingForms.warning).toEqual("Empty");
expect(state.isWarningFree).toBeFalsy();
repeatingForms.push({ bar: "BAR" });
state.validate();
expect(repeatingForms.isWarningFree).toBeTruthy();
expect(repeatingForms.warning).toBeUndefined();
expect(state.isWarningFree).toBeTruthy();
});
test("error on indexed repeating form", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.array(N),
});
const form = new Form(M, {
foo: new RepeatingForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: [{ bar: "correct" }, { bar: "incorrect" }] });
const state = form.state(o, {
getError: (accessor: any) =>
accessor.path === "/foo/1" ? "Error" : undefined,
});
const result = state.validate();
const forms = state.repeatingForm("foo");
const fooForm1 = forms.index(0);
const fooForm2 = forms.index(1);
expect(fooForm1.error).toBeUndefined();
expect(fooForm2.error).toEqual("Error");
expect(state.isWarningFree).toBeTruthy();
expect(result).toBeFalsy();
});
test("warning on indexed repeating form", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.array(N),
});
const form = new Form(M, {
foo: new RepeatingForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: [{ bar: "correct" }, { bar: "incorrect" }] });
const state = form.state(o, {
getWarning: (accessor: any) =>
accessor.path === "/foo/1" ? "Warning" : undefined,
});
const forms = state.repeatingForm("foo");
const fooForm1 = forms.index(0);
const fooForm2 = forms.index(1);
expect(fooForm1.isWarningFree).toBeTruthy();
expect(fooForm1.warning).toBeUndefined();
expect(fooForm2.isWarningFree).toBeFalsy();
expect(fooForm2.warning).toEqual("Warning");
expect(forms.isWarningFree).toBeFalsy();
expect(state.isWarningFree).toBeFalsy();
});
test("error on subform", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.string,
sub: N,
});
const form = new Form(M, {
foo: new Field(converters.string),
sub: new SubForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: "FOO", sub: { bar: "BAR" } });
const state = form.state(o, {
getError: (accessor: any) =>
accessor.path === "/sub" ? "Error" : undefined,
});
const result = state.validate();
const subForms = state.subForm("sub");
expect(subForms.error).toEqual("Error");
expect(state.isWarningFree).toBeTruthy();
expect(result).toBeFalsy();
});
test("warning on subform", () => {
const N = types.model("N", {
bar: types.string,
});
const M = types.model("M", {
foo: types.string,
sub: N,
});
const form = new Form(M, {
foo: new Field(converters.string),
sub: new SubForm({
bar: new Field(converters.string),
}),
});
const o = M.create({ foo: "FOO", sub: { bar: "BAR" } });
const state = form.state(o, {
getWarning: (accessor: any) =>
accessor.path === "/sub" ? "Warning" : undefined,
});
const subform = state.subForm("sub");
expect(subform.warning).toEqual("Warning");
expect(subform.isWarningFree).toBeFalsy();
expect(state.isWarningFree).toBeFalsy();
});
test("error on formstate", () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
});
const o = M.create({ foo: "FOO" });
let usedAccessor: IAnyFormAccessor | undefined = undefined;
const state = form.state(o, {
getError: (accessor: any) => {
usedAccessor = accessor;
return "Error";
},
});
const result = state.validate();
expect(state.error).toEqual("Error");
expect(state.isWarningFree).toBeTruthy();
expect(result).toBeFalsy();
expect(usedAccessor).toBe(state);
});
test("warning on formstate", () => {
const M = types.model("M", {
foo: types.string,
});
const form = new Form(M, {
foo: new Field(converters.string),
});
const o = M.create({ foo: "FOO" });
let usedAccessor: IAnyFormAccessor | undefined = undefined;
const state = form.state(o, {
getWarning: (accessor: any) => {
usedAccessor = accessor;
return "Warning";
},
});
expect(state.warning).toEqual("Warning");
expect(state.isWarningFree).toBeFalsy();
expect(usedAccessor).toBe(state);
}); | the_stack |
import { Container, DisplayObject } from '@pixi/display';
import { Renderer, MaskData } from '@pixi/core';
import { Rectangle } from '@pixi/math';
/** Interface for a child of a LinkedListContainer (has the prev/next properties added) */
export interface LinkedListChild extends DisplayObject
{
nextChild: LinkedListChild|null;
prevChild: LinkedListChild|null;
}
/**
* A semi-experimental Container that uses a doubly linked list to manage children instead of an
* array. This means that adding/removing children often is not the same performance hit that
* it would to be continually pushing/splicing.
* However, this is primarily intended to be used for heavy particle usage, and may not handle
* edge cases well if used as a complete Container replacement.
*/
export class LinkedListContainer extends Container
{
private _firstChild: LinkedListChild|null = null;
private _lastChild: LinkedListChild|null = null;
private _childCount = 0;
public get firstChild(): LinkedListChild
{
return this._firstChild;
}
public get lastChild(): LinkedListChild
{
return this._lastChild;
}
public get childCount(): number
{
return this._childCount;
}
public addChild<T extends DisplayObject[]>(...children: T): T[0]
{
// if there is only one argument we can bypass looping through the them
if (children.length > 1)
{
// loop through the array and add all children
for (let i = 0; i < children.length; i++)
{
// eslint-disable-next-line prefer-rest-params
this.addChild(children[i]);
}
}
else
{
const child = children[0] as LinkedListChild;
// if the child has a parent then lets remove it as PixiJS objects can only exist in one place
if (child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.sortDirty = true;
// ensure child transform will be recalculated
child.transform._parentID = -1;
// add to list if we have a list
if (this._lastChild)
{
this._lastChild.nextChild = child;
child.prevChild = this._lastChild;
this._lastChild = child;
}
// otherwise initialize the list
else
{
this._firstChild = this._lastChild = child;
}
// update child count
++this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange();
this.emit('childAdded', child, this, this._childCount);
child.emit('added', this);
}
return children[0];
}
public addChildAt<T extends DisplayObject>(child: T, index: number): T
{
if (index < 0 || index > this._childCount)
{
throw new Error(`addChildAt: The index ${index} supplied is out of bounds ${this._childCount}`);
}
if (child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.sortDirty = true;
// ensure child transform will be recalculated
child.transform._parentID = -1;
const c = (child as any) as LinkedListChild;
// if no children, do basic initialization
if (!this._firstChild)
{
this._firstChild = this._lastChild = c;
}
// add at beginning (back)
else if (index === 0)
{
this._firstChild.prevChild = c;
c.nextChild = this._firstChild;
this._firstChild = c;
}
// add at end (front)
else if (index === this._childCount)
{
this._lastChild.nextChild = c;
c.prevChild = this._lastChild;
this._lastChild = c;
}
// otherwise we have to start counting through the children to find the right one
// - SLOW, only provided to fully support the possibility of use
else
{
let i = 0;
let target = this._firstChild;
while (i < index)
{
target = target.nextChild;
++i;
}
// insert before the target that we found at the specified index
target.prevChild.nextChild = c;
c.prevChild = target.prevChild;
c.nextChild = target;
target.prevChild = c;
}
// update child count
++this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(index);
child.emit('added', this);
this.emit('childAdded', child, this, index);
return child;
}
/**
* Adds a child to the container to be rendered below another child.
*
* @param child The child to add
* @param relative - The current child to add the new child relative to.
* @return The child that was added.
*/
public addChildBelow<T extends DisplayObject>(child: T, relative: DisplayObject): T
{
if (relative.parent !== this)
{
throw new Error(`addChildBelow: The relative target must be a child of this parent`);
}
if (child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.sortDirty = true;
// ensure child transform will be recalculated
child.transform._parentID = -1;
// insert before the target that we were given
(relative as LinkedListChild).prevChild.nextChild = (child as any as LinkedListChild);
(child as any as LinkedListChild).prevChild = (relative as LinkedListChild).prevChild;
(child as any as LinkedListChild).nextChild = (relative as LinkedListChild);
(relative as LinkedListChild).prevChild = (child as any as LinkedListChild);
if (this._firstChild === relative)
{
this._firstChild = (child as any as LinkedListChild);
}
// update child count
++this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange();
this.emit('childAdded', child, this, this._childCount);
child.emit('added', this);
return child;
}
/**
* Adds a child to the container to be rendered above another child.
*
* @param child The child to add
* @param relative - The current child to add the new child relative to.
* @return The child that was added.
*/
public addChildAbove<T extends DisplayObject>(child: T, relative: DisplayObject): T
{
if (relative.parent !== this)
{
throw new Error(`addChildBelow: The relative target must be a child of this parent`);
}
if (child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.sortDirty = true;
// ensure child transform will be recalculated
child.transform._parentID = -1;
// insert after the target that we were given
(relative as LinkedListChild).nextChild.prevChild = (child as any as LinkedListChild);
(child as any as LinkedListChild).nextChild = (relative as LinkedListChild).nextChild;
(child as any as LinkedListChild).prevChild = (relative as LinkedListChild);
(relative as LinkedListChild).nextChild = (child as any as LinkedListChild);
if (this._lastChild === relative)
{
this._lastChild = (child as any as LinkedListChild);
}
// update child count
++this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange();
this.emit('childAdded', child, this, this._childCount);
child.emit('added', this);
return child;
}
public swapChildren(child: DisplayObject, child2: DisplayObject): void
{
if (child === child2 || child.parent !== this || child2.parent !== this)
{
return;
}
const { prevChild, nextChild } = (child as LinkedListChild);
(child as LinkedListChild).prevChild = (child2 as LinkedListChild).prevChild;
(child as LinkedListChild).nextChild = (child2 as LinkedListChild).nextChild;
(child2 as LinkedListChild).prevChild = prevChild;
(child2 as LinkedListChild).nextChild = nextChild;
if (this._firstChild === child)
{
this._firstChild = child2 as LinkedListChild;
}
else if (this._firstChild === child2)
{
this._firstChild = child as LinkedListChild;
}
if (this._lastChild === child)
{
this._lastChild = child2 as LinkedListChild;
}
else if (this._lastChild === child2)
{
this._lastChild = child as LinkedListChild;
}
this.onChildrenChange();
}
public getChildIndex(child: DisplayObject): number
{
let index = 0;
let test = this._firstChild;
while (test)
{
if (test === child)
{
break;
}
test = test.nextChild;
++index;
}
if (!test)
{
throw new Error('The supplied DisplayObject must be a child of the caller');
}
return index;
}
setChildIndex(child: DisplayObject, index: number): void
{
if (index < 0 || index >= this._childCount)
{
throw new Error(`The index ${index} supplied is out of bounds ${this._childCount}`);
}
if (child.parent !== this)
{
throw new Error('The supplied DisplayObject must be a child of the caller');
}
// remove child
if ((child as LinkedListChild).nextChild)
{
(child as LinkedListChild).nextChild.prevChild = (child as LinkedListChild).prevChild;
}
if ((child as LinkedListChild).prevChild)
{
(child as LinkedListChild).prevChild.nextChild = (child as LinkedListChild).nextChild;
}
if (this._firstChild === (child as LinkedListChild))
{
this._firstChild = (child as LinkedListChild).nextChild;
}
if (this._lastChild === (child as LinkedListChild))
{
this._lastChild = (child as LinkedListChild).prevChild;
}
(child as LinkedListChild).nextChild = null;
(child as LinkedListChild).prevChild = null;
// do addChildAt
if (!this._firstChild)
{
this._firstChild = this._lastChild = (child as LinkedListChild);
}
else if (index === 0)
{
this._firstChild.prevChild = (child as LinkedListChild);
(child as LinkedListChild).nextChild = this._firstChild;
this._firstChild = (child as LinkedListChild);
}
else if (index === this._childCount)
{
this._lastChild.nextChild = (child as LinkedListChild);
(child as LinkedListChild).prevChild = this._lastChild;
this._lastChild = (child as LinkedListChild);
}
else
{
let i = 0;
let target = this._firstChild;
while (i < index)
{
target = target.nextChild;
++i;
}
target.prevChild.nextChild = (child as LinkedListChild);
(child as LinkedListChild).prevChild = target.prevChild;
(child as LinkedListChild).nextChild = target;
target.prevChild = (child as LinkedListChild);
}
this.onChildrenChange(index);
}
public removeChild<T extends DisplayObject[]>(...children: T): T[0]
{
// if there is only one argument we can bypass looping through the them
if (children.length > 1)
{
// loop through the arguments property and remove all children
for (let i = 0; i < children.length; i++)
{
this.removeChild(children[i]);
}
}
else
{
const child = children[0] as LinkedListChild;
// bail if not actually our child
if (child.parent !== this) return null;
child.parent = null;
// ensure child transform will be recalculated
child.transform._parentID = -1;
// swap out child references
if (child.nextChild)
{
child.nextChild.prevChild = child.prevChild;
}
if (child.prevChild)
{
child.prevChild.nextChild = child.nextChild;
}
if (this._firstChild === child)
{
this._firstChild = child.nextChild;
}
if (this._lastChild === child)
{
this._lastChild = child.prevChild;
}
// clear sibling references
child.nextChild = null;
child.prevChild = null;
// update child count
--this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange();
child.emit('removed', this);
this.emit('childRemoved', child, this);
}
return children[0];
}
public getChildAt(index: number): DisplayObject
{
if (index < 0 || index >= this._childCount)
{
throw new Error(`getChildAt: Index (${index}) does not exist.`);
}
if (index === 0)
{
return this._firstChild;
}
// add at end (front)
else if (index === this._childCount)
{
return this._lastChild;
}
// otherwise we have to start counting through the children to find the right one
// - SLOW, only provided to fully support the possibility of use
let i = 0;
let target = this._firstChild;
while (i < index)
{
target = target.nextChild;
++i;
}
return target;
}
public removeChildAt(index: number): DisplayObject
{
const child = this.getChildAt(index) as LinkedListChild;
// ensure child transform will be recalculated..
child.parent = null;
child.transform._parentID = -1;
// swap out child references
if (child.nextChild)
{
child.nextChild.prevChild = child.prevChild;
}
if (child.prevChild)
{
child.prevChild.nextChild = child.nextChild;
}
if (this._firstChild === child)
{
this._firstChild = child.nextChild;
}
if (this._lastChild === child)
{
this._lastChild = child.prevChild;
}
// clear sibling references
child.nextChild = null;
child.prevChild = null;
// update child count
--this._childCount;
// ensure bounds will be recalculated
this._boundsID++;
// TODO - lets either do all callbacks or all events.. not both!
this.onChildrenChange(index);
child.emit('removed', this);
this.emit('childRemoved', child, this, index);
return child;
}
public removeChildren(beginIndex = 0, endIndex = this._childCount): DisplayObject[]
{
const begin = beginIndex;
const end = endIndex;
const range = end - begin;
if (range > 0 && range <= end)
{
const removed: LinkedListChild[] = [];
let child = this._firstChild;
for (let i = 0; i <= end && child; ++i, child = child.nextChild)
{
if (i >= begin)
{
removed.push(child);
}
}
// child before removed section
const prevChild = removed[0].prevChild;
// child after removed section
const nextChild = removed[removed.length - 1].nextChild;
if (!nextChild)
{
// if we removed the last child, then the new last child is the one before
// the removed section
this._lastChild = prevChild;
}
else
{
// otherwise, stitch the child before the section to the child after
nextChild.prevChild = prevChild;
}
if (!prevChild)
{
// if we removed the first child, then the new first child is the one after
// the removed section
this._firstChild = nextChild;
}
else
{
// otherwise stich the child after the section to the one before
prevChild.nextChild = nextChild;
}
for (let i = 0; i < removed.length; ++i)
{
// clear parenting and sibling references for all removed children
removed[i].parent = null;
if (removed[i].transform)
{
removed[i].transform._parentID = -1;
}
removed[i].nextChild = null;
removed[i].prevChild = null;
}
this._boundsID++;
this.onChildrenChange(beginIndex);
for (let i = 0; i < removed.length; ++i)
{
removed[i].emit('removed', this);
this.emit('childRemoved', removed[i], this, i);
}
return removed;
}
else if (range === 0 && this._childCount === 0)
{
return [];
}
throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
}
/**
* Updates the transform on all children of this container for rendering.
* Copied from and overrides PixiJS v5 method (v4 method is identical)
*/
updateTransform(): void
{
this._boundsID++;
this.transform.updateTransform(this.parent.transform);
// TODO: check render flags, how to process stuff here
this.worldAlpha = this.alpha * this.parent.worldAlpha;
let child;
let next;
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
if (child.visible)
{
child.updateTransform();
}
}
}
/**
* Recalculates the bounds of the container.
* Copied from and overrides PixiJS v5 method (v4 method is identical)
*/
calculateBounds(): void
{
this._bounds.clear();
this._calculateBounds();
let child;
let next;
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
if (!child.visible || !child.renderable)
{
continue;
}
child.calculateBounds();
// TODO: filter+mask, need to mask both somehow
if (child._mask)
{
const maskObject = ((child._mask as MaskData).maskObject || child._mask) as Container;
maskObject.calculateBounds();
this._bounds.addBoundsMask(child._bounds, maskObject._bounds);
}
else if (child.filterArea)
{
this._bounds.addBoundsArea(child._bounds, child.filterArea);
}
else
{
this._bounds.addBounds(child._bounds);
}
}
this._bounds.updateID = this._boundsID;
}
/**
* Retrieves the local bounds of the displayObject as a rectangle object. Copied from and overrides PixiJS v5 method
*/
public getLocalBounds(rect?: Rectangle, skipChildrenUpdate = false): Rectangle
{
// skip Container's getLocalBounds, go directly to DisplayObject
const result = DisplayObject.prototype.getLocalBounds.call(this, rect);
if (!skipChildrenUpdate)
{
let child;
let next;
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
if (child.visible)
{
child.updateTransform();
}
}
}
return result;
}
/**
* Renders the object using the WebGL renderer. Copied from and overrides PixiJS v5 method
*/
render(renderer: Renderer): void
{
// if the object is not visible or the alpha is 0 then no need to render this element
if (!this.visible || this.worldAlpha <= 0 || !this.renderable)
{
return;
}
// do a quick check to see if this element has a mask or a filter.
if (this._mask || (this.filters && this.filters.length))
{
this.renderAdvanced(renderer);
}
else
{
this._render(renderer);
let child;
let next;
// simple render children!
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
child.render(renderer);
}
}
}
/**
* Render the object using the WebGL renderer and advanced features. Copied from and overrides PixiJS v5 method
*/
protected renderAdvanced(renderer: Renderer): void
{
renderer.batch.flush();
const filters = this.filters;
const mask = this._mask;
// _enabledFilters note: As of development, _enabledFilters is not documented in pixi.js
// types but is in code of current release (5.2.4).
// push filter first as we need to ensure the stencil buffer is correct for any masking
if (filters)
{
if (!this._enabledFilters)
{
this._enabledFilters = [];
}
this._enabledFilters.length = 0;
for (let i = 0; i < filters.length; i++)
{
if (filters[i].enabled)
{
this._enabledFilters.push(filters[i]);
}
}
if (this._enabledFilters.length)
{
renderer.filter.push(this, this._enabledFilters);
}
}
if (mask)
{
renderer.mask.push(this, this._mask);
}
// add this object to the batch, only rendered if it has a texture.
this._render(renderer);
let child;
let next;
// now loop through the children and make sure they get rendered
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
child.render(renderer);
}
renderer.batch.flush();
if (mask)
{
renderer.mask.pop(this);
}
if (filters && this._enabledFilters && this._enabledFilters.length)
{
renderer.filter.pop();
}
}
/**
* Renders the object using the Canvas renderer. Copied from and overrides PixiJS Canvas mixin in V5 and V6.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
renderCanvas(renderer: any): void
{
// if not visible or the alpha is 0 then no need to render this
if (!this.visible || this.worldAlpha <= 0 || !this.renderable)
{
return;
}
if (this._mask)
{
renderer.maskManager.pushMask(this._mask);
}
(this as any)._renderCanvas(renderer);
let child;
let next;
for (child = this._firstChild; child; child = next)
{
next = child.nextChild;
(child as any).renderCanvas(renderer);
}
if (this._mask)
{
renderer.maskManager.popMask(renderer);
}
}
} | the_stack |
import WebGame = Facepunch.WebGame;
namespace Gokz {
/**
* Address hash format for the ReplayViewer.
*/
export interface IHashData {
/** Tick number, starting from 1 for the first tick. */
t?: number;
}
/**
* Creates a GOKZ replay viewer applet.
*/
export class ReplayViewer extends SourceUtils.MapViewer {
/**
* Handles a key input display overlay that also shows some stats like
* speed and sync.
*/
readonly keyDisplay: KeyDisplay;
/**
* Handles replay controls such as a playback bar.
*/
readonly controls: ReplayControls;
/**
* Handles options menu.
*/
readonly options: OptionsMenu;
/**
* The URL to look for exported maps at. The directory at the URL
* should contain sub-folders for each map, inside each of which is the
* index.json for that map.
* @example `viewer.mapBaseUrl = "http://my-website.com/maps";`
*/
mapBaseUrl: string;
/**
* The currently loaded replay. Will be automatically set after a
* replay is loaded with `loadReplay(url)`. You can also set this
* manually to switch between replays.
*/
replay: ReplayFile;
/**
* If true, the current tick will be stored in the address hash when
* playback is paused or the viewer uses the playback bar to skip
* around.
* @default `true`
*/
saveTickInHash = true;
/**
* The current tick being shown during playback, starting with 0 for
* the first tick. Will automatically be increased while playing,
* although some ticks might be skipped depending on playback speed and
* frame rate. Can be set to skip to a particular tick.
*/
tick = -1;
/**
* Current playback rate, measured in seconds per second. Can support
* negative values for rewinding.
* @default `1.0`
*/
playbackRate = 1.0;
/**
* If true, the replay will automatically loop back to the first tick
* when it reaches the end.
* @default `true`
*/
autoRepeat = true;
/**
* Used internally to temporarily pause playback while the user is
* dragging the scrubber in the playback bar.
*/
isScrubbing = false;
/**
* If true, the currently displayed tick will advance based on the
* value of `playbackRate`.
* @default `false`
*/
isPlaying = false;
/**
* If true, a crosshair graphic will be displayed in the middle of the
* viewer.
* @default `true`
*/
showCrosshair = true;
/**
* If true, makes the key press display visible.
* @default `true`
*/
showKeyDisplay = true;
/**
* If true, makes the options menu visible.
* @default `false`
*/
showOptions = false;
/**
* Event invoked when a new replay is loaded. Will be invoked before
* the map for the replay is loaded (if required).
*
* **Available event arguments**:
* * `replay: Gokz.ReplayFile` - The newly loaded ReplayFile
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly replayLoaded = new Event<ReplayFile, ReplayViewer>(this);
/**
* Event invoked after each update.
*
* **Available event arguments**:
* * `dt: number` - Time since the last update
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly updated = new Event<number, ReplayViewer>(this);
/**
* Event invoked when the current tick has changed.
*
* **Available event arguments**:
* * `tickData: Gokz.TickData` - Recorded data for the current tick
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly tickChanged = new ChangedEvent<number, TickData, ReplayViewer>(this);
/**
* Event invoked when playback has skipped to a different tick, for
* example when the user uses the scrubber.
*
* **Available event arguments**:
* * `oldTick: number` - The previous value of `tick` before skipping
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly playbackSkipped = new Event<number, ReplayViewer>(this);
/**
* Event invoked when `playbackRate` changes.
*
* **Available event arguments**:
* * `playbackRate: number` - The new playback rate
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly playbackRateChanged = new ChangedEvent<number, number, ReplayViewer>(this);
/**
* Event invoked when `isPlaying` changes, for example when the user
* pauses or resumes playback.
*
* **Available event arguments**:
* * `isPlaying: boolean` - True if currently playing
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly isPlayingChanged = new ChangedEvent<boolean, boolean, ReplayViewer>(this);
/**
* Event invoked when `showCrosshair` changes.
*
* **Available event arguments**:
* * `showCrosshair: boolean` - True if crosshair is now visible
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly showCrosshairChanged = new ChangedEvent<boolean, boolean, ReplayViewer>(this);
/**
* Event invoked when `showKeyDisplay` changes.
*
* **Available event arguments**:
* * `showKeyDisplay: boolean` - True if keyDisplay is now visible
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly showKeyDisplayChanged = new ChangedEvent<boolean, boolean, ReplayViewer>(this);
/**
* Event invoked when `showOptions` changes.
*
* **Available event arguments**:
* * `showOptions: boolean` - True if options menu is now visible
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly showOptionsChanged = new ChangedEvent<boolean, boolean, ReplayViewer>(this);
/**
* Event invoked when `cameraMode` changes.
*
* **Available event arguments**:
* * `cameraMode: SourceUtils.CameraMode` - Camera mode value
* * `sender: Gokz.ReplayViewer` - This ReplayViewer
*/
readonly cameraModeChanged = new ChangedEvent<SourceUtils.CameraMode, SourceUtils.CameraMode, ReplayViewer>(this);
private messageElem: HTMLElement;
private lastReplay: ReplayFile;
private currentMapName: string;
private pauseTime = 1.0;
private pauseTicks: number;
private wakeLock: any;
private spareTime = 0;
private prevTick: number = undefined;
private tickData = new TickData();
private tempTickData0 = new TickData();
private tempTickData1 = new TickData();
private tempTickData2 = new TickData();
private routeLine: RouteLine;
/**
* Creates a new ReplayViewer inside the given `container` element.
* @param container Element that should contain the viewer.
*/
constructor(container: HTMLElement) {
super(container);
this.saveCameraPosInHash = false;
this.controls = new ReplayControls(this);
this.keyDisplay = new KeyDisplay(this, this.controls.playbackBarElem);
this.options = new OptionsMenu(this, this.controls.playbackBarElem);
const crosshair = document.createElement("div");
crosshair.classList.add("crosshair");
container.appendChild(crosshair);
this.showCrosshairChanged.addListener(showCrosshair => {
crosshair.hidden = !showCrosshair;
});
this.isPlayingChanged.addListener(isPlaying => {
if (!isPlaying && this.saveTickInHash) this.updateTickHash();
if (isPlaying) {
this.wakeLock = (navigator as any).wakeLock;
if (this.wakeLock != null) {
this.wakeLock.request("display");
}
this.cameraMode = SourceUtils.CameraMode.Fixed;
} else if (this.wakeLock != null) {
this.wakeLock.release("display");
this.wakeLock = null;
}
});
this.cameraModeChanged.addListener(mode => {
if (mode === SourceUtils.CameraMode.FreeCam) {
this.isPlaying = false;
}
if (this.routeLine != null) {
this.routeLine.visible = mode === SourceUtils.CameraMode.FreeCam;
}
this.canLockPointer = mode === SourceUtils.CameraMode.FreeCam;
if (!this.canLockPointer && this.isPointerLocked()) {
document.exitPointerLock();
}
});
}
/**
* Used to display an error message in the middle of the viewer.
* @param message Message to display
*/
showMessage(message: string): void {
if (this.messageElem === undefined) {
this.messageElem = this.onCreateMessagePanel();
}
if (this.messageElem == null) return;
this.messageElem.innerText = message;
}
/**
* Attempt to load a GOKZ replay from the given URL. When loaded, the
* replay will be stored in the `replay` property in this viewer.
* @param url Url of the replay to download.
*/
loadReplay(url: string): void {
console.log(`Downloading: ${url}`);
const req = new XMLHttpRequest();
req.open("GET", url, true);
req.responseType = "arraybuffer";
req.onload = ev => {
if (req.status !== 200) {
this.showMessage(`Unable to download replay: ${req.statusText}`);
return;
}
const arrayBuffer = req.response;
if (arrayBuffer) {
if (this.routeLine != null) {
this.routeLine.dispose();
this.routeLine = null;
}
try {
this.replay = new ReplayFile(arrayBuffer);
} catch (e) {
this.showMessage(`Unable to read replay: ${e}`);
}
}
};
req.send(null);
}
/**
* If `saveTickInHash` is true, will set the address hash to include
* the current tick number.
*/
updateTickHash(): void {
if (this.replay == null || !this.saveTickInHash) return;
this.setHash({ t: this.replay.clampTick(this.tick) + 1 });
}
protected onCreateMessagePanel(): HTMLElement {
const elem = document.createElement("div");
elem.classList.add("message");
this.container.appendChild(elem);
return elem;
}
protected onInitialize(): void {
super.onInitialize();
this.canLockPointer = false;
this.cameraMode = SourceUtils.CameraMode.Fixed;
}
protected onHashChange(hash: string | Object): void {
if (typeof hash === "string") return;
if (!this.saveTickInHash) return;
const data = hash as IHashData;
if (data.t !== undefined && this.tick !== data.t) {
this.tick = data.t - 1;
this.isPlaying = false;
}
}
private ignoreMouseUp = true;
protected onMouseDown(button: WebGame.MouseButton, screenPos: Facepunch.Vector2, target: EventTarget): boolean {
this.ignoreMouseUp = event.target !== this.canvas;
if (super.onMouseDown(button, screenPos, target)) {
this.showOptions = false;
return true;
}
return false;
}
protected onMouseUp(button: WebGame.MouseButton, screenPos: Facepunch.Vector2, target: EventTarget): boolean {
const ignored = this.ignoreMouseUp || event.target !== this.canvas;
this.ignoreMouseUp = true;
if (ignored) return false;
if (this.controls.hideSpeedControl() || this.showOptions) {
this.showOptions = false;
return true;
}
if (super.onMouseUp(button, screenPos, target)) return true;
if (button === WebGame.MouseButton.Left && this.replay != null && this.map.isReady()) {
this.isPlaying = !this.isPlaying;
return true;
}
return false;
}
protected onKeyDown(key: WebGame.Key): boolean {
switch (key) {
case WebGame.Key.X:
this.cameraMode = this.cameraMode === SourceUtils.CameraMode.FreeCam
? SourceUtils.CameraMode.Fixed : SourceUtils.CameraMode.FreeCam;
if (this.cameraMode === SourceUtils.CameraMode.FreeCam) {
this.container.requestPointerLock();
}
return true;
case WebGame.Key.F:
this.toggleFullscreen();
return true;
case WebGame.Key.Space:
if (this.replay != null && this.map.isReady()) {
this.isPlaying = !this.isPlaying;
}
return true;
}
return super.onKeyDown(key);
}
protected onChangeReplay(replay: ReplayFile): void {
this.pauseTicks = Math.round(replay.tickRate * this.pauseTime);
this.tick = this.tick === -1 ? 0 : this.tick;
this.spareTime = 0;
this.prevTick = undefined;
this.replayLoaded.dispatch(this.replay);
if (this.currentMapName !== replay.mapName) {
if (this.currentMapName != null) {
this.map.unload();
}
if (this.mapBaseUrl == null) {
throw "Cannot load a map when mapBaseUrl is unspecified.";
}
const version = new Date().getTime().toString(16);
this.currentMapName = replay.mapName;
this.loadMap(`${this.mapBaseUrl}/${replay.mapName}/index.json?v=${version}`);
}
}
protected onUpdateFrame(dt: number): void {
super.onUpdateFrame(dt);
if (this.replay != this.lastReplay) {
this.lastReplay = this.replay;
if (this.replay != null) {
this.onChangeReplay(this.replay);
}
}
this.showCrosshairChanged.update(this.showCrosshair);
this.showKeyDisplayChanged.update(this.showKeyDisplay);
this.showOptionsChanged.update(this.showOptions);
this.playbackRateChanged.update(this.playbackRate);
this.cameraModeChanged.update(this.cameraMode);
if (this.replay == null) {
this.updated.dispatch(dt);
return;
}
const replay = this.replay;
const tickPeriod = 1.0 / replay.tickRate;
this.isPlayingChanged.update(this.isPlaying);
if (this.prevTick !== undefined && this.tick !== this.prevTick) {
this.playbackSkipped.dispatch(this.prevTick);
}
if (this.routeLine == null && this.map.isReady()) {
this.routeLine = new RouteLine(this.map, this.replay);
}
if (this.map.isReady() && this.isPlaying && !this.isScrubbing) {
this.spareTime += dt * this.playbackRate;
const oldTick = this.tick;
// Forward playback
while (this.spareTime > tickPeriod) {
this.spareTime -= tickPeriod;
this.tick += 1;
if (this.tick > replay.tickCount + this.pauseTicks * 2) {
this.tick = -this.pauseTicks;
}
}
// Rewinding
while (this.spareTime < 0) {
this.spareTime += tickPeriod;
this.tick -= 1;
if (this.tick < -this.pauseTicks * 2) {
this.tick = replay.tickCount + this.pauseTicks;
}
}
} else {
this.spareTime = 0;
}
this.prevTick = this.tick;
replay.getTickData(replay.clampTick(this.tick), this.tickData);
let eyeHeight = this.tickData.getEyeHeight();
this.tickChanged.update(this.tick, this.tickData);
if (this.spareTime >= 0 && this.spareTime <= tickPeriod) {
const t = this.spareTime / tickPeriod;
const d0 = replay.getTickData(replay.clampTick(this.tick - 1), this.tempTickData0);
const d1 = this.tickData;
const d2 = replay.getTickData(replay.clampTick(this.tick + 1), this.tempTickData1);
const d3 = replay.getTickData(replay.clampTick(this.tick + 2), this.tempTickData2);
Utils.hermitePosition(d0.position, d1.position,
d2.position, d3.position, t, this.tickData.position);
Utils.hermiteAngles(d0.angles, d1.angles,
d2.angles, d3.angles, t, this.tickData.angles);
eyeHeight = Utils.hermiteValue(
d0.getEyeHeight(), d1.getEyeHeight(),
d2.getEyeHeight(), d3.getEyeHeight(), t);
}
if (this.cameraMode === SourceUtils.CameraMode.Fixed) {
this.mainCamera.setPosition(
this.tickData.position.x,
this.tickData.position.y,
this.tickData.position.z + eyeHeight);
this.setCameraAngles(
(this.tickData.angles.y - 90) * Math.PI / 180,
-this.tickData.angles.x * Math.PI / 180);
}
this.updated.dispatch(dt);
}
}
} | the_stack |
import { EventEmitter, Injectable } from '@angular/core'
import { EnumValues, MathUtils } from '@app/class'
import { ElectronProvider } from '@app/provider/electron.provider'
import { GameLogService } from '@app/service/game-log.service'
import { IpcMain, IpcMainEvent, IpcRenderer } from 'electron'
import moment from 'moment'
import { forkJoin } from 'rxjs'
import { TradeRegexesProvider } from '../../provider/trade-regexes.provider'
import { ItemCategory, Language } from '../../type'
import {
ExampleNotificationType,
MAX_STASH_SIZE,
TradeNotification,
TradeNotificationType
} from '../../type/trade-companion.type'
import { BaseItemTypesService } from '../base-item-types/base-item-types.service'
import { ClientStringService } from '../client-string/client-string.service'
import { CurrencyService } from '../currency/currency.service'
const LOGLINE_DATE_FORMAT = 'YYYY/MM/DD HH:mm:ss'
const FROM_TO_PLACEHOLDER = '{fromto}'
const ADD_EXAMPLE_TRADE_NOTIFICATION_KEY = 'trade-notification-add-example'
const MAP_GENERATION_ID = 10
const MAP_TIER_REGEXES: LangRegExp[] = [
{ language: Language.English, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.Portuguese, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.Russian, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.Thai, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.German, regex: new RegExp('\\(Lvl (?<tier>\\S+)\\)') },
{ language: Language.French, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.Spanish, regex: new RegExp('\\(G(?<tier>\\S+)\\)') },
{ language: Language.Korean, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
{ language: Language.TraditionalChinese, regex: new RegExp('\\(T(?<tier>\\S+)\\)') },
]
const TIERLESS_MAPS = ['MapWorldsChimera', 'MapWorldsHydra', 'MapWorldsMinotaur', 'MapWorldsPhoenix']
interface TradeRegexes {
whisper: RegExp
itemTradeOffer: LangRegExp[]
currencyTradeOffer: LangRegExp[]
playerJoinedArea: LangRegExp[]
playerLeftArea: LangRegExp[]
}
interface LangRegExp {
language: Language
regex: RegExp
}
@Injectable({
providedIn: 'root',
})
export class TradeNotificationsService {
public readonly notificationAddedOrChanged = new EventEmitter<TradeNotification>()
private readonly tradeRegexes: TradeRegexes
private readonly languages = new EnumValues(Language)
private ipcMain: IpcMain
private ipcRenderer: IpcRenderer
private notifications: TradeNotification[] = []
private scopedAddExampleNotificationEvent
constructor(
electronProvider: ElectronProvider,
tradeRegexesProvider: TradeRegexesProvider,
private readonly gameLogService: GameLogService,
private readonly currencyService: CurrencyService,
private readonly baseItemTypesService: BaseItemTypesService,
private readonly clientString: ClientStringService
) {
this.ipcMain = electronProvider.provideIpcMain()
this.ipcRenderer = electronProvider.provideIpcRenderer()
this.gameLogService.logLineAdded.subscribe((logLine: string) => this.onLogLineAdded(logLine))
// Init regexes
const tradeRegexStrings = tradeRegexesProvider.provide()
this.tradeRegexes = {
whisper: new RegExp(tradeRegexStrings.all + tradeRegexStrings.whisper, 'i'),
itemTradeOffer: [],
currencyTradeOffer: [],
playerJoinedArea: [],
playerLeftArea: [],
}
for (const key in tradeRegexStrings.tradeItemPrice) {
const regex = tradeRegexStrings.tradeItemPrice[key]
this.tradeRegexes.itemTradeOffer.push({
language: this.languages.values[key],
regex: new RegExp(regex, 'i'),
})
}
for (const key in tradeRegexStrings.tradeBulk) {
const regex = tradeRegexStrings.tradeBulk[key]
this.tradeRegexes.currencyTradeOffer.push({
language: this.languages.values[key],
regex: new RegExp(regex, 'i'),
})
}
for (const key in tradeRegexStrings.joinedArea) {
const regex = tradeRegexStrings.joinedArea[key]
this.tradeRegexes.playerJoinedArea.push({
language: this.languages.values[key],
regex: new RegExp(tradeRegexStrings.all + regex, 'i'),
})
}
for (const key in tradeRegexStrings.leftArea) {
const regex = tradeRegexStrings.leftArea[key]
this.tradeRegexes.playerLeftArea.push({
language: this.languages.values[key],
regex: new RegExp(tradeRegexStrings.all + regex, 'i'),
})
}
}
/**
* Call this method only from the main window
*/
public registerEvents(): void {
if (!this.scopedAddExampleNotificationEvent) {
this.scopedAddExampleNotificationEvent = (event, exampleNotificationType) =>
this.onAddExampleNotification(event, exampleNotificationType)
this.ipcMain.on(ADD_EXAMPLE_TRADE_NOTIFICATION_KEY, this.scopedAddExampleNotificationEvent)
}
}
/**
* Call this method only from the main window
*/
public unregisterEvents(): void {
this.ipcMain.removeListener(
ADD_EXAMPLE_TRADE_NOTIFICATION_KEY,
this.scopedAddExampleNotificationEvent
)
}
/**
* Call this method only from the settings window
*/
public addExampleTradeNotification(exampleNotificationType: ExampleNotificationType): void {
this.ipcRenderer.send(ADD_EXAMPLE_TRADE_NOTIFICATION_KEY, exampleNotificationType)
}
public dismissNotification(notification: TradeNotification): void {
this.notifications = this.notifications.filter((tn) => tn !== notification)
}
private addNotification(notification: TradeNotification): void {
this.notifications.push(notification)
this.notificationAddedOrChanged.emit(notification)
}
private onLogLineAdded(logLine: string): void {
if (this.tradeRegexes.whisper.test(logLine)) {
const whisperMatch = this.tradeRegexes.whisper.exec(logLine)
const whisperMessage = whisperMatch.groups.message
for (const langRegex of this.tradeRegexes.itemTradeOffer) {
if (langRegex.regex.test(whisperMessage)) {
this.parseItemTradeWhisper(
whisperMatch,
langRegex.regex.exec(whisperMessage),
langRegex.language
)
return
}
}
for (const langRegex of this.tradeRegexes.currencyTradeOffer) {
if (langRegex.regex.test(whisperMessage)) {
this.parseCurrencyTradeWhisper(
whisperMatch,
langRegex.regex.exec(whisperMessage),
langRegex.language
)
return
}
}
} else {
for (const langRegex of this.tradeRegexes.playerJoinedArea) {
if (langRegex.regex.test(logLine)) {
this.parsePlayerJoinedArea(langRegex.regex.exec(logLine))
return
}
}
for (const langRegex of this.tradeRegexes.playerLeftArea) {
if (langRegex.regex.test(logLine)) {
this.parsePlayerLeftArea(langRegex.regex.exec(logLine))
return
}
}
}
}
private parsePlayerJoinedArea(whisperMatch: RegExpMatchArray): void {
const playerName = whisperMatch.groups.player
this.notifications
.filter(
(notification) =>
notification.playerName === playerName &&
!notification.playerInHideout &&
!notification.playerLeftHideout
)
.forEach((notification) => {
notification.playerInHideout = true
this.notificationAddedOrChanged.emit(notification)
})
}
private parsePlayerLeftArea(whisperMatch: RegExpMatchArray): void {
const playerName = whisperMatch.groups.player
this.notifications
.filter(
(notification) =>
notification.playerName === playerName &&
notification.playerInHideout &&
!notification.playerLeftHideout
)
.forEach((notification) => {
notification.playerInHideout = false
notification.playerLeftHideout = true
this.notificationAddedOrChanged.emit(notification)
})
}
private parseCurrencyTradeWhisper(
whisperMatch: RegExpMatchArray,
tradeMatch: RegExpMatchArray,
tradeLanguage: Language
): void {
const whisperGroups = whisperMatch.groups
const tradeGroups = tradeMatch.groups
const playerName = whisperGroups.player
const currencyID = tradeGroups.name
const offerItemID = tradeGroups.currency
const fullWhisper = `@${playerName} ${whisperGroups.message}`
const whisperTime = moment(whisperGroups.timestamp, LOGLINE_DATE_FORMAT)
const notificationType = whisperGroups.from
? TradeNotificationType.Incoming
: TradeNotificationType.Outgoing
const notification = this.notifications.find(
(x) => x.type === notificationType && x.text === fullWhisper
)
if (notification) {
// Repeated whisper -> Reset timer
notification.time = whisperTime
this.notificationAddedOrChanged.emit(notification)
return
}
forkJoin([
this.currencyService.searchByNameType(currencyID, tradeLanguage),
this.currencyService.searchByNameType(offerItemID, tradeLanguage),
]).subscribe((currencies) => {
const currency = currencies[0] || {
id: currencyID,
nameType: currencyID,
image: null,
}
const offerCurrency = currencies[1] || {
id: offerItemID,
nameType: offerItemID,
image: null,
}
currency.image = currency.image || this.getImageUrl(currencyID, tradeLanguage)
offerCurrency.image = offerCurrency.image || this.getImageUrl(offerItemID, tradeLanguage)
const notification: TradeNotification = {
text: fullWhisper,
type: notificationType,
time: whisperTime,
playerName,
item: {
amount: +tradeGroups.count,
currency,
},
price: {
amount: +tradeGroups.price,
currency: offerCurrency,
},
offer: tradeGroups.message,
}
this.addNotification(notification)
})
}
private parseItemTradeWhisper(
whisperMatch: RegExpMatchArray,
tradeMatch: RegExpMatchArray,
tradeLanguage: Language
): void {
const whisperGroups = whisperMatch.groups
const tradeGroups = tradeMatch.groups
const currencyID = tradeGroups.currency
const playerName = whisperGroups.player
const fullWhisper = `@${playerName} ${whisperGroups.message}`
const whisperTime = moment(whisperGroups.timestamp, LOGLINE_DATE_FORMAT)
const notificationType = whisperGroups.from
? TradeNotificationType.Incoming
: TradeNotificationType.Outgoing
const notification = this.notifications.find(
(x) => x.type === notificationType && x.text === fullWhisper
)
if (notification) {
// Repeated whisper -> Reset timer
notification.time = whisperTime
this.notificationAddedOrChanged.emit(notification)
return
}
this.currencyService.searchById(currencyID, tradeLanguage).subscribe((currency) => {
currency = currency || {
id: currencyID,
nameType: currencyID,
image: null,
}
currency.image = currency.image || this.getImageUrl(currencyID, tradeLanguage)
const itemName = tradeGroups.name
const baseItemType = this.baseItemTypesService.search(itemName, tradeLanguage).baseItemType
const notification: TradeNotification = {
text: fullWhisper,
type: notificationType,
time: whisperTime,
playerName,
item: itemName,
price: {
amount: +tradeGroups.price,
currency,
},
itemLocation: {
tabName: tradeGroups.stash,
bounds: {
x: MathUtils.clamp(+tradeGroups.left, 1, MAX_STASH_SIZE),
y: MathUtils.clamp(+tradeGroups.top, 1, MAX_STASH_SIZE),
width: baseItemType?.width ?? 1,
height: baseItemType?.height ?? 1,
},
},
offer: tradeGroups.message,
}
this.addNotification(notification)
})
}
private getImageUrl(item: string, language: Language): string {
const result = this.baseItemTypesService.search(item, language)
const baseItemType = result?.baseItemType
if (!baseItemType) {
return null
}
switch (baseItemType.category) {
case ItemCategory.Card:
return '/image/Art/2DItems/Divination/InventoryIcon.png?w=1&h=1&scale=1'
case ItemCategory.Prophecy:
return '/image/Art/2DItems/Currency/ProphecyOrbRed.png?w=1&h=1&scale=1'
case ItemCategory.Map:
if (!baseItemType.artName) {
return null
}
// Check for map tier
const tierRegex = MAP_TIER_REGEXES.find((x) => x.language === language)?.regex
const tierMatch = tierRegex?.exec(item)
let tier = tierMatch?.groups?.tier ?? 0
if (TIERLESS_MAPS.indexOf(result.id) !== -1) {
tier = 0
}
// Check for blighted map
let blighted = ''
const blightedMapItemNameDisplay = this.clientString
.translate('InfectedMap')
.replace('{0}', baseItemType.names[language])
if (item.startsWith(blightedMapItemNameDisplay)) {
blighted = '&mb=1'
}
return `/image/${baseItemType.artName}.png?w=1&h=1&scale=1&mn=${MAP_GENERATION_ID}&mt=${tier}${blighted}`
}
return null
}
private onAddExampleNotification(
event: IpcMainEvent,
exampleNotificationType: ExampleNotificationType
): void {
let logLine: string
switch (exampleNotificationType) {
case ExampleNotificationType.Item:
// 2021/04/16 17:04:56 26257593 bb3 [INFO Client 24612] @From FakePlayerName: Hi, I would like to buy your level 14 0% Steelskin listed for 1 alch in Standard (stash tab "~price 1 alch #2"; position: left 3, top 9) -- Offer 1c?
logLine = `${moment().format(
LOGLINE_DATE_FORMAT
)} 12345678 bb3 [INFO Client 12345] @${FROM_TO_PLACEHOLDER} FakePlayerName: Hi, I would like to buy your level 14 0% Steelskin listed for 1 alch in Standard (stash tab "~price 1 alch #2"; position: left 3, top 9) -- Offer 1c?`
break
case ExampleNotificationType.Currency:
// 2021/04/16 15:48:55 12345678 bb3 [INFO Client 12345] @From FakePlayerName: Hi, I'd like to buy your 1 Exalted Orb for my 100 Chaos Orb in Standard. -- Offer 95c?
logLine = `${moment().format(
LOGLINE_DATE_FORMAT
)} 12345678 bb3 [INFO Client 12345] @${FROM_TO_PLACEHOLDER} FakePlayerName: Hi, I'd like to buy your 1 Exalted Orb for my 100 Chaos Orb in Standard. -- Offer 95c?`
break
default:
return
}
this.onLogLineAdded(logLine.replace(FROM_TO_PLACEHOLDER, 'To'))
this.onLogLineAdded(logLine.replace(FROM_TO_PLACEHOLDER, 'From'))
}
} | the_stack |
import { ArrayHelper, StringHelper } from "../ExtensionMethods";
import { BasePropertySet } from "../Enumerations/BasePropertySet";
import { BodyType } from "../Enumerations/BodyType";
import { Dictionary } from "../AltDictionary";
import { EwsLogging } from "../Core/EwsLogging";
import { EwsServiceXmlWriter } from "./EwsServiceXmlWriter";
import { EwsUtilities } from "./EwsUtilities";
import { ExchangeVersion } from "../Enumerations/ExchangeVersion";
import { IEnumerable } from "../Interfaces/IEnumerable";
import { ISelfValidate } from "../Interfaces/ISelfValidate";
import { LazyMember } from "./LazyMember";
import { PropertyDefinition } from "../PropertyDefinitions/PropertyDefinition";
import { PropertyDefinitionBase } from "../PropertyDefinitions/PropertyDefinitionBase";
import { PropertyDefinitionFlags } from "../Enumerations/PropertyDefinitionFlags";
import { ServiceObjectType } from "../Enumerations/ServiceObjectType";
import { ServiceRequestBase } from "./Requests/ServiceRequestBase";
import { ServiceValidationException } from "../Exceptions/ServiceValidationException";
import { ServiceVersionException } from "../Exceptions/ServiceVersionException";
import { Strings } from "../Strings";
import { XmlAttributeNames } from "../Core/XmlAttributeNames";
import { XmlElementNames } from "../Core/XmlElementNames";
import { XmlNamespace } from "../Enumerations/XmlNamespace";
export type DefaultPropertySetDictionary = LazyMember<Dictionary<BasePropertySet, string>>;
/**
* Represents a set of item or folder properties. Property sets are used to indicate what properties of an item or folder should be loaded when binding to an existing item or folder or when loading an item or folder's properties.
*
* @sealed
*/
export class PropertySet implements ISelfValidate, IEnumerable<PropertyDefinitionBase> {
/**
* Returns a predefined property set that only includes the Id property.
*/
static readonly IdOnly: PropertySet = PropertySet.CreateReadonlyPropertySet(BasePropertySet.IdOnly);
/**
* Returns a predefined property set that includes the first class properties of an item or folder.
*/
static readonly FirstClassProperties: PropertySet = PropertySet.CreateReadonlyPropertySet(BasePropertySet.FirstClassProperties);
/**
* Maps BasePropertySet values to EWS's BaseShape values.
*/
private static defaultPropertySetMap: DefaultPropertySetDictionary = new LazyMember<Dictionary<BasePropertySet, string>>(() => {
let result: Dictionary<BasePropertySet, string> = new Dictionary<BasePropertySet, string>((bps) => BasePropertySet[bps]);
result.Add(BasePropertySet.IdOnly, "IdOnly");
result.Add(BasePropertySet.FirstClassProperties, "AllProperties");
return result;
});
/**
* The base property set this property set is based upon.
*/
private basePropertySet: BasePropertySet = BasePropertySet.IdOnly;
/**
* The list of additional properties included in this property set.
*/
private additionalProperties: PropertyDefinitionBase[] = [];
/**
* The requested body type for get and find operations. If null, the "best body" is returned.
*/
private requestedBodyType: BodyType = null; //nullable
/**
* The requested unique body type for get and find operations. If null, the should return the same value as body type.
*/
private requestedUniqueBodyType: BodyType = null; //nullable
/**
* The requested normalized body type for get and find operations. If null, the should return the same value as body type.
*/
private requestedNormalizedBodyType: BodyType = null; //nullable
/**
* Value indicating whether or not the server should filter HTML content.
*/
private filterHtml: boolean = null; //nullable
/**
* Value indicating whether or not the server should convert HTML code page to UTF8.
*/
private convertHtmlCodePageToUTF8: boolean = null; //nullable
/**
* Value of the URL template to use for the src attribute of inline IMG elements.
*/
private inlineImageUrlTemplate: string = null;
/**
* Value indicating whether or not the server should block references to external images.
*/
private blockExternalImages: boolean = null; //nullable
/**
* Value indicating whether or not to add a blank target attribute to anchor links.
*/
private addTargetToLinks: boolean = null; //nullable
/**
* Value indicating whether or not this PropertySet can be modified.
*/
private isReadOnly: boolean = false;
/**
* Value indicating the maximum body size to retrieve.
*/
private maximumBodySize: number = null; //nullable
/**
* @internal Maps BasePropertySet values to EWS's BaseShape values.
*/
static get DefaultPropertySetMap(): DefaultPropertySetDictionary {
return this.defaultPropertySetMap;
}
/**
* Gets or sets the base property set the property set is based upon.
*/
get BasePropertySet(): BasePropertySet {
return this.basePropertySet;
}
set BasePropertySet(value) {
this.ThrowIfReadonly();
this.basePropertySet = value;
}
/**
* Gets or sets type of body that should be loaded on items. If RequestedBodyType is null, body is returned as HTML if available, plain text otherwise.
*
* @Nullable
*/
get RequestedBodyType(): BodyType {
return this.requestedBodyType;
}
set RequestedBodyType(value) {
this.ThrowIfReadonly();
this.requestedBodyType = value;
}
/**
* Gets or sets type of body that should be loaded on items. If null, the should return the same value as body type.
*
* @nullable
*/
get RequestedUniqueBodyType(): BodyType {
return this.requestedUniqueBodyType;
}
set RequestedUniqueBodyType(value) {
this.ThrowIfReadonly();
this.requestedUniqueBodyType = value;
}
/**
* Gets or sets type of normalized body that should be loaded on items. If null, the should return the same value as body type.
*
* @nullable
*/
get RequestedNormalizedBodyType(): BodyType {
return this.requestedNormalizedBodyType;
}
set RequestedNormalizedBodyType(value) {
this.ThrowIfReadonly();
this.requestedNormalizedBodyType = value;
}
/**
* Gets the number of explicitly added properties in this set.
*/
get Count(): number {
return this.additionalProperties.length;
}
/**
* Gets or sets value indicating whether or not to filter potentially unsafe HTML content from message bodies.
*
* @nullable
*/
get FilterHtmlContent(): boolean {
return this.filterHtml;
}
set FilterHtmlContent(value) {
this.ThrowIfReadonly();
this.filterHtml = value;
}
/**
* Gets or sets value indicating whether or not to convert HTML code page to UTF8 encoding.
*
* @nullable
*/
get ConvertHtmlCodePageToUTF8(): boolean {
return this.convertHtmlCodePageToUTF8;
}
set ConvertHtmlCodePageToUTF8(value) {
this.ThrowIfReadonly();
this.convertHtmlCodePageToUTF8 = value;
}
/**
* Gets or sets a value of the URL template to use for the src attribute of inline IMG elements.
*
* @nullable
*/
get InlineImageUrlTemplate(): string {
return this.inlineImageUrlTemplate;
}
set InlineImageUrlTemplate(value) {
this.ThrowIfReadonly();
this.inlineImageUrlTemplate = value;
}
/**
* Gets or sets value indicating whether or not to convert inline images to data URLs.
*
* @nullable
*/
get BlockExternalImages(): boolean {
return this.blockExternalImages;
}
set BlockExternalImages(value) {
this.ThrowIfReadonly();
this.blockExternalImages = value;
}
/**
* Gets or sets value indicating whether or not to add blank target attribute to anchor links.
*
* @nullable
*/
get AddBlankTargetToLinks(): boolean {
return this.addTargetToLinks;
}
set AddBlankTargetToLinks(value) {
this.ThrowIfReadonly();
this.addTargetToLinks = value;
}
/**
* Gets or sets the maximum size of the body to be retrieved.
*
* @nullable
*
* @value The maximum size of the body to be retrieved.
*/
get MaximumBodySize(): number {
return this.maximumBodySize;
}
set MaximumBodySize(value) {
this.ThrowIfReadonly();
this.maximumBodySize = value;
}
/**
* Initializes a new instance of **PropertySet** based upon BasePropertySet.IdOnly.
*/
constructor();
/**
* Initializes a new instance of **PropertySet** based upon BasePropertySet.IdOnly.
*
* @param {BasePropertySet} basePropertySet The base property set to base the property set upon.
*/
constructor(basePropertySet: BasePropertySet);
/**
* Initializes a new instance of **PropertySet** based upon BasePropertySet.IdOnly.
*
* @param {PropertyDefinitionBase[]} additionalProperties Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)
*/
constructor(additionalProperties: PropertyDefinitionBase[]);
/**
* Initializes a new instance of **PropertySet**.
*
* @param {PropertyDefinitionBase[]} additionalProperties Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)
*/
constructor(...additionalProperties: PropertyDefinitionBase[]);
/**
* Initializes a new instance of **PropertySet**.
*
* @param {BasePropertySet} basePropertySet The base property set to base the property set upon.
* @param {PropertyDefinitionBase[]} additionalProperties Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)
*/
constructor(basePropertySet: BasePropertySet, additionalProperties: PropertyDefinitionBase[]);
/**
* Initializes a new instance of **PropertySet**.
*
* @param {BasePropertySet} basePropertySet The base property set to base the property set upon.
* @param {PropertyDefinitionBase[]} additionalProperties Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)
*/
constructor(basePropertySet: BasePropertySet, ...additionalProperties: PropertyDefinitionBase[]);
constructor(basePropertySetOrAdditionalProperties: BasePropertySet | PropertyDefinitionBase | PropertyDefinitionBase[] = null, _additionalProperties: PropertyDefinitionBase | PropertyDefinitionBase[] = null) {
let argsLength = arguments.length;
let basePropertySet: BasePropertySet = BasePropertySet.IdOnly;
let additionalProperties: PropertyDefinitionBase[] = [];
if (argsLength >= 1) {
if (typeof basePropertySetOrAdditionalProperties === 'number') {
basePropertySet = basePropertySetOrAdditionalProperties;
}
else if (ArrayHelper.isArray(basePropertySetOrAdditionalProperties)) {
additionalProperties = basePropertySetOrAdditionalProperties;
}
else {
additionalProperties = [basePropertySetOrAdditionalProperties];
}
}
if (argsLength >= 2) {
if (ArrayHelper.isArray(_additionalProperties)) {
additionalProperties = _additionalProperties;
}
else {
additionalProperties.push(_additionalProperties);
}
}
if (argsLength > 2) {
for (var _i = 2; _i < arguments.length; _i++) {
additionalProperties.push(arguments[_i]);
}
}
this.basePropertySet = basePropertySet;
if (additionalProperties.length > 0) {
this.additionalProperties = additionalProperties;
//ArrayHelper.AddRange(this.additionalProperties, <any>additionalProperties);
//this.additionalProperties.push.apply(this.additionalProperties, additionalProperties); //todo: addrange for array - http://typescript.codeplex.com/workitem/1422
}
}
/**
* Gets the **PropertyDefinitionBase** at the specified index. this[int] indexer
*
* @param {number} index Index.
*/
_getItem(index: number): PropertyDefinitionBase {
return this.additionalProperties[index];
}
/**
* Adds the specified property to the property set.
*
* @param {PropertyDefinitionBase} property The property to add.
*/
Add(property: PropertyDefinitionBase): void {
this.ThrowIfReadonly();
EwsUtilities.ValidateParam(property, "property");
if (this.additionalProperties.indexOf(property) === -1) {
this.additionalProperties.push(property);
}
}
/**
* Adds the specified properties to the property set.
*
* @param {PropertyDefinitionBase[]} properties The properties to add.
*/
AddRange(properties: PropertyDefinitionBase[]): void {
this.ThrowIfReadonly();
EwsUtilities.ValidateParamCollection(properties, "properties");
for (let property of properties) {
this.Add(property);
}
}
/**
* Remove all explicitly added properties from the property set.
*/
Clear(): void {
this.ThrowIfReadonly();
this.additionalProperties.splice(0);
}
/**
* Determines whether the specified property has been explicitly added to this property set using the Add or AddRange methods.
*
* @param {PropertyDefinitionBase} property The property.
* @return {boolean} true if this property set contains the specified propert]; otherwise, false.
*/
Contains(property: PropertyDefinitionBase): boolean { return this.additionalProperties.indexOf(property) !== -1; }
/**
* Creates a read-only PropertySet.
*
* @param {BasePropertySet} basePropertySet The base property set.
* @return {PropertySet} PropertySet
*/
private static CreateReadonlyPropertySet(basePropertySet: BasePropertySet): PropertySet {
let propertySet: PropertySet = new PropertySet(basePropertySet);
propertySet.isReadOnly = true;
return propertySet;
}
/**
* Returns an enumerator that iterates through the collection. this case this.additionalProperties itself
*/
GetEnumerator(): PropertyDefinitionBase[] {
return this.additionalProperties;
}
/**
* Gets the name of the shape.
*
* @param {ServiceObjectType} serviceObjectType Type of the service object.
* @return {string} Shape name.
*/
private static GetShapeName(serviceObjectType: ServiceObjectType): string {
switch (serviceObjectType) {
case ServiceObjectType.Item:
return XmlElementNames.ItemShape;
case ServiceObjectType.Folder:
return XmlElementNames.FolderShape;
case ServiceObjectType.Conversation:
return XmlElementNames.ConversationShape;
default:
EwsLogging.Assert(
false,
"PropertySet.GetShapeName",
StringHelper.Format("An unexpected object type {0} for property shape. This code path should never be reached.", serviceObjectType));
return StringHelper.Empty;
}
}
/**
* @internal Validates this property set.
*/
InternalValidate(): void {
for (let i = 0; i < this.additionalProperties.length; i++) {
if (this.additionalProperties[i] == null) {
throw new ServiceValidationException(StringHelper.Format(Strings.AdditionalPropertyIsNull, i));
}
}
}
/**
* Removes the specified property from the set.
*
* @param {PropertyDefinitionBase} property The property to remove.
* @return {boolean} true if the property was successfully removed, false otherwise.
*/
Remove(property: PropertyDefinitionBase): boolean {
this.ThrowIfReadonly();
return ArrayHelper.RemoveEntry(this.additionalProperties, property);
}
/**
* Throws if readonly property set.
*/
private ThrowIfReadonly(): void {
if (this.isReadOnly) {
throw new Error(" PropertySet can not be modified");// System.NotSupportedException(Strings.PropertySetCannotBeModified);
}
}
/**
* Implements ISelfValidate.Validate. Validates this property set.
*/
Validate(): void {
this.InternalValidate();
}
/**
* @internal Validates this property set instance for request to ensure that:
* 1. Properties are valid for the request server version.
* 2. If only summary properties are legal for this request (e.g. FindItem) then only summary properties were specified.
*
* @param {ServiceRequestBase} request The request.
* @param {boolean} summaryPropertiesOnly if set to true then only summary properties are allowed.
*/
ValidateForRequest(request: ServiceRequestBase, summaryPropertiesOnly: boolean): void {
for (let propDefBase of this.additionalProperties) {
//let propDefBase: PropertyDefinitionBase = propItem;
let propertyDefinition = <PropertyDefinition>propDefBase;
if (propertyDefinition instanceof PropertyDefinition/* != null*/) {
if (propertyDefinition.Version > request.Service.RequestedServerVersion) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
propertyDefinition.Name,
ExchangeVersion[propertyDefinition.Version]));
}
if (summaryPropertiesOnly && !propertyDefinition.HasFlag(PropertyDefinitionFlags.CanFind, request.Service.RequestedServerVersion)) {
throw new ServiceValidationException(
StringHelper.Format(
Strings.NonSummaryPropertyCannotBeUsed,
propertyDefinition.Name,
request.GetXmlElementName()));
}
}
}
if (this.FilterHtmlContent/*.HasValue*/) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"FilterHtmlContent",
ExchangeVersion[ExchangeVersion.Exchange2010]));
}
}
if (this.ConvertHtmlCodePageToUTF8/*.HasValue*/) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010_SP1) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"ConvertHtmlCodePageToUTF8",
ExchangeVersion[ExchangeVersion.Exchange2010_SP1]));
}
}
if (!StringHelper.IsNullOrEmpty(this.InlineImageUrlTemplate)) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"InlineImageUrlTemplate",
ExchangeVersion[ExchangeVersion.Exchange2013]));
}
}
if (this.BlockExternalImages/*.HasValue*/) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"BlockExternalImages",
ExchangeVersion[ExchangeVersion.Exchange2013]));
}
}
if (this.AddBlankTargetToLinks/*.HasValue*/) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"AddTargetToLinks",
ExchangeVersion[ExchangeVersion.Exchange2013]));
}
}
if (this.MaximumBodySize/*.HasValue*/) {
if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.PropertyIncompatibleWithRequestVersion,
"MaximumBodySize",
ExchangeVersion[ExchangeVersion.Exchange2013]));
}
}
}
/**
* @internal Writes additonal properties to XML.
*
* @param {EwsServiceXmlWriter} writer The writer to write to.
* @param {PropertyDefinitionBase[]} propertyDefinitions The property definitions to write.
*/
static WriteAdditionalPropertiesToXml(writer: EwsServiceXmlWriter, propertyDefinitions: PropertyDefinitionBase[]): void {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties);
for (let propertyDefinition of propertyDefinitions) {
propertyDefinition.WriteToXml(writer);
}
writer.WriteEndElement();
}
/**
* @internal Writes the property set to XML.
*
* @param {EwsServiceXmlWriter} writer The writer to write to.
* @param {ServiceObjectType} serviceObjectType The type of service object the property set is emitted for.
*/
WriteToXml(writer: EwsServiceXmlWriter, serviceObjectType: ServiceObjectType): void {
let shapeElementName: string = PropertySet.GetShapeName(serviceObjectType);
writer.WriteStartElement(XmlNamespace.Messages, shapeElementName);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.BaseShape,
PropertySet.defaultPropertySetMap.Member.get(this.BasePropertySet));
if (serviceObjectType == ServiceObjectType.Item) {
if (this.RequestedBodyType/*.HasValue*/) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.BodyType,
BodyType[this.RequestedBodyType]/*.Value*/);
}
if (this.RequestedUniqueBodyType/*.HasValue*/) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.UniqueBodyType,
BodyType[this.RequestedUniqueBodyType]/*.Value*/);
}
if (this.RequestedNormalizedBodyType/*.HasValue*/) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.NormalizedBodyType,
BodyType[this.RequestedNormalizedBodyType]/*.Value*/);
}
if (this.FilterHtmlContent/*.HasValue*/) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.FilterHtmlContent,
this.FilterHtmlContent/*.Value*/);
}
if (this.ConvertHtmlCodePageToUTF8/*.HasValue*/ &&
writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP1) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.ConvertHtmlCodePageToUTF8,
this.ConvertHtmlCodePageToUTF8/*.Value*/);
}
if (!StringHelper.IsNullOrEmpty(this.InlineImageUrlTemplate) &&
writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.InlineImageUrlTemplate,
this.InlineImageUrlTemplate);
}
if (this.BlockExternalImages/*.HasValue*/ &&
writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.BlockExternalImages,
this.BlockExternalImages/*.Value*/);
}
if (this.AddBlankTargetToLinks/*.HasValue*/ &&
writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.AddBlankTargetToLinks,
this.AddBlankTargetToLinks/*.Value*/);
}
if (this.MaximumBodySize/*.HasValue*/ &&
writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) {
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.MaximumBodySize,
this.MaximumBodySize/*.Value*/);
}
}
if (this.additionalProperties.length > 0) {
PropertySet.WriteAdditionalPropertiesToXml(writer, this.additionalProperties);
}
writer.WriteEndElement(); // Item/FolderShape
}
} | the_stack |
import { SpreadsheetHelper } from "../util/spreadsheethelper.spec";
import { defaultData } from '../util/datasource.spec';
import { SheetModel, getRangeAddress, Spreadsheet, getCell } from "../../../src/index";
import { L10n } from '@syncfusion/ej2-base';
describe('Cell Format ->', () => {
let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet');
describe('API ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], rows: [{ cells:[{ style: { fontSize: '9pt', fontFamily: 'Georgia', fontWeight: 'normal', fontStyle: 'normal', textAlign: 'left' } }] }] }], cellStyle: { fontSize: '14pt', fontFamily: 'Courier', fontWeight: 'bold', fontStyle: 'italic', textAlign: 'center' } }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('', (done: Function) => {
let td: HTMLElement = helper.invoke('getCell', [0, 0]);
expect(td.style.fontSize).toBe('9pt');
expect(td.style.fontFamily).toBe('Georgia');
expect(td.style.fontWeight).toBe('normal');
expect(td.style.fontStyle).toBe('normal');
expect(td.style.textAlign).toBe('left');
td = helper.invoke('getCell', [0, 1]);
expect(td.style.fontSize).toBe('14pt');
expect(td.style.fontFamily).toBe('Courier');
expect(td.style.fontWeight).toBe('bold');
expect(td.style.fontStyle).toBe('italic');
expect(td.style.textAlign).toBe('center');
done();
});
});
describe('public method ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Border', (done: Function) => {
helper.invoke('cellFormat', [{ border: '1px solid #000' }, 'A1']);
let td: HTMLElement = helper.invoke('getCell', [0, 0]);
expect(td.style.borderWidth).toBe('1px');
expect(td.style.borderStyle).toBe('solid');
expect(td.style.borderColor).toBe('rgb(0, 0, 0)');
helper.invoke('cellFormat', [{ border: '1px solid red' }, 'C1']);
td = helper.invoke('getCell', [0, 2]);
expect(td.style.borderTop).toBe('1px solid red');
expect(td.style.borderRight).toBe('1px solid red');
expect(td.style.borderBottom).toBe('1px solid red');
expect(td.style.borderLeft).toBe('');
expect(helper.invoke('getCell', [0, 1]).style.borderRight).toBe('1px solid red');
helper.invoke('cellFormat', [{ border: '2px solid #eb4034' }, 'B5']);
td = helper.invoke('getCell', [4, 1]);
expect(td.style.borderTop).toBe('');
expect(td.style.borderLeft).toBe('');
expect(td.style.borderRight).toBe('2px solid rgb(235, 64, 52)');
expect(td.style.borderBottom).toBe('2px solid rgb(235, 64, 52)');
expect(helper.invoke('getCell', [3, 1]).style.borderBottom).toBe('2px solid rgb(235, 64, 52)');
expect(helper.invoke('getCell', [4, 0]).style.borderRight).toBe('2px solid rgb(235, 64, 52)');
done();
});
it('Border are not removed after undo when selection is in reverse', (done: Function) => {
helper.invoke('selectRange', ['D3:C2']);
helper.click('#spreadsheet_borders');
helper.click('.e-borders-menu ul li:nth-child(5)');
helper.click('#spreadsheet_undo');
expect(helper.invoke('getCell', [1, 3]).style.borderRight).toBe('');
expect(helper.invoke('getCell', [2, 3]).style.borderRight).toBe('');
expect(helper.invoke('getCell', [2, 3]).style.borderBottom).toBe('');
expect(helper.invoke('getCell', [2, 2]).style.borderBottom).toBe('');
done();
});
});
describe('CR-Issues ->', () => {
describe('fb22572 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ cellStyle: { fontSize: '8pt' }, sheets: [{ rows: [{ index: 3, cells:
[{ index: 3, value: 'test' }] }], selectedRange: 'D4' }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Cell size is getting changed after applying border', (done: Function) => {
helper.getElement('#' + helper.id + '_borders').click();
helper.getElement('.e-menu-item[aria-label="Outside Borders"]').click();
expect(helper.getInstance().sheets[0].rows[2]).toBeNull();
expect(helper.getInstance().sheets[0].rows[3].height).toBeUndefined();
expect(helper.invoke('getRow', [2]).style.height).toBe('20px');
expect(helper.invoke('getRow', [3]).style.height).toBe('20px');
done();
});
});
describe('fb21556, fb21625 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: 'Item Name' }] }] }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
// it('When wrap text is applied to the cell, horizontal/vertical alignment is not working properly', (done: Function) => {
// helper.invoke('setRowHeight', [100]);
// helper.invoke('setColWidth', [150]);
// helper.getElement('#' + helper.id + '_wrap').click();
// helper.getElement('#' + helper.id + '_vertical_align').click();
// helper.getElement('#' + helper.id + '_vertical_align-popup .e-item:nth-child(2)').click();
// const wrapContent: HTMLElement = helper.invoke('getCell', [0, 0]).querySelector('.e-wrap-content');
// expect(getComputedStyle(wrapContent).bottom).toBe('33px');
// expect(getComputedStyle(wrapContent).transform).toBe('matrix(1, 0, 0, 1, 0, -8.5)');
// expect(getComputedStyle(wrapContent).left).toBe('0px');
// helper.getElement('#' + helper.id + '_vertical_align').click();
// helper.getElement('#' + helper.id + '_vertical_align-popup .e-item').click();
// expect(getComputedStyle(wrapContent).transform).toBe('none');
// expect(getComputedStyle(wrapContent).top).toBe('0px');
// helper.getElement('#' + helper.id + '_wrap').click();
// done();
// });
});
describe('SF-356947 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ index: 3, height: 30, customHeight: true, cells: [{ index: 3, value: 'test' }] }],
selectedRange: 'D4' }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Selection issue while apply font size as 72pt for whole column with custom height enabled', (done: Function) => {
const cell: HTMLElement = helper.invoke('getCell', [3, 3]);
expect(cell.style.lineHeight).toBe('');
helper.getElement('#' + helper.id + '_font_size').click();
helper.getElement('#' + helper.id + '_font_size-popup').firstElementChild.lastElementChild.click();
expect(cell.style.fontSize).toBe('72pt');
expect(cell.style.lineHeight).toBe('29px');
expect(helper.invoke('getRow', [3]).style.height).toBe('30px');
helper.getElement('#' + helper.id + '_font_size').click();
helper.getElement('#' + helper.id + '_font_size-popup').firstElementChild.children[5].click();
expect(cell.style.fontSize).toBe('14pt');
expect(cell.style.lineHeight).toBe('');
helper.getElement('#' + helper.id + '_font_size').click();
helper.getElement('#' + helper.id + '_font_size-popup').firstElementChild.children[13].click();
expect(cell.style.fontSize).toBe('36pt');
expect(cell.style.lineHeight).toBe('29px');
helper.getElement('#' + helper.id + '_wrap').click();
expect(cell.style.lineHeight).toBe('');
expect(cell.querySelector('.e-wrap-content')).not.toBeNull();
done();
});
});
describe('EJ2-57647 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Used range not updated while Clear entire data.', (done: Function) => {
let spreadsheet: Spreadsheet = helper.getInstance();
let sheet: SheetModel = spreadsheet.sheets[0];
spreadsheet.clear({type: 'Clear All', range: getRangeAddress([0, 0, sheet.usedRange.rowIndex, sheet.usedRange.colIndex])});
setTimeout(() => {
expect(sheet.usedRange.rowIndex).toEqual(0);
expect(sheet.usedRange.colIndex).toEqual(0);
done();
});
});
it('Used range not updated while delete entire data.', (done: Function) => {
let spreadsheet: Spreadsheet = helper.getInstance();
let sheet: SheetModel = spreadsheet.sheets[0];
spreadsheet.selectRange(getRangeAddress([0, 0, sheet.usedRange.rowIndex, sheet.usedRange.colIndex]));
helper.triggerKeyNativeEvent(46);
setTimeout(() => {
expect(sheet.usedRange.rowIndex).toEqual(0);
expect(sheet.usedRange.colIndex).toEqual(0);
done();
});
});
});
describe('EJ2-57647 ->', () => {
let sheets: SheetModel[];
L10n.load({
'de-DE': {
'spreadsheet': {
"Clear": "klar",
"ClearContents": "Inhalt löschen",
"ClearAll": "Alles löschen",
"ClearFormats": "Formate löschen",
"ClearHyperlinks": "Löschen Sie Hyperlinks",
}
}
});
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }], locale: 'de-DE' }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Clear Hyperlink', (done: Function) => {
helper.invoke('insertHyperlink', [{ address: 'www.google.com' }, 'Sheet1!A7', 'Test', false]);
helper.invoke('selectRange', ['A7:A7']);
helper.click('#spreadsheet_clear');
helper.click('#spreadsheet_clear-popup ul li:nth-child(4)');
sheets = helper.getInstance().sheets;
setTimeout(() => {
expect(getCell(6, 0, sheets[0]).hyperlink).toBeUndefined();
let td: HTMLElement = helper.invoke('getCell', [6, 0]);
expect(helper.invoke('getCell', [6, 0]).children.length).toBe(0);
done();
});
});
it('Clear Formats', (done: Function) => {
helper.invoke('cellFormat', [{ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' }, 'A1:F1']);
helper.invoke('selectRange', ['A1:A1']);
helper.click('#spreadsheet_clear');
helper.click('#spreadsheet_clear-popup ul li:nth-child(2)');
sheets = helper.getInstance().sheets;
setTimeout(() => {
expect(getCell(0, 0, sheets[0]).format).toBeUndefined();
expect(helper.invoke('getCell', [0, 0]).style.fontWeight).toBe('');
done();
});
});
it('Clear Contents', (done: Function) => {
helper.invoke('selectRange', ['D3:D3']);
helper.click('#spreadsheet_clear');
helper.click('#spreadsheet_clear-popup ul li:nth-child(3)');
sheets = helper.getInstance().sheets;
setTimeout(() => {
expect(getCell(2, 3, sheets[0]).value).toBeUndefined();
expect(helper.invoke('getCell', [2, 3]).textContent).toBe('');
done();
});
});
it('Clear All', (done: Function) => {
helper.invoke('insertHyperlink', [{ address: 'www.google.com' }, 'Sheet1!A4', 'Test', false]);
helper.invoke('selectRange', ['A1:C6']);
helper.click('#spreadsheet_clear');
helper.click('#spreadsheet_clear-popup ul li:nth-child(1)');
sheets = helper.getInstance().sheets;
setTimeout(() => {
expect(getCell(2, 0, sheets[0]).value).toBeUndefined();
expect(helper.invoke('getCell', [2, 0]).textContent).toBe('');
expect(getCell(0, 4, sheets[0]).format).toBeUndefined();
expect(helper.invoke('getCell', [0, 4]).style.fontWeight).toBe('');
expect(getCell(3, 0, sheets[0]).hyperlink).toBeUndefined();
let td: HTMLElement = helper.invoke('getCell', [6, 0]);
expect(helper.invoke('getCell', [3, 0]).children.length).toBe(0);
done();
});
});
});
});
}); | the_stack |
import arrify = require('arrify');
import * as escapeStringRegexp from 'escape-string-regexp';
import * as is from 'is';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const isUtf8 = require('is-utf8');
import {Mutation} from './mutation';
/**
* @private
*/
export class FilterError extends Error {
constructor(filter: string) {
super();
this.name = 'FilterError';
this.message = `Unknown filter: ${filter}.`;
}
}
export interface Column {
name?: string | RegExp;
cellLimit?: number;
start?: BoundData;
end?: {};
family?: BoundData;
}
export interface BoundData {
inclusive?: boolean;
value?: {};
}
export interface Time {
start: Date | number;
end: Date | number;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type RawFilter = any;
export interface Condition {
pass: {};
fail: {};
test: {};
}
export interface Row {
cellLimit?: number;
sample?: string;
cellOffset?: number;
key?: string;
}
export interface ValueFilter {
value?: string;
start?: BoundData;
end?: BoundData;
strip?: boolean;
}
/**
* A filter takes a row as input and produces an alternate view of the row based
* on specified rules. For example, a row filter might trim down a row to
* include just the cells from columns matching a given regular expression, or
* might return all the cells of a row but not their values. More complicated
* filters can be composed out of these components to express requests such as,
* "within every column of a particular family, give just the two most recent
* cells which are older than timestamp X."
*
* There are two broad categories of filters (true filters and transformers),
* as well as two ways to compose simple filters into more complex ones
* ({@link Filter#interleave}). They work as follows:
*
* True filters alter the input row by excluding some of its cells wholesale
* from the output row. An example of a true filter is the
* {@link Filter#value} filter, which excludes cells whose values
* don't match the specified pattern. All regex true filters use RE2 syntax
* (https://github.com/google/re2/wiki/Syntax) and are evaluated as full
* matches. An important point to keep in mind is that RE2(.) is equivalent by
* default to RE2([^\n]), meaning that it does not match newlines. When
* attempting to match an arbitrary byte, you should therefore use the escape
* sequence '\C', which may need to be further escaped as '\\C' in your client
* language.
*
* Transformers alter the input row by changing the values of some of its
* cells in the output, without excluding them completely. Currently, the only
* supported transformer is the {@link Filter#value} `strip` filter,
* which replaces every cell's value with the empty string.
*
* The total serialized size of a filter message must not
* exceed 4096 bytes, and filters may not be nested within each other to a depth
* of more than 20.
*
* Use the following table for the various examples found throughout the
* filter documentation.
*
* | Row Key | follows:gwashington | follows:jadams | follows:tjefferson |
* | ----------- |:-------------------:|:--------------:|:------------------:|
* | gwashington | | 1 | |
* | tjefferson | 1 | 1 | |
* | jadams | 1 | | 1 |
*
* @class
*/
export class Filter {
filters_: Array<{[index: string]: {}}> = [];
constructor() {
this.filters_ = [];
}
/**
* @throws TypeError
*
* Transforms Arrays into a simple regular expression for matching multiple
* values.
*
* @param {regex|string|string[]} regex Either a plain regex, a regex in
* string form or an array of strings.
*
* @returns {string}
*
* @example
* ```
* const regexString = Filter.convertToRegExpString(['a', 'b', 'c']);
* // => '(a|b|c)'
* ```
*/
static convertToRegExpString(
regex:
| RegExp
| RegExp[]
| string
| string[]
| Buffer
| Buffer[]
| number
| number[]
): string | Buffer {
if (is.regexp(regex)) {
return regex.toString().replace(/^\/|\/$/g, '');
}
if (Array.isArray(regex)) {
return `(${(regex as string[])
.map(Filter.convertToRegExpString)
.join('|')})`;
}
if (typeof regex === 'string') {
return regex;
}
if (typeof regex === 'number') {
return regex.toString();
}
if (Buffer.isBuffer(regex)) {
const encodingToUse = isUtf8(regex) ? 'utf8' : 'binary';
const regexToEscape = regex.toString(encodingToUse);
const escapedString = escapeStringRegexp(regexToEscape);
return Buffer.from(escapedString, encodingToUse);
}
throw new TypeError("Can't convert to RegExp String from unknown type.");
}
/**
* Creates a range object. All bounds default to inclusive.
*
* @param {?object|string} start Lower bound value.
* @param {?object|string} end Upper bound value.
* @param {string} key Key used to create range value keys.
*
* @returns {object}
*
* @example
* ```
* const {Bigtable} = require('@google-cloud/bigtable');
* const Filter = Bigtable.Filter;
*
* const range = Filter.createRange('value1', 'value2', 'Test');
* // {
* // startTestInclusive: new Buffer('value1'),
* // endTestExclusive: new Buffer('value2')
* // }
*
* //-
* // It's also possible to pass in objects to specify inclusive/exclusive
* // bounds.
* //-
* const upperBound = {
* value: 'value3',
* inclusive: false
* };
*
* const range = Filter.createRange(upperBound, null, 'Test2');
* // => {
* // startTest2Exclusive: 'value3'
* // }
* ```
*/
static createRange(
start: BoundData | null,
end: BoundData | null,
key: string
) {
const range = {};
if (start) {
Object.assign(range, createBound('start', start, key));
}
if (end) {
Object.assign(range, createBound('end', end, key));
}
return range;
function createBound(boundName: string, boundData: BoundData, key: string) {
const isInclusive = boundData.inclusive !== false;
const boundKey = boundName + key + (isInclusive ? 'Closed' : 'Open');
const bound = {} as {[index: string]: {}};
bound[boundKey] = Mutation.convertToBytes(boundData.value || boundData);
return bound;
}
}
/**
* @throws FilterError
*
* Turns filters into proto friendly format.
*
* @param {object[]} filters The list of filters to be parsed.
*
* @returns {object}
*
* @example
* ```
* const filter = Filter.parse([
* {
* family: 'my-family',
* }, {
* column: 'my-column'
* }
* ]);
* // {
* // chain: {
* // filters: [
* // {
* // familyNameRegexFilter: 'my-family'
* // },
* // {
* // columnQualifierRegexFilter: 'my-column'
* // }
* // ]
* // }
* // }
* ```
*/
static parse(filters: RawFilter[] | RawFilter) {
interface Fn {
[index: string]: Function;
}
const filter = new Filter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
arrify(filters).forEach((filterObj: any) => {
const key = Object.keys(filterObj)[0];
if (typeof (filter as {} as Fn)[key] !== 'function') {
throw new FilterError(key);
}
(filter as {} as Fn)[key](filterObj[key]);
});
return filter.toProto();
}
/**
* Sets passAllFilter or blockAllFilter
*
* @param {boolean} pass Whether to passAllFilter or blockAllFilter
*
* Assign true for enabling passAllFilter and false for enabling blockAllFilter
*
* @example
* ```
* //-
* // Matches all cells, regardless of input. Functionally equivalent to
* // leaving `filter` unset, but included for completeness.
* //-
* const filter = {
* all: true
* };
*
* //-
* // Does not match any cells, regardless of input. Useful for temporarily
* // disabling just part of a filter.
* //-
* const filter = {
* all: false
* };
* ```
*/
all(pass: boolean): void {
const filterName = pass ? 'passAllFilter' : 'blockAllFilter';
this.set(filterName, true);
}
/**
* Matches only cells from columns whose qualifiers satisfy the given RE2
* regex.
* @param {?regex|string|object} column Matching Column to filter with
*
* Note that, since column qualifiers can contain arbitrary bytes, the '\C'
* escape sequence must be used if a true wildcard is desired. The '.'
* character will not match the new line character '\n', which may be
* present in a binary qualifier.
*
* @example
* ```
* //-
* // Using the following filter, we would retrieve the `tjefferson` and
* // `gwashington` columns.
* //-
* const filter = [
* {
* column: /[a-z]+on$/
* }
* ];
*
* //-
* // You can also provide a string (optionally containing regexp characters)
* // for simple column filters.
* //-
* const filter = [
* {
* column: 'gwashington'
* }
* ];
*
* //-
* // Or you can provide an array of strings if you wish to match against
* // multiple columns.
* //-
* const filter = [
* {
* column: [
* 'gwashington',
* 'tjefferson'
* ]
* }
* ];
*
* //-
* // If you wish to use additional column filters, consider using the following
* // syntax.
* //-
* const filter = [
* {
* column: {
* name: 'gwashington'
* }
* }
* ];
*
*
* //-
* // <h4>Column Cell Limits</h4>
* //
* // Matches only the most recent number of versions within each column. For
* // example, if the `versions` is set to 2, this filter would only match
* // columns updated at the two most recent timestamps.
* //
* // If duplicate cells are present, as is possible when using an
* // {@link Filter#interleave} filter, each copy of the cell is
* // counted separately.
* //-
* const filter = [
* {
* column: {
* cellLimit: 2
* }
* }
* ];
*
* //-
* // <h4>Column Ranges</h4>
* //
* // Specifies a contiguous range of columns within a single column family.
* // The range spans from <column_family>:<start_qualifier> to
* // <column_family>:<end_qualifier>, where both bounds can be either
* // inclusive or exclusive. By default both are inclusive.
* //
* // When the `start` bound is omitted it is interpreted as an empty string.
* // When the `end` bound is omitted it is interpreted as Infinity.
* //-
* const filter = [
* {
* column: {
* family: 'follows',
* start: 'gwashington',
* end: 'tjefferson'
* }
* }
* ];
*
* //-
* // By default, both the `start` and `end` bounds are inclusive. You can
* // override these by providing an object explicity stating whether or not it
* // is `inclusive`.
* //-
* const filter = [
* {
* column: {
* family: 'follows',
* start: {
* value: 'gwashington',
* inclusive: false
* },
* end: {
* value: 'jadams',
* inclusive: false
* }
* }
* }
* ];
* ```
*/
column(column: RegExp | string | {}): void {
let col: Column;
if (!is.object(column)) {
col = {
name: column as string,
};
} else {
col = column as Column;
}
if (col.name) {
const name = Mutation.convertToBytes(
Filter.convertToRegExpString(col.name)
);
this.set('columnQualifierRegexFilter', name);
}
if (typeof col.cellLimit === 'number') {
this.set('cellsPerColumnLimitFilter', col.cellLimit!);
}
if (col.start || col.end) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const range: any = Filter.createRange(col.start!, col.end!, 'Qualifier');
range.familyName = col.family;
this.set('columnRangeFilter', range);
}
}
/**
* A filter which evaluates one of two possible filters, depending on
* whether or not a `test` filter outputs any cells from the input row.
*
* IMPORTANT NOTE: The `test` filter does not execute atomically with the
* pass and fail filters, which may lead to inconsistent or unexpected
* results. Additionally, condition filters have poor performance, especially
* when filters are set for the fail condition.
*
* @param {object} condition Condition to filter.
*
* @example
* ```
* //-
* // In the following example we're creating a filter that will check if
* // `gwashington` follows `tjefferson`. If he does, we'll get all of the
* // `gwashington` data. If he does not, we'll instead return all of the
* // `tjefferson` data.
* //-
* const filter = [
* {
* condition: {
* // If `test` outputs any cells, then `pass` will be evaluated on the
* // input row. Otherwise `fail` will be evaluated.
* test: [
* {
* row: 'gwashington'
* },
* {
* family: 'follows'
* },
* {
* column: 'tjefferson'
* }
* ],
*
* // If omitted, no results will be returned in the true case.
* pass: [
* {
* row: 'gwashington'
* }
* ],
*
* // If omitted, no results will be returned in the false case.
* fail: [
* {
* row: 'tjefferson'
* }
* ]
* }
* }
* ];
* ```
*/
condition(condition: Condition) {
this.set('condition', {
predicateFilter: Filter.parse(condition.test),
trueFilter: Filter.parse(condition.pass),
falseFilter: Filter.parse(condition.fail),
});
}
/**
* Matches only cells from columns whose families satisfy the given RE2
* regex. For technical reasons, the regex must not contain the ':'
* character, even if it is not being used as a literal.
* Note that, since column families cannot contain the new line character
* '\n', it is sufficient to use '.' as a full wildcard when matching
* column family names.
*
* @param {regex} family Expression to filter family
*
* @example
* ```
* const filter = [
* {
* family: 'follows'
* }
* ];
* ```
*/
family(
family:
| RegExp
| string
| number
| Buffer
| RegExp[]
| string[]
| number[]
| Buffer[]
): void {
const f = Filter.convertToRegExpString(family);
this.set('familyNameRegexFilter', f);
}
/**
* Applies several filters to the data in parallel and combines the results.
*
* @param {object} filters The elements of "filters" all process a copy of the input row, and the
* results are pooled, sorted, and combined into a single output row.
* If multiple cells are produced with the same column and timestamp,
* they will all appear in the output row in an unspecified mutual order.
* All interleaved filters are executed atomically.
*
* @example
* ```
* //-
* // In the following example, we're creating a filter that will retrieve
* // results for entries that were either created between December 17th, 2015
* // and March 22nd, 2016 or entries that have data for `follows:tjefferson`.
* //-
* const filter = [
* {
* interleave: [
* [
* {
* time: {
* start: new Date('December 17, 2015'),
* end: new Date('March 22, 2016')
* }
* }
* ],
* [
* {
* family: 'follows'
* },
* {
* column: 'tjefferson'
* }
* ]
* ]
* }
* ];
* ```
*/
interleave(filters: RawFilter[]): void {
this.set('interleave', {
filters: filters.map(Filter.parse),
});
}
/**
* Applies the given label to all cells in the output row. This allows
* the client to determine which results were produced from which part of
* the filter.
*
* @param {string} label Label to determine filter point
* Values must be at most 15 characters in length, and match the RE2
* pattern [a-z0-9\\-]+
*
* Due to a technical limitation, it is not currently possible to apply
* multiple labels to a cell. As a result, a chain filter may have no more than
* one sub-filter which contains a apply label transformer. It is okay for
* an {@link Filter#interleave} to contain multiple apply label
* transformers, as they will be applied to separate copies of the input. This
* may be relaxed in the future.
*
* @example
* ```
* const filter = {
* label: 'my-label'
* };
* ```
*/
label(label: string): void {
this.set('applyLabelTransformer', label);
}
/**
* Matches only cells from rows whose keys satisfy the given RE2 regex. In
* other words, passes through the entire row when the key matches, and
* otherwise produces an empty row.
*
* @param {?regex|string|string[]} row Row format to Filter
*
* Note that, since row keys can contain arbitrary bytes, the '\C' escape
* sequence must be used if a true wildcard is desired. The '.' character
* will not match the new line character '\n', which may be present in a
* binary key.
*
* @example
* ```
* //-
* // In the following example we'll use a regular expression to match all
* // row keys ending with the letters "on", which would then yield
* // `gwashington` and `tjefferson`.
* //-
* const filter = [
* {
* row: /[a-z]+on$/
* }
* ];
*
* //-
* // You can also provide a string (optionally containing regexp characters)
* // for simple key filters.
* //-
* const filter = [
* {
* row: 'gwashington'
* }
* ];
*
* //-
* // Or you can provide an array of strings if you wish to match against
* // multiple keys.
* //-
* const filter = [
* {
* row: [
* 'gwashington',
* 'tjefferson'
* ]
* }
* ];
*
* //-
* // If you wish to use additional row filters, consider using the following
* // syntax.
* //-
* const filter = [
* {
* row: {
* key: 'gwashington'
* }
* }
* ];
*
* //-
* // <h4>Row Samples</h4>
* //
* // Matches all cells from a row with probability p, and matches no cells
* // from the row with probability 1-p.
* //-
* const filter = [
* {
* row: {
* sample: 1
* }
* }
* ];
*
* //-
* // <h4>Row Cell Offsets</h4>
* //
* // Skips the first N cells of each row, matching all subsequent cells.
* // If duplicate cells are present, as is possible when using an
* // {@link Filter#interleave}, each copy of the cell is counted
* // separately.
* //-
* const filter = [
* {
* row: {
* cellOffset: 2
* }
* }
* ];
*
* //-
* // <h4>Row Cell Limits</h4>
* //
* // Matches only the first N cells of each row.
* // If duplicate cells are present, as is possible when using an
* // {@link Filter#interleave}, each copy of the cell is counted
* // separately.
* //-
* const filter = [
* {
* row: {
* cellLimit: 4
* }
* }
* ];
* ```
*/
row(row: Row | string | RegExp | string[]): void {
let r: Row;
if (!is.object(row)) {
r = {
key: row as string,
};
} else {
r = row as Row;
}
if (r.key) {
const key = Mutation.convertToBytes(Filter.convertToRegExpString(r.key));
this.set('rowKeyRegexFilter', key);
}
if (r.sample) {
this.set('rowSampleFilter', r.sample);
}
if (typeof r.cellOffset === 'number') {
this.set('cellsPerRowOffsetFilter', r.cellOffset!);
}
if (typeof r.cellLimit === 'number') {
this.set('cellsPerRowLimitFilter', r.cellLimit!);
}
}
/**
* Stores a filter object.
*
* @param {string} key Filter name.
* @param {*} value Filter value.
*/
set(key: string, value: {}): void {
this.filters_.push({
[key]: value,
});
}
/**
* This filter is meant for advanced use only. Hook for introspection into the
* filter. Outputs all cells directly to the output of the read rather than to
* any parent filter.
* Despite being excluded by the qualifier filter, a copy of every cell that
* reaches the sink is present in the final result.
* As with an {@link Filter#interleave} filter, duplicate cells are
* possible, and appear in an unspecified mutual order.
*
* Cannot be used within {@link Filter#condition} filter.
*
* @param {boolean} sink
*
* @example
* ```
* //-
* // Using the following filter, a copy of every cell that reaches the sink is
* // present in the final result, despite being excluded by the qualifier
* // filter
* //-
* const filter = [
* {
* family: 'follows'
* },
* {
* interleave: [
* [
* {
* all: true
* }
* ],
* [
* {
* label: 'prezzy'
* },
* {
* sink: true
* }
* ]
* ]
* },
* {
* column: 'gwashington'
* }
* ];
*
* //-
* // As with an {@link Filter#interleave} filter, duplicate cells
* // are possible, and appear in an unspecified mutual order. In this case we
* // have a duplicates with multiple `gwashington` columns because one copy
* // passed through the {@link Filter#all} filter while the other was
* // passed through the {@link Filter#label} and sink. Note that one
* // copy has label "prezzy" while the other does not.
* //-
* ```
*/
sink(sink: boolean): void {
this.set('sink', sink);
}
/**
* Matches only cells with timestamps within the given range.
*
* @param {object} time Start and End time Object
*
* @example
* ```
* const filter = [
* {
* time: {
* start: new Date('December 17, 2006 03:24:00'),
* end: new Date()
* }
* }
* ];
* ```
*/
time(time: Time): void {
const range = Mutation.createTimeRange(time.start, time.end);
this.set('timestampRangeFilter', range);
}
/**
* If we detect multiple filters, we'll assume it's a chain filter and the
* execution of the filters will be the order in which they were specified.
*/
toProto(): null | {} {
if (!this.filters_.length) {
return null;
}
if (this.filters_.length === 1) {
return this.filters_[0];
}
return {
chain: {
filters: this.filters_,
},
};
}
/**
* Matches only cells with values that satisfy the given regular expression.
* Note that, since cell values can contain arbitrary bytes, the '\C' escape
* sequence must be used if a true wildcard is desired. The '.' character
* will not match the new line character '\n', which may be present in a
* binary value.
*
* @param {?string|string[]|object} value Value to filter cells
*
* @example
* ```
* const filter = [
* {
* value: /[0-9]/
* }
* ];
*
* //-
* // You can also provide a string (optionally containing regexp characters)
* // for value filters.
* //-
* const filter = [
* {
* value: '1'
* }
* ];
*
* //-
* // You can also provide an array of strings if you wish to match against
* // multiple values.
* //-
* const filter = [
* {
* value: ['1', '9']
* }
* ];
*
* //-
* // Or you can provide a Buffer or an array of Buffers if you wish to match
* // against specfic binary value(s).
* //-
* const userInputedFaces = [Buffer.from('.|.'), Buffer.from(':-)')];
* const filter = [
* {
* value: userInputedFaces
* }
* ];
*
* //-
* // <h4>Value Ranges</h4>
* //
* // Specifies a contiguous range of values.
* //
* // When the `start` bound is omitted it is interpreted as an empty string.
* // When the `end` bound is omitted it is interpreted as Infinity.
* //-
* const filter = [
* {
* value: {
* start: '1',
* end: '9'
* }
* }
* ];
*
* //-
* // By default, both the `start` and `end` bounds are inclusive. You can
* // override these by providing an object explicity stating whether or not it
* // is `inclusive`.
* //-
* const filter = [
* {
* value: {
* start: {
* value: '1',
* inclusive: false
* },
* end: {
* value: '9',
* inclusive: false
* }
* }
* }
* ];
*
* //-
* // <h4>Strip Values</h4>
* //
* // Replaces each cell's value with an emtpy string.
* //-
* const filter = [
* {
* value: {
* strip: true
* }
* }
* ];
* ```
*/
value(value: string | string[] | ValueFilter): void {
let v: ValueFilter;
if (!is.object(value)) {
v = {
value: value as string,
};
} else {
v = value as ValueFilter;
}
if (v.value) {
const valueReg = Mutation.convertToBytes(
Filter.convertToRegExpString(v.value)
);
this.set('valueRegexFilter', valueReg);
}
if (v.start || v.end) {
const range = Filter.createRange(v.start!, v.end!, 'Value');
this.set('valueRangeFilter', range);
}
if (v.strip) {
this.set('stripValueTransformer', v.strip);
}
}
} | the_stack |
"use strict";
import {BrokerOptions, Errors, MetricRegistry, ServiceBroker} from "moleculer";
/**
* Moleculer ServiceBroker configuration file
*
* More info about options:
* https://moleculer.services/docs/0.14/configuration.html
*
*
* Overwriting options in production:
* ================================
* You can overwrite any option with environment variables.
* For example to overwrite the "logLevel" value, use `LOGLEVEL=warn` env var.
* To overwrite a nested parameter, e.g. retryPolicy.retries, use `RETRYPOLICY_RETRIES=10` env var.
*
* To overwrite broker’s deeply nested default options, which are not presented in "moleculer.config.js",
* use the `MOL_` prefix and double underscore `__` for nested properties in .env file.
* For example, to set the cacher prefix to `MYCACHE`, you should declare an env var as `MOL_CACHER__OPTIONS__PREFIX=mycache`.
* It will set this:
* {
* cacher: {
* options: {
* prefix: "mycache"
* }
* }
* }
*/
const brokerConfig: BrokerOptions = {
// Namespace of nodes to segment your nodes on the same network.
namespace: "",
// Unique node identifier. Must be unique in a namespace.
nodeID: null,
// Custom metadata store. Store here what you want. Accessing: `this.broker.metadata`
metadata: {},
// Enable/disable logging or use custom logger. More info: https://moleculer.services/docs/0.14/logging.html
// Available logger types: "Console", "File", "Pino", "Winston", "Bunyan", "debug", "Log4js", "Datadog"
logger: {
type: "Console",
options: {
// Using colors on the output
colors: true,
// Print module names with different colors (like docker-compose for containers)
moduleColors: false,
// Line formatter. It can be "json", "short", "simple", "full", a `Function` or a template string like "{timestamp} {level} {nodeID}/{mod}: {msg}"
formatter: "full",
// Custom object printer. If not defined, it uses the `util.inspect` method.
objectPrinter: null,
// Auto-padding the module name in order to messages begin at the same column.
autoPadding: false,
},
},
// Default log level for built-in console logger. It can be overwritten in logger options above.
// Available values: trace, debug, info, warn, error, fatal
logLevel: "info",
// Define transporter.
// More info: https://moleculer.services/docs/0.14/networking.html
// Note: During the development, you don't need to define it because all services will be loaded locally.
// In production you can set it via `TRANSPORTER=nats://localhost:4222` environment variable.
transporter: null,{{#if needTransporter}} // "{{transporter}}"{{/if}}
// Define a cacher.
// More info: https://moleculer.services/docs/0.14/caching.html
{{#if needCacher}}cacher: "{{cacher}}"{{/if}}{{#unless needCacher}}cacher: null{{/unless}},
// Define a serializer.
// Available values: "JSON", "Avro", "ProtoBuf", "MsgPack", "Notepack", "Thrift".
// More info: https://moleculer.services/docs/0.14/networking.html#Serialization
serializer: "JSON",
// Number of milliseconds to wait before reject a request with a RequestTimeout error. Disabled: 0
requestTimeout: 10 * 1000,
// Retry policy settings. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Retry
retryPolicy: {
// Enable feature
enabled: false,
// Count of retries
retries: 5,
// First delay in milliseconds.
delay: 100,
// Maximum delay in milliseconds.
maxDelay: 1000,
// Backoff factor for delay. 2 means exponential backoff.
factor: 2,
// A function to check failed requests.
check: (err: Errors.MoleculerError) => err && !!err.retryable,
},
// Limit of calling level. If it reaches the limit, broker will throw an MaxCallLevelError error. (Infinite loop protection)
maxCallLevel: 100,
// Number of seconds to send heartbeat packet to other nodes.
heartbeatInterval: 10,
// Number of seconds to wait before setting node to unavailable status.
heartbeatTimeout: 30,
// Cloning the params of context if enabled. High performance impact, use it with caution!
contextParamsCloning: false,
// Tracking requests and waiting for running requests before shuting down. More info: https://moleculer.services/docs/0.14/context.html#Context-tracking
tracking: {
// Enable feature
enabled: false,
// Number of milliseconds to wait before shuting down the process.
shutdownTimeout: 5000,
},
// Disable built-in request & emit balancer. (Transporter must support it, as well.). More info: https://moleculer.services/docs/0.14/networking.html#Disabled-balancer
disableBalancer: false,
// Settings of Service Registry. More info: https://moleculer.services/docs/0.14/registry.html
registry: {
// Define balancing strategy. More info: https://moleculer.services/docs/0.14/balancing.html
// Available values: "RoundRobin", "Random", "CpuUsage", "Latency", "Shard"
strategy: "RoundRobin",
// Enable local action call preferring. Always call the local action instance if available.
preferLocal: true,
},
// Settings of Circuit Breaker. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Circuit-Breaker
circuitBreaker: {
// Enable feature
enabled: false,
// Threshold value. 0.5 means that 50% should be failed for tripping.
threshold: 0.5,
// Minimum request count. Below it, CB does not trip.
minRequestCount: 20,
// Number of seconds for time window.
windowTime: 60,
// Number of milliseconds to switch from open to half-open state
halfOpenTime: 10 * 1000,
// A function to check failed requests.
check: (err: Errors.MoleculerError) => err && err.code >= 500,
},
// Settings of bulkhead feature. More info: https://moleculer.services/docs/0.14/fault-tolerance.html#Bulkhead
bulkhead: {
// Enable feature.
enabled: false,
// Maximum concurrent executions.
concurrency: 10,
// Maximum size of queue
maxQueueSize: 100,
},
// Enable action & event parameter validation. More info: https://moleculer.services/docs/0.14/validating.html
validator: true,
errorHandler: null,
// Enable/disable built-in metrics function. More info: https://moleculer.services/docs/0.14/metrics.html
metrics: {
enabled: {{#if metrics}}true{{/if}}{{#unless metrics}}false{{/unless}},
// Available built-in reporters: "Console", "CSV", "Event", "Prometheus", "Datadog", "StatsD"
reporter: {
type: "{{reporter}}",
{{#if_eq reporter "Console"}}
options: {
// HTTP port
port: 3030,
// HTTP URL path
path: "/metrics",
// Default labels which are appended to all metrics labels
defaultLabels: (registry: MetricRegistry) => ({
namespace: registry.broker.namespace,
nodeID: registry.broker.nodeID,
}),
},
{{/if_eq}}
{{#if_eq reporter "CSV"}}
options: {
// Folder of CSV files.
folder: "./reports/metrics",
// CSV field delimiter
delimiter: ",",
// CSV row delimiter
rowDelimiter: "\n",
// Saving mode.
// - "metric" - save metrics to individual files
// - "label" - save metrics by labels to individual files
mode: "metric",
// Saved metrics types.
types: null,
// Saving interval in seconds
interval: 5,
// Custom filename formatter
filenameFormatter: null,
// Custom CSV row formatter.
rowFormatter: null,
},
{{/if_eq}}
{{#if_eq reporter "Event"}}
options: {
// Event name
eventName: "$metrics.snapshot",
// Broadcast or emit
broadcast: false,
// Event groups
groups: null,
// Send only changed metrics
onlyChanges: false,
// Sending interval in seconds
interval: 5,
},
{{/if_eq}}
{{#if_eq reporter "Datadog"}}
options: {
// Hostname
host: "my-host",
// Base URL
baseUrl: "https://api.datadoghq.eu/api/", // Default is https://api.datadoghq.com/api/
// API version
apiVersion: "v1",
// Server URL path
path: "/series",
// Datadog API Key
apiKey: process.env.DATADOG_API_KEY,
// Default labels which are appended to all metrics labels
defaultLabels: (registry: MetricRegistry) => ({
namespace: registry.broker.namespace,
nodeID: registry.broker.nodeID,
}),
// Sending interval in seconds
interval: 10
},
{{/if_eq}}
{{#if_eq reporter "Prometheus"}}
options: {
// HTTP port
port: 3030,
// HTTP URL path
path: "/metrics",
// Default labels which are appended to all metrics labels
defaultLabels: (registry: MetricRegistry) => ({
namespace: registry.broker.namespace,
nodeID: registry.broker.nodeID,
}),
},
{{/if_eq}}
{{#if_eq reporter "StatsD"}}
options: {
// Server host
host: "localhost",
// Server port
port: 8125,
// Maximum payload size.
maxPayloadSize: 1300
},
{{/if_eq}}
},
},
// Enable built-in tracing function. More info: https://moleculer.services/docs/0.14/tracing.html
tracing: {
enabled: {{#if tracing}}true{{/if}}{{#unless tracing}}false{{/unless}},
// Available built-in exporters: "Console", "Datadog", "Event", "EventLegacy", "Jaeger", "Zipkin"
exporter: {
type: "{{exporter}}", // Console exporter is only for development!
{{#if_eq exporter "Console"}}
options: {
// Custom logger
logger: null,
// Using colors
colors: true,
// Width of row
width: 100,
// Gauge width in the row
gaugeWidth: 40,
},
{{/if_eq}}
{{#if_eq exporter "Datadog"}}
options: {
// Datadog Agent URL
agentUrl: process.env.DD_AGENT_URL || "http://localhost:8126",
// Environment variable
env: process.env.DD_ENVIRONMENT || null,
// Sampling priority. More info: https://docs.datadoghq.com/tracing/guide/trace_sampling_and_storage/?tab=java#sampling-rules
samplingPriority: "AUTO_KEEP",
// Default tags. They will be added into all span tags.
defaultTags: null,
// Custom Datadog Tracer options. More info: https://datadog.github.io/dd-trace-js/#tracer-settings
tracerOptions: null,
},
{{/if_eq}}
{{#if_eq exporter "Event"}}
options: {
// Name of event
eventName: "$tracing.spans",
// Send event when a span started
sendStartSpan: false,
// Send event when a span finished
sendFinishSpan: true,
// Broadcast or emit event
broadcast: false,
// Event groups
groups: null,
// Sending time interval in seconds
interval: 5,
// Custom span object converter before sending
spanConverter: null,
// Default tags. They will be added into all span tags.
defaultTags: null
},
{{/if_eq}}
{{#if_eq exporter "Jaeger"}}
options: {
// HTTP Reporter endpoint. If set, HTTP Reporter will be used.
endpoint: null,
// UDP Sender host option.
host: "127.0.0.1",
// UDP Sender port option.
port: 6832,
// Jaeger Sampler configuration.
sampler: {
// Sampler type. More info: https://www.jaegertracing.io/docs/1.14/sampling/#client-sampling-configuration
type: "Const",
// Sampler specific options.
options: {}
},
// Additional options for `Jaeger.Tracer`
tracerOptions: {},
// Default tags. They will be added into all span tags.
defaultTags: null
},
{{/if_eq}}
{{#if_eq exporter "Zipkin"}}
options: {
// Base URL for Zipkin server.
baseURL: "http://localhost:9411",
// Sending time interval in seconds.
interval: 5,
// Additional payload options.
payloadOptions: {
// Set `debug` property in payload.
debug: false,
// Set `shared` property in payload.
shared: false,
},
// Default tags. They will be added into all span tags.
defaultTags: null
},
{{/if_eq}}
{{#if_eq exporter "NewRelic"}}
options: {
// Base URL for NewRelic server
baseURL: 'https://trace-api.newrelic.com',
// NewRelic Insert Key
insertKey: 'my-secret-key',
// Sending time interval in seconds.
interval: 5,
// Additional payload options.
payloadOptions: {
// Set `debug` property in payload.
debug: false,
// Set `shared` property in payload.
shared: false,
},
// Default tags. They will be added into all span tags.
defaultTags: null,
},
{{/if_eq}}
},
},
// Register custom middlewares
middlewares: [],
// Register custom REPL commands.
replCommands: null,
/*
// Called after broker created.
created : (broker: ServiceBroker): void => {},
// Called after broker started.
started: async (broker: ServiceBroker): Promise<void> => {},
stopped: async (broker: ServiceBroker): Promise<void> => {},
*/
};
export = brokerConfig; | the_stack |
import {ifEnvSupports} from '../test-util';
describe('element', function() {
let button: HTMLButtonElement;
beforeEach(function() {
button = document.createElement('button');
document.body.appendChild(button);
});
afterEach(function() {
document.body.removeChild(button);
});
// https://github.com/angular/zone.js/issues/190
it('should work when addEventListener / removeEventListener are called in the global context',
function() {
const clickEvent = document.createEvent('Event');
let callCount = 0;
clickEvent.initEvent('click', true, true);
const listener = function(event: Event) {
callCount++;
expect(event).toBe(clickEvent);
};
// `this` would be null inside the method when `addEventListener` is called from strict mode
// it would be `window`:
// - when called from non strict-mode,
// - when `window.addEventListener` is called explicitly.
addEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
});
it('should work with addEventListener when called with a function listener', function() {
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', function(event) {
expect(event).toBe(clickEvent);
});
button.dispatchEvent(clickEvent);
});
it('should not call microtasks early when an event is invoked', function(done) {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => log += 'microtask;');
log += 'click;';
});
button.click();
expect(log).toEqual('click;');
done();
});
it('should call microtasks early when an event is invoked', function(done) {
/*
* In this test we escape the Zone using unpatched setTimeout.
* This way the eventTask invoked from click will think it is the top most
* task and eagerly drain the microtask queue.
*
* THIS IS THE WRONG BEHAVIOR!
*
* But there is no easy way for the task to know if it is the top most task.
*
* Given that this can only arise when someone is emulating clicks on DOM in a synchronous
* fashion we have few choices:
* 1. Ignore as this is unlikely to be a problem outside of tests.
* 2. Monkey patch the event methods to increment the _numberOfNestedTaskFrames and prevent
* eager drainage.
* 3. Pay the cost of throwing an exception in event tasks and verifying that we are the
* top most frame.
*
* For now we are choosing to ignore it and assume that this arises in tests only.
* As an added measure we make sure that all jasmine tests always run in a task. See: jasmine.ts
*/
(window as any)[(Zone as any).__symbol__('setTimeout')](() => {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => log += 'microtask;');
log += 'click;';
});
button.click();
expect(log).toEqual('click;microtask;');
done();
});
});
it('should work with addEventListener when called with an EventListener-implementing listener',
function() {
const eventListener = {
x: 5,
handleEvent: function(event: Event) {
// Test that context is preserved
expect(this.x).toBe(5);
expect(event).toBe(clickEvent);
}
};
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', eventListener);
button.dispatchEvent(clickEvent);
});
it('should respect removeEventListener when called with a function listener', function() {
let log = '';
const logFunction = function logFunction() {
log += 'a';
};
button.addEventListener('click', logFunction);
button.addEventListener('focus', logFunction);
button.click();
expect(log).toEqual('a');
const focusEvent = document.createEvent('Event');
focusEvent.initEvent('focus', true, true);
button.dispatchEvent(focusEvent);
expect(log).toEqual('aa');
button.removeEventListener('click', logFunction);
button.click();
expect(log).toEqual('aa');
});
it('should respect removeEventListener with an EventListener-implementing listener', function() {
const eventListener = {x: 5, handleEvent: jasmine.createSpy('handleEvent')};
button.addEventListener('click', eventListener);
button.removeEventListener('click', eventListener);
button.click();
expect(eventListener.handleEvent).not.toHaveBeenCalled();
});
it('should have no effect while calling addEventListener without listener', function() {
const onAddEventListenerSpy = jasmine.createSpy('addEventListener');
const eventListenerZone =
Zone.current.fork({name: 'eventListenerZone', onScheduleTask: onAddEventListenerSpy});
expect(function() {
eventListenerZone.run(function() {
button.addEventListener('click', null as any);
button.addEventListener('click', undefined as any);
});
}).not.toThrowError();
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should have no effect while calling removeEventListener without listener', function() {
const onAddEventListenerSpy = jasmine.createSpy('removeEventListener');
const eventListenerZone =
Zone.current.fork({name: 'eventListenerZone', onScheduleTask: onAddEventListenerSpy});
expect(function() {
eventListenerZone.run(function() {
button.removeEventListener('click', null as any);
button.removeEventListener('click', undefined as any);
});
}).not.toThrowError();
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should only add a listener once for a given set of arguments', function() {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function listener() {
log.push('listener');
}
clickEvent.initEvent('click', true, true);
button.addEventListener('click', listener);
button.addEventListener('click', listener);
button.addEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener']);
button.removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener']);
});
it('should correctly handler capturing versus nonCapturing eventListeners', function() {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function capturingListener() {
log.push('capturingListener');
}
function bubblingListener() {
log.push('bubblingListener');
}
clickEvent.initEvent('click', true, true);
document.body.addEventListener('click', capturingListener, true);
document.body.addEventListener('click', bubblingListener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['capturingListener', 'bubblingListener']);
});
it('should correctly handler a listener that is both capturing and nonCapturing', function() {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
function listener() {
log.push('listener');
}
clickEvent.initEvent('click', true, true);
document.body.addEventListener('click', listener, true);
document.body.addEventListener('click', listener);
button.dispatchEvent(clickEvent);
document.body.removeEventListener('click', listener, true);
document.body.removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(log).toEqual(['listener', 'listener']);
});
describe('onclick', function() {
function supportsOnClick() {
const div = document.createElement('div');
const clickPropDesc = Object.getOwnPropertyDescriptor(div, 'onclick');
return !(
EventTarget && div instanceof EventTarget && clickPropDesc &&
clickPropDesc.value === null);
}
(<any>supportsOnClick).message = 'Supports Element#onclick patching';
ifEnvSupports(supportsOnClick, function() {
it('should spawn new child zones', function() {
let run = false;
button.onclick = function() {
run = true;
};
button.click();
expect(run).toBeTruthy();
});
});
it('should only allow one onclick handler', function() {
let log = '';
button.onclick = function() {
log += 'a';
};
button.onclick = function() {
log += 'b';
};
button.click();
expect(log).toEqual('b');
});
it('should handler removing onclick', function() {
let log = '';
button.onclick = function() {
log += 'a';
};
button.onclick = null as any;
button.click();
expect(log).toEqual('');
});
it('should be able to deregister the same event twice', function() {
const listener = (event: Event) => {};
document.body.addEventListener('click', listener, false);
document.body.removeEventListener('click', listener, false);
document.body.removeEventListener('click', listener, false);
});
});
describe('onEvent default behavior', function() {
let checkbox: HTMLInputElement;
beforeEach(function() {
checkbox = document.createElement('input');
checkbox.type = 'checkbox';
document.body.appendChild(checkbox);
});
afterEach(function() {
document.body.removeChild(checkbox);
});
it('should be possible to prevent default behavior by returning false', function() {
checkbox.onclick = function() {
return false;
};
checkbox.click();
expect(checkbox.checked).toBe(false);
});
it('should have no effect on default behavior when not returning anything', function() {
checkbox.onclick = function() {};
checkbox.click();
expect(checkbox.checked).toBe(true);
});
});
}); | the_stack |
import { Config } from "../types/Config";
import { generateTopologicGraph } from "../workspace/generateTopologicalGraph";
import { NpmScriptTask } from "./NpmScriptTask";
import { PackageInfo, PackageInfos } from "workspace-tools";
import { RunContext } from "../types/RunContext";
import { PipelineTarget, TargetConfig, TargetConfigFactory, TaskArgs } from "../types/PipelineDefinition";
import { TopologicalGraph } from "../types/TopologicalGraph";
import { Workspace } from "../types/Workspace";
import pGraph, { PGraphNodeMap } from "p-graph";
import path from "path";
import { getPipelinePackages } from "./getPipelinePackages";
import { getPackageAndTask, getTargetId } from "./taskId";
import { WrappedTarget } from "./WrappedTarget";
import { DistributedTask } from "./DistributedTask";
export const START_TARGET_ID = "__start";
/**
* Pipeline class represents lage's understanding of the dependency graphs and wraps the promise graph implementations to execute tasks in order
*
* Distributed notes:
* - for doing distributed work, the WrapperTask will instead place the PipelineTarget info into a worker queue
*/
export class Pipeline {
/** Target represent a unit of work and the configuration of how to run it */
targets: Map<string, PipelineTarget> = new Map([
[
START_TARGET_ID,
{
id: START_TARGET_ID,
cwd: "",
run: () => {},
task: START_TARGET_ID,
hidden: true,
cache: false,
},
],
]);
/** Target dependencies determine the run order of the targets */
dependencies: [string, string][] = [];
/** Internal cache of the package.json information */
packageInfos: PackageInfos;
/** Internal generated cache of the topological package graph */
graph: TopologicalGraph;
/** Internal cache of context */
context: RunContext | undefined;
constructor(private workspace: Workspace, private config: Config) {
this.packageInfos = workspace.allPackages;
this.graph = generateTopologicGraph(workspace);
this.loadConfig(config);
}
private runTask(id: string, cwd: string, run?: PipelineTarget["run"]) {
if (this.config.dist) {
return (args: TaskArgs) => {
const task = new DistributedTask(id, cwd, this.config, this.context?.workerQueue!, args.logger);
task.run();
};
}
return run;
}
/**
* NPM Tasks are blindly placed in the task dependency graph, but we skip doing work if the package does not contain the specific npm task
* @param task
* @param info
* @returns
*/
private maybeRunNpmTask(task: string, info: PackageInfo) {
if (!info.scripts?.[task]) {
return;
}
return (args: TaskArgs) => {
if (this.config.dist && this.context?.workerQueue!) {
const distributedTask = new DistributedTask(
getTargetId(info.name, task),
path.dirname(info.packageJsonPath),
this.config,
this.context?.workerQueue!,
args.logger
);
return distributedTask.run();
} else {
const npmTask = new NpmScriptTask(task, info, this.config, args.logger);
return npmTask.run();
}
};
}
/**
* Generates a package target during the expansion of the shortcut syntax
*/
private generatePackageTarget(packageName: string, task: string, deps: string[]): PipelineTarget {
const info = this.packageInfos[packageName];
const id = getTargetId(packageName, task);
return {
id,
task,
cache: this.config.cache,
outputGlob: this.config.cacheOptions.outputGlob,
packageName: packageName,
cwd: path.dirname(this.packageInfos[packageName].packageJsonPath),
run: this.maybeRunNpmTask(task, info),
// TODO: do we need to really merge this? Is this desired? (this is the OLD behavior)
deps: this.targets.has(id) ? [...(this.targets.get(id)!.deps || []), ...deps] : deps,
};
}
/**
* Expands the shorthand notation to pipeline targets (executable units)
*/
private expandShorthandTargets(id: string, deps: string[]): PipelineTarget[] {
// shorthand gets converted to npm tasks
const { packageName, task } = getPackageAndTask(id);
const results: PipelineTarget[] = [];
let packages: string[] = [];
if (packageName) {
// specific case in definition (e.g. 'package-name#test': ['build'])
packages.push(packageName);
} else {
// generic case in definition (e.g. 'test': ['build'])
packages = Object.entries(this.packageInfos).map(([pkg, _info]) => pkg);
}
for (const packageWithScript of packages) {
results.push(this.generatePackageTarget(packageWithScript, task, deps));
}
return results;
}
/**
* Given an id & factory, generate targets configurations
* @param id
* @param factory
*/
private generateFactoryTargets(factory: TargetConfigFactory): TargetConfig[] {
const targets = factory({
config: this.config,
cwd: this.workspace.root,
});
return Array.isArray(targets) ? targets : [targets];
}
/**
* Converts target configuration to pipeline targets
* @param id
* @param target
*/
private convertToPipelineTarget(id: string, index: number, target: TargetConfig): PipelineTarget[] {
if (target.type === "global") {
const targetId = `${id}.${index}`;
return [
{
...target,
id: targetId,
cache: target.cache !== false,
cwd: this.workspace.root,
task: id,
run: this.runTask(targetId, this.workspace.root, target.run) || (() => {}),
},
];
} else if (id.includes("#")) {
const { packageName: pkg, task } = getPackageAndTask(id);
return [
{
...target,
id,
cache: target.cache !== false,
task: id,
cwd: path.dirname(this.packageInfos[pkg!].packageJsonPath),
packageName: pkg,
run:
this.runTask(id, path.dirname(this.packageInfos[pkg!].packageJsonPath), target.run) ||
this.maybeRunNpmTask(task, this.packageInfos[pkg!]),
},
];
} else {
const packages = Object.entries(this.packageInfos);
return packages.map(([pkg, _info]) => {
const targetId = getTargetId(pkg, id);
return {
...target,
id: targetId,
cache: target.cache !== false,
task: id,
cwd: path.dirname(this.packageInfos[pkg].packageJsonPath),
packageName: pkg,
run:
this.runTask(targetId, path.dirname(this.packageInfos[pkg].packageJsonPath), target.run) ||
this.maybeRunNpmTask(id, this.packageInfos[pkg]),
};
});
}
}
/**
* Adds a target definition (takes in shorthand, target config, or a target config factory)
* @param id
* @param targetDefinition
*/
addTargetDefinition(id: string, targetDefinition: string[] | TargetConfig | TargetConfigFactory) {
// e.g. build: ["^build", "prepare"]
if (Array.isArray(targetDefinition)) {
const targets = this.expandShorthandTargets(id, targetDefinition);
for (const target of targets) {
this.targets.set(target.id!, target);
}
} else {
// e.g. build: { /* target config */ }
const targets =
typeof targetDefinition === "function" ? this.generateFactoryTargets(targetDefinition) : [targetDefinition];
targets.forEach((target, index) => {
const pipelineTargets = this.convertToPipelineTarget(id, index, target);
for (const pipelineTarget of pipelineTargets) {
this.targets.set(pipelineTarget.id, pipelineTarget);
}
});
}
}
/**
* Adds all the target dependencies to the graph
*/
addDependencies() {
const targets = [...this.targets.values()];
for (const target of targets) {
const { deps, packageName, id } = target;
// Always start with a root node with a special "START_TARGET_ID"
this.dependencies.push([START_TARGET_ID, id]);
// Skip any targets that have no "deps" specified
if (!deps || deps.length === 0) {
continue;
}
/**
* Now for every deps defined, we need to "interpret" it based on the syntax:
* - for any deps like package#task, we simply add the singular dependency (source could be a single package or all packages)
* - for anything that starts with a "^", we add the package-tasks according to the topological package graph
* NOTE: in a non-strict mode (TODO), the dependencies can come from transitive task dependencies
* - for {"pkgA#task": ["dep"]}, we interpret to add "pkgA#dep"
* - for anything that is a string without a "^", we treat that string as the name of a task, adding all targets that way
* NOTE: in a non-strict mode (TODO), the dependencies can come from transitive task dependencies
*
* We interpret anything outside of these conditions as invalid
*/
for (const dep of deps) {
if (dep.includes("#")) {
// package and task as deps
this.dependencies.push([dep, id]);
} else if (dep.startsWith("^") && packageName) {
// topo dep -> build: ['^build']
const depTask = dep.substr(1);
const dependencyIds = targets
.filter((needle) => {
const { task, packageName: needlePackageName } = needle;
return (
task === depTask && this.graph[packageName].dependencies.some((depPkg) => depPkg === needlePackageName)
);
})
.map((needle) => needle.id);
for (const dependencyId of dependencyIds) {
this.dependencies.push([dependencyId, id]);
}
} else if (packageName) {
// Intra package task dependency - only add the target dependency if it exists in the pipeline targets lists
if (this.targets.has(getTargetId(packageName, dep))) {
this.dependencies.push([getTargetId(packageName, dep), target.id]);
}
} else if (!dep.startsWith("^")) {
const dependencyIds = targets.filter((needle) => needle.task === dep).map((needle) => needle.id);
for (const dependencyId of dependencyIds) {
this.dependencies.push([dependencyId, id]);
}
} else {
throw new Error(`invalid pipeline config detected: ${target.id}`);
}
}
}
}
generateTargetGraph() {
const scope = getPipelinePackages(this.workspace, this.config);
const tasks = this.config.command;
const targetGraph: [string, string][] = [];
const queue: string[] = [];
for (const task of tasks) {
// package task
for (const pkg of scope) {
if (this.targets.has(getTargetId(pkg, task))) {
queue.push(getTargetId(pkg, task));
targetGraph.push([START_TARGET_ID, getTargetId(pkg, task)]);
}
}
// if we have globals, send those into the queue
for (const target of this.targets.values()) {
if (target.task === task && !target.packageName) {
queue.push(target.id);
targetGraph.push([START_TARGET_ID, target.id]);
}
}
}
const visited = new Set<string>();
while (queue.length > 0) {
const id = queue.shift()!;
if (visited.has(id)) {
continue;
}
visited.add(id);
const { packageName, task } = getPackageAndTask(id);
if (!packageName) {
// global - find all deps in the form of "task.index"
for (const [from, to] of this.dependencies) {
if (to.includes(".")) {
const toTaskName = to.split(".")[0];
if (toTaskName === task) {
targetGraph.push([from, to]);
if (from) {
queue.push(from);
}
}
}
}
} else {
// package dep
for (const [from, to] of this.dependencies) {
if (to === id) {
targetGraph.push([from, to]);
if (from) {
queue.push(from);
}
}
}
}
}
return targetGraph;
}
loadConfig(config: Config) {
this.config = config;
for (const [id, targetDefinition] of Object.entries(this.config.pipeline)) {
this.addTargetDefinition(id, targetDefinition);
}
// add target definitions for unknown tasks
const knownTasks = new Set<string>();
for (const target of this.targets.values()) {
knownTasks.add(target.task);
}
knownTasks.add(START_TARGET_ID);
const unknownCommands = this.config.command.filter((cmd) => !knownTasks.has(cmd));
for (const command of unknownCommands) {
this.addTargetDefinition(command, [`^${command}`]);
}
this.addDependencies();
}
private getTargetPriority(target: PipelineTarget) {
return target.priority !== undefined
? target.priority
: this.config.priorities?.find(
(priority) => priority.package === target.packageName && priority.task === target.task
)?.priority;
}
/**
* The "run" public API, accounts for setting distributed mode for the master lage node
*
* Runs the pipeline with the p-graph library
*
* Note: this is the abstraction layer on top of the external p-graph library to insulate
* any incoming changes to the library.
*/
async run(context: RunContext) {
this.context = context;
const nodeMap: PGraphNodeMap = new Map();
const targetGraph = this.generateTargetGraph();
for (const [from, to] of targetGraph) {
const fromTarget = this.targets.get(from)!;
const toTarget = this.targets.get(to)!;
for (const target of [fromTarget, toTarget]) {
nodeMap.set(target.id, {
run: () => {
if (target.id === START_TARGET_ID || !target.run) {
return Promise.resolve();
}
const wrappedTask = new WrappedTarget(target, this.workspace.root, this.config, context);
return wrappedTask.run();
},
priority: this.getTargetPriority(target),
});
}
}
// Initialize the worker queue if in distributed mode
if (this.config.dist) {
await context.workerQueue?.initializeAsMaster(targetGraph.length * 2);
}
await pGraph(nodeMap, targetGraph).run({
concurrency: this.config.dist ? targetGraph.length : this.config.concurrency,
continue: this.config.continue,
});
}
} | the_stack |
// helper types
export type JsonData = string | number | boolean | Date | Json | JsonArray | undefined;
export type KnuddelsJsonData = string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable | undefined;
export type KnuddelsSerializable = string | number | boolean | User | BotUser | undefined;
export type KnuddelsEvent = string | Json | KnuddelsEventArray;
// helper interfaces
declare global {
interface Json {
[x: string]: JsonData | undefined;
}
interface KnuddelsJson {
[x: string]: KnuddelsJsonData | undefined;
}
interface JsonArray extends Array<JsonData> {
}
interface KnuddelsJsonArray extends Array<KnuddelsJsonData> {
}
interface KnuddelsEventArray extends Array<string | Json | KnuddelsEventArray> {
}
}
// Apps API
declare global {
/**
* @see https://developer.knuddels.de/docs/classes/App.html
*/
interface App {
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_mayJoinChannel
*/
mayJoinChannel?(
user: User
): ChannelJoinPermission;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicMessage
*/
mayShowPublicMessage?(
publicMessage: PublicMessage
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicActionMessage
*/
mayShowPublicActionMessage?(
publicActionMessage: PublicActionMessage
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onAppStart
*/
onAppStart?(): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onBeforeKnuddelReceived
*/
onBeforeKnuddelReceived?(
knuddelTransfer: KnuddelTransfer
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onKnuddelReceived
*/
onKnuddelReceived?(
sender: User,
receiver: BotUser,
knuddelAmount: KnuddelAmount,
transferReason: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onPrepareShutdown
*/
onPrepareShutdown?(
secondsTillShutdown: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onPrivateMessage
*/
onPrivateMessage?(
privateMessage: PrivateMessage
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicMessage
*/
onPublicMessage?(
publicMessage: PublicMessage
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicEventMessage
*/
onPublicEventMessage?(
publicEventMessage: PublicEventMessage
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicActionMessage
*/
onPublicActionMessage?(
publicActionMessage: PublicActionMessage
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onShutdown
*/
onShutdown?(): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDiced
*/
onUserDiced?(
diceEvent: DiceEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onUserJoined
*/
onUserJoined?(
user: User
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onUserLeft
*/
onUserLeft?(
user: User
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onAppEventReceived
*/
onAppEventReceived?(
appInstance: AppInstance,
type: string,
data: KnuddelsEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onEventReceived
*/
onEventReceived?(
user: User,
type: string,
data: KnuddelsEvent,
appContentSession: AppContentSession
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountReceivedKnuddel
*/
onAccountReceivedKnuddel?(
sender: User,
receiver: BotUser,
knuddelAmount: KnuddelAmount,
transferReason: string,
knuddelAccount: KnuddelAccount
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountChangedKnuddelAmount
*/
onAccountChangedKnuddelAmount?(
user: User,
knuddelAccount: KnuddelAccount,
oldKnuddelAmount: KnuddelAmount,
newKnuddelAmount: KnuddelAmount
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDeleted
*/
onUserDeleted?(
userId: number,
userPersistence: UserPersistence
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_onDeveloperCommand
* @since AppServer 108662, ChatServer 108662
*/
onDeveloperCommand?(
user: User,
params: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#method_mayUserDice
*/
mayUserDice?(
user: User,
diceConfig: DiceConfiguration
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/App.html#property_chatCommands
*/
chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void };
}
/**
* @see https://developer.knuddels.de/docs/classes/AppAccess.html
*/
class AppAccess {
/**
* @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getOwnInstance
*/
getOwnInstance(): AppInstance;
/**
* @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getAllRunningAppsInChannel
* @since AppServer 82904
*/
getAllRunningAppsInChannel(
includeSelf?: boolean
): AppInstance[];
/**
* @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getRunningAppInChannel
* @since AppServer 82904
*/
getRunningAppInChannel(
appId: string
): (AppInstance|null);
}
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html
*/
class AppContent {
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getAppViewMode
*/
getAppViewMode(): AppViewMode;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHTMLFile
*/
getHTMLFile(): HTMLFile;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getWidth
*/
getWidth(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHeight
*/
getHeight(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getLoadConfiguration
*/
getLoadConfiguration(): LoadConfiguration;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent
*/
static overlayContent(
htmlFile: HTMLFile,
width: number,
height: number
): AppContent;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent
*/
static overlayContent(
htmlFile: HTMLFile
): AppContent;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent
*/
static popupContent(
htmlFile: HTMLFile
): AppContent;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent
*/
static popupContent(
htmlFile: HTMLFile,
width: number,
height: number
): AppContent;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_headerbarContent
*/
static headerbarContent(
htmlFile: HTMLFile,
height: number
): AppContent;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_sendEvent
*/
sendEvent(
type: string,
data?: KnuddelsEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getUsers
*/
getUsers(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getSessions
*/
getSessions(): AppContentSession[];
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_replaceWithAppContent
*/
replaceWithAppContent(
newAppContent: AppContent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_remove
*/
remove(): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_addCloseListener
*/
addCloseListener(
callback: {
user: User;
appContent: AppContent;
}
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_setAllowJFXBrowser
*/
setAllowJFXBrowser(
allowJFXBrowser: boolean
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContent.html#method_isAllowJFXBrowser
*/
isAllowJFXBrowser(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html
*/
class AppContentSession {
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_sendEvent
*/
sendEvent(
type: string,
data?: KnuddelsEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppViewMode
*/
getAppViewMode(): AppViewMode;
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_remove
*/
remove(): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppContent
*/
getAppContent(): AppContent;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html
*/
class AppInfo {
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppUid
*/
getAppUid(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getRootAppUid
*/
getRootAppUid(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppName
*/
getAppName(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppVersion
*/
getAppVersion(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppId
*/
getAppId(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppKey
*/
getAppKey(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppDeveloper
*/
getAppDeveloper(): User;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppManagers
*/
getAppManagers(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTaxRate
*/
getTaxRate(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTotalTaxKnuddelAmount
*/
getTotalTaxKnuddelAmount(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getMaxPayoutKnuddelAmount
*/
getMaxPayoutKnuddelAmount(): KnuddelAmount;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html
*/
class AppInstance {
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAppInfo
*/
getAppInfo(): AppInfo;
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_sendAppEvent
*/
sendAppEvent(
type: string,
data: KnuddelsEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_isRootInstance
*/
isRootInstance(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRootInstance
*/
getRootInstance(): RootAppInstance;
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAllInstances
*/
getAllInstances(
includeSelf?: boolean
): AppInstance[];
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getStartDate
*/
getStartDate(): Date;
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRegisteredChatCommandNames
*/
getRegisteredChatCommandNames(): (string[]|null);
/**
* @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getChannelName
*/
getChannelName(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppPersistence.html
*/
class AppPersistence extends Persistence {
/**
* @see https://developer.knuddels.de/docs/classes/AppPersistence.html#method_getDatabaseFileSize
*/
getDatabaseFileSize(): number;
/**
* @see https://developer.knuddels.de/docs/classes/AppPersistence.html#method_getDatabaseFileSizeLimit
*/
getDatabaseFileSizeLimit(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html
*/
class AppProfileEntry {
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getKey
*/
getKey(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getDisplayType
*/
getDisplayType(): ToplistDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getToplist
*/
getToplist(): Toplist;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html
*/
class AppProfileEntryAccess {
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAllProfileEntries
*/
getAllProfileEntries(): AppProfileEntry[];
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAppProfileEntry
*/
getAppProfileEntry(
userPersistenceNumberKey: string
): AppProfileEntry;
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_createOrUpdateEntry
*/
createOrUpdateEntry(
toplist: Toplist,
toplistDisplayType: ToplistDisplayType
): AppProfileEntry;
/**
* @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_removeEntry
*/
removeEntry(
appProfileEntry: AppProfileEntry
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/AppServerInfo.html
*/
class AppServerInfo extends ServerInfo {
}
/**
* @see https://developer.knuddels.de/docs/classes/AppViewMode.html
*/
class AppViewMode {
/**
* @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Overlay
*/
static readonly Overlay: AppViewMode;
/**
* @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Popup
*/
static readonly Popup: AppViewMode;
/**
* @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Headerbar
*/
static readonly Headerbar: AppViewMode;
}
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html
*/
class AuthenticityClassification {
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#method_getDisplayText
* @since AppServer 94663, ChatServer 94663
*/
getDisplayText(): string;
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_ServiceNotAvailable
*/
static readonly ServiceNotAvailable: AuthenticityClassification;
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Unknown
*/
static readonly Unknown: AuthenticityClassification;
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Trusted
*/
static readonly Trusted: AuthenticityClassification;
/**
* @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_VeryTrusted
*/
static readonly VeryTrusted: AuthenticityClassification;
}
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html
*/
class BotUser extends User {
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicMessage
*/
sendPublicMessage(
message: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicActionMessage
*/
sendPublicActionMessage(
actionMessage: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPrivateMessage
*/
sendPrivateMessage(
message: string,
users?: User[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPostMessage
*/
sendPostMessage(
topic: string,
text: string,
receivingUser?: User
): void;
/**
* @see https://developer.knuddels.de/docs/classes/BotUser.html#method_transferKnuddel
*/
transferKnuddel(
receivingUserOrAccount: (User|KnuddelAccount),
knuddelAmount: KnuddelAmount,
parameters?: {
displayReasonText?: string;
transferDisplayType?: KnuddelTransferDisplayType;
onSuccess?: () => void;
onError?: (message: string) => void;
}
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html
*/
class Channel {
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelConfiguration
*/
getChannelConfiguration(): ChannelConfiguration;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelRestrictions
*/
getChannelRestrictions(): ChannelRestrictions;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelDesign
* @since AppServer 87470, ChatServer 87470
*/
getChannelDesign(): ChannelDesign;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getOnlineUsers
*/
getOnlineUsers(
...userType: UserType[]
): User[];
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVideoChannel
*/
isVideoChannel(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getVideoChannelData
*/
getVideoChannelData(): VideoChannelData;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelName
*/
getChannelName(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getRootChannelName
*/
getRootChannelName(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getTalkMode
*/
getTalkMode(): ChannelTalkMode;
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_getAllUsersWithTalkPermission
*/
getAllUsersWithTalkPermission(
...channelTalkPermission: ChannelTalkPermission[]
): User[];
/**
* @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVisible
* @since AppServer 82202
*/
isVisible(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html
*/
class ChannelConfiguration {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelRights
*/
getChannelRights(): ChannelRights;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelInformation
*/
getChannelInformation(): ChannelInformation;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelDesign.html
* @since AppServer 87470, ChatServer 87470
*/
class ChannelDesign {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontSize
* @since AppServer 87470, ChatServer 87470
*/
getDefaultFontSize(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontColor
* @since AppServer 87470, ChatServer 87470
*/
getDefaultFontColor(): Color;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getBackgroundColor
* @since AppServer 87470, ChatServer 87470
*/
getBackgroundColor(): Color;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelInformation.html
*/
class ChannelInformation {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_getTopic
*/
getTopic(): string;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_setTopic
*/
setTopic(
topic: string,
showMessage: boolean
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html
*/
class ChannelJoinPermission {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_accepted
*/
static accepted(): ChannelJoinPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_denied
*/
static denied(
denyReason: string
): ChannelJoinPermission;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html
*/
class ChannelRestrictions {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getMutedUsers
*/
getMutedUsers(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getColorMutedUsers
*/
getColorMutedUsers(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getLockedUsers
*/
getLockedUsers(): User[];
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRights.html
*/
class ChannelRights {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelOwners
*/
getChannelOwners(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelModerators
*/
getChannelModerators(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getEventModerators
*/
getEventModerators(): User[];
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html
*/
class ChannelTalkMode {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_Everyone
*/
static readonly Everyone: ChannelTalkMode;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_OnlyWithTalkPermission
*/
static readonly OnlyWithTalkPermission: ChannelTalkMode;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_FilteredByModerators
*/
static readonly FilteredByModerators: ChannelTalkMode;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html
*/
class ChannelTalkPermission {
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_NotInChannel
*/
static readonly NotInChannel: ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Default
*/
static readonly Default: ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkOnce
*/
static readonly TalkOnce: ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkPermanent
*/
static readonly TalkPermanent: ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_VIP
*/
static readonly VIP: ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Moderator
*/
static readonly Moderator: ChannelTalkPermission;
}
/**
* @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html
*/
class ChatServerInfo extends ServerInfo {
/**
* @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html#method_isTestSystem
*/
isTestSystem(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/Client.html
*/
class Client {
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_close
*/
static close(): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_sendEvent
*/
static sendEvent(
type: string,
data: KnuddelsEvent
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_executeSlashCommand
*/
static executeSlashCommand(
command: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_includeJS
*/
static includeJS(
...files: string[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_addEventListener
*/
static addEventListener(
type: string,
callback: (event: {type: string, data: KnuddelsEvent}) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_dispatchEvent
*/
static dispatchEvent(
event: Client.Event
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_removeEventListener
*/
static removeEventListener(
type: string,
callback?: (event: {type: string, data: KnuddelsEvent}) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_includeCSS
*/
static includeCSS(
...files: string[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_playSound
*/
static playSound(
fileName: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_prefetchSound
*/
static prefetchSound(
fileName: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_freeSound
*/
static freeSound(
fileName: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_getHostFrame
*/
static getHostFrame(): Client.HostFrame;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_getNick
*/
static getNick(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_getClientType
*/
static getClientType(): ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_getCacheInvalidationId
*/
static getCacheInvalidationId(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_getDirectConnection
*/
static getDirectConnection(): Promise<void>;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_addConnectionTypeChangeListener
*/
static addConnectionTypeChangeListener(
callback: (type: string) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#method_removeConnectionTypeChangeListener
*/
static removeConnectionTypeChangeListener(
callback: (type: string) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.html#property_pageData
*/
static pageData: Json;
}
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html
*/
namespace Client {
class Color {
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromRGB
*/
static fromRGB(
red: number,
green: number,
blue: number
): Color;
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromHexString
*/
static fromHexString(
colorString: string
): Color;
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getRed
*/
getRed(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getGreen
*/
getGreen(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getBlue
*/
getBlue(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_asHexString
*/
asHexString(): string;
}
}
/**
* @see https://developer.knuddels.de/docs/classes/Client.Event.html
*/
namespace Client {
class Event {
/**
* @see https://developer.knuddels.de/docs/classes/Client.Event.html#method_Event
*/
constructor(
type: string,
data: KnuddelsEvent
);
}
}
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html
*/
namespace Client {
class HostFrame {
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setTitle
*/
setTitle(
newTitle: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setBackgroundColor
*/
setBackgroundColor(
newColor: Color,
durationMillis?: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setIcons
* @since Applet: 9.0bwj, AppServer: 84904
*/
setIcons(
...path: string[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setResizable
*/
setResizable(
resizable: boolean
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_focus
* @since Applet: 9.0bwj, AppServer: 84904
*/
focus(): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setSize
* @since Applet: 9.0bwj, AppServer: 84516
*/
setSize(
width: number,
height: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getAppViewMode
* @since Applet: 9.0byl
*/
getAppViewMode(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getBrowserType
* @since Applet: 9.0bzp
*/
getBrowserType(): string;
}
}
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html
*/
class ClientType {
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Applet
*/
static readonly Applet: ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Browser
*/
static readonly Browser: ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Android
*/
static readonly Android: ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html#property_IOS
*/
static readonly IOS: ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Offline
*/
static readonly Offline: ClientType;
}
/**
* @see https://developer.knuddels.de/docs/classes/Color.html
*/
class Color {
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGB
*/
static fromRGB(
red: number,
green: number,
blue: number
): Color;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGBA
*/
static fromRGBA(
red: number,
green: number,
blue: number,
alpha: number
): Color;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_getAlpha
*/
getAlpha(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_getBlue
*/
getBlue(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_getGreen
*/
getGreen(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_getRed
*/
getRed(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_toKCode
*/
toKCode(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_asNumber
*/
asNumber(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Color.html#method_fromNumber
*/
static fromNumber(
value: number
): Color;
}
/**
* @see https://developer.knuddels.de/docs/classes/Dice.html
*/
class Dice {
/**
* @see https://developer.knuddels.de/docs/classes/Dice.html#method_Dice
*/
constructor(
count: number /* optional */,
value: number
);
/**
* @see https://developer.knuddels.de/docs/classes/Dice.html#method_getAmount
*/
getAmount(): number;
/**
* @see https://developer.knuddels.de/docs/classes/Dice.html#method_getNumberOfSides
*/
getNumberOfSides(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html
*/
class DiceConfiguration {
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingOpenThrow
*/
isUsingOpenThrow(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingPrivateThrow
*/
isUsingPrivateThrow(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getDices
*/
getDices(): Dice[];
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_equals
*/
equals(
diceConfiguration: DiceConfiguration
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getChatCommand
* @since AppServer 82248
*/
getChatCommand(): string;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_toString
* @since AppServer 108781
*/
toString(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html
*/
class DiceConfigurationFactory {
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_addDice
*/
addDice(
dice: Dice
): void;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_computeCurrentDiceCount
*/
computeCurrentDiceCount(): number;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setUseOpenThrow
*/
setUseOpenThrow(
shouldUseOpenThrow: boolean
): void;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setShouldUsePrivateThrow
*/
setShouldUsePrivateThrow(
shouldUsePrivateThrow: boolean
): void;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_getDiceConfiguration
*/
getDiceConfiguration(): DiceConfiguration;
/**
* @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_fromString
*/
static fromString(
diceConfigurationString: string
): DiceConfiguration;
}
/**
* @see https://developer.knuddels.de/docs/classes/DiceEvent.html
*/
class DiceEvent {
/**
* @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getDiceResult
*/
getDiceResult(): DiceResult;
}
/**
* @see https://developer.knuddels.de/docs/classes/DiceResult.html
*/
class DiceResult {
/**
* @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getDiceConfiguration
*/
getDiceConfiguration(): DiceConfiguration;
/**
* @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getSingleDiceResults
*/
getSingleDiceResults(): SingleDiceResult[];
/**
* @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_totalSum
*/
totalSum(): number;
/**
* @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_toString
* @since AppServer 108781
*/
toString(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/Domain.html
*/
class Domain {
/**
* @see https://developer.knuddels.de/docs/classes/Domain.html#method_getDomainName
*/
getDomainName(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html
*/
class ExternalServerAccess {
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getAllAccessibleDomains
*/
getAllAccessibleDomains(): Domain[];
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_canAccessURL
*/
canAccessURL(
urlString: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getURL
*/
getURL(
urlString: string,
parameters?: {
onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
}
): void;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_postURL
*/
postURL(
urlString: string,
parameters?: {
onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
data?: Json;
}
): void;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_touchURL
*/
touchURL(
urlString: string,
parameters?: {
onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
}
): void;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_callURL
*/
callURL(
urlString: string,
parameters?: {
onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void;
method?: ("GET" | "POST");
data?: Json;
}
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html
*/
class ExternalServerResponse {
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getURLString
*/
getURLString(): string;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getResponseCode
*/
getResponseCode(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldNames
* @since AppServer 108668
*/
getHeaderFieldNames(): string[];
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFields
*/
getHeaderFields(): { [key: string]: string[] };
/**
* @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldValues
* @since AppServer 108668
*/
getHeaderFieldValues(
headerFieldName: string
): string[];
}
/**
* @see https://developer.knuddels.de/docs/classes/Gender.html
*/
class Gender {
/**
* @see https://developer.knuddels.de/docs/classes/Gender.html#property_Male
*/
static readonly Male: Gender;
/**
* @see https://developer.knuddels.de/docs/classes/Gender.html#property_Female
*/
static readonly Female: Gender;
/**
* @see https://developer.knuddels.de/docs/classes/Gender.html#property_Unknown
*/
static readonly Unknown: Gender;
}
/**
* @see https://developer.knuddels.de/docs/classes/HTMLFile.html
*/
class HTMLFile {
/**
* @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_HTMLFile
*/
constructor(
assetPath: string,
pageData?: Json
);
/**
* @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getAssetPath
*/
getAssetPath(): string;
/**
* @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getPageData
*/
getPageData(): Json;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html
*/
class KnuddelAccount {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmount
*/
getKnuddelAmount(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUsed
*/
getKnuddelAmountUsed(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUnused
*/
getKnuddelAmountUnused(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountAppToUser
*/
getTotalKnuddelAmountAppToUser(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountUserToApp
*/
getTotalKnuddelAmountUserToApp(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_hasEnough
*/
hasEnough(
knuddelAmount: KnuddelAmount
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_use
*/
use(
knuddelAmount: KnuddelAmount,
displayReasonText: string,
parameters?: {
transferReason?: string;
onError?: (message: string) => void;
onSuccess?: () => void;
}
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html
*/
class KnuddelAmount {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_KnuddelAmount
*/
constructor(
knuddel: number
);
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromCents
*/
static fromCents(
knuddel: number
): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromKnuddel
*/
static fromKnuddel(
knuddel: number
): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_getKnuddelCents
*/
getKnuddelCents(): number;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_asNumber
*/
asNumber(): number;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_negate
*/
negate(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_isNegative
*/
isNegative(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html
*/
class KnuddelPot {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getId
*/
getId(): number;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getState
*/
getState(): KnuddelPotState;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountPerParticipant
*/
getKnuddelAmountPerParticipant(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountTotal
*/
getKnuddelAmountTotal(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getParticipants
*/
getParticipants(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getMaxFeeMultiplier
*/
getMaxFeeMultiplier(): number;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_setFee
*/
setFee(
feeUser: BotUser,
feeMultiplier: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeUser
*/
getFeeUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeMultiplier
*/
getFeeMultiplier(): number;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_seal
*/
seal(): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_refund
*/
refund(
reason?: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_addWinner
*/
addWinner(
user: User,
weight?: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_payout
*/
payout(
text?: string
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html
*/
class KnuddelPotState {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Open
*/
static readonly Open: KnuddelPotState;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Sealed
*/
static readonly Sealed: KnuddelPotState;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Closed
*/
static readonly Closed: KnuddelPotState;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html
*/
class KnuddelTransfer {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getSender
*/
getSender(): User;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getReceiver
*/
getReceiver(): BotUser;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getKnuddelAmount
*/
getKnuddelAmount(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getTransferReason
*/
getTransferReason(): string;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_reject
*/
reject(
reason: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_accept
*/
accept(): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_canAddToPot
*/
canAddToPot(
pot: KnuddelPot
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_addToPot
*/
addToPot(
knuddelPot: KnuddelPot
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_isProcessed
*/
isProcessed(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html
*/
class KnuddelTransferDisplayType {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Public
*/
static readonly Public: KnuddelTransferDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Private
*/
static readonly Private: KnuddelTransferDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Post
*/
static readonly Post: KnuddelTransferDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Silent
*/
static readonly Silent: KnuddelTransferDisplayType;
}
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html
*/
class KnuddelsServer {
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_execute
*/
static execute(
fileName: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_listFiles
*/
static listFiles(
path: string
): string[];
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultBotUser
*/
static getDefaultBotUser(): BotUser;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPersistence
*/
static getPersistence(): AppPersistence;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChannel
*/
static getChannel(): Channel;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getUserAccess
*/
static getUserAccess(): UserAccess;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPaymentAccess
* @since AppServer 108571, ChatServer 108571
*/
static getPaymentAccess(): PaymentAccess;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getExternalServerAccess
*/
static getExternalServerAccess(): ExternalServerAccess;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_refreshHooks
*/
static refreshHooks(): void;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultLogger
*/
static getDefaultLogger(): Logger;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullImagePath
*/
static getFullImagePath(
imageName: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullSystemImagePath
*/
static getFullSystemImagePath(
imageName: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChatServerInfo
*/
static getChatServerInfo(): ChatServerInfo;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppServerInfo
*/
static getAppServerInfo(): AppServerInfo;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppAccess
*/
static getAppAccess(): AppAccess;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_createKnuddelPot
*/
static createKnuddelPot(
knuddelAmount: KnuddelAmount,
params?: {
payoutTimeoutMinutes?: number;
shouldSealPot?: (pot: KnuddelPot) => boolean;
onPotSealed?: (pot: KnuddelPot) => void;
}
): KnuddelPot;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getKnuddelPot
*/
static getKnuddelPot(
id: number
): (KnuddelPot|null);
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAllKnuddelPots
*/
static getAllKnuddelPots(): KnuddelPot[];
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getToplistAccess
*/
static getToplistAccess(): ToplistAccess;
/**
* @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppProfileEntryAccess
*/
static getAppProfileEntryAccess(): AppProfileEntryAccess;
}
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html
*/
class LoadConfiguration {
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundColor
*/
setBackgroundColor(
color: Color
): void;
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundImage
*/
setBackgroundImage(
imageUrl: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setText
*/
setText(
text: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setLoadingIndicatorImage
*/
setLoadingIndicatorImage(
imageUrl: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setForegroundColor
*/
setForegroundColor(
color: Color
): void;
/**
* @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setEnabled
*/
setEnabled(
enabled: boolean
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html
*/
class Logger {
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html#method_debug
*/
debug(
...msg: any[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html#method_info
*/
info(
...msg: any[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html#method_warn
*/
warn(
...msg: any[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html#method_error
*/
error(
...msg: any[]
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Logger.html#method_fatal
*/
fatal(
...msg: any[]
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/Message.html
*/
class Message {
/**
* @see https://developer.knuddels.de/docs/classes/Message.html#method_getAuthor
*/
getAuthor(): User;
/**
* @see https://developer.knuddels.de/docs/classes/Message.html#method_getText
*/
getText(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Message.html#method_getRawText
*/
getRawText(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Message.html#method_getCreationDate
*/
getCreationDate(): Date;
}
/**
* @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html
*/
class OwnAppInstance {
/**
* @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html#method_getOnlineUsers
* @since AppServer 82560
*/
getOnlineUsers(
otherAppInstance: AppInstance,
...userType: UserType[]
): User[];
}
/**
* @see https://developer.knuddels.de/docs/classes/PaymentAccess.html
* @since AppServer 108571, ChatServer 108571
*/
class PaymentAccess {
/**
* @see https://developer.knuddels.de/docs/classes/PaymentAccess.html#method_startKnuddelPurchase
* @since AppServer 108571, ChatServer 108571
*/
startKnuddelPurchase(
user: User,
amount: KnuddelAmount,
parameters?: {
customMessage?: string;
transferReason?: string;
toAccount?: boolean;
}
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html
*/
class Persistence {
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasString
*/
hasString(
key: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setString
*/
setString(
key: string,
value: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getString
*/
getString(
key: string,
defaultValue?: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteString
*/
deleteString(
key: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasNumber
*/
hasNumber(
key: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setNumber
*/
setNumber(
key: string,
value: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_addNumber
*/
addNumber(
key: string,
value: number
): number;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getNumber
*/
getNumber(
key: string,
defaultValue?: number
): number;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteNumber
*/
deleteNumber(
key: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasObject
*/
hasObject(
key: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setObject
*/
setObject(
key: string,
object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getObject
*/
getObject(
key: string,
defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)
): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable);
/**
* @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteObject
*/
deleteObject(
key: string
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/PrivateMessage.html
*/
class PrivateMessage extends Message {
/**
* @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_getReceivingUsers
*/
getReceivingUsers(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_sendReply
*/
sendReply(
text: string
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/PublicActionMessage.html
*/
class PublicActionMessage extends Message {
/**
* @see https://developer.knuddels.de/docs/classes/PublicActionMessage.html#method_getFunctionName
*/
getFunctionName(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/PublicEventMessage.html
*/
class PublicEventMessage extends Message {
/**
* @see https://developer.knuddels.de/docs/classes/PublicEventMessage.html#method_getFunctionName
*/
getFunctionName(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/PublicMessage.html
*/
class PublicMessage extends Message {
}
/**
* @see https://developer.knuddels.de/docs/classes/Quest.html
*/
class Quest {
/**
* @see https://developer.knuddels.de/docs/classes/Quest.html#method_setSolved
* @since AppServer 82290, ChatServer 82290
*/
setSolved(
count?: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Quest.html#method_getQuestKey
* @since AppServer 82290, ChatServer 82290
*/
getQuestKey(): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/QuestAccess.html
*/
class QuestAccess {
/**
* @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuests
* @since AppServer 82290, ChatServer 82290
*/
getQuests(): Quest[];
/**
* @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_hasQuest
* @since AppServer 82290, ChatServer 82290
*/
hasQuest(
questKey: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuest
* @since AppServer 82290, ChatServer 82290
*/
getQuest(
questKey: string
): (Quest|null);
/**
* @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getUser
* @since AppServer 82290, ChatServer 82290
*/
getUser(): User;
}
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html
*/
class RandomOperations {
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInt
*/
static nextInt(
minValue: number /* optional */,
maxValue: number
): number;
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInts
*/
static nextInts(
minValue: number /* optional */,
maxValue: number,
count: number,
onlyDifferentNumbers: boolean
): number[];
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_flipTrue
*/
static flipTrue(
truePropability: number
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomObject
*/
static getRandomObject<T>(
objects: T[]
): T;
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_shuffleObjects
*/
static shuffleObjects<T>(
objects: T[]
): T[];
/**
* @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomString
* @since AppServer 92699
*/
static getRandomString(
length: number,
allowedCharacters?: string
): string;
}
/**
* @see https://developer.knuddels.de/docs/classes/RootAppInstance.html
*/
class RootAppInstance extends AppInstance {
/**
* @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_updateApp
*/
updateApp(
message: string /* optional */,
logMessage?: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_cancelUpdateApp
* @since AppServer 98117
*/
cancelUpdateApp(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_stopApp
*/
stopApp(
message: string /* optional */,
logMessage?: string
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/ServerInfo.html
*/
class ServerInfo {
/**
* @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getServerId
*/
getServerId(): string;
/**
* @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getRevision
*/
getRevision(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html
*/
class SingleDiceResult {
/**
* @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_getDice
*/
getDice(): Dice;
/**
* @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_valuesRolled
*/
valuesRolled(): number[];
/**
* @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_sum
*/
sum(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/String.html
*/
interface String {
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_escapeKCode
*/
escapeKCode(): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_stripKCode
*/
stripKCode(): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_startsWith
*/
startsWith(
prefix: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_endsWith
*/
endsWith(
suffix: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_getPixelWidth
*/
getPixelWidth(
fontSize: number,
isBold: boolean
): number;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_limitString
*/
limitString(
fontSize: number,
isBold: boolean,
maxPixelWidth: number,
abbreviationMarker?: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_contains
*/
contains(
needle: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_minimalConversionCost
* @since AppServer 82271
*/
minimalConversionCost(
otherString: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyNicknameCharacters
* @since AppServer 82271
*/
hasOnlyNicknameCharacters(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyDigits
* @since AppServer 82271
*/
hasOnlyDigits(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyAlphanumericalAndWhitespaceCharacters
* @since AppServer 82271
*/
hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_isEmpty
* @since AppServer 92695
*/
isEmpty(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_toCamelCase
* @since AppServer 92695
*/
toCamelCase(): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_capitalize
* @since AppServer 92695
*/
capitalize(): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_replaceAll
*/
replaceAll(
search: string|RegExp,
replacement: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/String.html#method_isOk
* @since ChatServer 82262, AppServer 82262
*/
isOk(): boolean;
}
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html
*/
class Toplist {
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getUserPersistenceNumberKey
*/
getUserPersistenceNumberKey(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getDisplayName
*/
getDisplayName(): string;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getChatCommand
*/
getChatCommand(
user_or_userId?: (User|number)
): string;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getLabel
*/
getLabel(
user_or_userId: (User|number)
): string;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addLabelChangeListener
*/
addLabelChangeListener(
listener: (labelChangeEvent: ToplistLabelChangeEvent) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeLabelChangeListener
*/
removeLabelChangeListener(
listener: (labelChangeEvent: ToplistLabelChangeEvent) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addRankChangeListener
*/
addRankChangeListener(
listener: (rankChangeEvent: ToplistRankChangeEvent) => void
): void;
/**
* @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeRankChangeListener
*/
removeRankChangeListener(
listener: (rankChangeEvent: ToplistRankChangeEvent) => void
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/ToplistAccess.html
*/
class ToplistAccess {
/**
* @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getAllToplists
*/
getAllToplists(): Toplist[];
/**
* @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getToplist
*/
getToplist(
userPersistenceNumberKey: string
): Toplist;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_removeToplist
*/
removeToplist(
toplist: Toplist
): void;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_createOrUpdateToplist
*/
createOrUpdateToplist(
userPersistenceNumberKey: string,
displayName: string,
parameters?: {
labelMapping?: { [minValue: string]: string };
ascending?: boolean;
sortIndex?: number;
}
): Toplist;
}
/**
* @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html
*/
class ToplistDisplayType {
/**
* @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Label
*/
static readonly Label: ToplistDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Value
*/
static readonly Value: ToplistDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_LabelAndRank
*/
static readonly LabelAndRank: ToplistDisplayType;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_ValueAndRank
*/
static readonly ValueAndRank: ToplistDisplayType;
}
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html
*/
class ToplistLabelChangeEvent {
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getToplist
*/
getToplist(): Toplist;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldLabel
*/
getOldLabel(): string;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewLabel
*/
getNewLabel(): string;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldValue
*/
getOldValue(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewValue
*/
getNewValue(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html
*/
class ToplistRankChangeEvent {
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getToplist
*/
getToplist(): Toplist;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldRank
*/
getOldRank(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewRank
*/
getNewRank(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUsersOvertook
*/
getUsersOvertook(): User[];
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldValue
*/
getOldValue(): number;
/**
* @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewValue
*/
getNewValue(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/User.html
*/
class User {
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getUserId
*/
getUserId(): number;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getNick
*/
getNick(): string;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getAge
*/
getAge(): number;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getGender
*/
getGender(): Gender;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getRegDate
*/
getRegDate(): Date;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getUserStatus
*/
getUserStatus(): UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getUserType
*/
getUserType(): UserType;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getClientType
*/
getClientType(): ClientType;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_canShowAppViewMode
*/
canShowAppViewMode(
mode: AppViewMode
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_canSendAppContent
*/
canSendAppContent(
appContent: AppContent
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isInTeam
*/
isInTeam(
teamName: string,
subTeamName?: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getPersistence
*/
getPersistence(): UserPersistence;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_sendPrivateMessage
*/
sendPrivateMessage(
message: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_sendPostMessage
*/
sendPostMessage(
topic: string,
text: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelOwner
*/
isChannelOwner(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isLikingChannel
*/
isLikingChannel(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelCoreUser
* @since AppServer 92701, ChatServer 92701
*/
isChannelCoreUser(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isAppManager
*/
isAppManager(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isMuted
*/
isMuted(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isColorMuted
*/
isColorMuted(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isLocked
*/
isLocked(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelModerator
*/
isChannelModerator(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isEventModerator
*/
isEventModerator(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isAppDeveloper
*/
isAppDeveloper(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getProfileLink
*/
getProfileLink(
displayText?: string
): string;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isOnlineInChannel
*/
isOnlineInChannel(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAmount
*/
getKnuddelAmount(): KnuddelAmount;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isOnline
*/
isOnline(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getReadme
*/
getReadme(): string;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getOnlineMinutes
*/
getOnlineMinutes(): number;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isAway
*/
isAway(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_hasProfilePhoto
*/
hasProfilePhoto(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_sendAppContent
*/
sendAppContent(
appContent: AppContent
): AppContentSession;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSessions
*/
getAppContentSessions(): AppContentSession[];
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSession
*/
getAppContentSession(
appViewMode: AppViewMode
): AppContentSession;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_equals
*/
equals(
user: User
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getProfilePhoto
*/
getProfilePhoto(
width: number,
height: number
): string;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getQuestAccess
* @since AppServer 82290, ChatServer 82290
*/
getQuestAccess(): QuestAccess;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isStreamingVideo
*/
isStreamingVideo(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAccount
*/
getKnuddelAccount(): KnuddelAccount;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getChannelTalkPermission
*/
getChannelTalkPermission(): ChannelTalkPermission;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isProfilePhotoVerified
*/
isProfilePhotoVerified(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_isAgeVerified
*/
isAgeVerified(): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_addNicklistIcon
*/
addNicklistIcon(
imagePath: string,
imageWidth: number
): void;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_removeNicklistIcon
*/
removeNicklistIcon(
imagePath: string
): void;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_triggerDice
* @since AppServer 89159, ChatServer 89159
*/
triggerDice(
diceConfiguration: DiceConfiguration
): void;
/**
* @see https://developer.knuddels.de/docs/classes/User.html#method_getAuthenticityClassification
* @since AppServer 94663, ChatServer 94663
*/
getAuthenticityClassification(): AuthenticityClassification;
}
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html
*/
class UserAccess {
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserId
*/
getUserId(
nick: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_exists
*/
exists(
nick: string
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_isUserDeleted
*/
isUserDeleted(
userId: number
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_mayAccess
*/
mayAccess(
userId: number
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserById
*/
getUserById(
userId: number
): User;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getNick
*/
getNick(
userId: number
): string;
/**
* @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_eachAccessibleUser
*/
eachAccessibleUser(
callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean,
parameters?: {
onStart?: (accessibleUserCount: number, key?: string) => void;
onEnd?: (accessibleUserCount: number, key?: string) => void;
}
): void;
}
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistence.html
*/
class UserPersistence extends Persistence {
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllNumbers
* @since AppServer 88569
*/
deleteAllNumbers(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllObjects
* @since AppServer 88569
*/
deleteAllObjects(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllStrings
* @since AppServer 88569
*/
deleteAllStrings(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAll
* @since AppServer 88569
*/
deleteAll(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html
*/
class UserPersistenceNumberEntry {
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getUser
*/
getUser(): User;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getValue
*/
getValue(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getRank
*/
getRank(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getPosition
*/
getPosition(): number;
}
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html
*/
class UserPersistenceNumbers {
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSum
*/
static getSum(
key: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_deleteAll
*/
static deleteAll(
key: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getCount
*/
static getCount(
key: string,
parameters?: {
minimumValue?: number;
maximumValue?: number;
}
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateKey
*/
static updateKey(
oldKeyName: string,
newKeyName: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateValue
*/
static updateValue(
key: string,
oldValue: number,
newValue: number
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_addNumber
*/
static addNumber(
key: string,
value: number,
parameters?: {
minimumValue?: number;
maximumValue?: number;
targetUsers?: User[];
}
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntries
*/
static getSortedEntries(
key: string,
parameters?: {
ascending?: boolean;
count?: number;
page?: number;
minimumValue?: number;
maximumValue?: number;
}
): UserPersistenceNumberEntry[];
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntriesAdjacent
*/
static getSortedEntriesAdjacent(
key: string,
user_or_userId: (User|number),
parameters?: {
ascending?: boolean;
count?: number;
}
): UserPersistenceNumberEntry[];
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getPosition
*/
static getPosition(
key: string,
user_or_userId: (User|number),
parameters?: {
ascending?: boolean;
minimumValue?: number;
}
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getRank
*/
static getRank(
key: string,
user_or_userId: (User|number),
parameters?: {
ascending?: boolean;
minimumValue?: number;
}
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_each
*/
static each(
key: string,
callback: (user: User, value: number, index: number, totalCount: number, key: string) => boolean,
parameters?: {
ascending?: boolean;
minimumValue?: number;
maximumValue?: number;
maximumCount?: number;
onStart?: (totalCount: number, key: string) => void;
onEnd?: (totalCount: number, key: string) => void;
}
): void;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getAllKeys
* @since AppServer 82483
*/
static getAllKeys(
filterKey?: string
): string[];
}
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html
*/
class UserPersistenceObjects {
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_deleteAll
* @since AppServer 82478
*/
static deleteAll(
key: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_getAllKeys
* @since AppServer 82483
*/
static getAllKeys(
filterKey?: string
): string[];
}
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html
*/
class UserPersistenceStrings {
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_exists
* @since AppServer 88571
*/
static exists(
key: string,
value: string,
ignoreCase?: boolean
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_deleteAll
* @since AppServer 82478
*/
static deleteAll(
key: string
): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_getAllKeys
* @since AppServer 82483
*/
static getAllKeys(
filterKey?: string
): string[];
}
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html
*/
class UserStatus {
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_getNumericStatus
*/
getNumericStatus(): number;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_isAtLeast
*/
isAtLeast(
otherUserStatus: UserStatus
): boolean;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Newbie
*/
static readonly Newbie: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Family
*/
static readonly Family: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Stammi
*/
static readonly Stammi: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_HonoryMember
*/
static readonly HonoryMember: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Admin
*/
static readonly Admin: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_SystemBot
*/
static readonly SystemBot: UserStatus;
/**
* @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Sysadmin
*/
static readonly Sysadmin: UserStatus;
}
/**
* @see https://developer.knuddels.de/docs/classes/UserType.html
*/
class UserType {
/**
* @see https://developer.knuddels.de/docs/classes/UserType.html#property_AppBot
*/
static readonly AppBot: UserType;
/**
* @see https://developer.knuddels.de/docs/classes/UserType.html#property_SystemBot
*/
static readonly SystemBot: UserType;
/**
* @see https://developer.knuddels.de/docs/classes/UserType.html#property_Human
*/
static readonly Human: UserType;
}
/**
* @see https://developer.knuddels.de/docs/classes/VideoChannelData.html
*/
class VideoChannelData {
/**
* @see https://developer.knuddels.de/docs/classes/VideoChannelData.html#method_getStreamingVideoUsers
*/
getStreamingVideoUsers(): User[];
}
} | the_stack |
import './index';
import { expect } from 'chai';
import {
DOT_STROKE_COLORS,
DOT_FILL_COLORS,
MAX_UNIQUE_DIGESTS,
} from '../dots-sk/constants';
import { setUpElementUnderTest } from '../../../infra-sk/modules/test_util';
import { DotsLegendSk } from './dots-legend-sk';
import { DotsLegendSkPO } from './dots-legend-sk_po';
describe('dots-legend-sk', () => {
const newInstance = setUpElementUnderTest<DotsLegendSk>('dots-legend-sk');
let dotsLegendSk: DotsLegendSk;
let dotsLegendSkPO: DotsLegendSkPO;
beforeEach(() => {
dotsLegendSk = newInstance();
dotsLegendSkPO = new DotsLegendSkPO(dotsLegendSk);
});
describe('with less than MAX_UNIQUE_DIGESTS unique digests', () => {
beforeEach(() => {
dotsLegendSk.test = 'My Test';
dotsLegendSk.digests = [
{ digest: '00000000000000000000000000000000', status: 'untriaged' },
{ digest: '11111111111111111111111111111111', status: 'positive' },
{ digest: '22222222222222222222222222222222', status: 'negative' },
{ digest: '33333333333333333333333333333333', status: 'negative' },
{ digest: '44444444444444444444444444444444', status: 'positive' },
];
// We set this to 5 to mimic what the server would give us - it is important that this
// match or exceed the length of digests, so as to draw properly.
dotsLegendSk.totalDigests = 5;
expect(dotsLegendSk.digests.length).to.equal(dotsLegendSk.totalDigests);
});
it('renders dots correctly', async () => {
expect(await dotsLegendSkPO.getDotBorderAndBackgroundColors()).to.deep.equal([
[DOT_STROKE_COLORS[0], DOT_FILL_COLORS[0]],
[DOT_STROKE_COLORS[1], DOT_FILL_COLORS[1]],
[DOT_STROKE_COLORS[2], DOT_FILL_COLORS[2]],
[DOT_STROKE_COLORS[3], DOT_FILL_COLORS[3]],
[DOT_STROKE_COLORS[4], DOT_FILL_COLORS[4]],
]);
});
it('renders digests correctly', async () => {
expect(await dotsLegendSkPO.getDigests()).to.deep.equal([
'00000000000000000000000000000000',
'11111111111111111111111111111111',
'22222222222222222222222222222222',
'33333333333333333333333333333333',
'44444444444444444444444444444444',
]);
});
it('renders digest links correctly', async () => {
const digestHrefFor = (d: string) => `/detail?test=My Test&digest=${d}`;
expect(await dotsLegendSkPO.getDigestHrefs()).to.deep.equal([
digestHrefFor('00000000000000000000000000000000'),
digestHrefFor('11111111111111111111111111111111'),
digestHrefFor('22222222222222222222222222222222'),
digestHrefFor('33333333333333333333333333333333'),
digestHrefFor('44444444444444444444444444444444'),
]);
});
it('renders status icons correctly', async () => {
expect(await dotsLegendSkPO.getTriageIconLabels()).to.deep.equal([
'untriaged',
'positive',
'negative',
'negative',
'positive',
]);
});
it('renders diff links correctly', async () => {
const diffHrefFor = (d: string) => `/diff?test=My Test&left=00000000000000000000000000000000&right=${d}`;
expect(await dotsLegendSkPO.getDiffHrefs()).to.deep.equal([
diffHrefFor('11111111111111111111111111111111'),
diffHrefFor('22222222222222222222222222222222'),
diffHrefFor('33333333333333333333333333333333'),
diffHrefFor('44444444444444444444444444444444'),
]);
});
describe('with CL ID and crs', () => {
beforeEach(() => {
dotsLegendSk.test = 'My Test';
dotsLegendSk.changeListID = '123456';
dotsLegendSk.crs = 'gerrit';
});
it('renders digest links correctly', async () => {
const digestHrefFor = (d: string) => `/detail?test=My Test&digest=${d}&changelist_id=123456&crs=gerrit`;
expect(await dotsLegendSkPO.getDigestHrefs()).to.deep.equal([
digestHrefFor('00000000000000000000000000000000'),
digestHrefFor('11111111111111111111111111111111'),
digestHrefFor('22222222222222222222222222222222'),
digestHrefFor('33333333333333333333333333333333'),
digestHrefFor('44444444444444444444444444444444'),
]);
});
it('renders diff links correctly', async () => {
const diffHrefFor = (d: string) => '/diff?test=My Test&left=00000000000000000000000000000000'
+ `&right=${d}&changelist_id=123456&crs=gerrit`;
expect(await dotsLegendSkPO.getDiffHrefs()).to.deep.equal([
diffHrefFor('11111111111111111111111111111111'),
diffHrefFor('22222222222222222222222222222222'),
diffHrefFor('33333333333333333333333333333333'),
diffHrefFor('44444444444444444444444444444444'),
]);
});
});
});
describe('with exactly MAX_UNIQUE_DIGESTS unique digests', () => {
beforeEach(() => {
dotsLegendSk.test = 'My Test';
dotsLegendSk.digests = [
{ digest: '00000000000000000000000000000000', status: 'untriaged' },
{ digest: '11111111111111111111111111111111', status: 'positive' },
{ digest: '22222222222222222222222222222222', status: 'negative' },
{ digest: '33333333333333333333333333333333', status: 'negative' },
{ digest: '44444444444444444444444444444444', status: 'positive' },
{ digest: '55555555555555555555555555555555', status: 'positive' },
{ digest: '66666666666666666666666666666666', status: 'untriaged' },
{ digest: '77777777777777777777777777777777', status: 'untriaged' },
{ digest: '88888888888888888888888888888888', status: 'untriaged' },
];
expect(dotsLegendSk.digests.length).to.equal(MAX_UNIQUE_DIGESTS);
dotsLegendSk.totalDigests = MAX_UNIQUE_DIGESTS;
});
it('renders dots correctly', async () => {
expect(await dotsLegendSkPO.getDotBorderAndBackgroundColors()).to.deep.equal([
[DOT_STROKE_COLORS[0], DOT_FILL_COLORS[0]],
[DOT_STROKE_COLORS[1], DOT_FILL_COLORS[1]],
[DOT_STROKE_COLORS[2], DOT_FILL_COLORS[2]],
[DOT_STROKE_COLORS[3], DOT_FILL_COLORS[3]],
[DOT_STROKE_COLORS[4], DOT_FILL_COLORS[4]],
[DOT_STROKE_COLORS[5], DOT_FILL_COLORS[5]],
[DOT_STROKE_COLORS[6], DOT_FILL_COLORS[6]],
[DOT_STROKE_COLORS[7], DOT_FILL_COLORS[7]],
[DOT_STROKE_COLORS[8], DOT_FILL_COLORS[8]],
]);
});
it('renders digests correctly', async () => {
expect(await dotsLegendSkPO.getDigests()).to.deep.equal([
'00000000000000000000000000000000',
'11111111111111111111111111111111',
'22222222222222222222222222222222',
'33333333333333333333333333333333',
'44444444444444444444444444444444',
'55555555555555555555555555555555',
'66666666666666666666666666666666',
'77777777777777777777777777777777',
'88888888888888888888888888888888',
]);
});
it('renders status icons correctly', async () => {
expect(await dotsLegendSkPO.getTriageIconLabels()).to.deep.equal([
'untriaged',
'positive',
'negative',
'negative',
'positive',
'positive',
'untriaged',
'untriaged',
'untriaged',
]);
});
it('renders diff links correctly', async () => {
const diffHrefFor = (d: string) => `/diff?test=My Test&left=00000000000000000000000000000000&right=${d}`;
expect(await dotsLegendSkPO.getDiffHrefs()).to.deep.equal([
diffHrefFor('11111111111111111111111111111111'),
diffHrefFor('22222222222222222222222222222222'),
diffHrefFor('33333333333333333333333333333333'),
diffHrefFor('44444444444444444444444444444444'),
diffHrefFor('55555555555555555555555555555555'),
diffHrefFor('66666666666666666666666666666666'),
diffHrefFor('77777777777777777777777777777777'),
diffHrefFor('88888888888888888888888888888888'),
]);
});
});
describe('with more than MAX_UNIQUE_DIGESTS unique digests', () => {
beforeEach(() => {
dotsLegendSk.test = 'My Test';
dotsLegendSk.digests = [
{ digest: '00000000000000000000000000000000', status: 'untriaged' },
{ digest: '11111111111111111111111111111111', status: 'positive' },
{ digest: '22222222222222222222222222222222', status: 'negative' },
{ digest: '33333333333333333333333333333333', status: 'negative' },
{ digest: '44444444444444444444444444444444', status: 'positive' },
{ digest: '55555555555555555555555555555555', status: 'positive' },
{ digest: '66666666666666666666666666666666', status: 'untriaged' },
{ digest: '77777777777777777777777777777777', status: 'untriaged' },
{ digest: '88888888888888888888888888888888', status: 'untriaged' },
// The API currently tops out at 9 unique digests (counting the one digest that is part of
// the search results. The tenth unique digest below is included to test that this component
// behaves gracefully in the event that the API behavior changes and the front-end and
// back-end code fall out of sync.
{ digest: '99999999999999999999999999999999', status: 'untriaged' },
];
dotsLegendSk.totalDigests = 123;
});
it('renders dots correctly', async () => {
expect(await dotsLegendSkPO.getDotBorderAndBackgroundColors()).to.deep.equal([
[DOT_STROKE_COLORS[0], DOT_FILL_COLORS[0]],
[DOT_STROKE_COLORS[1], DOT_FILL_COLORS[1]],
[DOT_STROKE_COLORS[2], DOT_FILL_COLORS[2]],
[DOT_STROKE_COLORS[3], DOT_FILL_COLORS[3]],
[DOT_STROKE_COLORS[4], DOT_FILL_COLORS[4]],
[DOT_STROKE_COLORS[5], DOT_FILL_COLORS[5]],
[DOT_STROKE_COLORS[6], DOT_FILL_COLORS[6]],
[DOT_STROKE_COLORS[7], DOT_FILL_COLORS[7]],
[DOT_STROKE_COLORS[8], DOT_FILL_COLORS[8]],
]);
});
it('renders digests correctly', async () => {
expect(await dotsLegendSkPO.getDigests()).to.deep.equal([
'00000000000000000000000000000000',
'11111111111111111111111111111111',
'22222222222222222222222222222222',
'33333333333333333333333333333333',
'44444444444444444444444444444444',
'55555555555555555555555555555555',
'66666666666666666666666666666666',
'77777777777777777777777777777777',
'One of 115 other digests (123 in total).',
]);
});
it('renders status icons correctly', async () => {
expect(await dotsLegendSkPO.getTriageIconLabels()).to.deep.equal([
'untriaged',
'positive',
'negative',
'negative',
'positive',
'positive',
'untriaged',
'untriaged',
]);
});
it('renders diff links correctly', async () => {
const diffHrefFor = (d: string) => `/diff?test=My Test&left=00000000000000000000000000000000&right=${d}`;
expect(await dotsLegendSkPO.getDiffHrefs()).to.deep.equal([
diffHrefFor('11111111111111111111111111111111'),
diffHrefFor('22222222222222222222222222222222'),
diffHrefFor('33333333333333333333333333333333'),
diffHrefFor('44444444444444444444444444444444'),
diffHrefFor('55555555555555555555555555555555'),
diffHrefFor('66666666666666666666666666666666'),
diffHrefFor('77777777777777777777777777777777'),
]);
});
});
}); | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
jest.mock('uuid', () => ({
v4: jest.fn().mockReturnValue('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'),
}));
import { RouteOptions } from 'hapi';
import { OpenSearchDashboardsRequest } from './request';
import { httpServerMock } from '../http_server.mocks';
import { schema } from '@osd/config-schema';
describe('OpenSearchDashboardsRequest', () => {
describe('id property', () => {
it('uses the request.app.requestId property if present', () => {
const request = httpServerMock.createRawRequest({
app: { requestId: 'fakeId' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.id).toEqual('fakeId');
});
it('generates a new UUID if request.app property is not present', () => {
// Undefined app property
const request = httpServerMock.createRawRequest({
app: undefined,
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.id).toEqual('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
it('generates a new UUID if request.app.requestId property is not present', () => {
// Undefined app.requestId property
const request = httpServerMock.createRawRequest({
app: {},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.id).toEqual('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
});
describe('uuid property', () => {
it('uses the request.app.requestUuid property if present', () => {
const request = httpServerMock.createRawRequest({
app: { requestUuid: '123e4567-e89b-12d3-a456-426614174000' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.uuid).toEqual('123e4567-e89b-12d3-a456-426614174000');
});
it('generates a new UUID if request.app property is not present', () => {
// Undefined app property
const request = httpServerMock.createRawRequest({
app: undefined,
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.uuid).toEqual('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
it('generates a new UUID if request.app.requestUuid property is not present', () => {
// Undefined app.requestUuid property
const request = httpServerMock.createRawRequest({
app: {},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.uuid).toEqual('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx');
});
});
describe('get all headers', () => {
it('returns all headers', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', authorization: 'token' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.headers).toEqual({
custom: 'one',
authorization: 'token',
});
});
});
describe('headers property', () => {
it('provides a frozen copy of request headers', () => {
const rawRequestHeaders = { custom: 'one' };
const request = httpServerMock.createRawRequest({
headers: rawRequestHeaders,
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.headers).toEqual({ custom: 'one' });
expect(opensearchDashboardsRequest.headers).not.toBe(rawRequestHeaders);
expect(Object.isFrozen(opensearchDashboardsRequest.headers)).toBe(true);
});
it.skip("doesn't expose authorization header by default", () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', authorization: 'token' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.headers).toEqual({
custom: 'one',
});
});
it('exposes authorization header if secured = false', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', authorization: 'token' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(
request,
undefined,
false
);
expect(opensearchDashboardsRequest.headers).toEqual({
custom: 'one',
authorization: 'token',
});
});
});
describe('isSytemApi property', () => {
it('is false when no osd-system-request header is set', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(false);
});
it('is true when osd-system-request header is set to true', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', 'osd-system-request': 'true' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(true);
});
it('is false when osd-system-request header is set to false', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', 'osd-system-request': 'false' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(false);
});
// Remove support for osd-system-api header in 8.x. Only used by legacy platform.
it('is false when no osd-system-api header is set', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(false);
});
it('is true when osd-system-api header is set to true', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', 'osd-system-api': 'true' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(true);
});
it('is false when osd-system-api header is set to false', () => {
const request = httpServerMock.createRawRequest({
headers: { custom: 'one', 'osd-system-api': 'false' },
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.isSystemRequest).toBe(false);
});
});
describe('route.options.authRequired property', () => {
it('handles required auth: undefined', () => {
const auth: RouteOptions['auth'] = undefined;
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.route.options.authRequired).toBe(true);
});
it('handles required auth: false', () => {
const auth: RouteOptions['auth'] = false;
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.route.options.authRequired).toBe(false);
});
it('handles required auth: { mode: "required" }', () => {
const auth: RouteOptions['auth'] = { mode: 'required' };
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.route.options.authRequired).toBe(true);
});
it('handles required auth: { mode: "optional" }', () => {
const auth: RouteOptions['auth'] = { mode: 'optional' };
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.route.options.authRequired).toBe('optional');
});
it('handles required auth: { mode: "try" } as "optional"', () => {
const auth: RouteOptions['auth'] = { mode: 'try' };
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request);
expect(opensearchDashboardsRequest.route.options.authRequired).toBe('optional');
});
it('throws on auth: strategy name', () => {
const auth: RouteOptions['auth'] = 'session';
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
expect(() => OpenSearchDashboardsRequest.from(request)).toThrowErrorMatchingInlineSnapshot(
`"unexpected authentication options: \\"session\\" for route: /"`
);
});
it('throws on auth: { mode: unexpected mode }', () => {
const auth: RouteOptions['auth'] = { mode: undefined };
const request = httpServerMock.createRawRequest({
route: {
settings: {
auth,
},
},
});
expect(() => OpenSearchDashboardsRequest.from(request)).toThrowErrorMatchingInlineSnapshot(
`"unexpected authentication options: {} for route: /"`
);
});
});
describe('RouteSchema type inferring', () => {
it('should work with config-schema', () => {
const body = Buffer.from('body!');
const request = {
...httpServerMock.createRawRequest({
params: { id: 'params' },
query: { search: 'query' },
}),
payload: body, // Set outside because the mock is using `merge` by lodash and breaks the Buffer into arrays
} as any;
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request, {
params: schema.object({ id: schema.string() }),
query: schema.object({ search: schema.string() }),
body: schema.buffer(),
});
expect(opensearchDashboardsRequest.params).toStrictEqual({ id: 'params' });
expect(opensearchDashboardsRequest.params.id.toUpperCase()).toEqual('PARAMS'); // infers it's a string
expect(opensearchDashboardsRequest.query).toStrictEqual({ search: 'query' });
expect(opensearchDashboardsRequest.query.search.toUpperCase()).toEqual('QUERY'); // infers it's a string
expect(opensearchDashboardsRequest.body).toEqual(body);
expect(opensearchDashboardsRequest.body.byteLength).toBeGreaterThan(0); // infers it's a buffer
});
it('should work with ValidationFunction', () => {
const body = Buffer.from('body!');
const request = {
...httpServerMock.createRawRequest({
params: { id: 'params' },
query: { search: 'query' },
}),
payload: body, // Set outside because the mock is using `merge` by lodash and breaks the Buffer into arrays
} as any;
const opensearchDashboardsRequest = OpenSearchDashboardsRequest.from(request, {
params: schema.object({ id: schema.string() }),
query: schema.object({ search: schema.string() }),
body: (data, { ok, badRequest }) => {
if (Buffer.isBuffer(data)) {
return ok(data);
} else {
return badRequest('It should be a Buffer', []);
}
},
});
expect(opensearchDashboardsRequest.params).toStrictEqual({ id: 'params' });
expect(opensearchDashboardsRequest.params.id.toUpperCase()).toEqual('PARAMS'); // infers it's a string
expect(opensearchDashboardsRequest.query).toStrictEqual({ search: 'query' });
expect(opensearchDashboardsRequest.query.search.toUpperCase()).toEqual('QUERY'); // infers it's a string
expect(opensearchDashboardsRequest.body).toEqual(body);
expect(opensearchDashboardsRequest.body.byteLength).toBeGreaterThan(0); // infers it's a buffer
});
});
}); | the_stack |
import { serialize, serializeAsColor4, serializeAsCameraReference } from "../Misc/decorators";
import { Tools } from "../Misc/tools";
import { SmartArray } from "../Misc/smartArray";
import { Observable } from "../Misc/observable";
import { Nullable } from "../types";
import { Camera } from "../Cameras/camera";
import { Scene } from "../scene";
import { ISize } from "../Maths/math.size";
import { Color4 } from '../Maths/math.color';
import { Engine } from "../Engines/engine";
import { EngineStore } from "../Engines/engineStore";
import { VertexBuffer } from "../Buffers/buffer";
import { SubMesh } from "../Meshes/subMesh";
import { AbstractMesh } from "../Meshes/abstractMesh";
import { Mesh } from "../Meshes/mesh";
import { PostProcess } from "../PostProcesses/postProcess";
import { BaseTexture } from "../Materials/Textures/baseTexture";
import { Texture } from "../Materials/Textures/texture";
import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
import { Effect } from "../Materials/effect";
import { Material } from "../Materials/material";
import { MaterialHelper } from "../Materials/materialHelper";
import { Constants } from "../Engines/constants";
import "../Shaders/glowMapGeneration.fragment";
import "../Shaders/glowMapGeneration.vertex";
import { _WarnImport } from '../Misc/devTools';
import { DataBuffer } from '../Buffers/dataBuffer';
import { EffectFallbacks } from '../Materials/effectFallbacks';
import { DrawWrapper } from "../Materials/drawWrapper";
/**
* Effect layer options. This helps customizing the behaviour
* of the effect layer.
*/
export interface IEffectLayerOptions {
/**
* Multiplication factor apply to the canvas size to compute the render target size
* used to generated the objects (the smaller the faster).
*/
mainTextureRatio: number;
/**
* Enforces a fixed size texture to ensure effect stability across devices.
*/
mainTextureFixedSize?: number;
/**
* Alpha blending mode used to apply the blur. Default depends of the implementation.
*/
alphaBlendingMode: number;
/**
* The camera attached to the layer.
*/
camera: Nullable<Camera>;
/**
* The rendering group to draw the layer in.
*/
renderingGroupId: number;
}
/**
* The effect layer Helps adding post process effect blended with the main pass.
*
* This can be for instance use to generate glow or highlight effects on the scene.
*
* The effect layer class can not be used directly and is intented to inherited from to be
* customized per effects.
*/
export abstract class EffectLayer {
private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
private _indexBuffer: Nullable<DataBuffer>;
private _cachedDefines: string;
private _effectLayerMapGenerationDrawWrapper: DrawWrapper;
private _effectLayerOptions: IEffectLayerOptions;
private _mergeDrawWrapper: DrawWrapper;
protected _scene: Scene;
protected _engine: Engine;
protected _maxSize: number = 0;
protected _mainTextureDesiredSize: ISize = { width: 0, height: 0 };
protected _mainTexture: RenderTargetTexture;
protected _shouldRender = true;
protected _postProcesses: PostProcess[] = [];
protected _textures: BaseTexture[] = [];
protected _emissiveTextureAndColor: { texture: Nullable<BaseTexture>, color: Color4 } = { texture: null, color: new Color4() };
/**
* The name of the layer
*/
@serialize()
public name: string;
/**
* The clear color of the texture used to generate the glow map.
*/
@serializeAsColor4()
public neutralColor: Color4 = new Color4();
/**
* Specifies whether the highlight layer is enabled or not.
*/
@serialize()
public isEnabled: boolean = true;
/**
* Gets the camera attached to the layer.
*/
@serializeAsCameraReference()
public get camera(): Nullable<Camera> {
return this._effectLayerOptions.camera;
}
/**
* Gets the rendering group id the layer should render in.
*/
@serialize()
public get renderingGroupId(): number {
return this._effectLayerOptions.renderingGroupId;
}
public set renderingGroupId(renderingGroupId: number) {
this._effectLayerOptions.renderingGroupId = renderingGroupId;
}
/**
* Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer
*/
@serialize()
public disableBoundingBoxesFromEffectLayer = false;
/**
* An event triggered when the effect layer has been disposed.
*/
public onDisposeObservable = new Observable<EffectLayer>();
/**
* An event triggered when the effect layer is about rendering the main texture with the glowy parts.
*/
public onBeforeRenderMainTextureObservable = new Observable<EffectLayer>();
/**
* An event triggered when the generated texture is being merged in the scene.
*/
public onBeforeComposeObservable = new Observable<EffectLayer>();
/**
* An event triggered when the mesh is rendered into the effect render target.
*/
public onBeforeRenderMeshToEffect = new Observable<AbstractMesh>();
/**
* An event triggered after the mesh has been rendered into the effect render target.
*/
public onAfterRenderMeshToEffect = new Observable<AbstractMesh>();
/**
* An event triggered when the generated texture has been merged in the scene.
*/
public onAfterComposeObservable = new Observable<EffectLayer>();
/**
* An event triggered when the effect layer changes its size.
*/
public onSizeChangedObservable = new Observable<EffectLayer>();
/** @hidden */
public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
throw _WarnImport("EffectLayerSceneComponent");
}
/**
* Instantiates a new effect Layer and references it in the scene.
* @param name The name of the layer
* @param scene The scene to use the layer in
*/
constructor(
/** The Friendly of the effect in the scene */
name: string,
scene: Scene) {
this.name = name;
this._scene = scene || EngineStore.LastCreatedScene;
EffectLayer._SceneComponentInitialization(this._scene);
this._engine = this._scene.getEngine();
this._maxSize = this._engine.getCaps().maxTextureSize;
this._scene.effectLayers.push(this);
this._effectLayerMapGenerationDrawWrapper = new DrawWrapper(this._engine);
this._mergeDrawWrapper = new DrawWrapper(this._engine);
// Generate Buffers
this._generateIndexBuffer();
this._generateVertexBuffer();
}
/**
* Get the effect name of the layer.
* @return The effect name
*/
public abstract getEffectName(): string;
/**
* Checks for the readiness of the element composing the layer.
* @param subMesh the mesh to check for
* @param useInstances specify whether or not to use instances to render the mesh
* @return true if ready otherwise, false
*/
public abstract isReady(subMesh: SubMesh, useInstances: boolean): boolean;
/**
* Returns whether or not the layer needs stencil enabled during the mesh rendering.
* @returns true if the effect requires stencil during the main canvas render pass.
*/
public abstract needStencil(): boolean;
/**
* Create the merge effect. This is the shader use to blit the information back
* to the main canvas at the end of the scene rendering.
* @returns The effect containing the shader used to merge the effect on the main canvas
*/
protected abstract _createMergeEffect(): Effect;
/**
* Creates the render target textures and post processes used in the effect layer.
*/
protected abstract _createTextureAndPostProcesses(): void;
/**
* Implementation specific of rendering the generating effect on the main canvas.
* @param effect The effect used to render through
*/
protected abstract _internalRender(effect: Effect): void;
/**
* Sets the required values for both the emissive texture and and the main color.
*/
protected abstract _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void;
/**
* Free any resources and references associated to a mesh.
* Internal use
* @param mesh The mesh to free.
*/
public abstract _disposeMesh(mesh: Mesh): void;
/**
* Serializes this layer (Glow or Highlight for example)
* @returns a serialized layer object
*/
public abstract serialize?(): any;
/**
* Initializes the effect layer with the required options.
* @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
*/
protected _init(options: Partial<IEffectLayerOptions>): void {
// Adapt options
this._effectLayerOptions = {
mainTextureRatio: 0.5,
alphaBlendingMode: Constants.ALPHA_COMBINE,
camera: null,
renderingGroupId: -1,
...options,
};
this._setMainTextureSize();
this._createMainTexture();
this._createTextureAndPostProcesses();
this._mergeDrawWrapper.setEffect(this._createMergeEffect());
}
/**
* Generates the index buffer of the full screen quad blending to the main canvas.
*/
private _generateIndexBuffer(): void {
// Indices
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = this._engine.createIndexBuffer(indices);
}
/**
* Generates the vertex buffer of the full screen quad blending to the main canvas.
*/
private _generateVertexBuffer(): void {
// VBO
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
var vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);
this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
}
/**
* Sets the main texture desired size which is the closest power of two
* of the engine canvas size.
*/
private _setMainTextureSize(): void {
if (this._effectLayerOptions.mainTextureFixedSize) {
this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
}
else {
this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
}
this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
}
/**
* Creates the main texture for the effect layer.
*/
protected _createMainTexture(): void {
this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
{
width: this._mainTextureDesiredSize.width,
height: this._mainTextureDesiredSize.height
},
this._scene,
false,
true,
Constants.TEXTURETYPE_UNSIGNED_INT);
this._mainTexture.activeCamera = this._effectLayerOptions.camera;
this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
this._mainTexture.anisotropicFilteringLevel = 1;
this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
this._mainTexture.renderParticles = false;
this._mainTexture.renderList = null;
this._mainTexture.ignoreCameraViewport = true;
// Custom render function
this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
this.onBeforeRenderMainTextureObservable.notifyObservers(this);
var index: number;
let engine = this._scene.getEngine();
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
this._renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
this._renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
this._renderSubMesh(alphaTestSubMeshes.data[index]);
}
const previousAlphaMode = engine.getAlphaMode();
for (index = 0; index < transparentSubMeshes.length; index++) {
this._renderSubMesh(transparentSubMeshes.data[index], true);
}
engine.setAlphaMode(previousAlphaMode);
};
this._mainTexture.onClearObservable.add((engine: Engine) => {
engine.clear(this.neutralColor, true, true, true);
});
// Prevent package size in es6 (getBoundingBoxRenderer might not be present)
if (this._scene.getBoundingBoxRenderer) {
const boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled;
this._mainTexture.onBeforeBindObservable.add(() => {
this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled;
});
this._mainTexture.onAfterUnbindObservable.add(() => {
this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled;
});
}
}
/**
* Adds specific effects defines.
* @param defines The defines to add specifics to.
*/
protected _addCustomEffectDefines(defines: string[]): void {
// Nothing to add by default.
}
/**
* Checks for the readiness of the element composing the layer.
* @param subMesh the mesh to check for
* @param useInstances specify whether or not to use instances to render the mesh
* @param emissiveTexture the associated emissive texture used to generate the glow
* @return true if ready otherwise, false
*/
protected _isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable<BaseTexture>): boolean {
let material = subMesh.getMaterial();
if (!material) {
return false;
}
if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
return false;
}
var defines: string[] = [];
var attribs = [VertexBuffer.PositionKind];
var mesh = subMesh.getMesh();
var uv1 = false;
var uv2 = false;
// Diffuse
if (material) {
const needAlphaTest = material.needAlphaTesting();
const diffuseTexture = material.getAlphaTestTexture();
const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
defines.push("#define DIFFUSE");
if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
diffuseTexture.coordinatesIndex === 1) {
defines.push("#define DIFFUSEUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
defines.push("#define DIFFUSEUV1");
uv1 = true;
}
if (needAlphaTest) {
defines.push("#define ALPHATEST");
defines.push("#define ALPHATESTVALUE 0.4");
}
if (!diffuseTexture.gammaSpace) {
defines.push("#define DIFFUSE_ISLINEAR");
}
}
var opacityTexture = (material as any).opacityTexture;
if (opacityTexture) {
defines.push("#define OPACITY");
if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
opacityTexture.coordinatesIndex === 1) {
defines.push("#define OPACITYUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
defines.push("#define OPACITYUV1");
uv1 = true;
}
}
}
// Emissive
if (emissiveTexture) {
defines.push("#define EMISSIVE");
if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
emissiveTexture.coordinatesIndex === 1) {
defines.push("#define EMISSIVEUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
defines.push("#define EMISSIVEUV1");
uv1 = true;
}
if (!emissiveTexture.gammaSpace) {
defines.push("#define EMISSIVE_ISLINEAR");
}
}
// Vertex
if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha) {
attribs.push(VertexBuffer.ColorKind);
defines.push("#define VERTEXALPHA");
}
if (uv1) {
attribs.push(VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (uv2) {
attribs.push(VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
// Bones
const fallbacks = new EffectFallbacks();
if (mesh.useBones && mesh.computeBonesUsingShaders) {
attribs.push(VertexBuffer.MatricesIndicesKind);
attribs.push(VertexBuffer.MatricesWeightsKind);
if (mesh.numBoneInfluencers > 4) {
attribs.push(VertexBuffer.MatricesIndicesExtraKind);
attribs.push(VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
let skeleton = mesh.skeleton;
if (skeleton && skeleton.isUsingTextureForMatrices) {
defines.push("#define BONETEXTURE");
} else {
defines.push("#define BonesPerMesh " + (skeleton ? (skeleton.bones.length + 1) : 0));
}
if (mesh.numBoneInfluencers > 0) {
fallbacks.addCPUSkinningFallback(0, mesh);
}
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
// Morph targets
var manager = (<Mesh>mesh).morphTargetManager;
let morphInfluencers = 0;
if (manager) {
if (manager.numInfluencers > 0) {
defines.push("#define MORPHTARGETS");
morphInfluencers = manager.numInfluencers;
defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
if (manager.isUsingTextureForTargets) {
defines.push("#define MORPHTARGETS_TEXTURE");
}
MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
}
}
// Instances
if (useInstances) {
defines.push("#define INSTANCES");
MaterialHelper.PushAttributesForInstances(attribs);
if (subMesh.getRenderingMesh().hasThinInstances) {
defines.push("#define THIN_INSTANCES");
}
}
this._addCustomEffectDefines(defines);
// Get correct effect
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effectLayerMapGenerationDrawWrapper.setEffect(this._scene.getEngine().createEffect("glowMapGeneration",
attribs,
["world", "mBones", "viewProjection",
"glowColor", "morphTargetInfluences", "boneTextureWidth",
"diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity",
"morphTargetTextureInfo", "morphTargetTextureIndices"],
["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], join,
fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers })
);
}
return this._effectLayerMapGenerationDrawWrapper.effect!.isReady();
}
/**
* Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
*/
public render(): void {
var currentEffect = this._mergeDrawWrapper;
// Check
if (!currentEffect.effect!.isReady()) {
return;
}
for (var i = 0; i < this._postProcesses.length; i++) {
if (!this._postProcesses[i].isReady()) {
return;
}
}
var engine = this._scene.getEngine();
this.onBeforeComposeObservable.notifyObservers(this);
// Render
engine.enableEffect(currentEffect);
engine.setState(false);
// VBOs
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect!);
// Cache
var previousAlphaMode = engine.getAlphaMode();
// Go Blend.
engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
// Blends the map on the main canvas.
this._internalRender(currentEffect.effect!);
// Restore Alpha
engine.setAlphaMode(previousAlphaMode);
this.onAfterComposeObservable.notifyObservers(this);
// Handle size changes.
var size = this._mainTexture.getSize();
this._setMainTextureSize();
if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) && this._mainTextureDesiredSize.width !== 0 && this._mainTextureDesiredSize.height !== 0) {
// Recreate RTT and post processes on size change.
this.onSizeChangedObservable.notifyObservers(this);
this._disposeTextureAndPostProcesses();
this._createMainTexture();
this._createTextureAndPostProcesses();
}
}
/**
* Determine if a given mesh will be used in the current effect.
* @param mesh mesh to test
* @returns true if the mesh will be used
*/
public hasMesh(mesh: AbstractMesh): boolean {
if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
return true;
}
return false;
}
/**
* Returns true if the layer contains information to display, otherwise false.
* @returns true if the glow layer should be rendered
*/
public shouldRender(): boolean {
return this.isEnabled && this._shouldRender;
}
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
protected _shouldRenderMesh(mesh: AbstractMesh): boolean {
return true;
}
/**
* Returns true if the mesh can be rendered, otherwise false.
* @param mesh The mesh to render
* @param material The material used on the mesh
* @returns true if it can be rendered otherwise false
*/
protected _canRenderMesh(mesh: AbstractMesh, material: Material): boolean {
return !material.needAlphaBlendingForMesh(mesh);
}
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
protected _shouldRenderEmissiveTextureForMesh(): boolean {
return true;
}
/**
* Renders the submesh passed in parameter to the generation map.
*/
protected _renderSubMesh(subMesh: SubMesh, enableAlphaMode: boolean = false): void {
if (!this.shouldRender()) {
return;
}
var material = subMesh.getMaterial();
var ownerMesh = subMesh.getMesh();
var replacementMesh = subMesh.getReplacementMesh();
var renderingMesh = subMesh.getRenderingMesh();
var effectiveMesh = subMesh.getEffectiveMesh();
var scene = this._scene;
var engine = scene.getEngine();
effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
if (!material) {
return;
}
// Do not block in blend mode.
if (!this._canRenderMesh(renderingMesh, material)) {
return;
}
// Culling
let sideOrientation = renderingMesh.overrideMaterialSideOrientation ?? material.sideOrientation;
const mainDeterminant = renderingMesh._getWorldMatrixDeterminant();
if (mainDeterminant < 0) {
sideOrientation = (sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
}
const reverse = sideOrientation === Material.ClockWiseSideOrientation;
engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits);
// Managing instances
var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);
if (batch.mustReturn) {
return;
}
// Early Exit per mesh
if (!this._shouldRenderMesh(renderingMesh)) {
return;
}
var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;
this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);
if (this._useMeshMaterial(renderingMesh)) {
renderingMesh.render(subMesh, hardwareInstancedRendering, replacementMesh || undefined);
}
else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
const effect = this._effectLayerMapGenerationDrawWrapper.effect!;
engine.enableEffect(this._effectLayerMapGenerationDrawWrapper);
if (!hardwareInstancedRendering) {
const fillMode = scene.forcePointsCloud ? Material.PointFillMode : scene.forceWireframe ? Material.WireFrameFillMode : material.fillMode;
renderingMesh._bind(subMesh, effect, fillMode);
}
effect.setMatrix("viewProjection", scene.getTransformMatrix());
effect.setMatrix("world", effectiveMesh.getWorldMatrix());
effect.setFloat4("glowColor",
this._emissiveTextureAndColor.color.r,
this._emissiveTextureAndColor.color.g,
this._emissiveTextureAndColor.color.b,
this._emissiveTextureAndColor.color.a);
const needAlphaTest = material.needAlphaTesting();
const diffuseTexture = material.getAlphaTestTexture();
const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
effect.setTexture("diffuseSampler", diffuseTexture);
const textureMatrix = diffuseTexture.getTextureMatrix();
if (textureMatrix) {
effect.setMatrix("diffuseMatrix", textureMatrix);
}
}
const opacityTexture = (material as any).opacityTexture;
if (opacityTexture) {
effect.setTexture("opacitySampler", opacityTexture);
effect.setFloat("opacityIntensity", opacityTexture.level);
const textureMatrix = opacityTexture.getTextureMatrix();
if (textureMatrix) {
effect.setMatrix("opacityMatrix", textureMatrix);
}
}
// Glow emissive only
if (this._emissiveTextureAndColor.texture) {
effect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
effect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
}
// Bones
if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
const skeleton = renderingMesh.skeleton;
if (skeleton.isUsingTextureForMatrices) {
const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
if (!boneTexture) {
return;
}
effect.setTexture("boneSampler", boneTexture);
effect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
} else {
effect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
}
}
// Morph targets
MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);
if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {
renderingMesh.morphTargetManager._bind(effect);
}
// Alpha mode
if (enableAlphaMode) {
engine.setAlphaMode(material.alphaMode);
}
// Draw
renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering,
(isInstance, world) => effect.setMatrix("world", world));
} else {
// Need to reset refresh rate of the main map
this._mainTexture.resetRefreshCounter();
}
this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);
}
/**
* Defines whether the current material of the mesh should be use to render the effect.
* @param mesh defines the current mesh to render
*/
protected _useMeshMaterial(mesh: AbstractMesh): boolean {
return false;
}
/**
* Rebuild the required buffers.
* @hidden Internal use only.
*/
public _rebuild(): void {
let vb = this._vertexBuffers[VertexBuffer.PositionKind];
if (vb) {
vb._rebuild();
}
this._generateIndexBuffer();
}
/**
* Dispose only the render target textures and post process.
*/
private _disposeTextureAndPostProcesses(): void {
this._mainTexture.dispose();
for (var i = 0; i < this._postProcesses.length; i++) {
if (this._postProcesses[i]) {
this._postProcesses[i].dispose();
}
}
this._postProcesses = [];
for (var i = 0; i < this._textures.length; i++) {
if (this._textures[i]) {
this._textures[i].dispose();
}
}
this._textures = [];
}
/**
* Dispose the highlight layer and free resources.
*/
public dispose(): void {
var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
// Clean textures and post processes
this._disposeTextureAndPostProcesses();
// Remove from scene
var index = this._scene.effectLayers.indexOf(this, 0);
if (index > -1) {
this._scene.effectLayers.splice(index, 1);
}
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBeforeRenderMainTextureObservable.clear();
this.onBeforeComposeObservable.clear();
this.onBeforeRenderMeshToEffect.clear();
this.onAfterRenderMeshToEffect.clear();
this.onAfterComposeObservable.clear();
this.onSizeChangedObservable.clear();
}
/**
* Gets the class name of the effect layer
* @returns the string with the class name of the effect layer
*/
public getClassName(): string {
return "EffectLayer";
}
/**
* Creates an effect layer from parsed effect layer data
* @param parsedEffectLayer defines effect layer data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing the effect layer information
* @returns a parsed effect Layer
*/
public static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer {
var effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);
return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
}
} | the_stack |
import { BentleyError, Id64, Id64Arg, Id64String } from "@itwin/core-bentley";
import { Angle, Geometry, Matrix3d, Point3d, Transform, Vector3d, YawPitchRollAngles } from "@itwin/core-geometry";
import {
ColorDef, GeometricElementProps, IModelStatus, isPlacement2dProps, LinePixels, PersistentGraphicsRequestProps, Placement, Placement2d, Placement3d,
} from "@itwin/core-common";
import { BasicManipulationCommandIpc, editorBuiltInCmdIds } from "@itwin/editor-common";
import {
AccuDrawHintBuilder, AngleDescription, BeButtonEvent, CoreTools, DynamicsContext, ElementSetTool, GraphicBranch, GraphicType, IModelApp,
IModelConnection, IpcApp, NotifyMessageDetails, OutputMessagePriority, readElementGraphics, RenderGraphic, RenderGraphicOwner,
ToolAssistanceInstruction,
} from "@itwin/core-frontend";
import { DialogItem, DialogProperty, DialogPropertySyncItem, EnumerationChoice, PropertyDescriptionHelper } from "@itwin/appui-abstract";
import { EditTools } from "./EditTool";
/** @alpha */
export interface TransformGraphicsData {
id: Id64String;
placement: Placement;
graphic: RenderGraphicOwner;
}
/** @alpha */
export class TransformGraphicsProvider {
public readonly iModel: IModelConnection;
public readonly data: TransformGraphicsData[];
public readonly pending: Map<Id64String, string>;
public readonly prefix: string;
/** Chord tolerance to use to stroke the element's geometry in meters. */
public chordTolerance = 0.01;
constructor(iModel: IModelConnection, prefix: string) {
this.iModel = iModel;
this.prefix = prefix;
this.data = new Array<TransformGraphicsData>();
this.pending = new Map<Id64String, string>();
}
private getRequestId(id: Id64String): string { return `${this.prefix}-${id}`; }
private getToleranceLog10(): number { return Math.floor(Math.log10(this.chordTolerance)); }
private async createRequest(id: Id64String): Promise<TransformGraphicsData | undefined> {
const elementProps = (await this.iModel.elements.getProps(id)) as GeometricElementProps[];
if (0 === elementProps.length)
return;
const placementProps = elementProps[0].placement;
if (undefined === placementProps)
return;
const placement = isPlacement2dProps(placementProps) ? Placement2d.fromJSON(placementProps) : Placement3d.fromJSON(placementProps);
if (!placement.isValid)
return; // Ignore assembly parents w/o geometry, etc...
const requestProps: PersistentGraphicsRequestProps = {
id: this.getRequestId(id),
elementId: id,
toleranceLog10: this.getToleranceLog10(),
};
this.pending.set(id, requestProps.id); // keep track of requests so they can be cancelled...
const graphicData = await IModelApp.tileAdmin.requestElementGraphics(this.iModel, requestProps);
if (undefined === graphicData)
return;
const graphic = await readElementGraphics(graphicData, this.iModel, elementProps[0].model, placement.is3d, { noFlash: true, noHilite: true });
if (undefined === graphic)
return;
return { id, placement, graphic: IModelApp.renderSystem.createGraphicOwner(graphic) };
}
private disposeOfGraphics(): void {
this.data.forEach((data) => {
data.graphic.disposeGraphic();
});
this.data.length = 0;
}
private async cancelPendingRequests(): Promise<void> {
const requests = new Array<string>();
for (const [_key, id] of this.pending)
requests.push(id);
this.pending.clear();
if (0 === requests.length)
return;
return IpcApp.callIpcHost("cancelElementGraphicsRequests", this.iModel.key, requests);
}
/** Call to request a RenderGraphic for the supplied element id.
* @see [[cleanupGraphics]] Must be called when the tool exits.
*/
public async createSingleGraphic(id: Id64String): Promise<boolean> {
try {
const info = await this.createRequest(id);
if (undefined !== info?.id)
this.pending.delete(info.id);
if (undefined === info?.graphic)
return false;
this.data.push(info);
return true;
} catch {
return false;
}
}
/** Call to request RenderGraphics for the supplied element ids. Does not wait for results as
* generating graphics for a large number of elements can take time. Instead an array of [[RenderGraphicOwner]]
* is populated as requests are resolved and the current dynamics frame displays what is available.
* @see [[cleanupGraphics]] Must be called when the tool exits.
*/
public createGraphics(elements: Id64Arg): void {
if (0 === Id64.sizeOf(elements))
return;
try {
for (const id of Id64.iterable(elements)) {
const promise = this.createRequest(id);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
promise.then((info) => {
if (undefined !== info?.id)
this.pending.delete(info.id);
if (undefined !== info?.graphic)
this.data.push(info);
});
}
} catch { }
}
/** Call to dispose of [[RenderGraphic]] held by [[RenderGraphicOwner]] and cancel requests that are still pending.
* @note Must be called when the tool exits to avoid leaks of graphics memory or other webgl resources.
*/
public async cleanupGraphics(): Promise<void> {
await this.cancelPendingRequests();
this.disposeOfGraphics();
}
public addSingleGraphic(graphic: RenderGraphic, transform: Transform, context: DynamicsContext): void {
const branch = new GraphicBranch(false);
branch.add(graphic);
const branchGraphic = context.createBranch(branch, transform);
context.addGraphic(branchGraphic);
}
public addGraphics(transform: Transform, context: DynamicsContext): void {
if (0 === this.data.length)
return;
const branch = new GraphicBranch(false);
for (const data of this.data)
branch.add(data.graphic);
const branchGraphic = context.createBranch(branch, transform);
context.addGraphic(branchGraphic);
}
}
/** @alpha Base class for applying a transform to element placements. */
export abstract class TransformElementsTool extends ElementSetTool {
protected override get allowSelectionSet(): boolean { return true; }
protected override get allowGroups(): boolean { return true; }
protected override get allowDragSelect(): boolean { return true; }
protected override get controlKeyContinuesSelection(): boolean { return true; }
protected override get wantAccuSnap(): boolean { return true; }
protected override get wantDynamics(): boolean { return true; }
protected get wantMakeCopy(): boolean { return false; } // For testing repeat vs. restart...
protected _graphicsProvider?: TransformGraphicsProvider;
protected _startedCmd?: string;
protected abstract calculateTransform(ev: BeButtonEvent): Transform | undefined;
protected async createAgendaGraphics(changed: boolean): Promise<void> {
if (changed) {
if (undefined === this._graphicsProvider)
return; // Not yet needed...
} else {
if (undefined !== this._graphicsProvider)
return; // Use existing graphics...
}
if (undefined === this._graphicsProvider)
this._graphicsProvider = new TransformGraphicsProvider(this.iModel, this.toolId);
else
await this._graphicsProvider.cleanupGraphics();
if (1 === this.agenda.length) {
await this._graphicsProvider.createSingleGraphic(this.agenda.elements[0]);
return;
}
this._graphicsProvider.createGraphics(this.agenda.elements);
}
protected async clearAgendaGraphics(): Promise<void> {
if (undefined === this._graphicsProvider)
return;
await this._graphicsProvider.cleanupGraphics();
this._graphicsProvider = undefined;
}
protected override async onAgendaModified(): Promise<void> {
await this.createAgendaGraphics(true);
}
protected override async initAgendaDynamics(): Promise<boolean> {
await this.createAgendaGraphics(false);
return super.initAgendaDynamics();
}
protected transformAgendaDynamics(transform: Transform, context: DynamicsContext): void {
if (undefined !== this._graphicsProvider)
this._graphicsProvider.addGraphics(transform, context);
}
public override onDynamicFrame(ev: BeButtonEvent, context: DynamicsContext): void {
const transform = this.calculateTransform(ev);
if (undefined === transform)
return;
this.transformAgendaDynamics(transform, context);
}
protected updateAnchorLocation(transform: Transform): void {
// Update anchor point to support creating additional copies (repeat vs. restart)...
if (undefined === this.anchorPoint)
return;
transform.multiplyPoint3d(this.anchorPoint, this.anchorPoint);
const hints = new AccuDrawHintBuilder();
hints.setOrigin(this.anchorPoint);
hints.sendHints();
}
protected async startCommand(): Promise<string> {
if (undefined !== this._startedCmd)
return this._startedCmd;
return EditTools.startCommand<string>(editorBuiltInCmdIds.cmdBasicManipulation, this.iModel.key);
}
public static callCommand<T extends keyof BasicManipulationCommandIpc>(method: T, ...args: Parameters<BasicManipulationCommandIpc[T]>): ReturnType<BasicManipulationCommandIpc[T]> {
return EditTools.callCommand(method, ...args) as ReturnType<BasicManipulationCommandIpc[T]>;
}
protected async transformAgenda(transform: Transform): Promise<void> {
try {
this._startedCmd = await this.startCommand();
if (IModelStatus.Success === await TransformElementsTool.callCommand("transformPlacement", this.agenda.compressIds(), transform.toJSON()))
await this.saveChanges();
} catch (err) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred."));
}
}
public override async processAgenda(ev: BeButtonEvent): Promise<void> {
const transform = this.calculateTransform(ev);
if (undefined === transform)
return;
await this.transformAgenda(transform);
this.updateAnchorLocation(transform);
}
public override async onProcessComplete(): Promise<void> {
if (this.wantMakeCopy)
return; // TODO: Update agenda to hold copies, replace current selection set with copies, etc...
return super.onProcessComplete();
}
public override async onCleanup() {
await this.clearAgendaGraphics();
return super.onCleanup();
}
}
/** @alpha Move elements by applying translation to placement. */
export class MoveElementsTool extends TransformElementsTool {
public static override toolId = "MoveElements";
public static override iconSpec = "icon-move";
protected calculateTransform(ev: BeButtonEvent): Transform | undefined {
if (undefined === this.anchorPoint)
return undefined;
return Transform.createTranslation(ev.point.minus(this.anchorPoint));
}
protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void {
let mainMsg;
if (!this.isSelectByPoints && !this.wantAdditionalElements)
mainMsg = CoreTools.translate(this.wantAdditionalInput ? "ElementSet.Prompts.StartPoint" : "ElementSet.Prompts.EndPoint");
super.provideToolAssistance(mainMsg);
}
public async onRestartTool(): Promise<void> {
const tool = new MoveElementsTool();
if (!await tool.run())
return this.exitTool();
}
}
/** @alpha */
export enum RotateMethod {
By3Points,
ByAngle,
}
/** @alpha */
export enum RotateAbout {
Point,
Origin,
Center,
}
/** @alpha Rotate elements by applying transform to placement. */
export class RotateElementsTool extends TransformElementsTool {
public static override toolId = "RotateElements";
public static override iconSpec = "icon-rotate";
protected xAxisPoint?: Point3d;
protected havePivotPoint = false;
protected haveFinalPoint = false;
public static override get minArgs() { return 0; }
public static override get maxArgs() { return 3; }
private static methodMessage(str: string) { return EditTools.translate(`RotateElements.Method.${str}`); }
private static getMethodChoices = (): EnumerationChoice[] => {
return [
{ label: RotateElementsTool.methodMessage("3Points"), value: RotateMethod.By3Points },
{ label: RotateElementsTool.methodMessage("Angle"), value: RotateMethod.ByAngle },
];
};
private _methodProperty: DialogProperty<number> | undefined;
public get methodProperty() {
if (!this._methodProperty)
this._methodProperty = new DialogProperty<number>(PropertyDescriptionHelper.buildEnumPicklistEditorDescription(
"rotateMethod", EditTools.translate("RotateElements.Label.Method"), RotateElementsTool.getMethodChoices()), RotateMethod.By3Points as number);
return this._methodProperty;
}
public get rotateMethod(): RotateMethod { return this.methodProperty.value as RotateMethod; }
public set rotateMethod(method: RotateMethod) { this.methodProperty.value = method; }
private static aboutMessage(str: string) { return EditTools.translate(`RotateElements.About.${str}`); }
private static getAboutChoices = (): EnumerationChoice[] => {
return [
{ label: RotateElementsTool.aboutMessage("Point"), value: RotateAbout.Point },
{ label: RotateElementsTool.aboutMessage("Origin"), value: RotateAbout.Origin },
{ label: RotateElementsTool.aboutMessage("Center"), value: RotateAbout.Center },
];
};
private _aboutProperty: DialogProperty<number> | undefined;
public get aboutProperty() {
if (!this._aboutProperty)
this._aboutProperty = new DialogProperty<number>(PropertyDescriptionHelper.buildEnumPicklistEditorDescription(
"rotateAbout", EditTools.translate("RotateElements.Label.About"), RotateElementsTool.getAboutChoices()), RotateAbout.Point as number);
return this._aboutProperty;
}
public get rotateAbout(): RotateAbout { return this.aboutProperty.value as RotateAbout; }
public set rotateAbout(method: RotateAbout) { this.aboutProperty.value = method; }
private _angleProperty: DialogProperty<number> | undefined;
public get angleProperty() {
if (!this._angleProperty)
this._angleProperty = new DialogProperty<number>(new AngleDescription("rotateAngle", EditTools.translate("RotateElements.Label.Angle")), 0.0);
return this._angleProperty;
}
public get rotateAngle(): number { return this.angleProperty.value; }
public set rotateAngle(value: number) { this.angleProperty.value = value; }
protected override get requireAcceptForSelectionSetDynamics(): boolean { return RotateMethod.ByAngle !== this.rotateMethod; }
protected calculateTransform(ev: BeButtonEvent): Transform | undefined {
if (undefined === ev.viewport)
return undefined;
if (RotateMethod.ByAngle === this.rotateMethod) {
const rotMatrix = AccuDrawHintBuilder.getCurrentRotation(ev.viewport, true, true);
if (undefined === rotMatrix)
return undefined;
const invMatrix = rotMatrix.inverse();
if (undefined === invMatrix)
return undefined;
const angMatrix = YawPitchRollAngles.createRadians(this.rotateAngle, 0, 0).toMatrix3d();
if (undefined === angMatrix)
return undefined;
angMatrix.multiplyMatrixMatrix(invMatrix, invMatrix);
rotMatrix.multiplyMatrixMatrix(invMatrix, rotMatrix);
return Transform.createFixedPointAndMatrix(ev.point, rotMatrix);
}
if (undefined === this.anchorPoint || undefined === this.xAxisPoint)
return undefined;
const vec1 = Vector3d.createStartEnd(this.anchorPoint, this.xAxisPoint);
const vec2 = Vector3d.createStartEnd(this.anchorPoint, ev.point);
if (!vec1.normalizeInPlace() || !vec2.normalizeInPlace())
return undefined;
const dot = vec1.dotProduct(vec2);
if (dot > (1.0 - Geometry.smallAngleRadians))
return undefined;
if (dot < (-1.0 + Geometry.smallAngleRadians)) {
const rotMatrix = AccuDrawHintBuilder.getCurrentRotation(ev.viewport, true, true);
if (undefined === rotMatrix)
return undefined;
const invMatrix = rotMatrix.inverse();
if (undefined === invMatrix)
return undefined;
const angMatrix = YawPitchRollAngles.createRadians(Math.PI, 0, 0).toMatrix3d(); // 180 degree rotation...
if (undefined === angMatrix)
return undefined;
angMatrix.multiplyMatrixMatrix(invMatrix, invMatrix);
rotMatrix.multiplyMatrixMatrix(invMatrix, rotMatrix);
return Transform.createFixedPointAndMatrix(this.anchorPoint, rotMatrix);
}
const zVec = vec1.unitCrossProduct(vec2);
if (undefined === zVec)
return undefined;
const yVec = zVec.unitCrossProduct(vec1);
if (undefined === yVec)
return undefined;
const matrix1 = Matrix3d.createRows(vec1, yVec, zVec);
zVec.unitCrossProduct(vec2, yVec);
const matrix2 = Matrix3d.createColumns(vec2, yVec, zVec);
const matrix = matrix2.multiplyMatrixMatrix(matrix1);
if (undefined === matrix)
return undefined;
return Transform.createFixedPointAndMatrix(this.anchorPoint, matrix);
}
protected override transformAgendaDynamics(transform: Transform, context: DynamicsContext): void {
if (RotateAbout.Point === this.rotateAbout)
return super.transformAgendaDynamics(transform, context);
if (undefined === this._graphicsProvider)
return;
const rotatePoint = Point3d.create();
for (const data of this._graphicsProvider.data) {
if (RotateAbout.Origin === this.rotateAbout)
rotatePoint.setFrom(data.placement.origin);
else
rotatePoint.setFrom(data.placement.calculateRange().center);
const rotateTrans = Transform.createFixedPointAndMatrix(rotatePoint, transform.matrix);
this._graphicsProvider.addSingleGraphic(data.graphic, rotateTrans, context);
}
}
protected override async transformAgenda(transform: Transform): Promise<void> {
if (RotateAbout.Point === this.rotateAbout)
return super.transformAgenda(transform);
try {
this._startedCmd = await this.startCommand();
if (IModelStatus.Success === await TransformElementsTool.callCommand("rotatePlacement", this.agenda.compressIds(), transform.matrix.toJSON(), RotateAbout.Center === this.rotateAbout))
await this.saveChanges();
} catch (err) {
IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, BentleyError.getErrorMessage(err) || "An unknown error occurred."));
}
}
public override onDynamicFrame(ev: BeButtonEvent, context: DynamicsContext): void {
const transform = this.calculateTransform(ev);
if (undefined !== transform)
return this.transformAgendaDynamics(transform, context);
if (undefined === this.anchorPoint)
return;
const builder = context.createGraphic({ type: GraphicType.WorldOverlay });
builder.setSymbology(context.viewport.getContrastToBackgroundColor(), ColorDef.black, 1, LinePixels.Code2);
builder.addLineString([this.anchorPoint.clone(), ev.point.clone()]);
context.addGraphic(builder.finish());
}
protected override get wantAdditionalInput(): boolean {
if (RotateMethod.ByAngle === this.rotateMethod)
return super.wantAdditionalInput;
return !this.haveFinalPoint;
}
protected override wantProcessAgenda(ev: BeButtonEvent): boolean {
if (RotateMethod.ByAngle === this.rotateMethod)
return super.wantProcessAgenda(ev);
if (!this.havePivotPoint)
this.havePivotPoint = true; // Uses anchorPoint...
else if (undefined === this.xAxisPoint)
this.xAxisPoint = ev.point.clone();
else if (!this.haveFinalPoint)
this.haveFinalPoint = true; // Uses button event...
return super.wantProcessAgenda(ev);
}
protected override setupAndPromptForNextAction(): void {
super.setupAndPromptForNextAction();
if (RotateMethod.ByAngle === this.rotateMethod)
return;
if (undefined === this.anchorPoint || undefined === this.xAxisPoint)
return;
const hints = new AccuDrawHintBuilder();
hints.setXAxis(Vector3d.createStartEnd(this.anchorPoint, this.xAxisPoint));
hints.setOrigin(this.anchorPoint);
hints.setModePolar();
hints.sendHints();
}
protected override provideToolAssistance(_mainInstrText?: string, _additionalInstr?: ToolAssistanceInstruction[]): void {
let mainMsg;
if (RotateMethod.ByAngle === this.rotateMethod) {
if (!this.isSelectByPoints && !this.wantAdditionalElements && this.wantAdditionalInput)
mainMsg = EditTools.translate("RotateElements.Prompts.IdentifyPoint");
} else {
if (!this.isSelectByPoints && !this.wantAdditionalElements) {
if (!this.havePivotPoint)
mainMsg = EditTools.translate("RotateElements.Prompts.IdentifyPoint");
else if (undefined === this.xAxisPoint)
mainMsg = EditTools.translate("RotateElements.Prompts.DefineStart");
else
mainMsg = EditTools.translate("RotateElements.Prompts.DefineAmount");
}
}
super.provideToolAssistance(mainMsg);
}
public override async applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): Promise<boolean> {
if (this.methodProperty.name === updatedValue.propertyName) {
this.methodProperty.value = updatedValue.value.value as number;
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, this.methodProperty.item);
await this.onRestartTool(); // calling restart, not reinitialize to not exit tool for selection set...
return true;
} else if (this.aboutProperty.name === updatedValue.propertyName) {
this.aboutProperty.value = updatedValue.value.value as number;
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, this.aboutProperty.item);
return true;
} else if (this.angleProperty.name === updatedValue.propertyName) {
this.rotateAngle = updatedValue.value.value as number;
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, this.angleProperty.item);
return true;
}
return false;
}
public override supplyToolSettingsProperties(): DialogItem[] | undefined {
const toolSettings = new Array<DialogItem>();
toolSettings.push(this.methodProperty.toDialogItem({ rowPriority: 1, columnIndex: 2 }));
toolSettings.push(this.aboutProperty.toDialogItem({ rowPriority: 2, columnIndex: 2 }));
if (RotateMethod.ByAngle === this.rotateMethod)
toolSettings.push(this.angleProperty.toDialogItem({ rowPriority: 3, columnIndex: 2 }));
return toolSettings;
}
public async onRestartTool(): Promise<void> {
const tool = new RotateElementsTool();
if (!await tool.run())
return this.exitTool();
}
public override async onInstall(): Promise<boolean> {
if (!await super.onInstall())
return false;
// Setup initial values here instead of supplyToolSettingsProperties to support keyin args w/o appui-react...
const rotateMethod = IModelApp.toolAdmin.toolSettingsState.getInitialToolSettingValue(this.toolId, this.methodProperty.name);
if (undefined !== rotateMethod)
this.methodProperty.dialogItemValue = rotateMethod;
const rotateAbout = IModelApp.toolAdmin.toolSettingsState.getInitialToolSettingValue(this.toolId, this.aboutProperty.name);
if (undefined !== rotateAbout)
this.aboutProperty.dialogItemValue = rotateAbout;
const rotateAngle = IModelApp.toolAdmin.toolSettingsState.getInitialToolSettingValue(this.toolId, this.angleProperty.name);
if (undefined !== rotateAngle)
this.angleProperty.dialogItemValue = rotateAngle;
return true;
}
/** The keyin takes the following arguments, all of which are optional:
* - `method=0|1` How rotate angle will be specified. 0 for by 3 points, 1 for by specified angle.
* - `about=0|1|2` Location to rotate about. 0 for point, 1 for placement origin, and 2 for center of range.
* - `angle=number` Rotation angle in degrees when not defining angle by points.
*/
public override async parseAndRun(...inputArgs: string[]): Promise<boolean> {
let rotateMethod;
let rotateAbout;
let rotateAngle;
for (const arg of inputArgs) {
const parts = arg.split("=");
if (2 !== parts.length)
continue;
if (parts[0].toLowerCase().startsWith("me")) {
const method = Number.parseInt(parts[1], 10);
if (!Number.isNaN(method)) {
switch (method) {
case 0:
rotateMethod = RotateMethod.By3Points;
break;
case 1:
rotateMethod = RotateMethod.ByAngle;
break;
}
}
} else if (parts[0].toLowerCase().startsWith("ab")) {
const about = Number.parseInt(parts[1], 10);
if (!Number.isNaN(about)) {
switch (about) {
case 0:
rotateAbout = RotateAbout.Point;
break;
case 1:
rotateAbout = RotateAbout.Origin;
break;
case 2:
rotateAbout = RotateAbout.Center;
break;
}
}
} else if (parts[0].toLowerCase().startsWith("an")) {
const angle = Number.parseFloat(parts[1]);
if (!Number.isNaN(angle)) {
rotateAngle = Angle.createDegrees(angle).radians;
}
}
}
// Update current session values so keyin args are picked up for tool settings/restart...
if (undefined !== rotateMethod)
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, { propertyName: this.methodProperty.name, value: { value: rotateMethod } });
if (undefined !== rotateAbout)
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, { propertyName: this.aboutProperty.name, value: { value: rotateAbout } });
if (undefined !== rotateAngle)
IModelApp.toolAdmin.toolSettingsState.saveToolSettingProperty(this.toolId, { propertyName: this.angleProperty.name, value: { value: rotateAngle } });
return this.run();
}
} | the_stack |
import type {Mutable, ObserverType} from "@swim/util";
import type {FastenerOwner} from "@swim/component";
import type {GestureInputType} from "./GestureInput";
import type {GestureMethod} from "./Gesture";
import {PositionGestureInit, PositionGestureClass, PositionGesture} from "./PositionGesture";
import {MomentumGestureInput} from "./MomentumGestureInput";
import {MouseMomentumGesture} from "./"; // forward import
import {TouchMomentumGesture} from "./"; // forward import
import {PointerMomentumGesture} from "./"; // forward import
import type {ViewContext} from "../view/ViewContext";
import {View} from "../"; // forward import
/** @public */
export interface MomentumGestureInit<V extends View = View> extends PositionGestureInit<V> {
extends?: {prototype: MomentumGesture<any, any>} | string | boolean | null;
/**
* The time delta for velocity derivation, in milliseconds.
*/
hysteresis?: number;
/**
* The magnitude of the deceleration on coasting input points in,
* pixels/millisecond^2. An acceleration of zero disables coasting.
*/
acceleration?: number;
/**
* The maximum magnitude of the velocity of coasting input points,
* in pixels/millisecond.
*/
velocityMax?: number;
willBeginHover?(input: MomentumGestureInput, event: Event | null): void;
didBeginHover?(input: MomentumGestureInput, event: Event | null): void;
willEndHover?(input: MomentumGestureInput, event: Event | null): void;
didEndHover?(input: MomentumGestureInput, event: Event | null): void;
willStartInteracting?(): void;
didStartInteracting?(): void;
willStopInteracting?(): void;
didStopInteracting?(): void;
willBeginPress?(input: MomentumGestureInput, event: Event | null): boolean | void;
didBeginPress?(input: MomentumGestureInput, event: Event | null): void;
willMovePress?(input: MomentumGestureInput, event: Event | null): void;
didMovePress?(input: MomentumGestureInput, event: Event | null): void;
willEndPress?(input: MomentumGestureInput, event: Event | null): void;
didEndPress?(input: MomentumGestureInput, event: Event | null): void;
willCancelPress?(input: MomentumGestureInput, event: Event | null): void;
didCancelPress?(input: MomentumGestureInput, event: Event | null): void;
willPress?(input: MomentumGestureInput, event: Event | null): void;
didPress?(input: MomentumGestureInput, event: Event | null): void;
willLongPress?(input: MomentumGestureInput): void;
didLongPress?(input: MomentumGestureInput): void;
willStartCoasting?(): void;
didStartCoasting?(): void;
willStopCoasting?(): void;
didStopCoasting?(): void;
willBeginCoast?(input: MomentumGestureInput, event: Event | null): boolean | void;
didBeginCoast?(input: MomentumGestureInput, event: Event | null): void;
willEndCoast?(input: MomentumGestureInput, event: Event | null): void;
didEndCoast?(input: MomentumGestureInput, event: Event | null): void;
willCoast?(): void;
didCoast?(): void;
}
/** @public */
export type MomentumGestureDescriptor<O = unknown, V extends View = View, I = {}> = ThisType<MomentumGesture<O, V> & I> & MomentumGestureInit<V> & Partial<I>;
/** @public */
export interface MomentumGestureClass<G extends MomentumGesture<any, any> = MomentumGesture<any, any>> extends PositionGestureClass<G> {
/** @internal */
readonly Hysteresis: number;
/** @internal */
readonly Acceleration: number;
/** @internal */
readonly VelocityMax: number;
}
/** @public */
export interface MomentumGestureFactory<G extends MomentumGesture<any, any> = MomentumGesture<any, any>> extends MomentumGestureClass<G> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): MomentumGestureFactory<G> & I;
specialize(method: GestureMethod): MomentumGestureFactory | null;
define<O, V extends View = View>(className: string, descriptor: MomentumGestureDescriptor<O, V>): MomentumGestureFactory<MomentumGesture<any, V>>;
define<O, V extends View = View>(className: string, descriptor: {observes: boolean} & MomentumGestureDescriptor<O, V, ObserverType<V>>): MomentumGestureFactory<MomentumGesture<any, V>>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & MomentumGestureDescriptor<O, V, I>): MomentumGestureFactory<MomentumGesture<any, V> & I>;
define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & MomentumGestureDescriptor<O, V, I & ObserverType<V>>): MomentumGestureFactory<MomentumGesture<any, V> & I>;
<O, V extends View = View>(descriptor: MomentumGestureDescriptor<O, V>): PropertyDecorator;
<O, V extends View = View>(descriptor: {observes: boolean} & MomentumGestureDescriptor<O, V, ObserverType<V>>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown} & MomentumGestureDescriptor<O, V, I>): PropertyDecorator;
<O, V extends View = View, I = {}>(descriptor: {implements: unknown; observes: boolean} & MomentumGestureDescriptor<O, V, I & ObserverType<V>>): PropertyDecorator;
}
/** @public */
export interface MomentumGesture<O = unknown, V extends View = View> extends PositionGesture<O, V> {
/** @internal @override */
readonly inputs: {readonly [inputId: string]: MomentumGestureInput | undefined};
/** @override */
getInput(inputId: string | number): MomentumGestureInput | null;
/** @internal @override */
createInput(inputId: string, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): MomentumGestureInput;
/** @internal @override */
getOrCreateInput(inputId: string | number, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): MomentumGestureInput;
/** @internal @override */
clearInput(input: MomentumGestureInput): void;
/** @internal @override */
clearInputs(): void;
hysteresis: number;
acceleration: number;
velocityMax: number;
/** @internal */
viewWillAnimate(viewContext: ViewContext): void;
/** @internal */
interrupt(event: Event | null): void;
/** @internal */
cancel(event: Event | null): void;
/** @internal */
startInteracting(): void;
/** @protected */
willStartInteracting(): void;
/** @protected */
onStartInteracting(): void;
/** @protected */
didStartInteracting(): void;
/** @internal */
stopInteracting(): void;
/** @protected */
willStopInteracting(): void;
/** @protected */
onStopInteracting(): void;
/** @protected */
didStopInteracting(): void;
/** @internal @override */
onStartPressing(): void;
/** @internal @override */
onStopPressing(): void;
/** @internal @override */
beginPress(input: MomentumGestureInput, event: Event | null): void;
/** @protected @override */
onBeginPress(input: MomentumGestureInput, event: Event | null): void;
/** @protected @override */
onMovePress(input: MomentumGestureInput, event: Event | null): void;
/** @protected @override */
willEndPress(input: MomentumGestureInput, event: Event | null): void;
/** @protected @override */
onEndPress(input: MomentumGestureInput, event: Event | null): void;
/** @protected @override */
onCancelPress(input: MomentumGestureInput, event: Event | null): void;
readonly coastCount: number;
get coasting(): boolean;
/** @internal */
startCoasting(): void;
/** @protected */
willStartCoasting(): void;
/** @protected */
onStartCoasting(): void;
/** @protected */
didStartCoasting(): void;
/** @internal */
stopCoasting(): void;
/** @protected */
willStopCoasting(): void;
/** @protected */
onStopCoasting(): void;
/** @protected */
didStopCoasting(): void;
/** @internal */
beginCoast(input: MomentumGestureInput, event: Event | null): void;
/** @protected */
willBeginCoast(input: MomentumGestureInput, event: Event | null): boolean | void;
/** @protected */
onBeginCoast(input: MomentumGestureInput, event: Event | null): void;
/** @protected */
didBeginCoast(input: MomentumGestureInput, event: Event | null): void;
/** @internal */
endCoast(input: MomentumGestureInput, event: Event | null): void;
/** @protected */
willEndCoast(input: MomentumGestureInput, event: Event | null): void;
/** @protected */
onEndCoast(input: MomentumGestureInput, event: Event | null): void;
/** @protected */
didEndCoast(input: MomentumGestureInput, event: Event | null): void;
/** @internal */
doCoast(t: number): void;
/** @protected */
willCoast(): void;
/** @protected */
onCoast(): void;
/** @protected */
didCoast(): void;
/** @internal */
integrate(t: number): void;
}
/** @public */
export const MomentumGesture = (function (_super: typeof PositionGesture) {
const MomentumGesture: MomentumGestureFactory = _super.extend("MomentumGesture");
Object.defineProperty(MomentumGesture.prototype, "observes", {
value: true,
enumerable: true,
configurable: true,
});
MomentumGesture.prototype.createInput = function (this: MomentumGesture, inputId: string, inputType: GestureInputType, isPrimary: boolean,
x: number, y: number, t: number): MomentumGestureInput {
return new MomentumGestureInput(inputId, inputType, isPrimary, x, y, t);
};
MomentumGesture.prototype.clearInput = function (this: MomentumGesture, input: MomentumGestureInput): void {
if (!input.coasting) {
PositionGesture.prototype.clearInput.call(this, input);
}
};
MomentumGesture.prototype.clearInputs = function (this: MomentumGesture): void {
PositionGesture.prototype.clearInputs.call(this);
(this as Mutable<typeof this>).coastCount = 0;
};
MomentumGesture.prototype.viewWillAnimate = function (this: MomentumGesture, viewContext: ViewContext): void {
this.doCoast(viewContext.updateTime);
};
MomentumGesture.prototype.interrupt = function (this: MomentumGesture, event: Event | null): void {
const inputs = this.inputs;
for (const inputId in inputs) {
const input = inputs[inputId]!;
this.endCoast(input, event);
}
};
MomentumGesture.prototype.cancel = function (this: MomentumGesture, event: Event | null): void {
const inputs = this.inputs;
for (const inputId in inputs) {
const input = inputs[inputId]!;
this.endPress(input, event);
this.endCoast(input, event);
}
};
MomentumGesture.prototype.startInteracting = function (this: MomentumGesture): void {
this.willStartInteracting();
this.onStartInteracting();
this.didStartInteracting();
};
MomentumGesture.prototype.willStartInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onStartInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.didStartInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.stopInteracting = function (this: MomentumGesture): void {
this.willStopInteracting();
this.onStopInteracting();
this.didStopInteracting();
};
MomentumGesture.prototype.willStopInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onStopInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.didStopInteracting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onStartPressing = function (this: MomentumGesture): void {
PositionGesture.prototype.onStartPressing.call(this);
if (this.coastCount === 0) {
this.startInteracting();
}
};
MomentumGesture.prototype.onStopPressing = function (this: MomentumGesture): void {
PositionGesture.prototype.onStopPressing.call(this);
if (this.coastCount === 0) {
this.stopInteracting();
}
};
MomentumGesture.prototype.beginPress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.beginPress.call(this, input, event);
this.interrupt(event);
};
MomentumGesture.prototype.onBeginPress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.onBeginPress.call(this, input, event);
input.updatePosition(this.hysteresis);
input.deriveVelocity(this.velocityMax);
};
MomentumGesture.prototype.onMovePress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.onMovePress.call(this, input, event);
input.updatePosition(this.hysteresis);
input.deriveVelocity(this.velocityMax);
};
MomentumGesture.prototype.willEndPress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.willEndPress.call(this, input, event);
this.beginCoast(input, event);
};
MomentumGesture.prototype.onEndPress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.onEndPress.call(this, input, event);
input.updatePosition(this.hysteresis);
input.deriveVelocity(this.velocityMax);
};
MomentumGesture.prototype.onCancelPress = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
PositionGesture.prototype.onCancelPress.call(this, input, event);
input.updatePosition(this.hysteresis);
input.deriveVelocity(this.velocityMax);
};
Object.defineProperty(MomentumGesture.prototype, "coasting", {
get(this: MomentumGesture): boolean {
return this.coastCount !== 0;
},
configurable: true,
})
MomentumGesture.prototype.startCoasting = function (this: MomentumGesture): void {
this.willStartCoasting();
this.onStartCoasting();
this.didStartCoasting();
};
MomentumGesture.prototype.willStartCoasting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onStartCoasting = function (this: MomentumGesture): void {
if (this.pressCount === 0) {
this.startInteracting();
}
if (this.view !== null) {
this.view.requireUpdate(View.NeedsAnimate);
}
};
MomentumGesture.prototype.didStartCoasting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.stopCoasting = function (this: MomentumGesture): void {
this.willStopCoasting();
this.onStopCoasting();
this.didStopCoasting();
};
MomentumGesture.prototype.willStopCoasting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onStopCoasting = function (this: MomentumGesture): void {
if (this.pressCount === 0) {
this.stopInteracting();
}
};
MomentumGesture.prototype.didStopCoasting = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.beginCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
if (!input.coasting && (input.vx !== 0 || input.vy !== 0)) {
const angle = Math.atan2(Math.abs(input.vy), Math.abs(input.vx));
const a = this.acceleration;
const ax = (input.vx < 0 ? a : input.vx > 0 ? -a : 0) * Math.cos(angle);
const ay = (input.vy < 0 ? a : input.vy > 0 ? -a : 0) * Math.sin(angle);
if (ax !== 0 || ay !== 0) {
input.ax = ax;
input.ay = ay;
let allowCoast = this.willBeginCoast(input, event);
if (allowCoast === void 0) {
allowCoast = true;
}
if (allowCoast) {
input.coasting = true;
(this as Mutable<typeof this>).coastCount += 1;
this.onBeginCoast(input, event);
this.didBeginCoast(input, event);
if (this.coastCount === 1) {
this.startCoasting();
}
}
}
}
};
MomentumGesture.prototype.willBeginCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): boolean | void {
// hook
};
MomentumGesture.prototype.onBeginCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
input.x0 = input.x;
input.y0 = input.y;
input.t0 = input.t;
input.dx = 0;
input.dy = 0;
input.dt = 0;
};
MomentumGesture.prototype.didBeginCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
// hook
};
MomentumGesture.prototype.endCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
if (input.coasting) {
this.willEndCoast(input, event);
input.coasting = false;
(this as Mutable<typeof this>).coastCount -= 1;
this.onEndCoast(input, event);
this.didEndCoast(input, event);
if (this.coastCount === 0) {
this.stopCoasting();
}
this.clearInput(input);
}
};
MomentumGesture.prototype.willEndCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
// hook
};
MomentumGesture.prototype.onEndCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
// hook
};
MomentumGesture.prototype.didEndCoast = function (this: MomentumGesture, input: MomentumGestureInput, event: Event | null): void {
// hook
};
MomentumGesture.prototype.doCoast = function (this: MomentumGesture, t: number): void {
if (this.coastCount !== 0) {
this.willCoast();
this.integrate(t);
this.onCoast();
const inputs = this.inputs;
for (const inputId in inputs) {
const input = inputs[inputId]!;
if (input.coasting && input.ax === 0 && input.ay === 0) {
this.endCoast(input, null);
}
}
this.didCoast();
if (this.coastCount !== 0 && this.view !== null) {
this.view.requireUpdate(View.NeedsAnimate);
}
}
};
MomentumGesture.prototype.willCoast = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.onCoast = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.didCoast = function (this: MomentumGesture): void {
// hook
};
MomentumGesture.prototype.integrate = function (this: MomentumGesture, t: number): void {
const inputs = this.inputs;
for (const inputId in inputs) {
const input = inputs[inputId]!;
if (input.coasting) {
input.integrateVelocity(t);
}
}
};
MomentumGesture.construct = function <G extends MomentumGesture<any, any>>(gestureClass: {prototype: G}, gesture: G | null, owner: FastenerOwner<G>): G {
gesture = _super.construct(gestureClass, gesture, owner) as G;
(gesture as Mutable<typeof gesture>).coastCount = 0;
gesture.hysteresis = MomentumGesture.Hysteresis;
gesture.acceleration = MomentumGesture.Acceleration;
gesture.velocityMax = MomentumGesture.VelocityMax;
return gesture;
};
MomentumGesture.specialize = function (method: GestureMethod): MomentumGestureFactory | null {
if (method === "pointer") {
return PointerMomentumGesture;
} else if (method === "touch") {
return TouchMomentumGesture;
} else if (method === "mouse") {
return MouseMomentumGesture;
} else if (typeof PointerEvent !== "undefined") {
return PointerMomentumGesture;
} else if (typeof TouchEvent !== "undefined") {
return TouchMomentumGesture;
} else {
return MouseMomentumGesture;
}
};
MomentumGesture.define = function <O, V extends View>(className: string, descriptor: MomentumGestureDescriptor<O, V>): MomentumGestureFactory<MomentumGesture<any, V>> {
let superClass = descriptor.extends as MomentumGestureFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
let method = descriptor.method;
const hysteresis = descriptor.hysteresis;
const acceleration = descriptor.hysteresis;
const velocityMax = descriptor.hysteresis;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.method;
delete descriptor.hysteresis;
delete descriptor.acceleration;
delete descriptor.velocityMax;
if (descriptor.key === true) {
Object.defineProperty(descriptor, "key", {
value: className,
configurable: true,
});
} else if (descriptor.key === false) {
Object.defineProperty(descriptor, "key", {
value: void 0,
configurable: true,
});
}
if (method === void 0) {
method = "auto";
}
if (superClass === void 0 || superClass === null) {
superClass = MomentumGesture.specialize(method);
}
if (superClass === null) {
superClass = this;
}
const gestureClass = superClass.extend(className, descriptor);
gestureClass.construct = function (gestureClass: {prototype: MomentumGesture<any, any>}, gesture: MomentumGesture<O, V> | null, owner: O): MomentumGesture<O, V> {
gesture = superClass!.construct(gestureClass, gesture, owner);
if (affinity !== void 0) {
gesture.initAffinity(affinity);
}
if (inherits !== void 0) {
gesture.initInherits(inherits);
}
if (hysteresis !== void 0) {
gesture.hysteresis = hysteresis;
}
if (acceleration !== void 0) {
gesture.acceleration = acceleration;
}
if (velocityMax !== void 0) {
gesture.velocityMax = velocityMax;
}
return gesture;
};
return gestureClass;
};
(MomentumGesture as Mutable<typeof MomentumGesture>).Hysteresis = 67;
(MomentumGesture as Mutable<typeof MomentumGesture>).Acceleration = 0.00175;
(MomentumGesture as Mutable<typeof MomentumGesture>).VelocityMax = 1.75;
return MomentumGesture;
})(PositionGesture); | the_stack |
import {
TSDocTagDefinition,
TSDocTagSyntaxKind,
TSDocConfiguration,
ParserMessageLog,
TSDocMessageId,
ParserMessage,
TextRange,
IParserMessageParameters,
ITSDocTagDefinitionParameters,
} from '@microsoft/tsdoc';
import * as fs from 'fs';
import * as resolve from 'resolve';
import * as path from 'path';
import Ajv from 'ajv';
import * as jju from 'jju';
const ajv: Ajv.Ajv = new Ajv({ verbose: true });
function initializeSchemaValidator(): Ajv.ValidateFunction {
const jsonSchemaPath: string = resolve.sync('@microsoft/tsdoc/schemas/tsdoc.schema.json', { basedir: __dirname });
const jsonSchemaContent: string = fs.readFileSync(jsonSchemaPath).toString();
const jsonSchema: object = jju.parse(jsonSchemaContent, { mode: 'cjson' });
return ajv.compile(jsonSchema);
}
// Warning: AJV has a fairly strange API. Each time this function is called, the function object's
// properties get overwritten with the results of the latest validation. Thus we need to be careful
// to read the properties before a subsequent call may occur.
const tsdocSchemaValidator: Ajv.ValidateFunction = initializeSchemaValidator();
interface ITagConfigJson {
tagName: string;
syntaxKind: 'inline' | 'block' | 'modifier';
allowMultiple?: boolean;
}
interface IConfigJson {
$schema: string;
extends?: string[];
noStandardTags?: boolean;
tagDefinitions?: ITagConfigJson[];
supportForTags?: { [tagName: string]: boolean };
supportedHtmlElements?: string[];
reportUnsupportedHtmlElements?: boolean;
}
/**
* Represents an individual `tsdoc.json` file.
*
* @public
*/
export class TSDocConfigFile {
public static readonly FILENAME: string = 'tsdoc.json';
public static readonly CURRENT_SCHEMA_URL: string =
'https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json';
/**
* A queryable log that reports warnings and error messages that occurred during parsing.
*/
public readonly log: ParserMessageLog;
private readonly _extendsFiles: TSDocConfigFile[];
private _filePath: string;
private _fileNotFound: boolean;
private _fileMTime: number;
private _hasErrors: boolean;
private _tsdocSchema: string;
private readonly _extendsPaths: string[];
private _noStandardTags: boolean | undefined;
private readonly _tagDefinitions: TSDocTagDefinition[];
private readonly _tagDefinitionNames: Set<string>;
private readonly _supportForTags: Map<string, boolean>;
private _supportedHtmlElements: Set<string> | undefined;
private _reportUnsupportedHtmlElements: boolean | undefined;
private constructor() {
this.log = new ParserMessageLog();
this._extendsFiles = [];
this._filePath = '';
this._fileNotFound = false;
this._hasErrors = false;
this._fileMTime = 0;
this._tsdocSchema = '';
this._extendsPaths = [];
this._noStandardTags = undefined;
this._tagDefinitions = [];
this._tagDefinitionNames = new Set();
this._supportForTags = new Map();
}
/**
* Other config files that this file extends from.
*/
public get extendsFiles(): ReadonlyArray<TSDocConfigFile> {
return this._extendsFiles;
}
/**
* The full path of the file that was attempted to load, or an empty string if the configuration was
* loaded from a source that is not a file.
*/
public get filePath(): string {
return this._filePath;
}
/**
* If true, then the TSDocConfigFile object contains an empty state, because the `tsdoc.json` file
* was not found by the loader.
*
* @remarks
* A missing "tsdoc.json" file is not considered an error. It simply means that the defaults will be used.
*/
public get fileNotFound(): boolean {
return this._fileNotFound;
}
/**
* If true, then at least one error was encountered while loading this file or one of its "extends" files.
*
* @remarks
* You can use {@link TSDocConfigFile.getErrorSummary} to report these errors.
*
* The individual messages can be retrieved from the {@link TSDocConfigFile.log} property of each `TSDocConfigFile`
* object (including the {@link TSDocConfigFile.extendsFiles} tree).
*/
public get hasErrors(): boolean {
return this._hasErrors;
}
/**
* The `$schema` field from the `tsdoc.json` file.
*/
public get tsdocSchema(): string {
return this._tsdocSchema;
}
/**
* The `extends` field from the `tsdoc.json` file. For the parsed file contents,
* use the `extendsFiles` property instead.
*/
public get extendsPaths(): ReadonlyArray<string> {
return this._extendsPaths;
}
/**
* By default, the config file loader will predefine all of the standardized TSDoc tags. To disable this and
* start with a completely empty configuration, set `noStandardTags` to true.
*
* @remarks
* If a config file uses `"extends"` to include settings from base config files, then its setting will
* override any settings from the base config files. If `"noStandardTags"` is not specified, then this
* property will be `undefined`. The config files are applied in the order they are processed (a depth-first
* traversal of the `"extends"` references), and files processed later can override earlier files.
* If no config file specifies `noStandardTags` then the default value is `false`.
*/
public get noStandardTags(): boolean | undefined {
return this._noStandardTags;
}
public set noStandardTags(value: boolean | undefined) {
this._noStandardTags = value;
}
public get tagDefinitions(): ReadonlyArray<TSDocTagDefinition> {
return this._tagDefinitions;
}
public get supportForTags(): ReadonlyMap<string, boolean> {
return this._supportForTags;
}
public get supportedHtmlElements(): ReadonlyArray<string> | undefined {
return this._supportedHtmlElements && Array.from(this._supportedHtmlElements);
}
public get reportUnsupportedHtmlElements(): boolean | undefined {
return this._reportUnsupportedHtmlElements;
}
public set reportUnsupportedHtmlElements(value: boolean | undefined) {
this._reportUnsupportedHtmlElements = value;
}
/**
* Removes all items from the `tagDefinitions` array.
*/
public clearTagDefinitions(): void {
this._tagDefinitions.length = 0;
this._tagDefinitionNames.clear();
}
/**
* Adds a new item to the `tagDefinitions` array.
*/
public addTagDefinition(parameters: ITSDocTagDefinitionParameters): void {
// This validates the tag name
const tagDefinition: TSDocTagDefinition = new TSDocTagDefinition(parameters);
if (this._tagDefinitionNames.has(tagDefinition.tagNameWithUpperCase)) {
throw new Error(`A tag definition was already added with the tag name "${parameters.tagName}"`);
}
this._tagDefinitionNames.add(tagDefinition.tagName);
this._tagDefinitions.push(tagDefinition);
}
// Similar to addTagDefinition() but reports errors using _reportError()
private _addTagDefinitionForLoad(parameters: ITSDocTagDefinitionParameters): void {
let tagDefinition: TSDocTagDefinition;
try {
// This validates the tag name
tagDefinition = new TSDocTagDefinition(parameters);
} catch (error) {
this._reportError({
messageId: TSDocMessageId.ConfigFileInvalidTagName,
messageText: error.message,
textRange: TextRange.empty,
});
return;
}
if (this._tagDefinitionNames.has(tagDefinition.tagNameWithUpperCase)) {
this._reportError({
messageId: TSDocMessageId.ConfigFileDuplicateTagName,
messageText: `The "tagDefinitions" field specifies more than one tag with the name "${parameters.tagName}"`,
textRange: TextRange.empty,
});
}
this._tagDefinitionNames.add(tagDefinition.tagNameWithUpperCase);
this._tagDefinitions.push(tagDefinition);
}
/**
* Adds a new item to the `supportedHtmlElements` array.
*/
public addSupportedHtmlElement(htmlElement: string): void {
if (!this._supportedHtmlElements) {
this._supportedHtmlElements = new Set();
}
this._supportedHtmlElements.add(htmlElement);
}
/**
* Removes the explicit list of allowed html elements.
*/
public clearSupportedHtmlElements(): void {
this._supportedHtmlElements = undefined;
}
/**
* Removes all entries from the "supportForTags" map.
*/
public clearSupportForTags(): void {
this._supportForTags.clear();
}
/**
* Sets an entry in the "supportForTags" map.
*/
public setSupportForTag(tagName: string, supported: boolean): void {
TSDocTagDefinition.validateTSDocTagName(tagName);
this._supportForTags.set(tagName, supported);
}
/**
* This can be used for cache eviction. It returns true if the modification timestamp has changed for
* any of the files that were read when loading this `TSDocConfigFile`, which indicates that the file should be
* reloaded. It does not consider cases where `TSDocConfigFile.fileNotFound` was `true`.
*
* @remarks
* This can be used for cache eviction. An example eviction strategy might be like this:
*
* - call `checkForModifiedFiles()` once per second, and reload the configuration if it returns true
*
* - otherwise, reload the configuration when it is more than 10 seconds old (to handle less common cases such
* as creation of a missing file, or creation of a file at an earlier location in the search path).
*/
public checkForModifiedFiles(): boolean {
if (this._checkForModifiedFile()) {
return true;
}
for (const extendsFile of this.extendsFiles) {
if (extendsFile.checkForModifiedFiles()) {
return true;
}
}
return false;
}
/**
* Checks the last modification time for `TSDocConfigFile.filePath` and returns `true` if it has changed
* since the file was loaded. If the file is missing, this returns `false`. If the timestamp cannot be read,
* then this returns `true`.
*/
private _checkForModifiedFile(): boolean {
if (this._fileNotFound || !this._filePath) {
return false;
}
try {
const mtimeMs: number = fs.statSync(this._filePath).mtimeMs;
return mtimeMs !== this._fileMTime;
} catch (error) {
return true;
}
}
private _reportError(parserMessageParameters: IParserMessageParameters): void {
this.log.addMessage(new ParserMessage(parserMessageParameters));
this._hasErrors = true;
}
private _loadJsonObject(configJson: IConfigJson): void {
if (configJson.$schema !== TSDocConfigFile.CURRENT_SCHEMA_URL) {
this._reportError({
messageId: TSDocMessageId.ConfigFileUnsupportedSchema,
messageText: `Unsupported JSON "$schema" value; expecting "${TSDocConfigFile.CURRENT_SCHEMA_URL}"`,
textRange: TextRange.empty,
});
return;
}
const success: boolean = tsdocSchemaValidator(configJson) as boolean;
if (!success) {
const description: string = ajv.errorsText(tsdocSchemaValidator.errors);
this._reportError({
messageId: TSDocMessageId.ConfigFileSchemaError,
messageText: 'Error loading config file: ' + description,
textRange: TextRange.empty,
});
return;
}
this._tsdocSchema = configJson.$schema;
if (configJson.extends) {
this._extendsPaths.push(...configJson.extends);
}
this.noStandardTags = configJson.noStandardTags;
for (const jsonTagDefinition of configJson.tagDefinitions || []) {
let syntaxKind: TSDocTagSyntaxKind;
switch (jsonTagDefinition.syntaxKind) {
case 'inline':
syntaxKind = TSDocTagSyntaxKind.InlineTag;
break;
case 'block':
syntaxKind = TSDocTagSyntaxKind.BlockTag;
break;
case 'modifier':
syntaxKind = TSDocTagSyntaxKind.ModifierTag;
break;
default:
// The JSON schema should have caught this error
throw new Error('Unexpected tag kind');
}
this._addTagDefinitionForLoad({
tagName: jsonTagDefinition.tagName,
syntaxKind: syntaxKind,
allowMultiple: jsonTagDefinition.allowMultiple,
});
}
if (configJson.supportedHtmlElements) {
this._supportedHtmlElements = new Set();
for (const htmlElement of configJson.supportedHtmlElements) {
this.addSupportedHtmlElement(htmlElement);
}
}
this._reportUnsupportedHtmlElements = configJson.reportUnsupportedHtmlElements;
if (configJson.supportForTags) {
for (const tagName of Object.keys(configJson.supportForTags)) {
const supported: boolean = configJson.supportForTags[tagName];
this._supportForTags.set(tagName, supported);
}
}
}
private _loadWithExtends(
configFilePath: string,
referencingConfigFile: TSDocConfigFile | undefined,
alreadyVisitedPaths: Set<string>
): void {
// In case an exception is thrown, start by assuming that the file was not found; we'll revise
// this later upon success
this._fileNotFound = true;
if (!configFilePath) {
this._reportError({
messageId: TSDocMessageId.ConfigFileNotFound,
messageText: 'File not found',
textRange: TextRange.empty,
});
return;
}
this._filePath = path.resolve(configFilePath);
if (!fs.existsSync(this._filePath)) {
this._reportError({
messageId: TSDocMessageId.ConfigFileNotFound,
messageText: 'File not found',
textRange: TextRange.empty,
});
return;
}
const configJsonContent: string = fs.readFileSync(this._filePath).toString();
this._fileMTime = fs.statSync(this._filePath).mtimeMs;
this._fileNotFound = false;
const hashKey: string = fs.realpathSync(this._filePath);
if (referencingConfigFile && alreadyVisitedPaths.has(hashKey)) {
this._reportError({
messageId: TSDocMessageId.ConfigFileCyclicExtends,
messageText: `Circular reference encountered for "extends" field of "${referencingConfigFile.filePath}"`,
textRange: TextRange.empty,
});
return;
}
alreadyVisitedPaths.add(hashKey);
let configJson: IConfigJson;
try {
configJson = jju.parse(configJsonContent, { mode: 'cjson' });
} catch (e) {
this._reportError({
messageId: TSDocMessageId.ConfigInvalidJson,
messageText: 'Error parsing JSON input: ' + e.message,
textRange: TextRange.empty,
});
return;
}
this._loadJsonObject(configJson);
const configFileFolder: string = path.dirname(this.filePath);
for (const extendsField of this.extendsPaths) {
let resolvedExtendsPath: string;
try {
resolvedExtendsPath = resolve.sync(extendsField, { basedir: configFileFolder });
} catch (e) {
this._reportError({
messageId: TSDocMessageId.ConfigFileUnresolvedExtends,
messageText: `Unable to resolve "extends" reference to "${extendsField}": ` + e.message,
textRange: TextRange.empty,
});
return;
}
const baseConfigFile: TSDocConfigFile = new TSDocConfigFile();
baseConfigFile._loadWithExtends(resolvedExtendsPath, this, alreadyVisitedPaths);
if (baseConfigFile.fileNotFound) {
this._reportError({
messageId: TSDocMessageId.ConfigFileUnresolvedExtends,
messageText: `Unable to resolve "extends" reference to "${extendsField}"`,
textRange: TextRange.empty,
});
}
this._extendsFiles.push(baseConfigFile);
if (baseConfigFile.hasErrors) {
this._hasErrors = true;
}
}
}
/**
* For the given folder, look for the relevant tsdoc.json file (if any), and return its path.
*
* @param folderPath - the path to a folder where the search should start
* @returns the (possibly relative) path to tsdoc.json, or an empty string if not found
*/
public static findConfigPathForFolder(folderPath: string): string {
if (folderPath) {
let foundFolder: string = folderPath;
for (;;) {
const tsconfigJsonPath: string = path.join(foundFolder, 'tsconfig.json');
if (fs.existsSync(tsconfigJsonPath)) {
// Stop when we reach a folder containing tsconfig.json
return path.join(foundFolder, TSDocConfigFile.FILENAME);
}
const packageJsonPath: string = path.join(foundFolder, 'package.json');
if (fs.existsSync(packageJsonPath)) {
// Stop when we reach a folder containing package.json; this avoids crawling out of the current package
return path.join(foundFolder, TSDocConfigFile.FILENAME);
}
const previousFolder: string = foundFolder;
foundFolder = path.dirname(foundFolder);
if (!foundFolder || foundFolder === previousFolder) {
// Give up if we reach the filesystem root directory
break;
}
}
}
return '';
}
/**
* Calls `TSDocConfigFile.findConfigPathForFolder()` to find the relevant tsdoc.json config file, if one exists.
* Then calls `TSDocConfigFile.findConfigPathForFolder()` to return the loaded result.
*
* @remarks
* This API does not report loading errors by throwing exceptions. Instead, the caller is expected to check
* for errors using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log},
* or {@link TSDocConfigFile.getErrorSummary}.
*
* @param folderPath - the path to a folder where the search should start
*/
public static loadForFolder(folderPath: string): TSDocConfigFile {
const rootConfigPath: string = TSDocConfigFile.findConfigPathForFolder(folderPath);
return TSDocConfigFile.loadFile(rootConfigPath);
}
/**
* Loads the specified tsdoc.json and any base files that it refers to using the "extends" option.
*
* @remarks
* This API does not report loading errors by throwing exceptions. Instead, the caller is expected to check
* for errors using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log},
* or {@link TSDocConfigFile.getErrorSummary}.
*
* @param tsdocJsonFilePath - the path to the tsdoc.json config file
*/
public static loadFile(tsdocJsonFilePath: string): TSDocConfigFile {
const configFile: TSDocConfigFile = new TSDocConfigFile();
const alreadyVisitedPaths: Set<string> = new Set<string>();
configFile._loadWithExtends(tsdocJsonFilePath, undefined, alreadyVisitedPaths);
return configFile;
}
/**
* Loads the object state from a JSON-serializable object as produced by {@link TSDocConfigFile.saveToObject}.
*
* @remarks
* The serialized object has the same structure as `tsdoc.json`; however the `"extends"` field is not allowed.
*
* This API does not report loading errors by throwing exceptions. Instead, the caller is expected to check
* for errors using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log},
* or {@link TSDocConfigFile.getErrorSummary}.
*/
public static loadFromObject(jsonObject: unknown): TSDocConfigFile {
const configFile: TSDocConfigFile = new TSDocConfigFile();
configFile._loadJsonObject(jsonObject as IConfigJson);
if (configFile.extendsPaths.length > 0) {
throw new Error('The "extends" field cannot be used with TSDocConfigFile.loadFromObject()');
}
return configFile;
}
/**
* Initializes a TSDocConfigFile object using the state from the provided `TSDocConfiguration` object.
*
* @remarks
* This API does not report loading errors by throwing exceptions. Instead, the caller is expected to check
* for errors using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log},
* or {@link TSDocConfigFile.getErrorSummary}.
*/
public static loadFromParser(configuration: TSDocConfiguration): TSDocConfigFile {
const configFile: TSDocConfigFile = new TSDocConfigFile();
// The standard tags will be mixed together with custom definitions,
// so set noStandardTags=true to avoid defining them twice.
configFile.noStandardTags = true;
for (const tagDefinition of configuration.tagDefinitions) {
configFile.addTagDefinition({
syntaxKind: tagDefinition.syntaxKind,
tagName: tagDefinition.tagName,
allowMultiple: tagDefinition.allowMultiple,
});
}
for (const tagDefinition of configuration.supportedTagDefinitions) {
configFile.setSupportForTag(tagDefinition.tagName, true);
}
for (const htmlElement of configuration.supportedHtmlElements) {
configFile.addSupportedHtmlElement(htmlElement);
}
configFile.reportUnsupportedHtmlElements = configuration.validation.reportUnsupportedHtmlElements;
return configFile;
}
/**
* Writes the config file content to a JSON file with the specified file path.
*/
public saveFile(jsonFilePath: string): void {
const jsonObject: unknown = this.saveToObject();
const jsonContent: string = JSON.stringify(jsonObject, undefined, 2);
fs.writeFileSync(jsonFilePath, jsonContent);
}
/**
* Writes the object state into a JSON-serializable object.
*/
public saveToObject(): unknown {
const configJson: IConfigJson = {
$schema: TSDocConfigFile.CURRENT_SCHEMA_URL,
};
if (this.noStandardTags !== undefined) {
configJson.noStandardTags = this.noStandardTags;
}
if (this.tagDefinitions.length > 0) {
configJson.tagDefinitions = [];
for (const tagDefinition of this.tagDefinitions) {
configJson.tagDefinitions.push(TSDocConfigFile._serializeTagDefinition(tagDefinition));
}
}
if (this.supportForTags.size > 0) {
configJson.supportForTags = {};
this.supportForTags.forEach((supported, tagName) => {
configJson.supportForTags![tagName] = supported;
});
}
if (this.supportedHtmlElements) {
configJson.supportedHtmlElements = [...this.supportedHtmlElements];
}
if (this._reportUnsupportedHtmlElements !== undefined) {
configJson.reportUnsupportedHtmlElements = this._reportUnsupportedHtmlElements;
}
return configJson;
}
private static _serializeTagDefinition(tagDefinition: TSDocTagDefinition): ITagConfigJson {
let syntaxKind: 'inline' | 'block' | 'modifier' | undefined;
switch (tagDefinition.syntaxKind) {
case TSDocTagSyntaxKind.InlineTag:
syntaxKind = 'inline';
break;
case TSDocTagSyntaxKind.BlockTag:
syntaxKind = 'block';
break;
case TSDocTagSyntaxKind.ModifierTag:
syntaxKind = 'modifier';
break;
default:
throw new Error('Unimplemented TSDocTagSyntaxKind');
}
const tagConfigJson: ITagConfigJson = {
tagName: tagDefinition.tagName,
syntaxKind,
};
if (tagDefinition.allowMultiple) {
tagConfigJson.allowMultiple = true;
}
return tagConfigJson;
}
/**
* Returns a report of any errors that occurred while attempting to load this file or any files
* referenced via the "extends" field.
*
* @remarks
* Use {@link TSDocConfigFile.hasErrors} to determine whether any errors occurred.
*/
public getErrorSummary(): string {
if (!this._hasErrors) {
return 'No errors.';
}
let result: string = '';
if (this.log.messages.length > 0) {
const errorNoun: string = this.log.messages.length > 1 ? 'Errors' : 'Error';
if (this.filePath) {
result += `${errorNoun} encountered for ${this.filePath}:\n`;
} else {
result += `${errorNoun} encountered when loading TSDoc configuration:\n`;
}
for (const message of this.log.messages) {
result += ` ${message.text}\n`;
}
}
for (const extendsFile of this.extendsFiles) {
if (extendsFile.hasErrors) {
if (result !== '') {
result += '\n';
}
result += extendsFile.getErrorSummary();
}
}
return result;
}
/**
* Applies the settings from this config file to a TSDoc parser configuration.
* Any `extendsFile` settings will also applied.
*
* @remarks
* Additional validation is performed during this operation. The caller is expected to check for errors
* using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log}, or {@link TSDocConfigFile.getErrorSummary}.
*/
public configureParser(configuration: TSDocConfiguration): void {
if (this._getNoStandardTagsWithExtends()) {
// Do not define standard tags
configuration.clear(true);
} else {
// Define standard tags (the default behavior)
configuration.clear(false);
}
this.updateParser(configuration);
}
/**
* This is the same as {@link configureParser}, but it preserves any previous state.
*
* @remarks
* Additional validation is performed during this operation. The caller is expected to check for errors
* using {@link TSDocConfigFile.hasErrors}, {@link TSDocConfigFile.log}, or {@link TSDocConfigFile.getErrorSummary}.
*/
public updateParser(configuration: TSDocConfiguration): void {
// First apply the base config files
for (const extendsFile of this.extendsFiles) {
extendsFile.updateParser(configuration);
}
// Then apply this one
for (const tagDefinition of this.tagDefinitions) {
configuration.addTagDefinition(tagDefinition);
}
this.supportForTags.forEach((supported: boolean, tagName: string) => {
const tagDefinition: TSDocTagDefinition | undefined = configuration.tryGetTagDefinition(tagName);
if (tagDefinition) {
// Note that setSupportForTag() automatically enables configuration.validation.reportUnsupportedTags
configuration.setSupportForTag(tagDefinition, supported);
} else {
// Note that this validation may depend partially on the preexisting state of the TSDocConfiguration
// object, so it cannot be performed during the TSConfigFile.loadFile() stage.
this._reportError({
messageId: TSDocMessageId.ConfigFileUndefinedTag,
messageText: `The "supportForTags" field refers to an undefined tag ${JSON.stringify(tagName)}.`,
textRange: TextRange.empty,
});
}
});
if (this.supportedHtmlElements) {
configuration.setSupportedHtmlElements([...this.supportedHtmlElements]);
}
if (this._reportUnsupportedHtmlElements === false) {
configuration.validation.reportUnsupportedHtmlElements = false;
} else if (this._reportUnsupportedHtmlElements === true) {
configuration.validation.reportUnsupportedHtmlElements = true;
}
}
private _getNoStandardTagsWithExtends(): boolean {
if (this.noStandardTags !== undefined) {
return this.noStandardTags;
}
// This config file does not specify "noStandardTags", so consider any base files referenced using "extends"
let result: boolean | undefined = undefined;
for (const extendsFile of this.extendsFiles) {
const extendedValue: boolean | undefined = extendsFile._getNoStandardTagsWithExtends();
if (extendedValue !== undefined) {
result = extendedValue;
}
}
if (result === undefined) {
// If no config file specifies noStandardTags, then it defaults to false
result = false;
}
return result;
}
} | the_stack |
import React from 'react';
import { BarStack } from '@visx/shape';
import { SeriesPoint } from '@visx/shape/lib/types';
import { Group } from '@visx/group';
import { Grid } from '@visx/grid';
import { AxisBottom, AxisLeft } from '@visx/axis';
import { scaleBand, scaleLinear, scaleOrdinal } from '@visx/scale';
import { useTooltip, useTooltipInPortal, defaultStyles } from '@visx/tooltip';
import { Text } from '@visx/text';
import { schemeSet3 } from 'd3-scale-chromatic';
import { makeStyles } from '@material-ui/core/styles';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import { onHover, onHoverExit, deleteSeries } from '../actions/actions';
import { useStoreContext } from '../store';
/* TYPESCRIPT */
interface data {
snapshotId?: string;
}
interface series {
seriesId?: any;
}
interface margin {
top: number;
right: number;
bottom: number;
left: number;
}
interface snapshot {
snapshotId?: string;
children: [];
componentData: any;
name: string;
state: string;
}
// On-hover data.
interface TooltipData {
bar: SeriesPoint<snapshot>;
key: string;
index: number;
height: number;
width: number;
x: number;
y: number;
color: string;
}
/* DEFAULTS */
const margin = {
top: 30, right: 30, bottom: 0, left: 50,
};
const axisColor = '#62d6fb';
const background = '#242529';
const tooltipStyles = {
...defaultStyles,
minWidth: 60,
backgroundColor: 'rgba(0,0,0,0.9)',
color: 'white',
fontSize: '14px',
lineHeight: '18px',
fontFamily: 'Roboto',
};
const BarGraphComparison = props => {
const [{ tabs, currentTab }, dispatch] = useStoreContext();
const {
width, height, data, comparison,
} = props;
const [series, setSeries] = React.useState(0);
const [snapshots, setSnapshots] = React.useState(0);
const [open, setOpen] = React.useState(false);
const [picOpen, setPicOpen] = React.useState(false);
const [maxRender, setMaxRender] = React.useState(data.maxTotalRender);
function titleFilter(comparisonArray) {
return comparisonArray.filter(
elem => elem.title.split('-')[1] === tabs[currentTab].title.split('-')[1],
);
}
const currentIndex = tabs[currentTab].sliderIndex;
const {
tooltipOpen,
tooltipLeft,
tooltipTop,
tooltipData,
hideTooltip,
showTooltip,
} = useTooltip<TooltipData>();
let tooltipTimeout: number;
const { containerRef, TooltipInPortal } = useTooltipInPortal();
const keys = Object.keys(data.componentData);
// data accessor (used to generate scales) and formatter (add units for on hover box)
const getSnapshotId = (d: snapshot) => d.snapshotId;
const formatSnapshotId = id => `Snapshot ID: ${id}`;
const formatRenderTime = time => `${time} ms `;
const getCurrentTab = storedSeries => storedSeries.currentTab;
// create visualization SCALES with cleaned data
// the domain array/xAxisPoints elements will place the bars along the x-axis
const xAxisPoints = ['currentTab', 'comparison'];
const snapshotIdScale = scaleBand<string>({
domain: xAxisPoints,
padding: 0.2,
});
// This function will iterate through the snapshots of the series,
// and grab the highest render times (sum of all component times).
// We'll then use it in the renderingScale function and compare
// with the render time of the current tab.
// The max render time will determine the Y-axis's highest number.
const calculateMaxTotalRender = series => {
const currentSeriesBarStacks = !comparison[series]
? []
: comparison[series].data.barStack;
if (currentSeriesBarStacks.length === 0) return 0;
let currentMax = -Infinity;
for (let i = 0; i < currentSeriesBarStacks.length; i += 1) {
const renderTimes = Object.values(currentSeriesBarStacks[i]).slice(1);
const renderTotal = renderTimes.reduce((acc, curr) => acc + curr);
if (renderTotal > currentMax) currentMax = renderTotal;
}
return currentMax;
};
// the domain array on rendering scale will set the coordinates for Y-aix points.
const renderingScale = scaleLinear<number>({
domain: [0, Math.max(calculateMaxTotalRender(series), data.maxTotalRender)],
nice: true,
});
// the domain array will assign each key a different color to make rectangle boxes
// and use range to set the color scheme each bar
const colorScale = scaleOrdinal<string>({
domain: keys,
range: schemeSet3,
});
// setting max dimensions and scale ranges
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - 200;
snapshotIdScale.rangeRound([0, xMax]);
renderingScale.range([yMax, 0]);
// useStyles will change the styling on save series dropdown feature
const useStyles = makeStyles(theme => ({
formControl: {
margin: theme.spacing(1),
minWidth: 80,
height: 30,
},
select: {
minWidth: 80,
fontSize: '.75rem',
fontWeight: '200',
border: '1px solid grey',
borderRadius: 4,
color: 'grey',
height: 30,
},
}));
const classes = useStyles();
const handleChange = event => {
setSeries(event.target.value);
// setXpoints();
};
const handleClose = () => {
setOpen(false);
// setXpoints();
};
const handleOpen = () => {
setOpen(true);
// setXpoints();
};
const picHandleChange = event => {
setSnapshots(`${(event.target.value + 1).toString()}.0`);
// setXpoints();
};
const picHandleClose = () => {
setPicOpen(false);
// setXpoints();
};
const picHandleOpen = () => {
setPicOpen(true);
// setXpoints();
};
// manually assignin X -axis points with tab ID.
function setXpointsComparison() {
comparison[series].data.barStack.forEach(elem => {
elem.currentTab = 'comparison';
});
// comparison[series].data.barStack.currentTab = currentTab;
return comparison[series].data.barStack;
}
function setXpointsCurrentTab() {
data.barStack.forEach(element => {
element.currentTab = 'currentTab';
});
return data.barStack;
}
const animateButton = function (e) {
e.preventDefault;
e.target.classList.add('animate');
e.target.innerHTML = 'Deleted!';
setTimeout(() => {
e.target.innerHTML = 'Clear All Series';
e.target.classList.remove('animate');
}, 1000);
};
const classname = document.getElementsByClassName('delete-button');
for (let i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', animateButton, false);
}
return (
<div>
<div className="series-options-container">
<div className="dropdown-and-delete-series-container">
<button
className="delete-button"
onClick={e => {
dispatch(deleteSeries());
}}
>
Clear All Series
</button>
<h4 style={{ padding: '0 1rem' }}>Comparison Series: </h4>
<FormControl variant="outlined" className={classes.formControl}>
<Select
style={{ color: 'white' }}
labelId="simple-select-outlined-label"
id="simple-select-outlined"
className={classes.select}
open={open}
onClose={handleClose}
onOpen={handleOpen}
value={series}
onChange={handleChange}
>
{!comparison[series] ? (
<MenuItem>No series available</MenuItem>
) : (
titleFilter(comparison).map((tabElem, index) => (
<MenuItem value={index}>{`Series ${index + 1}`}</MenuItem>
))
)}
</Select>
</FormControl>
{/* <h4 style={{ padding: '0 1rem' }}>Comparator Snapshot? </h4>
<FormControl variant="outlined" className={classes.formControl}>
<Select
style={{ color: 'white' }}
labelId="snapshot-select"
id="snapshot-select"
className={classes.select}
open={picOpen}
onClose={picHandleClose}
onOpen={picHandleOpen}
value={snapshots} //snapshots
onChange={picHandleChange}
>
{!comparison[snapshots] ? (
<MenuItem>No snapshots available</MenuItem>
) : (
titleFilter(comparison).map((tabElem, index) => {
return (
<MenuItem value={index}>{`${index + 1}`}</MenuItem>
);
})
)}
</Select>
</FormControl> */}
</div>
</div>
<svg ref={containerRef} width={width} height={height}>
{}
<rect
x={0}
y={0}
width={width}
height={height}
fill={background}
rx={14}
/>
<Grid
top={margin.top}
left={margin.left}
xScale={snapshotIdScale}
yScale={renderingScale}
width={xMax}
height={yMax}
stroke="black"
strokeOpacity={0.1}
xOffset={snapshotIdScale.bandwidth() / 2}
/>
<Group top={margin.top} left={margin.left}>
<BarStack
// Current Tab bar stack.
data={setXpointsCurrentTab()}
keys={keys}
x={getCurrentTab}
xScale={snapshotIdScale}
yScale={renderingScale}
color={colorScale}
>
{barStacks => barStacks.map((barStack, idx) => {
// Uses map method to iterate through all components,
// creating a rect component (from visx) for each iteration.
// height/width/etc. are calculated by visx.
// to set X and Y scale, it will used the passed in function and
// will run it on the array thats outputted by data
const bar = barStack.bars[currentIndex];
if (Number.isNaN(bar.bar[1]) || bar.height < 0) {
bar.height = 0;
}
return (
<rect
key={`bar-stack-${idx}-NewView`}
x={bar.x}
y={bar.y}
height={bar.height === 0 ? null : bar.height}
width={bar.width}
fill={bar.color}
/* TIP TOOL EVENT HANDLERS */
// Hides tool tip once cursor moves off the current rect
onMouseLeave={() => {
dispatch(
onHoverExit(data.componentData[bar.key].rtid),
(tooltipTimeout = window.setTimeout(() => {
hideTooltip();
}, 300)),
);
}}
// Cursor position in window updates position of the tool tip
onMouseMove={event => {
dispatch(onHover(data.componentData[bar.key].rtid));
if (tooltipTimeout) clearTimeout(tooltipTimeout);
const top = event.clientY - margin.top - bar.height;
const left = bar.x + bar.width / 2;
showTooltip({
tooltipData: bar,
tooltipTop: top,
tooltipLeft: left,
});
}}
/>
);
})}
</BarStack>
<BarStack
// Comparison Barstack (populates based on series selected)
// to set X and Y scale, it will used the passed in function and
// will run it on the array thats outputted by data
data={!comparison[series] ? [] : setXpointsComparison()}
keys={keys}
x={getCurrentTab}
xScale={snapshotIdScale}
yScale={renderingScale}
color={colorScale}
>
{barStacks => barStacks.map((barStack, idx) => {
// Uses map method to iterate through all components,
// creating a rect component (from visx) for each iteration.
// height/width/etc. are calculated by visx.
if (!barStack.bars[currentIndex]) {
return <h1>No Comparison</h1>;
}
const bar = barStack.bars[currentIndex];
if (Number.isNaN(bar.bar[1]) || bar.height < 0) {
bar.height = 0;
}
return (
<rect
key={`bar-stack-${idx}-${bar.index}`}
x={bar.x}
y={bar.y}
height={bar.height === 0 ? null : bar.height}
width={bar.width}
fill={bar.color}
/* TIP TOOL EVENT HANDLERS */
// Hides tool tip once cursor moves off the current rect
onMouseLeave={() => {
dispatch(
onHoverExit(data.componentData[bar.key].rtid),
(tooltipTimeout = window.setTimeout(() => {
hideTooltip();
}, 300)),
);
}}
// Cursor position in window updates position of the tool tip
onMouseMove={event => {
dispatch(onHover(data.componentData[bar.key].rtid));
if (tooltipTimeout) clearTimeout(tooltipTimeout);
const top = event.clientY - margin.top - bar.height;
const left = bar.x + bar.width / 2;
showTooltip({
tooltipData: bar,
tooltipTop: top,
tooltipLeft: left,
});
}}
/>
);
})}
</BarStack>
</Group>
<AxisLeft
top={margin.top}
left={margin.left}
scale={renderingScale}
stroke={axisColor}
tickStroke={axisColor}
strokeWidth={2}
tickLabelProps={() => ({
fill: 'rgb(231, 231, 231)',
fontSize: 11,
verticalAnchor: 'middle',
textAnchor: 'end',
})}
/>
<AxisBottom
top={yMax + margin.top}
left={margin.left}
scale={snapshotIdScale}
stroke={axisColor}
tickStroke={axisColor}
strokeWidth={2}
tickLabelProps={() => ({
fill: 'rgb(231, 231, 231)',
fontSize: 11,
textAnchor: 'middle',
})}
/>
<Text
x={-xMax / 2}
y="15"
transform="rotate(-90)"
fontSize={12}
fill="#FFFFFF"
>
Rendering Time (ms)
</Text>
<Text x={xMax / 2} y={yMax + 65} fontSize={12} fill="#FFFFFF">
Series ID
</Text>
</svg>
{/* FOR HOVER OVER DISPLAY */}
{tooltipOpen && tooltipData && (
<TooltipInPortal
key={Math.random()} // update tooltip bounds each render
top={tooltipTop}
left={tooltipLeft}
style={tooltipStyles}
>
<div style={{ color: colorScale(tooltipData.key) }}>
{' '}
<strong>{tooltipData.key}</strong>
{' '}
</div>
<div>{data.componentData[tooltipData.key].stateType}</div>
<div>
{' '}
{formatRenderTime(tooltipData.bar.data[tooltipData.key])}
{' '}
</div>
<div>
{' '}
<small>
{formatSnapshotId(getSnapshotId(tooltipData.bar.data))}
</small>
</div>
</TooltipInPortal>
)}
</div>
);
};
export default BarGraphComparison; | the_stack |
import * as React from 'react';
import styles from '@patternfly/react-styles/css/components/SearchInput/search-input';
import { css } from '@patternfly/react-styles';
import { Button, ButtonVariant } from '../Button';
import { Badge } from '../Badge';
import AngleDownIcon from '@patternfly/react-icons/dist/esm/icons/angle-down-icon';
import AngleUpIcon from '@patternfly/react-icons/dist/esm/icons/angle-up-icon';
import TimesIcon from '@patternfly/react-icons/dist/esm/icons/times-icon';
import SearchIcon from '@patternfly/react-icons/dist/esm/icons/search-icon';
import CaretDownIcon from '@patternfly/react-icons/dist/esm/icons/caret-down-icon';
import ArrowRightIcon from '@patternfly/react-icons/dist/esm/icons/arrow-right-icon';
import { InputGroup } from '../InputGroup';
import { AdvancedSearchMenu } from './AdvancedSearchMenu';
export interface SearchAttribute {
/** The search attribute's value to be provided in the search input's query string.
* It should have no spaces and be unique for every attribute */
attr: string;
/** The search attribute's display name. It is used to label the field in the advanced search menu */
display: React.ReactNode;
}
export interface SearchInputProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange' | 'results' | 'ref'> {
/** Additional classes added to the banner */
className?: string;
/** Value of the search input */
value?: string;
/** Flag indicating if search input is disabled */
isDisabled?: boolean;
/** An accessible label for the search input */
'aria-label'?: string;
/** placeholder text of the search input */
placeholder?: string;
/** @hide A reference object to attach to the input box */
innerRef?: React.RefObject<any>;
/** A callback for when the input value changes */
onChange?: (value: string, event: React.FormEvent<HTMLInputElement>) => void;
/** A suggestion for autocompleting */
hint?: string;
/** A callback for when the search button clicked changes */
onSearch?: (
value: string,
event: React.SyntheticEvent<HTMLButtonElement>,
attrValueMap: { [key: string]: string }
) => void;
/** A callback for when the user clicks the clear button */
onClear?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
/** Label for the buttons which reset the advanced search form and clear the search input */
resetButtonLabel?: string;
/** Label for the buttons which called the onSearch event handler */
submitSearchButtonLabel?: string;
/** A callback for when the open advanced search button is clicked */
onToggleAdvancedSearch?: (event: React.SyntheticEvent<HTMLButtonElement>, isOpen?: boolean) => void;
/** A flag for controlling the open state of a custom advanced search implementation */
isAdvancedSearchOpen?: boolean;
/** Label for the button which opens the advanced search form menu */
openMenuButtonAriaLabel?: string;
/** Function called when user clicks to navigate to next result */
onNextClick?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
/** Function called when user clicks to navigate to previous result */
onPreviousClick?: (event: React.SyntheticEvent<HTMLButtonElement>) => void;
/** The number of search results returned. Either a total number of results,
* or a string representing the current result over the total number of results. i.e. "1 / 5" */
resultsCount?: number | string;
/** Array of attribute values used for dynamically generated advanced search */
attributes?: string[] | SearchAttribute[];
/* Additional elements added after the attributes in the form.
* The new form elements can be wrapped in a FormGroup component for automatic formatting */
formAdditionalItems?: React.ReactNode;
/** Attribute label for strings unassociated with one of the provided listed attributes */
hasWordsAttrLabel?: React.ReactNode;
/** Delimiter in the query string for pairing attributes with search values.
* Required whenever attributes are passed as props */
advancedSearchDelimiter?: string;
}
const SearchInputBase: React.FunctionComponent<SearchInputProps> = ({
className,
value = '',
attributes = [] as string[],
formAdditionalItems,
hasWordsAttrLabel = 'Has words',
advancedSearchDelimiter,
placeholder,
hint,
onChange,
onSearch,
onClear,
onToggleAdvancedSearch,
isAdvancedSearchOpen,
resultsCount,
onNextClick,
onPreviousClick,
innerRef,
'aria-label': ariaLabel = 'Search input',
resetButtonLabel = 'Reset',
openMenuButtonAriaLabel = 'Open advanced search',
submitSearchButtonLabel = 'Search',
isDisabled = false,
...props
}: SearchInputProps) => {
const [isSearchMenuOpen, setIsSearchMenuOpen] = React.useState(false);
const [searchValue, setSearchValue] = React.useState(value);
const searchInputRef = React.useRef(null);
const searchInputInputRef = innerRef || React.useRef(null);
React.useEffect(() => {
setSearchValue(value);
}, [value]);
React.useEffect(() => {
if (attributes.length > 0 && !advancedSearchDelimiter) {
// eslint-disable-next-line no-console
console.error(
'An advancedSearchDelimiter prop is required when advanced search attributes are provided using the attributes prop'
);
}
});
React.useEffect(() => {
setIsSearchMenuOpen(isAdvancedSearchOpen);
}, [isAdvancedSearchOpen]);
const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
if (onChange) {
onChange(event.currentTarget.value, event);
}
setSearchValue(event.currentTarget.value);
};
const onToggle = (e: React.SyntheticEvent<HTMLButtonElement>) => {
const isOpen = !isSearchMenuOpen;
setIsSearchMenuOpen(isOpen);
if (onToggleAdvancedSearch) {
onToggleAdvancedSearch(e, isOpen);
}
};
const onSearchHandler = (event: React.SyntheticEvent<HTMLButtonElement>) => {
event.preventDefault();
if (onSearch) {
onSearch(value, event, getAttrValueMap());
}
setIsSearchMenuOpen(false);
};
const getAttrValueMap = () => {
const attrValue: { [key: string]: string } = {};
const pairs = searchValue.split(' ');
pairs.map(pair => {
const splitPair = pair.split(advancedSearchDelimiter);
if (splitPair.length === 2) {
attrValue[splitPair[0]] = splitPair[1];
} else if (splitPair.length === 1) {
attrValue.haswords = attrValue.hasOwnProperty('haswords')
? `${attrValue.haswords} ${splitPair[0]}`
: splitPair[0];
}
});
return attrValue;
};
const onEnter = (event: React.KeyboardEvent<any>) => {
if (event.key === 'Enter') {
onSearchHandler(event);
}
};
const onClearInput = (e: React.SyntheticEvent<HTMLButtonElement>) => {
if (onClear) {
onClear(e);
}
if (searchInputInputRef && searchInputInputRef.current) {
searchInputInputRef.current.focus();
}
};
return (
<div className={css(className, styles.searchInput)} ref={searchInputRef} {...props}>
<InputGroup>
<div className={css(styles.searchInputBar)}>
<span className={css(styles.searchInputText)}>
<span className={css(styles.searchInputIcon)}>
<SearchIcon />
</span>
{hint && (
<input
className={css(styles.searchInputTextInput, styles.modifiers.hint)}
type="text"
disabled
aria-hidden="true"
value={hint}
/>
)}
<input
ref={searchInputInputRef}
className={css(styles.searchInputTextInput)}
value={searchValue}
placeholder={placeholder}
aria-label={ariaLabel}
onKeyDown={onEnter}
onChange={onChangeHandler}
disabled={isDisabled}
/>
</span>
{value && (
<span className={css(styles.searchInputUtilities)}>
{resultsCount && (
<span className={css(styles.searchInputCount)}>
<Badge isRead>{resultsCount}</Badge>
</span>
)}
{!!onNextClick && !!onPreviousClick && (
<span className={css(styles.searchInputNav)}>
<Button
variant={ButtonVariant.plain}
aria-label="Previous"
isDisabled={isDisabled}
onClick={onPreviousClick}
>
<AngleUpIcon />
</Button>
<Button variant={ButtonVariant.plain} aria-label="Next" isDisabled={isDisabled} onClick={onNextClick}>
<AngleDownIcon />
</Button>
</span>
)}
{!!onClear && (
<span className="pf-c-search-input__clear">
<Button
variant={ButtonVariant.plain}
isDisabled={isDisabled}
aria-label={resetButtonLabel}
onClick={onClearInput}
>
<TimesIcon />
</Button>
</span>
)}
</span>
)}
</div>
{(attributes.length > 0 || onToggleAdvancedSearch) && (
<Button
className={isSearchMenuOpen && 'pf-m-expanded'}
variant={ButtonVariant.control}
aria-label={openMenuButtonAriaLabel}
onClick={onToggle}
isDisabled={isDisabled}
aria-expanded={isSearchMenuOpen}
>
<CaretDownIcon />
</Button>
)}
{!!onSearch && (
<Button
type="submit"
variant={ButtonVariant.control}
aria-label={submitSearchButtonLabel}
onClick={onSearchHandler}
isDisabled={isDisabled}
>
<ArrowRightIcon />
</Button>
)}
</InputGroup>
{attributes.length > 0 && (
<AdvancedSearchMenu
value={value}
parentRef={searchInputRef}
parentInputRef={searchInputInputRef}
onSearch={onSearch}
onClear={onClear}
onChange={onChange}
onToggleAdvancedMenu={onToggle}
resetButtonLabel={resetButtonLabel}
submitSearchButtonLabel={submitSearchButtonLabel}
attributes={attributes}
formAdditionalItems={formAdditionalItems}
hasWordsAttrLabel={hasWordsAttrLabel}
advancedSearchDelimiter={advancedSearchDelimiter}
getAttrValueMap={getAttrValueMap}
isSearchMenuOpen={isSearchMenuOpen}
/>
)}
</div>
);
};
SearchInputBase.displayName = 'SearchInputBase';
export const SearchInput = React.forwardRef((props: SearchInputProps, ref: React.Ref<HTMLInputElement>) => (
<SearchInputBase {...props} innerRef={ref as React.MutableRefObject<any>} />
));
SearchInput.displayName = 'SearchInput'; | the_stack |
import {
BufferGeometry,
Float32BufferAttribute,
Mesh,
MeshBasicMaterial,
Object3D,
PlaneBufferGeometry,
Renderer,
sRGBEncoding,
Texture,
Uint32BufferAttribute,
WebGLRenderer
} from 'three';
import { moduloBy, createElement } from './utils';
type AdvancedHTMLVideoElement = HTMLVideoElement & { requestVideoFrameCallback: (callback: (number, { }) => void) => void };
type onMeshBufferingCallback = (progress: number) => void;
type onFrameShowCallback = (frame: number) => void;
type onRenderingCallback = () => void;
enum PlayModeEnum {
Single = 1,
Random,
Loop,
SingleLoop,
}
export default class Player {
static defaultWorkerURL = new URL('./worker.build.es.js', import.meta.url).href
// Public Fields
public frameRate: number = 30;
public speed: number = 1.0; // Multiplied by framerate for final playback output rate
public loop: boolean = true;
public encoderWindowSize = 8; // length of the databox
public encoderByteLength = 16;
public videoSize = 1024;
// Three objects
public scene: Object3D;
public renderer: Renderer;
public mesh: Mesh;
public paths: Array<String>;
public material: MeshBasicMaterial;
public failMaterial: MeshBasicMaterial;
public bufferGeometry: BufferGeometry;
public playMode: PlayModeEnum;
// Private Fields
private readonly _scale: number = 1;
private _video: HTMLVideoElement | AdvancedHTMLVideoElement = null;
private _videoTexture = null;
private meshBuffer: Map<number, BufferGeometry> = new Map();
private _worker: Worker;
private onMeshBuffering: onMeshBufferingCallback | null = null;
private onFrameShow: onFrameShowCallback | null = null;
private rendererCallback: onRenderingCallback | null = null;
fileHeader: any;
tempBufferObject: BufferGeometry;
private meshFilePath: String;
private currentTrack: number = 0;
private nextTrack: number = 0;
private manifestFilePath: any;
private videoFilePath: any;
private counterCtx: CanvasRenderingContext2D;
private actorCtx: CanvasRenderingContext2D;
private numberOfFrames: number = 0;
private numberOfNextFrames: number = 0;
private isWorkerWaitNextLoop: boolean = false;
private isWorkerReady: boolean = false;
private isWorkerBusy: boolean = false;
private isVideoReady: boolean = false;
private maxNumberOfFrames: number;
private actorCanvas: HTMLCanvasElement;
currentFrame: number = 0;
lastFrameRequested: number = 0;
targetFramesToRequest: number = 30;
set paused(value){
if(!value) this.play();
else {
this._video.pause();
this.hasPlayed = false;
this.stopOnNextFrame = false;
}
}
bufferLoop = () => {
const isOnLoop = this.lastFrameRequested < this.currentFrame;
for (const [key, buffer] of this.meshBuffer.entries()) {
// If key is between current keyframe and last requested, don't delete
if ((isOnLoop && (key > this.lastFrameRequested && key < this.currentFrame)) ||
(!isOnLoop && key < this.currentFrame)) {
// console.log("Destroying", key);
if (buffer && buffer instanceof BufferGeometry) {
buffer.dispose();
}
this.meshBuffer.delete(key);
}
}
const minimumBufferLength = this.targetFramesToRequest * 2;
const meshBufferHasEnoughToPlay = this.meshBuffer.size >= minimumBufferLength;
if (meshBufferHasEnoughToPlay) {
if(this.isVideoReady && this._video.paused && this.hasPlayed)
this._video.play();
}
else {
if (!this.isWorkerBusy && this.isWorkerReady) {
if (this.isWorkerWaitNextLoop) {
this.isWorkerWaitNextLoop = false
this.handleNextLoop()
} else if (moduloBy(this.lastFrameRequested - this.currentFrame, this.numberOfFrames) <= minimumBufferLength * 2) {
let newLastFrame = Math.max(this.lastFrameRequested + minimumBufferLength, this.lastFrameRequested + this.targetFramesToRequest);
if (newLastFrame >= this.numberOfFrames - 1) {
newLastFrame = this.numberOfFrames - 1
}
newLastFrame = newLastFrame % this.numberOfFrames
const payload = {
frameStart: this.lastFrameRequested,
frameEnd: newLastFrame
}
console.log("Posting request", payload);
this._worker.postMessage({ type: "request", payload }); // Send data to our worker.
this.isWorkerBusy = true;
if (newLastFrame >= this.numberOfFrames - 1) {
this.lastFrameRequested = 0
this.isWorkerWaitNextLoop = true
} else {
this.lastFrameRequested = newLastFrame;
}
if (!meshBufferHasEnoughToPlay && typeof this.onMeshBuffering === "function") {
// console.log('buffering ', this.meshBuffer.size / minimumBufferLength,', have: ', this.meshBuffer.size, ', need: ', minimumBufferLength )
this.onMeshBuffering(this.meshBuffer.size / minimumBufferLength);
}
}
}
}
requestAnimationFrame(() => this.bufferLoop());
}
hasPlayed = false;
stopOnNextFrame = false;
constructor({
scene,
renderer,
playMode,
paths,
targetFramesToRequest = 90,
frameRate = 30,
loop = true,
scale = 1,
encoderWindowSize = 8,
encoderByteLength = 16,
videoSize = 1024,
video = null,
onMeshBuffering = null,
onFrameShow = null,
rendererCallback = null,
worker = null
}: {
scene: Object3D,
renderer: WebGLRenderer,
playMode?: PlayModeEnum,
paths: Array<String>,
targetFramesToRequest?: number,
frameRate?: number,
loop?: boolean,
autoplay?: boolean,
scale?: number,
video?: any,
encoderWindowSize?: number,
encoderByteLength?: number,
videoSize?: number,
onMeshBuffering?: onMeshBufferingCallback
onFrameShow?: onFrameShowCallback,
rendererCallback?: onRenderingCallback,
worker?: Worker
}) {
this.onMeshBuffering = onMeshBuffering;
this.onFrameShow = onFrameShow;
this.rendererCallback = rendererCallback;
this.encoderWindowSize = encoderWindowSize;
this.encoderByteLength = encoderByteLength;
this.maxNumberOfFrames = Math.pow(2, this.encoderByteLength)-2;
this.videoSize = videoSize;
this.targetFramesToRequest = targetFramesToRequest;
this._worker = worker ? worker : (new Worker(Player.defaultWorkerURL)); // spawn new worker;
this.scene = scene;
this.renderer = renderer;
this.loop = loop;
this._scale = scale;
this._video = video ? video : createElement('video', {
crossorigin: "",
playsInline: "true",
preload: "auto",
style: {
display: "none",
position: 'fixed',
zIndex: '-1',
top: '0',
left: '0',
width: '1px'
},
playbackRate: 1
});
this.paths = paths
if (!playMode) this.playMode = PlayModeEnum.Loop
this._video.setAttribute('crossorigin', '');
this._video.setAttribute('preload', 'auto');
this.frameRate = frameRate;
const counterCanvas = document.createElement('canvas') as HTMLCanvasElement;
counterCanvas.width = this.encoderByteLength;
counterCanvas.height = 1;
this.counterCtx = counterCanvas.getContext('2d');
this.actorCanvas = document.createElement('canvas')
this.actorCtx = this.actorCanvas.getContext('2d');
this.actorCtx.canvas.width = this.actorCtx.canvas.height = this.videoSize;
this.counterCtx.canvas.setAttribute('crossOrigin', 'Anonymous');
this.actorCtx.canvas.setAttribute('crossOrigin', 'Anonymous');
this.actorCtx.fillStyle = '#ACC';
this.actorCtx.fillRect(0, 0, this.actorCtx.canvas.width, this.actorCtx.canvas.height);
this._videoTexture = new Texture(this.actorCtx.canvas);
this._videoTexture.encoding = sRGBEncoding;
this.material = new MeshBasicMaterial({ map: this._videoTexture });
this.failMaterial = new MeshBasicMaterial({ color: '#555555' });
this.mesh = new Mesh(new PlaneBufferGeometry(0.00001, 0.00001), this.material);
this.mesh.scale.set(this._scale, this._scale, this._scale);
this.scene.add(this.mesh);
const handleFrameData = (messages) => {
// console.log(`received frames ${messages[0].keyframeNumber} - ${messages[messages.length-1].keyframeNumber}`)
for (const frameData of messages) {
let geometry = new BufferGeometry();
geometry.setIndex(
new Uint32BufferAttribute(frameData.bufferGeometry.index, 1)
);
geometry.setAttribute(
'position',
new Float32BufferAttribute(frameData.bufferGeometry.position, 3)
);
geometry.setAttribute(
'uv',
new Float32BufferAttribute(frameData.bufferGeometry.uv, 2)
);
this.meshBuffer.set(frameData.keyframeNumber, geometry );
}
if (typeof this.onMeshBuffering === "function") {
const minimumBufferLength = this.targetFramesToRequest * 2;
// console.log('buffering ', this.meshBuffer.size / minimumBufferLength,', have: ', this.meshBuffer.size, ', need: ', minimumBufferLength )
this.onMeshBuffering(this.meshBuffer.size / minimumBufferLength);
}
}
this._worker.onmessage = (e) => {
switch (e.data.type) {
case 'initialized':
console.log("Worker initialized");
this.isWorkerReady = true
Promise.resolve().then(() => {
this.bufferLoop();
});
break;
case 'framedata':
Promise.resolve().then(() => {
this.isWorkerBusy = false;
handleFrameData(e.data.payload);
});
break;
}
};
this.setTrackPath(this.currentTrack)
this.setVideo(this.videoFilePath)
this.setWorker(this.manifestFilePath, this.meshFilePath)
}
handleNextLoop() {
if (this.playMode == PlayModeEnum.Random) {
this.nextTrack = Math.floor(Math.random() * this.paths.length)
} else if (this.playMode == PlayModeEnum.Single) {
this.nextTrack = (this.currentTrack + 1) % this.paths.length
if ((this.currentTrack + 1) == this.paths.length) {
this.nextTrack = 0
this.isWorkerReady = false
return
}
} else if (this.playMode == PlayModeEnum.SingleLoop) {
this.nextTrack = this.currentTrack
} else { //PlayModeEnum.Loop
this.nextTrack = (this.currentTrack + 1) % this.paths.length
}
this.setTrackPath(this.nextTrack)
this.setWorker(this.manifestFilePath, this.meshFilePath)
}
handleLoop() {
if (this.nextTrack == -1) {
this.nextTrack = 0
return
}
if (this.numberOfNextFrames != 0) this.numberOfFrames = this.numberOfNextFrames
this.currentTrack = this.nextTrack
this.setVideo(this.videoFilePath)
this.hasPlayed = true;
}
setTrackPath(track) {
const meshFilePath = this.paths[track % this.paths.length]
this.meshFilePath = meshFilePath
this.manifestFilePath = `${meshFilePath.substring(0, meshFilePath.lastIndexOf("."))}.manifest`
this.videoFilePath = `${meshFilePath.substring(0, meshFilePath.lastIndexOf("."))}.mp4`
}
setVideo(videoFilePath) {
this.isVideoReady = false
if (!this._video.paused) {
this._video.pause();
this.hasPlayed = false;
this.stopOnNextFrame = false;
}
this._video.setAttribute('src', videoFilePath);
this._video.load()
this._video.addEventListener('loadeddata', (event) => {
this.isVideoReady = true
});
}
setWorker(manifestFilePath, meshFilePath) {
this.isWorkerReady = false;
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
this.fileHeader = JSON.parse(xhr.responseText);
this.frameRate = this.fileHeader.frameRate;
// Get count of frames associated with keyframe
this.numberOfNextFrames = this.fileHeader.frameData.length;
if (this.numberOfFrames == 0) this.numberOfFrames = this.numberOfNextFrames
if (this.numberOfNextFrames > this.maxNumberOfFrames) {
console.error('There are more frames (%d) in file then our decoder can handle(%d) with provided encoderByteLength(%d)', this.numberOfNextFrames, this.maxNumberOfFrames, this.encoderByteLength);
}
this._worker.postMessage({ type: "initialize", payload: { targetFramesToRequest: this.targetFramesToRequest, meshFilePath, numberOfFrames: this.numberOfNextFrames, fileHeader: this.fileHeader } }); // Send data to our worker.
};
xhr.open('GET', manifestFilePath, true); // true for asynchronous
xhr.send();
}
/**
* emulated video frame callback
* bridge from video.timeupdate event to videoUpdateHandler
* @param cb
*/
handleRender(cb?: onRenderingCallback) {
if (!this.fileHeader) // || (this._video.currentTime === 0 || this._video.paused))
return;
// TODO: handle paused state
this.processFrame(cb);
}
/**
* sync mesh frame to video texture frame
* calls this.rendererCallback and provided callback if frame is changed and render needs update
* @param cb
*/
processFrame(cb?: onRenderingCallback) {
const frameToPlay = this.getCurrentFrameNumber();
if (frameToPlay > this.numberOfFrames) {
console.warn('video texture is not ready? frameToPlay:', frameToPlay);
return;
}
if (this.currentFrame === frameToPlay) {
return;
}
this.currentFrame = frameToPlay;
if (this.currentFrame >= this.numberOfFrames - 1) {
this.handleLoop()
}
if (this.stopOnNextFrame) {
this._video.pause();
this.hasPlayed = false;
this.stopOnNextFrame = false;
}
const hasFrame = this.meshBuffer.has(frameToPlay);
// If keyframe changed, set mesh buffer to new keyframe
if (!hasFrame) {
if (!this._video.paused) {
this._video.pause();
}
if (typeof this.onMeshBuffering === "function") {
this.onMeshBuffering(0);
}
this.mesh.material = this.failMaterial;
} else {
this.mesh.material = this.material;
this.material.needsUpdate = true;
this.mesh.material.needsUpdate = true;
this.mesh.geometry = this.meshBuffer.get(frameToPlay) as BufferGeometry;
this.mesh.geometry.attributes.position.needsUpdate = true;
(this.mesh.geometry as any).needsUpdate = true;
this.currentFrame = frameToPlay;
if (typeof this.onFrameShow === "function") {
this.onFrameShow(frameToPlay);
}
if(this.rendererCallback) this.rendererCallback();
if(cb) cb();
}
}
getCurrentFrameNumber():number {
const encoderWindowWidth = this.encoderWindowSize * this.encoderByteLength;
const encoderWindowHeight = this.encoderWindowSize / 2;
// this.actorCtx.clearRect(0, 0, this.videoSize, this.videoSize);
this.actorCtx.drawImage(this._video, 0, 0);
// this.counterCtx.clearRect(0, 0, this.encoderByteLength, 1);
this.counterCtx.drawImage(
this.actorCtx.canvas,
0,
this.videoSize - encoderWindowHeight,
encoderWindowWidth,
encoderWindowHeight,
0,
0,
this.encoderByteLength, 1);
const imgData = this.counterCtx.getImageData(0, 0, this.encoderByteLength, 1);
let frameToPlay = 0;
for (let i = 0; i < this.encoderByteLength; i++) {
frameToPlay += Math.round(imgData.data[i * 4] / 255) * Math.pow(2, i);
}
frameToPlay = Math.max(frameToPlay - 1, 0);
this._videoTexture.needsUpdate = this.currentFrame !== frameToPlay;
return frameToPlay;
}
get video():any {
return this._video;
}
// Start loop to check if we're ready to play
play() {
this.hasPlayed = true;
this._video.playsInline = true;
this.mesh.visible = true
this._video.play()
}
playOneFrame() {
this.stopOnNextFrame = true;
this.play();
}
dispose(): void {
this._worker && this._worker.terminate();
if (this._video) {
this._video.pause();
this._video = null;
this._videoTexture.dispose();
this._videoTexture = null;
}
if (this.meshBuffer) {
for (let i = 0; i < this.meshBuffer.size; i++) {
const buffer = this.meshBuffer.get(i);
if (buffer && buffer instanceof BufferGeometry) {
buffer.dispose();
}
}
this.meshBuffer.clear();
}
}
} | the_stack |
import {ENGINE} from './engine';
import * as tf from './index';
import {ALL_ENVS, describeWithFlags} from './jasmine_util';
import {Tensor} from './tensor';
import {expectArraysClose} from './test_util';
describeWithFlags('gradients', ALL_ENVS, () => {
it('matmul + relu', async () => {
const a = tf.tensor2d([-1, 2, -3, 10, -20, 30], [2, 3]);
const b = tf.tensor2d([2, -3, 4, -1, 2, -3], [3, 2]);
const [da, db] = tf.grads((a: tf.Tensor2D, b: tf.Tensor2D) => {
// m = dot(a, b)
// y = relu(m)
// e = sum(y)
const m = tf.matMul(a, b);
const y = tf.relu(m);
return tf.sum(y);
})([a, b]);
// de/dy = 1
// dy/dm = step(m)
// de/dm = de/dy * dy/dm = step(m)
const dedm = tf.step(tf.matMul(a, b));
// de/da = dot(de/dy, bT)
expect(da.shape).toEqual(a.shape);
let transposeA = false;
let transposeB = true;
expectArraysClose(
await da.data(),
await tf.matMul(dedm, b, transposeA, transposeB).data());
// de/db = dot(aT, de/dy)
expect(db.shape).toEqual(b.shape);
transposeA = true;
transposeB = false;
expectArraysClose(
await db.data(),
await tf.matMul(a, dedm, transposeA, transposeB).data());
});
it('grad(f)', async () => {
const grad = tf.grad(x => x.square());
const result = grad(tf.tensor1d([.1, .2]));
expectArraysClose(await result.data(), [.2, .4]);
});
it('calling grad(f) twice works', async () => {
const grad = tf.grad(x => x.square());
const result = grad(tf.tensor1d([.1, .2]));
const result2 = grad(tf.tensor1d([.1, .4]));
expectArraysClose(await result.data(), [.2, .4]);
expectArraysClose(await result2.data(), [.2, .8]);
});
it('grad(f): throwing an error during forward pass', () => {
const grad = tf.grad(x => {
throw new Error('failed forward pass');
});
expect(() => grad(tf.zeros([]))).toThrowError();
expect(ENGINE.isTapeOn()).toBe(false);
});
it('grad(f): throwing an error during backwards pass', () => {
const customOp = tf.customGrad((x: tf.Tensor) => {
return {
value: x,
gradFunc: () => {
throw new Error('failed backward pass');
}
};
});
const grad = tf.grad(x => customOp(x));
expect(() => grad(tf.zeros([]))).toThrowError();
expect(ENGINE.isTapeOn()).toBe(false);
});
it('grads(f)', async () => {
const grads = tf.grads(x => x.square());
const result = grads([tf.tensor1d([.1, .2])]);
expectArraysClose(await result[0].data(), [.2, .4]);
});
it('calling grads(f) twice works', async () => {
const grads = tf.grads(x => x.square());
const result = grads([tf.tensor1d([.1, .2])]);
const result2 = grads([tf.tensor1d([.1, .4])]);
expectArraysClose(await result[0].data(), [.2, .4]);
expectArraysClose(await result2[0].data(), [.2, .8]);
});
it('works with reshape', async () => {
const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
const exponent = tf.tensor1d([2, 2, 2, 2], 'int32');
const da = tf.grad(a => {
const b = a.flatten();
const m = tf.pow(b, exponent);
return tf.sum(m);
})(a);
expect(da.shape).toEqual([2, 2]);
expectArraysClose(await da.data(), [2, 4, 6, 8]);
});
it('reshape outside tf.grads() throws error', () => {
const a = tf.tensor2d([1, 2, 3, 4], [2, 2]);
const b = a.flatten();
const exponent = tf.tensor1d([2, 2, 2, 2], 'int32');
const f = () => {
tf.grads((a, b) => {
const m = tf.pow(b, exponent);
return tf.sum(m);
})([a, b]);
};
expect(f).toThrowError();
});
it('does not error if irrelevant (pruned) ops are missing grads',
async () => {
const a = tf.tensor1d([true, true], 'bool');
const b = tf.tensor1d([false, true], 'bool');
const da = tf.grad(a => {
// Logical has no gradients, but it is irrelevant.
a.logicalAnd(b);
return a.sum();
})(a);
expectArraysClose(await da.data(), [1, 1]);
});
it('errors if relevant ops are missing grads', () => {
const a = tf.tensor1d([true, true], 'bool');
const b = tf.tensor1d([false, true], 'bool');
const dfda = tf.grad(a => {
// Logical has no gradients, but it's relevant to the output.
return a.logicalAnd(b);
});
expect(() => dfda(a)).toThrowError();
});
it('works with asType', async () => {
const a = tf.tensor2d([1, 2, 3, 4], [2, 2], 'int32');
const exponent = tf.tensor2d([2, 2, 2, 2], [2, 2], 'int32');
const da = tf.grad(a => {
const b = a.toFloat();
const m = tf.pow(b, exponent);
return tf.sum(m);
})(a);
expect(da.shape).toEqual([2, 2]);
expect(da.dtype).toEqual('float32');
expectArraysClose(await da.data(), [2, 4, 6, 8]);
});
it('asType outside of tf.grads() throws error', () => {
const a = tf.tensor2d([1, 2, 3, 4], [2, 2], 'int32');
const b = a.toFloat();
const exponent = tf.tensor2d([2, 2, 2, 2], [2, 2], 'int32');
const f = () => {
tf.grad(a => {
const m = tf.pow(b, exponent);
return tf.sum(m);
})(a);
};
expect(f).toThrowError();
});
it('saves tensors from the forward pass as expected', () => {
const x = tf.scalar(1).variable();
const optimizer = tf.train.sgd(0.1);
optimizer.minimize(() => {
const y = x.square();
const z = y.square();
y.dispose();
return z;
});
});
it('custom ops do not leak', () => {
const before = tf.memory().numTensors;
const x = tf.softmax([1, 2, 3, 4]);
x.dispose();
const now = tf.memory().numTensors;
expect(now).toBe(before);
});
});
describeWithFlags('valueAndGradients', ALL_ENVS, () => {
it('matmul + relu', async () => {
const a = tf.tensor2d([-1, 2, -3, 10, -20, 30], [2, 3]);
const b = tf.tensor2d([2, -3, 4, -1, 2, -3], [3, 2]);
const {value, grads} =
tf.valueAndGrads((a: tf.Tensor2D, b: tf.Tensor2D) => {
// m = dot(a, b)
// y = relu(m)
// e = sum(y)
const m = tf.matMul(a, b);
const y = tf.relu(m);
return tf.sum(y);
})([a, b]);
expectArraysClose(await value.data(), 10);
// de/dy = 1
// dy/dm = step(m)
// de/dm = de/dy * dy/dm = step(m)
const dedm = tf.step(tf.matMul(a, b));
const [da, db] = grads;
// de/da = dot(de/dy, bT)
let transposeA = false;
let transposeB = true;
expectArraysClose(
await da.data(),
await tf.matMul(dedm, b, transposeA, transposeB).data());
// de/db = dot(aT, de/dy)
transposeA = true;
transposeB = false;
expectArraysClose(
await db.data(),
await tf.matMul(a, dedm, transposeA, transposeB).data());
});
it('matmul + relu + inner tidy', async () => {
const a = tf.tensor2d([-1, 2, -3, 10, -20, 30], [2, 3]);
const b = tf.tensor2d([2, -3, 4, -1, 2, -3], [3, 2]);
const {value, grads} =
tf.valueAndGrads((a: tf.Tensor2D, b: tf.Tensor2D) => {
// m = dot(a, b)
// y = relu(m)
// e = sum(y)
const m = tf.matMul(a, b);
return tf.tidy(() => {
const y = tf.relu(m);
return tf.sum(y);
});
})([a, b]);
expectArraysClose(await value.data(), 10);
// de/dy = 1
// dy/dm = step(m)
// de/dm = de/dy * dy/dm = step(m)
const dedm = tf.step(tf.matMul(a, b));
const [da, db] = grads;
// de/da = dot(de/dy, bT)
let transposeA = false;
let transposeB = true;
expectArraysClose(
await da.data(),
await tf.matMul(dedm, b, transposeA, transposeB).data());
// de/db = dot(aT, de/dy)
transposeA = true;
transposeB = false;
expectArraysClose(
await db.data(),
await tf.matMul(a, dedm, transposeA, transposeB).data());
});
});
describeWithFlags('higher-order gradients', ALL_ENVS, () => {
it('grad(grad(f))', async () => {
const x = tf.tensor1d([.1, .2]);
const before = tf.memory().numTensors;
const gradgrad = tf.grad(tf.grad(x => x.mul(x).mul(x)));
const result = gradgrad(x);
expect(tf.memory().numTensors).toBe(before + 1);
expectArraysClose(await result.data(), [.6, 1.2]);
});
it('grad(grad(x^2))', async () => {
const x = tf.scalar(3);
const gradgrad = tf.grad(tf.grad(x => x.square()));
const result = gradgrad(x);
// grad(grad(x^2)) = grad(2x) = 2
expectArraysClose(await result.data(), [2]);
});
it('grads(grads(f))', async () => {
const grads = tf.grads(x => x.mul(x).mul(x));
const gradsgrads = tf.grads(x => grads([x])[0]);
const result = gradsgrads([tf.tensor1d([.1, .2])]);
expectArraysClose(await result[0].data(), [.6, 1.2]);
});
});
describeWithFlags('customGradient', ALL_ENVS, () => {
it('basic', async () => {
const a = tf.scalar(3);
const b = tf.scalar(2, 'int32');
const dy = tf.scalar(4);
const customPow = tf.customGrad((a: tf.Tensor) => {
const value = tf.pow(a, b);
const gradFunc = (dy: tf.Tensor) => dy.mul(tf.scalar(0.1));
return {value, gradFunc};
});
const {value, grad} = tf.valueAndGrad(a => customPow(a))(a, dy);
expect(value.shape).toEqual(a.shape);
expectArraysClose(await value.data(), [9]);
expect(grad.shape).toEqual(a.shape);
expectArraysClose(await grad.data(), [.4]);
});
it('second order derivative through customGradient', async () => {
const a = tf.scalar(3);
const b = tf.scalar(2, 'int32');
const dy = tf.scalar(5);
const customPow = tf.customGrad((a: tf.Tensor, save: tf.GradSaveFunc) => {
const value = tf.pow(a, b);
save([a]);
const gradFunc = (dy: tf.Tensor, saved: Tensor[]) => {
const [a] = saved;
return dy.mul(a);
};
return {value, gradFunc};
});
const dda = tf.grad(tf.grad(a => customPow(a)))(a, dy);
expect(dda.shape).toEqual(a.shape);
// First order: dy * a. Second order: dy.
expectArraysClose(await dda.data(), await dy.data());
});
it('calling gradient of custom op twice works', async () => {
const customOp = tf.customGrad((x: tf.Tensor, save: tf.GradSaveFunc) => {
// Override gradient of our custom x ^ 2 op to be dy * abs(x);
save([x]);
return {
value: x.square(),
gradFunc: (dy, saved: Tensor[]) => {
const [x] = saved;
return dy.mul(x.abs());
}
};
});
const x = tf.tensor1d([-1, -2, 3]);
const grad = tf.grad(x => customOp(x));
expectArraysClose(await grad(x).data(), [1, 2, 3]);
expectArraysClose(await grad(x).data(), [1, 2, 3]);
});
}); | the_stack |
import {ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {AbstractComponent} from '@common/component/abstract.component';
import {SelectComponent} from '@common/component/select/select.component';
import {Format} from '@domain/workbook/configurations/format';
import {
ChartType,
GridViewType,
UIFormatNumericAliasType,
UIFormatSymbolPosition
} from '@common/component/chart/option/define/common';
import {FormatOptionConverter} from '@common/component/chart/option/converter/format-option-converter';
import {CustomSymbol} from '@common/component/chart/option/ui-option/ui-format';
import {OptionGenerator} from '@common/component/chart/option/util/option-generator';
import {UIOption} from '@common/component/chart/option/ui-option';
import {UIGridChart} from '@common/component/chart/option/ui-option/ui-grid-chart';
import UI = OptionGenerator.UI;
export abstract class AbstractFormatItemComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild('typeListSelect', {static: true})
private typeListComp: SelectComponent;
@ViewChild('signListSelect', {static: true})
private signListComp: SelectComponent;
@ViewChild('numericAliasListSelect')
private numericAliasListComp: SelectComponent;
// 타입 목록
private _orgTypeList: object[] = [
{name: this.translateService.instant('msg.page.li.num'), value: 'number'},
{name: this.translateService.instant('msg.page.li.currency'), value: 'currency'},
{name: this.translateService.instant('msg.page.li.percent'), value: 'percent'},
{name: this.translateService.instant('msg.page.li.exponent'), value: 'exponent10'}
];
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 포맷 정보가 바뀐 경우
@Output('changeFormat')
public changeEvent: EventEmitter<any> = new EventEmitter();
public uiOption: UIOption;
// 포맷정보
public format: Format;
// 타입 목록
public typeList: any[] = [
{name: this.translateService.instant('msg.page.li.num'), value: 'number'},
{name: this.translateService.instant('msg.page.li.currency'), value: 'currency'},
{name: this.translateService.instant('msg.page.li.percent'), value: 'percent'},
{name: this.translateService.instant('msg.page.li.exponent'), value: 'exponent10'}
];
// 선택된 공통 타입
public selectedType: any = this.typeList[0];
// 기호: 통화일때
public currencySignList: object[] = [
{name: '₩ (KRW)', value: 'KRW'},
{name: '$ (USD)', value: 'USD'},
{name: '£ (GBP)', value: 'GBP'},
{name: '¥ (JPY)', value: 'JPY'},
{name: '€ (EUR)', value: 'EUR'},
{name: '¥ (CNY)', value: 'CNY'},
{name: '₽ (RUB)', value: 'RUB'}
];
// 선택된 기호
public selectedSign: object = this.currencySignList[0];
// 소수 자리수
public decimal: number = 2;
public decimalCopy: number = this.decimal;
public MIN_DIGIT: number = 0;
public MAX_DIGIT: number = 5;
// 1000자리 구분자 사용여부
public useThousandsSep: boolean = false;
// 수치표기 약어목록
public numericAliasList: object[] = [
{
name: this.translateService.instant('msg.page.format.numeric.alias.none'),
value: String(UIFormatNumericAliasType.NONE)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.auto'),
value: String(UIFormatNumericAliasType.AUTO)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.kilo'),
value: String(UIFormatNumericAliasType.KILO)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.milion'),
value: String(UIFormatNumericAliasType.MEGA)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.billion'),
value: String(UIFormatNumericAliasType.GIGA)
},{
name: this.translateService.instant('msg.page.format.numeric.alias.kilo.ko'),
value: String(UIFormatNumericAliasType.KILO_KOR)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.million.ko'),
value: String(UIFormatNumericAliasType.MEGA_KOR)
},
{
name: this.translateService.instant('msg.page.format.numeric.alias.billion.ko'),
value: String(UIFormatNumericAliasType.GIGA_KOR)
},
];
// 선택된 수치표기 약어
public selectedNumericAlias: object = this.numericAliasList[0];
// 포멧 위치 리스트
public positionList: object[] = [
{
name: this.translateService.instant('msg.page.format.custom.symbol.position.front'),
value: UIFormatSymbolPosition.BEFORE
},
{
name: this.translateService.instant('msg.page.format.custom.symbol.position.back'),
value: UIFormatSymbolPosition.AFTER
}
];
// 미리보기 값
public preview: string;
// 단위설정
public customSymbol: CustomSymbol;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Getter & Setter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@Input('uiOption')
public set setUiOption(uiOption: UIOption) {
this.uiOption = uiOption;
this.typeList = JSON.parse(JSON.stringify(this._orgTypeList));
if (uiOption.type === ChartType.GRID && (uiOption as UIGridChart).dataType === GridViewType.MASTER) {
this.typeList.push({name: this.translateService.instant('msg.page.li.origin'), value: 'origin'});
}
}
@Input('format')
public set setFormat(format: Format) {
if (!format) {
return;
}
// Set
this.format = format;
this.setType = this.format.type;
this.setSign = this.format.sign;
this.decimal = this.format.decimal;
this.decimalCopy = this.decimal;
this.useThousandsSep = this.format.useThousandsSep;
this.setNumericAlias = this.format.abbr;
if (this.format.customSymbol) {
this.customSymbol = {};
this.customSymbol.value = this.format.customSymbol ? this.format.customSymbol.value : '';
this.customSymbol.pos = this.format.customSymbol ? this.format.customSymbol.pos : UIFormatSymbolPosition.BEFORE;
this.customSymbol.abbreviations = this.format.customSymbol ? this.format.customSymbol.abbreviations : false;
}
// 설정된 포멧으로 preview값 설정
this.preview = FormatOptionConverter.getFormatValue(1000, this.format);
}
// 외부에서 타입 주입
@Input('type')
public set setType(type: string) {
// 값이 유효하지 않으면 패스~
if (!type) {
return;
}
// 타입 목록에서 찾아서 주입
for (let num: number = 0; num < this.typeList.length; num++) {
if (this.typeList[num]['value'] === type) {
this.typeListComp.setDefaultIndex = num;
this.selectedType = this.typeList[num];
this.changeDetect.detectChanges();
break;
}
}
}
// 외부에서 심볼타입 주입
@Input('sign')
public set setSign(sign: string) {
// 값이 유효하지 않으면 패스~
if (!sign || !this.signListComp) {
return;
}
const signList: object[] = this.currencySignList;
// 심볼 목록에서 찾아서 주입
for (let num: number = 0; num < signList.length; num++) {
if (signList[num]['value'] === sign) {
this.signListComp.setDefaultIndex = num;
this.selectedSign = signList[num];
break;
}
}
}
// 외부에서 수치표시 약어설정 주입
@Input('numericAlias')
public set setNumericAlias(numericAlias: string) {
// 값이 유효하지 않으면 패스~
if (!numericAlias || !this.numericAliasListComp) {
return;
}
const aliasList: object[] = this.numericAliasList;
// 심볼 목록에서 찾아서 주입
for (let num: number = 0; num < aliasList.length; num++) {
if (aliasList[num]['value'] === numericAlias) {
this.numericAliasListComp.setDefaultIndex = num;
this.selectedNumericAlias = aliasList[num];
break;
}
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
protected constructor(protected elementRef: ElementRef,
protected injector: Injector) {
super(elementRef, injector);
this.typeList = JSON.parse(JSON.stringify(this._orgTypeList));
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 타입 변경 핸들러
* @param type
*/
public onTypeChange(type: object): void {
// 타입변경
this.selectedType = type;
// 변경 이벤트 발생
this.change();
}
/**
* 심볼 변경 핸들러
* @param sign
*/
public onSignChange(sign: object): void {
// 심볼변경
this.selectedSign = sign;
// 변경 이벤트 발생
this.change();
}
/**
* 자리수 변경 핸들러
* @param isPlus
*/
public onDigitChange(isPlus: boolean): void {
if (isPlus) {
if (this.decimal === this.MAX_DIGIT) {
return;
}
this.decimal = this.decimal + 1;
} else {
if (this.decimal === this.MIN_DIGIT) {
return;
}
this.decimal = this.decimal - 1;
}
this.decimalCopy = this.decimal;
// 변경 이벤트 발생
this.change();
}
/**
* 자리수 입력 변경후 핸들러
*/
public onDigitValid(): void {
if (this.decimalCopy === this.decimal) {
return;
}
if (this.decimalCopy < this.MIN_DIGIT || this.decimalCopy > this.MAX_DIGIT) {
this.decimalCopy = 2;
}
this.decimal = this.decimalCopy;
// 변경 이벤트 발생
this.change();
}
/**
* 1000단위 구분자 사용여부 변경 핸들러
*/
public onThousandsSepChange(): void {
// Set
this.useThousandsSep = !this.useThousandsSep;
// 변경 이벤트 발생
this.change();
}
/**
* 수치표시 약어설정 변경 핸들러
* @param numericAlias
*/
public onNumericAliasChange(numericAlias: object): void {
console.log('onNumericAliasChange');
console.log(numericAlias);
// 심볼변경
this.selectedNumericAlias = numericAlias;
// 변경 이벤트 발생
this.change();
}
/**
* 변경 이벤트 발생
*/
public change(): void {
// Null Check
if (!this.format) {
this.format = {};
}
this.format = {};
// Value Setting
this.format.type = this.selectedType['value'];
this.format.sign = this.selectedSign['value'];
this.format.decimal = this.decimal;
this.format.useThousandsSep = this.useThousandsSep;
this.format.abbr = this.selectedNumericAlias['value'];
this.format.customSymbol = this.customSymbol;
// 설정된 포멧으로 preview값 설정
this.preview = FormatOptionConverter.getFormatValue(1000, this.format);
// Dispatch Event
this.changeEvent.emit(this.format);
console.log('change');
console.log(this.format);
}
/**
* 사용자 기호위치 변경시
*/
public changePosition(position: any): void {
// 선택된값 설정
this.customSymbol.pos = position.value;
// 변경 이벤트 발생
this.change();
}
/**
* custom symbol 변경시
*/
public changeSymbol(): void {
// 변경 이벤트 발생
this.change();
}
/**
* symbol show 설정
*/
public showCustomSymbol(): void {
// customSymbol값이 있는경우
if (this.customSymbol) {
this.customSymbol = null;
// customSymbol값이 없는경우
} else {
// customSymbol 생성
this.customSymbol = UI.Format.customSymbol(UIFormatSymbolPosition.BEFORE);
}
// 변경 이벤트 발생
this.change();
}
/**
* 숫자기호 표시 변경
*/
public changeNumberSymbol(): void {
// 선택된값 설정
this.customSymbol.abbreviations = !this.customSymbol.abbreviations;
// 변경 이벤트 발생
this.change();
}
public checkSelectedType(type: string): boolean {
return (this.selectedType['value'] == type);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
} | the_stack |
import 'mocha';
import 'chai';
import { newDb } from '../db';
import { expect, assert } from 'chai';
import { Types } from '../datatypes';
import { _IDb } from '../interfaces-private';
import { SelectFromStatement, SelectStatement } from 'pgsql-ast-parser';
import { buildValue } from '../expression-builder';
import { parseSql } from '../parse-cache';
describe('Selections', () => {
let db: _IDb;
let many: (str: string) => any[];
let none: (str: string) => void;
beforeEach(() => {
db = newDb() as _IDb;
many = db.public.many.bind(db.public);
none = db.public.none.bind(db.public);
});
function simpleDb() {
db.public.declareTable({
name: 'data',
fields: [{
name: 'id',
type: Types.text(),
constraints: [{ type: 'primary key' }],
}, {
name: 'str',
type: Types.text(),
}, {
name: 'otherstr',
type: Types.text(),
}],
});
return db;
}
function stuff() {
none(`create table test(txt text, val integer);
insert into test values ('A', 999);
insert into test values ('A', 0);
insert into test values ('A', 1);
insert into test values ('B', 2);
insert into test values ('C', 3);`)
}
it('can select nothing', () => {
// yea... thats a valid query. Try it oO'
expect(many(`select;`))
.to.deep.equal([{}]);
});
it('can use transformations', () => {
stuff();
expect(many(`select * from (select val as xx from test where txt = 'A') x where x.xx >= 1`))
.to.deep.equal([{ xx: 999 }, { xx: 1 }]);
});
it('executes the right plan on transformations', () => {
stuff();
const plan = (db as _IDb).public.explainSelect(`select * from (select val as valAlias from test where txt = 'A') x where x.valAlias >= 1`);
// assert.deepEqual(plan, {} as any);
assert.deepEqual(plan, {
id: 1,
_: 'seqFilter',
filtered: {
id: 2,
_: 'map',
select: [{
what: {
col: 'val',
on: 'test',
},
as: 'valalias',
}],
of: {
id: 3,
_: 'seqFilter',
filtered: {
_: 'table',
table: 'test',
}
}
}
});
})
it('can use an expression on a transformed selection', () => {
stuff();
// preventSeqScan(db);
expect(many(`select *, lower(txtx) as v from (select val as valx, txt as txtx from test where val >= 1) x where lower(x.txtx) = 'a'`))
.to.deep.equal([{ txtx: 'A', valx: 999, v: 'a' }, { txtx: 'A', valx: 1, v: 'a' }]);
});
it('selects case whithout condition', () => {
simpleDb();
expect(many(`insert into data(id, str) values ('id1', 'SOME STRING'), ('id2', 'other string'), ('id3', 'Some String');
select case when id='id1' then 'one ' || str else 'something else' end as x from data`))
.to.deep.equal([{ x: 'one SOME STRING' }, { x: 'something else' }, { x: 'something else' }]);
})
it('selects case with disparate types results', () => {
simpleDb();
expect(many(`select case when 2 > 1 then 1.5 when 2 < 1 then 1 end as x`))
.to.deep.equal([{ x: 1.5 }]);
})
it('does not support select * on dual', () => {
assert.throw(() => many(`select *`));
});
it('supports concat operator', () => {
expect(many(`select 'a' || 'b' as x`))
.to.deep.equal([{ x: 'ab' }]);
});
it('has an index', () => {
simpleDb();
const [{ where }] = parseSql(`select * from data where id='x'`) as SelectFromStatement[];
if (!where || where.type !== 'binary') {
assert.fail('Should be a binary');
}
const built = buildValue(db.getTable('data').selection, where.left);
assert.exists(built.index);
});
it('detects ambiguous column selections on aliases', () => {
// same-name columns not supported...if supported, must continue to throw when doing this:
assert.throws(() => none(`create table data(id text primary key, str text);
select x.a from (select id as a, str as a from data) x;`), /column reference "a" is ambiguous/);
});
it('can select for update', () => {
expect(many(`create table test (a text);
insert into test(a) values ('v');
select * from test for update`))
.to.deep.equal([
{ a: 'v' },
])
})
it('can select from values', () => {
expect(many(`select * from (values (1, 'one'), (2, 'two')) as tbl (num, str);`))
.to.deep.equal([
{ num: 1, str: 'one' },
{ num: 2, str: 'two' },
])
})
it('can select qualified from values', () => {
expect(many(`select tbl.num, tbl.str from (values (1, 'one'), (2, 'two')) as tbl (num, str);`))
.to.deep.equal([
{ num: 1, str: 'one' },
{ num: 2, str: 'two' },
])
})
it('can filter from values', () => {
expect(many(`select * from (values (1, 'one'), (2, 'two')) as tbl (num, str) where tbl.num>1;`))
.to.deep.equal([
{ num: 2, str: 'two' },
])
});
it('can select from function with selection', () => {
expect(many(`select a,b from concat('a') as a join concat('a') as b on b=a`))
.to.deep.equal([{ a: 'a', b: 'a' }])
})
it('can select from function without alias', () => {
expect(many(`select * from concat('a') as a join concat('a') as b on b=a`))
.to.deep.equal([{ a: 'a', b: 'a' }])
})
it('can select from function with alias', () => {
expect(many(`select * from concat('a') as a join concat('a') as b on a.a=b.b`))
.to.deep.equal([{ a: 'a', b: 'a' }])
})
it('can select record when not aliased', () => {
expect(many(`create table test (a text, b text);
insert into test values ('a', 'b');
select test from test;`))
.to.deep.equal([{ test: { a: 'a', b: 'b' } }]);
})
it.skip('can select record when aliased', () => {
expect(many(`create table test (a text, b text);
insert into test values ('a', 'b');
select v from test as v;`))
.to.deep.equal([{ v: { a: 'a', b: 'b' } }]);
})
it.skip('does not select parent alias record', () => {
many(`create table test (a text, b text);
insert into test values ('a', 'b')`);
assert.throws(() => many(`select test from test as v`), /does not exist/);
})
it.skip('does not select record when scoped', () => {
many(`create table test (a text, b text);
insert into test values ('a', 'b')`);
assert.throws(() => many(`select test.test from test`), /does not exist/);
})
it('can alias record selection', () => {
expect(many(`create table test (a text, b text);
insert into test values ('a', 'b');
select test as v from test;`))
.to.deep.equal([{ v: { a: 'a', b: 'b' } }]);
})
it('prefers column seleciton over record selection', () => {
expect(many(`create table test (test text, b text);
insert into test values ('a', 'b');
select test from test;`))
.to.deep.equal([{ test: 'a' }]);
})
it('does not leak null symbols (bugfix)', () => {
expect(many(`
create table test(data jsonb);
insert into test values ('{"value": null}'), ('{"value":[null]}'), (null);
select * from test;
`)).to.deep.equal([
{ data: { value: null } },
{ data: { value: [null] } },
{ data: null },
])
})
it('can select raw values', () => {
expect(many(`values (1), (2)`))
.to.deep.equal([
{ column1: 1 },
{ column1: 2 },
]);
expect(many(`values (1, 2)`))
.to.deep.equal([
{ column1: 1, column2: 2 },
]);
});
it('cannot select raw values when not same length', () => {
assert.throws(() => many(`values (1, 2), (3)`), /VALUES lists must all be the same length/);
})
it('can map column names 1', () => {
expect(many(`
create table test(id text, name text, value text);
insert into test values ('id', 'name', 'value');
select * from test as xxx(a,b);
`))
.to.deep.equal([
{ a: 'id', b: 'name', value: 'value' },
]);
});
it('can map column names 2', () => {
expect(many(`
create table test(id text, name text, value text);
insert into test values ('id', 'name', 'value');
select * from test newalias(a,b);
`))
.to.deep.equal([
{ a: 'id', b: 'name', value: 'value' },
]);
});
it('map column names with conflict', () => {
expect(many(`
create table test(id text, name text, value text);
insert into test values ('id', 'name', 'value');
select * from test newalias(a,value);
`))
.to.deep.equal([
{ a: 'id', value: 'name', value1: 'value' },
]);
});
it('cannot map column names when too many names specified', () => {
assert.throws(() => many(`
create table test(id text, name text, value text);
insert into test values ('id', 'name', 'value');
select * from test newalias(a,b,c,d);
`), /table "test" has 3 columns available but 4 columns specified/);
});
it('cannot use default in expression', () => {
assert.throws(() => many(`values (1, default)`), /DEFAULT is not allowed in this context/);
});
}); | the_stack |
import { darker, lighter } from "app/client/ui2018/ColorPalette";
import { colors, testId, vars } from 'app/client/ui2018/cssVars';
import { textInput } from "app/client/ui2018/editableLabel";
import { icon } from "app/client/ui2018/icons";
import { isValidHex } from "app/common/gutil";
import { cssSelectBtn } from 'app/client/ui2018/select';
import { Computed, Disposable, dom, DomArg, Observable, onKeyDown, styled } from "grainjs";
import { defaultMenuOptions, IOpenController, setPopupToCreateDom } from "popweasel";
/**
* colorSelect allows to select color for both fill and text cell color. It allows for fast
* selection thanks to two color palette, `lighter` and `darker`, and also to pick custom color with
* native color picker. Pressing Escape reverts to the saved value. Caller is expected to handle
* logging of onSave() callback rejection. In case of rejection, values are reverted to their saved one.
*/
export function colorSelect(textColor: Observable<string>, fillColor: Observable<string>,
onSave: () => Promise<void>): Element {
const selectBtn = cssSelectBtn(
cssContent(
cssButtonIcon(
'T',
dom.style('color', textColor),
dom.style('background-color', (use) => use(fillColor).slice(0, 7)),
cssLightBorder.cls(''),
testId('btn-icon'),
),
'Cell Color',
),
icon('Dropdown'),
testId('color-select'),
);
const domCreator = (ctl: IOpenController) => buildColorPicker(ctl, textColor, fillColor, onSave);
setPopupToCreateDom(selectBtn, domCreator, {...defaultMenuOptions, placement: 'bottom-end'});
return selectBtn;
}
export function colorButton(textColor: Observable<string>, fillColor: Observable<string>,
onSave: () => Promise<void>): Element {
const iconBtn = cssIconBtn(
icon(
'Dropdown',
dom.style('background-color', textColor),
testId('color-button-dropdown')
),
dom.style('background-color', (use) => use(fillColor).slice(0, 7)),
dom.on('click', (e) => { e.stopPropagation(); e.preventDefault(); }),
testId('color-button'),
);
const domCreator = (ctl: IOpenController) => buildColorPicker(ctl, textColor, fillColor, onSave);
setPopupToCreateDom(iconBtn, domCreator, { ...defaultMenuOptions, placement: 'bottom-end' });
return iconBtn;
}
function buildColorPicker(ctl: IOpenController, textColor: Observable<string>, fillColor: Observable<string>,
onSave: () => Promise<void>): Element {
const textColorModel = PickerModel.create(null, textColor);
const fillColorModel = PickerModel.create(null, fillColor);
function revert() {
textColorModel.revert();
fillColorModel.revert();
ctl.close();
}
ctl.onDispose(async () => {
if (textColorModel.needsSaving() || fillColorModel.needsSaving()) {
try {
// TODO: disable the trigger btn while saving
await onSave();
} catch (e) {
/* Does no logging: onSave() callback is expected to handle their reporting */
textColorModel.revert();
fillColorModel.revert();
}
}
textColorModel.dispose();
fillColorModel.dispose();
});
const colorSquare = (...args: DomArg[]) => cssColorSquare(
...args,
dom.style('color', textColor),
dom.style('background-color', fillColor),
cssLightBorder.cls(''),
);
return cssContainer(
dom.create(PickerComponent, fillColorModel, {
colorSquare: colorSquare(),
title: 'fill',
defaultMode: 'lighter'
}),
cssVSpacer(),
dom.create(PickerComponent, textColorModel, {
colorSquare: colorSquare('T'),
title: 'text',
defaultMode: 'darker'
}),
// gives focus and binds keydown events
(elem: any) => { setTimeout(() => elem.focus(), 0); },
onKeyDown({
Escape: () => { revert(); },
Enter: () => { ctl.close(); },
}),
// Set focus when `focusout` is bubbling from a children element. This is to allow to receive
// keyboard event again after user interacted with the hex box text input.
dom.on('focusout', (ev, elem) => (ev.target !== elem) && elem.focus()),
);
}
interface PickerComponentOptions {
colorSquare: Element;
title: string;
defaultMode: 'darker'|'lighter';
}
// PickerModel is a helper model that helps keep track of the server value for an observable that
// needs to be changed locally without saving. To use, you must call `model.setValue(...)` instead
// of `obs.set(...)`. Then it offers `model.needsSaving()` that tells you whether current value
// needs saving, and `model.revert()` that reverts obs to the its server value.
class PickerModel extends Disposable {
private _serverValue = this.obs.get();
private _localChange: boolean = false;
constructor(public obs: Observable<string>) {
super();
this.autoDispose(this.obs.addListener((val) => {
if (this._localChange) { return; }
this._serverValue = val;
}));
}
// Set the value picked by the user
public setValue(val: string) {
this._localChange = true;
this.obs.set(val);
this._localChange = false;
}
// Revert obs to its server value
public revert() {
this.obs.set(this._serverValue);
}
// Is current value different from the server value?
public needsSaving() {
return this.obs.get() !== this._serverValue;
}
}
class PickerComponent extends Disposable {
private _color = Computed.create(this, this._model.obs, (use, val) => val.toUpperCase().slice(0, 7));
private _mode = Observable.create<'darker'|'lighter'>(this, this._guessMode());
constructor(private _model: PickerModel, private _options: PickerComponentOptions) {
super();
}
public buildDom() {
const title = this._options.title;
return [
cssHeaderRow(
cssColorPreview(
dom.update(
this._options.colorSquare,
cssColorInput(
{type: 'color'},
dom.attr('value', this._color),
dom.on('input', (ev, elem) => this._setValue(elem.value)),
testId(`${title}-input`),
),
),
cssHexBox(
this._color,
async (val) => { if (isValidHex(val)) { this._model.setValue(val); } },
testId(`${title}-hex`),
// select the hex value on click. Doing it using settimeout allows to avoid some
// sporadically losing the selection just after the click.
dom.on('click', (ev, elem) => setTimeout(() => elem.select(), 0)),
)
),
title,
cssBrickToggle(
cssBrick(
cssBrick.cls('-selected', (use) => use(this._mode) === 'darker'),
dom.on('click', () => this._mode.set('darker')),
testId(`${title}-darker-brick`),
),
cssBrick(
cssBrick.cls('-lighter'),
cssBrick.cls('-selected', (use) => use(this._mode) === 'lighter'),
dom.on('click', () => this._mode.set('lighter')),
testId(`${title}-lighter-brick`),
),
),
),
cssPalette(
dom.domComputed(this._mode, (mode) => (mode === 'lighter' ? lighter : darker).map(color => (
cssColorSquare(
dom.style('background-color', color),
cssLightBorder.cls('', (use) => use(this._mode) === 'lighter'),
cssColorSquare.cls('-selected', (use) => use(this._color) === color),
dom.style('outline-color', (use) => use(this._mode) === 'lighter' ? '' : color),
dom.on('click', () => this._setValue(color)),
testId(`color-${color}`),
)
))),
testId(`${title}-palette`),
),
];
}
private _setValue(val: string) {
this._model.setValue(val);
}
private _guessMode(): 'darker'|'lighter' {
if (lighter.indexOf(this._color.get()) > -1) {
return 'lighter';
}
if (darker.indexOf(this._color.get()) > -1) {
return 'darker';
}
return this._options.defaultMode;
}
}
const cssColorInput = styled('input', `
opacity: 0;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0;
border: none;
`);
const cssBrickToggle = styled('div', `
display: flex;
`);
const cssBrick = styled('div', `
height: 20px;
width: 34px;
background-color: #414141;
box-shadow: inset 0 0 0 2px #FFFFFF;
&-selected {
border: 1px solid #414141;
box-shadow: inset 0 0 0 1px #FFFFFF;
}
&-lighter {
background-color: #DCDCDC;
}
`);
const cssColorPreview = styled('div', `
display: flex;
`);
const cssHeaderRow = styled('div', `
display: flex;
justify-content: space-between;
margin-bottom: 8px;
text-transform: capitalize;
`);
const cssPalette = styled('div', `
width: 236px;
height: 68px;
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: space-between;
align-content: space-between;
`);
const cssVSpacer = styled('div', `
height: 12px;
`);
const cssContainer = styled('div', `
padding: 18px 16px;
background-color: white;
box-shadow: 0 2px 16px 0 rgba(38,38,51,0.6);
z-index: 20;
margin: 2px 0;
&:focus {
outline: none;
}
`);
const cssContent = styled('div', `
display: flex;
align-items: center;
`);
const cssHexBox = styled(textInput, `
border: 1px solid #D9D9D9;
border-left: none;
font-size: ${vars.smallFontSize};
display: flex;
align-items: center;
color: ${colors.slate};
width: 56px;
outline: none;
padding: 0 3px;
height: unset;
border-radius: unset;
`);
const cssLightBorder = styled('div', `
border: 1px solid #D9D9D9;
`);
const cssColorSquare = styled('div', `
width: 20px;
height: 20px;
display: flex;
justify-content: center;
align-items: center;
position: relative;
&-selected {
outline: 1px solid #D9D9D9;
outline-offset: 1px;
}
`);
const cssButtonIcon = styled(cssColorSquare, `
margin-right: 6px;
margin-left: 4px;
`);
const cssIconBtn = styled('div', `
min-width: 18px;
width: 18px;
height: 18px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
`); | the_stack |
import { tmpdir as osTmpdir } from 'os';
import { join as pathJoin } from 'path';
import { expect } from 'chai';
import { shouldThrow, testSetup, unexpectedResult } from '../../../src/testSetup';
import { fs } from '../../../src/util/fs';
// Setup the test environment.
const $$ = testSetup();
describe('util/fs', () => {
describe('remove', () => {
it('should throw an error on falsy', async () => {
try {
await shouldThrow(fs.remove(undefined));
} catch (e) {
expect(e).to.have.property('name', 'PathIsNullOrUndefined');
}
});
it('should remove a folder with no files', async () => {
const folderToDelete = pathJoin(osTmpdir(), 'foo');
await fs.mkdirp(folderToDelete);
await fs.remove(folderToDelete);
try {
await shouldThrow(fs.access(folderToDelete));
} catch (e) {
expect(e).to.have.property('code', 'ENOENT');
}
});
it('should remove a folder with one file', async () => {
const folderToDelete = pathJoin(osTmpdir(), 'foo');
const fileToDelete = pathJoin(folderToDelete, 'test.json');
await fs.mkdirp(folderToDelete);
await fs.writeJson(fileToDelete, {});
await fs.remove(folderToDelete);
for (const path of [folderToDelete, fileToDelete]) {
try {
await shouldThrow(fs.access(path));
} catch (e) {
expect(e).to.have.property('code', 'ENOENT');
}
}
});
it('should remove nested sub dirs', async () => {
const folderToDelete = pathJoin(osTmpdir(), 'alpha');
const sub1 = pathJoin(folderToDelete, 'bravo');
const sub2 = pathJoin(folderToDelete, 'charlie');
const nestedSub1 = pathJoin(sub1, 'echo');
const file1 = pathJoin(nestedSub1, 'foo.txt');
const file2 = pathJoin(sub2, 'foo.txt');
await fs.mkdirp(sub2);
await fs.mkdirp(nestedSub1);
await fs.writeJson(file1, {});
await fs.writeJson(file2, {});
await fs.remove(folderToDelete);
for (const path of [file1, file2, nestedSub1, sub2, sub1]) {
try {
await shouldThrow(fs.access(path));
} catch (e) {
expect(e).to.have.property('code', 'ENOENT');
}
}
});
});
describe('removeSync', () => {
it('should throw an error on falsy', () => {
try {
fs.removeSync(undefined);
throw unexpectedResult;
} catch (e) {
expect(e).to.have.property('name', 'PathIsNullOrUndefined');
}
});
it('should remove a folder with no files', () => {
const folderToDelete = pathJoin(osTmpdir(), 'foo');
fs.mkdirpSync(folderToDelete);
fs.removeSync(folderToDelete);
try {
fs.accessSync(folderToDelete);
throw unexpectedResult;
} catch (e) {
expect(e).to.have.property('code', 'ENOENT');
}
});
it('should remove a folder with one file', () => {
const folderToDelete = pathJoin(osTmpdir(), 'foo');
const fileToDelete = pathJoin(folderToDelete, 'test.json');
fs.mkdirpSync(folderToDelete);
fs.writeJsonSync(fileToDelete, {});
fs.removeSync(folderToDelete);
for (const path of [folderToDelete, fileToDelete]) {
try {
fs.accessSync(path);
throw unexpectedResult;
} catch (e) {
expect(e).to.have.property('code', 'ENOENT');
}
}
});
it('should remove nested sub dirs', () => {
const folderToDelete = pathJoin(osTmpdir(), 'alpha');
const sub1 = pathJoin(folderToDelete, 'bravo');
const sub2 = pathJoin(folderToDelete, 'charlie');
const nestedSub1 = pathJoin(sub1, 'echo');
const file1 = pathJoin(nestedSub1, 'foo.txt');
const file2 = pathJoin(sub2, 'foo.txt');
fs.mkdirpSync(sub2);
fs.mkdirpSync(nestedSub1);
fs.writeJsonSync(file1, {});
fs.writeJsonSync(file2, {});
fs.removeSync(folderToDelete);
for (const path of [file1, file2, nestedSub1, sub2, sub1]) {
expect(fs.fileExistsSync(path)).to.be.false;
}
});
});
describe('traverseForFile', () => {
let statFileStub;
let statError;
beforeEach(() => {
statFileStub = $$.SANDBOX.stub(fs, 'stat');
statError = new Error('test');
statError['code'] = 'ENOENT';
});
it('should find a file in the starting dir', async () => {
const path = await fs.traverseForFile('/foo/bar/baz', 'fizz');
expect(path).to.equal('/foo/bar/baz');
});
it('should find a file in a parent dir', async () => {
statFileStub.withArgs('/foo/bar/baz/fizz').returns(Promise.reject(statError));
const path = await fs.traverseForFile('/foo/bar/baz', 'fizz');
expect(path).to.equal('/foo/bar');
});
it('should find a file in the root dir', async () => {
statFileStub.withArgs('/foo/bar/baz/fizz').returns(Promise.reject(statError));
statFileStub.withArgs('/foo/bar/fizz').returns(Promise.reject(statError));
statFileStub.withArgs('/foo/fizz').returns(Promise.reject(statError));
const path = await fs.traverseForFile('/foo/bar/baz', 'fizz');
expect(path).to.equal('/');
});
it('should return undefined if not found', async () => {
statFileStub.returns(Promise.reject(statError));
const path = await fs.traverseForFile('/foo/bar/baz', 'fizz');
expect(path).to.be.undefined;
});
});
describe('traverseForFileSync', () => {
let statFileStub;
let statError;
beforeEach(() => {
statFileStub = $$.SANDBOX.stub(fs, 'statSync');
statError = new Error('test');
statError['code'] = 'ENOENT';
});
it('should find a file in the starting dir', () => {
const path = fs.traverseForFileSync('/foo/bar/baz', 'fizz');
expect(path).to.equal('/foo/bar/baz');
});
it('should find a file in a parent dir', () => {
statFileStub.withArgs('/foo/bar/baz/fizz').throws(statError);
const path = fs.traverseForFileSync('/foo/bar/baz', 'fizz');
expect(path).to.equal('/foo/bar');
});
it('should find a file in the root dir', () => {
statFileStub.withArgs('/foo/bar/baz/fizz').throws(statError);
statFileStub.withArgs('/foo/bar/fizz').throws(statError);
statFileStub.withArgs('/foo/fizz').throws(statError);
const path = fs.traverseForFileSync('/foo/bar/baz', 'fizz');
expect(path).to.equal('/');
});
it('should return undefined if not found', () => {
statFileStub.throws(statError);
const path = fs.traverseForFileSync('/foo/bar/baz', 'fizz');
expect(path).to.be.undefined;
});
});
describe('readJson', () => {
let readFileStub;
beforeEach(() => {
readFileStub = $$.SANDBOX.stub(fs, 'readFile');
});
it('should throw a ParseError for empty JSON file', async () => {
readFileStub.returns(Promise.resolve(''));
try {
await shouldThrow(fs.readJson('emptyFile'));
} catch (error) {
expect(error.message).to.contain('Unexpected end of JSON input');
}
});
it('should throw a ParseError for invalid multiline JSON file', async () => {
readFileStub.returns(
Promise.resolve(`{
"key": 12345,
"value": true,
}`)
);
try {
await shouldThrow(fs.readJson('invalidJSON'));
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON on line 4');
}
});
it('should throw a ParseError for invalid multiline JSON file 2', async () => {
readFileStub.returns(Promise.resolve('{\n"a":}'));
try {
await shouldThrow(fs.readJson('invalidJSON2'));
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON2 on line 2');
}
});
it('should throw a ParseError for invalid single line JSON file', async () => {
readFileStub.returns(Promise.resolve('{ "key": 12345, "value": [1,2,3], }'));
try {
await shouldThrow(fs.readJson('invalidJSON_no_newline'));
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON_no_newline on line 1');
}
});
it('should return a JSON object', async () => {
const validJSON = { key: 12345, value: true };
const validJSONStr = JSON.stringify(validJSON);
readFileStub.returns(Promise.resolve(validJSONStr));
const rv = await fs.readJson('validJSONStr');
expect(rv).to.eql(validJSON);
});
});
describe('readJsonSync', () => {
let readFileStub;
beforeEach(() => {
readFileStub = $$.SANDBOX.stub(fs, 'readFileSync');
});
it('should throw a ParseError for empty JSON file', async () => {
readFileStub.returns('');
try {
fs.readJsonSync('emptyFile');
throw unexpectedResult;
} catch (error) {
expect(error.message).to.contain('Unexpected end of JSON input');
}
});
it('should throw a ParseError for invalid multiline JSON file', async () => {
readFileStub.returns(
`{
"key": 12345,
"value": true,
}`
);
try {
fs.readJsonSync('invalidJSON');
throw unexpectedResult;
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON on line 4');
}
});
it('should throw a ParseError for invalid multiline JSON file 2', async () => {
readFileStub.returns('{\n"a":}');
try {
fs.readJsonSync('invalidJSON2');
throw unexpectedResult;
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON2 on line 2');
}
});
it('should throw a ParseError for invalid single line JSON file', async () => {
readFileStub.returns('{ "key": 12345, "value": [1,2,3], }');
try {
fs.readJsonSync('invalidJSON_no_newline');
throw unexpectedResult;
} catch (err) {
expect(err.message).to.contain('Parse error in file invalidJSON_no_newline on line 1');
}
});
it('should return a JSON object', async () => {
const validJSON = { key: 12345, value: true };
const validJSONStr = JSON.stringify(validJSON);
readFileStub.returns(validJSONStr);
const rv = fs.readJsonSync('validJSONStr');
expect(rv).to.eql(validJSON);
});
});
describe('readJsonMap', () => {
let readFileStub;
beforeEach(() => {
readFileStub = $$.SANDBOX.stub(fs, 'readFile');
});
it('should throw an error for non-object JSON content', async () => {
readFileStub.returns(Promise.resolve('[]'));
try {
await shouldThrow(fs.readJsonMap('arrayFile'));
} catch (error) {
expect(error.message).to.contain('Expected parsed JSON data to be an object');
}
});
it('should return a JSON object', async () => {
const validJSON = { key: 12345, value: true };
const validJSONStr = JSON.stringify(validJSON);
readFileStub.returns(Promise.resolve(validJSONStr));
const rv = await fs.readJsonMap('validJSONStr');
expect(rv).to.eql(validJSON);
});
});
describe('readJsonMapSync', () => {
let readFileStub;
beforeEach(() => {
readFileStub = $$.SANDBOX.stub(fs, 'readFileSync');
});
it('should throw an error for non-object JSON content', () => {
readFileStub.returns('[]');
try {
fs.readJsonMapSync('arrayFile');
throw unexpectedResult;
} catch (error) {
expect(error.message).to.contain('Expected parsed JSON data to be an object');
}
});
it('should return a JSON object', () => {
const validJSON = { key: 12345, value: true };
const validJSONStr = JSON.stringify(validJSON);
readFileStub.returns(validJSONStr);
const rv = fs.readJsonMapSync('validJSONStr');
expect(rv).to.eql(validJSON);
});
});
describe('writeJson', () => {
it('should call writeFile with correct args', async () => {
const writeStub = $$.SANDBOX.stub(fs, 'writeFile').returns(Promise.resolve(null));
const testFilePath = 'utilTest_testFilePath';
const testJSON = { username: 'utilTest_username' };
const stringifiedTestJSON = JSON.stringify(testJSON, null, 2);
await fs.writeJson(testFilePath, testJSON);
expect(writeStub.called).to.be.true;
expect(writeStub.firstCall.args[0]).to.equal(testFilePath);
expect(writeStub.firstCall.args[1]).to.deep.equal(stringifiedTestJSON);
expect(writeStub.firstCall.args[2]).to.deep.equal({
encoding: 'utf8',
mode: '600',
});
});
it('should call writeFile with defined spaces', async () => {
const writeStub = $$.SANDBOX.stub(fs, 'writeFile').returns(Promise.resolve(null));
const testFilePath = 'utilTest_testFilePath';
const testJSON = { username: 'utilTest_username' };
const stringifiedTestJSON = JSON.stringify(testJSON, null, 4);
await fs.writeJson(testFilePath, testJSON, { space: 4 });
expect(writeStub.called).to.be.true;
expect(writeStub.firstCall.args[0]).to.equal(testFilePath);
expect(writeStub.firstCall.args[1]).to.deep.equal(stringifiedTestJSON);
expect(writeStub.firstCall.args[2]).to.deep.equal({
encoding: 'utf8',
mode: '600',
});
});
});
describe('writeJsonSync', () => {
it('should call writeFile with correct args', () => {
const writeStub = $$.SANDBOX.stub(fs, 'writeFileSync').returns(null);
const testFilePath = 'utilTest_testFilePath';
const testJSON = { username: 'utilTest_username' };
const stringifiedTestJSON = JSON.stringify(testJSON, null, 2);
fs.writeJsonSync(testFilePath, testJSON);
expect(writeStub.called).to.be.true;
expect(writeStub.firstCall.args[0]).to.equal(testFilePath);
expect(writeStub.firstCall.args[1]).to.deep.equal(stringifiedTestJSON);
expect(writeStub.firstCall.args[2]).to.deep.equal({
encoding: 'utf8',
mode: '600',
});
});
it('should call writeFile with defined spaces', () => {
const writeStub = $$.SANDBOX.stub(fs, 'writeFileSync').returns(null);
const testFilePath = 'utilTest_testFilePath';
const testJSON = { username: 'utilTest_username' };
const stringifiedTestJSON = JSON.stringify(testJSON, null, 4);
fs.writeJsonSync(testFilePath, testJSON, { space: 4 });
expect(writeStub.called).to.be.true;
expect(writeStub.firstCall.args[0]).to.equal(testFilePath);
expect(writeStub.firstCall.args[1]).to.deep.equal(stringifiedTestJSON);
expect(writeStub.firstCall.args[2]).to.deep.equal({
encoding: 'utf8',
mode: '600',
});
});
});
describe('fileExists', () => {
it('should return true if the file exists', async () => {
// @ts-ignore
$$.SANDBOX.stub(fs, 'access').resolves(true);
const exists = await fs.fileExists('foo/bar.json');
expect(exists).to.be.true;
});
it('should return false if the file does not exist', async () => {
const exists = await fs.fileExists('foo/bar.json');
expect(exists).to.be.false;
});
});
describe('fileExistsSync', () => {
it('should return true if the file exists', () => {
// @ts-ignore
$$.SANDBOX.stub(fs, 'accessSync').returns(true);
const exists = fs.fileExistsSync('foo/bar.json');
expect(exists).to.be.true;
});
it('should return false if the file does not exist', () => {
const exists = fs.fileExistsSync('foo/bar.json');
expect(exists).to.be.false;
});
});
describe('areFilesEqual', () => {
afterEach(() => {
$$.SANDBOX.restore();
});
it('should return false if the files stat.size are different', async () => {
// @ts-ignore
$$.SANDBOX.stub(fs, 'readFile').onCall(0).resolves({}).onCall(1).resolves({});
$$.SANDBOX.stub(fs, 'stat')
.onCall(0)
// @ts-ignore
.resolves({
size: 1,
})
.onCall(1)
// @ts-ignore
.resolves({
size: 2,
});
const results = await fs.areFilesEqual('foo/bar.json', 'foo/bar2.json');
expect(results).to.be.false;
});
it('should return true if the file hashes are the same', async () => {
$$.SANDBOX.stub(fs, 'readFile')
.onCall(0)
.resolves(
`{
"key": 12345,
"value": true,
}`
)
.onCall(1)
.resolves(
`{
"key": 12345,
"value": true,
}`
);
// @ts-ignore
$$.SANDBOX.stub(fs, 'stat').onCall(0).resolves({}).onCall(1).resolves({});
const results = await fs.areFilesEqual('foo/bar.json', 'foo/bar2.json');
expect(results).to.be.true;
});
it('should return false if the file hashes are different', async () => {
$$.SANDBOX.stub(fs, 'readFile')
.onCall(0)
.resolves(
`{
"key": 12345,
"value": true,
}`
)
.onCall(1)
.resolves(
`{
"key": 12345,
"value": false,
}`
);
// @ts-ignore
$$.SANDBOX.stub(fs, 'stat').onCall(0).resolves({}).onCall(1).resolves({});
const results = await fs.areFilesEqual('foo/bar.json', 'foo/bsar2.json');
expect(results).to.be.false;
});
it('should return error when fs.readFile throws error', async () => {
$$.SANDBOX.stub(fs, 'stat')
.onCall(0)
// @ts-ignore
.resolves({
size: 1,
})
.onCall(1)
// @ts-ignore
.resolves({
size: 2,
});
try {
await fs.areFilesEqual('foo', 'bar');
} catch (e) {
expect(e.name).to.equal('DirMissingOrNoAccess');
}
});
it('should return error when fs.stat throws error', async () => {
try {
await fs.areFilesEqual('foo', 'bar');
} catch (e) {
expect(e.name).to.equal('DirMissingOrNoAccess');
}
});
});
describe('actOn', () => {
afterEach(() => {
$$.SANDBOX.restore();
});
it('should run custom functions against contents of a directory', async () => {
const actedOnArray = [];
// @ts-ignore
$$.SANDBOX.stub(fs, 'readdir').resolves(['test1.json', 'test2.json']);
// @ts-ignore
$$.SANDBOX.stub(fs, 'stat').resolves({
isDirectory: () => false,
isFile: () => true,
});
const pathToFolder = pathJoin(osTmpdir(), 'foo');
await fs.actOn(pathToFolder, async (file) => {
actedOnArray.push(file), 'file';
});
const example = [pathJoin(pathToFolder, 'test1.json'), pathJoin(pathToFolder, 'test2.json')];
expect(actedOnArray).to.eql(example);
});
});
}); | the_stack |
import * as vscode from 'vscode';
import { JestTotalResults } from 'jest-editor-support';
import { TestStatus } from '../decorations/test-status';
import { statusBar, StatusBar, Mode, StatusBarUpdate, SBTestStats } from '../StatusBar';
import {
TestReconciliationState,
TestResultProvider,
TestResult,
resultsWithLowerCaseWindowsDriveLetters,
SortedTestResults,
TestResultStatusInfo,
TestReconciliationStateType,
} from '../TestResults';
import { testIdString, IdStringType, escapeRegExp, emptyTestStats } from '../helpers';
import { CoverageMapProvider, CoverageCodeLensProvider } from '../Coverage';
import { updateDiagnostics, updateCurrentDiagnostics, resetDiagnostics } from '../diagnostics';
import { DebugCodeLensProvider, DebugTestIdentifier } from '../DebugCodeLens';
import { DebugConfigurationProvider } from '../DebugConfigurationProvider';
import { DecorationOptions, TestStats } from '../types';
import { CoverageOverlay } from '../Coverage/CoverageOverlay';
import { resultsWithoutAnsiEscapeSequence } from '../TestResults/TestResult';
import { CoverageMapData } from 'istanbul-lib-coverage';
import { Logging } from '../logging';
import { createProcessSession, ProcessSession } from './process-session';
import {
DebugFunction,
JestExtContext,
JestSessionEvents,
JestExtSessionContext,
JestRunEvent,
} from './types';
import * as messaging from '../messaging';
import { SupportedLanguageIds } from '../appGlobals';
import { createJestExtContext, getExtensionResourceSettings, prefixWorkspace } from './helper';
import { PluginResourceSettings } from '../Settings';
import { startWizard, WizardTaskId } from '../setup-wizard';
import { JestExtExplorerContext } from '../test-provider/types';
import { JestTestProvider } from '../test-provider';
import { JestProcessInfo } from '../JestProcessManagement';
interface RunTestPickItem extends vscode.QuickPickItem {
id: DebugTestIdentifier;
}
/** extract lines starts and end with [] */
export class JestExt {
coverageMapProvider: CoverageMapProvider;
coverageOverlay: CoverageOverlay;
testResultProvider: TestResultProvider;
debugCodeLensProvider: DebugCodeLensProvider;
debugConfigurationProvider: DebugConfigurationProvider;
coverageCodeLensProvider: CoverageCodeLensProvider;
// So you can read what's going on
channel: vscode.OutputChannel;
private decorations: TestStatus;
// The ability to show fails in the problems section
private failDiagnostics: vscode.DiagnosticCollection;
// We have to keep track of our inline assert fails to remove later
private processSession: ProcessSession;
private vscodeContext: vscode.ExtensionContext;
private status: ReturnType<StatusBar['bind']>;
private logging: Logging;
private extContext: JestExtContext;
private dirtyFiles: Set<string> = new Set();
private testProvider?: JestTestProvider;
public events: JestSessionEvents;
constructor(
vscodeContext: vscode.ExtensionContext,
workspaceFolder: vscode.WorkspaceFolder,
debugCodeLensProvider: DebugCodeLensProvider,
debugConfigurationProvider: DebugConfigurationProvider,
coverageCodeLensProvider: CoverageCodeLensProvider
) {
const pluginSettings = getExtensionResourceSettings(workspaceFolder.uri);
this.extContext = createJestExtContext(workspaceFolder, pluginSettings);
this.logging = this.extContext.loggingFactory.create('JestExt');
this.channel = vscode.window.createOutputChannel(`Jest (${workspaceFolder.name})`);
this.failDiagnostics = vscode.languages.createDiagnosticCollection(
`Jest (${workspaceFolder.name})`
);
this.debugCodeLensProvider = debugCodeLensProvider;
this.coverageCodeLensProvider = coverageCodeLensProvider;
this.coverageMapProvider = new CoverageMapProvider();
this.vscodeContext = vscodeContext;
this.coverageOverlay = new CoverageOverlay(
vscodeContext,
this.coverageMapProvider,
pluginSettings.showCoverageOnLoad,
pluginSettings.coverageFormatter,
pluginSettings.coverageColors
);
this.events = {
onRunEvent: new vscode.EventEmitter<JestRunEvent>(),
onTestSessionStarted: new vscode.EventEmitter<JestExtSessionContext>(),
onTestSessionStopped: new vscode.EventEmitter<void>(),
};
this.setupRunEvents(this.events);
this.testResultProvider = new TestResultProvider(
this.events,
pluginSettings.debugMode ?? false
);
this.debugConfigurationProvider = debugConfigurationProvider;
this.status = statusBar.bind(workspaceFolder.name);
// The theme stuff
this.decorations = new TestStatus(vscodeContext);
// reset the jest diagnostics
resetDiagnostics(this.failDiagnostics);
this.processSession = this.createProcessSession();
this.setupStatusBar();
}
private getExtExplorerContext(): JestExtExplorerContext {
return {
...this.extContext,
sessionEvents: this.events,
session: this.processSession,
testResolveProvider: this.testResultProvider,
debugTests: this.debugTests,
};
}
private setupWizardAction(taskId: WizardTaskId): messaging.MessageAction {
return {
title: 'Run Setup Wizard',
action: (): unknown =>
startWizard(this.debugConfigurationProvider, {
workspace: this.extContext.workspace,
taskId,
verbose: this.extContext.settings.debugMode,
}),
};
}
private setupRunEvents(events: JestSessionEvents): void {
events.onRunEvent.event((event: JestRunEvent) => {
switch (event.type) {
case 'scheduled':
this.channel.appendLine(`${event.process.id} is scheduled`);
break;
case 'data':
if (event.newLine) {
this.channel.appendLine(event.text);
} else {
this.channel.append(event.text);
}
if (event.isError) {
this.channel.show();
}
break;
case 'start':
this.updateStatusBar({ state: 'running' });
this.channel.clear();
break;
case 'end':
this.updateStatusBar({ state: 'done' });
break;
case 'exit':
if (event.error) {
this.updateStatusBar({ state: 'stopped' });
const msg = `${event.error}\n see troubleshooting: ${messaging.TROUBLESHOOTING_URL}`;
this.channel.appendLine(msg);
this.channel.show();
messaging.systemErrorMessage(
event.error,
messaging.showTroubleshootingAction,
this.setupWizardAction('cmdLine')
);
} else {
this.updateStatusBar({ state: 'done' });
}
break;
}
});
}
private createProcessSession(): ProcessSession {
return createProcessSession({
...this.extContext,
updateWithData: this.updateWithData.bind(this),
onRunEvent: this.events.onRunEvent,
});
}
private toSBStats(stats: TestStats): SBTestStats {
return { ...stats, isDirty: this.dirtyFiles.size > 0 };
}
private setTestFiles(list: string[] | undefined): void {
this.testResultProvider.updateTestFileList(list);
this.updateStatusBar({ stats: this.toSBStats(this.testResultProvider.getTestSuiteStats()) });
}
/**
* starts a new session, notify all session-aware components and gather the metadata.
*/
public async startSession(newSession = false): Promise<void> {
try {
this.dirtyFiles.clear();
this.resetStatusBar();
// new session is needed when the JestExtContext changes
if (newSession) {
await this.processSession.stop();
this.processSession = this.createProcessSession();
this.channel.appendLine('Starting a new Jest Process Session');
} else {
this.channel.appendLine('Starting Jest Session');
}
this.testProvider?.dispose();
if (this.extContext.settings.testExplorer.enabled) {
this.testProvider = new JestTestProvider(this.getExtExplorerContext());
}
await this.processSession.start();
this.events.onTestSessionStarted.fire({ ...this.extContext, session: this.processSession });
this.updateTestFileList();
this.channel.appendLine('Jest Session Started');
} catch (e) {
const msg = prefixWorkspace(this.extContext, 'Failed to start jest session');
this.logging('error', `${msg}:`, e);
this.channel.appendLine('Failed to start jest session');
messaging.systemErrorMessage(
`${msg}...`,
messaging.showTroubleshootingAction,
this.setupWizardAction('cmdLine')
);
}
}
public async stopSession(): Promise<void> {
try {
this.channel.appendLine('Stopping Jest Session');
await this.processSession.stop();
this.testProvider?.dispose();
this.testProvider = undefined;
this.events.onTestSessionStopped.fire();
this.channel.appendLine('Jest Session Stopped');
this.updateStatusBar({ state: 'stopped' });
} catch (e) {
const msg = prefixWorkspace(this.extContext, 'Failed to stop jest session');
this.logging('error', `${msg}:`, e);
this.channel.appendLine('Failed to stop jest session');
messaging.systemErrorMessage('${msg}...', messaging.showTroubleshootingAction);
}
}
/** update custom editor context used by vscode when clause, such as `jest:run.interactive` in package.json */
private updateEditorContext(): void {
const isInteractive = this.extContext.autoRun.isOff || !this.extContext.autoRun.isWatch;
vscode.commands.executeCommand('setContext', 'jest:run.interactive', isInteractive);
}
private updateTestFileEditor(editor: vscode.TextEditor): void {
if (!this.isTestFileEditor(editor)) {
return;
}
const filePath = editor.document.fileName;
let sortedResults: SortedTestResults | undefined;
try {
sortedResults = this.testResultProvider.getSortedResults(filePath);
} catch (e) {
this.channel.appendLine(`${filePath}: failed to parse test results: ${e}`);
// assign an empty result so we can clear the outdated decorators/diagnostics etc
sortedResults = {
fail: [],
skip: [],
success: [],
unknown: [],
};
}
if (!sortedResults) {
return;
}
this.updateDecorators(sortedResults, editor);
updateCurrentDiagnostics(sortedResults.fail, this.failDiagnostics, editor);
}
public triggerUpdateActiveEditor(editor: vscode.TextEditor): void {
this.updateEditorContext();
this.coverageOverlay.updateVisibleEditors();
this.updateTestFileEditor(editor);
}
public triggerUpdateSettings(newSettings?: PluginResourceSettings): Promise<void> {
const updatedSettings =
newSettings ?? getExtensionResourceSettings(this.extContext.workspace.uri);
this.extContext = createJestExtContext(this.extContext.workspace, updatedSettings);
// debug
this.testResultProvider.verbose = updatedSettings.debugMode ?? false;
// coverage
const showCoverage = this.coverageOverlay.enabled ?? updatedSettings.showCoverageOnLoad;
this.coverageOverlay.dispose();
this.coverageOverlay = new CoverageOverlay(
this.vscodeContext,
this.coverageMapProvider,
updatedSettings.showCoverageOnLoad,
updatedSettings.coverageFormatter,
updatedSettings.coverageColors
);
this.extContext.runnerWorkspace.collectCoverage = showCoverage;
this.coverageOverlay.enabled = showCoverage;
return this.startSession(true);
}
updateDecorators(testResults: SortedTestResults, editor: vscode.TextEditor): void {
if (
this.extContext.settings.testExplorer.enabled === false ||
this.extContext.settings.testExplorer.showClassicStatus
) {
// Status indicators (gutter icons)
const styleMap = [
{
data: testResults.success,
decorationType: this.decorations.passing,
state: TestReconciliationState.KnownSuccess,
},
{
data: testResults.fail,
decorationType: this.decorations.failing,
state: TestReconciliationState.KnownFail,
},
{
data: testResults.skip,
decorationType: this.decorations.skip,
state: TestReconciliationState.KnownSkip,
},
{
data: testResults.unknown,
decorationType: this.decorations.unknown,
state: TestReconciliationState.Unknown,
},
];
styleMap.forEach((style) => {
const decorators = this.generateDotsForItBlocks(style.data, style.state);
editor.setDecorations(style.decorationType, decorators);
});
}
// Debug CodeLens
this.debugCodeLensProvider.didChange();
}
private isSupportedDocument(document: vscode.TextDocument | undefined): boolean {
if (!document) {
return false;
}
// if no testFiles list, then error on including more possible files as long as they are in the supported languages - this is backward compatible with v3 logic
return SupportedLanguageIds.includes(document.languageId);
}
private isTestFileEditor(editor: vscode.TextEditor): boolean {
if (!this.isSupportedDocument(editor.document)) {
return false;
}
if (this.testResultProvider.isTestFile(editor.document.fileName) === 'no') {
return false;
}
// if isTestFile returns unknown or true, treated it like a test file to give it best chance to display any test result if ever available
return true;
}
public activate(): void {
if (
vscode.window.activeTextEditor?.document.uri &&
vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri) ===
this.extContext.workspace
) {
this.onDidChangeActiveTextEditor(vscode.window.activeTextEditor);
}
}
public deactivate(): void {
this.stopSession();
this.channel.dispose();
this.testResultProvider.dispose();
this.testProvider?.dispose();
this.events.onRunEvent.dispose();
this.events.onTestSessionStarted.dispose();
this.events.onTestSessionStopped.dispose();
}
//** commands */
public debugTests: DebugFunction = async (
document: vscode.TextDocument | string,
...ids: DebugTestIdentifier[]
): Promise<void> => {
const idString = (type: IdStringType, id: DebugTestIdentifier): string =>
typeof id === 'string' ? id : testIdString(type, id);
const selectTest = async (
testIdentifiers: DebugTestIdentifier[]
): Promise<DebugTestIdentifier | undefined> => {
const items: RunTestPickItem[] = testIdentifiers.map((id) => ({
label: idString('display-reverse', id),
id,
}));
const selected = await vscode.window.showQuickPick<RunTestPickItem>(items, {
placeHolder: 'Select a test to debug',
});
return selected?.id;
};
let testId: DebugTestIdentifier | undefined;
switch (ids.length) {
case 0:
return;
case 1:
testId = ids[0];
break;
default:
testId = await selectTest(ids);
break;
}
if (!testId) {
return;
}
this.debugConfigurationProvider.prepareTestRun(
typeof document === 'string' ? document : document.fileName,
escapeRegExp(idString('full-name', testId))
);
const configs = vscode.workspace
.getConfiguration('launch', this.extContext.workspace.uri)
?.get<vscode.DebugConfiguration[]>('configurations');
let debugConfig =
configs?.find((c) => c.name === 'vscode-jest-tests.v2') ??
configs?.find((c) => c.name === 'vscode-jest-tests');
if (!debugConfig) {
messaging.systemWarningMessage(
prefixWorkspace(
this.extContext,
'No debug config named "vscode-jest-tests.v2" or "vscode-jest-tests" found in launch.json, will use a default config.\nIf you encountered debugging problems, feel free to try the setup wizard below'
),
this.setupWizardAction('debugConfig')
);
debugConfig = this.debugConfigurationProvider.provideDebugConfigurations(
this.extContext.workspace
)[0];
}
vscode.debug.startDebugging(this.extContext.workspace, debugConfig);
};
public runAllTests(editor?: vscode.TextEditor): void {
if (!editor) {
if (this.processSession.scheduleProcess({ type: 'all-tests' })) {
this.dirtyFiles.clear();
return;
}
} else {
const name = editor.document.fileName;
if (
this.processSession.scheduleProcess({
type: 'by-file',
testFileName: name,
notTestFile: this.testResultProvider.isTestFile(name) !== 'yes',
})
) {
this.dirtyFiles.delete(name);
return;
}
}
this.logging('error', 'failed to schedule the run for', editor?.document.fileName);
}
//** window events handling */
onDidCloseTextDocument(document: vscode.TextDocument): void {
this.removeCachedTestResults(document);
}
removeCachedTestResults(document: vscode.TextDocument, invalidateResult = false): void {
if (!document || document.isUntitled) {
return;
}
const filePath = document.fileName;
if (invalidateResult) {
this.testResultProvider.invalidateTestResults(filePath);
} else {
this.testResultProvider.removeCachedResults(filePath);
}
}
onDidChangeActiveTextEditor(editor: vscode.TextEditor): void {
this.triggerUpdateActiveEditor(editor);
}
private handleOnSaveRun(document: vscode.TextDocument): void {
if (!this.isSupportedDocument(document) || this.extContext.autoRun.isWatch) {
return;
}
const isTestFile = this.testResultProvider.isTestFile(document.fileName);
if (
this.extContext.autoRun.onSave &&
(this.extContext.autoRun.onSave === 'test-src-file' || isTestFile !== 'no')
) {
this.processSession.scheduleProcess({
type: 'by-file',
testFileName: document.fileName,
notTestFile: isTestFile !== 'yes',
});
} else {
this.dirtyFiles.add(document.fileName);
}
}
/**
* refresh UI for the given document editor or all active editors in the workspace
* @param document refresh UI for the specific document. if undefined, refresh all active editors in the workspace.
*/
private refreshDocumentChange(document?: vscode.TextDocument): void {
for (const editor of vscode.window.visibleTextEditors) {
if (
(document && editor.document === document) ||
vscode.workspace.getWorkspaceFolder(editor.document.uri) === this.extContext.workspace
) {
this.triggerUpdateActiveEditor(editor);
}
}
this.updateStatusBar({
stats: this.toSBStats(this.testResultProvider.getTestSuiteStats()),
});
}
/**
* This event is fired with the document not dirty when:
* - before the onDidSaveTextDocument event
* - the document was changed by an external editor
*/
onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent): void {
if (event.document.isDirty) {
return;
}
if (event.document.uri.scheme === 'git') {
return;
}
// Ignore a clean file with a change:
if (event.contentChanges.length > 0) {
return;
}
// there is a bit redudant since didSave already handle the save changes
// but not sure if there are other non-editor related change we are trying
// to capture, so leave it be for now...
this.refreshDocumentChange(event.document);
}
onWillSaveTextDocument(event: vscode.TextDocumentWillSaveEvent): void {
if (event.document.isDirty) {
this.removeCachedTestResults(event.document, true);
}
}
onDidSaveTextDocument(document: vscode.TextDocument): void {
this.handleOnSaveRun(document);
this.refreshDocumentChange(document);
}
private updateTestFileList(): void {
this.processSession.scheduleProcess({
type: 'list-test-files',
onResult: (files, error) => {
this.setTestFiles(files);
this.logging('debug', `found ${files?.length} testFiles`);
if (error) {
const msg = prefixWorkspace(
this.extContext,
'Failed to obtain test file list, something might not be setup right?'
);
this.logging('error', msg, error);
messaging.systemWarningMessage(
msg,
messaging.showTroubleshootingAction,
this.setupWizardAction('cmdLine')
);
}
},
});
}
onDidCreateFiles(_event: vscode.FileCreateEvent): void {
this.updateTestFileList();
}
onDidRenameFiles(_event: vscode.FileRenameEvent): void {
this.updateTestFileList();
}
onDidDeleteFiles(_event: vscode.FileDeleteEvent): void {
this.updateTestFileList();
}
toggleCoverageOverlay(): void {
this.coverageOverlay.toggleVisibility();
// restart jest since coverage condition has changed
this.triggerUpdateSettings(this.extContext.settings);
}
private setupStatusBar(): void {
this.updateStatusBar({ state: 'initial' });
}
private resetStatusBar(): void {
const modes: Mode[] = [];
if (this.coverageOverlay.enabled) {
modes.push('coverage');
}
modes.push(this.extContext.autoRun.mode);
this.updateStatusBar({ state: 'initial', mode: modes, stats: emptyTestStats() });
}
private updateStatusBar(status: StatusBarUpdate): void {
this.status.update(status);
}
_updateCoverageMap(coverageMap?: CoverageMapData): Promise<void> {
return this.coverageMapProvider.update(coverageMap).then(() => {
this.coverageCodeLensProvider.coverageChanged();
this.coverageOverlay.updateVisibleEditors();
});
}
private updateWithData(data: JestTotalResults, process: JestProcessInfo): void {
const noAnsiData = resultsWithoutAnsiEscapeSequence(data);
const normalizedData = resultsWithLowerCaseWindowsDriveLetters(noAnsiData);
this._updateCoverageMap(normalizedData.coverageMap);
const statusList = this.testResultProvider.updateTestResults(normalizedData, process);
updateDiagnostics(statusList, this.failDiagnostics);
this.refreshDocumentChange();
}
private generateDotsForItBlocks(
blocks: TestResult[],
state: TestReconciliationStateType
): DecorationOptions[] {
return blocks.map((it) => ({
range: new vscode.Range(it.start.line, it.start.column, it.start.line, it.start.column + 1),
hoverMessage: TestResultStatusInfo[state].desc,
identifier: it.name,
}));
}
} | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Signer, BigNumberish, utils, Wallet } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
MockERC20,
MockERC20__factory,
PancakeFactory,
PancakeFactory__factory,
PancakeRouter,
PancakeRouterV2__factory,
PancakeRouter__factory,
PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading,
PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading__factory,
WETH,
WETH__factory,
WNativeRelayer__factory,
WNativeRelayer,
} from "../../../../../typechain";
import { MockPancakeswapV2CakeMaxiWorker__factory } from "../../../../../typechain/factories/MockPancakeswapV2CakeMaxiWorker__factory";
import { MockPancakeswapV2CakeMaxiWorker } from "../../../../../typechain/MockPancakeswapV2CakeMaxiWorker";
chai.use(solidity);
const { expect } = chai;
describe("PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading", () => {
const FOREVER = "2000000000";
/// Pancakeswap-related instance(s)
let factoryV2: PancakeFactory;
let routerV2: PancakeRouter;
/// MockPancakeswapV2CakeMaxiWorker-related instance(s)
let mockPancakeswapV2WorkerBaseFTokenPair: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2WorkerBNBFtokenPair: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2WorkerBaseBNBTokenPair: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2EvilWorker: MockPancakeswapV2CakeMaxiWorker;
/// Token-related instance(s)
let wbnb: WETH;
let baseToken: MockERC20;
let farmingToken: MockERC20;
/// Strategy instance(s)
let strat: PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let deployerAddress: string;
let aliceAddress: string;
let bobAddress: string;
// Contract Signer
let baseTokenAsAlice: MockERC20;
let baseTokenAsBob: MockERC20;
let farmingTokenAsAlice: MockERC20;
let farmingTokenAsBob: MockERC20;
let wbnbTokenAsAlice: WETH;
let routerV2AsAlice: PancakeRouter;
let routerV2AsBob: PancakeRouter;
let stratAsAlice: PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading;
let stratAsBob: PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading;
let mockPancakeswapV2WorkerBaseFTokenPairAsAlice: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2WorkerBNBFtokenPairAsAlice: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice: MockPancakeswapV2CakeMaxiWorker;
let mockPancakeswapV2EvilWorkerAsAlice: MockPancakeswapV2CakeMaxiWorker;
let wNativeRelayer: WNativeRelayer;
async function fixture() {
[deployer, alice, bob] = await ethers.getSigners();
[deployerAddress, aliceAddress, bobAddress] = await Promise.all([
deployer.getAddress(),
alice.getAddress(),
bob.getAddress(),
]);
// Setup Pancakeswap
const PancakeFactory = (await ethers.getContractFactory("PancakeFactory", deployer)) as PancakeFactory__factory;
factoryV2 = await PancakeFactory.deploy(deployerAddress);
await factoryV2.deployed();
const WBNB = (await ethers.getContractFactory("WETH", deployer)) as WETH__factory;
wbnb = await WBNB.deploy();
/// Setup WNativeRelayer
const WNativeRelayer = (await ethers.getContractFactory("WNativeRelayer", deployer)) as WNativeRelayer__factory;
wNativeRelayer = await WNativeRelayer.deploy(wbnb.address);
await wNativeRelayer.deployed();
const PancakeRouterV2 = (await ethers.getContractFactory("PancakeRouterV2", deployer)) as PancakeRouterV2__factory;
routerV2 = await PancakeRouterV2.deploy(factoryV2.address, wbnb.address);
await routerV2.deployed();
/// Setup token stuffs
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
baseToken = (await upgrades.deployProxy(MockERC20, ["BTOKEN", "BTOKEN", 18])) as MockERC20;
await baseToken.deployed();
await baseToken.mint(aliceAddress, ethers.utils.parseEther("100"));
await baseToken.mint(bobAddress, ethers.utils.parseEther("100"));
farmingToken = (await upgrades.deployProxy(MockERC20, ["FTOKEN", "FTOKEN", 18])) as MockERC20;
await farmingToken.deployed();
await farmingToken.mint(aliceAddress, ethers.utils.parseEther("10"));
await farmingToken.mint(bobAddress, ethers.utils.parseEther("10"));
await factoryV2.createPair(baseToken.address, wbnb.address);
await factoryV2.createPair(farmingToken.address, wbnb.address);
/// Setup MockPancakeswapV2CakeMaxiWorker
const MockPancakeswapV2CakeMaxiWorker = (await ethers.getContractFactory(
"MockPancakeswapV2CakeMaxiWorker",
deployer
)) as MockPancakeswapV2CakeMaxiWorker__factory;
mockPancakeswapV2WorkerBaseFTokenPair = (await MockPancakeswapV2CakeMaxiWorker.deploy(
baseToken.address,
farmingToken.address,
[baseToken.address, wbnb.address, farmingToken.address],
[farmingToken.address, wbnb.address]
)) as MockPancakeswapV2CakeMaxiWorker;
await mockPancakeswapV2WorkerBaseFTokenPair.deployed();
mockPancakeswapV2WorkerBNBFtokenPair = (await MockPancakeswapV2CakeMaxiWorker.deploy(
wbnb.address,
farmingToken.address,
[wbnb.address, farmingToken.address],
[farmingToken.address, wbnb.address]
)) as MockPancakeswapV2CakeMaxiWorker;
await mockPancakeswapV2WorkerBNBFtokenPair.deployed();
mockPancakeswapV2WorkerBaseBNBTokenPair = (await MockPancakeswapV2CakeMaxiWorker.deploy(
baseToken.address,
wbnb.address,
[baseToken.address, wbnb.address],
[farmingToken.address, wbnb.address]
)) as MockPancakeswapV2CakeMaxiWorker;
await mockPancakeswapV2WorkerBaseBNBTokenPair.deployed();
mockPancakeswapV2EvilWorker = (await MockPancakeswapV2CakeMaxiWorker.deploy(
baseToken.address,
farmingToken.address,
[baseToken.address, wbnb.address, farmingToken.address],
[farmingToken.address, wbnb.address]
)) as MockPancakeswapV2CakeMaxiWorker;
await mockPancakeswapV2EvilWorker.deployed();
const PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading = (await ethers.getContractFactory(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading",
deployer
)) as PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading__factory;
strat = (await upgrades.deployProxy(PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading, [
routerV2.address,
wNativeRelayer.address,
])) as PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading;
await strat.deployed();
await strat.setWorkersOk(
[
mockPancakeswapV2WorkerBaseFTokenPair.address,
mockPancakeswapV2WorkerBNBFtokenPair.address,
mockPancakeswapV2WorkerBaseBNBTokenPair.address,
],
true
);
await wNativeRelayer.setCallerOk([strat.address], true);
// Assign contract signer
baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice);
baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob);
farmingTokenAsAlice = MockERC20__factory.connect(farmingToken.address, alice);
farmingTokenAsBob = MockERC20__factory.connect(farmingToken.address, bob);
wbnbTokenAsAlice = WETH__factory.connect(wbnb.address, alice);
routerV2AsAlice = PancakeRouter__factory.connect(routerV2.address, alice);
routerV2AsBob = PancakeRouter__factory.connect(routerV2.address, bob);
stratAsAlice = PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading__factory.connect(
strat.address,
alice
);
stratAsBob = PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading__factory.connect(
strat.address,
bob
);
mockPancakeswapV2WorkerBaseFTokenPairAsAlice = MockPancakeswapV2CakeMaxiWorker__factory.connect(
mockPancakeswapV2WorkerBaseFTokenPair.address,
alice
);
mockPancakeswapV2WorkerBNBFtokenPairAsAlice = MockPancakeswapV2CakeMaxiWorker__factory.connect(
mockPancakeswapV2WorkerBNBFtokenPair.address,
alice
);
mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice = MockPancakeswapV2CakeMaxiWorker__factory.connect(
mockPancakeswapV2WorkerBaseBNBTokenPair.address,
alice
);
mockPancakeswapV2EvilWorkerAsAlice = MockPancakeswapV2CakeMaxiWorker__factory.connect(
mockPancakeswapV2EvilWorker.address,
alice
);
// Adding liquidity to the pool
// Alice adds 0.1 FTOKEN + 1 BTOKEN + 1 WBNB
await wbnbTokenAsAlice.deposit({
value: ethers.utils.parseEther("52"),
});
await farmingTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("0.1"));
await baseTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("1"));
await wbnbTokenAsAlice.approve(routerV2.address, ethers.utils.parseEther("2"));
// Add liquidity to the BTOKEN-WBNB pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
baseToken.address,
wbnb.address,
ethers.utils.parseEther("1"),
ethers.utils.parseEther("1"),
"0",
"0",
aliceAddress,
FOREVER
);
// Add liquidity to the WBNB-FTOKEN pool on Pancakeswap
await routerV2AsAlice.addLiquidity(
farmingToken.address,
wbnb.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("1"),
"0",
"0",
aliceAddress,
FOREVER
);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
context("when bad calldata", async () => {
it("should revert", async () => {
// Bob passes some bad calldata that can't be decoded
await expect(stratAsBob.execute(bobAddress, "0", "0x1234")).to.be.reverted;
});
});
context("when the setOkWorkers caller is not an owner", async () => {
it("should be reverted", async () => {
await expect(stratAsBob.setWorkersOk([mockPancakeswapV2EvilWorkerAsAlice.address], true)).to.reverted;
});
});
context("when non-worker call the strat", async () => {
it("should revert", async () => {
await expect(stratAsBob.execute(bobAddress, "0", ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"]))).to.be
.reverted;
});
});
context("when caller worker hasn't been whitelisted", async () => {
it("should revert as bad worker", async () => {
await wbnbTokenAsAlice.transfer(mockPancakeswapV2EvilWorkerAsAlice.address, ethers.utils.parseEther("0.05"));
await expect(
mockPancakeswapV2EvilWorkerAsAlice.work(
0,
aliceAddress,
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.02"), "0", ethers.utils.parseEther("0.05")]
),
]
)
)
).to.be.revertedWith(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading::onlyWhitelistedWorkers:: bad worker"
);
});
});
context("when revoking whitelist workers", async () => {
it("should revert as bad worker", async () => {
await strat.setWorkersOk([mockPancakeswapV2WorkerBNBFtokenPair.address], false);
await expect(
mockPancakeswapV2WorkerBNBFtokenPairAsAlice.work(
0,
aliceAddress,
"0",
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.02"), "0", ethers.utils.parseEther("0.05")]
),
]
)
)
).to.be.revertedWith(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading::onlyWhitelistedWorkers:: bad worker"
);
});
});
context("when BTOKEN is a wrap native", async () => {
context("when liquidated FTOKEN not enough to cover maxReturnDebt", async () => {
it("should revert", async () => {
// if 0.1 Ftoken = 1 WBNB
// x FToken = (x * 0.9975) * (1 / (0.1 + x*0.9975)) = 0.5
// x = ~ 9.975
// thus, 0.04 < 9.975 then retrun not enough to pay back debt
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
await expect(
mockPancakeswapV2WorkerBNBFtokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.5"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.04"),
ethers.utils.parseEther("0.5"),
ethers.utils.parseEther("0.088861041492620439"),
]
),
]
)
)
).to.be.revertedWith("PancakeRouter: EXCESSIVE_INPUT_AMOUNT");
});
});
context("when maxfarmingTokenToLiquidate > FTOKEN from worker", async () => {
it("should use all FTOKEN", async () => {
// Alice position: 0.1 FTOKEN
// Alice liquidate: Math.min(888, 0.1) = 0.1 FTOKEN
// Debt: 0.1 WBNB
// maxReturn: 8888, hence Alice return 0.1 BNB (all debt)
// (x * 0.9975) * (1 / (0.1 + x * 0.9975)) = 0.1 WBNB
// x = 0.011138958507379561 FTOKEN needed to be swap to 0.1 WBNB to pay debt
// -------
// Deployer should get 0.1 BNB back. (Assuming Deployer is Vault)
// Alice should get 0.1 - 0.011138958507379561 = 0.088861041492620439 FTOKEN back.
// Worker should get 0.1 - 0.1 = 0 FTOKEN back as Alice liquidate 100% of her position.
// -------
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
const deployerWbnbBefore = await wbnb.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBNBFtokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("888"),
ethers.utils.parseEther("0.5"),
ethers.utils.parseEther("0.088861041492620439"),
]
),
]
),
{ gasPrice: 0 }
)
)
.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(wbnb.address, farmingToken.address, ethers.utils.parseEther("0.1"), ethers.utils.parseEther("0.1"));
const workerFarmingTokenAfter = await farmingToken.balanceOf(mockPancakeswapV2WorkerBNBFtokenPair.address);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
const deployerWbnbAfter = await wbnb.balanceOf(deployerAddress);
expect(
aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore),
"Alice should get 0.088861041492620439 FTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.088861041492620439"));
expect(deployerWbnbAfter.sub(deployerWbnbBefore), "Deployer (as Vault) should get 0.1 WBNB back").to.be.eq(
ethers.utils.parseEther("0.1")
);
expect(workerFarmingTokenAfter, "Worker should get 0 FTOKEN back").to.be.eq(ethers.utils.parseEther("0"));
});
});
context("when maxReturnDebt > debt", async () => {
it("should return all debt", async () => {
// Alice position: 0.1 FTOKEN
// Alice liquidate: 0.05 FTOKEN
// Debt: 0.1 WBNB
// maxReturn: 8888, hence Alice return 0.1 BNB (all debt)
// (x * 0.9975) * (1 / (0.1 + x * 0.9975)) = 0.1 WBNB
// x = 0.011138958507379561 FTOKEN needed to be swap to 0.1 WBNB to pay debt
// -------
// Alice should get 0.1 BNB back. (Assuming Alice is Vault)
// Alice should get 0.05 - 0.011138958507379561 = 0.038861041492620439 FTOKEN back.
// Worker should get 0.1 - 0.05 = 0.05 FTOKEN back.
// -------
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
const deployerWbnbBefore = await wbnb.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBNBFtokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("0.038861041492620439"),
]
),
]
),
{ gasPrice: "0" }
)
)
.to.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(
wbnb.address,
farmingToken.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.1")
);
const workerFarmingTokenAfter = await farmingToken.balanceOf(mockPancakeswapV2WorkerBNBFtokenPair.address);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
const deployerWbnbAfter = await wbnb.balanceOf(deployerAddress);
expect(
aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore),
"Alice should get 0.038861041492620439 FTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.038861041492620439"));
expect(deployerWbnbAfter.sub(deployerWbnbBefore), "Deployer (as Vault) should get 0.1 WBNB back").to.be.eq(
ethers.utils.parseEther("0.1")
);
expect(workerFarmingTokenAfter, "Worker should get 0.05 FTOKEN back").to.be.eq(ethers.utils.parseEther("0.05"));
});
});
context("when FTOKEN from swap < slippage", async () => {
it("should revert", async () => {
// if 0.1 Ftoken = 1 WBNB
// x FToken = (x * 0.9975) * (1 / (0.1 + x*0.9975)) = 0.1
// x = ~ 0.011138958507379568
// thus, the return farming token will be 0.088861041492620439
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
await expect(
mockPancakeswapV2WorkerBNBFtokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.04"), "0", ethers.utils.parseEther("0.088861041492620439").add(1)]
),
]
)
)
).to.be.revertedWith(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading::execute:: insufficient farmingToken amount received"
);
});
});
context("when debt > 0", async () => {
it("should convert FTOKEN to WBNB enough for maxReturnDebt, and return farmingToken to the user", async () => {
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceWbnbBefore = await wbnb.balanceOf(aliceAddress);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
await mockPancakeswapV2WorkerBNBFtokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.04"), ethers.utils.parseEther("0.01"), "0"]
),
]
)
);
const aliceWbnbAfter = await wbnb.balanceOf(aliceAddress);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
// amountOut of 0.04 Ftoken
// if 0.1 Ftoken = 1 WBNB
// x FToken = (x * 0.9975 * 1) / (0.1 + x*0.9975) = 0.01
// x = ~ 0.00101263259157996
// thus, 0.04 - 0.00101263259157996 = 0.03898736740842004 FToken will be returned to ALICE
// and the worker will return 0.01 WBNB to ALICE as a repaying debt
expect(aliceWbnbAfter.sub(aliceWbnbBefore)).to.be.eq(ethers.utils.parseEther("0.01"));
expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await wbnb.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(mockPancakeswapV2WorkerBNBFtokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.06")
);
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.be.eq(
ethers.utils.parseEther("0.038987367408420039")
);
});
});
context("when debt = 0", async () => {
it("should return partial farmingToken to the user", async () => {
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBNBFtokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceWbnbBefore = await wbnb.balanceOf(aliceAddress);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
await mockPancakeswapV2WorkerBNBFtokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.04"), "0", "0"]
),
]
)
);
const aliceWbnbAfter = await wbnb.balanceOf(aliceAddress);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
// FToken, wbnb in a strategy contract MUST be 0
expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await wbnb.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(mockPancakeswapV2WorkerBNBFtokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.06")
);
// Alice will have partial farming token of 0.04 FToken back since she got no debt
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.be.eq(ethers.utils.parseEther("0.04"));
expect(aliceWbnbAfter.sub(aliceWbnbBefore)).to.be.eq(ethers.utils.parseEther("0"));
});
});
});
context("when BTOKEN is NOT a wrap native", async () => {
context("when liquidated FTOKEN not enough to cover maxReturnDebt", async () => {
it("should revert", async () => {
// if 0.1 Ftoken = 1 WBNB
// x FToken = (x * 0.9975) * (1 / (0.1 + x*0.9975)) = 0.2
// x = ~ 0.02506265664160401
// thus, 0.02 < 0.02506265664160401 then retrun not enough to pay back debt
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
await expect(
mockPancakeswapV2WorkerBaseFTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.2"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.02"),
ethers.utils.parseEther("0.2"),
ethers.utils.parseEther("0.088861041492620439").add(1),
]
),
]
)
)
).to.be.revertedWith("PancakeRouter: EXCESSIVE_INPUT_AMOUNT");
});
});
context("when maxFarmingTokenToLiquidate > FTOKEN from worker", async () => {
it("should use all FTOKEN", async () => {
// Alice position: 0.1 FTOKEN
// Alice liquidate: Math.min(8888, 0.1) = 0.1 FTOKEN
// Debt: 0.1 BTOKEN
// maxReturn: 8888, hence Alice return 0.1 BTOKEN (all debt)
// (x * 0.9975) * (1 / (1 + x * 0.9975)) = 0.1 BTOKEN
// x = 0.11138958507379568 WBNB needed to be swap to 0.1 BTOKEN to pay debt
// (y * 0.9975) * (1 / (1 + y * 0.9975)) = 0.11138958507379568 WBNB
// y = 0.012566672086044004 FTOKEN needed to be swapped to 0.11138958507379568 WBNB
// -------
// Deployer should get 0.1 BTOKEN back. (Assuming Deployer is Vault)
// Alice should get 0.1 - 0.012566672086044004 = 0.087433327913955996 FTOKEN back.
// Worker should get 0.1 - 0.1 = 0 FTOKEN back as Alice uses 100% of her position.
// -------
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
const deployerBtokenBefore = await baseToken.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBaseFTokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("0.087433327913955996"),
]
),
]
),
{ gasPrice: "0" }
)
)
.to.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(
baseToken.address,
farmingToken.address,
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0.1")
);
const workerFarmingTokenAfter = await farmingToken.balanceOf(mockPancakeswapV2WorkerBaseFTokenPair.address);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
const deployerBtokenAfter = await baseToken.balanceOf(deployerAddress);
expect(
aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore),
"Alice should get 0.087433327913955996 FTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.087433327913955996"));
expect(
deployerBtokenAfter.sub(deployerBtokenBefore),
"Deployer (as Vault) should get 0.1 BTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.1"));
expect(workerFarmingTokenAfter, "Worker should get 0.05 FTOKEN back").to.be.eq(ethers.utils.parseEther("0"));
});
});
context("when maxReturnDebt > debt", async () => {
it("should return all debt", async () => {
// Alice position: 0.1 FTOKEN
// Alice liquidate: 0.05 FTOKEN
// Debt: 0.1 BTOKEN
// maxReturn: 8888, hence Alice return 0.1 BTOKEN (all debt)
// (x * 0.9975) * (1 / (1 + x * 0.9975)) = 0.1 BTOKEN
// x = 0.11138958507379568 WBNB needed to be swap to 0.1 BTOKEN to pay debt
// (y * 0.9975) * (1 / (1 + y * 0.9975)) = 0.11138958507379568 WBNB
// y = 0.012566672086044004 FTOKEN needed to be swapped to 0.11138958507379568 WBNB
// -------
// Deployer should get 0.1 BTOKEN back. (Assuming Deployer is Vault)
// Alice should get 0.05 - 0.012566672086044004 = 0.037433327913955996 FTOKEN back.
// Worker should get 0.1 - 0.05 = 0.05 FTOKEN back.
// -------
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
const deployerBtokenBefore = await baseToken.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBaseFTokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("0.037433327913955996"),
]
),
]
),
{ gasPrice: "0" }
)
)
.to.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(
baseToken.address,
farmingToken.address,
ethers.utils.parseEther("0.05"),
ethers.utils.parseEther("0.1")
);
const workerFarmingTokenAfter = await farmingToken.balanceOf(mockPancakeswapV2WorkerBaseFTokenPair.address);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
const deployerBtokenAfter = await baseToken.balanceOf(deployerAddress);
expect(
aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore),
"Alice should get 0.037433327913955996 FTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.037433327913955996"));
expect(
deployerBtokenAfter.sub(deployerBtokenBefore),
"Deployer (as Vault) should get 0.1 BTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.1"));
expect(workerFarmingTokenAfter, "Worker should get 0.05 FTOKEN back").to.be.eq(ethers.utils.parseEther("0.05"));
});
});
context("when FTOKEN from swap < slippage", async () => {
it("should revert", async () => {
// if 1 WBNB = 1 BaseToken
// x WBNB = (x * 0.9975) * (1 / (1 + x * 0.9975)) = 0.1
// x WBNB =~ ~ 0.11138958507379568
// if 0.1 FToken = 1 WBNB
// x FToken = (x * 0.9975) * (1 / (0.1 + x * 0.9975)) = 0.11138958507379568
// x = 0.012566672086044004
// thus 0.1 - 0.012566672086044 = 0.087433327913955996
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
await expect(
mockPancakeswapV2WorkerBaseFTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.04"),
ethers.utils.parseEther("0.1"),
ethers.utils.parseEther("0.087433327913955996").add(1),
]
),
]
)
)
).to.be.revertedWith(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading::execute:: insufficient farmingToken amount received"
);
});
});
context("when debt > 0", async () => {
it("should convert to BTOKEN to be enough for repaying the debt, and return farmingToken to the user", async () => {
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
await mockPancakeswapV2WorkerBaseFTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.05"), ethers.utils.parseEther("0.1"), "0"]
),
]
)
);
const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
// if 1 WBNB = 1 BTOKEN
// x WBNB = (x * 0.9975 * 1) / (1 + x * 0.9975) = 0.1
// x WBNB =~ ~ 0.11138958507379568
// if 0.1 FToken = 1 WBNB
// x FToken = (x * 0.9975 * 1) / (0.1 + x * 0.9975) = 0.11138958507379568
// x = 0.012566672086044004
// thus 0.05 - 0.012566672086044004 = 0.037433327913955996 FToken will be returned to ALICE
// Alice will have 0.037433327913955996 FTOKEN back and 0.1 BTOKEN as a repaying debt
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.be.eq(ethers.utils.parseEther("0.1"));
expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(mockPancakeswapV2WorkerBaseFTokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.05")
);
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.be.eq(
ethers.utils.parseEther("0.037433327913955996")
);
});
});
context("when debt = 0", async () => {
it("should return partial farmingToken to the user", async () => {
await farmingTokenAsAlice.transfer(
mockPancakeswapV2WorkerBaseFTokenPair.address,
ethers.utils.parseEther("0.1")
);
const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress);
const aliceFarmingTokenBefore = await farmingToken.balanceOf(aliceAddress);
await mockPancakeswapV2WorkerBaseFTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.04"), "0", "0"]
),
]
)
);
const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress);
const aliceFarmingTokenAfter = await farmingToken.balanceOf(aliceAddress);
// FToken, BToken in a strategy contract MUST be 0
expect(await farmingToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await farmingToken.balanceOf(mockPancakeswapV2WorkerBaseFTokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.06")
);
// Alice will have partial farming token of 0.04 FToken back since she got no debt
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.be.eq(ethers.utils.parseEther("0"));
expect(aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore)).to.be.eq(ethers.utils.parseEther("0.04"));
});
});
});
context("when the farming token is a wrap native", async () => {
context("when liquidated WBNB not enough to cover maxReturnDebt", async () => {
it("should revert", async () => {
// if 0.1 Ftoken = 1 WBNB
// x FToken = (x * 0.9975) * (1 / (0.1 + x*0.9975)) = 0.5
// x = ~ 9.975
// thus, 0.04 < 9.975 then retrun not enough to pay back debt
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
await expect(
mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.5"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.04"),
ethers.utils.parseEther("0.5"),
ethers.utils.parseEther("0.088861041492620439"),
]
),
]
)
)
).to.be.revertedWith("PancakeRouter: EXCESSIVE_INPUT_AMOUNT");
});
});
context("when maxFarmingTokenToLiquidate > WBNB from worker", async () => {
it("should use all WBNB", async () => {
// Alice position: 1 WBNB
// Alice liquidate: Math.min(8888, 1) = 1 WBNB
// Debt: 0.1 BTOKEN
// maxReturn: 8888, hence Alice return 0.1 BTOKEN (all debt)
// (x * 9975 * 1) / (1 * 1000 + (x * 9975)) = 0.1 BTOKEN
// x = 0.111389585073795601 WBNB needed to be swap to 0.1 BTOKEN to pay debt
// -------
// Deployer should get 0.1 BTOKEN back. (Assuming Deployer is Vault)
// Alice should get 1 - 0.111389585073795601 = 0.888610414926204399 BNB back.
// Worker should get 1 - 1 = 0 WBNB back.
// -------
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
const aliceBnbBefore = await alice.getBalance();
const deployerBtokenBefore = await baseToken.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBaseBNBTokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("0.888610414926204399"),
]
),
]
),
{ gasPrice: "0" }
)
)
.to.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(baseToken.address, wbnb.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("0.1"));
const workerWbnbAfter = await wbnb.balanceOf(mockPancakeswapV2WorkerBaseBNBTokenPair.address);
const aliceBnbAfter = await alice.getBalance();
const deployerBtokenAfter = await baseToken.balanceOf(deployerAddress);
expect(aliceBnbAfter.sub(aliceBnbBefore), "Alice should get 0.888610414926204399 BNB back").to.be.eq(
ethers.utils.parseEther("0.888610414926204399")
);
expect(
deployerBtokenAfter.sub(deployerBtokenBefore),
"Deployer (as Vault) should get 0.1 BTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.1"));
expect(workerWbnbAfter, "Worker should get 0 WBNB back").to.be.eq(ethers.utils.parseEther("0"));
});
});
context("when maxReturnDebt > debt", async () => {
it("should return all debt", async () => {
// Alice position: 1 WBNB
// Alice liquidate: 0.5 WBNB
// Debt: 0.1 BTOKEN
// maxReturn: 8888, hence Alice return 0.1 BTOKEN (all debt)
// (x * 9975 * 1) / (1 * 1000 + (x * 9975)) = 0.1 BTOKEN
// x = 0.111389585073795601 WBNB needed to be swap to 0.1 BTOKEN to pay debt
// -------
// Deployer should get 0.1 BTOKEN back. (Assuming Deployer is Vault)
// Alice should get 0.5 - 0.111389585073795601 = 0.388610414926204399 BNB back.
// Worker should get 1 - 0.5 = 0.5 WBNB back.
// -------
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
const aliceBnbBefore = await alice.getBalance();
const deployerBtokenBefore = await baseToken.balanceOf(deployerAddress);
await expect(
mockPancakeswapV2WorkerBaseBNBTokenPair.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[
ethers.utils.parseEther("0.5"),
ethers.utils.parseEther("8888"),
ethers.utils.parseEther("0.038861041492620439"),
]
),
]
),
{ gasPrice: "0" }
)
)
.to.emit(strat, "PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTradingEvent")
.withArgs(baseToken.address, wbnb.address, ethers.utils.parseEther("0.5"), ethers.utils.parseEther("0.1"));
const workerWbnbAfter = await wbnb.balanceOf(mockPancakeswapV2WorkerBaseBNBTokenPair.address);
const aliceBnbAfter = await alice.getBalance();
const deployerBtokenAfter = await baseToken.balanceOf(deployerAddress);
expect(aliceBnbAfter.sub(aliceBnbBefore), "Alice should get 0.388610414926204399 BNB back").to.be.eq(
ethers.utils.parseEther("0.388610414926204399")
);
expect(
deployerBtokenAfter.sub(deployerBtokenBefore),
"Deployer (as Vault) should get 0.1 BTOKEN back"
).to.be.eq(ethers.utils.parseEther("0.1"));
expect(workerWbnbAfter, "Worker should get 0.5 WBNB back").to.be.eq(ethers.utils.parseEther("0.5"));
});
});
context("when FTOKEN from swap < slippage", async () => {
it("should revert", async () => {
// if 1 BNB = 1 BaseToken
// x BNB = (x * 0.9975) * (1 / (1 + x * 0.9975)) = 0.1
// x = ~ 0.11138958507379568
// thus, the return farming token will be 0.888610414926204399
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
await expect(
mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
["0", "0", ethers.utils.parseEther("0.888610414926204399").add(1)]
),
]
)
)
).to.be.revertedWith(
"PancakeswapV2RestrictedSingleAssetStrategyPartialCloseMinimizeTrading::execute:: insufficient farmingToken amount received"
);
});
});
context("when debt > 0", async () => {
it("should convert to WBNB to be enough for repaying the debt, and return farmingToken to the user", async () => {
// mock farming token (WBNB)
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress);
const aliceNativeFarmingTokenBefore = await ethers.provider.getBalance(aliceAddress);
await mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0.1"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.4"), ethers.utils.parseEther("0.1"), "0"]
),
]
),
{
gasPrice: 0,
}
);
// if 1 BNB = 1 BaseToken
// x BNB = (x * 0.9975 * 1) / (1 + x * 0.9975) = 0.1 baseToken
// x = ~ 0.11138958507379568 BNB
// thus, alice will receive 0.4 - 0.11138958507379568 = 0.288610414926204399 BNB as a return farming token and 0.1 BaseToken for repaying the debt
const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress);
const aliceNativeFarmingTokenAfter = await ethers.provider.getBalance(aliceAddress);
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0.1"));
expect(aliceNativeFarmingTokenAfter.sub(aliceNativeFarmingTokenBefore)).to.eq(
ethers.utils.parseEther("0.288610414926204399")
);
expect(await wbnb.balanceOf(mockPancakeswapV2WorkerBaseBNBTokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.6")
);
expect(await wbnb.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
});
});
context("when debt = 0", async () => {
it("should return all farmingToken to the user", async () => {
// mock farming token (WBNB)
await wbnbTokenAsAlice.transfer(mockPancakeswapV2WorkerBaseBNBTokenPair.address, ethers.utils.parseEther("1"));
const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress);
const aliceNativeFarmingTokenBefore = await ethers.provider.getBalance(aliceAddress);
await mockPancakeswapV2WorkerBaseBNBTokenPairAsAlice.work(
0,
aliceAddress,
ethers.utils.parseEther("0"),
ethers.utils.defaultAbiCoder.encode(
["address", "bytes"],
[
strat.address,
ethers.utils.defaultAbiCoder.encode(
["uint256", "uint256", "uint256"],
[ethers.utils.parseEther("0.1"), ethers.utils.parseEther("0"), ethers.utils.parseEther("0")]
),
]
),
{
gasPrice: 0,
}
);
const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress);
const aliceNativeFarmingTokenAfter = await ethers.provider.getBalance(aliceAddress);
// Alice will have partial farming token of 0.1 BNB (as a native farming token) back since she got no debt
expect(aliceBaseTokenAfter.sub(aliceBaseTokenBefore)).to.eq(ethers.utils.parseEther("0"));
expect(aliceNativeFarmingTokenAfter.sub(aliceNativeFarmingTokenBefore)).to.eq(ethers.utils.parseEther("0.1"));
// wbnb, BToken in a strategy contract MUST be 0
expect(await wbnb.balanceOf(mockPancakeswapV2WorkerBaseBNBTokenPair.address)).to.be.eq(
ethers.utils.parseEther("0.9")
);
expect(await wbnb.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
expect(await baseToken.balanceOf(strat.address)).to.be.eq(ethers.utils.parseEther("0"));
});
});
});
}); | the_stack |
import {Component, OnInit, ViewChild, ViewEncapsulation, ChangeDetectorRef, Inject, OnDestroy} from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FormControl } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import {debounceTime, filter, take, takeUntil} from 'rxjs/operators';
import { InstallLibrariesModel } from './install-libraries.model';
import { LibrariesInstallationService } from '../../../core/services';
import {SortUtils, HTTP_STATUS_CODES, PATTERNS} from '../../../core/util';
import {FilterLibsModel} from './filter-libs.model';
import {Subject, timer} from 'rxjs';
import {CompareUtils} from '../../../core/util/compareUtils';
interface Library {
name: string;
version: string;
}
interface GetLibrary {
autoComplete: string;
libraries: Library[];
}
@Component({
selector: 'install-libraries',
templateUrl: './install-libraries.component.html',
styleUrls: ['./libraries-info.component.scss', './install-libraries.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class InstallLibrariesComponent implements OnInit, OnDestroy {
private readonly CHECK_GROUPS_TIMEOUT: number = 5000;
private readonly INSTALLATION_IN_PROGRESS_CHECK: number = 10000;
private unsubscribe$ = new Subject();
public model: InstallLibrariesModel;
public notebook: any;
public filteredList: any = [];
public groupsList: Array<string>;
public notebookLibs: Array<any> = [];
public loadLibsTimer: any;
public group: string;
public destination: any;
public uploading: boolean = false;
public libs_uploaded: boolean = false;
public validity_format: string = '';
public isInstalled: boolean = false;
public isInSelectedList: boolean = false;
public installingInProgress: boolean = false;
public libSearch: FormControl = new FormControl();
public groupsListMap = {
'r_pkg': 'R packages',
'pip3': 'Python 3',
'os_pkg': 'Apt/Yum',
'others': 'Others',
'java': 'Java'
};
public filterConfiguration: FilterLibsModel = new FilterLibsModel('', [], [], [], []);
public filterModel: FilterLibsModel = new FilterLibsModel('', [], [], [], []);
public filtered: boolean;
public autoComplete: string;
public filtredNotebookLibs: Array<any> = [];
public lib: Library = {name: '', version: ''};
public selectedLib: any = null;
public isLibSelected: boolean = false;
public isVersionInvalid: boolean = false;
public isFilterChanged: boolean;
public isFilterSelected: boolean;
private cashedFilterForm: FilterLibsModel;
@ViewChild('groupSelect') group_select;
@ViewChild('resourceSelect') resource_select;
@ViewChild('trigger') matAutoComplete;
constructor(
@Inject(MAT_DIALOG_DATA) public data: any,
public toastr: ToastrService,
public dialog: MatDialog,
public dialogRef: MatDialogRef<InstallLibrariesComponent>,
private librariesInstallationService: LibrariesInstallationService,
private changeDetector: ChangeDetectorRef
) {
this.model = InstallLibrariesModel.getDefault(librariesInstallationService);
}
ngOnInit() {
this.open(this.data);
this.libSearch.valueChanges
.pipe(
debounceTime(1000),
takeUntil(this.unsubscribe$)
)
.subscribe(value => {
if(!!value?.match(/\s+/g)) {
this.libSearch.setValue(value.replace(/\s+/g, ''))
this.lib.name = value.replace(/\s+/g, '');
} else {
this.lib.name = value;
}
this.isDuplicated(this.lib);
this.filterList();
});
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
uploadLibGroups(): void {
this.libs_uploaded = false;
this.uploading = true;
this.librariesInstallationService.getGroupsList(this.notebook.project, this.notebook.name, this.model.computational_name)
.pipe(
takeUntil(this.unsubscribe$),
)
.subscribe(
response => {
const groups = [].concat(response);
// Remove when will be removed pip2 from Backend
const groupWithoutPip2 = groups.filter(group => group !== 'pip2');
this.libsUploadingStatus(groupWithoutPip2);
this.changeDetector.detectChanges();
this.resource_select && this.resource_select.setDefaultOptions(
this.getResourcesList(),
this.destination.title, 'destination', 'title', 'array');
this.group_select && this.group_select.setDefaultOptions(
this.groupsList, 'Select group', 'group_lib', null, 'list', this.groupsListMap);
},
error => this.toastr.error(error.message || 'Groups list loading failed!', 'Oops!'));
}
private getResourcesList() {
this.notebook.type = 'EXPLORATORY';
this.notebook.title = `${this.notebook.name} <em class="capt">notebook</em>`;
return [this.notebook].concat(this.notebook.resources
.filter(item => item.status === 'running')
.map(item => {
item['name'] = item.computational_name;
item['title'] = `${item.computational_name} <em class="capt">compute</em>`;
item['type'] = 'СOMPUTATIONAL';
return item;
}));
}
public filterList(): void {
this.validity_format = '';
(this.lib.name && this.lib.name.length >= 2 && this.group ) ? this.getFilteredList() : this.filteredList = null;
}
public filterGroups(groupsList): Array<string> {
const CURRENT_TEMPLATE = this.notebook.template_name.toLowerCase();
if (CURRENT_TEMPLATE.indexOf('jupyter with tensorflow') !== -1 || CURRENT_TEMPLATE.indexOf('deep learning') !== -1) {
const filtered = groupsList.filter(group => group !== 'r_pkg');
return SortUtils.libGroupsSort(filtered);
}
const PREVENT_TEMPLATES = ['rstudio', 'rstudio with tensorflow'];
const templateCheck = PREVENT_TEMPLATES.some(template => CURRENT_TEMPLATE.indexOf(template) !== -1);
const filteredGroups = templateCheck ? groupsList.filter(group => group !== 'java') : groupsList;
return SortUtils.libGroupsSort(filteredGroups);
}
public onUpdate($event): void {
if ($event.model.type === 'group_lib') {
this.group = $event.model.value;
this.autoComplete = '';
this.isLibSelected = false;
if (this.group) {
this.libSearch.enable();
}
this.lib = {name: '', version: ''};
this.isVersionInvalid = false;
this.libSearch.setValue('');
} else if ($event.model.type === 'destination') {
this.isLibSelected = false;
this.destination = $event.model.value;
this.destination && this.destination.type === 'СOMPUTATIONAL'
? this.model.computational_name = this.destination.name
: this.model.computational_name = null;
this.resetDialog();
this.libSearch.disable();
}
this.filterList();
}
public onFilterUpdate($event): void {
this.filterModel[$event.type] = $event.model;
this.checkFilters();
}
private checkFilters() : void{
this.isFilterChanged = CompareUtils.compareFilters(this.filterModel, this.cashedFilterForm);
this.isFilterSelected = Object.keys(this.filterModel).some(v => this.filterModel[v].length > 0);
}
public isDuplicated(item): void {
if (this.filteredList && this.filteredList.length) {
if (this.group !== 'java') {
this.selectedLib = this.filteredList.find(lib => lib.name.toLowerCase() === item.name.toLowerCase());
} else {
this.selectedLib = this.filteredList.find(lib => {
return lib.name.toLowerCase() === item.name.substring(0, item.name.lastIndexOf(':')).toLowerCase();
});
}
} else if ( this.autoComplete === 'NONE' || (this.autoComplete === 'ENABLED' && !this.filteredList?.length && this.group !== 'java')) {
this.selectedLib = {
name: this.lib.name,
version: this.lib.version,
isInSelectedList: this.model.selectedLibs.some(el => el.name.toLowerCase() === this.lib.name.toLowerCase().trim())
};
} else {
this.selectedLib = null;
}
}
public addLibrary(item): void {
if ((this.autoComplete === 'ENABLED' && !this.isLibSelected && this.filteredList?.length)
|| this.lib.name.trim().length < 2
|| (this.selectedLib && this.selectedLib.isInSelectedList) || this.isVersionInvalid || this.autoComplete === 'UPDATING') {
return;
}
this.validity_format = '';
this.isLibSelected = false;
if ( (!this.selectedLib && !this.isVersionInvalid) || (!this.selectedLib.isInSelectedList && !this.isVersionInvalid)) {
if ( this.group !== 'java') {
this.model.selectedLibs.push({ group: this.group, name: item.name.trim(), version: item.version.trim() || 'N/A' });
} else {
this.model.selectedLibs.push({
group: this.group,
name: item.name.substring(0, item.name.lastIndexOf(':')),
version: item.name.substring(item.name.lastIndexOf(':') + 1).trim() || 'N/A'
});
}
this.libSearch.setValue('');
this.lib = {name: '', version: ''};
this.filteredList = null;
}
}
public selectLibrary(item): void {
if (item.isInSelectedList) {
return;
}
if (this.group === 'java') {
this.isLibSelected = true;
this.libSearch.setValue(item.name + ':' + item.version);
this.lib.name = item.name + ':' + item.version;
} else {
this.isLibSelected = true;
this.libSearch.setValue(item.name);
this.lib.name = item.name;
}
this.matAutoComplete.closePanel();
}
public removeSelectedLibrary(item): void {
this.model.selectedLibs.splice(this.model.selectedLibs.indexOf(item), 1);
this.getMatchedLibs();
}
public open(notebook): void {
this.notebook = notebook;
this.destination = this.getResourcesList()[0];
this.model = new InstallLibrariesModel(notebook,
response => {
if (response.status === HTTP_STATUS_CODES.OK) {
this.getInstalledLibrariesList();
this.resetDialog();
}
},
error => this.toastr.error(error.message || 'Library installation error!', 'Oops!'),
() => {
this.getInstalledLibrariesList(true);
this.changeDetector.detectChanges();
this.selectorsReset();
},
this.librariesInstallationService);
}
public showErrorMessage(item): void {
const dialogRef: MatDialogRef<ErrorLibMessageDialogComponent> = this.dialog.open(
ErrorLibMessageDialogComponent, { data: item.error, width: '550px', panelClass: 'error-modalbox' });
}
public isInstallingInProgress(): void {
this.installingInProgress = this.notebookLibs.some(lib => lib.filteredStatus.some(status => status.status === 'installing'));
if (this.installingInProgress) {
timer(this.INSTALLATION_IN_PROGRESS_CHECK)
.pipe(
take(1),
takeUntil(this.unsubscribe$)
)
.subscribe(v => this.getInstalledLibrariesList());
}
}
public reinstallLibrary(item, lib): void {
const retry = [{ group: lib.group, name: lib.name, version: lib.version }];
if (this.getResourcesList().find(el => el.name === item.resource).type === 'СOMPUTATIONAL') {
this.model.confirmAction(retry, item.resource);
} else {
this.model.confirmAction(retry);
}
}
private getInstalledLibrariesList(init?: boolean): void {
this.model.getInstalledLibrariesList(this.notebook)
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((data: any) => {
if ( !this.filtredNotebookLibs.length || data.length !== this.notebookLibs.length) {
this.filtredNotebookLibs = [...data];
}
this.filtredNotebookLibs = data.filter(lib =>
this.filtredNotebookLibs.some(v =>
(v.name + v.version === lib.name + v.version) && v.resource === lib.resource));
this.notebookLibs = data ? data : [];
this.notebookLibs.forEach(lib => {
lib.filteredStatus = lib.status;
if (lib.version && lib.version !== 'N/A')
lib.version = 'v.' + lib.version;
}
);
this.filterLibs();
this.changeDetector.markForCheck();
this.filterConfiguration.group = this.createFilterList(this.notebookLibs.map(v => this.groupsListMap[v.group]));
this.filterConfiguration.group = SortUtils.libFilterGroupsSort(this.filterConfiguration.group);
this.filterConfiguration.resource = this.createFilterList(this.notebookLibs.map(lib => lib.status.map(status => status.resource)));
this.filterConfiguration.resource_type = this.createFilterList(this.notebookLibs.map(lib =>
lib.status.map(status => status.resourceType)));
this.filterConfiguration.status = this.createFilterList(this.notebookLibs.map(lib => lib.status.map(status => status.status)));
this.isInstallingInProgress();
});
}
public createFilterList(array): [] {
return array.flat().filter((v, i, arr) => arr.indexOf(v) === i);
}
private getInstalledLibsByResource(): void {
this.librariesInstallationService.getInstalledLibsByResource(this.notebook.project, this.notebook.name, this.model.computational_name)
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((data: any) => this.destination.libs = data);
}
private libsUploadingStatus(groupsList): void {
if (groupsList.length) {
this.groupsList = this.filterGroups(groupsList);
this.libs_uploaded = true;
this.uploading = false;
} else {
this.libs_uploaded = false;
this.uploading = true;
timer(this.CHECK_GROUPS_TIMEOUT).pipe(
take(1),
takeUntil(this.unsubscribe$)
).subscribe(() => this.uploadLibGroups());
}
}
private getFilteredList(): void {
this.validity_format = '';
if (this.lib.name.length > 1) {
if (this.group === 'java') {
this.model.getDependencies(this.lib.name)
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe(
libs => {
this.filteredList = [libs];
this.filteredList.forEach(lib => {
lib.isInSelectedList = this.model.selectedLibs
.some(el => {
return lib.name.toLowerCase() === el.name.toLowerCase();
});
lib.isInstalled = this.notebookLibs.some(libr => {
return lib.name.toLowerCase() === libr.name.toLowerCase() &&
this.group === libr.group &&
libr.status.some(res => res.resource === this.destination.name);
}
);
});
this.isDuplicated(this.lib);
},
error => {
if (error.status === HTTP_STATUS_CODES.NOT_FOUND
|| error.status === HTTP_STATUS_CODES.BAD_REQUEST
|| error.status === HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR) {
this.validity_format = error.message || '';
if (error.message.indexOf('query param artifact') !== -1 || error.message.indexOf('Illegal character') !== -1) {
this.validity_format = 'Wrong library name format. Should be <groupId>:<artifactId>:<versionId>.';
}
if (error.message.indexOf('not found') !== -1) {
this.validity_format = 'No matches found.';
}
this.filteredList = null;
}
});
} else {
if (this.lib.name && this.lib.name.length > 1) {
this.getMatchedLibs();
}
}
}
}
private getMatchedLibs() {
if (!this.lib.name || this.lib.name.trim().length < 2) {
return;
}
this.model.getLibrariesList(this.group, this.lib.name.trim().toLowerCase())
.pipe(
takeUntil(this.unsubscribe$)
)
.subscribe((libs: GetLibrary) => {
if (libs.autoComplete === 'UPDATING') {
timer(5000).pipe(
take(1),
takeUntil(this.unsubscribe$)
).subscribe(_ => {
this.getMatchedLibs();
});
}
this.autoComplete = libs.autoComplete;
this.filteredList = libs.libraries;
this.filteredList.forEach(lib => {
lib.isInSelectedList = this.model.selectedLibs.some(el => el.name.toLowerCase() === lib.name.toLowerCase());
lib.isInstalled = this.notebookLibs.some(libr => lib.name === libr.name &&
this.group === libr.group &&
libr.status.some(res => res.resource === this.destination.name));
});
this.isDuplicated(this.lib);
});
}
private selectorsReset(leaveDestanation?): void {
if (!leaveDestanation) this.destination = this.getResourcesList()[0];
this.uploadLibGroups();
this.getInstalledLibsByResource();
this.libSearch.disable();
}
private resetDialog(): void {
this.group = '';
this.lib.name = '';
this.libSearch.setValue('');
this.isInstalled = false;
this.isInSelectedList = false;
this.uploading = false;
this.model.selectedLibs = [];
this.filteredList = [];
this.groupsList = [];
this.selectorsReset(true);
}
public toggleFilterRow(): void {
this.filtered = !this.filtered;
}
public filterLibs(updCachedForm?): void {
if (!this.cashedFilterForm || updCachedForm) {
this.cashedFilterForm = JSON.parse(JSON.stringify(this.filterModel));
Object.setPrototypeOf(this.cashedFilterForm, Object.getPrototypeOf(this.filterModel));
}
this.filtredNotebookLibs = this.notebookLibs.filter((lib) => {
const isName = this.cashedFilterForm.name ?
lib.name.toLowerCase().indexOf(this.cashedFilterForm.name.toLowerCase().trim()) !== -1
|| lib.version.indexOf(this.cashedFilterForm.name.toLowerCase().trim()) !== -1 : true;
const isGroup = this.cashedFilterForm.group.length ? this.cashedFilterForm.group.includes(this.groupsListMap[lib.group]) : true;
lib.filteredStatus = lib.status.filter(status => {
const isResource = this.cashedFilterForm.resource.length ? this.cashedFilterForm.resource.includes(status.resource) : true;
const isResourceType = this.cashedFilterForm.resource_type.length ?
this.cashedFilterForm.resource_type.includes(status.resourceType) : true;
const isStatus = this.cashedFilterForm.status.length ? this.cashedFilterForm.status.includes(status.status) : true;
return isResource && isResourceType && isStatus;
});
this.checkFilters();
return isName && isGroup && lib.filteredStatus.length;
});
}
public resetFilterConfigurations(): void {
this.notebookLibs.forEach(v => v.filteredStatus = v.status);
this.filterModel.resetFilterLibs();
this.filterLibs(true);
}
public openLibInfo(lib, type) {
this.dialog.open(
LibInfoDialogComponent, { data: {lib, type}, width: '550px', panelClass: 'error-modalbox' });
}
public emitClick() {
this.matAutoComplete.closePanel();
}
public clearLibSelection(event) {
this.isLibSelected = false;
}
public validateVersion(version) {
if (version.length) {
this.isVersionInvalid = !PATTERNS.libVersion.test(version);
} else {
this.isVersionInvalid = false;
}
}
public onFilterNameUpdate(targetElement: any) {
this.filterModel.name = targetElement;
this.checkFilters();
}
}
@Component({
selector: 'error-message-dialog',
template: `
<div class="dialog-header">
<h4 class="modal-title">Library installation error</h4>
<button type="button" class="close" (click)="dialogRef.close()">×</button>
</div>
<div class="content lib-error scrolling" >
{{ data }}
</div>
`,
styles: [ `
.lib-error { max-height: 200px; overflow-x: auto; word-break: break-all; padding: 20px 30px !important; margin: 20px 0 !important;}
`
]
})
export class ErrorLibMessageDialogComponent {
constructor(
public dialogRef: MatDialogRef<ErrorLibMessageDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
}
}
@Component({
selector: 'lib-info-dialog',
template: `
<div class="dialog-header">
<h4 class="modal-title" *ngIf="data.type === 'added'">Installed dependency</h4>
<h4 class="modal-title" *ngIf="data.type === 'available'">Version is not available</h4>
<button type="button" class="close" (click)="dialogRef.close()">×</button>
</div>
<div class="lib-list scrolling" *ngIf="data.type === 'added'">
<span class="strong dependency-title">Dependency: </span><span class="packeges" *ngFor="let pack of data.lib.add_pkgs; index as i">{{pack + (i !== data.lib.add_pkgs.length - 1 ? ', ' : '')}}</span>
</div>
<div class="lib-list" *ngIf="data.type === 'available'">
<span class="strong">Available versions: </span>{{data.lib.available_versions.join(', ')}}
</div>
`,
styles: [ `
.lib-list { max-height: 200px; overflow-x: auto; word-break: break-all; padding: 20px 30px !important; margin: 20px 0; color: #577289;}
.packeges { word-spacing: 5px; line-height: 23px;}
.dependency-title{ line-height: 23px; }
`
]
})
export class LibInfoDialogComponent {
constructor(
public dialogRef: MatDialogRef<ErrorLibMessageDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
}
} | the_stack |
import {
App,
FileView,
ItemView,
MarkdownRenderer,
MarkdownView,
TAbstractFile,
TFile,
TFolder,
Vault,
WorkspaceLeaf
} from 'obsidian';
import { Elm, ElmApp, Flags } from '../src/Main';
import CardBoardPlugin from './main';
import { getDateFromFile, IPeriodicNoteSettings } from 'obsidian-daily-notes-interface';
export const VIEW_TYPE_CARD_BOARD = "card-board-view";
export class CardBoardView extends ItemView {
private vault: Vault;
private plugin: CardBoardPlugin;
private elm: ElmApp;
constructor(
plugin: CardBoardPlugin,
leaf: WorkspaceLeaf
) {
super(leaf);
this.plugin = plugin;
this.app = plugin.app;
this.vault = plugin.app.vault;
}
getViewType(): string {
return VIEW_TYPE_CARD_BOARD;
}
getDisplayText(): string {
return 'CardBoard';
}
async onOpen() {
this.icon = "card-board"
const mySettings:Flags = {
now: Date.now(),
zone: new Date().getTimezoneOffset(),
settings: this.plugin.settings
};
const elmDiv = document.createElement('div');
elmDiv.id = "elm-node";
this.containerEl.children[1].appendChild(elmDiv);
this.elm = Elm.Main.init({
node: elmDiv,
flags: mySettings
})
// TODO: I know I shouldn't need to do this, but my js foo
// failed me at the time!
const that = this;
// messages from elm code. This is the only route
// that elm has to the obsidian API, so this is the
// entry point for anything side-effecty
this.elm.ports.interopFromElm.subscribe((fromElm) => {
switch (fromElm.tag) {
case "addFilePreviewHovers":
that.handleAddFilePreviewHovers(fromElm.data);
break;
case "closeView":
that.handleCloseView();
break;
case "deleteTask":
that.handleDeleteTask(fromElm.data);
break;
case "displayTaskMarkdown":
that.handleDisplayTaskMarkdown(fromElm.data);
break;
case "elmInitialized":
that.handleElmInitialized();
break;
case "openTaskSourceFile":
that.handleOpenTaskSourceFile(fromElm.data);
break;
case "requestFilterCandidates":
that.handleRequestFilterCandidates();
break;
case "updateSettings":
that.handleUpdateSettings(fromElm.data);
break;
case "updateTasks":
that.handleUpdateTasks(fromElm.data);
break;
}
});
this.registerEvent(this.app.workspace.on("active-leaf-change",
(leaf) => this.handleActiveLeafChange(leaf)));
this.registerEvent(this.app.vault.on("create",
(file) => this.handleFileCreated(file)));
this.registerEvent(this.app.vault.on("delete",
(file) => this.handleFileDeleted(file)));
this.registerEvent(this.app.vault.on("modify",
(file) => this.handleFileModified(file)));
this.registerEvent(this.app.vault.on("rename",
(file, oldPath) => this.handleFileRenamed(file, oldPath)));
}
async onClose() {
await this.elm.ports.interopToElm.send({
tag: "activeStateUpdated",
data: false
});
}
currentBoardIndex(index: number) {
this.elm.ports.interopToElm.send({
tag: "showBoard",
data: index
});
}
// MESSAGES FROM ELM
async handleAddFilePreviewHovers(
data: {
filePath: string,
id : string
}[]
) {
const that = this;
requestAnimationFrame(function () {
for (const card of data) {
const element = document.getElementById(card.id);
if (element instanceof HTMLElement) {
element.addEventListener('mouseover', (event: MouseEvent) => {
that.app.workspace.trigger('hover-link', {
event,
source: "card-board",
hoverParent: element,
targetEl: element,
linktext: card.filePath,
sourcePath: card.filePath
});
});
}
}
})
}
async handleCloseView() {
this.plugin.deactivateView();
}
async handleDeleteTask(
data: {
filePath: string,
lineNumber: number,
originalText: string}
) {
const file = this.app.vault.getAbstractFileByPath(data.filePath)
if (file instanceof TFile) {
const markdown = await this.vault.read(file)
const markdownLines = markdown.split(/\r?\n/)
if (markdownLines[data.lineNumber - 1].includes(data.originalText)) {
markdownLines[data.lineNumber - 1] = markdownLines[data.lineNumber - 1].replace(/^(.*)$/, "<del>$1</del>")
this.vault.modify(file, markdownLines.join("\n"))
}
}
}
async handleDisplayTaskMarkdown(
data: {
filePath: string,
taskMarkdown: {
id: string,
markdown: string
}[]
}[]
) {
const that = this;
requestAnimationFrame(function () {
for (const card of data) {
for (const item of card.taskMarkdown) {
const element = document.getElementById(item.id);
if (element instanceof HTMLElement) {
element.innerHTML = "";
MarkdownRenderer.renderMarkdown(item.markdown, element, card.filePath, this);
const internalLinks = Array.from(element.getElementsByClassName("internal-link"));
for (const internalLink of internalLinks) {
if (internalLink instanceof HTMLElement) {
internalLink.addEventListener('mouseover', (event: MouseEvent) => {
that.app.workspace.trigger('hover-link', {
event,
source: "card-board",
hoverParent: element,
targetEl: internalLink,
linktext: internalLink.getAttribute("href"),
sourcePath: card.filePath
});
});
internalLink.addEventListener("click", (event: MouseEvent) => {
event.preventDefault();
that.app.workspace.openLinkText(internalLink.getAttribute("href"), card.filePath, true, {
active: !0
});
});
}
}
}
}
}
})
}
async handleElmInitialized() {
const markdownFiles = this.vault.getMarkdownFiles();
for (const file of markdownFiles) {
const fileDate = this.formattedFileDate(file);
const fileContents = await this.vault.cachedRead(file);
this.elm.ports.interopToElm.send({
tag: "fileAdded",
data: {
filePath: file.path,
fileDate: fileDate,
fileContents: fileContents
}
});
}
this.elm.ports.interopToElm.send({
tag: "allMarkdownLoaded",
data: { }
});
}
async handleOpenTaskSourceFile(
data: {
filePath: string,
lineNumber: number,
originalText: string
}
) {
await this.openOrSwitchWithHighlight(this.app, data.filePath, data.lineNumber);
}
async handleRequestFilterCandidates() {
const loadedFiles = this.app.vault.getAllLoadedFiles();
const filterCandidates: { tag : "pathFilter" | "fileFilter" | "tagFilter", data : string }[] = [];
// @ts-ignore
const tagsWithCounts = this.app.metadataCache.getTags();
const tags = Object.keys(tagsWithCounts).map(x => x.slice(1));
loadedFiles.forEach((folder: TAbstractFile) => {
if (folder instanceof TFolder) {
filterCandidates.push({ tag : "pathFilter", data : folder.path});
}
});
loadedFiles.forEach((file: TAbstractFile) => {
if (file instanceof TFile && file.extension === "md") {
filterCandidates.push({ tag : "fileFilter", data : file.path});
}
});
tags.forEach((tag: string) => {
filterCandidates.push({ tag : "tagFilter", data : tag});
filterCandidates.push({ tag : "tagFilter", data : tag + "/"});
});
this.elm.ports.interopToElm.send({
tag: "filterCandidates",
data: filterCandidates
});
}
async handleUpdateSettings(
data: {
data : {
boardConfigs : (
{ data : {
columns : { displayTitle : string; tag : string }[];
completedCount : number;
filters : ({ data : string; tag : "tagFilter" } | { data : string; tag : "pathFilter" } | { data : string; tag : "fileFilter" })[];
includeOthers : boolean;
includeUntagged : boolean;
title : string
};
tag : "tagBoardConfig" }
| { data : {
completedCount : number;
filters : ({ data : string; tag : "tagFilter" } | { data : string; tag : "pathFilter" } | { data : string; tag : "fileFilter" })[];
includeUndated : boolean;
title : string
};
tag : "dateBoardConfig"
}
)[];
globalSettings : {
hideCompletedSubtasks : boolean;
ignorePaths : ({ data : string; tag : "tagFilter" } | { data : string; tag : "pathFilter" } | { data : string; tag : "fileFilter" })[];
subTaskDisplayLimit : number | null
}
};
version : string
}) {
await this.plugin.saveSettings(data);
this.elm.ports.interopToElm.send({
tag: "settingsUpdated",
data: data
});
}
async handleUpdateTasks(
data: {
filePath: string,
tasks: { lineNumber: number, originalText: string, newText: string }[]
}) {
const file = this.app.vault.getAbstractFileByPath(data.filePath)
if (file instanceof TFile) {
const markdown = await this.vault.read(file)
const markdownLines = markdown.split(/\r?\n/)
for (const item of data.tasks) {
if (markdownLines[item.lineNumber - 1].includes(item.originalText)) {
markdownLines[item.lineNumber - 1] = item.newText
}
}
this.vault.modify(file, markdownLines.join("\n"))
}
}
// THESE SEND MESSAGES TO THE ELM APPLICATION
async handleActiveLeafChange(
leaf: WorkspaceLeaf | null
) {
let isActive: boolean = false;
if (leaf.view.getViewType() == "card-board-view") {
isActive = true
}
this.elm.ports.interopToElm.send({
tag: "activeStateUpdated",
data: isActive
});
}
async handleFileCreated(
file: TAbstractFile
) {
if (file instanceof TFile) {
const fileDate = this.formattedFileDate(file);
const fileContents = await this.vault.read(file);
this.elm.ports.interopToElm.send({
tag: "fileAdded",
data: {
filePath: file.path,
fileDate: fileDate,
fileContents: fileContents
}
});
}
}
async handleFileDeleted(
file: TAbstractFile
) {
if (file instanceof TFile) {
const fileDate = this.formattedFileDate(file);
this.elm.ports.interopToElm.send({
tag: "fileDeleted",
data: file.path
});
}
}
async handleFileModified(
file: TAbstractFile
) {
if (file instanceof TFile) {
const fileDate = this.formattedFileDate(file);
const fileContents = await this.vault.read(file);
this.elm.ports.interopToElm.send({
tag: "fileUpdated",
data: {
filePath: file.path,
fileDate: fileDate,
fileContents: fileContents
}
});
}
}
async handleFileRenamed(
file: TAbstractFile,
oldPath: string
) {
this.elm.ports.interopToElm.send({
tag: "fileRenamed",
data: {
oldPath: oldPath,
newPath: file.path
}
});
}
// HELPERS
formattedFileDate(
file: TFile
): string | null {
return getDateFromFile(file, "day")?.format('YYYY-MM-DD') || null;
}
async openOrSwitchWithHighlight(
app: App,
filePath: string,
lineNumber: number
): Promise<void> {
const { workspace } = app;
let destFile = app.metadataCache.getFirstLinkpathDest(filePath, "");
if (!destFile) {
return;
}
const leavesWithDestAlreadyOpen: WorkspaceLeaf[] = [];
workspace.iterateAllLeaves((leaf) => {
if (leaf.view instanceof MarkdownView) {
if (leaf.view?.file?.path === filePath) {
leavesWithDestAlreadyOpen.push(leaf);
}
}
});
let leaf: WorkspaceLeaf;
if (leavesWithDestAlreadyOpen.length > 0) {
leaf = leavesWithDestAlreadyOpen[0];
await workspace.setActiveLeaf(leaf);
} else {
leaf = workspace.splitActiveLeaf();
await leaf.openFile(destFile);
}
leaf.setEphemeralState({ line: lineNumber - 1 });
}
} | the_stack |
import test from 'japa'
import { DateTime } from 'luxon'
import { validator as validatorType } from '@ioc:Adonis/Core/Validator'
import { rules } from '../src/Rules'
import { schema } from '../src/Schema'
import { getLiteralType } from '../src/utils'
import * as validations from '../src/Validations'
import { ApiErrorReporter, VanillaErrorReporter } from '../src/ErrorReporter'
import { validator as validatorBase } from '../src/Validator'
const validator = validatorBase as unknown as typeof validatorType
test.group('Validator | validate', () => {
test('validate schema object against runtime data', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, { username: ['required validation failed'] })
}
})
test('collect all errors', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
email: schema.string(),
password: schema.string(),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
username: ['required validation failed'],
email: ['required validation failed'],
password: ['required validation failed'],
})
}
})
test('stop at first error when bail is true', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
email: schema.string(),
password: schema.string(),
}),
data: {},
bail: true,
})
} catch (error) {
assert.deepEqual(error.messages, {
username: ['required validation failed'],
})
}
})
test('use custom messages when defined', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
email: schema.string(),
password: schema.string(),
}),
data: {},
messages: {
required: 'The field is required',
},
bail: true,
})
} catch (error) {
assert.deepEqual(error.messages, {
username: ['The field is required'],
})
}
})
test('use custom error reporter when defined', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
email: schema.string(),
password: schema.string(),
}),
data: {},
messages: { required: 'The field is required' },
bail: true,
reporter: ApiErrorReporter,
})
} catch (error) {
assert.deepEqual(error.messages, {
errors: [
{
rule: 'required',
field: 'username',
message: 'The field is required',
},
],
})
}
})
test('cache schema using the cache key', async () => {
const initialSchema = schema.create({
username: schema.string.optional(),
})
/**
* First validation will be skipped, since we have marked
* the field optional
*/
await validator.validate({
schema: initialSchema,
data: {},
cacheKey: 'foo',
reporter: ApiErrorReporter,
})
const newSchema = schema.create({
username: schema.string(),
})
/**
* This one should have failed, but not, since the same
* cache key is used and hence new schema is not
* compiled
*/
await validator.validate({
schema: newSchema,
data: {},
cacheKey: 'foo',
reporter: ApiErrorReporter,
})
})
})
test.group('Validator | validate object', () => {
test('do not fail when value is undefined and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.optional().members({
username: schema.string(),
}),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('do not fail when value is null and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.optional().members({
username: schema.string(),
}),
}),
data: {
user: null,
},
})
assert.deepEqual(data as any, {})
})
test('fail when value is undefined and nullable', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
user: schema.object.nullable().members({
username: schema.string(),
}),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
user: ['nullable validation failed'],
})
}
})
test('do not fail when value is null and nullable', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullable().members({
username: schema.string(),
}),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is null and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullableAndOptional().members({
username: schema.string(),
}),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is undefined and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullableAndOptional().members({
username: schema.string(),
}),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('ignore object properties when not defined inside the schema', async (assert) => {
const output = await validator.validate({
schema: schema.create({
profile: schema.object().members({}),
}),
data: {
profile: {
username: 'virk',
age: 30,
},
},
})
assert.deepEqual(output, { profile: {} })
})
})
test.group('Validator | validate object | anyMembers', () => {
test('do not fail when value is undefined and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.optional().anyMembers(),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('do not fail when value is null and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.optional().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data as any, {})
})
test('fail when value is undefined and nullable', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
user: schema.object.nullable().anyMembers(),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
user: ['nullable validation failed'],
})
}
})
test('do not fail when value is null and nullable', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullable().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is null and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullableAndOptional().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is undefined and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.object.nullableAndOptional().anyMembers(),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('return object by reference when anyMembers are allowed', async (assert) => {
assert.plan(1)
const output = await validator.validate({
schema: schema.create({
profile: schema.object().anyMembers(),
}),
data: {
profile: {
username: 'virk',
age: 30,
},
},
})
assert.deepEqual(output, { profile: { username: 'virk', age: 30 } })
})
})
test.group('Validator | validate array', () => {
test('do not fail when value is undefined and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.optional().members(schema.string()),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('do not fail when value is null and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.optional().members(schema.string()),
}),
data: {
user: null,
},
})
assert.deepEqual(data as any, {})
})
test('fail when value is undefined and nullable', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
user: schema.array.nullable().members(schema.string()),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
user: ['nullable validation failed'],
})
}
})
test('do not fail when value is null and nullable', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullable().members(schema.string()),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is null and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullableAndOptional().members(schema.string()),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is undefined and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullableAndOptional().members(schema.string()),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
})
test.group('Validator | validate array | anyMembers', () => {
test('do not fail when value is undefined and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.optional().anyMembers(),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('do not fail when value is null and optional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.optional().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data as any, {})
})
test('fail when value is undefined and nullable', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
user: schema.array.nullable().anyMembers(),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
user: ['nullable validation failed'],
})
}
})
test('do not fail when value is null and nullable', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullable().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is null and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullableAndOptional().anyMembers(),
}),
data: {
user: null,
},
})
assert.deepEqual(data, { user: null })
})
test('do not fail when value is undefined and nullableAndOptional', async (assert) => {
const data = await validator.validate({
schema: schema.create({
user: schema.array.nullableAndOptional().anyMembers(),
}),
data: {},
})
assert.deepEqual(data as any, {})
})
test('pass array by reference', async (assert) => {
assert.plan(1)
const output = await validator.validate({
schema: schema.create({
profiles: schema.array().anyMembers(),
}),
data: {
profiles: [
{
username: 'virk',
age: 30,
},
],
},
})
assert.deepEqual(output, { profiles: [{ username: 'virk', age: 30 }] })
})
})
test.group('Validator | rule', () => {
test('add a custom rule', (assert) => {
validator.rule('isPhone', () => {})
assert.property(validations, 'isPhone')
assert.property(rules, 'isPhone')
assert.deepEqual(rules['isPhone'](), { name: 'isPhone', options: [] })
assert.deepEqual(rules['isPhone']('sample'), { name: 'isPhone', options: ['sample'] })
assert.deepEqual(validations['isPhone'].compile('literal', 'string', []), {
async: false,
allowUndefineds: false,
name: 'isPhone',
compiledOptions: [],
})
})
test('rule recieves correct arguments', async (assert) => {
assert.plan(14)
const name = 'testArguments'
const refs = schema.refs({
username: 'ruby',
})
const options = [
{
operator: '=',
},
]
const data = {
users: ['virk'],
}
validator.rule(
name,
(value, compiledOptions, runtimeOptions) => {
assert.equal(value, 'virk')
assert.deepEqual(compiledOptions, options)
assert.hasAllKeys(runtimeOptions, [
'root',
'tip',
'field',
'pointer',
'arrayExpressionPointer',
'refs',
'errorReporter',
'mutate',
])
assert.deepEqual(runtimeOptions.root, data)
assert.deepEqual(runtimeOptions.tip, ['virk'])
assert.equal(runtimeOptions.field, '0')
assert.equal(runtimeOptions.pointer, 'users.0')
assert.equal(runtimeOptions.arrayExpressionPointer, 'users.*')
assert.deepEqual(runtimeOptions.refs, refs)
assert.instanceOf(runtimeOptions.errorReporter, ApiErrorReporter)
assert.isFunction(runtimeOptions.mutate)
},
(opts, type, subtype) => {
assert.deepEqual(opts, options)
assert.equal(type, 'literal')
assert.equal(subtype, 'string')
return {}
}
)
await validator.validate({
refs,
schema: schema.create({
users: schema.array().members(schema.string({}, [{ name, options }])),
}),
data,
reporter: ApiErrorReporter,
})
})
test('set allowUndefineds to true', (assert) => {
validator.rule(
'isPhone',
() => {},
() => {
return {
allowUndefineds: true,
}
}
)
assert.property(validations, 'isPhone')
assert.property(rules, 'isPhone')
assert.deepEqual(rules['isPhone'](), { name: 'isPhone', options: [] })
assert.deepEqual(rules['isPhone']('sample'), { name: 'isPhone', options: ['sample'] })
assert.deepEqual(validations['isPhone'].compile('literal', 'string', []), {
async: false,
allowUndefineds: true,
name: 'isPhone',
compiledOptions: [],
})
})
test('return custom options', (assert) => {
validator.rule(
'isPhone',
() => {},
(options) => {
assert.isArray(options)
return {
compiledOptions: { foo: 'bar' },
}
}
)
assert.property(validations, 'isPhone')
assert.property(rules, 'isPhone')
assert.deepEqual(rules['isPhone'](), { name: 'isPhone', options: [] })
assert.deepEqual(rules['isPhone']('sample'), { name: 'isPhone', options: ['sample'] })
assert.deepEqual(validations['isPhone'].compile('literal', 'string', []), {
async: false,
allowUndefineds: false,
name: 'isPhone',
compiledOptions: { foo: 'bar' },
})
})
})
test.group('Validator | addType', () => {
test('add a custom type', (assert) => {
function unicorn() {
return getLiteralType('unicorn', false, false, {}, [])
}
validator.addRule('unicorn', {
compile() {
return {
async: false,
allowUndefineds: false,
name: 'unicorn',
compiledOptions: undefined,
}
},
validate() {},
})
validator.addType('unicorn', unicorn)
assert.property(schema, 'file')
const parsed = schema.create({
avatar: schema['unicorn'](),
})
assert.deepEqual(parsed.tree, {
avatar: {
type: 'literal' as const,
subtype: 'unicorn',
nullable: false,
optional: false,
rules: [
{
name: 'required',
async: false,
allowUndefineds: true,
compiledOptions: [],
},
{
name: 'unicorn',
async: false,
allowUndefineds: false,
compiledOptions: undefined,
},
],
},
})
})
})
test.group('Validator | validations with non-serialized options', () => {
test('validate against a regex', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string({}, [rules.regex(/[a-z]/)]),
}),
data: {
username: '12',
},
})
} catch (error) {
assert.deepEqual(error.messages, { username: ['regex validation failed'] })
}
})
})
test.group('Min Max Rules', () => {
test('min rule should check against the original value', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
username: schema.string({ escape: true }, [rules.minLength(5)]),
}),
data: {
username: '\\0',
},
})
} catch (error) {
assert.deepEqual(error.messages, { username: ['minLength validation failed'] })
}
})
test('min rule should check against the original nested value', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
profile: schema.object().members({
username: schema.string({ escape: true }, [rules.minLength(5)]),
}),
}),
data: {
profile: {
username: '\\0',
},
},
})
} catch (error) {
assert.deepEqual(error.messages, { 'profile.username': ['minLength validation failed'] })
}
})
})
test.group('After Before Field', () => {
test('fail when value is not after the defined field value', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
after: schema.date({}, [rules.afterField('before')]),
before: schema.date({}),
}),
data: {
before: '2020-10-20',
after: '2020-10-19',
},
})
} catch (error) {
assert.deepEqual(error.messages, { after: ['after date validation failed'] })
}
})
test('pass when value is after the defined field value', async (assert) => {
const { before, after } = await validator.validate({
schema: schema.create({
after: schema.date({}, [rules.afterField('before')]),
before: schema.date({}),
}),
data: {
before: '2020-10-20',
after: '2020-10-22',
},
})
assert.instanceOf(before, DateTime)
assert.instanceOf(after, DateTime)
})
test('handle date formatting', async (assert) => {
const { before, after } = await validator.validate({
schema: schema.create({
after: schema.date({ format: 'LLLL dd yyyy' }, [rules.afterField('before')]),
before: schema.date({ format: 'LLLL dd yyyy' }),
}),
data: {
before: 'October 10 2020',
after: 'October 12 2020',
},
})
assert.instanceOf(before, DateTime)
assert.instanceOf(after, DateTime)
})
test('handle use case when comparison field is not valid separately', async (assert) => {
const { after } = await validator.validate({
schema: schema.create({
after: schema.date({ format: 'LLLL dd yyyy' }, [rules.afterField('before')]),
}),
data: {
before: 'October 10 2020',
after: 'October 12 2020',
},
})
assert.instanceOf(after, DateTime)
})
test('fail when format mis-match', async (assert) => {
assert.plan(1)
try {
await validator.validate({
schema: schema.create({
after: schema.date({ format: 'LLLL dd yyyy' }, [rules.afterField('before')]),
}),
data: {
after: 'October 12 2020',
before: '2020-10-10',
},
})
} catch (error) {
assert.deepEqual(error.messages, { after: ['after date validation failed'] })
}
})
})
test.group('Validator | options', (group) => {
group.afterEach(() => {
/**
* reset config
*/
validator.configure({
bail: false,
existsStrict: false,
reporter: VanillaErrorReporter,
})
})
test('use options reporter when defined', async (assert) => {
assert.plan(1)
validator.configure({ reporter: ApiErrorReporter })
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
}),
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
errors: [
{
message: 'required validation failed',
field: 'username',
rule: 'required',
},
],
})
}
})
test('use inline reporter over config reporter', async (assert) => {
assert.plan(1)
validator.configure({ reporter: ApiErrorReporter })
try {
await validator.validate({
schema: schema.create({
username: schema.string(),
}),
reporter: VanillaErrorReporter,
data: {},
})
} catch (error) {
assert.deepEqual(error.messages, {
username: ['required validation failed'],
})
}
})
}) | the_stack |
import { RequestOptions as HttpRequestOptions } from 'http';
import { RequestOptions as HttpsRequestOptions } from 'https';
import * as url from 'url';
/**
* Represents the interface between ApiClient and a Service Client.
* @export
* @interface ApiClientMessage
*/
export interface ApiClientMessage {
headers : Array<{key : string, value : string}>;
body? : string;
}
/**
* Represents a request sent from Service Clients to an ApiClient implementation.
* @export
* @interface ApiClientRequest
* @extends {ApiClientMessage}
*/
export interface ApiClientRequest extends ApiClientMessage {
url : string;
method : string;
}
/**
* Represents a response returned by ApiClient implementation to a Service Client.
* @export
* @interface ApiClientResponse
* @extends {ApiClientMessage}
*/
export interface ApiClientResponse extends ApiClientMessage {
/**
* Result code of the attempt to satisfy the request. Normally this
* corresponds to the HTTP status code returned by the server.
*/
statusCode : number;
}
/**
* Represents a response with parsed body.
* @export
* @interface ApiResponse
*/
export interface ApiResponse {
headers : Array<{key : string, value : string}>;
body? : any;
statusCode : number;
}
/**
* Represents a basic contract for API request execution
* @export
* @interface ApiClient
*/
export interface ApiClient {
/**
* Dispatches a request to an API endpoint described in the request.
* An ApiClient is expected to resolve the Promise in the case an API returns a non-200 HTTP
* status code. The responsibility of translating a particular response code to an error lies with the
* caller to invoke.
* @param {ApiClientRequest} request request to dispatch to the ApiClient
* @returns {Promise<ApiClientResponse>} Response from the ApiClient
* @memberof ApiClient
*/
invoke(request : ApiClientRequest) : Promise<ApiClientResponse>;
}
/**
* Default implementation of {@link ApiClient} which uses the native HTTP/HTTPS library of Node.JS.
*/
export class DefaultApiClient implements ApiClient {
/**
* Dispatches a request to an API endpoint described in the request.
* An ApiClient is expected to resolve the Promise in the case an API returns a non-200 HTTP
* status code. The responsibility of translating a particular response code to an error lies with the
* caller to invoke.
* @param {ApiClientRequest} request request to dispatch to the ApiClient
* @returns {Promise<ApiClientResponse>} response from the ApiClient
*/
public invoke(request : ApiClientRequest) : Promise<ApiClientResponse> {
const urlObj = url.parse(request.url);
const clientRequestOptions : HttpRequestOptions | HttpsRequestOptions = {
// tslint:disable:object-literal-sort-keys
hostname : urlObj.hostname,
path : urlObj.path,
port : urlObj.port,
protocol : urlObj.protocol,
auth : urlObj.auth,
headers : this.arrayToObjectHeader(request.headers),
method : request.method,
};
const client = clientRequestOptions.protocol === 'https:' ? require('https') : require('http');
return new Promise<ApiClientResponse>((resolve, reject) => {
const clientRequest = client.request(clientRequestOptions, (response) => {
const chunks = [];
response.on('data', (chunk) => {
chunks.push(chunk);
});
response.on('end', () => {
const responseStr = Buffer.concat(chunks).toString();
const responseObj : ApiClientResponse = {
statusCode : response.statusCode,
body : responseStr,
headers : this.objectToArrayHeader(response.headers),
};
resolve(responseObj);
});
});
clientRequest.on('error', (err) => {
reject(this.createAskSdkModelRuntimeError(this.constructor.name, err.message));
});
if (request.body) {
clientRequest.write(request.body);
}
clientRequest.end();
});
}
/**
* Converts the header array in {@link ApiClientRequest} to compatible JSON object.
* @private
* @param {{key : string, value : string}[]} header header array from ApiClientRequest}
* @returns {Object.<string, string[]>} header object to pass into HTTP client
*/
private arrayToObjectHeader(header : Array<{key : string, value : string}>) : {[key : string] : string[]} {
const reducer = (obj : {[key : string] : string[]}, item : {key : string, value : string})
: {[key : string] : string[]} => {
if (obj[item.key]) {
obj[item.key].push(item.value);
} else {
obj[item.key] = [item.value];
}
return obj;
};
return header.reduce(reducer, {});
}
/**
* Converts JSON header object to header array required for {ApiClientResponse}
* @private
* @param {Object.<string, (string|string[])>} header JSON header object returned by HTTP client
* @returns {{key : string, value : string}[]}
*/
private objectToArrayHeader(header : {[key : string] : string | string[]}) : Array<{key : string, value : string}> {
const arrayHeader = <Array<{key : string, value : string}>> [];
Object.keys(header).forEach((key : string) => {
const headerArray = Array.isArray(header[key]) ? header[key] : [header[key]];
for (const value of <string[]> headerArray) {
arrayHeader.push({
key,
value,
});
}
});
return arrayHeader;
}
/**
* function creating an AskSdk error.
* @param {string} errorScope
* @param {string} errorMessage
* @returns {Error}
*/
private createAskSdkModelRuntimeError(errorScope : string, errorMessage : string) : Error {
const error = new Error(errorMessage);
error.name = `AskSdkModelRuntime.${errorScope} Error`;
return error;
}
}
/**
* Represents an interface that provides API configuration options needed by service clients.
* @interface ApiConfiguration
*/
export interface ApiConfiguration {
/**
* Configured ApiClient implementation
*/
apiClient : ApiClient;
/**
* Authorization value to be used on any calls of the service client instance
*/
authorizationValue : string;
/**
* Endpoint to hit by the service client instance
*/
apiEndpoint : string;
}
/**
* Class to be used as the base class for the generated service clients.
*/
export abstract class BaseServiceClient {
private static isCodeSuccessful( responseCode : number ) : boolean {
return responseCode >= 200 && responseCode < 300;
}
private static buildUrl(
endpoint : string,
path : string,
queryParameters : Array<{ key : string, value : string }>,
pathParameters : Map<string, string>,
) : string {
const processedEndpoint : string = endpoint.endsWith('/') ? endpoint.substr(0, endpoint.length - 1) : endpoint;
const pathWithParams : string = this.interpolateParams(path, pathParameters);
const isConstantQueryPresent : boolean = pathWithParams.includes('?');
const queryString : string = this.buildQueryString(queryParameters, isConstantQueryPresent);
return processedEndpoint + pathWithParams + queryString;
}
private static interpolateParams(path : string, params : Map<string, string>) : string {
if (!params) {
return path;
}
let result : string = path;
params.forEach((paramValue : string, paramName : string) => {
result = result.replace('{' + paramName + '}', encodeURIComponent(paramValue));
});
return result;
}
private static buildQueryString(params : Array<{ key : string, value : string }>, isQueryStart : boolean) : string {
if (!params) {
return '';
}
const sb : string[] = [];
if (isQueryStart) {
sb.push('&');
} else {
sb.push('?');
}
params.forEach((obj) => {
sb.push(encodeURIComponent(obj.key));
sb.push('=');
sb.push(encodeURIComponent(obj.value));
sb.push('&');
});
sb.pop();
return sb.join('');
}
/**
* ApiConfiguration instance to provide dependencies for this service client
*/
protected apiConfiguration : ApiConfiguration;
private requestInterceptors : Array<(request : ApiClientRequest) => void | Promise<void>> = [];
private responseInterceptors : Array<(response : ApiClientResponse) => void | Promise<void>> = [];
/**
* Creates new instance of the BaseServiceClient
* @param {ApiConfiguration} apiConfiguration configuration parameter to provide dependencies to service client instance
*/
protected constructor(apiConfiguration : ApiConfiguration) {
this.apiConfiguration = apiConfiguration;
}
/**
* Sets array of functions that is going to be executed before the request is send
* @param {Function} requestInterceptor request interceptor function
* @returns {BaseServiceClient}
*/
public withRequestInterceptors(...requestInterceptors : Array<(request : ApiClientRequest) => void | Promise<void>>) : BaseServiceClient {
for ( const interceptor of requestInterceptors ) {
this.requestInterceptors.push(interceptor);
}
return this;
}
/**
* Sets array of functions that is going to be executed after the request is send
* @param {Function} responseInterceptor response interceptor function
* @returns {BaseServiceClient}
*/
public withResponseInterceptors(...responseInterceptors : Array<(response : ApiClientResponse) => void | Promise<void>>) : BaseServiceClient {
for ( const interceptor of responseInterceptors ) {
this.responseInterceptors.push(interceptor);
}
return this;
}
/**
* Invocation wrapper to implement service operations in generated classes
* @param method HTTP method, such as 'POST', 'GET', 'DELETE', etc.
* @param endpoint base API url
* @param path the path pattern with possible placeholders for path parameters in form {paramName}
* @param pathParams path parameters collection
* @param queryParams query parameters collection
* @param headerParams headers collection
* @param bodyParam if body parameter is present it is provided here, otherwise null or undefined
* @param errors maps recognized status codes to messages
* @param nonJsonBody if the body is in JSON format
*/
protected async invoke(
method : string,
endpoint : string,
path : string,
pathParams : Map<string, string>,
queryParams : Array<{ key : string, value : string }>,
headerParams : Array<{ key : string, value : string }>,
bodyParam : any,
errors : Map<number, string>,
nonJsonBody? : boolean,
) : Promise<any> {
const request : ApiClientRequest = {
url : BaseServiceClient.buildUrl(endpoint, path, queryParams, pathParams),
method,
headers : headerParams,
};
if (bodyParam != null) {
const contentType = headerParams.find((header) => header.key.toLowerCase() === 'content-type');
const contentTypeNonJson = contentType && !contentType.value.includes('application/json');
request.body = nonJsonBody || contentTypeNonJson ? bodyParam : JSON.stringify(bodyParam);
}
const apiClient = this.apiConfiguration.apiClient;
let response : ApiClientResponse;
try {
for (const requestInterceptor of this.requestInterceptors) {
await requestInterceptor(request);
}
response = await apiClient.invoke(request);
for (const responseInterceptor of this.responseInterceptors) {
await responseInterceptor(response);
}
} catch (err) {
err.message = `Call to service failed: ${err.message}`;
throw err;
}
let body;
try {
body = response.body ? JSON.parse(response.body) : undefined;
} catch (err) {
throw new SyntaxError(`Failed trying to parse the response body: ${response.body}`);
}
if (BaseServiceClient.isCodeSuccessful(response.statusCode)) {
const apiResponse : ApiResponse = {
headers : response.headers,
body,
statusCode : response.statusCode,
};
return apiResponse;
}
const err = new Error('Unknown error');
err.name = 'ServiceError';
err['statusCode'] = response.statusCode; // tslint:disable-line:no-string-literal
err['headers'] = response.headers; // tslint:disable-line:no-string-literal
err['response'] = body; // tslint:disable-line:no-string-literal
if (errors && errors.has(response.statusCode)) {
err.message = errors.get(response.statusCode);
}
throw err;
}
}
/**
* Represents a Login With Amazon(LWA) access token
*/
export interface AccessToken {
token : string;
expiry : Number;
}
/**
* Represents a request for retrieving a Login With Amazon(LWA) access token
*/
export interface AccessTokenRequest {
clientId : string;
clientSecret : string;
scope? : string;
refreshToken? : string;
}
/**
* Represents a response returned by LWA containing a Login With Amazon(LWA) access token
*/
export interface AccessTokenResponse {
access_token : string;
expires_in : number;
scope : string;
token_type : string;
}
/**
* Represents the authentication configuration for a client ID and client secret
*/
export interface AuthenticationConfiguration {
clientId : string;
clientSecret : string;
accessToken? : string;
refreshToken? : string;
authEndpoint? : string;
}
/**
* Class to be used to call Amazon LWA to retrieve access tokens.
*/
export class LwaServiceClient extends BaseServiceClient {
protected static EXPIRY_OFFSET_MILLIS : number = 60000;
protected static REFRESH_ACCESS_TOKEN : string = 'refresh_access_token';
protected static CLIENT_CREDENTIALS_GRANT_TYPE : string = 'client_credentials';
protected static LWA_CREDENTIALS_GRANT_TYPE : string = 'refresh_token';
protected static AUTH_ENDPOINT : string = 'https://api.amazon.com';
protected authenticationConfiguration : AuthenticationConfiguration;
protected tokenStore : {[cacheKey : string] : AccessToken};
protected grantType : string;
constructor(options : {
apiConfiguration : ApiConfiguration,
authenticationConfiguration : AuthenticationConfiguration,
grantType? : string,
}) {
super(options.apiConfiguration);
if (options.authenticationConfiguration == null) {
throw new Error('AuthenticationConfiguration cannot be null or undefined.');
}
this.grantType = options.grantType ? options.grantType : LwaServiceClient.CLIENT_CREDENTIALS_GRANT_TYPE;
this.authenticationConfiguration = options.authenticationConfiguration;
this.tokenStore = {};
}
public async getAccessTokenForScope(scope : string) : Promise<string> {
if (scope == null) {
throw new Error('Scope cannot be null or undefined.');
}
return this.getAccessToken(scope);
}
public async getAccessToken(scope? : string) : Promise<string> {
if (this.authenticationConfiguration.accessToken) {
return this.authenticationConfiguration.accessToken;
}
const cacheKey : string = scope ? scope : LwaServiceClient.REFRESH_ACCESS_TOKEN;
const accessToken = this.tokenStore[cacheKey];
if (accessToken && accessToken.expiry > Date.now() + LwaServiceClient.EXPIRY_OFFSET_MILLIS) {
return accessToken.token;
}
const accessTokenRequest : AccessTokenRequest = {
clientId : this.authenticationConfiguration.clientId,
clientSecret : this.authenticationConfiguration.clientSecret,
};
if (scope && this.authenticationConfiguration.refreshToken) {
throw new Error('Cannot support both refreshToken and scope.');
} else if (scope == null && this.authenticationConfiguration.refreshToken == null) {
throw new Error('Either refreshToken or scope must be specified.');
} else if (scope == null) {
accessTokenRequest.refreshToken = this.authenticationConfiguration.refreshToken;
} else {
accessTokenRequest.scope = scope;
}
const accessTokenResponse : AccessTokenResponse = await this.generateAccessToken(accessTokenRequest);
this.tokenStore[cacheKey] = {
token : accessTokenResponse.access_token,
expiry : Date.now() + accessTokenResponse.expires_in * 1000,
};
return accessTokenResponse.access_token;
}
protected async generateAccessToken(accessTokenRequest : AccessTokenRequest) : Promise<AccessTokenResponse> {
const authEndpoint = this.authenticationConfiguration.authEndpoint || LwaServiceClient.AUTH_ENDPOINT;
if (!accessTokenRequest.clientId || ! accessTokenRequest.clientSecret) {
throw new Error(`Required parameter accessTokenRequest didn't specify clientId or clientSecret`);
}
const queryParams : Array<{ key : string, value : string }> = [];
const headerParams : Array<{key : string, value : string}> = [];
headerParams.push({key : 'Content-type', value : 'application/x-www-form-urlencoded'});
const pathParams : Map<string, string> = new Map<string, string>();
const paramInfo = this.grantType === LwaServiceClient.LWA_CREDENTIALS_GRANT_TYPE ? `&refresh_token=${accessTokenRequest.refreshToken}` : `&scope=${accessTokenRequest.scope}`;
const bodyParams : string = `grant_type=${this.grantType}&client_secret=${accessTokenRequest.clientSecret}&client_id=${accessTokenRequest.clientId}` + paramInfo;
const errorDefinitions : Map<number, string> = new Map<number, string>();
errorDefinitions.set(200, 'Token request sent.');
errorDefinitions.set(400, 'Bad Request');
errorDefinitions.set(401, 'Authentication Failed');
errorDefinitions.set(500, 'Internal Server Error');
const apiResponse : ApiResponse = await this.invoke(
'POST',
authEndpoint,
'/auth/O2/token',
pathParams,
queryParams,
headerParams,
bodyParams,
errorDefinitions,
true,
);
const response : AccessTokenResponse = {
access_token: apiResponse.body[`access_token`],
expires_in: apiResponse.body[`expires_in`],
scope: apiResponse.body[`scope`],
token_type: apiResponse.body[`token_type`],
};
return response;
}
}
/**
* function creating an AskSdk user agent.
* @param packageVersion
* @param customUserAgent
*/
export function createUserAgent(packageVersion : string, customUserAgent : string) : string {
const customUserAgentString = customUserAgent ? (' ' + customUserAgent) : '';
return `ask-node-model/${packageVersion} Node/${process.version}` + customUserAgentString;
} | the_stack |
import {Environment} from "../Env";
import {IO} from "../IO";
import {Errors} from "../Errors";
import {Strings} from "./Strings";
import {Lists} from "./List";
import {Maps} from "./Maps";
import {Iter} from "./Iter";
/**
* Created by Josh on 2/13/17.
*/
//AST functions that implement standard library
export namespace STD {
//produces a callable Oblivion function
export let func = (env:Environment.Env, args:any[]) => {
let paramList = env.callLib(env, args[0].node, args[0].args);
let funcBody = args[1].args;
return (env:Environment.Env, args:any[]) => {
//functionally scoped environment
let funcEnv = env.createChild();
if(args.length !== paramList.length) throw `Argument Error, expected ${paramList.length} args but got ${args.length}`;
for(let i=0;i<paramList.length;i++){
//binds called arguments to new Env
funcEnv.set(paramList[i], funcEnv.callLib(funcEnv, args[i].node, args[i].args));
}
//calls all statements in body
for(let j=0;j<funcBody.length;j++){
funcEnv.callLib(funcEnv, funcBody[j].node, funcBody[j].args)
}
return funcEnv.getReturnValue();
};
};
//creates a generator object
export let generator = (env:Environment.Env, args:any[]) => {
let defBody = args[0].args;
let genBody = args[1].args;
let genEnv = env.createChild();
//runs the def body only once, to set up generator
for(let i=0;i<defBody.length;i++){
genEnv.callLib(genEnv, defBody[i].node, defBody[i].args);
}
return (env:Environment.Env, args:any[]) => {
if(args.length !== 0) throw new Errors.ArgumentError(args.length, 0);
//calls all statements in the generator body
for(let j=0;j<genBody.length;j++){
genEnv.callLib(genEnv, genBody[j].node, genBody[j].args);
}
//This is preserved between generator calls, but functions the same as a return
return genEnv.getReturnValue();
};
};
//handles a process, no parameter bodies of statemnts evaluated in child scope
export let process = (env:Environment.Env, args:any[]) => {
let procBody = args[0].args;
return (env:Environment.Env, args:any[]) => {
let procEnv = env.createChild();
if(args.length !== 0) throw new Errors.ArgumentError(args.length, 0);
//calls all statements in the procBody
for(let j=0;j<procBody.length;j++){
procEnv.callLib(procEnv, procBody[j].node, procBody[j].args);
}
//returns localized return value
return procEnv.getReturnValue()
};
};
//handles variable assignment
export let assign = (env:Environment.Env, args:any[]) => {
env.set(env.callLib(env,args[0].node, args[0].args), env.callLib(env,args[1].node, args[1].args))
};
//handles Word rule, which retrieves variables
export let wordVar = (env:Environment.Env, args:any[]) => {
let varr = env.safeGet(args[0]);
if(varr !== undefined) return varr;
else return args[0];
};
//facilitates return function
export let _return = (env:Environment.Env, args:any[]) => {
if(args.length === 1) env.setReturnValue(env.callLib(env, args[0].node, args[0].args));
};
//handles parameters for a function
export let params = (env:Environment.Env, args:any[]) => {
for(let i=0;i<args.length;i++){
args[i] = env.callLib(env, args[i].node, args[i].args);
}
return args;
};
//processes name nodes
export let name = (env:Environment.Env, args:any[]) => {
return args[0];
};
export let print = (env:Environment.Env, args:any[]) => {
for(let i=0;i<args.length;i++){
let printed = env.callLib(env, args[i].node, args[i].args);
if(typeof printed === 'object') IO.pushOut(printed.strFormat());
else if(typeof printed === 'function') IO.pushOut("{func}");
else IO.pushOut(printed);
}
};
//need to be changed to operator
export let add = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Error(`+ only supports number type.`);
return left + right;
};
export let sub = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Error(`- only supports number type.`);
return left - right;
};
export let mul = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Error(`* only supports number type.`);
return left * right;
};
export let div = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Error(`/ only supports number type.`);
return left / right;
};
export let rem = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Error(`% only supports number type.`);
return left % right;
};
export let c_number = (env:Environment.Env, args:any[]) => {
return Number(args[0]);
};
//handles bool nodes
export let c_bool = (env:Environment.Env, args:any[]) => {
return args[0];
};
export let c_null = (env:Environment.Env, args:any[]) => {
return null;
};
//eq logical op functions -------------
export let eq = (env:Environment.Env, args:any[]) => {
return env.callLib(env, args[0].node, args[0].args) === env.callLib(env, args[1].node, args[1].args);
};
export let ne = (env:Environment.Env, args:any[]) => {
return env.callLib(env, args[0].node, args[0].args) !== env.callLib(env, args[1].node, args[1].args);
};
//only numbers can be compared with <, <=, >=, and >
export let lt = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Errors.TypeError('number', `${typeof left} and ${typeof right}`);
return left < right;
};
export let gt = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Errors.TypeError('number', `${typeof left} and ${typeof right}`);
return left > right;
};
export let le = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Errors.TypeError('number', `${typeof left} and ${typeof right}`);
return left <= right;
};
export let ge = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Errors.TypeError('number', `${typeof left} and ${typeof right}`);
return left >= right;
};
//comparison that works on lists and maps
export let same = (env:Environment.Env, args:any[]) => {
return JSON.stringify(env.callLib(env, args[0].node, args[0].args)) === JSON.stringify(env.callLib(env, args[1].node, args[1].args));
};
//logical or operator
export let _or = (env:Environment.Env, args:any[]) => {
return Boolean(env.callLib(env, args[0].node, args[0].args) || env.callLib(env, args[1].node, args[1].args));
};
//logical and operator
export let _and = (env:Environment.Env, args:any[]) => {
return Boolean(env.callLib(env, args[0].node, args[0].args) && env.callLib(env, args[1].node, args[1].args));
};
/*Conditional StdLib funcs*/
export let _if = (env:Environment.Env, args:any[]) => {
if(args.length < 2) throw new Errors.ArgumentError(args.length, 2);
let cond = env.callLib(env, args[0].node, args[0].args);
let trueBody = args[1].args;
let falseBody = args[2].args;
//if condition is true, executes statements in the true body
if(cond){
for(let i=0;i<trueBody.length;i++){
let statement = env.callLib(env, trueBody[i].node, trueBody[i].args);
if(typeof statement === 'function') statement(env, []);
}
}
//If condition is false, executes the statements in the false body
else {
for(let j=0;j<falseBody.length;j++){
let state = env.callLib(env, falseBody[j].node, falseBody[j].args);
if(typeof state === 'function') state(env, []);
}
}
};
export let loop = (env:Environment.Env, args:any[]) => {
//must have at least a condition and statement/argument
let loopBody = args[1].args;
while(env.callLib(env, args[0].node, args[0].args)){
for(let i=0;i<loopBody.length;i++){
//treats function types genrated from AST as callable blocks
let state = env.callLib(env, loopBody[i].node, loopBody[i].args);
if(typeof state === 'function') state(env, []);
}
}
};
//repeat function useful for drawing and looping
//only accepts 2 arguments
export let repeat = (env:Environment.Env, args:any[]) => {
if(args.length !== 2) throw new Error(`ArgumentError: Expected 2 arguments but got ${args.length}`);
let times = env.callLib(env, args[0].node, args[0].args);
let proc = env.callLib(env, args[1].node, args[1].args);
if(typeof proc !== 'function' || typeof times !== 'number') throw new Error("repeat() must take one number and one process or function.");
if(times < 1) throw new Error("Cannot call repeat less than 1 times, in valid argument: " +times);
while(times--){
proc(env, []);
}
};
export let attribute = (env:Environment.Env, args:any[]) => {
if(args.length !== 2) throw new Errors.ArgumentError(args.length, 2);
let obj = env.get(env.callLib(env, args[0].node, args[0].args));
let index = env.callLib(env, args[1].node, args[1].args);
if(typeof obj === 'object' && obj !== null) {
return obj.getItem(index); //collection interface
}
else throw new Errors.TypeError('Collection', typeof obj);
};
//handles any forms of a.b()
export let methodCall = (env:Environment.Env, args:any[]) => {
let method = env.callLib(env, args[0].node, args[0].args);
if(typeof method !== 'function') throw new Errors.TypeError('callable', typeof args[0]);
return method(env, args.slice(1));
};
//function for => operator
export let attrAssign = (env:Environment.Env, args:any[]) => {
let obj = env.get(args[0].args[0].args[0]);
if(obj.constructor.name !== 'List') throw new Error('=> Operator can only be used on lists');
let key = env.callLib(env, args[0].args[1].node, args[0].args[1].args);
return obj.setItem(key, env.callLib(env, args[1].node, args[1].args));
};
//creates new list object
export let c_list = (env:Environment.Env, args:any[]) => {
let newlst = [];
for(let i=0;i<args.length;i++){
newlst.push(env.callLib(env, args[i].node, args[i].args));
}
return new Lists.List(newlst);
};
//creates new map object
export let c_map = (env:Environment.Env, args:any[]) => {
let map = new Maps.OblMap();
for(let pair of args){
map.setItem(env.callLib(env, pair.args[0].node, pair.args[0].args), env.callLib(env, pair.args[1].node, pair.args[1].args))
}
return map;
};
//produces lists in a range
export let range = (env:Environment.Env, args:any[]) => {
switch(args.length){
case 0:
return new Lists.List();
case 1:
var lst = [];
let limit = env.callLib(env, args[0].node, args[0].args);
if(typeof limit !== 'number') throw new Error(`TypeError: Got type ${typeof limit} but needs number.`);
for(let i=0;i<limit;i++) lst.push(i);
return new Lists.List(lst);
case 2:
var lst = [];
let start = env.callLib(env, args[0].node, args[0].args);
let end = env.callLib(env, args[1].node, args[1].args);
if(typeof start !== 'number' || typeof end !== 'number') throw new Error(`TypeError: Needs type number.`);
for(let i=start;i<end;i++) lst.push(i);
return new Lists.List(lst);
}
};
export let _for = (env:Environment.Env, args:any[]) => {
let varName = env.callLib(env, args[0].node, args[0].args);
let iterable = Iter.makeIter(env.callLib(env, args[1].node, args[1].args));
let forBody = args[2].args;
//calls for body continously for each in the iterator
while(!iterable.done){
env.set(varName, iterable.next());
for(let i=0;i<forBody.length;i++) env.callLib(env, forBody[i].node, forBody[i].args);
}
};
/*Generic get and set functions*/
/*Generic Collection functions*/
export let len = (env:Environment.Env, args:any[]) => {
let obj = env.callLib(env, args[0].node, args[0].args);
switch(typeof obj){
case 'number': return obj;
case 'object': return obj.size();
default: return 1;
}
};
export let _in = (env:Environment.Env, args:any[]) => {
if(args.length !== 2) throw new Errors.ArgumentError(args.length, 2);
let obj = env.callLib(env, args[0].node, args[0].args);
if(typeof obj !== 'object' || obj === null) throw new Error('TypeError: Argument not of collection type');
return obj.hasItem(env.callLib(env, args[1].node, args[1].args));
};
export let pop = (env:Environment.Env, args:any[]) => {
if(args.length !== 1) throw new Errors.ArgumentError(args.length, 1);
let obj = env.callLib(env, args[0].node, args[0].args);
if(obj.constructor.name !== 'List') throw new Error(`Cannot call pop on type ${typeof obj}`);
return obj.pop();
};
export let insert = (env:Environment.Env, args:any[]) => {
if(args.length < 3) throw new Errors.ArgumentError(args.length, 3);
let obj = env.callLib(env, args[0].node, args[0].args);
if(obj.constructor.name !== 'List') throw new Error('TypeError: Argument not of List type');
return obj.insert(env.callLib(env, args[1].node, args[1].args), env.callLib(env, args[2].node, args[2].args));
};
//operator implementation of &
export let extend = (env:Environment.Env, args:any[]) => {
let obj = env.callLib(env, args[0].node, args[0].args);
if(obj.constructor.name !== 'List') throw new Error('TypeError: Argument not of collection type');
return obj.extend(env.callLib(env, args[1].node, args[1].args));
};
export let find = (env:Environment.Env, args:any[]) => {
if(args.length !== 2) throw new Errors.ArgumentError(args.length, 2);
let obj = env.callLib(env, args[0].node, args[0].args);
if(obj.constructor.name !== 'List') throw new Error('TypeError: Argument not of List type');
return obj.find(env.callLib(env, args[1].node, args[1].args));
};
export let slice = (env:Environment.Env, args:any[]) => {
if(args.length < 2 || args.length > 3) throw new Error("slice() takes either 2 or 3 arguments only");
let lst = env.callLib(env, args[0].node, args[0].args);
switch(args.length){
case 2:
var start = env.callLib(env, args[1].node, args[1].args);
if(typeof start !== 'number') throw new Error("slice() indexes must be a number");
return lst.copy(start);
case 3:
var start = env.callLib(env, args[1].node, args[1].args);
let end = env.callLib(env, args[2].node, args[2].args);
if(typeof start !== 'number' || typeof end !== 'number') throw new Error("slice() indexes must be a number");
return lst.copy(start, end);
}
};
//can call a function or process arbitrarily
export let call = (env:Environment.Env, args:any[]) => {
if(args.length === 0) throw new Error("call() must take 1 or more arguments");
let fnc = env.callLib(env, args[0].node, args[0].args);
if(typeof fnc !== 'function') throw new Error("Cannot call non-function type");
return fnc(env, args.slice(1));
};
//random number operator
export let rand = (env:Environment.Env, args:any[]) => {
let left = env.callLib(env, args[0].node, args[0].args);
let right = env.callLib(env, args[1].node, args[1].args);
if(typeof left !== 'number' || typeof right !== 'number') throw new Errors.TypeError('number', `${typeof left} and ${typeof right}`);
return Math.floor(Math.random() * (Math.floor(right) - Math.ceil(left))) + Math.ceil(left);
};
} | the_stack |
import {
WeightVectorOption,
ErrorCohort,
defaultModelAssessmentContext,
ModelAssessmentContext,
JointDataset,
ModelExplanationUtils,
FabricStyles,
constructRows,
constructCols,
ModelTypes
} from "@responsible-ai/core-ui";
import { IGlobalSeries, LocalImportancePlots } from "@responsible-ai/interpret";
import { localization } from "@responsible-ai/localization";
import {
ConstrainMode,
DetailsList,
DetailsListLayoutMode,
Fabric,
IDetailsColumnRenderTooltipProps,
IDetailsHeaderProps,
IDropdownOption,
IRenderFunction,
MarqueeSelection,
ScrollablePane,
ScrollbarVisibility,
Selection,
SelectAllVisibility,
SelectionMode,
Stack,
TooltipHost,
IColumn,
IGroup,
Text
} from "office-ui-fabric-react";
import React from "react";
export interface IIndividualFeatureImportanceProps {
features: string[];
jointDataset: JointDataset;
invokeModel?: (data: any[], abortSignal: AbortSignal) => Promise<any[]>;
selectedWeightVector: WeightVectorOption;
weightOptions: WeightVectorOption[];
weightLabels: any;
onWeightChange: (option: WeightVectorOption) => void;
selectedCohort: ErrorCohort;
modelType?: ModelTypes;
}
export interface IIndividualFeatureImportanceTableState {
rows: any[];
columns: IColumn[];
groups?: IGroup[];
}
export interface IIndividualFeatureImportanceState
extends IIndividualFeatureImportanceTableState {
featureImportances: IGlobalSeries[];
sortArray: number[];
sortingSeriesIndex?: number;
}
export class IndividualFeatureImportanceView extends React.Component<
IIndividualFeatureImportanceProps,
IIndividualFeatureImportanceState
> {
public static contextType = ModelAssessmentContext;
public context: React.ContextType<typeof ModelAssessmentContext> =
defaultModelAssessmentContext;
private selection: Selection = new Selection({
onSelectionChanged: (): void => {
this.updateViewedFeatureImportances();
}
});
public constructor(props: IIndividualFeatureImportanceProps) {
super(props);
const tableState = this.updateItems();
this.state = {
featureImportances: [],
sortArray: [],
...tableState
};
}
public componentDidUpdate(
prevProps: IIndividualFeatureImportanceProps
): void {
if (this.props.selectedCohort !== prevProps.selectedCohort) {
this.setState(this.updateItems());
}
}
public render(): React.ReactNode {
if (this.state.rows === undefined || this.state.columns === undefined) {
return React.Fragment;
}
const testableDatapoints = this.state.featureImportances.map(
(item) => item.unsortedFeatureValues as any[]
);
const testableDatapointColors = this.state.featureImportances.map(
(item) => FabricStyles.fabricColorPalette[item.colorIndex]
);
const testableDatapointNames = this.state.featureImportances.map(
(item) => item.name
);
const featuresOption: IDropdownOption[] = new Array(
this.context.jointDataset.datasetFeatureCount
)
.fill(0)
.map((_, index) => {
const key = JointDataset.DataLabelRoot + index.toString();
const meta = this.context.jointDataset.metaDict[key];
const options = meta.isCategorical
? meta.sortedCategoricalValues?.map((optionText, index) => {
return { key: index, text: optionText };
})
: undefined;
return {
data: {
categoricalOptions: options,
fullLabel: meta.label.toLowerCase()
},
key,
text: meta.abbridgedLabel
};
});
return (
<Stack tokens={{ childrenGap: "10px", padding: "15px 38px 0 38px" }}>
<Stack.Item>
<Text variant="medium">
{localization.ModelAssessment.FeatureImportances.IndividualFeature}
</Text>
</Stack.Item>
<Stack.Item className="tabularDataView">
<div style={{ height: "800px", position: "relative" }}>
<Fabric>
<ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto}>
<MarqueeSelection selection={this.selection}>
<DetailsList
items={this.state.rows}
columns={this.state.columns}
groups={this.state.groups}
setKey="set"
layoutMode={DetailsListLayoutMode.fixedColumns}
constrainMode={ConstrainMode.unconstrained}
onRenderDetailsHeader={this.onRenderDetailsHeader}
selectionPreservedOnEmptyClick
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
checkButtonAriaLabel="Row checkbox"
// checkButtonGroupAriaLabel="Group checkbox"
groupProps={{ showEmptyGroups: true }}
selectionMode={SelectionMode.multiple}
selection={this.selection}
/>
</MarqueeSelection>
</ScrollablePane>
</Fabric>
</div>
</Stack.Item>
<LocalImportancePlots
includedFeatureImportance={this.state.featureImportances}
jointDataset={this.context.jointDataset}
metadata={this.context.modelMetadata}
selectedWeightVector={this.props.selectedWeightVector}
weightOptions={this.props.weightOptions}
weightLabels={this.props.weightLabels}
testableDatapoints={testableDatapoints}
testableDatapointColors={testableDatapointColors}
testableDatapointNames={testableDatapointNames}
featuresOption={featuresOption}
sortArray={this.state.sortArray}
sortingSeriesIndex={this.state.sortingSeriesIndex}
invokeModel={this.props.invokeModel}
onWeightChange={this.props.onWeightChange}
/>
</Stack>
);
}
private updateViewedFeatureImportances(): void {
const allSelectedItems = this.selection.getSelection();
const featureImportances = allSelectedItems.map(
(row, colorIndex): IGlobalSeries => {
const rowDict = this.props.jointDataset.getRow(row[0]);
return {
colorIndex,
id: rowDict[JointDataset.IndexLabel],
name: localization.formatString(
localization.Interpret.WhatIfTab.rowLabel,
rowDict[JointDataset.IndexLabel].toString()
),
unsortedAggregateY: JointDataset.localExplanationSlice(
rowDict,
this.props.jointDataset.localExplanationFeatureCount
) as number[],
unsortedFeatureValues: JointDataset.datasetSlice(
rowDict,
this.props.jointDataset.metaDict,
this.props.jointDataset.datasetFeatureCount
)
};
}
);
let sortArray: number[] = [];
let sortingSeriesIndex: number | undefined;
if (featureImportances.length !== 0) {
sortingSeriesIndex = 0;
sortArray = ModelExplanationUtils.getSortIndices(
featureImportances[0].unsortedAggregateY
).reverse();
} else {
sortingSeriesIndex = undefined;
}
this.setState({
featureImportances,
sortArray,
sortingSeriesIndex
});
}
private updateItems(): IIndividualFeatureImportanceTableState {
let groups: IGroup[] | undefined;
// assume classifier by default, otherwise regressor
if (
this.props.modelType &&
this.props.modelType === ModelTypes.Regression
) {
// don't use groups since there are no correct/incorrect buckets
this.props.selectedCohort.cohort.sort();
} else {
this.props.selectedCohort.cohort.sortByGroup(
JointDataset.IndexLabel,
(row) =>
row[JointDataset.TrueYLabel] === row[JointDataset.PredictedYLabel]
);
// find first incorrect item
const firstIncorrectItemIndex =
this.props.selectedCohort.cohort.filteredData.findIndex(
(row) =>
row[JointDataset.TrueYLabel] !== row[JointDataset.PredictedYLabel]
);
groups = [
{
count: firstIncorrectItemIndex,
key: "groupCorrect",
level: 0,
name: localization.ModelAssessment.FeatureImportances
.CorrectPredictions,
startIndex: 0
},
{
count:
this.props.selectedCohort.cohort.filteredData.length -
firstIncorrectItemIndex,
key: "groupIncorrect",
level: 0,
name: localization.ModelAssessment.FeatureImportances
.IncorrectPredictions,
startIndex: firstIncorrectItemIndex
}
];
}
const cohortData = this.props.selectedCohort.cohort.filteredData;
const numRows: number = cohortData.length;
const indices = this.props.selectedCohort.cohort.filteredData.map(
(row: { [key: string]: number }) => {
return row[JointDataset.IndexLabel] as number;
}
);
const rows = constructRows(
cohortData,
this.props.jointDataset,
numRows,
() => false, // don't filter any items
indices
);
const numCols: number = this.props.jointDataset.datasetFeatureCount;
const featureNames: string[] = this.props.features;
const viewedCols: number = Math.min(numCols, featureNames.length);
const columns = constructCols(
viewedCols,
featureNames,
this.props.jointDataset,
false
);
return {
columns,
groups,
rows
};
}
private onRenderDetailsHeader: IRenderFunction<IDetailsHeaderProps> = (
props,
defaultRender
) => {
if (!props) {
return <div />;
}
const onRenderColumnHeaderTooltip: IRenderFunction<IDetailsColumnRenderTooltipProps> =
(tooltipHostProps) => <TooltipHost {...tooltipHostProps} />;
return (
<div>
{defaultRender?.({
...props,
onRenderColumnHeaderTooltip,
selectAllVisibility: SelectAllVisibility.hidden
})}
</div>
);
};
} | the_stack |
import { DataManager, Query } from '@syncfusion/ej2-data';
import { extend } from '@syncfusion/ej2-base';
import { CallbackFunction } from '../../../src/schedule/base/interface';
/**
* Schedule datasource spec
*/
export const defaultData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Paris',
StartTime: new Date(2017, 9, 29, 10, 0),
EndTime: new Date(2017, 9, 29, 11, 30),
IsAllDay: false
}, {
Id: 2,
Subject: 'Meeting - 1',
StartTime: new Date(2017, 9, 30, 10, 0),
EndTime: new Date(2017, 9, 30, 12, 30),
IsAllDay: false
}, {
Id: 3,
Subject: 'Meeting - 2',
StartTime: new Date(2017, 9, 30, 11, 0),
EndTime: new Date(2017, 9, 30, 14, 30),
IsAllDay: false
}, {
Id: 4,
StartTime: new Date(2017, 9, 31),
EndTime: new Date(2017, 10, 1),
IsAllDay: true
}, {
Id: 5,
Subject: 'Conference - 2',
StartTime: new Date(2017, 9, 31, 22, 0),
EndTime: new Date(2017, 10, 1, 0, 0),
IsAllDay: false
}, {
Id: 6,
Subject: 'Conference - 3',
StartTime: new Date(2017, 10, 1, 9, 30),
EndTime: new Date(2017, 10, 1, 11, 45),
IsAllDay: false
}, {
Id: 7,
Subject: 'Conference - 4',
StartTime: new Date(2017, 10, 1, 10, 30),
EndTime: new Date(2017, 10, 1, 12, 45),
IsAllDay: false
}, {
Id: 8,
Subject: 'Travelling',
StartTime: new Date(2017, 10, 1, 11, 30),
EndTime: new Date(2017, 10, 1, 13, 45),
IsAllDay: false
}, {
Id: 9,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 2, 10, 0),
EndTime: new Date(2017, 10, 2, 12, 30),
IsAllDay: false
}, {
Id: 10,
Subject: 'Conference',
StartTime: new Date(2017, 10, 2, 15, 30),
EndTime: new Date(2017, 10, 2, 18, 45),
IsAllDay: false
}, {
Id: 11,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 3, 10, 15),
EndTime: new Date(2017, 10, 3, 14, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
IsAllDay: false
}, {
Id: 12,
Subject: 'Conference',
StartTime: new Date(2017, 10, 4, 9, 30),
EndTime: new Date(2017, 10, 5, 5, 45),
IsAllDay: false
}, {
Id: 13,
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 14,
Subject: 'Same Time',
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 15,
Subject: 'Same Time',
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 16,
Subject: 'Same Time',
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 17,
Subject: 'Same Time',
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 18,
Subject: 'Same Time',
StartTime: new Date(2017, 10, 5, 10, 0),
EndTime: new Date(2017, 10, 5, 11, 30),
IsAllDay: false
}, {
Id: 19,
Subject: 'Meeting - 1',
StartTime: new Date(2017, 10, 6),
EndTime: new Date(2017, 10, 7),
IsAllDay: true
}, {
Id: 20,
Subject: 'Meeting - 2',
StartTime: new Date(2017, 10, 6, 11, 0),
EndTime: new Date(2017, 10, 6, 14, 30),
IsAllDay: false
}, {
Id: 21,
Subject: 'Conference - 1',
StartTime: new Date(2017, 10, 7, 22, 0),
EndTime: new Date(2017, 10, 8, 20, 0),
IsAllDay: true
}, {
Id: 22,
Subject: 'Conference - 2',
StartTime: new Date(2017, 10, 7, 22, 0),
EndTime: new Date(2017, 10, 14, 23, 0),
IsAllDay: false
}, {
Id: 23,
Subject: 'Conference - 3',
StartTime: new Date(2017, 10, 8, 9, 30),
EndTime: new Date(2017, 10, 9, 11, 45),
IsAllDay: true
}, {
Id: 24,
Subject: 'Conference - 3 - A',
StartTime: new Date(2017, 10, 8, 9, 30),
EndTime: new Date(2017, 10, 8, 10, 0),
IsAllDay: true
}, {
Id: 25,
Subject: 'Conference - 3 - B',
StartTime: new Date(2017, 10, 8, 10, 0),
EndTime: new Date(2017, 10, 8, 10, 30),
IsAllDay: false
}, {
Id: 26,
Subject: 'Conference - 4',
StartTime: new Date(2017, 10, 8, 10, 30),
EndTime: new Date(2017, 10, 8, 12, 45),
IsAllDay: false
}, {
Id: 27,
Subject: 'Travelling',
StartTime: new Date(2017, 10, 8, 11, 30),
EndTime: new Date(2017, 10, 8, 13, 45),
IsAllDay: false
}, {
Id: 28,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 9, 10, 0),
EndTime: new Date(2017, 10, 9, 12, 30),
IsAllDay: false
}, {
Id: 29,
Subject: 'Conference',
StartTime: new Date(2017, 10, 9, 15, 30),
EndTime: new Date(2017, 10, 9, 18, 45),
IsAllDay: false
}, {
Id: 30,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 10, 10, 15),
EndTime: new Date(2017, 10, 10, 14, 45),
IsAllDay: false
}, {
Id: 31,
Subject: 'Conference',
StartTime: new Date(2017, 10, 11, 9, 30),
EndTime: new Date(2017, 10, 11, 10, 45),
IsAllDay: false
}, {
Id: 32,
Subject: 'Paris',
StartTime: new Date(2017, 10, 12, 10, 0),
EndTime: new Date(2017, 10, 12, 11, 30),
IsAllDay: true
}, {
Id: 33,
Subject: 'Meeting - 1',
StartTime: new Date(2017, 10, 13, 10, 0),
EndTime: new Date(2017, 10, 13, 12, 30),
IsAllDay: false
}, {
Id: 34,
Subject: 'Meeting - 2',
StartTime: new Date(2017, 10, 13, 11, 0),
EndTime: new Date(2017, 10, 13, 14, 30),
IsAllDay: false
}, {
Id: 35,
Subject: 'Conference - 1',
StartTime: new Date(2017, 10, 14, 22, 0),
EndTime: new Date(2017, 10, 15, 2, 30),
IsAllDay: false
}, {
Id: 36,
Subject: 'Conference - 2',
StartTime: new Date(2017, 10, 14, 22, 0),
EndTime: new Date(2017, 10, 15, 0, 0),
IsAllDay: false
}, {
Id: 37,
Subject: 'Conference - 3',
StartTime: new Date(2017, 10, 15, 9, 30),
EndTime: new Date(2017, 10, 15, 11, 45),
IsAllDay: false
}, {
Id: 38,
Subject: 'Conference - 4',
StartTime: new Date(2017, 10, 15, 10, 30),
EndTime: new Date(2017, 10, 15, 12, 45),
IsAllDay: false
}, {
Id: 39,
Subject: 'Travelling',
StartTime: new Date(2017, 10, 15, 11, 30),
EndTime: new Date(2017, 10, 15, 13, 45),
IsAllDay: false
}, {
Id: 40,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 16, 10, 0),
EndTime: new Date(2017, 10, 16, 12, 30),
IsAllDay: false
}, {
Id: 41,
Subject: 'Conference',
StartTime: new Date(2017, 10, 16, 15, 30),
EndTime: new Date(2017, 10, 16, 18, 45),
IsAllDay: false
}, {
Id: 42,
Subject: 'Vacation',
StartTime: new Date(2017, 10, 17, 10, 15),
EndTime: new Date(2017, 10, 17, 14, 45),
IsAllDay: false
}, {
Id: 43,
Subject: 'Conference',
StartTime: new Date(2017, 10, 18, 9, 30),
EndTime: new Date(2017, 10, 18, 10, 45),
IsAllDay: false
}
];
export const blockData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Meeting with CEO',
StartTime: new Date(2017, 9, 30, 10, 0),
EndTime: new Date(2017, 9, 30, 11, 30),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 2,
Subject: 'Holiday',
StartTime: new Date(2017, 10, 1),
EndTime: new Date(2017, 10, 2),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 3,
Subject: 'Vacation',
StartTime: new Date(2017, 9, 22, 11, 0),
EndTime: new Date(2017, 9, 24, 10, 0),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 4,
Subject: 'Server Refreshing',
StartTime: new Date(2017, 10, 4),
EndTime: new Date(2017, 10, 6),
IsAllDay: true,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 5,
Subject: 'Infrastructure Work',
StartTime: new Date(2017, 9, 27, 11, 0),
EndTime: new Date(2017, 9, 29, 9, 0),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 6,
Subject: 'Holiday-Trip',
StartTime: new Date(2017, 10, 8),
EndTime: new Date(2017, 10, 11),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 7,
Subject: 'Refreshment',
StartTime: new Date(2017, 10, 13, 10, 0),
EndTime: new Date(2017, 10, 13, 12, 0),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 8,
Subject: 'General Meeting',
StartTime: new Date(2017, 9, 31, 9, 30),
EndTime: new Date(2017, 9, 31, 11, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 9,
Subject: 'Client Meeting',
StartTime: new Date(2017, 10, 3, 8, 0),
EndTime: new Date(2017, 10, 3, 10, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 10,
Subject: 'Conference',
StartTime: new Date(2017, 10, 2, 13, 30),
EndTime: new Date(2017, 10, 2, 14, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 11,
Subject: 'Review',
StartTime: new Date(2017, 9, 25, 11, 15),
EndTime: new Date(2017, 9, 25, 13, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 12,
Subject: 'Shopping',
StartTime: new Date(2017, 9, 26, 8, 30),
EndTime: new Date(2017, 9, 26, 10, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 13,
Subject: 'Review-2',
StartTime: new Date(2017, 10, 7, 11, 15),
EndTime: new Date(2017, 10, 7, 13, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 14,
Subject: 'Greetings',
StartTime: new Date(2017, 10, 7, 8, 30),
EndTime: new Date(2017, 10, 7, 10, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 15,
Subject: 'Vacation',
StartTime: new Date(2017, 9, 29, 11, 0),
EndTime: new Date(2017, 9, 31, 10, 0),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 16,
Subject: 'Holiday-Trip',
StartTime: new Date(2017, 10, 2),
EndTime: new Date(2017, 10, 5),
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 17,
Subject: 'Refreshment',
StartTime: new Date(2017, 9, 30, 10, 0),
EndTime: new Date(2017, 9, 30, 12, 0),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
IsAllDay: false,
IsBlock: true,
HallId: 1,
RoomId: 2,
OwnerId: 2
}, {
Id: 18,
Subject: 'Review',
StartTime: new Date(2017, 9, 31, 11, 15),
EndTime: new Date(2017, 9, 31, 13, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 19,
Subject: 'Shopping',
StartTime: new Date(2017, 9, 29, 8, 30),
EndTime: new Date(2017, 9, 29, 10, 45),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 20,
Subject: 'Review-2',
StartTime: new Date(2017, 10, 1, 12, 0),
EndTime: new Date(2017, 10, 1, 13, 45),
IsAllDay: false,
HallId: 1,
RoomId: 2,
OwnerId: 2
}, {
Id: 21,
Subject: 'Greetings',
StartTime: new Date(2017, 10, 2, 8, 30),
EndTime: new Date(2017, 10, 2, 10, 0),
IsAllDay: false,
HallId: 1,
RoomId: 2,
OwnerId: 2
}
];
const msPerDay: number = 86400000;
const msPerHour: number = 3600000;
const currentTime: number = new Date().setMinutes(0, 0, 0);
export const readonlyEventsData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Project Workflow Analysis',
StartTime: new Date(currentTime + msPerDay * -2 + msPerHour * 2),
EndTime: new Date(currentTime + msPerDay * -2 + msPerHour * 4),
IsReadonly: true
}, {
Id: 2,
Subject: 'Project Requirement Planning',
StartTime: new Date(currentTime + msPerDay * -1 + msPerHour * 2),
EndTime: new Date(currentTime + msPerDay * -1 + msPerHour * 4),
IsReadonly: true
}, {
Id: 3,
Subject: 'Meeting with Developers',
StartTime: new Date(currentTime + msPerDay * -1 + msPerHour * -3),
EndTime: new Date(currentTime + msPerDay * -1 + msPerHour * -1),
IsReadonly: true
}, {
Id: 4,
Subject: 'Team Fun Activities',
StartTime: new Date(currentTime + msPerHour * -4),
EndTime: new Date(currentTime + msPerHour * -2),
IsReadonly: true
}, {
Id: 5,
Subject: 'Quality Analysis',
StartTime: new Date(currentTime + msPerHour * 1),
EndTime: new Date(currentTime + msPerHour * 3),
IsReadonly: true
}, {
Id: 6,
Subject: 'Customer meeting – John Mackenzie',
StartTime: new Date(currentTime + msPerHour * 5),
EndTime: new Date(currentTime + msPerHour * 6),
IsReadonly: false
}, {
Id: 7,
Subject: 'Meeting with Core team',
StartTime: new Date(currentTime + msPerHour * 9),
EndTime: new Date(currentTime + msPerHour * 10),
IsReadonly: false
}, {
Id: 8,
Subject: 'Project Review',
StartTime: new Date(currentTime + msPerDay * 1 + msPerHour * 3),
EndTime: new Date(currentTime + msPerDay * 1 + msPerHour * 5),
IsReadonly: false
}, {
Id: 9,
Subject: 'Project demo meeting with Andrew',
StartTime: new Date(currentTime + msPerDay * 1 + msPerHour * -4),
EndTime: new Date(currentTime + msPerDay * 1 + msPerHour * -3),
IsReadonly: false
}, {
Id: 10,
Subject: 'Online Hosting of Project',
StartTime: new Date(currentTime + msPerDay * 2 + msPerHour * 4),
EndTime: new Date(currentTime + msPerDay * 2 + msPerHour * 6),
IsReadonly: false
}
];
export const dragResizeData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Paris Conference',
StartTime: new Date(2018, 6, 1, 10, 0),
EndTime: new Date(2018, 6, 1, 11, 30),
IsAllDay: false,
RoomId: 1,
OwnerId: 1
}, {
Id: 2,
Subject: 'Daily Meeting',
StartTime: new Date(2018, 6, 2, 11, 15),
EndTime: new Date(2018, 6, 2, 12, 30),
AllDay: false,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
RoomId: 1,
OwnerId: 3
}, {
Id: 3,
Subject: 'General Meeting',
StartTime: new Date(2018, 6, 3, 11, 0),
EndTime: new Date(2018, 6, 3, 12, 45),
IsAllDay: false,
RoomId: 2,
OwnerId: 2
}, {
Id: 4,
Subject: 'Board Meeting',
StartTime: new Date(2018, 6, 4, 9, 0),
EndTime: new Date(2018, 6, 4, 11, 0),
IsAllDay: false,
RoomId: 1,
OwnerId: 1
}, {
Id: 5,
Subject: 'Holiday',
StartTime: new Date(2018, 6, 5, 10, 30),
EndTime: new Date(2018, 6, 5, 11, 30),
IsAllDay: false,
RoomId: 1,
OwnerId: 3
}, {
Id: 6,
Subject: 'Vacation',
StartTime: new Date(2018, 6, 6, 12, 15),
EndTime: new Date(2018, 6, 6, 13, 30),
IsAllDay: false,
RoomId: 2,
OwnerId: 2
}, {
Id: 7,
Subject: 'Entertainment',
StartTime: new Date(2018, 6, 7, 11, 0),
EndTime: new Date(2018, 6, 7, 12, 30),
IsAllDay: false,
RoomId: 1,
OwnerId: 1
}, {
Id: 8,
Subject: 'Event 1',
StartTime: new Date(2018, 6, 2),
EndTime: new Date(2018, 6, 3),
IsAllDay: true,
RoomId: 1,
OwnerId: 1
}, {
Id: 9,
Subject: 'Event 2',
StartTime: new Date(2018, 6, 4),
EndTime: new Date(2018, 6, 6),
IsAllDay: true,
RoomId: 1,
OwnerId: 3
}, {
Id: 10,
Subject: 'Event 3',
StartTime: new Date(2018, 6, 6, 10),
EndTime: new Date(2018, 6, 8, 11),
IsAllDay: false,
RoomId: 2,
OwnerId: 2
}
];
export const stringData: Record<string, any>[] = [
{
Id: '1',
Subject: 'Event1',
StartTime: new Date(2017, 9, 31, 10, 0),
EndTime: new Date(2017, 9, 31, 11, 0)
},
{
Id: '2',
Subject: 'Event2',
StartTime: new Date(2017, 9, 29, 10, 0),
EndTime: new Date(2017, 9, 29, 11, 0)
},
{
Id: '3',
Subject: 'Event3',
StartTime: new Date(2017, 9, 30, 10, 0),
EndTime: new Date(2017, 9, 30, 11, 0)
},
{
Id: 'recEvent',
Subject: 'Event4',
StartTime: new Date(2017, 9, 30, 12, 0),
EndTime: new Date(2017, 9, 30, 13, 0),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5'
}
];
export const sampleData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Explosion of Betelgeuse Star',
StartTime: new Date(2018, 1, 16, 9, 30),
EndTime: new Date(2018, 1, 16, 11, 0),
CategoryColor: '#1aaa55'
}, {
Id: 2,
Subject: 'Thule Air Crash Report',
StartTime: new Date(2018, 1, 12, 12, 0),
EndTime: new Date(2018, 1, 12, 14, 0),
CategoryColor: '#357cd2'
}, {
Id: 3,
Subject: 'Blue Moon Eclipse',
StartTime: new Date(2018, 1, 13, 9, 30),
EndTime: new Date(2018, 1, 13, 11, 0),
CategoryColor: '#7fa900'
}, {
Id: 4,
Subject: 'Meteor Showers in 2018',
StartTime: new Date(2018, 1, 14, 13, 0),
EndTime: new Date(2018, 1, 14, 14, 30),
CategoryColor: '#ea7a57'
}, {
Id: 5,
Subject: 'Milky Way as Melting pot',
StartTime: new Date(2018, 1, 15, 12, 0),
EndTime: new Date(2018, 1, 15, 14, 0),
CategoryColor: '#00bdae'
}, {
Id: 6,
Subject: 'Mysteries of Bermuda Triangle',
StartTime: new Date(2018, 1, 15, 9, 30),
EndTime: new Date(2018, 1, 15, 11, 0),
CategoryColor: '#f57f17'
}];
export const tooltipData: Record<string, any>[] = [
{
Id: 1,
StartTime: new Date(2017, 11, 31, 10, 0),
EndTime: new Date(2018, 0, 1, 11, 30),
IsAllDay: false,
Description: 'Tooltip Testing',
Location: 'Chennai'
}, {
Id: 2,
Subject: 'AllDay Event',
StartTime: new Date(2018, 0, 1),
EndTime: new Date(2018, 0, 2),
IsAllDay: true,
Description: 'Tooltip Testing',
Location: 'Chennai'
}, {
Id: 3,
Subject: 'Normal Event',
StartTime: new Date(2018, 0, 3, 10, 0),
EndTime: new Date(2018, 0, 3, 11, 0),
IsAllDay: false,
Description: 'Tooltip Testing'
}, {
Id: 4,
Subject: 'AllDay Spanned Event',
StartTime: new Date(2018, 0, 6, 10, 0),
EndTime: new Date(2018, 0, 8, 10, 30),
IsAllDay: false,
Description: 'Tooltip Testing',
Location: 'Chennai'
}, {
Id: 5,
Subject: 'Normal Spanned Event',
StartTime: new Date(2018, 0, 4, 10, 0),
EndTime: new Date(2018, 0, 5, 9, 30),
IsAllDay: false,
Description: 'Tooltip Testing',
Location: 'Chennai'
}
];
export const timezoneData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Paris',
StartTime: new Date(2017, 9, 16, 10, 0),
EndTime: new Date(2017, 9, 16, 11, 30),
IsAllDay: true,
Location: 'India',
Description: 'Summer vacation planned for outstation.',
StartTimezone: 'America/New_York',
EndTimezone: 'America/New_York'
}, {
Id: 2,
Subject: 'Meeting - 1',
StartTime: new Date(2017, 9, 17, 10, 0),
EndTime: new Date(2017, 9, 19, 12, 30),
IsAllDay: false,
StartTimezone: 'America/New_York'
}, {
Id: 3,
Subject: 'Meeting - 2',
StartTime: new Date(2017, 9, 19, 14, 0),
EndTime: new Date(2017, 9, 19, 16, 30),
IsAllDay: false,
EndTimezone: 'America/New_York'
}, {
Id: 4,
Subject: 'Conference - 1',
StartTime: new Date(2017, 9, 20, 9, 30),
EndTime: new Date(2017, 9, 20, 10, 45),
IsAllDay: false
}
];
export const testBlockData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Block Event',
StartTime: new Date(2017, 10, 2, 10),
IsBlock: true,
EndTime: new Date(2017, 10, 2, 12)
}, {
Id: 2,
Subject: 'Spanned - Less than 24 hour',
StartTime: new Date(2017, 10, 1, 12, 30),
EndTime: new Date(2017, 10, 2, 1, 30)
}, {
Id: 3,
Subject: 'Spanned - Greater than 24 hour',
StartTime: new Date(2017, 10, 1, 2),
EndTime: new Date(2017, 10, 8, 4)
}, {
Id: 4,
Subject: 'Allday event',
StartTime: new Date(2017, 10, 3),
EndTime: new Date(2017, 10, 4),
IsAllDay: true
}, {
Id: 5,
Subject: 'Allday Spanned event',
StartTime: new Date(2017, 10, 3),
EndTime: new Date(2017, 10, 10),
IsAllDay: true
}, {
Id: 6,
Subject: 'Allday across the month',
StartTime: new Date(2017, 10, 16),
EndTime: new Date(2018, 0, 1),
IsAllDay: true
}, {
Id: 7,
Subject: 'Recurrence every 2 days',
StartTime: new Date(2017, 10, 13, 11),
EndTime: new Date(2017, 10, 13, 12),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=2;COUNT=1'
}
];
export const testData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Normal Event',
StartTime: new Date(2017, 10, 2, 10),
EndTime: new Date(2017, 10, 2, 12)
}, {
Id: 2,
Subject: 'Spanned - Less than 24 hour',
StartTime: new Date(2017, 10, 1, 12, 30),
EndTime: new Date(2017, 10, 2, 1, 30)
}, {
Id: 3,
Subject: 'Spanned - Greater than 24 hour',
StartTime: new Date(2017, 10, 1, 2),
EndTime: new Date(2017, 10, 8, 4)
}, {
Id: 4,
Subject: 'Allday event',
StartTime: new Date(2017, 10, 3),
EndTime: new Date(2017, 10, 4),
IsAllDay: true
}, {
Id: 5,
Subject: 'Allday Spanned event',
StartTime: new Date(2017, 10, 3),
EndTime: new Date(2017, 10, 10),
IsAllDay: true
}, {
Id: 6,
Subject: 'Allday across the month',
StartTime: new Date(2017, 10, 16),
EndTime: new Date(2018, 0, 1),
IsAllDay: true
}, {
Id: 7,
Subject: 'Recurrence every 2 days',
StartTime: new Date(2017, 10, 13, 11),
EndTime: new Date(2017, 10, 13, 12),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=2;COUNT=1'
}
];
/**
* Method to generate resources dynamically
*
* @param {number} startId Accepts start Id
* @param {number} endId Accepts end Id
* @param {string} text Accepts resource anme
* @param {boolean} isAddGroupId Accepts the level grouping
* @param {number} groupStartId Accepts the group start Id
* @param {number} groupEndId Accepts the group end Id
* @returns {Object[]} Returns the collection of resource datas
* @private
*/
export function generateResourceData(startId: number = 1, endId: number = 100, text: string = '', isAddGroupId: boolean = false, groupStartId?: number, groupEndId?: number): Record<string, any>[] {
const data: Record<string, any>[] = [];
const resData: Record<string, any>[] = [
{ text: 'Nancy', color: '#ffaa00' },
{ text: 'Steven', color: '#f8a398' },
{ text: 'Michael', color: '#7499e1' }
];
for (let a: number = startId; a <= endId; a++) {
const n: number = Math.floor(Math.random() * resData.length);
data.push({ Id: a, Text: text + a + '', Color: resData[n].color });
}
if (isAddGroupId) {
let i: number = groupStartId;
for (const d of data) {
d.GroupID = i; // Math.floor(Math.random() * (groupEndId - groupStartId+1) + groupStartId);
d.Text += '_' + d.GroupID;
i++;
if (i > groupEndId) {
i = groupStartId;
}
}
}
return data;
}
/**
* Methods to add resource fields
*
* @param {Object[]} eventData Accepts the collection of datas
* @param {string} field Accepts the field name
* @param {number} start Accepts the start number ID
* @param {number} end Accepts the end number ID
* @param {string} groupField Accepts the group field
* @param {number} groupStart Accepts the group start ID
* @param {number} groupEnd Accepts the group end ID
* @param {Object[]} resData Accepts the collection of datas
* @returns {void}
* @private
*/
// eslint-disable-next-line max-len
export function addResourceField(eventData: Record<string, any>[], field: string, start: number, end: number, groupField?: string, groupStart?: number, groupEnd?: number, resData?: Record<string, any>[]): void {
if (!groupField) {
let i: number = start;
for (const data of eventData) {
data[field] = i;
i++;
if (i > end) {
i = start;
}
}
} else {
const dm: DataManager = new DataManager({ json: eventData });
const dm1: DataManager = new DataManager({ json: resData });
for (let a: number = groupStart; a <= groupEnd; a++) {
const eve: Record<string, any>[] = dm.executeLocal(new Query().where(groupField, 'equal', a)) as Record<string, any>[];
const filteredRes: Record<string, any>[] = dm1.executeLocal(new Query().where('GroupID', 'equal', a).select(['Id'])) as Record<string, any>[];
const possibleIds: number[] = (filteredRes as Record<string, any>[]).map((a: Record<string, any>) => a.Id as number);
const addField: CallbackFunction = (events: Record<string, any>[], list: number[]) => {
let index: number = 0;
for (let i: number = 0; i < events.length; i++) {
events[i][field] = list[index];
index++;
if (index >= list.length) {
index = 0;
}
}
};
addField(eve, possibleIds);
}
}
}
/**
* Method to generate events data dynamically
*
* @param {Date} startDate Accepts the start date
* @param {Date} endDate Accepts the end date
* @param {number} eventCount Accepts the event count
* @returns {Object[]} Returns the collection of event datas
* @private
*/
export function generateEventData(startDate: Date, endDate: Date, eventCount: number): Record<string, any>[] {
const data: Record<string, any>[] = [];
const names: string[] = [
'Bering Sea Gold', 'Technology', 'Maintenance', 'Meeting', 'Travelling', 'Annual Conference', 'Birthday Celebration',
'Farewell Celebration', 'Wedding Aniversary', 'Alaska: The Last Frontier', 'Deadest Catch', 'Sports Day',
'MoonShiners', 'Close Encounters', 'HighWay Thru Hell', 'Daily Planet', 'Cash Cab', 'Basketball Practice',
'Rugby Match', 'Guitar Class', 'Music Lessons', 'Doctor checkup', 'Brazil - Mexico', 'Opening ceremony', 'Final presentation'
];
const msPerHour: number = 1000 * 60 * 60;
let id: number = 1;
const incMs: number = (msPerHour * 24) * 1;
const generate: CallbackFunction = () => {
const start: number = startDate.getTime();
const end: number = endDate.getTime();
for (let a: number = start; a < end; a += incMs) {
const count: number = Math.floor((Math.random() * 9) + 1);
for (let b: number = 0; b < count; b++) {
const hour: number = Math.floor(Math.random() * 100) % 24;
const minutes: number = Math.round((Math.floor(Math.random() * 100) % 60) / 5) * 5;
const nCount: number = Math.floor(Math.random() * names.length);
const startDate: Date = new Date(new Date(a).setHours(hour, minutes));
const endDate: Date = new Date(startDate.getTime() + (msPerHour * 2.5));
data.push({
Id: id,
Subject: names[nCount],
StartTime: startDate,
EndTime: endDate,
IsAllDay: (id % 10) ? false : true
});
if (data.length >= eventCount) {
return;
}
id++;
}
}
};
while (data.length < eventCount) {
generate();
}
return data;
}
/**
* Method to clone the datasource objects
*
* @param {Object[]} datas Accepts the original datasource
* @returns {Object[]} Returns the cloned datasource
* @private
*/
export function cloneDataSource(datas: Record<string, any>[]): Record<string, any>[] {
const dataSrc: Record<string, any>[] = [];
for (const data of datas) {
dataSrc.push(extend({}, data) as Record<string, any>);
}
return dataSrc;
}
/**
* Method to generate events data dynamically
*
* @returns {Object[]} Returns the collection of event datas
* @private
*/
export function generateObject(): Record<string, any>[] {
const data: Record<string, any>[] = [];
const names: string[] = [
'Bering Sea Gold', 'Technology', 'Maintenance', 'Meeting', 'Travelling', 'Annual Conference', 'Birthday Celebration',
'Farewell Celebration', 'Wedding Aniversary', 'Alaska: The Last Frontier', 'Deadest Catch', 'Sports Day',
'MoonShiners', 'Close Encounters', 'HighWay Thru Hell', 'Daily Planet', 'Cash Cab', 'Basketball Practice',
'Rugby Match', 'Guitar Class', 'Music Lessons', 'Doctor checkup', 'Brazil - Mexico', 'Opening ceremony', 'Final presentation'
];
const start: number = new Date(2017, 0, 1).getTime();
const end: number = new Date(2018, 11, 31).getTime();
const dayCount: number = 1000 * 60 * 60;
for (let a: number = start, id: number = 3; a < end; a += (dayCount * 24) * 2) {
const count: number = Math.floor((Math.random() * 9) + 1);
for (let b: number = 0; b < count; b++) {
const hour: number = Math.floor(Math.random() * 100) % 24;
const minutes: number = Math.round((Math.floor(Math.random() * 100) % 60) / 5) * 5;
const nCount: number = Math.floor(Math.random() * names.length);
const startDate: Date = new Date(new Date(a).setHours(hour, minutes));
const endDate: Date = new Date(startDate.getTime() + (dayCount * 2.5));
data.push({
Id: id,
Subject: names[nCount],
StartTime: startDate,
EndTime: endDate,
IsAllDay: (id % 10) ? false : true
});
id++;
}
}
const longerEvent: Record<string, any> = {
Id: 0,
StartTime: new Date(2017, 0, 1),
EndTime: new Date(2017, 0, 10),
IsAllDay: true,
Location: 'Chennai'
};
const occurrenceEvent: Record<string, any> = {
Id: 1,
StartTime: new Date(2017, 0, 1),
EndTime: new Date(2017, 0, 10),
IsAllDay: true,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
RecurrenceId: 0
};
const recurrenceEvent: Record<string, any> = {
Id: 2,
StartTime: new Date(2017, 0, 1),
EndTime: new Date(2017, 0, 10),
IsAllDay: true,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1'
};
data.push(longerEvent);
data.push(occurrenceEvent);
data.push(recurrenceEvent);
return data;
}
export const resourceData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Nancy',
StartTime: new Date(2018, 3, 1, 10, 0),
EndTime: new Date(2018, 3, 1, 12, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 2,
Subject: 'Michael',
StartTime: new Date(2018, 3, 1, 10, 0),
EndTime: new Date(2018, 3, 1, 12, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 3,
Subject: 'Steven',
StartTime: new Date(2018, 3, 1, 10, 0),
EndTime: new Date(2018, 3, 1, 12, 30),
IsAllDay: false,
HallId: 1,
RoomId: 2,
OwnerId: 2
}, {
Id: 4,
Subject: 'Meeting',
StartTime: new Date(2018, 3, 4, 14, 0),
EndTime: new Date(2018, 3, 4, 15, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 5,
Subject: 'Conference',
StartTime: new Date(2018, 3, 3, 8, 0),
EndTime: new Date(2018, 3, 3, 9, 30),
IsAllDay: false,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 6,
Subject: 'Break Time',
StartTime: new Date(2018, 3, 5, 13, 0),
EndTime: new Date(2018, 3, 5, 14, 0),
IsAllDay: false,
HallId: 1,
RoomId: 2,
OwnerId: 2
}, {
Id: 7,
Subject: 'Holiday',
StartTime: new Date(2018, 3, 5),
EndTime: new Date(2018, 3, 7),
IsAllDay: true,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 8,
Subject: 'Sick Leave',
StartTime: new Date(2018, 3, 5),
EndTime: new Date(2018, 3, 6),
IsAllDay: true,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 9,
Subject: 'Weekend',
StartTime: new Date(2018, 3, 7),
EndTime: new Date(2018, 3, 9),
IsAllDay: true,
HallId: 1,
RoomId: 2,
OwnerId: 2
}
];
export const resourceGroupData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Meeting',
StartTime: new Date(2018, 3, 1, 10, 0),
EndTime: new Date(2018, 3, 1, 12, 30),
IsAllDay: false,
RoomId: [1, 2],
OwnerId: [1, 2, 3]
}, {
Id: 2,
Subject: 'Conference',
StartTime: new Date(2018, 3, 4, 12, 0),
EndTime: new Date(2018, 3, 4, 13, 30),
IsAllDay: false,
RoomId: [1],
OwnerId: [1, 3]
}, {
Id: 3,
Subject: 'Travelling',
StartTime: new Date(2018, 3, 5),
EndTime: new Date(2018, 3, 7),
IsAllDay: true,
RoomId: [1, 2],
OwnerId: [1, 2]
}, {
Id: 4,
Subject: 'Events - Within a day',
StartTime: new Date(2018, 4, 1, 10, 0),
EndTime: new Date(2018, 4, 1, 12, 30),
IsAllDay: false,
RoomId: [2, 3],
OwnerId: [2, 3]
}, {
Id: 5,
Subject: 'Spanned Event - Less than 24',
StartTime: new Date(2018, 3, 30, 18, 0),
EndTime: new Date(2018, 4, 1, 10, 30),
IsAllDay: false,
RoomId: [1, 2],
OwnerId: [4, 2]
}, {
Id: 6,
Subject: 'Spanned Event - Greater than 24',
StartTime: new Date(2018, 4, 1, 18, 0),
EndTime: new Date(2018, 4, 3, 10, 30),
IsAllDay: false,
RoomId: [3],
OwnerId: [6, 3]
}, {
Id: 7,
Subject: 'Spanned Event - Previous week',
StartTime: new Date(2018, 3, 27, 15, 0),
EndTime: new Date(2018, 3, 30, 12, 30),
IsAllDay: false,
RoomId: [2],
OwnerId: [5, 8]
}, {
Id: 8,
Subject: 'Spanned Event - Same week',
StartTime: new Date(2018, 3, 30, 10, 0),
EndTime: new Date(2018, 4, 3, 13, 0),
IsAllDay: false,
RoomId: [2, 3],
OwnerId: [2, 5, 9]
}, {
Id: 9,
Subject: 'Spanned Event - Next week',
StartTime: new Date(2018, 4, 2, 15, 30),
EndTime: new Date(2018, 4, 8, 18, 0),
IsAllDay: false,
RoomId: [1],
OwnerId: [6]
}, {
Id: 10,
Subject: 'Recurrence Event - Previous week',
StartTime: new Date(2018, 3, 28, 10, 15),
EndTime: new Date(2018, 4, 1, 11, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=SA;INTERVAL=1;COUNT=3',
IsAllDay: false,
RoomId: [1, 3],
OwnerId: [4, 6, 7, 10]
}, {
Id: 11,
Subject: 'All Day Event - Current date',
StartTime: new Date(2018, 4, 1),
EndTime: new Date(2018, 4, 2),
IsAllDay: true,
RoomId: [3],
OwnerId: [3, 6, 9]
}, {
Id: 12,
Subject: 'All Day Event - Previous week',
StartTime: new Date(2018, 3, 26, 10, 0),
EndTime: new Date(2018, 3, 30, 11, 30),
IsAllDay: true,
RoomId: [1],
OwnerId: [1, 4, 7]
}, {
Id: 13,
Subject: 'All Day Event - Next week',
StartTime: new Date(2018, 4, 4, 10, 0),
EndTime: new Date(2018, 4, 8, 11, 30),
IsAllDay: true,
RoomId: [2],
OwnerId: [2, 5, 8]
}, {
Id: 14,
Subject: 'Recurrence Event - Same day',
StartTime: new Date(2018, 4, 1, 10, 15),
EndTime: new Date(2018, 4, 1, 14, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false,
RoomId: [1, 2],
OwnerId: [1, 8, 10]
}, {
Id: 15,
Subject: 'Recurrence Event - Less than 24',
StartTime: new Date(2018, 4, 3, 15, 0),
EndTime: new Date(2018, 4, 4, 10, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false,
RoomId: [1, 3],
OwnerId: [7, 10]
}, {
Id: 16,
Subject: 'Recurrence Event - Greater than 24',
StartTime: new Date(2018, 3, 30, 15, 0),
EndTime: new Date(2018, 4, 2, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO;INTERVAL=1;COUNT=3',
IsAllDay: false,
RoomId: [1, 2, 3],
OwnerId: [2, 4, 10, 7]
}, {
Id: 17,
Subject: 'Recurrence Event - Next week',
StartTime: new Date(2018, 4, 3, 2, 0),
EndTime: new Date(2018, 4, 7, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=FR;INTERVAL=1;COUNT=5',
IsAllDay: false,
RoomId: [1, 2, 3],
OwnerId: [1, 2, 3]
}, {
Id: 18,
Subject: 'Recurrence Event - Same day',
StartTime: new Date(2018, 4, 1, 10, 15),
EndTime: new Date(2018, 4, 1, 14, 45),
IsAllDay: false,
RoomId: [1, 2, 3],
OwnerId: [2, 4, 6]
}
];
export const timelineData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Events - Within a day',
StartTime: new Date(2018, 4, 1, 10, 0),
EndTime: new Date(2018, 4, 1, 12, 30),
IsAllDay: false
}, {
Id: 2,
Subject: 'Spanned Event - Less than 24',
StartTime: new Date(2018, 3, 30, 18, 0),
EndTime: new Date(2018, 4, 1, 10, 30),
IsAllDay: false
}, {
Id: 3,
Subject: 'Spanned Event - Greater than 24',
StartTime: new Date(2018, 4, 1, 18, 0),
EndTime: new Date(2018, 4, 3, 10, 30),
IsAllDay: false
}, {
Id: 4,
Subject: 'Spanned Event - Previous week',
StartTime: new Date(2018, 3, 27, 15, 0),
EndTime: new Date(2018, 3, 30, 12, 30),
IsAllDay: false
}, {
Id: 5,
Subject: 'Spanned Event - Same week',
StartTime: new Date(2018, 3, 30, 10, 0),
EndTime: new Date(2018, 4, 3, 13, 0),
IsAllDay: false
}, {
Id: 6,
Subject: 'Spanned Event - Next week',
StartTime: new Date(2018, 4, 2, 15, 30),
EndTime: new Date(2018, 4, 8, 18, 0),
IsAllDay: false
}, {
Id: 7,
Subject: 'Recurrence Event - Previous week',
StartTime: new Date(2018, 3, 28, 10, 15),
EndTime: new Date(2018, 4, 1, 11, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=SA;INTERVAL=1;COUNT=3',
IsAllDay: false
}, {
Id: 8,
Subject: 'All Day Event - Current date',
StartTime: new Date(2018, 4, 1),
EndTime: new Date(2018, 4, 2),
IsAllDay: true
}, {
Id: 9,
Subject: 'All Day Event - Previous week',
StartTime: new Date(2018, 3, 26, 10, 0),
EndTime: new Date(2018, 3, 30, 11, 30),
IsAllDay: true
}, {
Id: 10,
Subject: 'All Day Event - Next week',
StartTime: new Date(2018, 4, 4, 10, 0),
EndTime: new Date(2018, 4, 8, 11, 30),
IsAllDay: true
}, {
Id: 11,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 12,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 13,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 14,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 15,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 16,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 17,
Subject: 'Same Time',
StartTime: new Date(2018, 4, 1, 13, 0),
EndTime: new Date(2018, 4, 1, 14, 0),
IsAllDay: false
}, {
Id: 18,
Subject: 'Recurrence Event - Same day',
StartTime: new Date(2018, 4, 1, 10, 15),
EndTime: new Date(2018, 4, 1, 14, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false
}, {
Id: 19,
Subject: 'Recurrence Event - Less than 24',
StartTime: new Date(2018, 4, 3, 15, 0),
EndTime: new Date(2018, 4, 4, 10, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false
}, {
Id: 20,
Subject: 'Recurrence Event - Greater than 24',
StartTime: new Date(2018, 3, 30, 15, 0),
EndTime: new Date(2018, 4, 2, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO;INTERVAL=1;COUNT=3',
IsAllDay: false
}, {
Id: 21,
Subject: 'Recurrence Event - Next week',
StartTime: new Date(2018, 4, 3, 2, 0),
EndTime: new Date(2018, 4, 7, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=FR;INTERVAL=1;COUNT=3',
IsAllDay: false
}
];
export const timelineResourceData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Events - Within a day',
StartTime: new Date(2018, 4, 1, 10, 0),
EndTime: new Date(2018, 4, 1, 12, 30),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 1
}, {
Id: 2,
Subject: 'Spanned Event - Less than 24',
StartTime: new Date(2018, 3, 30, 18, 0),
EndTime: new Date(2018, 4, 1, 10, 30),
IsAllDay: false,
FId: 2,
HallId: 2,
RoomId: 2,
OwnerId: 2
}, {
Id: 3,
Subject: 'Spanned Event - Greater than 24',
StartTime: new Date(2018, 4, 1, 18, 0),
EndTime: new Date(2018, 4, 3, 10, 30),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 3
}, {
Id: 4,
Subject: 'Spanned Event - Previous week',
StartTime: new Date(2018, 3, 27, 15, 0),
EndTime: new Date(2018, 3, 30, 12, 30),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 4
}, {
Id: 5,
Subject: 'Spanned Event - Same week',
StartTime: new Date(2018, 3, 30, 10, 0),
EndTime: new Date(2018, 4, 3, 13, 0),
IsAllDay: false,
FId: 2,
HallId: 2,
RoomId: 2,
OwnerId: 5
}, {
Id: 6,
Subject: 'Spanned Event - Next week',
StartTime: new Date(2018, 4, 2, 15, 30),
EndTime: new Date(2018, 4, 8, 18, 0),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 6
}, {
Id: 7,
Subject: 'Recurrence Event - Previous week',
StartTime: new Date(2018, 3, 28, 10, 15),
EndTime: new Date(2018, 4, 1, 11, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=SA;INTERVAL=1;COUNT=3',
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 7
}, {
Id: 8,
Subject: 'All Day Event - Current date',
StartTime: new Date(2018, 4, 1),
EndTime: new Date(2018, 4, 2),
IsAllDay: true,
FId: 2,
HallId: 2,
RoomId: 2,
OwnerId: 8
}, {
Id: 9,
Subject: 'All Day Event - Previous week',
StartTime: new Date(2018, 3, 26, 10, 0),
EndTime: new Date(2018, 3, 30, 11, 30),
IsAllDay: true,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 9
}, {
Id: 10,
Subject: 'All Day Event - Next week',
StartTime: new Date(2018, 4, 4, 10, 0),
EndTime: new Date(2018, 4, 8, 11, 30),
IsAllDay: true,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 10
}, {
Id: 11,
Subject: 'Recurrence Event - Same day',
StartTime: new Date(2018, 4, 1, 10, 15),
EndTime: new Date(2018, 4, 1, 14, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 10
}, {
Id: 12,
Subject: 'Recurrence Event - Less than 24',
StartTime: new Date(2018, 4, 3, 15, 0),
EndTime: new Date(2018, 4, 4, 10, 45),
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=3',
IsAllDay: false,
FId: 2,
HallId: 2,
RoomId: 2,
OwnerId: 5
}, {
Id: 13,
Subject: 'Recurrence Event - Greater than 24',
StartTime: new Date(2018, 3, 30, 15, 0),
EndTime: new Date(2018, 4, 2, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=MO;INTERVAL=1;COUNT=3',
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 4
}, {
Id: 14,
Subject: 'Recurrence Event - Next week',
StartTime: new Date(2018, 4, 3, 2, 0),
EndTime: new Date(2018, 4, 7, 16, 45),
RecurrenceRule: 'FREQ=WEEKLY;BYDAY=FR;INTERVAL=1;COUNT=3',
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 6
}, {
Id: 15,
Subject: 'Recurrence Event - Same day',
StartTime: new Date(2018, 4, 1, 10, 15),
EndTime: new Date(2018, 4, 1, 14, 45),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 10
}
];
export const levelBasedData: Record<string, any>[] = [
{
Id: 1,
Subject: 'Events - Within a day',
StartTime: new Date(2018, 4, 1, 10, 0),
EndTime: new Date(2018, 4, 1, 12, 30),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1
}, {
Id: 2,
Subject: 'Spanned Event - Less than 24',
StartTime: new Date(2018, 3, 30, 18, 0),
EndTime: new Date(2018, 4, 1, 10, 30),
IsAllDay: false,
FId: 2,
HallId: 2,
RoomId: 2
}, {
Id: 3,
Subject: 'Spanned Event - Greater than 24',
StartTime: new Date(2018, 4, 1, 18, 0),
EndTime: new Date(2018, 4, 3, 10, 30),
IsAllDay: false,
FId: 1
}, {
Id: 4,
Subject: 'Spanned Event - Previous week',
StartTime: new Date(2018, 3, 27, 15, 0),
EndTime: new Date(2018, 4, 2, 12, 30),
IsAllDay: false,
FId: 1,
HallId: 1
}, {
Id: 5,
Subject: 'Recurrence Event',
StartTime: new Date(2018, 4, 1, 10, 0),
EndTime: new Date(2018, 4, 1, 13, 0),
IsAllDay: false,
RecurrenceRule: 'FREQ=DAILY;INTERVAL=1;COUNT=5',
FId: 2,
HallId: 2,
RoomId: 2,
OwnerId: 4
}, {
Id: 6,
Subject: 'Spanned Event - Next week',
StartTime: new Date(2018, 4, 1, 15, 30),
EndTime: new Date(2018, 4, 8, 18, 0),
IsAllDay: false,
FId: 1,
HallId: 1,
RoomId: 1,
OwnerId: 1
}
];
export const moreIndicatorData: Record<string, any>[] = [{
Id: 2,
Subject: 'id 2',
StartTime: new Date(2021, 1, 17, 0, 0),
EndTime: new Date(2021, 1, 18, 0, 0),
IsAllDay: true,
GroupId: 2
},
{
Id: 3,
Subject: 'id 3',
StartTime: new Date(2021, 1, 14, 0, 0),
EndTime: new Date(2021, 1, 18, 0, 0),
IsAllDay: true,
GroupId: 2
},
{
Id: 4,
Subject: 'id 4',
StartTime: new Date(2021, 1, 10, 0, 0),
EndTime: new Date(2021, 1, 16, 0, 0),
IsAllDay: true,
GroupId: 2
},
{
Id: 5,
Subject: 'id 5',
StartTime: new Date(2021, 1, 10, 0, 0),
EndTime: new Date(2021, 1, 17, 0, 0),
IsAllDay: true,
GroupId: 2
},
{
Id: 1,
Subject: 'id 1',
StartTime: new Date(2021, 1, 13, 0, 0),
EndTime: new Date(2021, 1, 19, 0, 0),
IsAllDay: true,
GroupId: 2
},
{
Id: 7,
Subject: 'id 6',
StartTime: new Date(2021, 1, 13, 0, 0),
EndTime: new Date(2021, 1, 19, 0, 0),
IsAllDay: true,
GroupId: 2
}];
/**
* Method to generate data for year view
*
* @param {number} count Accepts the number of events data count
* @param {Date} date Accepts the event start date
* @param {number} yearCount Accepts the number of years
* @returns {Object[]} Returns the collection of event datas
* @private
*/
export function yearDataGenerator(count: number = 100, date: Date = new Date(), yearCount: number = 0): Record<string, any>[] {
const startDate: Date = new Date(date.getFullYear(), 0, 1);
const endDate: Date = new Date(date.getFullYear() + yearCount, 11, 31);
const dateCollections: Record<string, any>[] = [];
for (let a: number = 0, id: number = 1; a < count; a++) {
const start: Date = new Date(Math.random() * (endDate.getTime() - startDate.getTime()) + startDate.getTime());
const end: Date = new Date(new Date(start.getTime()).setHours(start.getHours() + 1));
dateCollections.push({
Id: id,
Subject: id.toString(),
StartTime: new Date(start.getTime()),
EndTime: new Date(end.getTime()),
IsAllDay: (id % 10) ? true : false,
ProjectId: (id % 3) + 1,
TaskId: (id % 6) + 1
});
id++;
}
return dateCollections;
}
/**
* Method to generate resources event dynamically
*
* @param {Date} start Accepts the start Date
* @param {number} resCount Accepts resource count
* @param {number} overlapCount Accepts resource anme
* @returns {Object[]} Returns the collection of resource datas
* @private
*/
export function generateEvents(start: Date, resCount: number, overlapCount: number): Record<string, any>[] {
const data: Record<string, any>[] = [];
let id: number = 1;
for (let i: number = 0; i < resCount; i++) {
let random: number = 0;
for (let j: number = 0; j < overlapCount; j++) {
const startDate: Date = new Date(start.getTime() + random * (1000 * 60));
const endDate: Date = new Date(startDate.getTime() + 15 * (1000 * 60));
data.push({
Id: id,
Subject: 'Event #' + id,
StartTime: startDate,
EndTime: endDate,
IsAllDay: false,
ResourceId: i + 1
});
id++;
random = random + 15;
}
}
return data;
}
/**
* Method to generate resource data dynamically
*
* @param {number} startId Accepts the start number
* @param {number} endId Accepts resource count
* @param {string} text Accepts resource name
* @returns {Object[]} Returns the collection of resource datas
* @private
*/
export function generateResourceDatasource(startId: number, endId: number, text: string): Record<string, any>[] {
const data: Record<string, any>[] = [];
const colors: string[] = [
'#ff8787', '#9775fa', '#748ffc', '#3bc9db', '#69db7c', '#fdd835', '#748ffc',
'#9775fa', '#df5286', '#7fa900', '#fec200', '#5978ee', '#00bdae', '#ea80fc'
];
for (let a: number = startId; a <= endId; a++) {
const n: number = Math.floor(Math.random() * colors.length);
data.push({ Id: a, Text: text + ' ' + a, Color: colors[n] });
}
return data;
}
/**
* Method to generate data for all day
*
* @param {number} count Accepts the number of events data count
* @param {Date} date Accepts the event start date
* @returns {Object[]} Returns the collection of event datas
* @private
*/
export function generateAllDayData(count: number = 30, date: Date = new Date()): Record<string, any>[] {
const dateCollections: Record<string, any>[] = [];
for (let i: number = 0; i < count; i++) {
dateCollections.push({
Id: i + 1,
Subject: 'Appointment ' + i,
StartTime: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 6),
EndTime: new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12),
IsAllDay: true
});
}
return dateCollections;
} | the_stack |
import { DbContext } from "@webiny/handler-db/types";
import { SecurityContext, SecurityPermission } from "@webiny/api-security/types";
import { TenancyContext } from "@webiny/api-tenancy/types";
import { I18NContext } from "@webiny/api-i18n/types";
import { ClientContext } from "@webiny/handler-client/types";
import { Topic } from "@webiny/pubsub/types";
import { Args as PsFlushParams } from "@webiny/api-prerendering-service/flush/types";
import { Args as PsRenderParams } from "@webiny/api-prerendering-service/render/types";
import { Args as PsQueueAddParams } from "@webiny/api-prerendering-service/queue/add/types";
import {
Category,
Menu,
Page,
PageElement,
PageSettings,
PageSpecialType,
Settings,
System
} from "~/types";
import { PrerenderingServiceClientContext } from "@webiny/api-prerendering-service/client/types";
import { FileManagerContext } from "@webiny/api-file-manager/types";
// CRUD types.
export interface ListPagesParams {
limit?: number;
after?: string | null;
where?: {
category?: string;
status?: string;
tags?: { query: string[]; rule?: "any" | "all" };
[key: string]: any;
};
exclude?: string[];
search?: { query?: string };
sort?: string[];
}
export interface ListMeta {
/**
* A cursor for pagination.
*/
cursor: string | null;
/**
* Is there more items to load?
*/
hasMoreItems: boolean;
/**
* Total count of the items in the storage.
*/
totalCount: number;
}
// Pages CRUD.
export interface ListLatestPagesOptions {
auth?: boolean;
}
export interface GetPagesOptions {
decompress?: boolean;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageCreateTopicParams<TPage extends Page = Page> {
page: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageCreateTopicParams<TPage extends Page = Page> {
page: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageUpdateTopicParams<TPage extends Page = Page> {
original: TPage;
page: TPage;
input: Record<string, any>;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageUpdateTopicParams<TPage extends Page = Page> {
original: TPage;
page: TPage;
input: Record<string, any>;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageCreateFromTopicParams<TPage extends Page = Page> {
original: TPage;
page: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageCreateFromTopicParams<TPage extends Page = Page> {
original: TPage;
page: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageDeleteTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
publishedPage: TPage | null;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageDeleteTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage | null;
publishedPage: TPage | null;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePagePublishTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
publishedPage: TPage | null;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPagePublishTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
publishedPage: TPage | null;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageUnpublishTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageUnpublishTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageRequestReviewTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageRequestReviewTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageRequestChangesTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageRequestChangesTopicParams<TPage extends Page = Page> {
page: TPage;
latestPage: TPage;
}
/**
* @category Pages
*/
export interface PagesCrud {
getPage<TPage extends Page = Page>(id: string, options?: GetPagesOptions): Promise<TPage>;
listLatestPages<TPage extends Page = Page>(
args: ListPagesParams,
options?: ListLatestPagesOptions
): Promise<[TPage[], ListMeta]>;
listPublishedPages<TPage extends Page = Page>(
args: ListPagesParams
): Promise<[TPage[], ListMeta]>;
listPagesTags(args: { search: { query: string } }): Promise<string[]>;
getPublishedPageById<TPage extends Page = Page>(args: {
id: string;
preview?: boolean;
}): Promise<TPage>;
getPublishedPageByPath<TPage extends Page = Page>(args: { path: string }): Promise<TPage>;
listPageRevisions<TPage extends Page = Page>(id: string): Promise<TPage[]>;
createPage<TPage extends Page = Page>(category: string): Promise<TPage>;
createPageFrom<TPage extends Page = Page>(page: string): Promise<TPage>;
updatePage<TPage extends Page = Page>(id: string, data: PbUpdatePageInput): Promise<TPage>;
deletePage<TPage extends Page = Page>(id: string): Promise<[TPage, TPage]>;
publishPage<TPage extends Page = Page>(id: string): Promise<TPage>;
unpublishPage<TPage extends Page = Page>(id: string): Promise<TPage>;
requestPageReview<TPage extends Page = Page>(id: string): Promise<TPage>;
requestPageChanges<TPage extends Page = Page>(id: string): Promise<TPage>;
prerendering: {
render(args: RenderParams): Promise<void>;
flush(args: FlushParams): Promise<void>;
};
/**
* Lifecycle events
*/
onBeforePageCreate: Topic<OnBeforePageCreateTopicParams>;
onAfterPageCreate: Topic<OnAfterPageCreateTopicParams>;
onBeforePageCreateFrom: Topic<OnBeforePageCreateFromTopicParams>;
onAfterPageCreateFrom: Topic<OnAfterPageCreateFromTopicParams>;
onBeforePageUpdate: Topic<OnBeforePageUpdateTopicParams>;
onAfterPageUpdate: Topic<OnAfterPageUpdateTopicParams>;
onBeforePageDelete: Topic<OnBeforePageDeleteTopicParams>;
onAfterPageDelete: Topic<OnAfterPageDeleteTopicParams>;
onBeforePagePublish: Topic<OnBeforePagePublishTopicParams>;
onAfterPagePublish: Topic<OnAfterPagePublishTopicParams>;
onBeforePageUnpublish: Topic<OnBeforePageUnpublishTopicParams>;
onAfterPageUnpublish: Topic<OnAfterPageUnpublishTopicParams>;
onBeforePageRequestReview: Topic<OnBeforePageRequestReviewTopicParams>;
onAfterPageRequestReview: Topic<OnAfterPageRequestReviewTopicParams>;
onBeforePageRequestChanges: Topic<OnBeforePageRequestChangesTopicParams>;
onAfterPageRequestChanges: Topic<OnAfterPageRequestChangesTopicParams>;
}
export interface ListPageElementsParams {
sort?: string[];
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageElementCreateTopicParams {
pageElement: PageElement;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageElementCreateTopicParams {
pageElement: PageElement;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageElementUpdateTopicParams {
original: PageElement;
pageElement: PageElement;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageElementUpdateTopicParams {
original: PageElement;
pageElement: PageElement;
}
/**
* @category Lifecycle events
*/
export interface OnBeforePageElementDeleteTopicParams {
pageElement: PageElement;
}
/**
* @category Lifecycle events
*/
export interface OnAfterPageElementDeleteTopicParams {
pageElement: PageElement;
}
/**
* @category PageElements
*/
export interface PageElementsCrud {
getPageElement(id: string): Promise<PageElement | null>;
listPageElements(params?: ListPageElementsParams): Promise<PageElement[]>;
createPageElement(data: Record<string, any>): Promise<PageElement>;
updatePageElement(id: string, data: Record<string, any>): Promise<PageElement>;
deletePageElement(id: string): Promise<PageElement>;
/**
* Lifecycle events
*/
onBeforePageElementCreate: Topic<OnBeforePageElementCreateTopicParams>;
onAfterPageElementCreate: Topic<OnAfterPageElementCreateTopicParams>;
onBeforePageElementUpdate: Topic<OnBeforePageElementUpdateTopicParams>;
onAfterPageElementUpdate: Topic<OnAfterPageElementUpdateTopicParams>;
onBeforePageElementDelete: Topic<OnBeforePageElementDeleteTopicParams>;
onAfterPageElementDelete: Topic<OnAfterPageElementDeleteTopicParams>;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeCategoryCreateTopicParams {
category: Category;
}
/**
* @category Lifecycle events
*/
export interface OnAfterCategoryCreateTopicParams {
category: Category;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeCategoryUpdateTopicParams {
original: Category;
category: Category;
}
/**
* @category Lifecycle events
*/
export interface OnAfterCategoryUpdateTopicParams {
original: Category;
category: Category;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeCategoryDeleteTopicParams {
category: Category;
}
/**
* @category Lifecycle events
*/
export interface OnAfterCategoryDeleteTopicParams {
category: Category;
}
/**
* @category Categories
*/
export interface CategoriesCrud {
getCategory(slug: string, options?: { auth: boolean }): Promise<Category | null>;
listCategories(): Promise<Category[]>;
createCategory(data: PbCategoryInput): Promise<Category>;
updateCategory(slug: string, data: PbCategoryInput): Promise<Category>;
deleteCategory(slug: string): Promise<Category>;
/**
* Lifecycle events
*/
onBeforeCategoryCreate: Topic<OnBeforeCategoryCreateTopicParams>;
onAfterCategoryCreate: Topic<OnAfterCategoryCreateTopicParams>;
onBeforeCategoryUpdate: Topic<OnBeforeCategoryUpdateTopicParams>;
onAfterCategoryUpdate: Topic<OnAfterCategoryUpdateTopicParams>;
onBeforeCategoryDelete: Topic<OnBeforeCategoryDeleteTopicParams>;
onAfterCategoryDelete: Topic<OnAfterCategoryDeleteTopicParams>;
}
export interface MenuGetOptions {
auth?: boolean;
}
export interface ListMenuParams {
sort?: string[];
}
/**
* @category Lifecycle events
*/
export interface OnBeforeMenuCreateTopicParams {
menu: Menu;
input: Record<string, any>;
}
/**
* @category Lifecycle events
*/
export interface OnAfterMenuCreateTopicParams {
menu: Menu;
input: Record<string, any>;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeMenuUpdateTopicParams {
original: Menu;
menu: Menu;
}
/**
* @category Lifecycle events
*/
export interface OnAfterMenuUpdateTopicParams {
original: Menu;
menu: Menu;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeMenuDeleteTopicParams {
menu: Menu;
}
/**
* @category Lifecycle events
*/
export interface OnAfterMenuDeleteTopicParams {
menu: Menu;
}
/**
* @category Menu
*/
export interface MenusCrud {
getMenu(slug: string, options?: MenuGetOptions): Promise<Menu | null>;
getPublicMenu(slug: string): Promise<Menu>;
listMenus(params?: ListMenuParams): Promise<Menu[]>;
createMenu(data: Record<string, any>): Promise<Menu>;
updateMenu(slug: string, data: Record<string, any>): Promise<Menu>;
deleteMenu(slug: string): Promise<Menu>;
/**
* Lifecycle events
*/
onBeforeMenuCreate: Topic<OnBeforeMenuCreateTopicParams>;
onAfterMenuCreate: Topic<OnAfterMenuCreateTopicParams>;
onBeforeMenuUpdate: Topic<OnBeforeMenuUpdateTopicParams>;
onAfterMenuUpdate: Topic<OnAfterMenuUpdateTopicParams>;
onBeforeMenuDelete: Topic<OnBeforeMenuDeleteTopicParams>;
onAfterMenuDelete: Topic<OnAfterMenuDeleteTopicParams>;
}
/**
* The options passed into the crud methods
*/
export interface DefaultSettingsCrudOptions {
tenant: string | false | undefined;
locale: string | false;
}
export interface SettingsUpdateTopicMetaParams {
diff: {
pages: Array<[PageSpecialType, string, string, Page]>;
};
}
/**
* @category Lifecycle events
*/
export interface OnBeforeSettingsUpdateTopicParams {
original: Settings;
settings: Settings;
meta: SettingsUpdateTopicMetaParams;
}
/**
* @category Lifecycle events
*/
export interface OnAfterSettingsUpdateTopicParams {
original: Settings;
settings: Settings;
meta: SettingsUpdateTopicMetaParams;
}
/**
* @category Settings
*/
export interface SettingsCrud {
getCurrentSettings: () => Promise<Settings>;
getSettings: (options?: DefaultSettingsCrudOptions) => Promise<Settings | null>;
getDefaultSettings: (
options?: Pick<DefaultSettingsCrudOptions, "tenant">
) => Promise<Settings | null>;
updateSettings: (
data: Record<string, any>,
options?: { auth?: boolean } & DefaultSettingsCrudOptions
) => Promise<Settings>;
getSettingsCacheKey: (options?: DefaultSettingsCrudOptions) => string;
/**
* Lifecycle events
*/
onBeforeSettingsUpdate: Topic<OnBeforeSettingsUpdateTopicParams>;
onAfterSettingsUpdate: Topic<OnAfterSettingsUpdateTopicParams>;
}
/**
* @category Lifecycle events
*/
export interface OnBeforeInstallTopicParams {
tenant: string;
}
/**
* @category Lifecycle events
*/
export interface OnAfterInstallTopicParams {
tenant: string;
}
/**
* @category System
*/
export interface SystemCrud {
getSystem: () => Promise<System | null>;
getSystemVersion(): Promise<string | null>;
setSystemVersion(version: string): Promise<void>;
installSystem(args: { name: string; insertDemoData: boolean }): Promise<void>;
upgradeSystem(version: string, data?: Record<string, any>): Promise<boolean>;
/**
* Lifecycle events
*/
onBeforeInstall: Topic<OnBeforeInstallTopicParams>;
onAfterInstall: Topic<OnBeforeInstallTopicParams>;
}
export interface PageBuilderContextObject
extends PagesCrud,
PageElementsCrud,
CategoriesCrud,
MenusCrud,
SettingsCrud,
SystemCrud {
setPrerenderingHandlers: (configuration: PrerenderingHandlers) => void;
getPrerenderingHandlers: () => PrerenderingHandlers;
/**
* Lifecycle events
*/
onPageBeforeRender: Topic<PageBeforeRenderEvent>;
onPageAfterRender: Topic<PageAfterRenderEvent>;
onPageBeforeFlush: Topic<PageBeforeFlushEvent>;
onPageAfterFlush: Topic<PageAfterFlushEvent>;
}
export interface PbContext
extends I18NContext,
ClientContext,
DbContext,
SecurityContext,
TenancyContext,
FileManagerContext,
PrerenderingServiceClientContext {
pageBuilder: PageBuilderContextObject;
}
// Permissions.
export interface PbSecurityPermission extends SecurityPermission {
// Can user operate only on content he created?
own?: boolean;
// Determines which of the following actions are allowed:
// "r" - read
// "w" - write
// "d" - delete
rwd?: string;
}
export interface MenuSecurityPermission extends PbSecurityPermission {
name: "pb.menu";
}
export interface CategorySecurityPermission extends PbSecurityPermission {
name: "pb.category";
}
export interface PageSecurityPermission extends PbSecurityPermission {
name: "pb.page";
// Determines which of the following publishing workflow actions are allowed:
// "r" - request review (for unpublished page)
// "c" - request change (for unpublished page on which a review was requested)
// "p" - publish
// "u" - unpublish
pw: string;
}
// Page Builder lifecycle events.
export interface PageBeforeRenderEvent extends Pick<RenderParams, "paths" | "tags"> {
args: {
render?: PsRenderParams[];
queue?: PsQueueAddParams[];
};
}
export interface PageAfterRenderEvent extends Pick<RenderParams, "paths" | "tags"> {
args: {
render?: PsRenderParams[];
queue?: PsQueueAddParams[];
};
}
export interface PageBeforeFlushEvent extends Pick<FlushParams, "paths" | "tags"> {
args: {
flush?: PsFlushParams[];
queue?: PsQueueAddParams[];
};
}
export interface PageAfterFlushEvent extends Pick<FlushParams, "paths" | "tags"> {
args: {
flush?: PsFlushParams[];
queue?: PsQueueAddParams[];
};
}
// Prerendering configuration.
export interface Tag {
key: string;
value?: string;
}
export interface TagItem {
tag: Tag;
configuration?: {
meta?: Record<string, any>;
storage?: {
folder?: string;
name?: string;
};
};
}
export interface PathItem {
path: string;
configuration?: {
db?: {
namespace: string;
};
meta?: Record<string, any>;
storage?: {
folder?: string;
name?: string;
};
};
}
export interface RenderParams {
queue?: boolean;
context: PbContext;
tags?: TagItem[];
paths?: PathItem[];
}
export interface FlushParams {
context: PbContext;
tags?: TagItem[];
paths?: PathItem[];
}
export interface PrerenderingHandlers {
render(args: RenderParams): Promise<void>;
flush(args: FlushParams): Promise<void>;
}
export interface PbCategoryInput {
name: string;
slug: string;
url: string;
layout: string;
}
export interface PbUpdatePageInput {
title?: string;
category?: string;
path?: string;
settings?: PageSettings;
content?: Record<string, any> | null;
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://adexchangebuyer.googleapis.com/$discovery/rest?version=v2beta1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Ad Exchange Buyer API II v2beta1 */
function load(name: "adexchangebuyer2", version: "v2beta1"): PromiseLike<void>;
function load(name: "adexchangebuyer2", version: "v2beta1", callback: () => any): void;
const accounts: adexchangebuyer2.AccountsResource;
namespace adexchangebuyer2 {
interface AbsoluteDateRange {
/**
* The end date of the range (inclusive).
* Must be within the 30 days leading up to current date, and must be equal to
* or after start_date.
*/
endDate?: Date;
/**
* The start date of the range (inclusive).
* Must be within the 30 days leading up to current date, and must be equal to
* or before end_date.
*/
startDate?: Date;
}
interface AddDealAssociationRequest {
/** The association between a creative and a deal that should be added. */
association?: CreativeDealAssociation;
}
interface AppContext {
/** The app types this restriction applies to. */
appTypes?: string[];
}
interface AuctionContext {
/** The auction types this restriction applies to. */
auctionTypes?: string[];
}
interface BidMetricsRow {
/** The number of bids that Ad Exchange received from the buyer. */
bids?: MetricValue;
/** The number of bids that were permitted to compete in the auction. */
bidsInAuction?: MetricValue;
/** The number of bids for which the buyer was billed. */
billedImpressions?: MetricValue;
/** The number of bids that won an impression. */
impressionsWon?: MetricValue;
/**
* The number of bids for which the corresponding impression was measurable
* for viewability (as defined by Active View).
*/
measurableImpressions?: MetricValue;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
/**
* The number of bids for which the corresponding impression was viewable (as
* defined by Active View).
*/
viewableImpressions?: MetricValue;
}
interface BidResponseWithoutBidsStatusRow {
/**
* The number of impressions for which there was a bid response with the
* specified status.
*/
impressionCount?: MetricValue;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
/**
* The status specifying why the bid responses were considered to have no
* applicable bids.
*/
status?: string;
}
interface CalloutStatusRow {
/**
* The ID of the callout status.
* See [callout-status-codes](https://developers.google.com/ad-exchange/rtb/downloads/callout-status-codes).
*/
calloutStatusId?: number;
/**
* The number of impressions for which there was a bid request or bid response
* with the specified callout status.
*/
impressionCount?: MetricValue;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
}
interface Client {
/**
* The globally-unique numerical ID of the client.
* The value of this field is ignored in create and update operations.
*/
clientAccountId?: string;
/**
* Name used to represent this client to publishers.
* You may have multiple clients that map to the same entity,
* but for each client the combination of `clientName` and entity
* must be unique.
* You can specify this field as empty.
*/
clientName?: string;
/**
* Numerical identifier of the client entity.
* The entity can be an advertiser, a brand, or an agency.
* This identifier is unique among all the entities with the same type.
*
* A list of all known advertisers with their identifiers is available in the
* [advertisers.txt](https://storage.googleapis.com/adx-rtb-dictionaries/advertisers.txt)
* file.
*
* A list of all known brands with their identifiers is available in the
* [brands.txt](https://storage.googleapis.com/adx-rtb-dictionaries/brands.txt)
* file.
*
* A list of all known agencies with their identifiers is available in the
* [agencies.txt](https://storage.googleapis.com/adx-rtb-dictionaries/agencies.txt)
* file.
*/
entityId?: string;
/**
* The name of the entity. This field is automatically fetched based on
* the type and ID.
* The value of this field is ignored in create and update operations.
*/
entityName?: string;
/** The type of the client entity: `ADVERTISER`, `BRAND`, or `AGENCY`. */
entityType?: string;
/**
* The role which is assigned to the client buyer. Each role implies a set of
* permissions granted to the client. Must be one of `CLIENT_DEAL_VIEWER`,
* `CLIENT_DEAL_NEGOTIATOR` or `CLIENT_DEAL_APPROVER`.
*/
role?: string;
/** The status of the client buyer. */
status?: string;
/** Whether the client buyer will be visible to sellers. */
visibleToSeller?: boolean;
}
interface ClientUser {
/**
* Numerical account ID of the client buyer
* with which the user is associated; the
* buyer must be a client of the current sponsor buyer.
* The value of this field is ignored in an update operation.
*/
clientAccountId?: string;
/**
* User's email address. The value of this field
* is ignored in an update operation.
*/
email?: string;
/** The status of the client user. */
status?: string;
/**
* The unique numerical ID of the client user
* that has accepted an invitation.
* The value of this field is ignored in an update operation.
*/
userId?: string;
}
interface ClientUserInvitation {
/**
* Numerical account ID of the client buyer
* that the invited user is associated with.
* The value of this field is ignored in create operations.
*/
clientAccountId?: string;
/**
* The email address to which the invitation is sent. Email
* addresses should be unique among all client users under each sponsor
* buyer.
*/
email?: string;
/**
* The unique numerical ID of the invitation that is sent to the user.
* The value of this field is ignored in create operations.
*/
invitationId?: string;
}
interface Correction {
/** The contexts for the correction. */
contexts?: ServingContext[];
/** Additional details about what was corrected. */
details?: string[];
/** The type of correction that was applied to the creative. */
type?: string;
}
interface Creative {
/**
* The account that this creative belongs to.
* Can be used to filter the response of the
* creatives.list
* method.
*/
accountId?: string;
/** The link to AdChoices destination page. */
adChoicesDestinationUrl?: string;
/** The name of the company being advertised in the creative. */
advertiserName?: string;
/** The agency ID for this creative. */
agencyId?: string;
/** @OutputOnly The last update timestamp of the creative via API. */
apiUpdateTime?: string;
/**
* All attributes for the ads that may be shown from this creative.
* Can be used to filter the response of the
* creatives.list
* method.
*/
attributes?: string[];
/** The set of destination URLs for the creative. */
clickThroughUrls?: string[];
/** @OutputOnly Shows any corrections that were applied to this creative. */
corrections?: Correction[];
/**
* The buyer-defined creative ID of this creative.
* Can be used to filter the response of the
* creatives.list
* method.
*/
creativeId?: string;
/**
* @OutputOnly The top-level deals status of this creative.
* If disapproved, an entry for 'auctionType=DIRECT_DEALS' (or 'ALL') in
* serving_restrictions will also exist. Note
* that this may be nuanced with other contextual restrictions, in which case,
* it may be preferable to read from serving_restrictions directly.
* Can be used to filter the response of the
* creatives.list
* method.
*/
dealsStatus?: string;
/** @OutputOnly Detected advertiser IDs, if any. */
detectedAdvertiserIds?: string[];
/**
* @OutputOnly
* The detected domains for this creative.
*/
detectedDomains?: string[];
/**
* @OutputOnly
* The detected languages for this creative. The order is arbitrary. The codes
* are 2 or 5 characters and are documented at
* https://developers.google.com/adwords/api/docs/appendix/languagecodes.
*/
detectedLanguages?: string[];
/**
* @OutputOnly Detected product categories, if any.
* See the ad-product-categories.txt file in the technical documentation
* for a list of IDs.
*/
detectedProductCategories?: number[];
/**
* @OutputOnly Detected sensitive categories, if any.
* See the ad-sensitive-categories.txt file in the technical documentation for
* a list of IDs. You should use these IDs along with the
* excluded-sensitive-category field in the bid request to filter your bids.
*/
detectedSensitiveCategories?: number[];
/** @OutputOnly The filtering stats for this creative. */
filteringStats?: FilteringStats;
/** An HTML creative. */
html?: HtmlContent;
/** The set of URLs to be called to record an impression. */
impressionTrackingUrls?: string[];
/** A native creative. */
native?: NativeContent;
/**
* @OutputOnly The top-level open auction status of this creative.
* If disapproved, an entry for 'auctionType = OPEN_AUCTION' (or 'ALL') in
* serving_restrictions will also exist. Note
* that this may be nuanced with other contextual restrictions, in which case,
* it may be preferable to read from serving_restrictions directly.
* Can be used to filter the response of the
* creatives.list
* method.
*/
openAuctionStatus?: string;
/** All restricted categories for the ads that may be shown from this creative. */
restrictedCategories?: string[];
/**
* @OutputOnly The granular status of this ad in specific contexts.
* A context here relates to where something ultimately serves (for example,
* a physical location, a platform, an HTTPS vs HTTP request, or the type
* of auction).
*/
servingRestrictions?: ServingRestriction[];
/**
* All vendor IDs for the ads that may be shown from this creative.
* See https://storage.googleapis.com/adx-rtb-dictionaries/vendors.txt
* for possible values.
*/
vendorIds?: number[];
/** @OutputOnly The version of this creative. */
version?: number;
/** A video creative. */
video?: VideoContent;
}
interface CreativeDealAssociation {
/** The account the creative belongs to. */
accountId?: string;
/** The ID of the creative associated with the deal. */
creativeId?: string;
/** The externalDealId for the deal associated with the creative. */
dealsId?: string;
}
interface CreativeStatusRow {
/** The number of bids with the specified status. */
bidCount?: MetricValue;
/**
* The ID of the creative status.
* See [creative-status-codes](https://developers.google.com/ad-exchange/rtb/downloads/creative-status-codes).
*/
creativeStatusId?: number;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
}
interface Date {
/**
* Day of month. Must be from 1 to 31 and valid for the year and month, or 0
* if specifying a year/month where the day is not significant.
*/
day?: number;
/** Month of year. Must be from 1 to 12. */
month?: number;
/**
* Year of date. Must be from 1 to 9999, or 0 if specifying a date without
* a year.
*/
year?: number;
}
interface Disapproval {
/** Additional details about the reason for disapproval. */
details?: string[];
/** The categorized reason for disapproval. */
reason?: string;
}
interface FilterSet {
/**
* An absolute date range, defined by a start date and an end date.
* Interpreted relative to Pacific time zone.
*/
absoluteDateRange?: AbsoluteDateRange;
/** The ID of the buyer account on which to filter; optional. */
buyerAccountId?: string;
/** The ID of the creative on which to filter; optional. */
creativeId?: string;
/** The ID of the deal on which to filter; optional. */
dealId?: string;
/** The environment on which to filter; optional. */
environment?: string;
/**
* The ID of the filter set; unique within the account of the filter set
* owner.
* The value of this field is ignored in create operations.
*/
filterSetId?: string;
/** The format on which to filter; optional. */
format?: string;
/**
* The account ID of the buyer who owns this filter set.
* The value of this field is ignored in create operations.
*/
ownerAccountId?: string;
/**
* The list of platforms on which to filter; may be empty. The filters
* represented by multiple platforms are ORed together (i.e. if non-empty,
* results must match any one of the platforms).
*/
platforms?: string[];
/**
* An open-ended realtime time range, defined by the aggregation start
* timestamp.
*/
realtimeTimeRange?: RealtimeTimeRange;
/**
* A relative date range, defined by an offset from today and a duration.
* Interpreted relative to Pacific time zone.
*/
relativeDateRange?: RelativeDateRange;
/**
* The list of IDs of the seller (publisher) networks on which to filter;
* may be empty. The filters represented by multiple seller network IDs are
* ORed together (i.e. if non-empty, results must match any one of the
* publisher networks).
* See [seller-network-ids](https://developers.google.com/ad-exchange/rtb/downloads/seller-network-ids)
* file for the set of existing seller network IDs.
*/
sellerNetworkIds?: number[];
/**
* The granularity of time intervals if a time series breakdown is desired;
* optional.
*/
timeSeriesGranularity?: string;
}
interface FilteredBidCreativeRow {
/** The number of bids with the specified creative. */
bidCount?: MetricValue;
/** The ID of the creative. */
creativeId?: string;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
}
interface FilteredBidDetailRow {
/** The number of bids with the specified detail. */
bidCount?: MetricValue;
/**
* The ID of the detail. The associated value can be looked up in the
* dictionary file corresponding to the DetailType in the response message.
*/
detailId?: number;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
}
interface FilteringStats {
/**
* The day during which the data was collected.
* The data is collected from 00:00:00 to 23:59:59 PT.
* During switches from PST to PDT and back, the day may
* contain 23 or 25 hours of data instead of the usual 24.
*/
date?: Date;
/** The set of filtering reasons for this date. */
reasons?: Reason[];
}
interface HtmlContent {
/** The height of the HTML snippet in pixels. */
height?: number;
/** The HTML snippet that displays the ad when inserted in the web page. */
snippet?: string;
/** The width of the HTML snippet in pixels. */
width?: number;
}
interface Image {
/** Image height in pixels. */
height?: number;
/** The URL of the image. */
url?: string;
/** Image width in pixels. */
width?: number;
}
interface ImpressionMetricsRow {
/**
* The number of impressions available to the buyer on Ad Exchange.
* In some cases this value may be unavailable.
*/
availableImpressions?: MetricValue;
/**
* The number of impressions for which Ad Exchange sent the buyer a bid
* request.
*/
bidRequests?: MetricValue;
/** The number of impressions that match the buyer's inventory pretargeting. */
inventoryMatches?: MetricValue;
/**
* The number of impressions for which Ad Exchange received a response from
* the buyer that contained at least one applicable bid.
*/
responsesWithBids?: MetricValue;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
/**
* The number of impressions for which the buyer successfully sent a response
* to Ad Exchange.
*/
successfulResponses?: MetricValue;
}
interface ListBidMetricsResponse {
/** List of rows, each containing a set of bid metrics. */
bidMetricsRows?: BidMetricsRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListBidMetricsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.bidMetrics.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListBidResponseErrorsResponse {
/** List of rows, with counts of bid responses aggregated by callout status. */
calloutStatusRows?: CalloutStatusRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListBidResponseErrorsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.bidResponseErrors.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListBidResponsesWithoutBidsResponse {
/**
* List of rows, with counts of bid responses without bids aggregated by
* status.
*/
bidResponseWithoutBidsStatusRows?: BidResponseWithoutBidsStatusRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListBidResponsesWithoutBidsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.bidResponsesWithoutBids.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListClientUserInvitationsResponse {
/** The returned list of client users. */
invitations?: ClientUserInvitation[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListClientUserInvitationsRequest.pageToken
* field in the subsequent call to the
* clients.invitations.list
* method to retrieve the next
* page of results.
*/
nextPageToken?: string;
}
interface ListClientUsersResponse {
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListClientUsersRequest.pageToken
* field in the subsequent call to the
* clients.invitations.list
* method to retrieve the next
* page of results.
*/
nextPageToken?: string;
/** The returned list of client users. */
users?: ClientUser[];
}
interface ListClientsResponse {
/** The returned list of clients. */
clients?: Client[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListClientsRequest.pageToken
* field in the subsequent call to the
* accounts.clients.list method
* to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListCreativeStatusBreakdownByCreativeResponse {
/**
* List of rows, with counts of bids with a given creative status aggregated
* by creative.
*/
filteredBidCreativeRows?: FilteredBidCreativeRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListCreativeStatusBreakdownByCreativeRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.filteredBids.creatives.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListCreativeStatusBreakdownByDetailResponse {
/** The type of detail that the detail IDs represent. */
detailType?: string;
/**
* List of rows, with counts of bids with a given creative status aggregated
* by detail.
*/
filteredBidDetailRows?: FilteredBidDetailRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListCreativeStatusBreakdownByDetailRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.filteredBids.details.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListCreativesResponse {
/** The list of creatives. */
creatives?: Creative[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListCreativesRequest.page_token
* field in the subsequent call to `ListCreatives` method to retrieve the next
* page of results.
*/
nextPageToken?: string;
}
interface ListDealAssociationsResponse {
/** The list of associations. */
associations?: CreativeDealAssociation[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListDealAssociationsRequest.page_token
* field in the subsequent call to 'ListDealAssociation' method to retrieve
* the next page of results.
*/
nextPageToken?: string;
}
interface ListFilterSetsResponse {
/** The filter sets belonging to the buyer. */
filterSets?: FilterSet[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListFilterSetsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListFilteredBidRequestsResponse {
/**
* List of rows, with counts of filtered bid requests aggregated by callout
* status.
*/
calloutStatusRows?: CalloutStatusRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListFilteredBidRequestsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.filteredBidRequests.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListFilteredBidsResponse {
/**
* List of rows, with counts of filtered bids aggregated by filtering reason
* (i.e. creative status).
*/
creativeStatusRows?: CreativeStatusRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListFilteredBidsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.filteredBids.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListImpressionMetricsResponse {
/** List of rows, each containing a set of impression metrics. */
impressionMetricsRows?: ImpressionMetricsRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListImpressionMetricsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.impressionMetrics.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListLosingBidsResponse {
/**
* List of rows, with counts of losing bids aggregated by loss reason (i.e.
* creative status).
*/
creativeStatusRows?: CreativeStatusRow[];
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListLosingBidsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.losingBids.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
}
interface ListNonBillableWinningBidsResponse {
/**
* A token to retrieve the next page of results.
* Pass this value in the
* ListNonBillableWinningBidsRequest.pageToken
* field in the subsequent call to the
* accounts.filterSets.nonBillableWinningBids.list
* method to retrieve the next page of results.
*/
nextPageToken?: string;
/** List of rows, with counts of bids not billed aggregated by reason. */
nonBillableWinningBidStatusRows?: NonBillableWinningBidStatusRow[];
}
interface LocationContext {
/**
* IDs representing the geo location for this context.
* Please refer to the
* [geo-table.csv](https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv)
* file for different geo criteria IDs.
*/
geoCriteriaIds?: number[];
}
interface MetricValue {
/** The expected value of the metric. */
value?: string;
/**
* The variance (i.e. square of the standard deviation) of the metric value.
* If value is exact, variance is 0.
* Can be used to calculate margin of error as a percentage of value, using
* the following formula, where Z is the standard constant that depends on the
* desired size of the confidence interval (e.g. for 90% confidence interval,
* use Z = 1.645):
*
* marginOfError = 100 * Z * sqrt(variance) / value
*/
variance?: string;
}
interface NativeContent {
/** The name of the advertiser or sponsor, to be displayed in the ad creative. */
advertiserName?: string;
/** The app icon, for app download ads. */
appIcon?: Image;
/** A long description of the ad. */
body?: string;
/** A label for the button that the user is supposed to click. */
callToAction?: string;
/** The URL that the browser/SDK will load when the user clicks the ad. */
clickLinkUrl?: string;
/** The URL to use for click tracking. */
clickTrackingUrl?: string;
/** A short title for the ad. */
headline?: string;
/** A large image. */
image?: Image;
/** A smaller image, for the advertiser's logo. */
logo?: Image;
/** The price of the promoted app including currency info. */
priceDisplayText?: string;
/** The app rating in the app store. Must be in the range [0-5]. */
starRating?: number;
/** The URL to the app store to purchase/download the promoted app. */
storeUrl?: string;
/** The URL to fetch a native video ad. */
videoUrl?: string;
}
interface NonBillableWinningBidStatusRow {
/** The number of bids with the specified status. */
bidCount?: MetricValue;
/** The values of all dimensions associated with metric values in this row. */
rowDimensions?: RowDimensions;
/** The status specifying why the winning bids were not billed. */
status?: string;
}
interface PlatformContext {
/** The platforms this restriction applies to. */
platforms?: string[];
}
interface RealtimeTimeRange {
/** The start timestamp of the real-time RTB metrics aggregation. */
startTimestamp?: string;
}
interface Reason {
/**
* The number of times the creative was filtered for the status. The
* count is aggregated across all publishers on the exchange.
*/
count?: string;
/**
* The filtering status code. Please refer to the
* [creative-status-codes.txt](https://storage.googleapis.com/adx-rtb-dictionaries/creative-status-codes.txt)
* file for different statuses.
*/
status?: number;
}
interface RelativeDateRange {
/**
* The number of days in the requested date range. E.g. for a range spanning
* today, 1. For a range spanning the last 7 days, 7.
*/
durationDays?: number;
/**
* The end date of the filter set, specified as the number of days before
* today. E.g. for a range where the last date is today, 0.
*/
offsetDays?: number;
}
interface RemoveDealAssociationRequest {
/** The association between a creative and a deal that should be removed. */
association?: CreativeDealAssociation;
}
interface RowDimensions {
/** The time interval that this row represents. */
timeInterval?: TimeInterval;
}
interface SecurityContext {
/** The security types in this context. */
securities?: string[];
}
interface ServingContext {
/** Matches all contexts. */
all?: string;
/** Matches impressions for a particular app type. */
appType?: AppContext;
/** Matches impressions for a particular auction type. */
auctionType?: AuctionContext;
/**
* Matches impressions coming from users *or* publishers in a specific
* location.
*/
location?: LocationContext;
/** Matches impressions coming from a particular platform. */
platform?: PlatformContext;
/** Matches impressions for a particular security type. */
securityType?: SecurityContext;
}
interface ServingRestriction {
/** The contexts for the restriction. */
contexts?: ServingContext[];
/**
* Any disapprovals bound to this restriction.
* Only present if status=DISAPPROVED.
* Can be used to filter the response of the
* creatives.list
* method.
*/
disapprovalReasons?: Disapproval[];
/**
* The status of the creative in this context (for example, it has been
* explicitly disapproved or is pending review).
*/
status?: string;
}
interface TimeInterval {
/**
* The timestamp marking the end of the range (exclusive) for which data is
* included.
*/
endTime?: string;
/**
* The timestamp marking the start of the range (inclusive) for which data is
* included.
*/
startTime?: string;
}
interface VideoContent {
/** The URL to fetch a video ad. */
videoUrl?: string;
}
interface WatchCreativeRequest {
/**
* The Pub/Sub topic to publish notifications to.
* This topic must already exist and must give permission to
* ad-exchange-buyside-reports@google.com to write to the topic.
* This should be the full resource name in
* "projects/{project_id}/topics/{topic_id}" format.
*/
topic?: string;
}
interface InvitationsResource {
/**
* Creates and sends out an email invitation to access
* an Ad Exchange client buyer account.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Numerical account ID of the client buyer that the user
* should be associated with. (required)
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ClientUserInvitation>;
/** Retrieves an existing client user invitation. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Numerical account ID of the client buyer that the user invitation
* to be retrieved is associated with. (required)
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Numerical identifier of the user invitation to retrieve. (required) */
invitationId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ClientUserInvitation>;
/**
* Lists all the client users invitations for a client
* with a given account ID.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Numerical account ID of the client buyer to list invitations for.
* (required)
* You must either specify a string representation of a
* numerical account identifier or the `-` character
* to list all the invitations for all the clients
* of a given sponsor buyer.
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. Server may return fewer clients than requested.
* If unspecified, server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListClientUserInvitationsResponse.nextPageToken
* returned from the previous call to the
* clients.invitations.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListClientUserInvitationsResponse>;
}
interface UsersResource {
/** Retrieves an existing client user. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Numerical account ID of the client buyer
* that the user to be retrieved is associated with. (required)
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
/** Numerical identifier of the user to retrieve. (required) */
userId: string;
}): Request<ClientUser>;
/**
* Lists all the known client users for a specified
* sponsor buyer account ID.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* Numerical account ID of the sponsor buyer of the client to list users for.
* (required)
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The account ID of the client buyer to list users for. (required)
* You must specify either a string representation of a
* numerical account identifier or the `-` character
* to list all the client users for all the clients
* of a given sponsor buyer.
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer clients than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListClientUsersResponse.nextPageToken
* returned from the previous call to the
* accounts.clients.users.list method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListClientUsersResponse>;
/**
* Updates an existing client user.
* Only the user status can be changed on update.
*/
update(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Numerical account ID of the client buyer that the user to be retrieved
* is associated with. (required)
*/
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
/** Numerical identifier of the user to retrieve. (required) */
userId: string;
}): Request<ClientUser>;
}
interface ClientsResource {
/** Creates a new client buyer. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* Unique numerical account ID for the buyer of which the client buyer
* is a customer; the sponsor buyer to create a client for. (required)
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Client>;
/** Gets a client buyer with a given client account ID. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Numerical account ID of the client's sponsor buyer. (required) */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Numerical account ID of the client buyer to retrieve. (required) */
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Client>;
/** Lists all the clients for the current sponsor buyer. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Unique numerical account ID of the sponsor buyer to list the clients for. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer clients than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListClientsResponse.nextPageToken
* returned from the previous call to the
* accounts.clients.list method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListClientsResponse>;
/** Updates an existing client buyer. */
update(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* Unique numerical account ID for the buyer of which the client buyer
* is a customer; the sponsor buyer to update a client for. (required)
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Unique numerical account ID of the client to update. (required) */
clientAccountId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Client>;
invitations: InvitationsResource;
users: UsersResource;
}
interface DealAssociationsResource {
/** Associate an existing deal with a creative. */
add(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** The account the creative belongs to. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** The ID of the creative associated with the deal. */
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** List all creative-deal associations. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* The account to list the associations from.
* Specify "-" to list all creatives the current user has access to.
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The creative ID to list the associations from.
* Specify "-" to list all creatives under the above account.
*/
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. Server may return fewer associations than requested.
* If unspecified, server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListDealAssociationsResponse.next_page_token
* returned from the previous call to 'ListDealAssociations' method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* An optional query string to filter deal associations. If no filter is
* specified, all associations will be returned.
* Supported queries are:
* <ul>
* <li>accountId=<i>account_id_string</i>
* <li>creativeId=<i>creative_id_string</i>
* <li>dealsId=<i>deals_id_string</i>
* <li>dealsStatus:{approved, conditionally_approved, disapproved,
* not_checked}
* <li>openAuctionStatus:{approved, conditionally_approved, disapproved,
* not_checked}
* </ul>
* Example: 'dealsId=12345 AND dealsStatus:disapproved'
*/
query?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListDealAssociationsResponse>;
/** Remove the association between a deal and a creative. */
remove(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** The account the creative belongs to. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** The ID of the creative associated with the deal. */
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
}
interface CreativesResource {
/** Creates a creative. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* The account that this creative belongs to.
* Can be used to filter the response of the
* creatives.list
* method.
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Indicates if multiple creatives can share an ID or not. Default is
* NO_DUPLICATES (one ID per creative).
*/
duplicateIdMode?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Creative>;
/** Gets a creative. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** The account the creative belongs to. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** The ID of the creative to retrieve. */
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Creative>;
/** Lists creatives. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* The account to list the creatives from.
* Specify "-" to list all creatives the current user has access to.
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer creatives than requested
* (due to timeout constraint) even if more are available via another call.
* If unspecified, server will pick an appropriate default.
* Acceptable values are 1 to 1000, inclusive.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListCreativesResponse.next_page_token
* returned from the previous call to 'ListCreatives' method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* An optional query string to filter creatives. If no filter is specified,
* all active creatives will be returned.
* Supported queries are:
* <ul>
* <li>accountId=<i>account_id_string</i>
* <li>creativeId=<i>creative_id_string</i>
* <li>dealsStatus: {approved, conditionally_approved, disapproved,
* not_checked}
* <li>openAuctionStatus: {approved, conditionally_approved, disapproved,
* not_checked}
* <li>attribute: {a numeric attribute from the list of attributes}
* <li>disapprovalReason: {a reason from
* DisapprovalReason
* </ul>
* Example: 'accountId=12345 AND (dealsStatus:disapproved AND
* disapprovalReason:unacceptable_content) OR attribute:47'
*/
query?: string;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCreativesResponse>;
/**
* Stops watching a creative. Will stop push notifications being sent to the
* topics when the creative changes status.
*/
stopWatching(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** The account of the creative to stop notifications for. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The creative ID of the creative to stop notifications for.
* Specify "-" to specify stopping account level notifications.
*/
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/** Updates a creative. */
update(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/**
* The account that this creative belongs to.
* Can be used to filter the response of the
* creatives.list
* method.
*/
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The buyer-defined creative ID of this creative.
* Can be used to filter the response of the
* creatives.list
* method.
*/
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Creative>;
/**
* Watches a creative. Will result in push notifications being sent to the
* topic when the creative changes status.
*/
watch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** The account of the creative to watch. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The creative ID to watch for status changes.
* Specify "-" to watch all creatives under the above account.
* If both creative-level and account-level notifications are
* sent, only a single notification will be sent to the
* creative-level notification topic.
*/
creativeId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
dealAssociations: DealAssociationsResource;
}
interface BidMetricsResource {
/** Lists all metrics that are measured in terms of number of bids. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListBidMetricsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.bidMetrics.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListBidMetricsResponse>;
}
interface BidResponseErrorsResource {
/**
* List all errors that occurred in bid responses, with the number of bid
* responses affected for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListBidResponseErrorsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.bidResponseErrors.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListBidResponseErrorsResponse>;
}
interface BidResponsesWithoutBidsResource {
/**
* List all reasons for which bid responses were considered to have no
* applicable bids, with the number of bid responses affected for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListBidResponsesWithoutBidsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.bidResponsesWithoutBids.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListBidResponsesWithoutBidsResponse>;
}
interface FilteredBidRequestsResource {
/**
* List all reasons that caused a bid request not to be sent for an
* impression, with the number of bid requests not sent for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListFilteredBidRequestsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.filteredBidRequests.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListFilteredBidRequestsResponse>;
}
interface CreativesResource {
/**
* List all creatives associated with a specific reason for which bids were
* filtered, with the number of bids filtered for each creative.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The ID of the creative status for which to retrieve a breakdown by
* creative.
* See
* [creative-status-codes](https://developers.google.com/ad-exchange/rtb/downloads/creative-status-codes).
*/
creativeStatusId: number;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListCreativeStatusBreakdownByCreativeResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.filteredBids.creatives.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCreativeStatusBreakdownByCreativeResponse>;
}
interface DetailsResource {
/**
* List all details associated with a specific reason for which bids were
* filtered, with the number of bids filtered for each detail.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* The ID of the creative status for which to retrieve a breakdown by detail.
* See
* [creative-status-codes](https://developers.google.com/ad-exchange/rtb/downloads/creative-status-codes).
* Details are only available for statuses 10, 14, 15, 17, 18, 19, 86, and 87.
*/
creativeStatusId: number;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListCreativeStatusBreakdownByDetailResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.filteredBids.details.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCreativeStatusBreakdownByDetailResponse>;
}
interface FilteredBidsResource {
/**
* List all reasons for which bids were filtered, with the number of bids
* filtered for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListFilteredBidsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.filteredBids.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListFilteredBidsResponse>;
creatives: CreativesResource;
details: DetailsResource;
}
interface ImpressionMetricsResource {
/** Lists all metrics that are measured in terms of number of impressions. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListImpressionMetricsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.impressionMetrics.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListImpressionMetricsResponse>;
}
interface LosingBidsResource {
/**
* List all reasons for which bids lost in the auction, with the number of
* bids that lost for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListLosingBidsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.losingBids.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListLosingBidsResponse>;
}
interface NonBillableWinningBidsResource {
/**
* List all reasons for which winning bids were not billable, with the number
* of bids not billed for each reason.
*/
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to apply. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListNonBillableWinningBidsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.nonBillableWinningBids.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListNonBillableWinningBidsResponse>;
}
interface FilterSetsResource {
/** Creates the specified filter set for the account with the given account ID. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* Whether the filter set is transient, or should be persisted indefinitely.
* By default, filter sets are not transient.
* If transient, it will be available for at least 1 hour after creation.
*/
isTransient?: boolean;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FilterSet>;
/**
* Deletes the requested filter set from the account with the given account
* ID.
*/
delete(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to delete. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<{}>;
/**
* Retrieves the requested filter set for the account with the given account
* ID.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The ID of the filter set to get. */
filterSetId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<FilterSet>;
/** Lists all filter sets for the account with the given account ID. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Account ID of the buyer. */
accountId: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Requested page size. The server may return fewer results than requested.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* A token identifying a page of results the server should return.
* Typically, this is the value of
* ListFilterSetsResponse.nextPageToken
* returned from the previous call to the
* accounts.filterSets.list
* method.
*/
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListFilterSetsResponse>;
bidMetrics: BidMetricsResource;
bidResponseErrors: BidResponseErrorsResource;
bidResponsesWithoutBids: BidResponsesWithoutBidsResource;
filteredBidRequests: FilteredBidRequestsResource;
filteredBids: FilteredBidsResource;
impressionMetrics: ImpressionMetricsResource;
losingBids: LosingBidsResource;
nonBillableWinningBids: NonBillableWinningBidsResource;
}
interface AccountsResource {
clients: ClientsResource;
creatives: CreativesResource;
filterSets: FilterSetsResource;
}
}
} | the_stack |
import Piscina from '@posthog/piscina'
import * as IORedis from 'ioredis'
import { ONE_HOUR } from '../../src/config/constants'
import { startPluginsServer } from '../../src/main/pluginsServer'
import { LogLevel } from '../../src/types'
import { Hub } from '../../src/types'
import { Client } from '../../src/utils/celery/client'
import { delay, UUIDT } from '../../src/utils/utils'
import { makePiscina } from '../../src/worker/piscina'
import { createPosthog, DummyPostHog } from '../../src/worker/vm/extensions/posthog'
import { writeToFile } from '../../src/worker/vm/extensions/test-utils'
import { pluginConfig39 } from '../helpers/plugins'
import { resetTestDatabase } from '../helpers/sql'
import { delayUntilEventIngested } from '../shared/process-event'
const { console: testConsole } = writeToFile
const HISTORICAL_EVENTS_COUNTER_CACHE_KEY = '@plugin/60/2/historical_events_seen'
jest.mock('../../src/utils/status')
jest.setTimeout(60000) // 60 sec timeout
const indexJs = `
import { console as testConsole } from 'test-utils/write-to-file'
export async function processEvent (event) {
testConsole.log('processEvent')
console.info('amogus')
event.properties.processed = 'hell yes'
event.properties.upperUuid = event.properties.uuid?.toUpperCase()
event.properties['$snapshot_data'] = 'no way'
const counter = await meta.cache.get('events_seen')
return event
}
export function onEvent (event, { global }) {
// we use this to mock setupPlugin being
// run after some events were already ingested
global.timestampBoundariesForTeam = {
max: new Date(),
min: new Date(Date.now()-${ONE_HOUR})
}
testConsole.log('onEvent', event.event)
}
export function onSnapshot (event) {
testConsole.log('onSnapshot', event.event)
}
export async function exportEvents(events) {
for (const event of events) {
if (event.properties && event.properties['$$is_historical_export_event']) {
testConsole.log('exported historical event', event)
}
}
}
export async function onAction(action, event) {
testConsole.log('onAction', action, event)
}
`
// TODO: merge these tests with clickhouse/e2e.test.ts
describe('e2e', () => {
let hub: Hub
let closeHub: () => Promise<void>
let posthog: DummyPostHog
let redis: IORedis.Redis
let piscina: Piscina
beforeEach(async () => {
testConsole.reset()
console.debug = jest.fn()
await resetTestDatabase(indexJs)
const startResponse = await startPluginsServer(
{
WORKER_CONCURRENCY: 2,
PLUGINS_CELERY_QUEUE: 'test-plugins-celery-queue',
CELERY_DEFAULT_QUEUE: 'test-celery-default-queue',
LOG_LEVEL: LogLevel.Log,
KAFKA_ENABLED: false,
},
makePiscina
)
hub = startResponse.hub
closeHub = startResponse.stop
piscina = startResponse.piscina
redis = await hub.redisPool.acquire()
await redis.del(hub.PLUGINS_CELERY_QUEUE)
await redis.del(hub.CELERY_DEFAULT_QUEUE)
await redis.del(HISTORICAL_EVENTS_COUNTER_CACHE_KEY)
posthog = createPosthog(hub, pluginConfig39)
})
afterEach(async () => {
await hub.redisPool.release(redis)
await closeHub()
})
describe('e2e postgres ingestion', () => {
test('event captured, processed, ingested', async () => {
expect((await hub.db.fetchEvents()).length).toBe(0)
const uuid = new UUIDT().toString()
await posthog.capture('custom event', { name: 'haha', uuid })
await delayUntilEventIngested(() => hub.db.fetchEvents())
const events = await hub.db.fetchEvents()
await delay(1000)
expect(events.length).toBe(1)
// processEvent ran and modified
expect(events[0].properties.processed).toEqual('hell yes')
expect(events[0].properties.upperUuid).toEqual(uuid.toUpperCase())
// onEvent ran
expect(testConsole.read()).toEqual([['processEvent'], ['onEvent', 'custom event']])
})
test('snapshot captured, processed, ingested', async () => {
expect((await hub.db.fetchSessionRecordingEvents()).length).toBe(0)
await posthog.capture('$snapshot', { $session_id: '1234abc', $snapshot_data: 'yes way' })
await delayUntilEventIngested(() => hub.db.fetchSessionRecordingEvents())
const events = await hub.db.fetchSessionRecordingEvents()
await delay(1000)
expect(events.length).toBe(1)
// processEvent did not modify
expect(events[0].snapshot_data).toEqual('yes way')
// onSnapshot ran
expect(testConsole.read()).toEqual([['onSnapshot', '$snapshot']])
})
test('console logging is persistent', async () => {
const logCount = (await hub.db.fetchPluginLogEntries()).length
const getLogsSinceStart = async () => (await hub.db.fetchPluginLogEntries()).slice(logCount)
await posthog.capture('custom event', { name: 'hehe', uuid: new UUIDT().toString() })
await delayUntilEventIngested(async () =>
(await getLogsSinceStart()).filter(({ message }) => message.includes('amogus'))
)
const pluginLogEntries = await getLogsSinceStart()
expect(
pluginLogEntries.filter(({ message, type }) => message.includes('amogus') && type === 'INFO').length
).toEqual(1)
})
test('action matches are saved', async () => {
await posthog.capture('xyz', { foo: 'bar' })
await delayUntilEventIngested(() => hub.db.fetchActionMatches())
const savedMatches = await hub.db.fetchActionMatches()
expect(savedMatches).toStrictEqual([
{ id: expect.any(Number), event_id: expect.any(Number), action_id: 69 },
])
})
})
describe('onAction', () => {
const awaitOnActionLogs = async () =>
await new Promise((resolve) => {
resolve(testConsole.read().filter((log) => log[1] === 'onAction event'))
})
test('onAction receives the action and event', async () => {
await posthog.capture('onAction event', { foo: 'bar' })
await delayUntilEventIngested(awaitOnActionLogs, 1)
const log = testConsole.read().filter((log) => log[0] === 'onAction')[0]
const [logName, action, event] = log
expect(logName).toEqual('onAction')
expect(action).toEqual(
expect.objectContaining({
id: 69,
name: 'Test Action',
team_id: 2,
deleted: false,
post_to_slack: true,
})
)
expect(event).toEqual(
expect.objectContaining({
distinct_id: 'plugin-id-60',
team_id: 2,
event: 'onAction event',
})
)
})
})
describe('e2e export historical events', () => {
const awaitHistoricalEventLogs = async () =>
await new Promise((resolve) => {
resolve(testConsole.read().filter((log) => log[0] === 'exported historical event'))
})
test('export historical events without payload timestamps', async () => {
await posthog.capture('historicalEvent1')
await posthog.capture('historicalEvent2')
await posthog.capture('historicalEvent3')
await posthog.capture('historicalEvent4')
await delayUntilEventIngested(() => hub.db.fetchEvents(), 4)
// the db needs to have events _before_ running setupPlugin
// to test payloads with missing timestamps
// hence we reload here
await piscina.broadcastTask({ task: 'teardownPlugins' })
await delay(2000)
await piscina.broadcastTask({ task: 'reloadPlugins' })
await delay(2000)
const historicalEvents = await hub.db.fetchEvents()
expect(historicalEvents.length).toBe(4)
const exportedEventsCountBeforeJob = testConsole
.read()
.filter((log) => log[0] === 'exported historical event').length
expect(exportedEventsCountBeforeJob).toEqual(0)
const kwargs = {
pluginConfigTeam: 2,
pluginConfigId: 39,
type: 'Export historical events',
jobOp: 'start',
payload: {},
}
const args = Object.values(kwargs)
const client = new Client(hub.db, hub.PLUGINS_CELERY_QUEUE)
client.sendTask('posthog.tasks.plugins.plugin_job', args, {})
await delayUntilEventIngested(awaitHistoricalEventLogs, 4, 1000)
const exportLogs = testConsole.read().filter((log) => log[0] === 'exported historical event')
const exportedEventsCountAfterJob = exportLogs.length
const exportedEvents = exportLogs.map((log) => log[1])
expect(exportedEventsCountAfterJob).toEqual(4)
expect(exportedEvents.map((e) => e.event)).toEqual(
expect.arrayContaining(['historicalEvent1', 'historicalEvent2', 'historicalEvent3', 'historicalEvent4'])
)
expect(Object.keys(exportedEvents[0].properties)).toEqual(
expect.arrayContaining([
'$$postgres_event_id',
'$$historical_export_source_db',
'$$is_historical_export_event',
'$$historical_export_timestamp',
])
)
expect(exportedEvents[0].properties['$$historical_export_source_db']).toEqual('postgres')
})
test('export historical events with specified timestamp boundaries', async () => {
await posthog.capture('historicalEvent1')
await posthog.capture('historicalEvent2')
await posthog.capture('historicalEvent3')
await posthog.capture('historicalEvent4')
await delayUntilEventIngested(() => hub.db.fetchEvents(), 4)
const historicalEvents = await hub.db.fetchEvents()
expect(historicalEvents.length).toBe(4)
const exportedEventsCountBeforeJob = testConsole
.read()
.filter((log) => log[0] === 'exported historical event').length
expect(exportedEventsCountBeforeJob).toEqual(0)
const kwargs = {
pluginConfigTeam: 2,
pluginConfigId: 39,
type: 'Export historical events',
jobOp: 'start',
payload: {
dateFrom: new Date(Date.now() - ONE_HOUR).toISOString(),
dateTo: new Date().toISOString(),
},
}
let args = Object.values(kwargs)
const client = new Client(hub.db, hub.PLUGINS_CELERY_QUEUE)
args = Object.values(kwargs)
client.sendTask('posthog.tasks.plugins.plugin_job', args, {})
await delayUntilEventIngested(awaitHistoricalEventLogs, 4, 1000)
const exportLogs = testConsole.read().filter((log) => log[0] === 'exported historical event')
const exportedEventsCountAfterJob = exportLogs.length
const exportedEvents = exportLogs.map((log) => log[1])
expect(exportedEventsCountAfterJob).toEqual(4)
expect(exportedEvents.map((e) => e.event)).toEqual(
expect.arrayContaining(['historicalEvent1', 'historicalEvent2', 'historicalEvent3', 'historicalEvent4'])
)
expect(Object.keys(exportedEvents[0].properties)).toEqual(
expect.arrayContaining([
'$$postgres_event_id',
'$$historical_export_source_db',
'$$is_historical_export_event',
'$$historical_export_timestamp',
])
)
expect(exportedEvents[0].properties['$$historical_export_source_db']).toEqual('postgres')
})
test('correct $elements included in historical event', async () => {
const properties = {
$elements: [
{ tag_name: 'a', nth_child: 1, nth_of_type: 2, attr__class: 'btn btn-sm' },
{ tag_name: 'div', nth_child: 1, nth_of_type: 2, $el_text: '💻' },
],
}
await posthog.capture('$autocapture', properties)
await delayUntilEventIngested(() => hub.db.fetchEvents(), 1)
const historicalEvents = await hub.db.fetchEvents()
expect(historicalEvents.length).toBe(1)
const kwargs = {
pluginConfigTeam: 2,
pluginConfigId: 39,
type: 'Export historical events',
jobOp: 'start',
payload: {
dateFrom: new Date(Date.now() - ONE_HOUR).toISOString(),
dateTo: new Date().toISOString(),
},
}
const args = Object.values(kwargs)
const client = new Client(hub.db, hub.PLUGINS_CELERY_QUEUE)
client.sendTask('posthog.tasks.plugins.plugin_job', args, {})
await delayUntilEventIngested(awaitHistoricalEventLogs, 1, 1000)
const exportLogs = testConsole.read().filter((log) => log[0] === 'exported historical event')
const exportedEventsCountAfterJob = exportLogs.length
const exportedEvents = exportLogs.map((log) => log[1])
expect(exportedEventsCountAfterJob).toEqual(1)
expect(exportedEvents.map((e) => e.event)).toEqual(['$autocapture'])
expect(Object.keys(exportedEvents[0].properties)).toEqual(
expect.arrayContaining([
'$$postgres_event_id',
'$$historical_export_source_db',
'$$is_historical_export_event',
'$$historical_export_timestamp',
])
)
expect(exportedEvents[0].properties['$elements']).toEqual([
{
attr_class: 'btn btn-sm',
attributes: { attr__class: 'btn btn-sm' },
nth_child: 1,
nth_of_type: 2,
tag_name: 'a',
},
{ $el_text: '💻', attributes: {}, nth_child: 1, nth_of_type: 2, tag_name: 'div', text: '💻' },
])
})
})
}) | the_stack |
const allHTMLTagsKnownToHumanity = new Set([
"a",
"abbr",
"acronym",
"address",
"applet",
"area",
"article",
"aside",
"audio",
"b",
"base",
"basefont",
"bdi",
"bdo",
"bgsound",
"big",
"blink",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"center",
"cite",
"code",
"col",
"colgroup",
"command",
"content",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"dir",
"div",
"dl",
"dt",
"element",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"font",
"footer",
"form",
"frame",
"frameset",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hgroup",
"hr",
"html",
"i",
"iframe",
"image",
"img",
"input",
"ins",
"isindex",
"kbd",
"keygen",
"label",
"legend",
"li",
"link",
"listing",
"main",
"map",
"mark",
"marquee",
"menu",
"menuitem",
"meta",
"meter",
"multicol",
"nav",
"nextid",
"nobr",
"noembed",
"noframes",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"p",
"param",
"picture",
"plaintext",
"pre",
"progress",
"q",
"rb",
"rp",
"rt",
"rtc",
"ruby",
"s",
"samp",
"script",
"section",
"select",
"shadow",
"slot",
"small",
"source",
"spacer",
"span",
"strike",
"strong",
"style",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"template",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"tt",
"u",
"ul",
"var",
"video",
"wbr",
"xmp",
]);
// contains all common templating language head/tail marker characters:
const espChars = `{}%-$_()*|#`;
const veryEspChars = `{}|#`;
const notVeryEspChars = `%()$_*#`;
const leftyChars = `({`;
const rightyChars = `})`;
const espLumpBlacklist = [
")|(",
"|(",
")(",
"()",
"}{",
"{}",
"%)",
"*)",
"||",
"--",
];
const punctuationChars = `.,;!?`;
const BACKTICK = "\x60";
const LEFTDOUBLEQUOTMARK = `\u201C`;
const RIGHTDOUBLEQUOTMARK = `\u201D`;
function lastChar(str: string): string {
return str[str.length - 1] || "";
}
function secondToLastChar(str: string): string {
return str[str.length - 2] || "";
}
function firstChar(str: string): string {
return str[0] || "";
}
function secondChar(str: string): string {
return str[1] || "";
}
function isLowerCaseLetter(char: string): boolean {
return char.charCodeAt(0) > 96 && char.charCodeAt(0) < 123;
}
// "is an upper case LATIN letter", that is
function isUppercaseLetter(char: string): boolean {
return !!(char && char.charCodeAt(0) > 64 && char.charCodeAt(0) < 91);
}
function isNumOrNumStr(something: any): boolean {
return (
(typeof something === "string" &&
something.charCodeAt(0) >= 48 &&
something.charCodeAt(0) <= 57) ||
Number.isInteger(something)
);
}
function isLowercase(char: string): boolean {
return !!(char && char.toLowerCase() === char && char.toUpperCase() !== char);
}
function isLatinLetter(char: string): boolean {
// we mean Latin letters A-Z, a-z
return !!(
char &&
((char.charCodeAt(0) > 64 && char.charCodeAt(0) < 91) ||
(char.charCodeAt(0) > 96 && char.charCodeAt(0) < 123))
);
}
// Considering custom element name character requirements:
// https://html.spec.whatwg.org/multipage/custom-elements.html
// Example of Unicode character in a regex:
// \u0041
// "-" | "." | [0-9] | "_" | [a-z] | #xB7 | [#xC0-#xEFFFF]
function charSuitableForTagName(char: string): boolean {
return /[.\-_a-z0-9\u00B7\u00C0-\uFFFD]/i.test(char);
}
// it flips all brackets backwards and puts characters in the opposite order
function flipEspTag(str: string): string {
let res = "";
for (let i = 0, len = str.length; i < len; i++) {
if (str[i] === "[") {
res = `]${res}`;
} else if (str[i] === "]") {
res = `[${res}`;
} else if (str[i] === "{") {
res = `}${res}`;
} else if (str[i] === "}") {
res = `{${res}`;
} else if (str[i] === "(") {
res = `)${res}`;
} else if (str[i] === ")") {
res = `(${res}`;
} else if (str[i] === "<") {
res = `>${res}`;
} else if (str[i] === ">") {
res = `<${res}`;
} else if (str[i] === LEFTDOUBLEQUOTMARK) {
res = `${RIGHTDOUBLEQUOTMARK}${res}`;
} else if (str[i] === RIGHTDOUBLEQUOTMARK) {
res = `${LEFTDOUBLEQUOTMARK}${res}`;
} else {
res = `${str[i]}${res}`;
}
}
return res;
}
function isTagNameRecognised(tagName: string): boolean {
return (
allHTMLTagsKnownToHumanity.has(tagName.toLowerCase()) ||
["doctype", "cdata", "xml"].includes(tagName.toLowerCase())
);
}
// Tells, if substring x goes before substring y on the right
// side of "str", starting at index "startingIdx".
// Used to troubleshoot dirty broken code.
function xBeforeYOnTheRight(
str: string,
startingIdx: number,
x: string,
y: string
) {
for (let i = startingIdx, len = str.length; i < len; i++) {
if (str.startsWith(x, i)) {
// if x was first, Bob's your uncle, that's truthy result
return true;
}
if (str.startsWith(y, i)) {
// since we're in this clause, x failed, so if y matched,
// this means y precedes x
return false;
}
}
// default result
return false;
}
function ensureXIsNotPresentBeforeOneOfY(
str: string,
startingIdx: number,
x: string,
y: string[] = []
) {
for (let i = startingIdx, len = str.length; i < len; i++) {
if (y.some((oneOfStr) => str.startsWith(oneOfStr, i))) {
// it's escape clause, bracket or whatever was reached and yet,
// "x" hasn't been encountered yet
return true;
}
if (str[i] === x) {
// if "x" was found, that's it - falsey result
return false;
}
}
// default result
return true;
}
// deliberately a simpler check for perf reasons
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
// https://html.spec.whatwg.org/multipage/syntax.html#elements-2
const voidTags = [
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"link",
"meta",
"param",
"source",
"track",
"wbr",
];
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element#Inline_text_semantics
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element#Image_and_multimedia
const inlineTags = new Set([
"a",
"abbr",
"acronym",
"audio",
"b",
"bdi",
"bdo",
"big",
"br",
"button",
"canvas",
"cite",
"code",
"data",
"datalist",
"del",
"dfn",
"em",
"embed",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"label",
"map",
"mark",
"meter",
"noscript",
"object",
"output",
"picture",
"progress",
"q",
"ruby",
"s",
"samp",
"script",
"select",
"slot",
"small",
"span",
"strong",
"sub",
"sup",
"svg",
"template",
"textarea",
"time",
"u",
"tt",
"var",
"video",
"wbr",
]);
// Rules which might wrap the media queries, for example:
// @supports (display: grid) {...
// const atRulesWhichMightWrapStyles = ["media", "supports", "document"];
const charsThatEndCSSChunks = ["{", "}", ","];
const SOMEQUOTE = `'"${LEFTDOUBLEQUOTMARK}${RIGHTDOUBLEQUOTMARK}`;
const attrNameRegexp = /[\w-]/;
interface Obj {
[key: string]: any;
}
interface Selector {
value: string;
selectorStarts: number;
selectorEnds: number;
}
type TokenType = "text" | "tag" | "rule" | "at" | "comment" | "esp";
type TokenKind = "simplet" | "not" | "doctype" | "cdata" | "xml" | "inline";
// "simple" or "only" or "not" (HTML)
// "block" or "line"(CSS)
type CommentKind = "simple" | "only" | "not" | "block" | "line" | "simplet";
type LayerType = "simple" | "at" | "block" | "esp";
interface TextToken {
type: "text";
start: number;
end: number;
value: string;
}
interface CommentToken {
type: "comment";
start: number;
end: number;
value: string;
closing: null | boolean;
kind: CommentKind;
language: "html" | "css";
}
interface EspToken {
type: "esp";
start: number;
end: number;
value: string;
head: null | string;
headStartsAt: null | number;
headEndsAt: null | number;
tail: null | string;
tailStartsAt: null | number;
tailEndsAt: null | number;
}
type PropertyValueWithinArray = TextToken | EspToken;
interface Property {
property: null | string;
propertyStarts: null | number;
propertyEnds: null | number;
colon: null | number;
value: string | PropertyValueWithinArray[];
valueStarts: null | number;
valueEnds: null | number;
importantStarts: null | number;
importantEnds: null | number;
important: null | string;
semi: null | number;
start: number; // mirrors "propertyStarts"
end: number; // mirrors whatever was last
}
interface Attrib {
attribName: string;
attribNameRecognised: boolean;
attribNameStartsAt: number;
attribNameEndsAt: number;
attribOpeningQuoteAt: null | number;
attribClosingQuoteAt: null | number;
attribValueRaw: string;
attribValue: (TextToken | Property | CommentToken | EspToken)[];
attribValueStartsAt: null | number;
attribValueEndsAt: null | number;
attribStarts: number;
attribEnds: number;
attribLeft: number;
}
interface RuleToken {
type: "rule";
start: number;
end: number;
value: string;
left: null | number;
nested: null | boolean;
openingCurlyAt: null | number;
closingCurlyAt: null | number;
selectorsStart: null | number;
selectorsEnd: null | number;
selectors: Selector[];
properties: (Property | TextToken)[];
}
interface TagToken {
type: "tag";
start: number;
end: number;
value: string;
tagNameStartsAt: number;
tagNameEndsAt: number;
tagName: string;
recognised: null | boolean;
closing: null | boolean;
void: null | boolean;
pureHTML: null | boolean;
kind: null | TokenKind;
attribs: Attrib[];
}
interface AtToken {
type: "at";
start: number;
end: number;
value: string;
left: null | number;
nested: null | false;
identifier: null | string;
identifierStartsAt: null | number;
identifierEndsAt: null | number;
query: string;
queryStartsAt: number;
queryEndsAt: number;
openingCurlyAt: null | number;
closingCurlyAt: null | number;
rules: (RuleToken | TextToken)[];
}
type Token =
| TextToken
| TagToken
| RuleToken
| AtToken
| CommentToken
| EspToken;
interface LayerKindAt {
type: "at";
token: AtToken;
}
interface LayerSimple {
type: "simple" | "block";
value: string;
position: number;
}
interface LayerEsp {
type: "esp";
openingLump: string;
guessedClosingLump: string;
position: number;
}
type Layer = LayerKindAt | LayerSimple | LayerEsp;
interface CharacterToken {
chr: string;
i: number;
type: TokenType;
}
type TokenCb = (token: Token, next: Token[]) => void;
type CharCb = (token: CharacterToken, next: CharacterToken[]) => void;
interface Opts {
tagCb: null | TokenCb;
tagCbLookahead: number;
charCb: null | CharCb;
charCbLookahead: number;
reportProgressFunc: null | ((percDone: number) => void);
reportProgressFuncFrom: number;
reportProgressFuncTo: number;
}
export {
ensureXIsNotPresentBeforeOneOfY,
allHTMLTagsKnownToHumanity,
charSuitableForTagName,
isTagNameRecognised,
xBeforeYOnTheRight,
isLowerCaseLetter,
isUppercaseLetter,
espLumpBlacklist,
secondToLastChar,
punctuationChars,
notVeryEspChars,
isNumOrNumStr,
isLatinLetter,
veryEspChars,
rightyChars,
isLowercase,
leftyChars,
flipEspTag,
secondChar,
firstChar,
lastChar,
espChars,
isObj,
Token,
voidTags,
inlineTags,
BACKTICK,
charsThatEndCSSChunks,
SOMEQUOTE,
attrNameRegexp,
Attrib,
TokenType,
Property,
Layer,
TextToken,
RuleToken,
TagToken,
CommentToken,
LayerType,
LayerSimple,
CharacterToken,
LayerEsp,
EspToken,
LayerKindAt,
AtToken,
Opts,
Obj,
TokenCb,
CharCb,
LEFTDOUBLEQUOTMARK,
RIGHTDOUBLEQUOTMARK,
}; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [databrew](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsgluedatabrew.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Databrew extends PolicyStatement {
public servicePrefix = 'databrew';
/**
* Statement provider for service [databrew](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsgluedatabrew.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 delete one or more recipe versions
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_BatchDeleteRecipeVersion.html
*/
public toBatchDeleteRecipeVersion() {
return this.to('BatchDeleteRecipeVersion');
}
/**
* Grants permission to create a dataset
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateDataset.html
*/
public toCreateDataset() {
return this.to('CreateDataset');
}
/**
* Grants permission to create a profile job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateProfileJob.html
*/
public toCreateProfileJob() {
return this.to('CreateProfileJob');
}
/**
* Grants permission to create a project
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateProject.html
*/
public toCreateProject() {
return this.to('CreateProject');
}
/**
* Grants permission to create a recipe
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateRecipe.html
*/
public toCreateRecipe() {
return this.to('CreateRecipe');
}
/**
* Grants permission to create a recipe job
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateRecipeJob.html
*/
public toCreateRecipeJob() {
return this.to('CreateRecipeJob');
}
/**
* Grants permission to create a schedule
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_CreateSchedule.html
*/
public toCreateSchedule() {
return this.to('CreateSchedule');
}
/**
* Grants permission to delete a dataset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteDataset.html
*/
public toDeleteDataset() {
return this.to('DeleteDataset');
}
/**
* Grants permission to delete a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteJob.html
*/
public toDeleteJob() {
return this.to('DeleteJob');
}
/**
* Grants permission to delete a project
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteProject.html
*/
public toDeleteProject() {
return this.to('DeleteProject');
}
/**
* Grants permission to delete a recipe version
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteRecipeVersion.html
*/
public toDeleteRecipeVersion() {
return this.to('DeleteRecipeVersion');
}
/**
* Grants permission to delete a schedule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DeleteSchedule.html
*/
public toDeleteSchedule() {
return this.to('DeleteSchedule');
}
/**
* Grants permission to view details about a dataset
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeDataset.html
*/
public toDescribeDataset() {
return this.to('DescribeDataset');
}
/**
* Grants permission to view details about a job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeJob.html
*/
public toDescribeJob() {
return this.to('DescribeJob');
}
/**
* Grants permission to view details about job run for a given job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeJobRun.html
*/
public toDescribeJobRun() {
return this.to('DescribeJobRun');
}
/**
* Grants permission to view details about a project
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeProject.html
*/
public toDescribeProject() {
return this.to('DescribeProject');
}
/**
* Grants permission to view details about a recipe
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeRecipe.html
*/
public toDescribeRecipe() {
return this.to('DescribeRecipe');
}
/**
* Grants permission to view details about a schedule
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_DescribeSchedule.html
*/
public toDescribeSchedule() {
return this.to('DescribeSchedule');
}
/**
* Grants permission to list datasets in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListDatasets.html
*/
public toListDatasets() {
return this.to('ListDatasets');
}
/**
* Grants permission to list job runs for a given job
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListJobRuns.html
*/
public toListJobRuns() {
return this.to('ListJobRuns');
}
/**
* Grants permission to list jobs in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListJobs.html
*/
public toListJobs() {
return this.to('ListJobs');
}
/**
* Grants permission to list projects in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListProjects.html
*/
public toListProjects() {
return this.to('ListProjects');
}
/**
* Grants permission to list versions in your recipe
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListRecipeVersions.html
*/
public toListRecipeVersions() {
return this.to('ListRecipeVersions');
}
/**
* Grants permission to list recipes in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListRecipes.html
*/
public toListRecipes() {
return this.to('ListRecipes');
}
/**
* Grants permission to list schedules in your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListSchedules.html
*/
public toListSchedules() {
return this.to('ListSchedules');
}
/**
* Grants permission to retrieve tags associated with a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to publish a major verison of a recipe
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_PublishRecipe.html
*/
public toPublishRecipe() {
return this.to('PublishRecipe');
}
/**
* Grants permission to submit an action to the interactive session for a project
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_SendProjectSessionAction.html
*/
public toSendProjectSessionAction() {
return this.to('SendProjectSessionAction');
}
/**
* Grants permission to start running a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_StartJobRun.html
*/
public toStartJobRun() {
return this.to('StartJobRun');
}
/**
* Grants permission to start an interactive session for a project
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_StartProjectSession.html
*/
public toStartProjectSession() {
return this.to('StartProjectSession');
}
/**
* Grants permission to stop a job run for a job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_StopJobRun.html
*/
public toStopJobRun() {
return this.to('StopJobRun');
}
/**
* Grants permission to add tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove tags associated with a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to modify a dataset
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateDataset.html
*/
public toUpdateDataset() {
return this.to('UpdateDataset');
}
/**
* Grants permission to modify a profile job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateProfileJob.html
*/
public toUpdateProfileJob() {
return this.to('UpdateProfileJob');
}
/**
* Grants permission to modify a project
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateProject.html
*/
public toUpdateProject() {
return this.to('UpdateProject');
}
/**
* Grants permission to modify a recipe
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateRecipe.html
*/
public toUpdateRecipe() {
return this.to('UpdateRecipe');
}
/**
* Grants permission to modify a recipe job
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateRecipeJob.html
*/
public toUpdateRecipeJob() {
return this.to('UpdateRecipeJob');
}
/**
* Grants permission to modify a schedule
*
* Access Level: Write
*
* https://docs.aws.amazon.com/databrew/latest/dg/API_UpdateSchedule.html
*/
public toUpdateSchedule() {
return this.to('UpdateSchedule');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"BatchDeleteRecipeVersion",
"CreateDataset",
"CreateProfileJob",
"CreateProject",
"CreateRecipe",
"CreateRecipeJob",
"CreateSchedule",
"DeleteDataset",
"DeleteJob",
"DeleteProject",
"DeleteRecipeVersion",
"DeleteSchedule",
"PublishRecipe",
"SendProjectSessionAction",
"StartJobRun",
"StartProjectSession",
"StopJobRun",
"UpdateDataset",
"UpdateProfileJob",
"UpdateProject",
"UpdateRecipe",
"UpdateRecipeJob",
"UpdateSchedule"
],
"Read": [
"DescribeDataset",
"DescribeJob",
"DescribeJobRun",
"DescribeProject",
"DescribeRecipe",
"DescribeSchedule",
"ListDatasets",
"ListJobRuns",
"ListJobs",
"ListProjects",
"ListRecipeVersions",
"ListRecipes",
"ListSchedules",
"ListTagsForResource"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type Project to the statement
*
* https://docs.aws.amazon.com/databrew/latest/dg/projects.html
*
* @param resourceId - Identifier for the resourceId.
* @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 onProject(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:databrew:${Region}:${Account}:project/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
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 Dataset to the statement
*
* https://docs.aws.amazon.com/databrew/latest/dg/datasets.html
*
* @param resourceId - Identifier for the resourceId.
* @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 onDataset(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:databrew:${Region}:${Account}:dataset/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
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 Recipe to the statement
*
* https://docs.aws.amazon.com/databrew/latest/dg/recipes.html
*
* @param resourceId - Identifier for the resourceId.
* @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 onRecipe(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:databrew:${Region}:${Account}:recipe/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
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 Job to the statement
*
* https://docs.aws.amazon.com/databrew/latest/dg/jobs.html
*
* @param resourceId - Identifier for the resourceId.
* @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 onJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:databrew:${Region}:${Account}:job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
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 Schedule to the statement
*
* https://docs.aws.amazon.com/databrew/latest/dg/jobs.html#jobs.scheduling
*
* @param resourceId - Identifier for the resourceId.
* @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 onSchedule(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:databrew:${Region}:${Account}:schedule/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { Injectable } from '@angular/core';
import { Website } from '../../decorators/website-decorator';
import { MarkdownParser } from 'src/app/utils/helpers/description-parsers/markdown.parser';
import { BaseWebsiteService } from '../base-website-service';
import { LoginProfileManagerService } from 'src/app/login/services/login-profile-manager.service';
import { Submission, SubmissionFormData } from 'src/app/database/models/submission.model';
import { supportsFileType } from '../../helpers/website-validator.helper';
import { MBtoBytes, isGIF, fileAsBlob, decodeText } from 'src/app/utils/helpers/file.helper';
import { TypeOfSubmission, getTypeOfSubmission } from 'src/app/utils/enums/type-of-submission.enum';
import { HttpClient } from '@angular/common/http';
import { WebsiteStatus, LoginStatus, SubmissionPostData, PostResult, WebsiteService } from '../../interfaces/website-service.interface';
import { FurryNetworkSubmissionForm } from './components/furry-network-submission-form/furry-network-submission-form.component';
import { FurryNetworkJournalForm } from './components/furry-network-journal-form/furry-network-journal-form.component';
import { SubmissionType, SubmissionRating } from 'src/app/database/tables/submission.table';
import { ISubmissionFileWithArray } from 'src/app/database/tables/submission-file.table';
import { BrowserWindowHelper } from 'src/app/utils/helpers/browser-window.helper';
const ACCEPTED_FILES = ['png', 'jpeg', 'jpg', 'mp3', 'mp4', 'webm', 'swf', 'gif', 'wav', 'txt', 'plain'];
function submissionValidate(submission: Submission, formData: SubmissionFormData): any[] {
const problems: any[] = [];
if (!supportsFileType(submission.fileInfo, ACCEPTED_FILES)) {
problems.push(['Does not support file format', { website: 'Furry Network', value: submission.fileInfo.type }]);
}
const type: TypeOfSubmission = getTypeOfSubmission(submission.fileInfo);
let maxSize: number = 32;
if (type === TypeOfSubmission.ANIMATION || isGIF(submission.fileInfo)) maxSize = 200;
if (MBtoBytes(maxSize) < submission.fileInfo.size) {
problems.push(['Max file size', { website: `Furry Network [${type}]`, value: `${maxSize}MB` }]);
}
return problems;
}
@Injectable({
providedIn: 'root'
})
@Website({
acceptedFiles: ACCEPTED_FILES,
displayedName: 'Furry Network',
refreshBeforePost: true,
login: {
url: 'https://furrynetwork.com/'
},
components: {
submissionForm: FurryNetworkSubmissionForm,
journalForm: FurryNetworkJournalForm
},
validators: {
submission: submissionValidate
},
parsers: {
description: [MarkdownParser.parse],
usernameShortcut: {
code: 'fn',
url: 'https://furrynetwork.com/$1'
}
}
})
export class FurryNetwork extends BaseWebsiteService implements WebsiteService {
readonly BASE_URL: string = 'https://furrynetwork.com';
private collections: string[] = ['artwork', 'story', 'multimedia'];
constructor(private http: HttpClient, private _profileManager: LoginProfileManagerService) {
super();
}
public async checkStatus(profileId: string): Promise<WebsiteStatus> {
const returnValue: WebsiteStatus = {
username: null,
status: LoginStatus.LOGGED_OUT
};
const data: any = await BrowserWindowHelper.runScript(profileId, this.BASE_URL,
`var x = {};
if (localStorage.token) {
x.token = JSON.parse(localStorage.token);
x.user = JSON.parse(localStorage.user);
}
x`, 5000); // wait in hopes that refresh token fires
if (data) {
if (data.token) {
const { user, token } = data;
this.storeUserInformation(profileId, 'user', user);
this.storeUserInformation(profileId, 'token', token);
returnValue.status = LoginStatus.LOGGED_IN;
returnValue.username = user.characters[0].name;
this.storeUserInformation(profileId, 'info', user);
const promises = user.characters.map(character => this._loadCollections(profileId, token.access_token, character));
await Promise.all(promises);
}
}
return returnValue;
}
public async refreshTokens(profileId: string): Promise<WebsiteStatus> {
return await this.checkStatus(profileId);
}
private async _loadCollections(profileId: string, token: any, character: any): Promise<void> {
const collections: any = {
artwork: [],
story: [],
multimedia: []
};
for (let i = 0; i < this.collections.length; i++) {
const collection = this.collections[i];
const response = await got.get(`${this.BASE_URL}/api/character/${character.name}/${collection}/collections`, this.BASE_URL, [], profileId, {
headers: {
'Authorization': `Bearer ${token}`
}
}).catch(() => console.warn(`No collections for ${character.name}`));
if (response && response.statusCode === 200) {
const body = JSON.parse(response.body)
collections[collection] = body;
}
}
const info = this.userInformation.get(profileId);
info[character.name] = collections;
}
public getProfiles(profileId: string): any[] {
const info = this.userInformation.get(profileId);
return info ? info.info.characters : []
}
public getCollections(profileId: string, profileName: string): any {
const info = this.userInformation.get(profileId);
return info ? info[profileName] : {};
}
private getRating(rating: SubmissionRating): any {
if (rating === SubmissionRating.GENERAL) return 0;
else if (rating === SubmissionRating.MATURE) return 1;
else if (rating === SubmissionRating.ADULT || rating === SubmissionRating.EXTREME) return 2;
else return 0;
}
private getContentType(type: TypeOfSubmission, isGIF: boolean): any {
if (type === TypeOfSubmission.ART && !isGIF) return 'artwork';
if (type === TypeOfSubmission.STORY) return 'story';
if (type === TypeOfSubmission.ANIMATION || type === TypeOfSubmission.AUDIO || isGIF) return 'multimedia'
return 'artwork';
}
public post(submission: Submission, postData: SubmissionPostData): Promise<PostResult> {
if (submission.submissionType === SubmissionType.SUBMISSION) {
return this.postSubmission(submission, postData);
} else if (submission.submissionType === SubmissionType.JOURNAL) {
return this.postJournal(submission, postData);
} else {
throw new Error('Unknown submission type.');
}
}
private async postJournal(submission: Submission, postData: SubmissionPostData): Promise<PostResult> {
const authData = this.userInformation.get(postData.profileId).token;
const data = {
community_tags_allowed: false,
collections: [],
content: postData.description,
description: postData.description.split('.')[0],
rating: this.getRating(postData.rating),
title: postData.title,
subtitle: '',
tags: this.formatTags(postData.tags, []),
status: 'public'
};
const postResponse = await got.post(`${this.BASE_URL}/api/journal`, null, this.BASE_URL, [], {
json: data,
headers: {
'Authorization': `Bearer ${authData.access_token}`
}
});
if (postResponse.error) {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.error));
}
if (postResponse.success.body.id) {
return this.createPostResponse(null);
} else {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.success.body));
}
}
private generateUploadUrl(userProfile: string, file: any, type: any): string {
let uploadURL = '';
if (type === 'story') {
uploadURL = `${this.BASE_URL}/api/story`;
} else {
uploadURL = `${this.BASE_URL}/api/submission/${userProfile}/${type}/upload?` +
'resumableChunkNumber=1' +
`&resumableChunkSize=${file.size}` + `&resumableCurrentChunkSize=${file.size
}&resumableTotalSize=${file.size
}&resumableType=${file.type
}&resumableIdentifier=${file.size}-${file.name.replace('.', '')
}&resumableFilename=${file.name
}&resumableRelativePath=${file.name
}&resumableTotalChunks=1`;
}
return uploadURL;
}
private generatePostData(submission: Submission, postData: SubmissionPostData, type: any): object {
const options = postData.options;
if (type === 'story') {
return {
collections: options.folders || [],
description: postData.description || postData.title,
status: options.status,
title: postData.title,
tags: this.formatTags(postData.tags, []),
rating: this.getRating(postData.rating),
community_tags_allowed: options.communityTags.toString(),
content: decodeText(postData.primary.buffer)
};
} else {
return {
collections: options.folders || [],
description: postData.description,
status: options.status,
title: postData.title,
tags: this.formatTags(postData.tags, []),
rating: this.getRating(postData.rating),
community_tags_allowed: options.communityTags,
publish: options.notify,
};
}
}
private async postSubmission(submission: Submission, postData: SubmissionPostData): Promise<PostResult> {
const authData = this.userInformation.get(postData.profileId).token;
const options = postData.options;
const type = this.getContentType(postData.typeOfSubmission, isGIF(postData.primary.fileInfo));
// Need to check that a correct profile is used
let profile: string = options.profile ? options.profile : null;
const existingProfiles = this.getProfiles(postData.profileId) || [];
if (!existingProfiles.find(p => p.name === profile)) {
profile = existingProfiles[0].name;
options.folders = [];
}
const uploadURL = this.generateUploadUrl(profile, postData.primary.fileInfo, type);
const headers = {
'Authorization': `Bearer ${authData.access_token}`
};
// STORY
if (type === 'story') {
const postResponse = await got.post(uploadURL, null, this.BASE_URL, [], { headers, json: this.generatePostData(submission, postData, type) });
if (postResponse.error) {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.error));
}
if (postResponse.success.body.id) {
return this.createPostResponse(null);
} else {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.success.body));
}
} else { // ANYTHING ELSE
const upload = await this.postChunks(profile, type, postData.primary, headers);
if (!upload) {
return Promise.reject(this.createPostResponse('Unable to upload file', 'Unable to upload file'));
}
const postResponse = await got.patch(`${this.BASE_URL}/api/${type}/${upload.id}`, null, this.BASE_URL, [], { headers, json: this.generatePostData(submission, postData, type) });
if (postResponse.error) {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.error));
}
if (postResponse.success.body.id) {
if (type === 'multimedia' && postData.thumbnail) {
const thumbnailURL = `${this.BASE_URL}/api/submission/${profile}/${type}/${upload.id}/thumbnail?` +
'resumableChunkNumber=1' +
`&resumableChunkSize=${postData.thumbnail.fileInfo.size}` + `&resumableCurrentChunkSize=${postData.thumbnail.fileInfo.size}
&resumableTotalSize=${postData.thumbnail.fileInfo.size}
&resumableType=${postData.thumbnail.fileInfo.type}
&resumableIdentifier=${postData.thumbnail.fileInfo.size}-${postData.thumbnail.fileInfo.name.replace('.', '')}
&resumableFilename=${postData.thumbnail.fileInfo.name}&resumableRelativePath=${postData.thumbnail.fileInfo.name}
&resumableTotalChunks=1`;
this.http.post(thumbnailURL, fileAsBlob(postData.thumbnail), { headers: headers })
.subscribe(success => {
//NOTHING TO DO
}, err => {
//NOTHING TO DO
});
}
const res = this.createPostResponse(null);
res.srcURL = `${this.BASE_URL}/${type}/${postResponse.success.body.id}`;
return res;
} else {
return Promise.reject(this.createPostResponse('Unknown error', postResponse.success.body));
}
}
}
private chunkArray(myArray: Uint8Array, chunk_size: number): Buffer[] {
var index = 0;
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunk_size) {
let myChunk = myArray.slice(index, index + chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
async postChunks(userProfile: any, type: any, file: ISubmissionFileWithArray, headers: any): Promise<any> {
const maxChunkSize = 524288;
const partitions = this.chunkArray(file.buffer, maxChunkSize);
let fileInfo = null;
for (let i = 0; i < partitions.length; i++) {
fileInfo = await this.uploadChunk(headers, userProfile, type, i + 1, partitions.length, file.fileInfo, Buffer.from(partitions[i]), maxChunkSize);
}
return fileInfo;
}
// Legacy code using http.post
uploadChunk(headers: any, userProfile: string, type: string, current: number, total: number, file: any, buffer: Buffer, chunkSize: number): Promise<any> {
const url = `${this.BASE_URL}/api/submission/${userProfile}/${type}/upload?` +
`resumableChunkNumber=${current}` +
`&resumableChunkSize=${chunkSize}` + `&resumableCurrentChunkSize=${buffer.length
}&resumableTotalSize=${file.size
}&resumableType=${file.type
}&resumableIdentifier=${file.size}-${file.name.replace('.', '')
}&resumableFilename=${file.name
}&resumableRelativePath=${file.name
}&resumableTotalChunks=${total}`;
return new Promise((resolve, reject) => {
this.http.post<any>(url, new Blob([new Uint8Array(buffer.subarray(0, buffer.length))], {}), { headers, responseType: 'json' })
.subscribe(res => {
resolve(res);
}, err => reject(err))
});
}
formatTags(defaultTags: string[] = [], other: string[] = []): any {
return super.formatTags(defaultTags, other, '-').filter(tag => tag.length <= 30 && tag.length >= 3)
.map(tag => { return tag.replace(/(\(|\)|:|#|;|\]|\[|'|\.)/g, '').replace(/(\\|\/)/g, '-').replace(/\?/g, 'unknown') })
.filter(tag => tag.length >= 3)
.slice(0, 30);
}
} | the_stack |
import '@testing-library/jest-dom'
import {act, render, screen} from '@testing-library/react'
import React from 'react'
import {mocked} from 'ts-jest/utils'
import userEvent from '@testing-library/user-event'
import {Utils} from '../utils'
import {TestBlockFactory} from '../test/testBlockFactory'
import {mockDOM, wrapDNDIntl} from '../testUtils'
import mutator from '../mutator'
import octoClient from '../octoClient'
import ContentBlock from './contentBlock'
import {CardDetailContext, CardDetailContextType} from './cardDetail/cardDetailContext'
jest.mock('../mutator')
jest.mock('../utils')
jest.mock('../octoClient')
beforeAll(mockDOM)
describe('components/contentBlock', () => {
const mockedMutator = mocked(mutator, true)
const mockedUtils = mocked(Utils, true)
const mockedOcto = mocked(octoClient, true)
mockedUtils.createGuid.mockReturnValue('test-id')
mockedOcto.getFileAsDataUrl.mockResolvedValue('test.jpg')
const board = TestBlockFactory.createBoard()
board.fields.cardProperties = []
board.id = 'board-id'
board.rootId = board.id
const boardView = TestBlockFactory.createBoardView(board)
boardView.id = board.id
const card = TestBlockFactory.createCard(board)
card.id = board.id
card.createdBy = 'user-id-1'
const textBlock = TestBlockFactory.createText(card)
textBlock.id = 'textBlock-id'
const dividerBlock = TestBlockFactory.createDivider(card)
dividerBlock.id = 'dividerBlock-id'
const imageBlock = TestBlockFactory.createImage(card)
imageBlock.fields.fileId = 'test.jpg'
imageBlock.id = 'imageBlock-id'
const commentBlock = TestBlockFactory.createComment(card)
commentBlock.id = 'commentBlock-id'
card.fields.contentOrder = [textBlock.id, dividerBlock.id, commentBlock.id]
const cardDetailContextValue = (autoAdded: boolean): CardDetailContextType => ({
card,
lastAddedBlock: {
id: textBlock.id,
autoAdded,
},
deleteBlock: jest.fn(),
addBlock: jest.fn(),
})
beforeEach(jest.clearAllMocks)
test('should match snapshot with textBlock', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={textBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
expect(container).toMatchSnapshot()
})
test('should match snapshot with dividerBlock', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={dividerBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
expect(container).toMatchSnapshot()
})
test('should match snapshot with commentBlock', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
expect(container).toMatchSnapshot()
})
test('should match snapshot with imageBlock', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={imageBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
expect(container).toMatchSnapshot()
})
test('should match snapshot with commentBlock readonly', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={true}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
expect(container).toMatchSnapshot()
})
test('return commentBlock and click on menuwrapper', async () => {
let container
await act(async () => {
const result = render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
container = result.container
})
const buttonElement = screen.getByRole('button', {name: 'menuwrapper'})
userEvent.click(buttonElement)
expect(container).toMatchSnapshot()
})
test('return commentBlock and click move up', async () => {
await act(async () => {
render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
})
const buttonElement = screen.getByRole('button', {name: 'menuwrapper'})
userEvent.click(buttonElement)
const buttonMoveUp = screen.getByRole('button', {name: 'Move up'})
userEvent.click(buttonMoveUp)
expect(mockedUtils.arrayMove).toBeCalledTimes(1)
expect(mockedMutator.changeCardContentOrder).toBeCalledTimes(1)
})
test('return commentBlock and click move down', async () => {
await act(async () => {
render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
})
const buttonElement = screen.getByRole('button', {name: 'menuwrapper'})
userEvent.click(buttonElement)
const buttonMoveUp = screen.getByRole('button', {name: 'Move down'})
userEvent.click(buttonMoveUp)
expect(mockedUtils.arrayMove).toBeCalledTimes(1)
expect(mockedMutator.changeCardContentOrder).toBeCalledTimes(1)
})
test('return commentBlock and click delete', async () => {
await act(async () => {
render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: -1, z: 0}}
/>
</CardDetailContext.Provider>,
))
})
const buttonElement = screen.getByRole('button', {name: 'menuwrapper'})
userEvent.click(buttonElement)
const buttonMoveUp = screen.getByRole('button', {name: 'Delete'})
userEvent.click(buttonMoveUp)
expect(mockedMutator.performAsUndoGroup).toBeCalledTimes(1)
})
test('return commentBlock and click delete with another contentOrder', async () => {
card.fields.contentOrder = [[textBlock.id], [dividerBlock.id], [commentBlock.id]]
await act(async () => {
render(wrapDNDIntl(
<CardDetailContext.Provider value={cardDetailContextValue(true)}>
<ContentBlock
block={commentBlock}
card={card}
readonly={false}
onDrop={jest.fn()}
width={undefined}
cords={{x: 1, y: 0, z: 0}}
/>
</CardDetailContext.Provider>,
))
})
const buttonElement = screen.getByRole('button', {name: 'menuwrapper'})
userEvent.click(buttonElement)
const buttonMoveUp = screen.getByRole('button', {name: 'Delete'})
userEvent.click(buttonMoveUp)
expect(mockedMutator.performAsUndoGroup).toBeCalledTimes(1)
})
}) | the_stack |
import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce';
import {ArraySpliceOp, spliceArray} from 'neuroglancer/util/array';
import {RefCounted} from 'neuroglancer/util/disposable';
import {removeFromParent, updateChildren} from 'neuroglancer/util/dom';
import {Signal} from 'neuroglancer/util/signal';
// Must be a multiple of 2.
const defaultNumItemsToRender = 10;
const overRenderFraction = 0.5;
export class VirtualListState {
/**
* Index of list element that serves as an anchor for positioning the rendered elements relative
* to the scroll container.
*/
anchorIndex: number = 0;
/**
* Offset of start of anchor item in pixels from the top of the visible content. May be negative
* to indicate that the anchor item starts before the visible viewport.
*/
anchorClientOffset: number = 0;
splice(splices: readonly Readonly<ArraySpliceOp>[]) {
let {anchorIndex} = this;
let offset = 0;
for (const splice of splices) {
offset += splice.retainCount;
if (anchorIndex < offset) break;
const {deleteCount} = splice;
if (anchorIndex < offset + deleteCount) {
anchorIndex = offset;
break;
}
const {insertCount} = splice;
anchorIndex = anchorIndex - deleteCount + insertCount;
offset += insertCount - insertCount;
}
this.anchorIndex = anchorIndex;
}
}
export interface VirtualListSource {
length: number;
render(index: number): HTMLElement;
changed?: Signal<(splices: ArraySpliceOp[]) => void>|undefined;
renderChanged?: Signal|undefined;
}
class RenderParameters {
startIndex: number = 0;
endIndex: number = 0;
anchorIndex: number = 0;
anchorOffset: number = 0;
scrollOffset: number = 0;
}
class SizeEstimates {
/**
* If height of item `i` has already been determined, it is set in `itemSize[i]`. Otherwise,
* `itemSize[i]` is `undefined`.
*/
itemSize: number[] = [];
/**
* Sum of non-`undefined` values in `itemSize`.
*/
totalKnownSize: number = 0;
/**
* Number of non-`undefined` values in `itemSize`.
*/
numItemsInTotalKnownSize: number = 0;
get averageSize() {
return this.totalKnownSize / this.numItemsInTotalKnownSize;
}
getEstimatedSize(index: number) {
return this.itemSize[index] ??this.averageSize;
}
getEstimatedTotalSize() {
return this.totalKnownSize / this.numItemsInTotalKnownSize * this.itemSize.length;
}
getEstimatedOffset(index: number, hintIndex: number = 0, hintOffset = 0) {
for (; hintIndex < index; ++hintIndex) {
hintOffset += this.getEstimatedSize(hintIndex);
}
for (; hintIndex > index; --hintIndex) {
hintOffset -= this.getEstimatedSize(hintIndex - 1);
}
return hintOffset;
}
getRangeSize(begin: number, end: number) {
let size = 0;
const {itemSize, averageSize} = this;
for (let i = begin; i < end; ++i) {
size += itemSize[i] ?? averageSize;
}
return size;
}
splice(splices: readonly Readonly<ArraySpliceOp>[]) {
let {itemSize} = this;
itemSize = this.itemSize = spliceArray(itemSize, splices);
this.totalKnownSize = itemSize.reduce((a, b) => a + b, 0);
this.numItemsInTotalKnownSize = itemSize.reduce(a => a + 1, 0);
}
}
function updateRenderParameters(
newParams: RenderParameters, prevParams: RenderParameters, numItems: number,
viewportHeight: number, sizes: SizeEstimates, state: VirtualListState) {
let {anchorIndex, anchorClientOffset} = state;
let anchorOffset = sizes.getEstimatedOffset(anchorIndex);
let renderStartIndex: number;
let renderEndIndex: number;
let renderAnchorOffset: number;
let renderScrollOffset: number;
let renderAnchorIndex: number;
if (viewportHeight === 0 || sizes.totalKnownSize === 0) {
// Guess
renderStartIndex = Math.max(0, anchorIndex - defaultNumItemsToRender / 2);
renderEndIndex = Math.min(numItems, renderStartIndex + defaultNumItemsToRender);
renderAnchorIndex = anchorIndex;
renderAnchorOffset = 0;
renderScrollOffset = anchorClientOffset;
} else {
const totalSize = sizes.getEstimatedTotalSize();
const maxScrollOffset = Math.max(0, totalSize - viewportHeight);
// Restrict anchorOffset and anchorClientOffset to be valid.
renderScrollOffset = anchorOffset - anchorClientOffset;
renderScrollOffset = Math.max(0, Math.min(maxScrollOffset, renderScrollOffset));
const minStartOffset = renderScrollOffset - 2 * overRenderFraction * viewportHeight;
const maxStartOffset = renderScrollOffset - overRenderFraction * viewportHeight;
const minEndOffset = renderScrollOffset + viewportHeight + overRenderFraction * viewportHeight;
const maxEndOffset = anchorOffset - anchorClientOffset + viewportHeight +
2 * overRenderFraction * viewportHeight;
// Update renderStartIndex
renderStartIndex = Math.min(numItems, prevParams.startIndex);
let renderStartOffset = sizes.getEstimatedOffset(renderStartIndex, anchorIndex, anchorOffset);
if (renderStartOffset < minStartOffset) {
for (; renderStartIndex + 1 < numItems; ++renderStartIndex) {
const itemSize = sizes.getEstimatedSize(renderStartIndex);
if (renderStartOffset + itemSize >= maxStartOffset) break;
renderStartOffset += itemSize;
}
}
if (renderStartOffset >= maxStartOffset) {
for (; renderStartOffset > minStartOffset && renderStartIndex > 0; --renderStartIndex) {
const itemSize = sizes.getEstimatedSize(renderStartIndex - 1);
renderStartOffset -= itemSize;
}
}
// Update renderEndIndex
renderEndIndex = Math.min(numItems, prevParams.endIndex);
let renderEndOffset = sizes.getEstimatedOffset(renderEndIndex, anchorIndex, anchorOffset);
if (renderEndOffset < minEndOffset) {
for (; renderEndOffset <= maxEndOffset && renderEndIndex + 1 <= numItems; ++renderEndIndex) {
const itemSize = sizes.getEstimatedSize(renderEndIndex);
renderEndOffset += itemSize;
}
} else if (renderEndOffset >= maxEndOffset) {
for (; renderEndIndex > renderStartIndex; --renderEndIndex) {
const itemSize = sizes.getEstimatedSize(renderEndIndex - 1);
if (renderEndOffset - itemSize < minEndOffset) break;
renderEndOffset -= itemSize;
}
}
// Update renderAnchorIndex and renderAnchorPixel
renderAnchorIndex = anchorIndex;
renderAnchorOffset = anchorOffset;
for (; renderAnchorIndex < renderStartIndex; ++renderAnchorIndex) {
const itemSize = sizes.getEstimatedSize(renderAnchorIndex);
renderAnchorOffset += itemSize;
}
for (; renderAnchorIndex > renderEndIndex; --renderAnchorIndex) {
const itemSize = sizes.getEstimatedSize(renderAnchorIndex - 1);
renderAnchorOffset -= itemSize;
}
}
newParams.startIndex = renderStartIndex;
newParams.endIndex = renderEndIndex;
newParams.anchorIndex = renderAnchorIndex;
newParams.anchorOffset = renderAnchorOffset;
newParams.scrollOffset = renderScrollOffset;
}
function normalizeRenderParams(p: RenderParameters, sizes: SizeEstimates) {
const anchorOffset = sizes.getEstimatedOffset(p.anchorIndex);
const oldAnchorOffset = p.anchorOffset;
p.anchorOffset = anchorOffset;
p.scrollOffset += (anchorOffset - oldAnchorOffset);
}
function rerenderNeeded(newParams: RenderParameters, prevParams: RenderParameters) {
return newParams.startIndex < prevParams.startIndex || newParams.endIndex > prevParams.endIndex;
}
export class VirtualList extends RefCounted {
// Outer scrollable element
element = document.createElement('div');
// Inner element (not scrollable) that contains `header` and `body`.
scrollContent = document.createElement('div');
header = document.createElement('div');
// Contains `topItems` and `bottomItems` as children.
body = document.createElement('div');
private topItems = document.createElement('div');
private bottomItems = document.createElement('div');
private renderedItems: HTMLElement[] = [];
private renderGeneration = -1;
private listGeneration = -1;
private newRenderedItems: HTMLElement[] = [];
state = new VirtualListState();
private renderParams = new RenderParameters();
private newRenderParams = new RenderParameters();
private sizes = new SizeEstimates();
private source: VirtualListSource;
private debouncedUpdateView =
this.registerCancellable(animationFrameDebounce(() => this.updateView()));
private resizeObserver = new ResizeObserver(() => this.updateView());
constructor(options: {source: VirtualListSource, selectedIndex?: number, horizontalScroll?: boolean}) {
super();
const {selectedIndex} = options;
if (selectedIndex !== undefined) {
this.state.anchorIndex = selectedIndex;
this.state.anchorClientOffset = 0;
}
const source = this.source = options.source;
this.sizes.itemSize.length = source.length;
const {element, header, body, scrollContent, topItems, bottomItems} = this;
this.resizeObserver.observe(element);
this.registerDisposer(() => this.resizeObserver.disconnect());
element.appendChild(scrollContent);
// The default scroll anchoring behavior of browsers interacts poorly with this virtual list
// mechanism and is unnecessary.
element.style.overflowAnchor = 'none';
scrollContent.appendChild(header);
scrollContent.appendChild(body);
header.style.position = 'sticky';
header.style.zIndex = '1';
header.style.top = '0';
if (options.horizontalScroll) {
scrollContent.style.width = 'min-content';
scrollContent.style.minWidth = '100%';
header.style.width = 'min-content';
header.style.minWidth = '100%';
bottomItems.style.width = 'min-content';
bottomItems.style.minWidth = '100%';
} else {
scrollContent.style.width = '100%';
header.style.width = '100%';
bottomItems.style.width = '100%';
}
body.appendChild(topItems);
body.appendChild(bottomItems);
topItems.style.width = 'min-content';
topItems.style.position = 'relative';
topItems.style.height = '0';
topItems.style.minWidth = '100%';
bottomItems.style.height = '0';
bottomItems.style.position = 'relative';
element.addEventListener('scroll', () => {
const scrollOffset = element.scrollTop;
this.state.anchorClientOffset = this.renderParams.anchorOffset - scrollOffset;
this.renderParams.scrollOffset = scrollOffset;
this.debouncedUpdateView();
});
if (source.changed !== undefined) {
this.registerDisposer(source.changed.add(splices => {
this.sizes.splice(splices);
this.state.splice(splices);
this.renderedItems.length = 0;
this.debouncedUpdateView();
}));
}
if (source.renderChanged !== undefined) {
this.registerDisposer(source.renderChanged.add(this.debouncedUpdateView));
}
}
private updateView() {
const {element} = this;
if (element.offsetHeight === 0) {
// Element not visible
return;
}
const viewportHeight = element.clientHeight - this.header.offsetHeight;
const {source, state, sizes} = this;
const numItems = source.length;
const {body, topItems, bottomItems} = this;
const {changed, renderChanged} = source;
let renderParams: RenderParameters;
while (true) {
renderParams = this.newRenderParams;
const prevRenderParams = this.renderParams;
updateRenderParameters(
renderParams, prevRenderParams, numItems, viewportHeight, sizes, state);
let forceRender: boolean;
if ((renderChanged !== undefined && renderChanged.count !== this.renderGeneration) ||
(changed !== undefined && changed.count !== this.listGeneration)) {
this.renderGeneration = renderChanged === undefined ? -1 : renderChanged.count;
this.listGeneration = changed === undefined ? -1 : changed.count;
forceRender = true;
this.renderedItems.length = 0;
} else {
forceRender = false;
}
if (!forceRender && !rerenderNeeded(renderParams, prevRenderParams)) {
prevRenderParams.scrollOffset = renderParams.scrollOffset;
renderParams = prevRenderParams;
break;
}
this.renderParams = renderParams;
this.newRenderParams = prevRenderParams;
const prevRenderedItems = this.renderedItems;
const renderedItems = this.newRenderedItems;
renderedItems.length = 0;
this.renderedItems = renderedItems;
this.newRenderedItems = prevRenderedItems;
const {source} = this;
const {render} = source;
const {startIndex: curStartIndex, endIndex: curEndIndex, anchorIndex} = renderParams;
function* getChildren(start: number, end: number) {
for (let i = start; i < end; ++i) {
let item = prevRenderedItems[i];
if (item === undefined) {
item = render.call(source, i);
}
renderedItems[i] = item;
yield item;
}
}
updateChildren(topItems, getChildren(curStartIndex, anchorIndex));
updateChildren(bottomItems, getChildren(anchorIndex, curEndIndex));
// Update item size estimates.
for (let i = curStartIndex; i < curEndIndex; ++i) {
const element = renderedItems[i];
const bounds = element.getBoundingClientRect();
const newSize = bounds.height;
const existingSize = sizes.itemSize[i];
if (existingSize !== undefined) {
sizes.totalKnownSize -= existingSize;
--sizes.numItemsInTotalKnownSize;
}
sizes.itemSize[i] = newSize;
sizes.totalKnownSize += newSize;
++sizes.numItemsInTotalKnownSize;
}
}
normalizeRenderParams(renderParams, sizes);
state.anchorIndex = renderParams.anchorIndex;
state.anchorClientOffset = renderParams.anchorOffset - renderParams.scrollOffset;
const topSize = sizes.getRangeSize(renderParams.startIndex, renderParams.anchorIndex);
const totalHeight = sizes.getEstimatedTotalSize();
body.style.height = `${totalHeight}px`;
topItems.style.top = `${renderParams.anchorOffset - topSize}px`;
bottomItems.style.top = `${renderParams.anchorOffset}px`;
element.scrollTop = renderParams.scrollOffset;
}
getItemElement(index: number): HTMLElement|undefined {
return this.renderedItems[index];
}
forEachRenderedItem(callback: (element: HTMLElement, index: number) => void) {
const {startIndex, endIndex} = this.renderParams;
const {renderedItems} = this;
for (let i = startIndex; i < endIndex; ++i) {
const item = renderedItems[i];
if (item === undefined) continue;
callback(item, i);
}
}
scrollToTop() {
this.state.anchorIndex = 0;
this.state.anchorClientOffset = 0;
this.debouncedUpdateView();
}
scrollItemIntoView(index: number) {
const itemStartOffset = this.sizes.getEstimatedOffset(index);
const itemEndOffset = itemStartOffset + this.sizes.getEstimatedSize(index);
const startOffset = this.element.scrollTop;
if (itemStartOffset < startOffset) {
this.state.anchorIndex = index;
this.state.anchorClientOffset = 0;
} else if (
itemStartOffset > startOffset && itemEndOffset > startOffset + this.element.offsetHeight) {
this.state.anchorIndex = index + 1;
this.state.anchorClientOffset = this.element.offsetHeight;
} else {
return;
}
this.debouncedUpdateView();
}
disposed() {
removeFromParent(this.element);
}
} | the_stack |
import {OwlBotAPIChanges} from '../src/process-checks/owl-bot-api-changes';
import {describe, it} from 'mocha';
import assert from 'assert';
import nock from 'nock';
const {Octokit} = require('@octokit/rest');
const octokit = new Octokit({
auth: 'mypersonalaccesstoken123',
});
function getPRsOnRepo(
owner: string,
repo: string,
response: {id: number; user: {login: string}}[]
) {
return nock('https://api.github.com')
.get(`/repos/${owner}/${repo}/pulls?state=open`)
.reply(200, response);
}
function getFileOnARepo(
owner: string,
repo: string,
path: string,
response: {name: string; content: string}
) {
return nock('https://api.github.com')
.get(`/repos/${owner}/${repo}/contents/${path}`)
.reply(200, response);
}
function listCommitsOnAPR(
owner: string,
repo: string,
response: {author: {login: string}}[]
) {
return nock('https://api.github.com')
.get(`/repos/${owner}/${repo}/pulls/1/commits`)
.reply(200, response);
}
describe('behavior of OwlBotAPIChanges process', () => {
it('should get constructed with the appropriate values', () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'testAuthor',
'testTitle',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'body'
);
const expectation = {
incomingPR: {
author: 'testAuthor',
title: 'testTitle',
fileCount: 3,
changedFiles: [{filename: 'hello', sha: '2345'}],
repoName: 'testRepoName',
repoOwner: 'testRepoOwner',
prNumber: 1,
body: 'body',
},
classRule: {
author: 'gcf-owl-bot[bot]',
titleRegex: /(breaking|BREAKING|!)/,
bodyRegex: /PiperOrigin-RevId/,
},
octokit,
};
assert.deepStrictEqual(
owlBotTemplateChanges.incomingPR,
expectation.incomingPR
);
assert.deepStrictEqual(
owlBotTemplateChanges.classRule,
expectation.classRule
);
assert.deepStrictEqual(owlBotTemplateChanges.octokit, octokit);
});
it('should return false in checkPR if incoming PR does not match classRules', async () => {
const owlBotAPIChanges = new OwlBotAPIChanges(
'testAuthor',
'testTitle',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'body'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 1, user: {login: 'anotherAuthor'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'testAuthor'}},
]),
];
assert.deepStrictEqual(await owlBotAPIChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return false in checkPR if incoming PR includes a breaking change', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'breaking change: a thing',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'Regenerate this pull request now.' +
'PiperOrigin-RevId: 413686247' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 1, user: {login: 'anotherAuthor'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'gcf-owl-bot[bot]'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return false in checkPR if incoming PR does not include PiperOrigin-RevId', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'a fine title',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'Regenerate this pull request now.' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 1, user: {login: 'anotherAuthor'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'gcf-owl-bot[bot]'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return false in checkPR if incoming PR is not GAPIC_AUTO', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'a fine title',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'PiperOrigin-RevId: 413686247' +
'Regenerate this pull request now.' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX1ZFTkVFUiIsCiAgICAicmVwbyI6ICJnb29nbGVhcGlzL3B5dGhvbi1kbHAiLAogICAgImRpc3RyaWJ1dGlvbl9uYW1lIjogImdvb2dsZS1jbG91ZC1kbHAiLAogICAgImFwaV9pZCI6ICJkbHAuZ29vZ2xlYXBpcy5jb20iLAogICAgInJlcXVpcmVzX2JpbGxpbmciOiB0cnVlLAogICAgImRlZmF1bHRfdmVyc2lvbiI6ICJ2MiIsCiAgICAiY29kZW93bmVyX3RlYW0iOiAiIgp9',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 1, user: {login: 'anotherAuthor'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'gcf-owl-bot[bot]'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return false in checkPR if incoming PR has other PRs that are also from owl-bot', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'a fine title',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'PiperOrigin-RevId: 413686247' +
'Regenerate this pull request now.' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 1, user: {login: 'gcf-owl-bot[bot]'}},
{id: 2, user: {login: 'gcf-owl-bot[bot]'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'gcf-owl-bot[bot]'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return false in checkPR if incoming PR has commits from other authors', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'a fine title',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'PiperOrigin-RevId: 413686247' +
'Regenerate this pull request now.' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 2, user: {login: 'gcf-owl-bot[bot]'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'anotherAuthor'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), false);
scopes.forEach(scope => scope.done());
});
it('should return true in checkPR if incoming PR does match classRules', async () => {
const owlBotTemplateChanges = new OwlBotAPIChanges(
'gcf-owl-bot[bot]',
'a fine title',
3,
[{filename: 'hello', sha: '2345'}],
'testRepoName',
'testRepoOwner',
1,
octokit,
'... signature to CreateFeatureStore, CreateEntityType, CreateFeature feat: add network and enable_private_service_connect to IndexEndpoint feat: add service_attachment to IndexPrivateEndpoints feat: add stratified_split field to training_pipeline InputDataConfig fix: remove invalid resource annotations in LineageSubgraph' +
'PiperOrigin-RevId: 413686247' +
'Regenerate this pull request now.' +
'Source-Link: googleapis/googleapis@244a89d' +
'Source-Link: googleapis/googleapis-gen@c485e44' +
'Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzQ4NWU0NGExYjJmZWY1MTZlOWJjYTM2NTE0ZDUwY2ViZDVlYTUxZiJ9'
);
const scopes = [
getFileOnARepo('testRepoOwner', 'testRepoName', '.repo-metadata.json', {
name: '.repo-metadata.json',
content:
'ewogICAgIm5hbWUiOiAiZGxwIiwKICAgICJuYW1lX3ByZXR0eSI6ICJDbG91ZCBEYXRhIExvc3MgUHJldmVudGlvbiIsCiAgICAicHJvZHVjdF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9kbHAvZG9jcy8iLAogICAgImNsaWVudF9kb2N1bWVudGF0aW9uIjogImh0dHBzOi8vY2xvdWQuZ29vZ2xlLmNvbS9weXRob24vZG9jcy9yZWZlcmVuY2UvZGxwL2xhdGVzdCIsCiAgICAiaXNzdWVfdHJhY2tlciI6ICIiLAogICAgInJlbGVhc2VfbGV2ZWwiOiAiZ2EiLAogICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICAibGlicmFyeV90eXBlIjogIkdBUElDX0FVVE8iLAogICAgInJlcG8iOiAiZ29vZ2xlYXBpcy9weXRob24tZGxwIiwKICAgICJkaXN0cmlidXRpb25fbmFtZSI6ICJnb29nbGUtY2xvdWQtZGxwIiwKICAgICJhcGlfaWQiOiAiZGxwLmdvb2dsZWFwaXMuY29tIiwKICAgICJyZXF1aXJlc19iaWxsaW5nIjogdHJ1ZSwKICAgICJkZWZhdWx0X3ZlcnNpb24iOiAidjIiLAogICAgImNvZGVvd25lcl90ZWFtIjogIiIKfQ==',
}),
getPRsOnRepo('testRepoOwner', 'testRepoName', [
{id: 2, user: {login: 'gcf-owl-bot[bot]'}},
]),
listCommitsOnAPR('testRepoOwner', 'testRepoName', [
{author: {login: 'gcf-owl-bot[bot]'}},
]),
];
assert.deepStrictEqual(await owlBotTemplateChanges.checkPR(), true);
scopes.forEach(scope => scope.done());
});
}); | the_stack |
import * as POGOProtos from 'node-pogo-protos';
/**
* Pogobuf typings created with <3 by hands.
*/
declare namespace pogobuf {
/**
* Pokémon Go RPC client.
*/
export class Client {
/**
* @param {Object} options Client options (see pogobuf wiki for documentation)
*/
constructor(options?: Object);
/**
* Sets the specified client option to the given value.
* Note that not all options support changes after client initialization.
* @param {string} option Option name
* @param {any} value Option value
*/
setOption(option: string, value: any): void;
/**
* Sets the player's latitude and longitude.
* Note that this does not actually update the player location on the server,
* it only sets the location to be used in following API calls.
* To update the location on the server you need to make an API call.
* @param {number|Object} latitude - The player's latitude, or an object with parameters
* @param {number} longitude The player's longitude
* @param {number} accuracy The location accuracy in m (optional) (default value is 0)
* @param {number} altitude The player's altitude (optional) (default value is 0)
*/
setPosition(latitude: number | Object, longitude?: number, accuracy?: number, altitude?: number): void;
/**
* Performs client initialization and downloads needed settings from the API.
*/
init(downloadSettings?: boolean): Promise<any>;
/**
* Sets batch mode. All further API requests will be held and executed in one RPC call when batchCall() is called.
*/
batchStart(): Client;
/**
* Clears the list of batched requests and aborts batch mode.
*/
batchClear(): void;
/**
* Executes any batched requests.
*/
batchCall(): Promise<any>;
/**
* Gets rate limit info from the latest signature server request, if applicable.
*/
getSignatureRateInfo(): Object;
// Pokémon Go API methods
addFortModifier(
modifierItemID: POGOProtos.Inventory.Item.ItemId,
fortID: string
): Promise<POGOProtos.Networking.Responses.AddFortModifierResponse>;
attackGym(
gymID: string,
battleID: string,
attackActions: POGOProtos.Data.Battle.BattleAction[],
lastRetrievedAction: POGOProtos.Data.Battle.BattleAction
): Promise<POGOProtos.Networking.Responses.AttackGymResponse>;
catchPokemon(
encounterID: string | number | Long,
pokeballItemID: POGOProtos.Inventory.Item.ItemId,
normalizedReticleSize: number,
spawnPointID: string,
hitPokemon: boolean,
spinModifier: number,
normalizedHitPosition: number
): Promise<POGOProtos.Networking.Responses.CatchPokemonResponse>;
checkAwardedBadges(
): Promise<POGOProtos.Networking.Responses.CheckAwardedBadgesResponse>;
checkChallenge(
isDebugRequest: boolean
): Promise<POGOProtos.Networking.Responses.CheckChallengeResponse>;
claimCodename(
codename: string
): Promise<POGOProtos.Networking.Responses.ClaimCodenameResponse>;
collectDailyBonus(
): Promise<POGOProtos.Networking.Responses.CollectDailyBonusResponse>;
collectDailyDefenderBonus(
): Promise<POGOProtos.Networking.Responses.CollectDailyDefenderBonusResponse>;
diskEncounter(
encounterID: string | number | Long,
fortID: string
): Promise<POGOProtos.Networking.Responses.DiskEncounterResponse>;
downloadItemTemplates(
paginate: boolean,
pageOffset?: number,
pageTimestamp?: Long
): Promise<POGOProtos.Networking.Responses.DownloadItemTemplatesResponse>;
downloadRemoteConfigVersion(
platform: POGOProtos.Enums.Platform,
deviceManufacturer: string,
deviceModel: string,
locale: string,
appVersion: number
): Promise<POGOProtos.Networking.Responses.DownloadRemoteConfigVersionResponse>;
downloadSettings(
hash?: string
): Promise<POGOProtos.Networking.Responses.DownloadSettingsResponse>;
echo(
): Promise<POGOProtos.Networking.Responses.EchoResponse>;
encounter(
encounterID: string | number | Long,
spawnPointID: string
): Promise<POGOProtos.Networking.Responses.EncounterResponse>;
encounterTutorialComplete(
pokemonID: POGOProtos.Enums.PokemonId
): Promise<POGOProtos.Networking.Responses.EncounterTutorialCompleteResponse>;
equipBadge(
badgeType: POGOProtos.Enums.BadgeType
): Promise<POGOProtos.Networking.Responses.EquipBadgeResponse>;
evolvePokemon(
pokemonID: string | number | Long,
evolutionRequirementItemID?: POGOProtos.Inventory.Item.ItemId
): Promise<POGOProtos.Networking.Responses.EvolvePokemonResponse>;
fortDeployPokemon(
fortID: string,
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.FortDeployPokemonResponse>;
fortDetails(
fortID: string,
fortLatitude: number,
fortLongitude: number
): Promise<POGOProtos.Networking.Responses.FortDetailsResponse>;
fortRecallPokemon(
fortID: string,
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.FortRecallPokemonResponse>;
fortSearch(
fortID: string,
fortLatitude: number,
fortLongitude: number
): Promise<POGOProtos.Networking.Responses.FortSearchResponse>;
getAssetDigest(
platform: POGOProtos.Enums.Platform,
deviceManufacturer: string,
deviceModel: string,
locale: string,
appVersion: number
): Promise<POGOProtos.Networking.Responses.GetAssetDigestResponse>;
getBuddyWalked(
): Promise<POGOProtos.Networking.Responses.GetBuddyWalkedResponse>;
getDownloadURLs(
assetIDs: string[]
): Promise<POGOProtos.Networking.Responses.GetDownloadUrlsResponse>;
getGymDetails(
gymID: string,
gymLatitude: number,
gymLongitude: number,
clientVersion: string
): Promise<POGOProtos.Networking.Responses.GetGymDetailsResponse>;
getHatchedEggs(
): Promise<POGOProtos.Networking.Responses.GetHatchedEggsResponse>;
getIncensePokemon(
): Promise<POGOProtos.Networking.Responses.GetIncensePokemonResponse>;
getInventory(
lastTimestamp?: string | number | Long
): Promise<POGOProtos.Networking.Responses.GetInventoryResponse>;
getMapObjects(
cellIDs: string[] | number[] | Long[],
sinceTimestamps: string[] | number[] | Long[]
): Promise<POGOProtos.Networking.Responses.GetMapObjectsResponse>;
getPlayer(
country: string,
language: string,
timezone: string
): Promise<POGOProtos.Networking.Responses.GetPlayerResponse>;
getPlayerProfile(
playerName: string
): Promise<POGOProtos.Networking.Responses.GetPlayerProfileResponse>;
incenseEncounter(
encounterID: string | number | Long,
encounterLocation: string
): Promise<POGOProtos.Networking.Responses.IncenseEncounterResponse>;
levelUpRewards(
level: number
): Promise<POGOProtos.Networking.Responses.LevelUpRewardsResponse>;
listAvatarCustomizations(
avatarType: POGOProtos.Data.Player.PlayerAvatarType,
slots: POGOProtos.Enums.Slot[],
filters: POGOProtos.Enums.Filter[],
start: number,
limit: number
): Promise<POGOProtos.Networking.Responses.ListAvatarCustomizationsResponse>;
markTutorialComplete(
tutorialsCompleted: POGOProtos.Enums.TutorialState[],
sendMarketingEmails: boolean,
sendPushNotifications: boolean
): Promise<POGOProtos.Networking.Responses.MarkTutorialCompleteResponse>;
nicknamePokemon(
pokemonID: string | number | Long,
nickname: string
): Promise<POGOProtos.Networking.Responses.NicknamePokemonResponse>;
registerBackgroundDevice(
deviceType: string,
deviceID: string
): Promise<POGOProtos.Networking.Responses.RegisterBackgroundDeviceResponse>;
recycleInventoryItem(
itemID: POGOProtos.Inventory.Item.ItemId,
count: number
): Promise<POGOProtos.Networking.Responses.RecycleInventoryItemResponse>;
releasePokemon(
pokemonIDs: string | number | Long | string[] | number[] | Long[]
): Promise<POGOProtos.Networking.Responses.ReleasePokemonResponse>;
setAvatar(
playerAvatar: POGOProtos.Data.Player.PlayerAvatar
): Promise<POGOProtos.Networking.Responses.SetAvatarResponse>;
setAvatarItemAsViewed(
avatarTemplateIDs: string[]
): Promise<POGOProtos.Networking.Responses.SetAvatarItemAsViewedResponse>;
setBuddyPokemon(
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.SetBuddyPokemonResponse>;
setContactSettings(
sendMarketingEmails: boolean,
sendPushNotifications: boolean
): Promise<POGOProtos.Networking.Responses.SetContactSettingsResponse>;
setFavoritePokemon(
pokemonID: string | number | Long,
isFavorite: boolean
): Promise<POGOProtos.Networking.Responses.SetFavoritePokemonResponse>;
setPlayerTeam(
teamColor: POGOProtos.Enums.TeamColor
): Promise<POGOProtos.Networking.Responses.SetPlayerTeamResponse>;
sfidaActionLog(
): Promise<POGOProtos.Networking.Responses.SfidaActionLogResponse>;
startGymBattle(
gymID: string,
attackingPokemonIDs: string[] | number[] | Long[],
defendingPokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.StartGymBattleResponse>;
upgradePokemon(
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.UpgradePokemonResponse>;
useIncense(
itemID: POGOProtos.Inventory.Item.ItemId
): Promise<POGOProtos.Networking.Responses.UseIncenseResponse>;
useItemCapture(
itemID: POGOProtos.Inventory.Item.ItemId,
encounterID: string | number | Long,
spawnPointID: string
): Promise<POGOProtos.Networking.Responses.UseItemCaptureResponse>;
useItemEggIncubator(
itemID: POGOProtos.Inventory.Item.ItemId,
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.UseItemEggIncubatorResponse>;
useItemEncounter(
itemID: POGOProtos.Inventory.Item.ItemId,
encounterID: string | number | Long,
spawnPointGUID: string
): Promise<POGOProtos.Networking.Responses.UseItemEncounterResponse>;
useItemGym(
itemID: POGOProtos.Inventory.Item.ItemId,
gymID: string
): Promise<POGOProtos.Networking.Responses.UseItemGymResponse>;
useItemPotion(
itemID: POGOProtos.Inventory.Item.ItemId,
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.UseItemPotionResponse>;
useItemRevive(
itemID: POGOProtos.Inventory.Item.ItemId,
pokemonID: string | number | Long
): Promise<POGOProtos.Networking.Responses.UseItemReviveResponse>;
useItemXPBoost(
itemID: POGOProtos.Inventory.Item.ItemId
): Promise<POGOProtos.Networking.Responses.UseItemXpBoostResponse>;
verifyChallenge(
token: string
): Promise<POGOProtos.Networking.Responses.VerifyChallengeResponse>;
}
/**
* Pokémon Trainer Club login client.
*/
export class PTCLogin {
/**
* Performs the PTC login process and returns a Promise that will be resolved with the auth token.
* @param {string} username
* @param {string} password
*/
login(username: string, password: string): Promise<string>;
/**
* Sets a proxy address to use for PTC logins.
* @param {string} proxy
*/
setProxy(proxy: string): void;
}
/**
* Google login client.
*/
export class GoogleLogin {
/**
* Performs the Google Login using Android Device and returns a Promise that will be resolved with the auth token.
* @param {string} username
* @param {string} password
*/
login(username: string, password: string): Promise<string>;
/**
* Sets a proxy address to use for logins.
* @param {string} proxy
*/
setProxy(proxy: string): void;
/**
* Performs the Google login by skipping the password step and starting with the Master Token instead.
* Returns a Promise that will be resolved with the auth token.
* @param {string} username
* @param {string} token
*/
loginWithToken(username: string, token: string): Promise<string>;
}
/**
* Various utilities for dealing with Pokémon Go API requests.
*/
export module Utils {
interface Inventory {
pokemon: POGOProtos.Data.PokemonData[],
removed_pokemon: number[],
items: POGOProtos.Inventory.Item.ItemData[],
pokedex: POGOProtos.Data.PokedexEntry[],
player: POGOProtos.Data.Player.PlayerStats,
currency: POGOProtos.Data.Player.PlayerCurrency[],
camera: POGOProtos.Data.Player.PlayerCamera,
inventory_upgrades: POGOProtos.Inventory.InventoryUpgrades[],
applied_items: POGOProtos.Inventory.AppliedItems[],
egg_incubators: POGOProtos.Inventory.EggIncubators[],
candies: POGOProtos.Inventory.Candy[],
quests: POGOProtos.Data.Quests.Quest[]
}
interface ItemTemplates {
pokemon_settings: POGOProtos.Settings.Master.PokemonSettings[],
item_settings: POGOProtos.Settings.Master.ItemSettings[],
move_settings: POGOProtos.Settings.Master.MoveSettings[],
move_sequence_settings: POGOProtos.Settings.Master.MoveSequenceSettings[],
type_effective_settings: POGOProtos.Settings.Master.TypeEffectiveSettings[],
badge_settings: POGOProtos.Settings.Master.BadgeSettings[],
camera_settings: POGOProtos.Settings.Master.CameraSettings,
player_level_settings: POGOProtos.Settings.Master.PlayerLevelSettings,
gym_level_settings: POGOProtos.Settings.Master.GymLevelSettings,
battle_settings: POGOProtos.Settings.Master.GymBattleSettings,
encounter_settings: POGOProtos.Settings.Master.EncounterSettings,
iap_item_display: POGOProtos.Settings.Master.IapItemDisplay[],
iap_settings: POGOProtos.Settings.Master.IapSettings,
pokemon_upgrade_settings: POGOProtos.Settings.Master.PokemonUpgradeSettings,
equipped_badge_settings: POGOProtos.Settings.Master.EquippedBadgeSettings
}
interface Stats {
attack: number,
defend: number,
stamina: number,
percent: number
}
/**
* Provides cell IDs of nearby cells based on the given coords and radius
* @param {number} latitude Latitude
* @param {number} longitude Longitude
* @param {number} radius Radius of the square in cells (optional) (default value is 3)
* @param {number} level S2 cell level (default value is 15)
*/
function getCellIDs(latitude: number, longitude: number, radius?: number, level?: number): string[];
/**
* Takes a getInventory() response and separates it into pokemon, items, candies, player data, eggs, quests, and pokedex.
* @param {object} inventory API response message as returned by getInventory()
*/
function splitInventory(inventory: POGOProtos.Networking.Responses.GetInventoryResponse): Inventory;
/**
* Takes a downloadItemTemplates() response and separates it into the individual settings objects.
* @param {object} templates API response message as returned by downloadItemTemplates()
*/
function splitItemTemplates(templates: POGOProtos.Networking.Responses.DownloadItemTemplatesResponse): ItemTemplates;
/**
* Utility method that finds the name of the key for a given enum value and makes it look a little nicer.
* @param {object} enumObjekt
* @param {number} value
*/
function getEnumKeyByValue(enumObjekt: Object, value: number): string;
/**
* Utility method to get the Individual Values from Pokémon
* @param {object} pokemon A pokemon_data structure
* @param {number} decimals Amount of decimals, negative values do not round, max 20
*/
function getIVsFromPokemon(pokemon: Object, decimals: number): Stats;
/**
* Utility method to convert all Long.js objects to integers or strings
* @param {object} object An object
*/
function convertLongs(object: Object): Object;
}
}
export = pogobuf; | the_stack |
import * as validator from '../utils/validator';
import { deepCopy } from '../utils/deep-copy';
import { AuthClientErrorCode, FirebaseAuthError } from '../utils/error';
/**
* Interface representing base properties of a user-enrolled second factor for a
* `CreateRequest`.
*/
export interface BaseCreateMultiFactorInfoRequest {
/**
* The optional display name for an enrolled second factor.
*/
displayName?: string;
/**
* The type identifier of the second factor. For SMS second factors, this is `phone`.
*/
factorId: string;
}
/**
* Interface representing a phone specific user-enrolled second factor for a
* `CreateRequest`.
*/
export interface CreatePhoneMultiFactorInfoRequest extends BaseCreateMultiFactorInfoRequest {
/**
* The phone number associated with a phone second factor.
*/
phoneNumber: string;
}
/**
* Type representing the properties of a user-enrolled second factor
* for a `CreateRequest`.
*/
export type CreateMultiFactorInfoRequest = | CreatePhoneMultiFactorInfoRequest;
/**
* Interface representing common properties of a user-enrolled second factor
* for an `UpdateRequest`.
*/
export interface BaseUpdateMultiFactorInfoRequest {
/**
* The ID of the enrolled second factor. This ID is unique to the user. When not provided,
* a new one is provisioned by the Auth server.
*/
uid?: string;
/**
* The optional display name for an enrolled second factor.
*/
displayName?: string;
/**
* The optional date the second factor was enrolled, formatted as a UTC string.
*/
enrollmentTime?: string;
/**
* The type identifier of the second factor. For SMS second factors, this is `phone`.
*/
factorId: string;
}
/**
* Interface representing a phone specific user-enrolled second factor
* for an `UpdateRequest`.
*/
export interface UpdatePhoneMultiFactorInfoRequest extends BaseUpdateMultiFactorInfoRequest {
/**
* The phone number associated with a phone second factor.
*/
phoneNumber: string;
}
/**
* Type representing the properties of a user-enrolled second factor
* for an `UpdateRequest`.
*/
export type UpdateMultiFactorInfoRequest = | UpdatePhoneMultiFactorInfoRequest;
/**
* The multi-factor related user settings for create operations.
*/
export interface MultiFactorCreateSettings {
/**
* The created user's list of enrolled second factors.
*/
enrolledFactors: CreateMultiFactorInfoRequest[];
}
/**
* The multi-factor related user settings for update operations.
*/
export interface MultiFactorUpdateSettings {
/**
* The updated list of enrolled second factors. The provided list overwrites the user's
* existing list of second factors.
* When null is passed, all of the user's existing second factors are removed.
*/
enrolledFactors: UpdateMultiFactorInfoRequest[] | null;
}
/**
* Interface representing the properties to update on the provided user.
*/
export interface UpdateRequest {
/**
* Whether or not the user is disabled: `true` for disabled;
* `false` for enabled.
*/
disabled?: boolean;
/**
* The user's display name.
*/
displayName?: string | null;
/**
* The user's primary email.
*/
email?: string;
/**
* Whether or not the user's primary email is verified.
*/
emailVerified?: boolean;
/**
* The user's unhashed password.
*/
password?: string;
/**
* The user's primary phone number.
*/
phoneNumber?: string | null;
/**
* The user's photo URL.
*/
photoURL?: string | null;
/**
* The user's updated multi-factor related properties.
*/
multiFactor?: MultiFactorUpdateSettings;
/**
* Links this user to the specified provider.
*
* Linking a provider to an existing user account does not invalidate the
* refresh token of that account. In other words, the existing account
* would continue to be able to access resources, despite not having used
* the newly linked provider to log in. If you wish to force the user to
* authenticate with this new provider, you need to (a) revoke their
* refresh token (see
* https://firebase.google.com/docs/auth/admin/manage-sessions#revoke_refresh_tokens),
* and (b) ensure no other authentication methods are present on this
* account.
*/
providerToLink?: UserProvider;
/**
* Unlinks this user from the specified providers.
*/
providersToUnlink?: string[];
}
/**
* Represents a user identity provider that can be associated with a Firebase user.
*/
export interface UserProvider {
/**
* The user identifier for the linked provider.
*/
uid?: string;
/**
* The display name for the linked provider.
*/
displayName?: string;
/**
* The email for the linked provider.
*/
email?: string;
/**
* The phone number for the linked provider.
*/
phoneNumber?: string;
/**
* The photo URL for the linked provider.
*/
photoURL?: string;
/**
* The linked provider ID (for example, "google.com" for the Google provider).
*/
providerId?: string;
}
/**
* Interface representing the properties to set on a new user record to be
* created.
*/
export interface CreateRequest extends UpdateRequest {
/**
* The user's `uid`.
*/
uid?: string;
/**
* The user's multi-factor related properties.
*/
multiFactor?: MultiFactorCreateSettings;
}
/**
* The response interface for listing provider configs. This is only available
* when listing all identity providers' configurations via
* {@link BaseAuth.listProviderConfigs}.
*/
export interface ListProviderConfigResults {
/**
* The list of providers for the specified type in the current page.
*/
providerConfigs: AuthProviderConfig[];
/**
* The next page token, if available.
*/
pageToken?: string;
}
/**
* The filter interface used for listing provider configurations. This is used
* when specifying how to list configured identity providers via
* {@link BaseAuth.listProviderConfigs}.
*/
export interface AuthProviderConfigFilter {
/**
* The Auth provider configuration filter. This can be either `saml` or `oidc`.
* The former is used to look up SAML providers only, while the latter is used
* for OIDC providers.
*/
type: 'saml' | 'oidc';
/**
* The maximum number of results to return per page. The default and maximum is
* 100.
*/
maxResults?: number;
/**
* The next page token. When not specified, the lookup starts from the beginning
* of the list.
*/
pageToken?: string;
}
/**
* The request interface for updating a SAML Auth provider. This is used
* when updating a SAML provider's configuration via
* {@link BaseAuth.updateProviderConfig}.
*/
export interface SAMLUpdateAuthProviderRequest {
/**
* The SAML provider's updated display name. If not provided, the existing
* configuration's value is not modified.
*/
displayName?: string;
/**
* Whether the SAML provider is enabled or not. If not provided, the existing
* configuration's setting is not modified.
*/
enabled?: boolean;
/**
* The SAML provider's updated IdP entity ID. If not provided, the existing
* configuration's value is not modified.
*/
idpEntityId?: string;
/**
* The SAML provider's updated SSO URL. If not provided, the existing
* configuration's value is not modified.
*/
ssoURL?: string;
/**
* The SAML provider's updated list of X.509 certificated. If not provided, the
* existing configuration list is not modified.
*/
x509Certificates?: string[];
/**
* The SAML provider's updated RP entity ID. If not provided, the existing
* configuration's value is not modified.
*/
rpEntityId?: string;
/**
* The SAML provider's callback URL. If not provided, the existing
* configuration's value is not modified.
*/
callbackURL?: string;
}
/**
* The request interface for updating an OIDC Auth provider. This is used
* when updating an OIDC provider's configuration via
* {@link BaseAuth.updateProviderConfig}.
*/
export interface OIDCUpdateAuthProviderRequest {
/**
* The OIDC provider's updated display name. If not provided, the existing
* configuration's value is not modified.
*/
displayName?: string;
/**
* Whether the OIDC provider is enabled or not. If not provided, the existing
* configuration's setting is not modified.
*/
enabled?: boolean;
/**
* The OIDC provider's updated client ID. If not provided, the existing
* configuration's value is not modified.
*/
clientId?: string;
/**
* The OIDC provider's updated issuer. If not provided, the existing
* configuration's value is not modified.
*/
issuer?: string;
/**
* The OIDC provider's client secret to enable OIDC code flow.
* If not provided, the existing configuration's value is not modified.
*/
clientSecret?: string;
/**
* The OIDC provider's response object for OAuth authorization flow.
*/
responseType?: OAuthResponseType;
}
export type UpdateAuthProviderRequest =
SAMLUpdateAuthProviderRequest | OIDCUpdateAuthProviderRequest;
/** A maximum of 10 test phone number / code pairs can be configured. */
export const MAXIMUM_TEST_PHONE_NUMBERS = 10;
/** The server side SAML configuration request interface. */
export interface SAMLConfigServerRequest {
idpConfig?: {
idpEntityId?: string;
ssoUrl?: string;
idpCertificates?: Array<{
x509Certificate: string;
}>;
signRequest?: boolean;
};
spConfig?: {
spEntityId?: string;
callbackUri?: string;
};
displayName?: string;
enabled?: boolean;
[key: string]: any;
}
/** The server side SAML configuration response interface. */
export interface SAMLConfigServerResponse {
// Used when getting config.
// projects/${projectId}/inboundSamlConfigs/${providerId}
name?: string;
idpConfig?: {
idpEntityId?: string;
ssoUrl?: string;
idpCertificates?: Array<{
x509Certificate: string;
}>;
signRequest?: boolean;
};
spConfig?: {
spEntityId?: string;
callbackUri?: string;
};
displayName?: string;
enabled?: boolean;
}
/** The server side OIDC configuration request interface. */
export interface OIDCConfigServerRequest {
clientId?: string;
issuer?: string;
displayName?: string;
enabled?: boolean;
clientSecret?: string;
responseType?: OAuthResponseType;
[key: string]: any;
}
/** The server side OIDC configuration response interface. */
export interface OIDCConfigServerResponse {
// Used when getting config.
// projects/${projectId}/oauthIdpConfigs/${providerId}
name?: string;
clientId?: string;
issuer?: string;
displayName?: string;
enabled?: boolean;
clientSecret?: string;
responseType?: OAuthResponseType;
}
/** The server side email configuration request interface. */
export interface EmailSignInConfigServerRequest {
allowPasswordSignup?: boolean;
enableEmailLinkSignin?: boolean;
}
/** Identifies the server side second factor type. */
type AuthFactorServerType = 'PHONE_SMS';
/** Client Auth factor type to server auth factor type mapping. */
const AUTH_FACTOR_CLIENT_TO_SERVER_TYPE: {[key: string]: AuthFactorServerType} = {
phone: 'PHONE_SMS',
};
/** Server Auth factor type to client auth factor type mapping. */
const AUTH_FACTOR_SERVER_TO_CLIENT_TYPE: {[key: string]: AuthFactorType} =
Object.keys(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE)
.reduce((res: {[key: string]: AuthFactorType}, key) => {
res[AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[key]] = key as AuthFactorType;
return res;
}, {});
/** Server side multi-factor configuration. */
export interface MultiFactorAuthServerConfig {
state?: MultiFactorConfigState;
enabledProviders?: AuthFactorServerType[];
}
/**
* Identifies a second factor type.
*/
export type AuthFactorType = 'phone';
/**
* Identifies a multi-factor configuration state.
*/
export type MultiFactorConfigState = 'ENABLED' | 'DISABLED';
/**
* Interface representing a multi-factor configuration.
* This can be used to define whether multi-factor authentication is enabled
* or disabled and the list of second factor challenges that are supported.
*/
export interface MultiFactorConfig {
/**
* The multi-factor config state.
*/
state: MultiFactorConfigState;
/**
* The list of identifiers for enabled second factors.
* Currently only ‘phone’ is supported.
*/
factorIds?: AuthFactorType[];
}
/**
* Defines the multi-factor config class used to convert client side MultiFactorConfig
* to a format that is understood by the Auth server.
*/
export class MultiFactorAuthConfig implements MultiFactorConfig {
public readonly state: MultiFactorConfigState;
public readonly factorIds: AuthFactorType[];
/**
* Static method to convert a client side request to a MultiFactorAuthServerConfig.
* Throws an error if validation fails.
*
* @param options - The options object to convert to a server request.
* @returns The resulting server request.
* @internal
*/
public static buildServerRequest(options: MultiFactorConfig): MultiFactorAuthServerConfig {
const request: MultiFactorAuthServerConfig = {};
MultiFactorAuthConfig.validate(options);
if (Object.prototype.hasOwnProperty.call(options, 'state')) {
request.state = options.state;
}
if (Object.prototype.hasOwnProperty.call(options, 'factorIds')) {
(options.factorIds || []).forEach((factorId) => {
if (typeof request.enabledProviders === 'undefined') {
request.enabledProviders = [];
}
request.enabledProviders.push(AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId]);
});
// In case an empty array is passed. Ensure it gets populated so the array is cleared.
if (options.factorIds && options.factorIds.length === 0) {
request.enabledProviders = [];
}
}
return request;
}
/**
* Validates the MultiFactorConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
*/
private static validate(options: MultiFactorConfig): void {
const validKeys = {
state: true,
factorIds: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig" must be a non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${key}" is not a valid MultiFactorConfig parameter.`,
);
}
}
// Validate content.
if (typeof options.state !== 'undefined' &&
options.state !== 'ENABLED' &&
options.state !== 'DISABLED') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig.state" must be either "ENABLED" or "DISABLED".',
);
}
if (typeof options.factorIds !== 'undefined') {
if (!validator.isArray(options.factorIds)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"MultiFactorConfig.factorIds" must be an array of valid "AuthFactorTypes".',
);
}
// Validate content of array.
options.factorIds.forEach((factorId) => {
if (typeof AUTH_FACTOR_CLIENT_TO_SERVER_TYPE[factorId] === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${factorId}" is not a valid "AuthFactorType".`,
);
}
});
}
}
/**
* The MultiFactorAuthConfig constructor.
*
* @param response - The server side response used to initialize the
* MultiFactorAuthConfig object.
* @constructor
* @internal
*/
constructor(response: MultiFactorAuthServerConfig) {
if (typeof response.state === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid multi-factor configuration response');
}
this.state = response.state;
this.factorIds = [];
(response.enabledProviders || []).forEach((enabledProvider) => {
// Ignore unsupported types. It is possible the current admin SDK version is
// not up to date and newer backend types are supported.
if (typeof AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider] !== 'undefined') {
this.factorIds.push(AUTH_FACTOR_SERVER_TO_CLIENT_TYPE[enabledProvider]);
}
})
}
/** @returns The plain object representation of the multi-factor config instance. */
public toJSON(): object {
return {
state: this.state,
factorIds: this.factorIds,
};
}
}
/**
* Validates the provided map of test phone number / code pairs.
* @param testPhoneNumbers - The phone number / code pairs to validate.
*/
export function validateTestPhoneNumbers(
testPhoneNumbers: {[phoneNumber: string]: string},
): void {
if (!validator.isObject(testPhoneNumbers)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"testPhoneNumbers" must be a map of phone number / code pairs.',
);
}
if (Object.keys(testPhoneNumbers).length > MAXIMUM_TEST_PHONE_NUMBERS) {
throw new FirebaseAuthError(AuthClientErrorCode.MAXIMUM_TEST_PHONE_NUMBER_EXCEEDED);
}
for (const phoneNumber in testPhoneNumbers) {
// Validate phone number.
if (!validator.isPhoneNumber(phoneNumber)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER,
`"${phoneNumber}" is not a valid E.164 standard compliant phone number.`
);
}
// Validate code.
if (!validator.isString(testPhoneNumbers[phoneNumber]) ||
!/^[\d]{6}$/.test(testPhoneNumbers[phoneNumber])) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_TESTING_PHONE_NUMBER,
`"${testPhoneNumbers[phoneNumber]}" is not a valid 6 digit code string.`
);
}
}
}
/**
* The email sign in provider configuration.
*/
export interface EmailSignInProviderConfig {
/**
* Whether email provider is enabled.
*/
enabled: boolean;
/**
* Whether password is required for email sign-in. When not required,
* email sign-in can be performed with password or via email link sign-in.
*/
passwordRequired?: boolean; // In the backend API, default is true if not provided
}
/**
* Defines the email sign-in config class used to convert client side EmailSignInConfig
* to a format that is understood by the Auth server.
*
* @internal
*/
export class EmailSignInConfig implements EmailSignInProviderConfig {
public readonly enabled: boolean;
public readonly passwordRequired?: boolean;
/**
* Static method to convert a client side request to a EmailSignInConfigServerRequest.
* Throws an error if validation fails.
*
* @param options - The options object to convert to a server request.
* @returns The resulting server request.
* @internal
*/
public static buildServerRequest(options: EmailSignInProviderConfig): EmailSignInConfigServerRequest {
const request: EmailSignInConfigServerRequest = {};
EmailSignInConfig.validate(options);
if (Object.prototype.hasOwnProperty.call(options, 'enabled')) {
request.allowPasswordSignup = options.enabled;
}
if (Object.prototype.hasOwnProperty.call(options, 'passwordRequired')) {
request.enableEmailLinkSignin = !options.passwordRequired;
}
return request;
}
/**
* Validates the EmailSignInConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
*/
private static validate(options: EmailSignInProviderConfig): void {
// TODO: Validate the request.
const validKeys = {
enabled: true,
passwordRequired: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig" must be a non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
`"${key}" is not a valid EmailSignInConfig parameter.`,
);
}
}
// Validate content.
if (typeof options.enabled !== 'undefined' &&
!validator.isBoolean(options.enabled)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig.enabled" must be a boolean.',
);
}
if (typeof options.passwordRequired !== 'undefined' &&
!validator.isBoolean(options.passwordRequired)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"EmailSignInConfig.passwordRequired" must be a boolean.',
);
}
}
/**
* The EmailSignInConfig constructor.
*
* @param response - The server side response used to initialize the
* EmailSignInConfig object.
* @constructor
*/
constructor(response: {[key: string]: any}) {
if (typeof response.allowPasswordSignup === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid email sign-in configuration response');
}
this.enabled = response.allowPasswordSignup;
this.passwordRequired = !response.enableEmailLinkSignin;
}
/** @returns The plain object representation of the email sign-in config. */
public toJSON(): object {
return {
enabled: this.enabled,
passwordRequired: this.passwordRequired,
};
}
}
/**
* The base Auth provider configuration interface.
*/
export interface BaseAuthProviderConfig {
/**
* The provider ID defined by the developer.
* For a SAML provider, this is always prefixed by `saml.`.
* For an OIDC provider, this is always prefixed by `oidc.`.
*/
providerId: string;
/**
* The user-friendly display name to the current configuration. This name is
* also used as the provider label in the Cloud Console.
*/
displayName?: string;
/**
* Whether the provider configuration is enabled or disabled. A user
* cannot sign in using a disabled provider.
*/
enabled: boolean;
}
/**
* The
* [SAML](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html)
* Auth provider configuration interface. A SAML provider can be created via
* {@link BaseAuth.createProviderConfig}.
*/
export interface SAMLAuthProviderConfig extends BaseAuthProviderConfig {
/**
* The SAML IdP entity identifier.
*/
idpEntityId: string;
/**
* The SAML IdP SSO URL. This must be a valid URL.
*/
ssoURL: string;
/**
* The list of SAML IdP X.509 certificates issued by CA for this provider.
* Multiple certificates are accepted to prevent outages during
* IdP key rotation (for example ADFS rotates every 10 days). When the Auth
* server receives a SAML response, it will match the SAML response with the
* certificate on record. Otherwise the response is rejected.
* Developers are expected to manage the certificate updates as keys are
* rotated.
*/
x509Certificates: string[];
/**
* The SAML relying party (service provider) entity ID.
* This is defined by the developer but needs to be provided to the SAML IdP.
*/
rpEntityId: string;
/**
* This is fixed and must always be the same as the OAuth redirect URL
* provisioned by Firebase Auth,
* `https://project-id.firebaseapp.com/__/auth/handler` unless a custom
* `authDomain` is used.
* The callback URL should also be provided to the SAML IdP during
* configuration.
*/
callbackURL?: string;
}
/**
* The interface representing OIDC provider's response object for OAuth
* authorization flow.
* One of the following settings is required:
* <ul>
* <li>Set <code>code</code> to <code>true</code> for the code flow.</li>
* <li>Set <code>idToken</code> to <code>true</code> for the ID token flow.</li>
* </ul>
*/
export interface OAuthResponseType {
/**
* Whether ID token is returned from IdP's authorization endpoint.
*/
idToken?: boolean;
/**
* Whether authorization code is returned from IdP's authorization endpoint.
*/
code?: boolean;
}
/**
* The [OIDC](https://openid.net/specs/openid-connect-core-1_0-final.html) Auth
* provider configuration interface. An OIDC provider can be created via
* {@link BaseAuth.createProviderConfig}.
*/
export interface OIDCAuthProviderConfig extends BaseAuthProviderConfig {
/**
* This is the required client ID used to confirm the audience of an OIDC
* provider's
* [ID token](https://openid.net/specs/openid-connect-core-1_0-final.html#IDToken).
*/
clientId: string;
/**
* This is the required provider issuer used to match the provider issuer of
* the ID token and to determine the corresponding OIDC discovery document, eg.
* [`/.well-known/openid-configuration`](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig).
* This is needed for the following:
* <ul>
* <li>To verify the provided issuer.</li>
* <li>Determine the authentication/authorization endpoint during the OAuth
* `id_token` authentication flow.</li>
* <li>To retrieve the public signing keys via `jwks_uri` to verify the OIDC
* provider's ID token's signature.</li>
* <li>To determine the claims_supported to construct the user attributes to be
* returned in the additional user info response.</li>
* </ul>
* ID token validation will be performed as defined in the
* [spec](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation).
*/
issuer: string;
/**
* The OIDC provider's client secret to enable OIDC code flow.
*/
clientSecret?: string;
/**
* The OIDC provider's response object for OAuth authorization flow.
*/
responseType?: OAuthResponseType;
}
/**
* The Auth provider configuration type.
* {@link BaseAuth.createProviderConfig}.
*/
export type AuthProviderConfig = SAMLAuthProviderConfig | OIDCAuthProviderConfig;
/**
* Defines the SAMLConfig class used to convert a client side configuration to its
* server side representation.
*
* @internal
*/
export class SAMLConfig implements SAMLAuthProviderConfig {
public readonly enabled: boolean;
public readonly displayName?: string;
public readonly providerId: string;
public readonly idpEntityId: string;
public readonly ssoURL: string;
public readonly x509Certificates: string[];
public readonly rpEntityId: string;
public readonly callbackURL?: string;
public readonly enableRequestSigning?: boolean;
/**
* Converts a client side request to a SAMLConfigServerRequest which is the format
* accepted by the backend server.
* Throws an error if validation fails. If the request is not a SAMLConfig request,
* returns null.
*
* @param options - The options object to convert to a server request.
* @param ignoreMissingFields - Whether to ignore missing fields.
* @returns The resulting server request or null if not valid.
*/
public static buildServerRequest(
options: Partial<SAMLAuthProviderConfig>,
ignoreMissingFields = false): SAMLConfigServerRequest | null {
const makeRequest = validator.isNonNullObject(options) &&
(options.providerId || ignoreMissingFields);
if (!makeRequest) {
return null;
}
const request: SAMLConfigServerRequest = {};
// Validate options.
SAMLConfig.validate(options, ignoreMissingFields);
request.enabled = options.enabled;
request.displayName = options.displayName;
// IdP config.
if (options.idpEntityId || options.ssoURL || options.x509Certificates) {
request.idpConfig = {
idpEntityId: options.idpEntityId,
ssoUrl: options.ssoURL,
signRequest: (options as any).enableRequestSigning,
idpCertificates: typeof options.x509Certificates === 'undefined' ? undefined : [],
};
if (options.x509Certificates) {
for (const cert of (options.x509Certificates || [])) {
request.idpConfig!.idpCertificates!.push({ x509Certificate: cert });
}
}
}
// RP config.
if (options.callbackURL || options.rpEntityId) {
request.spConfig = {
spEntityId: options.rpEntityId,
callbackUri: options.callbackURL,
};
}
return request;
}
/**
* Returns the provider ID corresponding to the resource name if available.
*
* @param resourceName - The server side resource name.
* @returns The provider ID corresponding to the resource, null otherwise.
*/
public static getProviderIdFromResourceName(resourceName: string): string | null {
// name is of form projects/project1/inboundSamlConfigs/providerId1
const matchProviderRes = resourceName.match(/\/inboundSamlConfigs\/(saml\..*)$/);
if (!matchProviderRes || matchProviderRes.length < 2) {
return null;
}
return matchProviderRes[1];
}
/**
* @param providerId - The provider ID to check.
* @returns Whether the provider ID corresponds to a SAML provider.
*/
public static isProviderId(providerId: any): providerId is string {
return validator.isNonEmptyString(providerId) && providerId.indexOf('saml.') === 0;
}
/**
* Validates the SAMLConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
* @param ignoreMissingFields - Whether to ignore missing fields.
*/
public static validate(options: Partial<SAMLAuthProviderConfig>, ignoreMissingFields = false): void {
const validKeys = {
enabled: true,
displayName: true,
providerId: true,
idpEntityId: true,
ssoURL: true,
x509Certificates: true,
rpEntityId: true,
callbackURL: true,
enableRequestSigning: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig" must be a valid non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${key}" is not a valid SAML config parameter.`,
);
}
}
// Required fields.
if (validator.isNonEmptyString(options.providerId)) {
if (options.providerId.indexOf('saml.') !== 0) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_PROVIDER_ID,
'"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".',
);
}
} else if (!ignoreMissingFields) {
// providerId is required and not provided correctly.
throw new FirebaseAuthError(
!options.providerId ? AuthClientErrorCode.MISSING_PROVIDER_ID : AuthClientErrorCode.INVALID_PROVIDER_ID,
'"SAMLAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "saml.".',
);
}
if (!(ignoreMissingFields && typeof options.idpEntityId === 'undefined') &&
!validator.isNonEmptyString(options.idpEntityId)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.idpEntityId" must be a valid non-empty string.',
);
}
if (!(ignoreMissingFields && typeof options.ssoURL === 'undefined') &&
!validator.isURL(options.ssoURL)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.ssoURL" must be a valid URL string.',
);
}
if (!(ignoreMissingFields && typeof options.rpEntityId === 'undefined') &&
!validator.isNonEmptyString(options.rpEntityId)) {
throw new FirebaseAuthError(
!options.rpEntityId ? AuthClientErrorCode.MISSING_SAML_RELYING_PARTY_CONFIG :
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.rpEntityId" must be a valid non-empty string.',
);
}
if (!(ignoreMissingFields && typeof options.callbackURL === 'undefined') &&
!validator.isURL(options.callbackURL)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.callbackURL" must be a valid URL string.',
);
}
if (!(ignoreMissingFields && typeof options.x509Certificates === 'undefined') &&
!validator.isArray(options.x509Certificates)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.',
);
}
(options.x509Certificates || []).forEach((cert: string) => {
if (!validator.isNonEmptyString(cert)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.x509Certificates" must be a valid array of X509 certificate strings.',
);
}
});
if (typeof (options as any).enableRequestSigning !== 'undefined' &&
!validator.isBoolean((options as any).enableRequestSigning)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.enableRequestSigning" must be a boolean.',
);
}
if (typeof options.enabled !== 'undefined' &&
!validator.isBoolean(options.enabled)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.enabled" must be a boolean.',
);
}
if (typeof options.displayName !== 'undefined' &&
!validator.isString(options.displayName)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"SAMLAuthProviderConfig.displayName" must be a valid string.',
);
}
}
/**
* The SAMLConfig constructor.
*
* @param response - The server side response used to initialize the SAMLConfig object.
* @constructor
*/
constructor(response: SAMLConfigServerResponse) {
if (!response ||
!response.idpConfig ||
!response.idpConfig.idpEntityId ||
!response.idpConfig.ssoUrl ||
!response.spConfig ||
!response.spConfig.spEntityId ||
!response.name ||
!(validator.isString(response.name) &&
SAMLConfig.getProviderIdFromResourceName(response.name))) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
}
const providerId = SAMLConfig.getProviderIdFromResourceName(response.name);
if (!providerId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
}
this.providerId = providerId;
// RP config.
this.rpEntityId = response.spConfig.spEntityId;
this.callbackURL = response.spConfig.callbackUri;
// IdP config.
this.idpEntityId = response.idpConfig.idpEntityId;
this.ssoURL = response.idpConfig.ssoUrl;
this.enableRequestSigning = !!response.idpConfig.signRequest;
const x509Certificates: string[] = [];
for (const cert of (response.idpConfig.idpCertificates || [])) {
if (cert.x509Certificate) {
x509Certificates.push(cert.x509Certificate);
}
}
this.x509Certificates = x509Certificates;
// When enabled is undefined, it takes its default value of false.
this.enabled = !!response.enabled;
this.displayName = response.displayName;
}
/** @returns The plain object representation of the SAMLConfig. */
public toJSON(): object {
return {
enabled: this.enabled,
displayName: this.displayName,
providerId: this.providerId,
idpEntityId: this.idpEntityId,
ssoURL: this.ssoURL,
x509Certificates: deepCopy(this.x509Certificates),
rpEntityId: this.rpEntityId,
callbackURL: this.callbackURL,
enableRequestSigning: this.enableRequestSigning,
};
}
}
/**
* Defines the OIDCConfig class used to convert a client side configuration to its
* server side representation.
*
* @internal
*/
export class OIDCConfig implements OIDCAuthProviderConfig {
public readonly enabled: boolean;
public readonly displayName?: string;
public readonly providerId: string;
public readonly issuer: string;
public readonly clientId: string;
public readonly clientSecret?: string;
public readonly responseType: OAuthResponseType;
/**
* Converts a client side request to a OIDCConfigServerRequest which is the format
* accepted by the backend server.
* Throws an error if validation fails. If the request is not a OIDCConfig request,
* returns null.
*
* @param options - The options object to convert to a server request.
* @param ignoreMissingFields - Whether to ignore missing fields.
* @returns The resulting server request or null if not valid.
*/
public static buildServerRequest(
options: Partial<OIDCAuthProviderConfig>,
ignoreMissingFields = false): OIDCConfigServerRequest | null {
const makeRequest = validator.isNonNullObject(options) &&
(options.providerId || ignoreMissingFields);
if (!makeRequest) {
return null;
}
const request: OIDCConfigServerRequest = {};
// Validate options.
OIDCConfig.validate(options, ignoreMissingFields);
request.enabled = options.enabled;
request.displayName = options.displayName;
request.issuer = options.issuer;
request.clientId = options.clientId;
if (typeof options.clientSecret !== 'undefined') {
request.clientSecret = options.clientSecret;
}
if (typeof options.responseType !== 'undefined') {
request.responseType = options.responseType;
}
return request;
}
/**
* Returns the provider ID corresponding to the resource name if available.
*
* @param resourceName - The server side resource name
* @returns The provider ID corresponding to the resource, null otherwise.
*/
public static getProviderIdFromResourceName(resourceName: string): string | null {
// name is of form projects/project1/oauthIdpConfigs/providerId1
const matchProviderRes = resourceName.match(/\/oauthIdpConfigs\/(oidc\..*)$/);
if (!matchProviderRes || matchProviderRes.length < 2) {
return null;
}
return matchProviderRes[1];
}
/**
* @param providerId - The provider ID to check.
* @returns Whether the provider ID corresponds to an OIDC provider.
*/
public static isProviderId(providerId: any): providerId is string {
return validator.isNonEmptyString(providerId) && providerId.indexOf('oidc.') === 0;
}
/**
* Validates the OIDCConfig options object. Throws an error on failure.
*
* @param options - The options object to validate.
* @param ignoreMissingFields - Whether to ignore missing fields.
*/
public static validate(options: Partial<OIDCAuthProviderConfig>, ignoreMissingFields = false): void {
const validKeys = {
enabled: true,
displayName: true,
providerId: true,
clientId: true,
issuer: true,
clientSecret: true,
responseType: true,
};
const validResponseTypes = {
idToken: true,
code: true,
};
if (!validator.isNonNullObject(options)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"OIDCAuthProviderConfig" must be a valid non-null object.',
);
}
// Check for unsupported top level attributes.
for (const key in options) {
if (!(key in validKeys)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${key}" is not a valid OIDC config parameter.`,
);
}
}
// Required fields.
if (validator.isNonEmptyString(options.providerId)) {
if (options.providerId.indexOf('oidc.') !== 0) {
throw new FirebaseAuthError(
!options.providerId ? AuthClientErrorCode.MISSING_PROVIDER_ID : AuthClientErrorCode.INVALID_PROVIDER_ID,
'"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".',
);
}
} else if (!ignoreMissingFields) {
throw new FirebaseAuthError(
!options.providerId ? AuthClientErrorCode.MISSING_PROVIDER_ID : AuthClientErrorCode.INVALID_PROVIDER_ID,
'"OIDCAuthProviderConfig.providerId" must be a valid non-empty string prefixed with "oidc.".',
);
}
if (!(ignoreMissingFields && typeof options.clientId === 'undefined') &&
!validator.isNonEmptyString(options.clientId)) {
throw new FirebaseAuthError(
!options.clientId ? AuthClientErrorCode.MISSING_OAUTH_CLIENT_ID : AuthClientErrorCode.INVALID_OAUTH_CLIENT_ID,
'"OIDCAuthProviderConfig.clientId" must be a valid non-empty string.',
);
}
if (!(ignoreMissingFields && typeof options.issuer === 'undefined') &&
!validator.isURL(options.issuer)) {
throw new FirebaseAuthError(
!options.issuer ? AuthClientErrorCode.MISSING_ISSUER : AuthClientErrorCode.INVALID_CONFIG,
'"OIDCAuthProviderConfig.issuer" must be a valid URL string.',
);
}
if (typeof options.enabled !== 'undefined' &&
!validator.isBoolean(options.enabled)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"OIDCAuthProviderConfig.enabled" must be a boolean.',
);
}
if (typeof options.displayName !== 'undefined' &&
!validator.isString(options.displayName)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"OIDCAuthProviderConfig.displayName" must be a valid string.',
);
}
if (typeof options.clientSecret !== 'undefined' &&
!validator.isNonEmptyString(options.clientSecret)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
'"OIDCAuthProviderConfig.clientSecret" must be a valid string.',
);
}
if (validator.isNonNullObject(options.responseType) && typeof options.responseType !== 'undefined') {
Object.keys(options.responseType).forEach((key) => {
if (!(key in validResponseTypes)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CONFIG,
`"${key}" is not a valid OAuthResponseType parameter.`,
);
}
});
const idToken = options.responseType.idToken;
if (typeof idToken !== 'undefined' && !validator.isBoolean(idToken)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"OIDCAuthProviderConfig.responseType.idToken" must be a boolean.',
);
}
const code = options.responseType.code;
if (typeof code !== 'undefined') {
if (!validator.isBoolean(code)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'"OIDCAuthProviderConfig.responseType.code" must be a boolean.',
);
}
// If code flow is enabled, client secret must be provided.
if (code && typeof options.clientSecret === 'undefined') {
throw new FirebaseAuthError(
AuthClientErrorCode.MISSING_OAUTH_CLIENT_SECRET,
'The OAuth configuration client secret is required to enable OIDC code flow.',
);
}
}
const allKeys = Object.keys(options.responseType).length;
const enabledCount = Object.values(options.responseType).filter(Boolean).length;
// Only one of OAuth response types can be set to true.
if (allKeys > 1 && enabledCount != 1) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_OAUTH_RESPONSETYPE,
'Only exactly one OAuth responseType should be set to true.',
);
}
}
}
/**
* The OIDCConfig constructor.
*
* @param response - The server side response used to initialize the OIDCConfig object.
* @constructor
*/
constructor(response: OIDCConfigServerResponse) {
if (!response ||
!response.issuer ||
!response.clientId ||
!response.name ||
!(validator.isString(response.name) &&
OIDCConfig.getProviderIdFromResourceName(response.name))) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid OIDC configuration response');
}
const providerId = OIDCConfig.getProviderIdFromResourceName(response.name);
if (!providerId) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'INTERNAL ASSERT FAILED: Invalid SAML configuration response');
}
this.providerId = providerId;
this.clientId = response.clientId;
this.issuer = response.issuer;
// When enabled is undefined, it takes its default value of false.
this.enabled = !!response.enabled;
this.displayName = response.displayName;
if (typeof response.clientSecret !== 'undefined') {
this.clientSecret = response.clientSecret;
}
if (typeof response.responseType !== 'undefined') {
this.responseType = response.responseType;
}
}
/** @returns The plain object representation of the OIDCConfig. */
public toJSON(): OIDCAuthProviderConfig {
return {
enabled: this.enabled,
displayName: this.displayName,
providerId: this.providerId,
issuer: this.issuer,
clientId: this.clientId,
clientSecret: deepCopy(this.clientSecret),
responseType: deepCopy(this.responseType),
};
}
} | the_stack |
import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { DatePipe } from '@angular/common';
import * as xml2js from 'xml2js';
import * as Crypto from 'crypto-js';
interface Importsource {
value: string;
viewValue: string;
}
@Component({
selector: 'app-dialog-import',
templateUrl: './dialog-import.component.html',
styleUrls: ['./dialog-import.component.scss']
})
export class DialogImportComponent implements OnInit {
selected = '';
selected_source = '';
csvContent: string;
parsedCsv: any[];
xmltojson: any[];
public show_input = true;
public please_wait = false;
public burpshow_input = true;
public burpplease_wait = false;
public openvas9show_input = true;
public openvas9please_wait = false;
public nessusxmlshow_input = true;
public nessusxmlplease_wait = false;
public vulnrepojsonshow_input = true;
public vulnrepojsonplease_wait = false;
public vulnrepowrongpass = false;
public nmapshow_input = true;
public nmapplease_wait = false;
public nmapwrongpass = false;
file: any;
hide = true;
sour: Importsource[] = [
{ value: 'vulnrepojson', viewValue: 'VULNRΞPO (.VULN)' },
{ value: 'burp', viewValue: 'Burp Suite (.XML)' },
{ value: 'nmap', viewValue: 'Nmap (.XML)' },
{ value: 'openvas', viewValue: 'OpenVAS 9 (.XML)' },
{ value: 'nessus_xml', viewValue: 'Tenable Nessus (.NESSUS)' },
{ value: 'nessus', viewValue: 'Tenable Nessus (.CSV)' }
];
constructor(public dialogRef: MatDialogRef<DialogImportComponent>, public datePipe: DatePipe) { }
ngOnInit() {
}
onFileLoad(fileLoadedEvent) {
}
onFileSelect(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
this.show_input = false;
this.please_wait = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.onload = (e) => {
this.parseNessus(fileReader.result);
};
fileReader.readAsText(fileToRead, 'UTF-8');
}
}
cancel(): void {
this.dialogRef.close();
}
parseNessus(imp): void {
const csvData = imp || '';
const allTextLines = csvData.split(/\r\n/);
const headers = allTextLines[0].split(',');
const lines = [];
for (let i = 0; i < allTextLines.length; i++) {
// split content based on comma
const data = allTextLines[i].split('","');
const tarr = [];
for (let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
this.parsedCsv = lines;
function unique(array, propertyName) {
return array.filter((e, i) => array.findIndex(a => a[propertyName] === e[propertyName]) === i);
}
function group_issues(array) {
const ret = [];
array.forEach((item, index) => {
ret.forEach((retit, retindex) => {
if (retit[0] === item[0]) {
if (retit[1] !== '') {
retit[1] = retit[1] + ',' + item[1];
}
if (retit[4] !== item[4]) {
if (retit[4] !== '') {
const doesContains = retit[4].match(item[4]);
if (doesContains !== null) {
} else {
if (item[6] === '0') {
retit[4] = retit[4] + '\n' + item[4];
} else {
retit[4] = retit[4] + '\n' + item[5] + '://' + item[4] + ':' + item[6];
}
}
}
}
}
});
if (item[6] !== '0') {
item[4] = item[5] + '://' + item[4] + ':' + item[6];
}
ret.push(item);
});
return ret;
}
const parsedCsv2 = group_issues(this.parsedCsv);
const parsedCsv = unique(parsedCsv2, 0);
const date = new Date();
const today = this.datePipe.transform(date, 'yyyy-MM-dd');
const info = parsedCsv.map((res, key) => {
const def = {
title: res[7],
poc: res[4],
files: [],
desc: res[8] + '\n\n' + res[9],
severity: res[3],
ref: res[11],
cvss: res[2],
cve: res[1],
tags: [],
bounty: [],
date: today
};
return def;
});
info.splice(info.length - 1, 1);
info.splice(0, 1);
this.dialogRef.close(info);
}
burponFileSelect(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
this.burpshow_input = false;
this.burpplease_wait = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.onload = (e) => {
this.parseBurp(fileReader.result);
};
fileReader.readAsText(fileToRead, 'UTF-8');
}
}
parseBurp(xml) {
function returnhost(host, path) {
let ret = '';
host.map((res, key) => {
ret = ret + res.$.ip + ' ' + res._ + path[key] + '\n';
});
return ret;
}
function stripHtml(html)
{
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
function setcvss(severity) {
let cvss = 0;
if (severity === 'High') {
cvss = 8;
} else if (severity === 'Medium') {
cvss = 5;
} else if (severity === 'Low') {
cvss = 2;
} else if (severity === 'Info') {
cvss = 0;
}
return cvss;
}
this.xmltojson = [];
const parser = new xml2js.Parser({ strict: true, trim: true });
parser.parseString(xml, (err, result) => {
this.xmltojson = result.issues.issue;
});
const emp = [];
this.xmltojson.map((res, key) => {
if (!emp.find(x => x.type[0] === res.type[0])) {
emp.push(res);
} else {
const index = emp.findIndex(x => x.type[0] === res.type[0]);
emp[index].location.push(res.location[0]);
emp[index].path.push(res.path[0]);
emp[index].host.push(res.host[0]);
}
});
const date = new Date();
const today = this.datePipe.transform(date, 'yyyy-MM-dd');
const info = emp.map((res, key) => {
let item = '';
if (res.vulnerabilityClassifications !== undefined) {
item = stripHtml(res.vulnerabilityClassifications[0]);
} else {
item = '';
}
let itempoc = '';
if (res.issueDetail !== undefined) {
itempoc = stripHtml(res.issueDetail[0]);
} else {
itempoc = '';
}
let itemrem = '';
if (res.remediationBackground !== undefined) {
itemrem = stripHtml(res.remediationBackground[0]);
} else {
itemrem = '';
}
if (res.severity[0] === 'Information') {
res.severity[0] = 'Info';
}
const def = {
title: res.name[0],
poc: itempoc + '\n\n' + returnhost(res.host, res.path),
files: [],
desc: stripHtml(res.issueBackground[0]) + '\n\n' + itemrem,
severity: res.severity[0],
ref: item,
cvss: setcvss(res.severity[0]),
cve: '',
tags: [],
bounty: [],
date: today
};
return def;
});
this.dialogRef.close(info);
}
openvas9onFileSelect(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
this.openvas9show_input = false;
this.openvas9please_wait = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.onload = (e) => {
this.parseOpenvas9(fileReader.result);
};
fileReader.readAsText(fileToRead, 'UTF-8');
}
}
parseOpenvas9(xml) {
this.xmltojson = [];
const parser = new xml2js.Parser({ strict: true, trim: true });
parser.parseString(xml, (err, result) => {
if (result.report !== undefined) {
if (result.report.report) {
this.xmltojson = result.report.report;
}
} else {
if (result.get_results_response !== undefined) {
this.parseOpenvasxml(result.get_results_response.result);
}
}
});
this.xmltojson.forEach((myObject, index) => {
if (myObject.results) {
myObject.results.forEach((myarrdeep) => {
this.parseOpenvasxml(myarrdeep.result);
});
}
});
}
parseOpenvasxml(xml) {
const date = new Date();
const today = this.datePipe.transform(date, 'yyyy-MM-dd');
const info = xml.map((res, key) => {
const def = {
title: res.name,
poc: res.port[0] + '\n\n' + res.host[0]._,
files: [],
desc: res.description,
severity: res.threat[0],
ref: res.nvt[0].xref[0],
cvss: res.severity[0],
cve: '',
tags: [],
bounty: [],
date: today
};
return def;
});
this.dialogRef.close(info);
}
nessusxmlonFileSelect(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
this.nessusxmlshow_input = false;
this.nessusxmlplease_wait = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.onload = (e) => {
this.parseNessusxml(fileReader.result);
};
fileReader.readAsText(fileToRead, 'UTF-8');
}
}
parseNessusxml(xml) {
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
this.xmltojson = [];
const issues = [];
const parser = new xml2js.Parser({ strict: true, trim: true });
parser.parseString(xml, (err, result) => {
this.xmltojson = result.NessusClientData_v2.Report;
});
this.xmltojson.forEach((myObject, index) => {
if (myObject.ReportHost) {
myObject.ReportHost.forEach((myarrdeep) => {
myarrdeep.ReportItem.forEach((itemissue) => {
// tslint:disable-next-line:max-line-length
type MyArrayType = Array<{ ip: string, port: string, protocol: string, hostfqdn: string, hostname: string, pluginout: string }>;
const arr: MyArrayType = [
// tslint:disable-next-line:max-line-length
{ ip: myarrdeep.$.name, port: itemissue.$.port, protocol: itemissue.$.protocol, hostfqdn: getSafe(() => myarrdeep.HostProperties[0].tag[2]._, ''), hostname: getSafe(() => myarrdeep.HostProperties[0].tag[14]._, ''), pluginout: itemissue.plugin_output }
];
if (myarrdeep.HostProperties[0].tag[2]._) {
}
// tslint:disable-next-line:max-line-length
issues.push([itemissue.$.pluginName, itemissue.$.pluginID, arr, itemissue.cvss_base_score, itemissue.solution, itemissue.description, itemissue.cve, itemissue.see_also, itemissue.risk_factor]);
});
});
}
});
const uniq_items = [];
issues.forEach((myissues, index) => {
if (!uniq_items.some((item) => item[1] === myissues[1])) {
uniq_items.push(myissues);
} else {
const ind = uniq_items.findIndex(x => x[1] === myissues[1]);
uniq_items[ind][2].push(myissues[2]);
}
});
const date = new Date();
const today = this.datePipe.transform(date, 'yyyy-MM-dd');
const info = uniq_items.map((res, key) => {
if (res[8].toString() === 'Information') {
res[8] = 'Info';
}
if (res[8].toString() === 'None') {
res[8] = 'Info';
res[3] = '0';
}
let out_hosts = 'IP List:\n\n';
res[2].forEach((myObject, index) => {
if (myObject.ip !== undefined) {
let port = '';
if (myObject.port.toString() === '0') {
port = '';
} else {
port = 'Port: ' + myObject.protocol + '/' + myObject.port;
}
if (myObject.hostname.toString() === 'true') {
myObject.hostname = '';
}
out_hosts = out_hosts + myObject.ip + ' ' + myObject.hostname + ' ' + port + '\n';
} else {
let port = '';
if (myObject[0].port.toString() === '0') {
port = '';
} else {
port = 'Port: ' + myObject[0].protocol + '/' + myObject[0].port;
}
if (myObject[0].hostname.toString() === 'true') {
myObject[0].hostname = '';
}
// tslint:disable-next-line:max-line-length
out_hosts = out_hosts + myObject[0].ip + ' ' + myObject[0].hostname + ' ' + port + '\n';
}
});
let out_ip = '\nOutput:\n';
res[2].forEach((myObject, index) => {
if (myObject.ip !== undefined) {
let port = '';
if (myObject.port.toString() === '0') {
port = '';
} else {
port = 'Port: ' + myObject.protocol + '/' + myObject.port;
}
if (myObject.hostname.toString() === 'true') {
myObject.hostname = '';
}
if (myObject.pluginout === undefined) {
myObject.pluginout = '';
}
out_ip = out_ip + '===\n' + myObject.ip + '\n' + myObject.hostname + '\n' + port + '\n\n' + myObject.pluginout + '\n\n';
} else {
let port = '';
if (myObject[0].port.toString() === '0') {
port = '';
} else {
port = 'Port: ' + myObject[0].protocol + '/' + myObject[0].port;
}
if (myObject[0].hostname.toString() === 'true') {
myObject[0].hostname = '';
}
if (myObject[0].pluginout === undefined) {
myObject[0].pluginout = '';
}
// tslint:disable-next-line:max-line-length
out_ip = out_ip + '===\n' + myObject[0].ip + '\n' + myObject[0].hostname + '\n' + port + '\n\n' + myObject[0].pluginout + '\n\n';
}
});
res[3] = getSafe(() => res[3], '0');
if (res[7] === undefined) {
res[7] = '';
}
if (res[5] === undefined) {
res[5] = '';
}
const def = {
title: res[0],
poc: out_hosts + out_ip,
files: [],
desc: res[5],
severity: res[8].toString(),
ref: res[7],
cvss: res[3],
cve: '',
tags: [],
bounty: [],
date: today
};
return def;
});
this.dialogRef.close(info);
}
fileChanged(e) {
this.file = e.target.files[0];
}
startUpload(pass) {
if (pass !== '' && this.file) {
this.vulnrepojsonshow_input = false;
this.vulnrepojsonplease_wait = true;
const fileReader = new FileReader();
fileReader.onload = (e) => {
this.vulnrepojson(fileReader.result, pass);
};
fileReader.readAsText(this.file, 'UTF-8');
}
}
vulnrepojson(json, pass) {
try {
// Decrypt
const bytes = Crypto.AES.decrypt(json.toString(), pass);
const decryptedData = JSON.parse(bytes.toString(Crypto.enc.Utf8));
if (decryptedData) {
this.dialogRef.close(decryptedData);
}
} catch (except) {
this.vulnrepojsonplease_wait = false;
this.vulnrepowrongpass = true;
}
}
nmaponFileSelect(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
this.show_input = false;
this.please_wait = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = this.onFileLoad;
fileReader.onload = (e) => {
this.parseNmap(fileReader.result);
};
fileReader.readAsText(fileToRead, 'UTF-8');
}
}
parseNmap(xml) {
let json = '';
let hosts = [];
const parser = new xml2js.Parser({ strict: true, trim: true });
parser.parseString(xml, (err, result) => {
json = result.nmaprun;
hosts = result.nmaprun.host;
});
const date = new Date();
const today = this.datePipe.transform(date, 'yyyy-MM-dd');
const info = hosts.map((res, key) => {
let addre = '';
if (res.address[0]['$'].addr !== undefined) {
addre = res.address[0]['$'].addr + ' ';
} else {
addre = '';
}
let hostt = '';
if(res.hostnames) {
if(res.hostnames[0].hostname) {
if (res.hostnames[0].hostname[0]['$'].name !== undefined) {
hostt = ' - ' + res.hostnames[0].hostname[0]['$'].name;
} else {
hostt = '';
}
}
}
let cmd = '';
if (json['$'].args !== undefined) {
cmd = 'Execute: ' + json['$'].args + '\n\n';
}
let status = '';
let ipstat = '';
if (res.status) {
if (res.status[0]['$'].state !== undefined) {
// tslint:disable-next-line:max-line-length
status = 'IP: ' + res.address[0]['$'].addr + '\nStatus: ' + res.status[0]['$'].state + '\nReason: ' + res.status[0]['$'].reason + '\nReason TTL: ' + res.status[0]['$'].reason_ttl + '\n';
ipstat = ' (' + res.status[0]['$'].state + ')';
}
}
let ports = 'Open ports:\n';
let filteredports = '';
if (res.ports) {
if (res.ports[0].port !== undefined) {
res.ports[0].port.forEach((myObject, index) => {
let service = '';
let service_name = '';
if (myObject.service[0]['$'].name !== undefined) {
service_name = myObject.service[0]['$'].name;
}
let service_product = '';
if (myObject.service[0]['$'].product !== undefined) {
service_product = myObject.service[0]['$'].product;
}
if (service_product === '') {
service = service_name
} else {
service = service_name + ' - ' + service_product;
}
ports = ports + myObject['$'].protocol + '/' + myObject['$'].portid + ' - ' + service + '\n';
});
}
if (res.ports[0].extraports !== undefined) {
const title = '\nFiltered ports:\n';
res.ports[0].extraports.forEach((myObject, index) => {
filteredports = myObject['$'].state + '/' + myObject['$'].count + '\n';
});
filteredports = title + filteredports;
}
}
let osdetect = '';
if (res.os) {
if (res.os[0].osmatch !== undefined) {
const title = '\n====================\nOS detection:\n';
res.os[0].osmatch.forEach((myObject, index) => {
osdetect = osdetect + myObject['$'].name + ' - ' + myObject['$'].accuracy + '% \n';
});
osdetect = title + osdetect;
}
}
const pocc = ports + filteredports + osdetect + '';
const descc = cmd + status + '';
const def = {
title: 'Nmap scan for: ' + addre + hostt + ipstat,
poc: pocc,
files: [],
desc: descc,
severity: 'Info',
ref: 'https://nmap.org/',
cvss: '',
cve: '',
tags: [],
bounty: [],
date: today
};
return def;
});
this.dialogRef.close(info);
}
} | the_stack |
import { KubernetesObject } from 'kpt-functions';
import * as apiCoreV1 from './io.k8s.api.core.v1';
import * as apisMetaV1 from './io.k8s.apimachinery.pkg.apis.meta.v1';
// StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.
//
// StorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.
export class StorageClass implements KubernetesObject {
// AllowVolumeExpansion shows whether the storage class allow volume expand
public allowVolumeExpansion?: boolean;
// Restrict the node topologies where volumes can be dynamically provisioned. Each volume plugin defines its own supported topology specifications. An empty TopologySelectorTerm list means there is no topology restriction. This field is only honored by servers that enable the VolumeScheduling feature.
public allowedTopologies?: apiCoreV1.TopologySelectorTerm[];
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// Dynamically provisioned PersistentVolumes of this storage class are created with these mountOptions, e.g. ["ro", "soft"]. Not validated - mount of the PVs will simply fail if one is invalid.
public mountOptions?: string[];
// Parameters holds the parameters for the provisioner that should create volumes of this storage class.
public parameters?: { [key: string]: string };
// Provisioner indicates the type of the provisioner.
public provisioner: string;
// Dynamically provisioned PersistentVolumes of this storage class are created with this reclaimPolicy. Defaults to Delete.
public reclaimPolicy?: string;
// VolumeBindingMode indicates how PersistentVolumeClaims should be provisioned and bound. When unset, VolumeBindingImmediate is used. This field is only honored by servers that enable the VolumeScheduling feature.
public volumeBindingMode?: string;
constructor(desc: StorageClass.Interface) {
this.allowVolumeExpansion = desc.allowVolumeExpansion;
this.allowedTopologies = desc.allowedTopologies;
this.apiVersion = StorageClass.apiVersion;
this.kind = StorageClass.kind;
this.metadata = desc.metadata;
this.mountOptions = desc.mountOptions;
this.parameters = desc.parameters;
this.provisioner = desc.provisioner;
this.reclaimPolicy = desc.reclaimPolicy;
this.volumeBindingMode = desc.volumeBindingMode;
}
}
export function isStorageClass(o: any): o is StorageClass {
return (
o &&
o.apiVersion === StorageClass.apiVersion &&
o.kind === StorageClass.kind
);
}
export namespace StorageClass {
export const apiVersion = 'storage.k8s.io/v1';
export const group = 'storage.k8s.io';
export const version = 'v1';
export const kind = 'StorageClass';
// StorageClass describes the parameters for a class of storage for which PersistentVolumes can be dynamically provisioned.
//
// StorageClasses are non-namespaced; the name of the storage class according to etcd is in ObjectMeta.Name.
export interface Interface {
// AllowVolumeExpansion shows whether the storage class allow volume expand
allowVolumeExpansion?: boolean;
// Restrict the node topologies where volumes can be dynamically provisioned. Each volume plugin defines its own supported topology specifications. An empty TopologySelectorTerm list means there is no topology restriction. This field is only honored by servers that enable the VolumeScheduling feature.
allowedTopologies?: apiCoreV1.TopologySelectorTerm[];
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// Dynamically provisioned PersistentVolumes of this storage class are created with these mountOptions, e.g. ["ro", "soft"]. Not validated - mount of the PVs will simply fail if one is invalid.
mountOptions?: string[];
// Parameters holds the parameters for the provisioner that should create volumes of this storage class.
parameters?: { [key: string]: string };
// Provisioner indicates the type of the provisioner.
provisioner: string;
// Dynamically provisioned PersistentVolumes of this storage class are created with this reclaimPolicy. Defaults to Delete.
reclaimPolicy?: string;
// VolumeBindingMode indicates how PersistentVolumeClaims should be provisioned and bound. When unset, VolumeBindingImmediate is used. This field is only honored by servers that enable the VolumeScheduling feature.
volumeBindingMode?: string;
}
}
// StorageClassList is a collection of storage classes.
export class StorageClassList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Items is the list of StorageClasses
public items: StorageClass[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: StorageClassList) {
this.apiVersion = StorageClassList.apiVersion;
this.items = desc.items.map((i) => new StorageClass(i));
this.kind = StorageClassList.kind;
this.metadata = desc.metadata;
}
}
export function isStorageClassList(o: any): o is StorageClassList {
return (
o &&
o.apiVersion === StorageClassList.apiVersion &&
o.kind === StorageClassList.kind
);
}
export namespace StorageClassList {
export const apiVersion = 'storage.k8s.io/v1';
export const group = 'storage.k8s.io';
export const version = 'v1';
export const kind = 'StorageClassList';
// StorageClassList is a collection of storage classes.
export interface Interface {
// Items is the list of StorageClasses
items: StorageClass[];
// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.
//
// VolumeAttachment objects are non-namespaced.
export class VolumeAttachment implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// Specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.
public spec: VolumeAttachmentSpec;
// Status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.
public status?: VolumeAttachmentStatus;
constructor(desc: VolumeAttachment.Interface) {
this.apiVersion = VolumeAttachment.apiVersion;
this.kind = VolumeAttachment.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isVolumeAttachment(o: any): o is VolumeAttachment {
return (
o &&
o.apiVersion === VolumeAttachment.apiVersion &&
o.kind === VolumeAttachment.kind
);
}
export namespace VolumeAttachment {
export const apiVersion = 'storage.k8s.io/v1';
export const group = 'storage.k8s.io';
export const version = 'v1';
export const kind = 'VolumeAttachment';
// VolumeAttachment captures the intent to attach or detach the specified volume to/from the specified node.
//
// VolumeAttachment objects are non-namespaced.
export interface Interface {
// Standard object metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// Specification of the desired attach/detach volume behavior. Populated by the Kubernetes system.
spec: VolumeAttachmentSpec;
// Status of the VolumeAttachment request. Populated by the entity completing the attach or detach operation, i.e. the external-attacher.
status?: VolumeAttachmentStatus;
}
}
// VolumeAttachmentList is a collection of VolumeAttachment objects.
export class VolumeAttachmentList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Items is the list of VolumeAttachments
public items: VolumeAttachment[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: VolumeAttachmentList) {
this.apiVersion = VolumeAttachmentList.apiVersion;
this.items = desc.items.map((i) => new VolumeAttachment(i));
this.kind = VolumeAttachmentList.kind;
this.metadata = desc.metadata;
}
}
export function isVolumeAttachmentList(o: any): o is VolumeAttachmentList {
return (
o &&
o.apiVersion === VolumeAttachmentList.apiVersion &&
o.kind === VolumeAttachmentList.kind
);
}
export namespace VolumeAttachmentList {
export const apiVersion = 'storage.k8s.io/v1';
export const group = 'storage.k8s.io';
export const version = 'v1';
export const kind = 'VolumeAttachmentList';
// VolumeAttachmentList is a collection of VolumeAttachment objects.
export interface Interface {
// Items is the list of VolumeAttachments
items: VolumeAttachment[];
// Standard list metadata More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// VolumeAttachmentSource represents a volume that should be attached. Right now only PersistenVolumes can be attached via external attacher, in future we may allow also inline volumes in pods. Exactly one member can be set.
export class VolumeAttachmentSource {
// inlineVolumeSpec contains all the information necessary to attach a persistent volume defined by a pod's inline VolumeSource. This field is populated only for the CSIMigration feature. It contains translated fields from a pod's inline VolumeSource to a PersistentVolumeSpec. This field is alpha-level and is only honored by servers that enabled the CSIMigration feature.
public inlineVolumeSpec?: apiCoreV1.PersistentVolumeSpec;
// Name of the persistent volume to attach.
public persistentVolumeName?: string;
}
// VolumeAttachmentSpec is the specification of a VolumeAttachment request.
export class VolumeAttachmentSpec {
// Attacher indicates the name of the volume driver that MUST handle this request. This is the name returned by GetPluginName().
public attacher: string;
// The node that the volume should be attached to.
public nodeName: string;
// Source represents the volume that should be attached.
public source: VolumeAttachmentSource;
constructor(desc: VolumeAttachmentSpec) {
this.attacher = desc.attacher;
this.nodeName = desc.nodeName;
this.source = desc.source;
}
}
// VolumeAttachmentStatus is the status of a VolumeAttachment request.
export class VolumeAttachmentStatus {
// The last error encountered during attach operation, if any. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
public attachError?: VolumeError;
// Indicates the volume is successfully attached. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
public attached: boolean;
// Upon successful attach, this field is populated with any information returned by the attach operation that must be passed into subsequent WaitForAttach or Mount calls. This field must only be set by the entity completing the attach operation, i.e. the external-attacher.
public attachmentMetadata?: { [key: string]: string };
// The last error encountered during detach operation, if any. This field must only be set by the entity completing the detach operation, i.e. the external-attacher.
public detachError?: VolumeError;
constructor(desc: VolumeAttachmentStatus) {
this.attachError = desc.attachError;
this.attached = desc.attached;
this.attachmentMetadata = desc.attachmentMetadata;
this.detachError = desc.detachError;
}
}
// VolumeError captures an error encountered during a volume operation.
export class VolumeError {
// String detailing the error encountered during Attach or Detach operation. This string may be logged, so it should not contain sensitive information.
public message?: string;
// Time the error was encountered.
public time?: apisMetaV1.Time;
} | the_stack |
import React = require("react");
var ReactDOM = require("react-dom");
import csx = require('./base/csx');
import { BaseComponent } from "./ui";
import * as ui from "./ui";
import Modal = require('react-modal');
import * as styles from "./styles/styles";
import { debounce, createMap, rangeLimited, getFileName } from "../common/utils";
import { cast, server } from "../socket/socketClient";
import * as commands from "./commands/commands";
import { match, filter as fuzzyFilter } from "fuzzaldrin";
import * as utils from "../common/utils";
import * as typestyle from "typestyle";
const inputClassName = typestyle.style(styles.modal.inputStyleBase);
/**
* The singleton select list view
*/
export var selectListView: SelectListView;
type DataItem = any;
export interface Props {
}
export interface State {
isOpen?: boolean;
filterValue?: string;
selectedIndex?: number;
header?: string;
data?: DataItem[];
render?: (t: DataItem, highlighted: JSX.Element[]) => any;
textify?: (t: DataItem) => string;
onSelect?: (t: DataItem) => string;
getNewData?: (filterValue: string) => Promise<DataItem[]>;
}
export class SelectListView extends BaseComponent<Props, State>{
filteredResults: DataItem[];
/*
API sample usage
this.refs.selectListView.show<ActiveProjectConfigDetails>({
header: 'Select the active project',
data: availableProjects,
render: (d,highlitedText) => <div>{highlitedText}</div>,
textify: (d) => d.name,
onSelect: (d) => {
server.setActiveProjectName({ name: d.name });
state.setActiveProject(d.name);
state.setInActiveProject(types.TriState.Unknown);
}
});
*/
/**
* The main interaction API
*/
show<T>(args: {
header: string;
data: T[];
render: (t: T, highlighted: JSX.Element[]) => any;
/** This text will be used for filtering as well as creating 'highlighted' which is passed to render */
textify: (t: T) => string;
/**
* If onselect returns a string then it is shown as an error
* TODO: actually support this `return`
*/
onSelect: (t: T) => string;
/**
* Allows you to provide new data that can be used for filtering
* Use Case: Opening a file from the server disk
* TODO: actually support this
*/
getNewData?: (text: string) => Promise<T[]>;
}) {
this.filteredResults = args.data.concat([]);
this.setState({
isOpen: true,
filterValue: '',
selectedIndex: 0,
header: args.header,
data: args.data,
render: args.render,
textify: args.textify,
onSelect: args.onSelect,
getNewData: args.getNewData || (() => Promise.resolve(args.data)),
});
ReactDOM.findDOMNode(this.refs.omniSearchInput).focus();
}
maxShowCount = 15;
constructor(props: Props) {
super(props);
this.filteredResults = [];
this.state = {
isOpen: false,
selectedIndex: 0,
header: '',
data: [],
};
}
refs: {
[string: string]: any;
omniSearch: any;
omniSearchInput: any;
selected: Element;
}
componentDidMount() {
selectListView = this;
commands.esc.on(() => {
this.closeOmniSearch();
});
}
componentDidUpdate() {
// get the dom node that is selected
// make sure its parent scrolls to make this visible
setTimeout(() => {
if (this.refs.selected) {
let selected = this.refs.selected as HTMLDivElement;
selected.scrollIntoViewIfNeeded(false);
}
});
}
render() {
let fileList = this.filteredResults;
let selectedIndex = this.state.selectedIndex;
let fileListRendered = fileList.map((item, i) => {
// key = i
let selected = selectedIndex === i;
let selectedStyle = selected ? {
background: '#545454',
color: 'white'
} : {};
let ref = selected && "selected";
return (
<div key={i} style={csx.extend(selectedStyle, styles.padded2, styles.hand, csx.content)} onClick={() => this.selectIndex(i)} ref={ref}>
{this.state.render(item, renderMatchedSegments(this.state.textify(item), this.state.filterValue))}
</div>
);
});
return <Modal
isOpen={this.state.isOpen}
onRequestClose={this.closeOmniSearch}>
<div style={csx.extend(csx.vertical, csx.flex)}>
<div style={csx.extend(csx.horizontal, csx.content)}>
<h4>{this.state.header}</h4>
<div style={csx.flex}></div>
<div style={{ fontSize: '0.9rem', color: 'grey' } as any}><code style={styles.modal.keyStrokeStyle}>Esc</code> to exit <code style={styles.modal.keyStrokeStyle}>Enter</code> to select</div>
</div>
<div style={csx.extend(styles.padded1TopBottom, csx.vertical, csx.content)}>
<input
type="text"
ref="omniSearchInput"
placeholder="Filter"
className={inputClassName}
onChange={this.onChangeFilter}
onKeyDown={this.onChangeSelected}
/>
</div>
<div style={csx.extend(csx.vertical, csx.flex, { overflow: 'auto' })}>
<div style={csx.vertical}>
{fileListRendered}
</div>
</div>
</div>
</Modal>
}
closeOmniSearch = () => {
this.setState({ isOpen: false, filterValue: '' });
};
onChangeFilter = debounce((e) => {
let filterValue = ReactDOM.findDOMNode(this.refs.omniSearchInput).value;
this.getNewData().then(() => {
this.filteredResults = getFilteredItems({
items: this.state.data,
textify: this.state.textify,
filterValue
});
this.filteredResults = this.filteredResults.slice(0, this.maxShowCount);
this.setState({ filterValue, selectedIndex: 0 });
});
}, 50);
incrementSelected = debounce(() => {
this.setState({ selectedIndex: rangeLimited({ num: this.state.selectedIndex + 1, min: 0, max: Math.min(this.maxShowCount - 1, this.filteredResults.length - 1), loopAround: true }) });
}, 0, true);
decrementSelected = debounce(() => {
this.setState({ selectedIndex: rangeLimited({ num: this.state.selectedIndex - 1, min: 0, max: Math.min(this.maxShowCount - 1, this.filteredResults.length - 1), loopAround: true }) });
}, 0, true);
onChangeSelected = (e) => {
if (e.key == 'ArrowUp') {
e.preventDefault();
this.decrementSelected();
}
if (e.key == 'ArrowDown') {
e.preventDefault();
this.incrementSelected();
}
if (e.key == 'Enter') {
e.preventDefault();
this.selectIndex(this.state.selectedIndex);
}
};
selectIndex = (index: number) => {
let result = this.filteredResults[index];
this.state.onSelect(result);
this.closeOmniSearch();
};
getNewData = utils.onlyLastCall(() => {
let filterValue = ReactDOM.findDOMNode(this.refs.omniSearchInput).value;
return this.state.getNewData(filterValue).then((data) => {
this.setState({ data });
});
});
}
/**
* Applies fuzzy filter to the text version of each item returning the matched items
*/
export function getFilteredItems<T>(args: { items: T[], textify: (item: T) => string, filterValue: string }): T[] {
// Store the items for each text value
let textValueToItems: { [text: string]: T[] } = Object.create(null);
args.items.forEach((item) => {
let text = args.textify(item);
if (!textValueToItems[text]) textValueToItems[text] = [];
textValueToItems[text].push(item);
})
// Get the unique text values
let textValues = Object.keys(utils.createMap(args.items.map(args.textify)));
// filter them
let filteredTextValues = fuzzyFilter(textValues, args.filterValue);
return utils.selectMany(filteredTextValues.map((textvalue) => textValueToItems[textvalue]));
}
/**
* Based on https://github.com/atom/fuzzy-finder/blob/51f1f2415ecbfab785596825a011c1d2fa2658d3/lib/fuzzy-finder-view.coffee#L56-L74
*/
export function renderMatchedSegments(result: string, query: string): JSX.Element[] {
// A data structure which is efficient to render
type MatchedSegments = { str: string, matched: boolean }[];
// local function that creates the *matched segment* data structure
function getMatchedSegments(result: string, query: string) {
let matches = match(result, query);
let matchMap = createMap(matches);
// collapse contiguous sections into a single `<strong>`
let currentUnmatchedCharacters = [];
let currentMatchedCharacters = [];
let combined: MatchedSegments = [];
function closeOffUnmatched() {
if (currentUnmatchedCharacters.length) {
combined.push({ str: currentUnmatchedCharacters.join(''), matched: false });
currentUnmatchedCharacters = [];
}
}
function closeOffMatched() {
if (currentMatchedCharacters.length) {
combined.push({ str: currentMatchedCharacters.join(''), matched: true });
currentMatchedCharacters = [];
}
}
result.split('').forEach((c, i) => {
let isMatched = matchMap[i];
if (isMatched) {
if (currentMatchedCharacters.length) {
currentMatchedCharacters.push(c);
}
else {
currentMatchedCharacters = [c]
// close off any unmatched characters
closeOffUnmatched();
}
}
else {
if (currentUnmatchedCharacters.length) {
currentUnmatchedCharacters.push(c);
}
else {
currentUnmatchedCharacters = [c]
// close off any matched characters
closeOffMatched();
}
}
});
closeOffMatched();
closeOffUnmatched();
return combined;
}
/**
* Rendering the matched segment data structure is trivial
*/
let matched = getMatchedSegments(result, query);
let matchedStyle = { fontWeight: 'bold' as 'bold', color: '#66d9ef' };
return matched.map((item, i) => {
return <span key={i} style={item.matched ? matchedStyle : {}}>{item.str}</span>;
});
} | the_stack |
import React, {useState, CSSProperties, useEffect, useContext, createRef} from "react";
import {Collapse, Icon, Card, Modal, Menu, Dropdown} from "antd";
import {DownOutlined} from "@ant-design/icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faCog} from "@fortawesome/free-solid-svg-icons"; // eslint-disable-line @typescript-eslint/no-unused-vars
import {faTrashAlt, faArrowAltCircleRight, faArrowAltCircleLeft} from "@fortawesome/free-regular-svg-icons";
import {MLButton} from "@marklogic/design-system";
import NewFlowDialog from "./new-flow-dialog/new-flow-dialog";
import sourceFormatOptions from "../../config/formats.config";
import {RunToolTips, SecurityTooltips} from "../../config/tooltips.config";
import "./flows.scss";
import styles from "./flows.module.scss";
import {MLTooltip, MLSpin, MLCheckbox} from "@marklogic/design-system"; // eslint-disable-line @typescript-eslint/no-unused-vars
import {useDropzone} from "react-dropzone";
import {AuthoritiesContext} from "../../util/authorities";
import {Link, useLocation} from "react-router-dom";
import axios from "axios";
import {getViewSettings, setViewSettings, UserContext} from "../../util/user-context";
enum ReorderFlowOrderDirection {
LEFT = "left",
RIGHT = "right"
}
const {Panel} = Collapse;
interface Props {
flows: any;
steps: any;
deleteFlow: any;
createFlow: any;
updateFlow: any;
deleteStep: any;
runStep: any;
runFlowSteps: any;
canReadFlow: boolean;
canWriteFlow: boolean;
hasOperatorRole: boolean;
running: any;
uploadError: string;
newStepToFlowOptions: any;
addStepToFlow: any;
flowsDefaultActiveKey: any;
showStepRunResponse: any;
runEnded: any;
onReorderFlow: (flowIndex: number, newSteps: Array<any>) => void
setJobId: any;
setOpenJobResponse: any;
}
const StepDefinitionTypeTitles = {
"INGESTION": "Load",
"ingestion": "Load",
"MAPPING": "Map",
"mapping": "Map",
"MASTERING": "Master",
"mastering": "Master",
"MATCHING": "Match",
"matching": "Match",
"MERGING": "Merge",
"merging": "Merge",
"CUSTOM": "Custom",
"custom": "Custom"
};
const Flows: React.FC<Props> = (props) => {
const storage = getViewSettings();
const openFlows = storage?.run?.openFlows;
const hasDefaultKey = JSON.stringify(props.newStepToFlowOptions?.flowsDefaultKey) !== JSON.stringify(["-1"]);
const {handleError} = useContext(UserContext);
const [newFlow, setNewFlow] = useState(false);
const [addedFlowName, setAddedFlowName] = useState("");
const [title, setTitle] = useState("");
const [flowData, setFlowData] = useState({});
const [dialogVisible, setDialogVisible] = useState(false);
const [stepDialogVisible, setStepDialogVisible] = useState(false);
const [addStepDialogVisible, setAddStepDialogVisible] = useState(false);
const [flowName, setFlowName] = useState("");
const [stepName, setStepName] = useState("");
const [stepType, setStepType] = useState("");
const [stepNumber, setStepNumber] = useState("");
const [runningStep, setRunningStep] = useState<any>({});
const [runningFlow, setRunningFlow] = useState<any>("");
const [fileList, setFileList] = useState<any[]>([]);
const [showUploadError, setShowUploadError] = useState(false);
const [openNewFlow, setOpenNewFlow] = useState(props.newStepToFlowOptions?.addingStepToFlow && !props.newStepToFlowOptions?.existingFlow);
const [activeKeys, setActiveKeys] = useState(
hasDefaultKey && (props.newStepToFlowOptions?.flowsDefaultKey ?? []).length > 0 ?
props.newStepToFlowOptions?.flowsDefaultKey :
(openFlows ? openFlows : [])
);
const [showLinks, setShowLinks] = useState("");
const [startRun, setStartRun] = useState(false);
const [latestJobData, setLatestJobData] = useState<any>({});
const [createAdd, setCreateAdd] = useState(true);
const [addFlowDirty, setAddFlowDirty] = useState({});
const [addExternalFlowDirty, setExternalAddFlowDirty] = useState(true);
const [hasQueriedInitialJobData, setHasQueriedInitialJobData] = useState(false);
const [selectedStepOptions, setSelectedStepOptions] = useState<any>({}); // eslint-disable-line @typescript-eslint/no-unused-vars
const [currentFlowName, setCurrentFlowName] = useState(""); // eslint-disable-line @typescript-eslint/no-unused-vars
const [selectedStepDetails, setSelectedStepDetails]= useState<any>([{stepName: "", stepNumber: -1, stepDefinitionType: "", isChecked: false}]);
const [runFlowClicked, setRunFlowClicked] = useState(false);
const location = useLocation();
// maintain a list of panel refs
const flowPanels: any = props.flows.reduce((p, n) => ({...p, ...{[n.name]: createRef()}}), {});
// Persists active keys in session storage as a user interacts with them
useEffect(() => {
if (activeKeys === undefined) {
return;
}
const newStorage = {...storage, run: {...storage.run, openFlows: activeKeys}};
setViewSettings(newStorage);
}, [activeKeys]);
// If a step was just added scroll the flow step panel fully to the right
useEffect(() => {
const scrollToEnd = f => {
const panel = flowPanels[f];
if (panel && panel.current) {
const {scrollWidth} = panel.current;
panel.current.scrollTo(scrollWidth * 2, 0);
}
};
if (!props.flows.length) return;
const currentFlow = props.flows.filter(({name}) => name === flowName).shift();
if (currentFlow?.steps?.length > addFlowDirty[flowName]) {
// Scrolling should happen on the last update after the number of steps in the flow has been updated
scrollToEnd(flowName);
setAddFlowDirty({...addFlowDirty, [flowName]: currentFlow?.steps?.length});
} else {
// if step is added from external view
let state: any = location.state || {};
const externalDirty = (state ? state["addFlowDirty"] : false) && addExternalFlowDirty;
const thisFlow = state ? state["flowName"] : null;
if (externalDirty) {
scrollToEnd(thisFlow);
setExternalAddFlowDirty(false);
}
}
}, [props.flows]);
useEffect(() => {
if (openFlows === undefined || props.flows.length === 0 || hasQueriedInitialJobData) {
return;
}
props.flows.map((flow, i) => {
getFlowWithJobInfo(i);
});
setHasQueriedInitialJobData(true);
}, [props.flows]);
useEffect(() => {
if (JSON.stringify(props.flowsDefaultActiveKey) !== JSON.stringify([]) && props.flowsDefaultActiveKey.length >= activeKeys.length) {
setActiveKeys([...props.flowsDefaultActiveKey]);
}
if (props.flows) {
// Get the latest job info when a step is added to an existing flow from Curate or Load Tile
if (JSON.stringify(props.flows) !== JSON.stringify([])) {
let stepsInFlow = props.flows[props.newStepToFlowOptions?.flowsDefaultKey]?.steps;
if (props.newStepToFlowOptions && props.newStepToFlowOptions.addingStepToFlow && props.newStepToFlowOptions.existingFlow && props.newStepToFlowOptions.flowsDefaultKey && props.newStepToFlowOptions.flowsDefaultKey !== -1) {
getFlowWithJobInfo(props.newStepToFlowOptions.flowsDefaultKey);
if (startRun) {
//run step after step is added to an existing flow
if (props.newStepToFlowOptions.stepDefinitionType === "ingestion") {
setShowUploadError(false);
setRunningStep(stepsInFlow[stepsInFlow.length - 1]);
setRunningFlow(props.newStepToFlowOptions?.flowName);
openFilePicker();
setStartRun(false);
} else {
props.runStep(props.newStepToFlowOptions?.flowName, stepsInFlow[stepsInFlow.length - 1]);
setStartRun(false);
}
}
//run step that is already inside a flow
} else if (props.newStepToFlowOptions && !props.newStepToFlowOptions.addingStepToFlow && props.newStepToFlowOptions.startRunStep && props.newStepToFlowOptions.flowsDefaultKey && props.newStepToFlowOptions.flowsDefaultKey !== -1) {
let runStepNum = stepsInFlow.findIndex(s => s.stepName === props.newStepToFlowOptions?.newStepName);
if (startRun) {
if (props.newStepToFlowOptions.stepDefinitionType === "ingestion") {
setShowUploadError(false);
setRunningStep(stepsInFlow[runStepNum]);
setRunningFlow(props.newStepToFlowOptions?.flowName);
openFilePicker();
setStartRun(false);
} else {
props.runStep(props.newStepToFlowOptions?.flowName, stepsInFlow[runStepNum]);
setStartRun(false);
}
}
}
}
}
if (activeKeys === undefined) {
setActiveKeys([]);
}
}, [props.flows]);
useEffect(() => {
//run step after step is added to a new flow
if (props.newStepToFlowOptions && !props.newStepToFlowOptions.existingFlow && startRun && addedFlowName) {
let indexFlow = props.flows?.findIndex(i => i.name === addedFlowName);
if (props.flows[indexFlow]?.steps.length > 0) {
let indexStep = props.flows[indexFlow].steps.findIndex(s => s.stepName === props.newStepToFlowOptions.newStepName);
if (props.flows[indexFlow].steps[indexStep].stepDefinitionType === "ingestion") {
setShowUploadError(false);
setRunningStep(props.flows[indexFlow].steps[indexStep]);
setRunningFlow(addedFlowName);
openFilePicker();
} else {
props.runStep(addedFlowName, props.flows[indexFlow].steps[indexStep]);
setAddedFlowName("");
setStartRun(false);
}
}
}
}, [props.steps]);
// Get the latest job info after a step (in a flow) run
useEffect(() => {
let num = props.flows.findIndex((flow) => flow.name === props.runEnded.flowId);
if (num >= 0) {
getFlowWithJobInfo(num);
}
}, [props.runEnded]);
useEffect(() => {
if (props.newStepToFlowOptions && props.newStepToFlowOptions.startRunStep) {
setStartRun(true);
}
}, [props.newStepToFlowOptions]);
// For role-based privileges
const authorityService = useContext(AuthoritiesContext);
const authorityByStepType = {
ingestion: authorityService.canReadLoad(),
mapping: authorityService.canReadMapping(),
matching: authorityService.canReadMatchMerge(),
merging: authorityService.canReadMatchMerge(),
custom: authorityService.canReadCustom()
};
const OpenAddNewDialog = () => {
setCreateAdd(false);
setTitle("New Flow");
setNewFlow(true);
};
//Custom CSS for source Format
const sourceFormatStyle = (sourceFmt) => {
let customStyles: CSSProperties;
if (!sourceFmt) {
customStyles = {
float: "left",
backgroundColor: "#fff",
color: "#fff",
padding: "5px"
};
} else {
customStyles = {
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
height: "35px",
width: "35px",
lineHeight: "35px",
backgroundColor: sourceFormatOptions[sourceFmt].color,
fontSize: sourceFmt === "json" ? "12px" : "13px",
borderRadius: "50%",
textAlign: "center",
color: "#ffffff",
verticalAlign: "middle"
};
}
return customStyles;
};
const handleStepAdd = async (stepName, flowName, stepType) => {
setAddStepDialogVisible(true);
setFlowName(flowName);
setStepName(stepName);
setStepType(stepType);
};
const handleFlowDelete = (name) => {
setDialogVisible(true);
setFlowName(name);
};
const handleStepDelete = (flowName, stepDetails) => {
setStepDialogVisible(true);
setFlowName(flowName);
setStepName(stepDetails.stepName);
setStepType(stepDetails.stepDefinitionType);
setStepNumber(stepDetails.stepNumber);
};
const onOk = (name) => {
props.deleteFlow(name);
setDialogVisible(false);
};
const onStepOk = (flowName, stepNumber) => {
props.deleteStep(flowName, stepNumber);
setStepDialogVisible(false);
};
const onAddStepOk = async (stepName, flowName, stepType) => {
await props.addStepToFlow(stepName, flowName, stepType);
// Open flow panel if not open
const flowIndex = props.flows.findIndex(f => f.name === flowName);
if (!activeKeys.includes(flowIndex)) {
let newActiveKeys = [...activeKeys, flowIndex];
setActiveKeys(newActiveKeys);
}
await setAddStepDialogVisible(false);
await setAddFlowDirty({...addFlowDirty, [flowName]: props.flows[flowIndex].steps.length});
};
const onCancel = () => {
setDialogVisible(false);
setStepDialogVisible(false);
setAddStepDialogVisible(false);
};
const isStepInFlow = (stepName, flowName) => {
let result = false;
let flow;
if (props.flows) flow = props.flows.find(f => f.name === flowName);
if (flow) result = flow["steps"].findIndex(s => s.stepName === stepName) > -1;
return result;
};
// Setup for file upload
const {getRootProps, getInputProps, open, acceptedFiles} = useDropzone({
noClick: true,
noKeyboard: true
});
const openFilePicker = () => {
open();
setStartRun(false);
};
useEffect(() => {
acceptedFiles.forEach(file => {
setFileList(prevState => [...prevState, file]);
});
if (startRun) {
setAddedFlowName("");
setStartRun(false);
}
}, [acceptedFiles]);
useEffect(() => {
customRequest();
}, [fileList]);
const deleteConfirmation = (
<Modal
visible={dialogVisible}
okText={<div aria-label="Yes">Yes</div>}
okType="primary"
cancelText={<div aria-label="No">No</div>}
onOk={() => onOk(flowName)}
onCancel={() => onCancel()}
width={350}
destroyOnClose={true}
>
<div className={styles.confirmationText}>Are you sure you want to delete the <strong>{flowName}</strong> flow?</div>
</Modal>
);
const deleteStepConfirmation = (
<Modal
visible={stepDialogVisible}
okText={<div aria-label="Yes">Yes</div>}
okType="primary"
cancelText={<div aria-label="No">No</div>}
onOk={() => onStepOk(flowName, stepNumber)}
onCancel={() => onCancel()}
width={350}
destroyOnClose={true}
>
<div className={styles.confirmationText}>Are you sure you want to remove the <strong>{stepName}</strong> step from the <strong>{flowName}</strong> flow?</div>
</Modal>
);
const addStepConfirmation = (
<Modal
visible={addStepDialogVisible}
okText={<div aria-label="Yes">Yes</div>}
okType="primary"
cancelText={<div aria-label="No">No</div>}
onOk={() => onAddStepOk(stepName, flowName, stepType)}
onCancel={() => onCancel()}
width={350}
>
<div className={styles.confirmationText}>
{
isStepInFlow(stepName, flowName)
?
<p>The step <b>{stepName}</b> is already in the flow <b>{flowName}</b>. Would you like to add another instance?</p>
:
<p>Are you sure you want to add step <b>{stepName}</b> to flow <b>{flowName}</b>?</p>
}
</div>
</Modal>
);
/* Commenting out for DHFPROD-7820, remove unfinished run flow epic stories from 5.6
const onCheckboxChange = (event, checkedValues, stepNumber, stepDefinitionType, flowNames, stepId, sourceFormat) => {
if (currentFlowName !== flowNames) {
if (currentFlowName.length > 0) {
let propertyNames=Object.getOwnPropertyNames(selectedStepOptions);
for (let i=0;i<propertyNames.length;i++) {
delete selectedStepOptions[propertyNames[i]];
}
for (let i=0;i<selectedStepDetails.length;i++) {
selectedStepDetails.shift();
}
setSelectedStepDetails({stepName: "", stepNumber: -1, stepDefinitionType: "", isChecked: false});
}
setCurrentFlowName(flowNames);
}
let data={stepName: "", stepNumber: -1, stepDefinitionType: "", isChecked: false, flowName: "", stepId: "", sourceFormat: ""};
data.stepName=checkedValues;
data.stepNumber=stepNumber;
data.stepDefinitionType=stepDefinitionType;
data.isChecked=event.target.checked;
data.flowName=flowNames;
data.stepId=stepId;
data.sourceFormat=sourceFormat;
let obj = selectedStepDetails;
if (data.isChecked) {
obj.push(data);
} else {
for (let i=0; i< obj.length;i++) {
if (obj[i].stepName === checkedValues) {
obj.splice(i, 1);
}
}
}
setSelectedStepDetails(obj);
setSelectedStepOptions({...selectedStepOptions, [checkedValues]: event.target.checked});
event.stopPropagation();
};
// const flowMenu = (flowName) => {
// return (
// <Menu>
// <Menu.ItemGroup title="Select the steps to include in the run.">
// {props.flows.map((flow) => (
// flow["name"] === flowName &&
// flow.steps.map((step, index) => (
// <Menu.Item key={index}>
// <MLCheckbox
// id={step.stepName}
// checked={selectedStepOptions[step.stepName]}
// onClick={(event) => onCheckboxChange(event, step.stepName, step.stepNumber, step.stepDefinitionType, flowName, step.stepId, step.sourceFormat)
// }
// >{step.stepName}</MLCheckbox>
// </Menu.Item>
// ))
// ))}
// </Menu.ItemGroup>
// </Menu>
// );
// };
// const handleRunFlow = async (index, name) => {
// setRunFlowClicked(true);
// const setKey = async () => {
// await setActiveKeys(`${index}`);
// };
// setRunningFlow(name);
// selectedStepDetails.shift();
// let flag=false;
// await selectedStepDetails.map(async step => {
// if (step.stepDefinitionType === "ingestion") {
// flag=true;
// setRunningStep(step);
// await setKey();
// await openFilePicker();
// }
// });
// if (Object.keys(selectedStepOptions).length === 0 && selectedStepOptions.constructor === Object) {
// flag=true;
// await setKey();
// await openFilePicker();
// }
// if (!flag) {
// let stepNumbers=[{}];
// for (let i=0;i<selectedStepDetails.length;i++) {
// stepNumbers.push(selectedStepDetails[i]);
// }
// stepNumbers.shift();
// await props.runFlowSteps(name, stepNumbers)
// .then(() => {
// setSelectedStepOptions({});
// setSelectedStepDetails([{stepName: "", stepNumber: -1, stepDefinitionType: "", isChecked: false}]);
// });
// }
// };
*/
const stepMenu = (flowName) => {
return (
<Menu>
<Menu.ItemGroup title="Load">
{props.steps && props.steps["ingestionSteps"] && props.steps["ingestionSteps"].length > 0 ? props.steps["ingestionSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "ingestion"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
<Menu.ItemGroup title="Map">
{props.steps && props.steps["mappingSteps"] && props.steps["mappingSteps"].length > 0 ? props.steps["mappingSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "mapping"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
<Menu.ItemGroup title="Match">
{props.steps && props.steps["matchingSteps"] && props.steps["matchingSteps"].length > 0 ? props.steps["matchingSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "matching"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
<Menu.ItemGroup title="Merge">
{props.steps && props.steps["mergingSteps"] && props.steps["mergingSteps"].length > 0 ? props.steps["mergingSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "merging"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
<Menu.ItemGroup title="Master">
{props.steps && props.steps["masteringSteps"] && props.steps["masteringSteps"].length > 0 ? props.steps["masteringSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "mastering"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
<Menu.ItemGroup title="Custom">
{props.steps && props.steps["customSteps"] && props.steps["customSteps"].length > 0 ? props.steps["customSteps"].map((elem, index) => (
<Menu.Item key={index} aria-label={`${elem.name}-to-flow`}>
<div
onClick={() => { handleStepAdd(elem.name, flowName, "custom"); }}
>{elem.name}</div>
</Menu.Item>
)) : null}
</Menu.ItemGroup>
</Menu>
);
};
const panelActions = (name, i) => (
<div
id="panelActions"
onClick={event => {
event.stopPropagation(); // Do not trigger collapse
event.preventDefault();
}}
>
{/* Commenting out for DHFPROD-7820, remove unfinished run flow epic stories from 5.6
<span id="stepsDropdown" className={styles.hoverColor}>
<Dropdown.Button
className={styles.runFlow}
overlay={flowMenu(name)}
data-testid={`runFlow-${name}`}
trigger={["click"]}
onClick={() => handleRunFlow(i, name)}
icon={<FontAwesomeIcon icon={faCog} type="edit" role="step-settings button" aria-label={`stepSettings-${name}`} className={styles.settingsIcon}/>}
>
<span className={styles.runIconAlign}><Icon type="play-circle" theme="filled" className={styles.runIcon}/></span>
<span className={styles.runFlowLabel}>Run Flow</span>
</Dropdown.Button></span> */}
<Dropdown
overlay={stepMenu(name)}
trigger={["click"]}
disabled={!props.canWriteFlow}
overlayClassName="stepMenu"
>
{props.canWriteFlow ?
<MLButton
className={styles.addStep}
size="default"
aria-label={`addStep-${name}`}
style={{}}
>Add Step <DownOutlined /></MLButton>
:
<MLTooltip title={SecurityTooltips.missingPermission} overlayStyle={{maxWidth: "175px"}} placement="bottom">
<span className={styles.disabledCursor}>
<MLButton
className={styles.addStep}
size="default"
aria-label={"addStepDisabled-" + i}
style={{backgroundColor: "#f5f5f5", borderColor: "#f5f5f5", pointerEvents: "none"}}
type="primary"
disabled={!props.canWriteFlow}
>Add Step <DownOutlined /></MLButton>
</span>
</MLTooltip>
}
</Dropdown>
<span className={styles.deleteFlow}>
{props.canWriteFlow ?
<MLTooltip title={"Delete Flow"} placement="bottom">
<i aria-label={`deleteFlow-${name}`}>
<FontAwesomeIcon
icon={faTrashAlt}
onClick={() => { handleFlowDelete(name); }}
data-testid={`deleteFlow-${name}`}
className={styles.deleteIcon}
size="lg" />
</i>
</MLTooltip>
:
<MLTooltip title={"Delete Flow: " + SecurityTooltips.missingPermission} overlayStyle={{maxWidth: "225px"}} placement="bottom">
<i aria-label={`deleteFlowDisabled-${name}`}>
<FontAwesomeIcon
icon={faTrashAlt}
data-testid={`deleteFlow-${name}`}
className={styles.disabledDeleteIcon}
size="lg" />
</i>
</MLTooltip>}
</span>
</div>
);
const flowHeader = (name, index) => (
<MLTooltip title={props.canWriteFlow ? "Edit Flow" : "Flow Details"} placement="right">
<span className={styles.flowName} onClick={(e) => OpenEditFlowDialog(e, index)}>
{name}
</span>
</MLTooltip>
/* Commenting out for DHFPROD-7820, remove unfinished run flow epic stories from 5.6, replace above with below later
// <span>
// <MLTooltip title={props.canWriteFlow ? "Edit Flow" : "Flow Details"} placement="bottom">
// <span className={styles.flowName} onClick={(e) => OpenEditFlowDialog(e, index)}>
// {name}
// </span>
// </MLTooltip>
// {latestJobData && latestJobData[name] && latestJobData[name].find(step => step.jobId) ?
// <MLTooltip title={"Flow Status"} placement="bottom">
// <span onClick={(e) => OpenFlowJobStatus(e, index, name)} className={styles.infoIcon}>
// <Icon type="info-circle" theme="filled" data-testid={name + "-StatusIcon"} />
// </span>
// </MLTooltip>
// : ""
// }
// </span>
*/
);
/* Commenting out for DHFPROD-7820, remove unfinished run flow epic stories from 5.6
const OpenFlowJobStatus = (e, index, name) => {
e.stopPropagation();
e.preventDefault();
let jobIdIndex = latestJobData[name].findIndex(step => step.hasOwnProperty("jobId"));
props.setJobId(latestJobData[name][jobIdIndex].jobId);
props.setOpenJobResponse(true);
};
*/
const OpenEditFlowDialog = (e, index) => {
e.stopPropagation();
setTitle("Edit Flow");
setFlowData(prevState => ({...prevState, ...props.flows[index]}));
setNewFlow(true);
};
const StepDefToTitle = (stepDef) => {
return (StepDefinitionTypeTitles[stepDef]) ? StepDefinitionTypeTitles[stepDef] : "Unknown";
};
const customRequest = async () => {
const filenames = fileList.map(({name}) => name);
if (filenames.length) {
let fl = fileList;
const formData = new FormData();
fl.forEach(file => {
formData.append("files", file);
});
if (!runFlowClicked) {
await props.runStep(runningFlow, runningStep, formData)
.then(resp => {
setShowUploadError(true);
setFileList([]);
});
} else {
let stepNumbers=[{}];
for (let i=0;i<selectedStepDetails.length;i++) {
stepNumbers.push(selectedStepDetails[i]);
}
stepNumbers.shift();
await props.runFlowSteps(runningFlow, stepNumbers, formData)
.then(resp => {
setShowUploadError(true);
setFileList([]);
setSelectedStepOptions({});
setSelectedStepDetails([{stepName: "", stepNumber: -1, stepDefinitionType: "", isChecked: false}]);
setRunFlowClicked(false);
});
}
}
};
const isRunning = (flowId, stepId) => {
let result = props.running.find(r => (r.flowId === flowId && r.stepId === stepId));
return result !== undefined;
};
function handleMouseOver(e, name) {
setShowLinks(name);
}
const showStepRunResponse = async (step) => {
try {
let response = await axios.get("/api/jobs/" + step.jobId);
if (response.status === 200) {
props.showStepRunResponse(step, step.jobId, response.data);
}
} catch (error) {
handleError(error);
}
};
const lastRunResponse = (step) => {
let stepEndTime, tooltipText;
if (step.stepEndTime) {
stepEndTime = new Date(step.stepEndTime).toLocaleString();
}
if (!step.lastRunStatus) {
return;
} else if (step.lastRunStatus === "completed step " + step.stepNumber) {
tooltipText = "Step last ran successfully on " + stepEndTime;
return (
<MLTooltip overlayStyle={{maxWidth: "200px"}} title={tooltipText} placement="bottom" getPopupContainer={() => document.getElementById("flowSettings") || document.body}
onClick={(e) => showStepRunResponse(step)}>
<Icon type="check-circle" theme="filled" className={styles.successfulRun} data-testid={`check-circle-${step.stepName}`}/>
</MLTooltip>
);
} else if (step.lastRunStatus === "completed with errors step " + step.stepNumber) {
tooltipText = "Step last ran with errors on " + stepEndTime;
return (
<MLTooltip overlayStyle={{maxWidth: "190px"}} title={tooltipText} placement="bottom" getPopupContainer={() => document.getElementById("flowSettings") || document.body}
onClick={(e) => showStepRunResponse(step)}>
<Icon type="exclamation-circle" theme="filled" className={styles.unSuccessfulRun} />
</MLTooltip>
);
} else {
tooltipText = "Step last failed on " + stepEndTime;
return (
<MLTooltip overlayStyle={{maxWidth: "175px"}} title={tooltipText} placement="bottom" getPopupContainer={() => document.getElementById("flowSettings") || document.body}
onClick={(e) => showStepRunResponse(step)}>
<Icon type="exclamation-circle" theme="filled" className={styles.unSuccessfulRun} />
</MLTooltip>
);
}
};
const updateFlow = async (flowName, flowDesc, steps) => {
let updatedFlow;
try {
updatedFlow = {
name: flowName,
steps: steps,
description: flowDesc
};
await axios.put(`/api/flows/` + flowName, updatedFlow);
} catch (error) {
console.error("Error updating flow", error);
}
};
const reorderFlow = (id, flowName, direction: ReorderFlowOrderDirection) => {
let flowNum = props.flows.findIndex((flow) => flow.name === flowName);
let flowDesc = props.flows[flowNum]["description"];
const stepList = props.flows[flowNum]["steps"];
let newSteps = stepList;
if (direction === ReorderFlowOrderDirection.RIGHT) {
if (id <= stepList.length - 2) {
newSteps = [...stepList];
const oldLeftStep = newSteps[id];
const oldRightStep = newSteps[id + 1];
newSteps[id] = oldRightStep;
newSteps[id + 1] = oldLeftStep;
}
} else {
if (id >= 1) {
newSteps = [...stepList];
const oldLeftStep = newSteps[id - 1];
const oldRightStep = newSteps[id];
newSteps[id - 1] = oldRightStep;
newSteps[id] = oldLeftStep;
}
}
let steps : string[] = [];
for (let i = 0; i < newSteps.length; i++) {
newSteps[i].stepNumber = String(i+1);
steps.push(newSteps[i].stepId);
}
const reorderedList = [...newSteps];
props.onReorderFlow(flowNum, reorderedList);
updateFlow(flowName, flowDesc, steps);
};
const getFlowWithJobInfo = async (flowNum) => {
let currentFlow = props.flows[flowNum];
if (currentFlow === undefined) {
return;
}
if (currentFlow["steps"].length > 0) {
try {
let response = await axios.get("/api/flows/" + currentFlow.name + "/latestJobInfo");
if (response.status === 200 && response.data) {
let currentFlowJobInfo = {};
currentFlowJobInfo[currentFlow["name"]] = response.data["steps"];
setLatestJobData(prevJobData => (
{...prevJobData, ...currentFlowJobInfo}
));
}
} catch (error) {
console.error("Error getting latest job info ", error);
}
}
};
let panels;
if (props.flows) {
panels = props.flows.map((flow, i) => {
let flowName = flow.name;
let cards = flow.steps.map((step, index) => {
let sourceFormat = step.sourceFormat;
let stepNumber = step.stepNumber;
let viewStepId = `${flowName}-${stepNumber}`;
let stepDefinitionType = step.stepDefinitionType ? step.stepDefinitionType.toLowerCase() : "";
let stepDefinitionTypeTitle = StepDefinitionTypeTitles[stepDefinitionType];
return (
<div key={viewStepId} id="flowSettings">
<Card
className={styles.cardStyle}
title={StepDefToTitle(step.stepDefinitionType)}
size="small"
actions={[
<div className={styles.reorder}>
{index !== 0 && props.canWriteFlow &&
<div className={styles.reorderLeft}>
<MLTooltip title={"Move left"} placement="bottom" getPopupContainer={() => document.getElementById("flowSettings") || document.body}>
<FontAwesomeIcon
aria-label={`leftArrow-${step.stepName}`}
icon={faArrowAltCircleLeft}
className={styles.reorderFlowLeft}
role="button"
onClick={() => reorderFlow(index, flowName, ReorderFlowOrderDirection.LEFT)}
onKeyDown={(e) => reorderFlowKeyDownHandler(e, index, flowName, ReorderFlowOrderDirection.LEFT)}
tabIndex={0}/>
</MLTooltip>
</div>
}
<div className={styles.reorderRight}>
<div className={styles.stepResponse}>
{latestJobData && latestJobData[flowName] && latestJobData[flowName][index]
? lastRunResponse(latestJobData[flowName][index])
: ""
}
</div>
{index < flow.steps.length - 1 && props.canWriteFlow &&
<MLTooltip title={"Move right"} placement="bottom" getPopupContainer={() => document.getElementById("flowSettings") || document.body}>
<FontAwesomeIcon
aria-label={`rightArrow-${step.stepName}`}
icon={faArrowAltCircleRight}
className={styles.reorderFlowRight}
role="button"
onClick={() => reorderFlow(index, flowName, ReorderFlowOrderDirection.RIGHT)}
onKeyDown={(e) => reorderFlowKeyDownHandler(e, index, flowName, ReorderFlowOrderDirection.RIGHT)}
tabIndex={0}/>
</MLTooltip>
}
</div>
</div>
]}
extra={
<div className={styles.actions}>
{props.hasOperatorRole ?
step.stepDefinitionType.toLowerCase() === "ingestion" ?
<div {...getRootProps()} style={{display: "inline-block"}}>
<input {...getInputProps()} id="fileUpload" />
<div
className={styles.run}
aria-label={`runStep-${step.stepName}`}
data-testid={"runStep-" + stepNumber}
onClick={() => {
setShowUploadError(false);
setRunningStep(step);
setRunningFlow(flowName);
openFilePicker();
}}
>
<MLTooltip title={RunToolTips.ingestionStep} placement="bottom">
<Icon type="play-circle" theme="filled" />
</MLTooltip>
</div>
</div>
:
<div
className={styles.run}
onClick={() => {
setShowUploadError(false);
props.runStep(flowName, step);
}}
aria-label={`runStep-${step.stepName}`}
data-testid={"runStep-" + stepNumber}
>
<MLTooltip title={RunToolTips.otherSteps} placement="bottom">
<Icon type="play-circle" theme="filled" />
</MLTooltip>
</div>
:
<div
className={styles.disabledRun}
onClick={(event) => { event.stopPropagation(); event.preventDefault(); }}
aria-label={"runStepDisabled-" + step.stepName}
data-testid={"runStepDisabled-" + stepNumber}
>
<Icon type="play-circle" theme="filled" />
</div>
}
{props.canWriteFlow ?
<MLTooltip title={RunToolTips.removeStep} placement="bottom">
<div className={styles.delete} aria-label={`deleteStep-${step.stepName}`} onClick={() => handleStepDelete(flowName, step)}><Icon type="close" /></div>
</MLTooltip> :
<MLTooltip title={RunToolTips.removeStep} placement="bottom">
<div className={styles.disabledDelete} aria-label={`deleteStepDisabled-${step.stepName}`} onClick={(event) => { event.stopPropagation(); event.preventDefault(); }}><Icon type="close" /></div>
</MLTooltip>
}
</div>
}
>
<div aria-label={viewStepId + "-content"} className={styles.cardContent}
onMouseOver={(e) => handleMouseOver(e, viewStepId)}
onMouseLeave={(e) => setShowLinks("")} >
{sourceFormat ?
<div className={styles.format} style={sourceFormatStyle(sourceFormat)} >{sourceFormatOptions[sourceFormat].label}</div>
: null}
<div className={sourceFormat ? styles.loadStepName : styles.name}>{step.stepName}</div>
<div className={styles.cardLinks}
style={{display: showLinks === viewStepId && step.stepId && authorityByStepType[stepDefinitionType] ? "block" : "none"}}
aria-label={viewStepId + "-cardlink"}
>
<Link id={"tiles-step-view-" + viewStepId}
to={{
pathname: `/tiles/${stepDefinitionType === "ingestion" ? "load" : "curate"}`,
state: {
stepToView: step.stepId,
stepDefinitionType: stepDefinitionType,
targetEntityType: step.targetEntityType
}
}}
>
<div className={styles.cardLink} data-testid={`${viewStepId}-viewStep`}>View {stepDefinitionTypeTitle} steps</div>
</Link>
</div>
</div>
<div className={styles.uploadError}>
{showUploadError && flowName === runningFlow && stepNumber === runningStep.stepNumber ? props.uploadError : ""}
</div>
<div className={styles.running} style={{display: isRunning(flowName, stepNumber) ? "block" : "none"}}>
<div><MLSpin data-testid="spinner" /></div>
<div className={styles.runningLabel}>Running...</div>
</div>
</Card>
</div>
);
});
return (
<Panel header={flowHeader(flowName, i)} key={i} extra={panelActions(flowName, i)} id={flowName} >
<div className={styles.panelContent} ref={flowPanels[flowName]}>
{cards}
</div>
</Panel>
);
});
}
//Update activeKeys on Collapse Panel interactions
const handlePanelInteraction = (key) => {
/* Request to get latest job info for the flow will be made when someone opens the pane for the first time
or opens a new pane. Closing the pane shouldn't send any requests*/
if (!activeKeys || (key.length > activeKeys.length && key.length > 0)) {
getFlowWithJobInfo(key[key.length - 1]);
}
setActiveKeys([...key]);
};
const createFlowKeyDownHandler = (event) => {
if (event.key === "Enter") {
OpenAddNewDialog();
event.preventDefault();
}
};
const reorderFlowKeyDownHandler = (event, index, flowName, direction) => {
if (event.key === "Enter") {
reorderFlow(index, flowName, direction);
event.preventDefault();
}
};
return (
<div id="flows-container" className={styles.flowsContainer}>
{props.canReadFlow || props.canWriteFlow ?
<>
<div className={styles.createContainer}>
{
props.canWriteFlow ?
<span> <MLButton
className={styles.createButton} size="default"
type="primary" onClick={OpenAddNewDialog} onKeyDown={createFlowKeyDownHandler}
aria-label={"create-flow"}
tabIndex={0}
>Create Flow</MLButton></span>
:
<MLTooltip title={SecurityTooltips.missingPermission} overlayStyle={{maxWidth: "175px"}}>
<span className={styles.disabledCursor}>
<MLButton
className={styles.createButtonDisabled} size="default"
type="primary"
disabled={true}
aria-label={"create-flow-disabled"}
tabIndex={-1}
>Create Flow</MLButton>
</span>
</MLTooltip>
}
</div>
<Collapse
className={styles.collapseFlows}
activeKey={activeKeys}
onChange={handlePanelInteraction}
>
{panels}
</Collapse>
<NewFlowDialog
newFlow={newFlow || openNewFlow}
title={title}
setNewFlow={setNewFlow}
setAddedFlowName={setAddedFlowName}
createFlow={props.createFlow}
createAdd={createAdd}
updateFlow={props.updateFlow}
flowData={flowData}
canWriteFlow={props.canWriteFlow}
addStepToFlow={props.addStepToFlow}
newStepToFlowOptions={props.newStepToFlowOptions}
setOpenNewFlow={setOpenNewFlow}
/>
{deleteConfirmation}
{deleteStepConfirmation}
{addStepConfirmation}
</> :
<div></div>
}
</div>
);
};
export default Flows; | the_stack |
import { sign } from "tweetnacl";
import { SkynetClient } from "./client";
import { DEFAULT_DOWNLOAD_OPTIONS, CustomDownloadOptions } from "./download";
import {
DEFAULT_GET_ENTRY_OPTIONS,
DEFAULT_SET_ENTRY_OPTIONS,
CustomGetEntryOptions,
RegistryEntry,
CustomSetEntryOptions,
validatePublicKey,
} from "./registry";
import { CachedRevisionNumber } from "./revision_cache";
import { BASE64_ENCODED_SKYLINK_SIZE, decodeSkylink, EMPTY_SKYLINK, RAW_SKYLINK_SIZE } from "./skylink/sia";
import { MAX_REVISION } from "./utils/number";
import { URI_SKYNET_PREFIX } from "./utils/url";
import {
hexToUint8Array,
trimUriPrefix,
toHexString,
stringToUint8ArrayUtf8,
uint8ArrayToStringUtf8,
} from "./utils/string";
import { formatSkylink } from "./skylink/format";
import { DEFAULT_UPLOAD_OPTIONS, CustomUploadOptions } from "./upload";
import { areEqualUint8Arrays } from "./utils/array";
import { decodeSkylinkBase64, encodeSkylinkBase64 } from "./utils/encoding";
import { DEFAULT_BASE_OPTIONS, extractOptions } from "./utils/options";
import { JsonData } from "./utils/types";
import {
throwValidationError,
validateHexString,
validateObject,
validateOptionalObject,
validateSkylinkString,
validateString,
validateUint8Array,
validateUint8ArrayLen,
} from "./utils/validation";
import { ResponseType } from "axios";
import { EntryData, MAX_ENTRY_LENGTH } from "./mysky";
type SkynetJson = {
_data: JsonData;
_v: number;
};
export const DELETION_ENTRY_DATA = new Uint8Array(RAW_SKYLINK_SIZE);
const JSON_RESPONSE_VERSION = 2;
const UNCACHED_REVISION_NUMBER = BigInt(-1);
/**
* Custom get JSON options. Includes the options for get entry, to get the
* skylink; and download, to download the file from the skylink.
*
* @property [cachedDataLink] - The last known data link. If it hasn't changed, do not download the file contents again.
*/
export type CustomGetJSONOptions = CustomGetEntryOptions &
CustomDownloadOptions & {
cachedDataLink?: string;
};
/**
* The default options for get JSON. Includes the default get entry and download
* options.
*/
export const DEFAULT_GET_JSON_OPTIONS = {
...DEFAULT_BASE_OPTIONS,
...DEFAULT_GET_ENTRY_OPTIONS,
...DEFAULT_DOWNLOAD_OPTIONS,
cachedDataLink: undefined,
};
/**
* Custom set JSON options. Includes the options for upload, to get the file for
* the skylink; get JSON, to retrieve the revision; and set entry, to set the
* entry with the skylink and revision.
*/
export type CustomSetJSONOptions = CustomUploadOptions & CustomGetJSONOptions & CustomSetEntryOptions;
/**
* The default options for set JSON. Includes the default upload, get JSON, and
* set entry options.
*/
export const DEFAULT_SET_JSON_OPTIONS = {
...DEFAULT_BASE_OPTIONS,
...DEFAULT_UPLOAD_OPTIONS,
...DEFAULT_GET_JSON_OPTIONS,
...DEFAULT_SET_ENTRY_OPTIONS,
};
/**
* Custom set entry data options. Includes the options for get and set entry.
*/
export type CustomSetEntryDataOptions = CustomGetEntryOptions &
CustomSetEntryOptions & { allowDeletionEntryData: boolean };
/**
* The default options for set entry data. Includes the default get entry and
* set entry options.
*/
export const DEFAULT_SET_ENTRY_DATA_OPTIONS = {
...DEFAULT_BASE_OPTIONS,
...DEFAULT_GET_ENTRY_OPTIONS,
...DEFAULT_SET_ENTRY_OPTIONS,
allowDeletionEntryData: false,
};
export type JSONResponse = {
data: JsonData | null;
dataLink: string | null;
};
export type RawBytesResponse = {
data: Uint8Array | null;
dataLink: string | null;
};
// ====
// JSON
// ====
/**
* Gets the JSON object corresponding to the publicKey and dataKey. If the data
* was found, we update the cached revision number for the entry.
*
* NOTE: The cached revision number will be updated only if the data is found
* (including deleted data). If there is a 404 or the entry contains deleted
* data, null will be returned. If there is an error, the error is returned
* without updating the cached revision number.
*
* Summary:
* - Data found: update cached revision
* - Parse error: don't update cached revision
* - Network error: don't update cached revision
* - Too low version error: don't update the cached revision
* - 404 (data not found): don't update the cached revision
* - Data deleted: update cached revision
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned JSON and corresponding data link.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
*/
export async function getJSON(
this: SkynetClient,
publicKey: string,
dataKey: string,
customOptions?: CustomGetJSONOptions
): Promise<JSONResponse> {
validatePublicKey("publicKey", publicKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_GET_JSON_OPTIONS);
const opts = {
...DEFAULT_GET_JSON_OPTIONS,
...this.customOptions,
...customOptions,
};
// Immediately fail if the mutex is not available.
return await this.db.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
// Lookup the registry entry.
const getEntryOpts = extractOptions(opts, DEFAULT_GET_ENTRY_OPTIONS);
const entry: RegistryEntry | null = await getSkyDBRegistryEntryAndUpdateCache(
this,
publicKey,
dataKey,
cachedRevisionEntry,
getEntryOpts
);
if (entry === null) {
return { data: null, dataLink: null };
}
// Determine the data link.
// TODO: Can this still be an entry link which hasn't yet resolved to a data link?
const { rawDataLink, dataLink } = parseDataLink(entry.data, true);
// If a cached data link is provided and the data link hasn't changed, return.
if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) {
return { data: null, dataLink };
}
// Download the data in the returned data link.
const downloadOpts = extractOptions(opts, DEFAULT_DOWNLOAD_OPTIONS);
const { data }: { data: JsonData | SkynetJson } = await this.getFileContent<JsonData>(dataLink, downloadOpts);
// Validate that the returned data is JSON.
if (typeof data !== "object" || data === null) {
throw new Error(`File data for the entry at data key '${dataKey}' is not JSON.`);
}
if (!(data["_data"] && data["_v"])) {
// Legacy data prior to skynet-js v4, return as-is.
return { data, dataLink };
}
// Extract the JSON from the returned SkynetJson.
const actualData = data["_data"];
if (typeof actualData !== "object" || data === null) {
throw new Error(`File data '_data' for the entry at data key '${dataKey}' is not JSON.`);
}
return { data: actualData as JsonData, dataLink };
});
}
/**
* Sets a JSON object at the registry entry corresponding to the publicKey and
* dataKey.
*
* This will use the entry revision number from the cache, so getJSON must
* always be called first for existing entries.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The key of the data to fetch for the given user.
* @param json - The JSON data to set.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned JSON and corresponding data link.
* @throws - Will throw if the input keys are not valid strings.
*/
export async function setJSON(
this: SkynetClient,
privateKey: string,
dataKey: string,
json: JsonData,
customOptions?: CustomSetJSONOptions
): Promise<JSONResponse> {
validateHexString("privateKey", privateKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateObject("json", json, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_SET_JSON_OPTIONS);
const opts = {
...DEFAULT_SET_JSON_OPTIONS,
...this.customOptions,
...customOptions,
};
const { publicKey: publicKeyArray } = sign.keyPair.fromSecretKey(hexToUint8Array(privateKey));
const publicKey = toHexString(publicKeyArray);
// Immediately fail if the mutex is not available.
return await this.db.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
// Get the cached revision number before doing anything else. Increment it.
const newRevision = incrementRevision(cachedRevisionEntry.revision);
const [entry, dataLink] = await getOrCreateSkyDBRegistryEntry(this, dataKey, json, newRevision, opts);
// Update the registry.
const setEntryOpts = extractOptions(opts, DEFAULT_SET_ENTRY_OPTIONS);
await this.registry.setEntry(privateKey, entry, setEntryOpts);
// Update the cached revision number.
cachedRevisionEntry.revision = newRevision;
return { data: json, dataLink: formatSkylink(dataLink) };
});
}
/**
* Deletes a JSON object at the registry entry corresponding to the publicKey
* and dataKey.
*
* This will use the entry revision number from the cache, so getJSON must
* always be called first.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the input keys are not valid strings.
*/
export async function deleteJSON(
this: SkynetClient,
privateKey: string,
dataKey: string,
customOptions?: CustomSetEntryDataOptions
): Promise<void> {
// Validation is done below in `db.setEntryData`.
const opts = {
...DEFAULT_SET_ENTRY_DATA_OPTIONS,
...this.customOptions,
...customOptions,
};
await this.db.setEntryData(privateKey, dataKey, DELETION_ENTRY_DATA, { ...opts, allowDeletionEntryData: true });
}
// ==========
// Entry Data
// ==========
/**
* Sets the datalink for the entry at the given private key and data key.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The data key.
* @param dataLink - The data link to set at the entry.
* @param [customOptions] - Additional settings that can optionally be set.
* @throws - Will throw if the input keys are not valid strings.
*/
export async function setDataLink(
this: SkynetClient,
privateKey: string,
dataKey: string,
dataLink: string,
customOptions?: CustomSetEntryDataOptions
): Promise<void> {
const parsedSkylink = validateSkylinkString("dataLink", dataLink, "parameter");
// Rest of validation is done below in `db.setEntryData`.
const data = decodeSkylink(parsedSkylink);
await this.db.setEntryData(privateKey, dataKey, data, customOptions);
}
/**
* Gets the raw registry entry data at the given public key and data key.
*
* If the data was found, we update the cached revision number for the entry.
* See getJSON for behavior in other cases.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The data key.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The entry data.
*/
export async function getEntryData(
this: SkynetClient,
publicKey: string,
dataKey: string,
customOptions?: CustomGetEntryOptions
): Promise<EntryData> {
validatePublicKey("publicKey", publicKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_GET_ENTRY_OPTIONS);
const opts = {
...DEFAULT_GET_ENTRY_OPTIONS,
...this.customOptions,
...customOptions,
};
// Immediately fail if the mutex is not available.
return await this.db.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
const entry = await getSkyDBRegistryEntryAndUpdateCache(this, publicKey, dataKey, cachedRevisionEntry, opts);
if (entry === null) {
return { data: null };
}
return { data: entry.data };
});
}
/**
* Sets the raw entry data at the given private key and data key.
*
* This will use the entry revision number from the cache, so getEntryData must
* always be called first for existing entries.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The data key.
* @param data - The raw entry data to set.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The entry data.
* @throws - Will throw if the length of the data is > 70 bytes.
*/
export async function setEntryData(
this: SkynetClient,
privateKey: string,
dataKey: string,
data: Uint8Array,
customOptions?: CustomSetEntryDataOptions
): Promise<EntryData> {
validateHexString("privateKey", privateKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateUint8Array("data", data, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_SET_ENTRY_DATA_OPTIONS);
const opts = {
...DEFAULT_SET_ENTRY_DATA_OPTIONS,
...this.customOptions,
...customOptions,
};
validateEntryData(data, opts.allowDeletionEntryData);
const { publicKey: publicKeyArray } = sign.keyPair.fromSecretKey(hexToUint8Array(privateKey));
const publicKey = toHexString(publicKeyArray);
// Immediately fail if the mutex is not available.
return await this.db.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
// Get the cached revision number.
const newRevision = incrementRevision(cachedRevisionEntry.revision);
const entry = { dataKey, data, revision: newRevision };
const setEntryOpts = extractOptions(opts, DEFAULT_SET_ENTRY_OPTIONS);
await this.registry.setEntry(privateKey, entry, setEntryOpts);
// Update the cached revision number.
cachedRevisionEntry.revision = newRevision;
return { data: entry.data };
});
}
/**
* Deletes the entry data at the given private key and data key. Trying to
* access the data again with e.g. getEntryData will result in null.
*
* This will use the entry revision number from the cache, so getEntryData must
* always be called first.
*
* @param this - SkynetClient
* @param privateKey - The user private key.
* @param dataKey - The data key.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - An empty promise.
*/
export async function deleteEntryData(
this: SkynetClient,
privateKey: string,
dataKey: string,
customOptions?: CustomSetEntryDataOptions
): Promise<void> {
// Validation is done below in `db.setEntryData`.
await this.db.setEntryData(privateKey, dataKey, DELETION_ENTRY_DATA, {
...customOptions,
allowDeletionEntryData: true,
});
}
// =========
// Raw Bytes
// =========
/**
* Gets the raw bytes corresponding to the publicKey and dataKey. The caller is responsible for setting any metadata in the bytes.
*
* If the data was found, we update the cached revision number for the entry.
* See getJSON for behavior in other cases.
*
* @param this - SkynetClient
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The returned bytes.
* @throws - Will throw if the returned signature does not match the returned entry, or if the skylink in the entry is invalid.
*/
export async function getRawBytes(
this: SkynetClient,
publicKey: string,
dataKey: string,
// TODO: Take a new options type?
customOptions?: CustomGetJSONOptions
): Promise<RawBytesResponse> {
validatePublicKey("publicKey", publicKey, "parameter");
validateString("dataKey", dataKey, "parameter");
validateOptionalObject("customOptions", customOptions, "parameter", DEFAULT_GET_JSON_OPTIONS);
const opts = {
...DEFAULT_GET_JSON_OPTIONS,
...this.customOptions,
...customOptions,
};
// Immediately fail if the mutex is not available.
return await this.db.revisionNumberCache.withCachedEntryLock(publicKey, dataKey, async (cachedRevisionEntry) => {
// Lookup the registry entry.
const getEntryOpts = extractOptions(opts, DEFAULT_GET_ENTRY_OPTIONS);
const entry = await getSkyDBRegistryEntryAndUpdateCache(
this,
publicKey,
dataKey,
cachedRevisionEntry,
getEntryOpts
);
if (entry === null) {
return { data: null, dataLink: null };
}
// Determine the data link.
// TODO: Can this still be an entry link which hasn't yet resolved to a data link?
const { rawDataLink, dataLink } = parseDataLink(entry.data, false);
// If a cached data link is provided and the data link hasn't changed, return.
if (checkCachedDataLink(rawDataLink, opts.cachedDataLink)) {
return { data: null, dataLink };
}
// Download the data in the returned data link.
const downloadOpts = {
...extractOptions(opts, DEFAULT_DOWNLOAD_OPTIONS),
responseType: "arraybuffer" as ResponseType,
};
const { data: buffer } = await this.getFileContent<ArrayBuffer>(dataLink, downloadOpts);
return { data: new Uint8Array(buffer), dataLink };
});
}
// =======
// Helpers
// =======
/**
* Gets the registry entry and data link or creates the entry if it doesn't
* exist. Uses the cached revision number for the entry, or 0 if the entry has
* not been cached.
*
* @param client - The Skynet client.
* @param dataKey - The data key.
* @param data - The JSON or raw byte data to set.
* @param revision - The revision number to set.
* @param [customOptions] - Additional settings that can optionally be set.
* @returns - The registry entry and corresponding data link.
* @throws - Will throw if the revision is already the maximum value.
*/
export async function getOrCreateSkyDBRegistryEntry(
client: SkynetClient,
dataKey: string,
data: JsonData | Uint8Array,
revision: bigint,
customOptions?: CustomSetJSONOptions
): Promise<[RegistryEntry, string]> {
// Not publicly available, don't validate input.
const opts = {
...DEFAULT_SET_JSON_OPTIONS,
...client.customOptions,
...customOptions,
};
let fullData: string | Uint8Array;
if (!(data instanceof Uint8Array)) {
// Set the hidden _data and _v fields.
const skynetJson = buildSkynetJsonObject(data);
fullData = JSON.stringify(skynetJson);
} else {
/* istanbul ignore next - This case is only called by setJSONEncrypted which is not tested in this repo */
fullData = data;
}
// Create the data to upload to acquire its skylink.
let dataKeyHex = dataKey;
if (!opts.hashedDataKeyHex) {
dataKeyHex = toHexString(stringToUint8ArrayUtf8(dataKey));
}
const file = new File([fullData], `dk:${dataKeyHex}`, { type: "application/json" });
// Do file upload.
const uploadOpts = extractOptions(opts, DEFAULT_UPLOAD_OPTIONS);
const skyfile = await client.uploadFile(file, uploadOpts);
// Build the registry entry.
const dataLink = trimUriPrefix(skyfile.skylink, URI_SKYNET_PREFIX);
const rawDataLink = decodeSkylinkBase64(dataLink);
validateUint8ArrayLen("rawDataLink", rawDataLink, "skylink byte array", RAW_SKYLINK_SIZE);
const entry: RegistryEntry = {
dataKey,
data: rawDataLink,
revision,
};
return [entry, formatSkylink(dataLink)];
}
/**
* Increments the given revision number and checks to make sure it is not
* greater than the maximum revision.
*
* @param revision - The given revision number.
* @returns - The incremented revision number.
* @throws - Will throw if the incremented revision number is greater than the maximum revision.
*/
export function incrementRevision(revision: bigint): bigint {
revision = revision + BigInt(1);
// Throw if the revision is already the maximum value.
if (revision > MAX_REVISION) {
throw new Error("Current entry already has maximum allowed revision, could not update the entry");
}
return revision;
}
/**
* Checks whether the raw data link matches the cached data link, if provided.
*
* @param rawDataLink - The raw, unformatted data link.
* @param cachedDataLink - The cached data link, if provided.
* @returns - Whether the cached data link is a match.
* @throws - Will throw if the given cached data link is not a valid skylink.
*/
export function checkCachedDataLink(rawDataLink: string, cachedDataLink?: string): boolean {
if (cachedDataLink) {
cachedDataLink = validateSkylinkString("cachedDataLink", cachedDataLink, "optional parameter");
return rawDataLink === cachedDataLink;
}
return false;
}
/**
* Validates the given entry data.
*
* @param data - The entry data to validate.
* @param allowDeletionEntryData - If set to false, disallows setting the entry data that marks a deletion. This is a likely developer error if it was not done through the deleteEntryData method.
* @throws - Will throw if the data is invalid.
*/
export function validateEntryData(data: Uint8Array, allowDeletionEntryData: boolean): void {
// Check that the length is not greater than the maximum allowed.
if (data.length > MAX_ENTRY_LENGTH) {
throwValidationError(
"data",
data,
"parameter",
`'Uint8Array' of length <= ${MAX_ENTRY_LENGTH}, was length ${data.length}`
);
}
// Check that we are not setting the deletion sentinel as that is probably a developer mistake.
if (!allowDeletionEntryData && areEqualUint8Arrays(data, DELETION_ENTRY_DATA)) {
throw new Error(
"Tried to set 'Uint8Array' entry data that is the deletion sentinel ('Uint8Array(RAW_SKYLINK_SIZE)'), please use the 'deleteEntryData' method instead`"
);
}
}
/**
* Gets the registry entry, returning null if the entry was not found or if it
* contained a sentinel value indicating deletion.
*
* If the data was found, we update the cached revision number for the entry.
* See getJSON for behavior in other cases.
*
* @param client - The Skynet Client
* @param publicKey - The user public key.
* @param dataKey - The key of the data to fetch for the given user.
* @param cachedRevisionEntry - The cached revision entry object containing the revision number and the mutex.
* @param opts - Additional settings.
* @returns - The registry entry, or null if not found or deleted.
*/
async function getSkyDBRegistryEntryAndUpdateCache(
client: SkynetClient,
publicKey: string,
dataKey: string,
cachedRevisionEntry: CachedRevisionNumber,
opts: CustomGetEntryOptions
): Promise<RegistryEntry | null> {
// If this throws due to a parse error or network error, exit early and do not
// update the cached revision number.
const { entry } = await client.registry.getEntry(publicKey, dataKey, opts);
// Don't update the cached revision number if the data was not found (404). Return null.
if (entry === null) {
return null;
}
// Calculate the new revision.
const newRevision = entry?.revision ?? UNCACHED_REVISION_NUMBER + BigInt(1);
// Don't update the cached revision number if the received version is too low.
// Throw error.
const cachedRevision = cachedRevisionEntry.revision;
if (cachedRevision && cachedRevision > newRevision) {
throw new Error(
"Returned revision number too low. A higher revision number for this userID and path is already cached"
);
}
// Update the cached revision.
cachedRevisionEntry.revision = newRevision;
// Return null if the entry contained a sentinel value indicating deletion.
// We do this after updating the revision number cache.
if (wasRegistryEntryDeleted(entry)) {
return null;
}
return entry;
}
/**
* Sets the hidden _data and _v fields on the given raw JSON data.
*
* @param data - The given JSON data.
* @returns - The Skynet JSON data.
*/
function buildSkynetJsonObject(data: JsonData): SkynetJson {
return { _data: data, _v: JSON_RESPONSE_VERSION };
}
/**
* Parses a data link out of the given registry entry data.
*
* @param data - The raw registry entry data.
* @param legacy - Whether to check for possible legacy skylink data, encoded as base64.
* @returns - The raw, unformatted data link and the formatted data link.
* @throws - Will throw if the data is not of the expected length for a skylink.
*/
function parseDataLink(data: Uint8Array, legacy: boolean): { rawDataLink: string; dataLink: string } {
let rawDataLink = "";
if (legacy && data.length === BASE64_ENCODED_SKYLINK_SIZE) {
// Legacy data, convert to string for backwards compatibility.
rawDataLink = uint8ArrayToStringUtf8(data);
} else if (data.length === RAW_SKYLINK_SIZE) {
// Convert the bytes to a base64 skylink.
rawDataLink = encodeSkylinkBase64(data);
} else {
throwValidationError("entry.data", data, "returned entry data", `length ${RAW_SKYLINK_SIZE} bytes`);
}
return { rawDataLink, dataLink: formatSkylink(rawDataLink) };
}
/**
* Returns whether the given registry entry indicates a past deletion.
*
* @param entry - The registry entry.
* @returns - Whether the registry entry data indicated a past deletion.
*/
function wasRegistryEntryDeleted(entry: RegistryEntry): boolean {
return areEqualUint8Arrays(entry.data, EMPTY_SKYLINK);
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreLogger } from '@singletons/logger';
import { CoreSites } from '@services/sites';
import { CoreApp } from '@services/app';
import { CoreUser, CoreUserBasicData } from '@features/user/services/user';
import {
AddonMessagesOffline,
AddonMessagesOfflineAnyMessagesFormatted,
AddonMessagesOfflineConversationMessagesDBRecordFormatted,
AddonMessagesOfflineMessagesDBRecordFormatted,
} from './messages-offline';
import { CoreUtils } from '@services/utils/utils';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreEvents } from '@singletons/events';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreWSExternalWarning } from '@services/ws';
import { makeSingleton } from '@singletons';
import { CoreError } from '@classes/errors/error';
import { AddonMessagesSyncEvents, AddonMessagesSyncProvider } from './messages-sync';
import { CoreWSError } from '@classes/errors/wserror';
import { AddonNotificationsPreferencesNotificationProcessorState } from '@addons/notifications/services/notifications';
const ROOT_CACHE_KEY = 'mmaMessages:';
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonMessagesProvider.NEW_MESSAGE_EVENT]: AddonMessagesNewMessagedEventData;
[AddonMessagesProvider.READ_CHANGED_EVENT]: AddonMessagesReadChangedEventData;
[AddonMessagesProvider.OPEN_CONVERSATION_EVENT]: AddonMessagesOpenConversationEventData;
[AddonMessagesProvider.UPDATE_CONVERSATION_LIST_EVENT]: AddonMessagesUpdateConversationListEventData;
[AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT]: AddonMessagesMemberInfoChangedEventData;
[AddonMessagesProvider.UNREAD_CONVERSATION_COUNTS_EVENT]: AddonMessagesUnreadConversationCountsEventData;
[AddonMessagesProvider.CONTACT_REQUESTS_COUNT_EVENT]: AddonMessagesContactRequestCountEventData;
[AddonMessagesSyncProvider.AUTO_SYNCED]: AddonMessagesSyncEvents;
}
}
/**
* Service to handle messages.
*/
@Injectable({ providedIn: 'root' })
export class AddonMessagesProvider {
static readonly NEW_MESSAGE_EVENT = 'addon_messages_new_message_event';
static readonly READ_CHANGED_EVENT = 'addon_messages_read_changed_event';
static readonly OPEN_CONVERSATION_EVENT = 'addon_messages_open_conversation_event'; // Notify a conversation should be opened.
static readonly UPDATE_CONVERSATION_LIST_EVENT = 'addon_messages_update_conversation_list_event';
static readonly MEMBER_INFO_CHANGED_EVENT = 'addon_messages_member_changed_event';
static readonly UNREAD_CONVERSATION_COUNTS_EVENT = 'addon_messages_unread_conversation_counts_event';
static readonly CONTACT_REQUESTS_COUNT_EVENT = 'addon_messages_contact_requests_count_event';
static readonly POLL_INTERVAL = 10000;
static readonly PUSH_SIMULATION_COMPONENT = 'AddonMessagesPushSimulation';
static readonly MESSAGE_PRIVACY_COURSEMEMBER = 0; // Privacy setting for being messaged by anyone within courses user is member.
static readonly MESSAGE_PRIVACY_ONLYCONTACTS = 1; // Privacy setting for being messaged only by contacts.
static readonly MESSAGE_PRIVACY_SITE = 2; // Privacy setting for being messaged by anyone on the site.
static readonly MESSAGE_CONVERSATION_TYPE_INDIVIDUAL = 1; // An individual conversation.
static readonly MESSAGE_CONVERSATION_TYPE_GROUP = 2; // A group conversation.
static readonly MESSAGE_CONVERSATION_TYPE_SELF = 3; // A self conversation.
static readonly LIMIT_CONTACTS = 50;
static readonly LIMIT_MESSAGES = 50;
static readonly LIMIT_INITIAL_USER_SEARCH = 3;
static readonly LIMIT_SEARCH = 50;
static readonly NOTIFICATION_PREFERENCES_KEY = 'message_provider_moodle_instantmessage';
protected logger: CoreLogger;
constructor() {
this.logger = CoreLogger.getInstance('AddonMessages');
}
/**
* Add a contact.
*
* @param userId User ID of the person to add.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
* @deprecatedonmoodle since Moodle 3.6
*/
protected async addContact(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params = {
userids: [userId],
};
await site.write('core_message_create_contacts', params);
await this.invalidateAllContactsCache(site.getId());
}
/**
* Block a user.
*
* @param userId User ID of the person to block.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved when done.
*/
async blockContact(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
try {
if (site.wsAvailable('core_message_block_user')) {
// Since Moodle 3.6
const params: AddonMessagesBlockUserWSParams = {
userid: site.getUserId(),
blockeduserid: userId,
};
await site.write('core_message_block_user', params);
} else {
const params: { userids: number[] } = {
userids: [userId],
};
await site.write('core_message_block_contacts', params);
}
await this.invalidateAllMemberInfo(userId, site);
} finally {
const data: AddonMessagesMemberInfoChangedEventData = { userId, userBlocked: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
}
}
/**
* Confirm a contact request from another user.
*
* @param userId ID of the user who made the contact request.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
* @since 3.6
*/
async confirmContactRequest(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesConfirmContactRequestWSParams = {
userid: userId,
requesteduserid: site.getUserId(),
};
await site.write('core_message_confirm_contact_request', params);
await CoreUtils.allPromises([
this.invalidateAllMemberInfo(userId, site),
this.invalidateContactsCache(site.id),
this.invalidateUserContacts(site.id),
this.refreshContactRequestsCount(site.id),
]).finally(() => {
const data: AddonMessagesMemberInfoChangedEventData = { userId, contactRequestConfirmed: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
});
}
/**
* Send a contact request to another user.
*
* @param userId ID of the receiver of the contact request.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
* @since 3.6
*/
async createContactRequest(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
// Use legacy function if not available.
if (!site.wsAvailable('core_message_create_contact_request')) {
await this.addContact(userId, site.getId());
} else {
const params: AddonMessagesCreateContactRequestWSParams = {
userid: site.getUserId(),
requesteduserid: userId,
};
const result = await site.write<AddonMessagesCreateContactRequestWSResponse>(
'core_message_create_contact_request',
params,
);
if (result.warnings?.length) {
throw new CoreWSError(result.warnings[0]);
}
}
await this.invalidateAllMemberInfo(userId, site).finally(() => {
const data: AddonMessagesMemberInfoChangedEventData = { userId, contactRequestCreated: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
});
}
/**
* Decline a contact request from another user.
*
* @param userId ID of the user who made the contact request.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
* @since 3.6
*/
async declineContactRequest(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesDeclineContactRequestWSParams = {
userid: userId,
requesteduserid: site.getUserId(),
};
await site.write('core_message_decline_contact_request', params);
await CoreUtils.allPromises([
this.invalidateAllMemberInfo(userId, site),
this.refreshContactRequestsCount(site.id),
]).finally(() => {
const data: AddonMessagesMemberInfoChangedEventData = { userId, contactRequestDeclined: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
});
}
/**
* Delete a conversation.
*
* @param conversationId Conversation to delete.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Promise resolved when the conversation has been deleted.
*/
async deleteConversation(conversationId: number, siteId?: string, userId?: number): Promise<void> {
await this.deleteConversations([conversationId], siteId, userId);
}
/**
* Delete several conversations.
*
* @param conversationIds Conversations to delete.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Promise resolved when the conversations have been deleted.
*/
async deleteConversations(conversationIds: number[], siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const params: AddonMessagesDeleteConversationsByIdWSParams = {
userid: userId,
conversationids: conversationIds,
};
await site.write('core_message_delete_conversations_by_id', params);
await Promise.all(conversationIds.map(async (conversationId) => {
try {
return AddonMessagesOffline.deleteConversationMessages(conversationId, site.getId());
} catch {
// Ignore errors.
}
}));
}
/**
* Delete a message (online or offline).
*
* @param message Message to delete.
* @param deleteForAll Whether the message should be deleted for all users.
* @return Promise resolved when the message has been deleted.
*/
deleteMessage(message: AddonMessagesConversationMessageFormatted, deleteForAll?: boolean): Promise<void> {
if ('id' in message) {
// Message has ID, it means it has been sent to the server.
if (deleteForAll) {
return this.deleteMessageForAllOnline(message.id);
} else {
return this.deleteMessageOnline(message.id, !!('read' in message && message.read));
}
}
// It's an offline message.
if (!('conversationid' in message)) {
return AddonMessagesOffline.deleteMessage(message.touserid, message.smallmessage, message.timecreated);
}
return AddonMessagesOffline.deleteConversationMessage(message.conversationid, message.text, message.timecreated);
}
/**
* Delete a message from the server.
*
* @param id Message ID.
* @param read True if message is read, false otherwise.
* @param userId User we want to delete the message for. If not defined, use current user.
* @return Promise resolved when the message has been deleted.
*/
async deleteMessageOnline(id: number, read: boolean, userId?: number): Promise<void> {
userId = userId || CoreSites.getCurrentSiteUserId();
const params: AddonMessagesDeleteMessageWSParams = {
messageid: id,
userid: userId,
};
if (read !== undefined) {
params.read = read;
}
await CoreSites.getCurrentSite()?.write('core_message_delete_message', params);
await this.invalidateDiscussionCache(userId);
}
/**
* Delete a message for all users.
*
* @param id Message ID.
* @param userId User we want to delete the message for. If not defined, use current user.
* @return Promise resolved when the message has been deleted.
*/
async deleteMessageForAllOnline(id: number, userId?: number): Promise<void> {
userId = userId || CoreSites.getCurrentSiteUserId();
const params: AddonMessagesDeleteMessageForAllUsersWSParams = {
messageid: id,
userid: userId,
};
await CoreSites.getCurrentSite()?.write('core_message_delete_message_for_all_users', params);
await this.invalidateDiscussionCache(userId);
}
/**
* Format a conversation.
*
* @param conversation Conversation to format.
* @param userId User ID viewing the conversation.
* @return Formatted conversation.
*/
protected formatConversation(
conversation: AddonMessagesConversationFormatted,
userId: number,
): AddonMessagesConversationFormatted {
const numMessages = conversation.messages.length;
const lastMessage = numMessages ? conversation.messages[numMessages - 1] : null;
conversation.lastmessage = lastMessage ? lastMessage.text : undefined;
conversation.lastmessagedate = lastMessage ? lastMessage.timecreated : undefined;
conversation.sentfromcurrentuser = lastMessage ? lastMessage.useridfrom == userId : undefined;
if (conversation.type != AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_GROUP) {
const isIndividual = conversation.type == AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_INDIVIDUAL;
const otherUser = conversation.members.find((member) =>
(isIndividual && member.id != userId) || (!isIndividual && member.id == userId));
if (otherUser) {
conversation.name = conversation.name ? conversation.name : otherUser.fullname;
conversation.imageurl = conversation.imageurl ? conversation.imageurl : otherUser.profileimageurl;
conversation.otherUser = otherUser;
conversation.userid = otherUser.id;
conversation.showonlinestatus = otherUser.showonlinestatus;
conversation.isonline = otherUser.isonline;
conversation.isblocked = otherUser.isblocked;
conversation.otherUser = otherUser;
}
}
return conversation;
}
/**
* Get the cache key for blocked contacts.
*
* @param userId The user who's contacts we're looking for.
* @return Cache key.
*/
protected getCacheKeyForBlockedContacts(userId: number): string {
return ROOT_CACHE_KEY + 'blockedContacts:' + userId;
}
/**
* Get the cache key for contacts.
*
* @return Cache key.
*/
protected getCacheKeyForContacts(): string {
return ROOT_CACHE_KEY + 'contacts';
}
/**
* Get the cache key for comfirmed contacts.
*
* @return Cache key.
*/
protected getCacheKeyForUserContacts(): string {
return ROOT_CACHE_KEY + 'userContacts';
}
/**
* Get the cache key for contact requests.
*
* @return Cache key.
*/
protected getCacheKeyForContactRequests(): string {
return ROOT_CACHE_KEY + 'contactRequests';
}
/**
* Get the cache key for contact requests count.
*
* @return Cache key.
*/
protected getCacheKeyForContactRequestsCount(): string {
return ROOT_CACHE_KEY + 'contactRequestsCount';
}
/**
* Get the cache key for a discussion.
*
* @param userId The other person with whom the current user is having the discussion.
* @return Cache key.
*/
getCacheKeyForDiscussion(userId: number): string {
return ROOT_CACHE_KEY + 'discussion:' + userId;
}
/**
* Get the cache key for the message count.
*
* @param userId User ID.
* @return Cache key.
*/
protected getCacheKeyForMessageCount(userId: number): string {
return ROOT_CACHE_KEY + 'count:' + userId;
}
/**
* Get the cache key for unread conversation counts.
*
* @return Cache key.
*/
protected getCacheKeyForUnreadConversationCounts(): string {
return ROOT_CACHE_KEY + 'unreadConversationCounts';
}
/**
* Get the cache key for the list of discussions.
*
* @return Cache key.
*/
protected getCacheKeyForDiscussions(): string {
return ROOT_CACHE_KEY + 'discussions';
}
/**
* Get cache key for get conversations.
*
* @param userId User ID.
* @param conversationId Conversation ID.
* @return Cache key.
*/
protected getCacheKeyForConversation(userId: number, conversationId: number): string {
return ROOT_CACHE_KEY + 'conversation:' + userId + ':' + conversationId;
}
/**
* Get cache key for get conversations between users.
*
* @param userId User ID.
* @param otherUserId Other user ID.
* @return Cache key.
*/
protected getCacheKeyForConversationBetweenUsers(userId: number, otherUserId: number): string {
return ROOT_CACHE_KEY + 'conversationBetweenUsers:' + userId + ':' + otherUserId;
}
/**
* Get cache key for get conversation members.
*
* @param userId User ID.
* @param conversationId Conversation ID.
* @return Cache key.
*/
protected getCacheKeyForConversationMembers(userId: number, conversationId: number): string {
return ROOT_CACHE_KEY + 'conversationMembers:' + userId + ':' + conversationId;
}
/**
* Get cache key for get conversation messages.
*
* @param userId User ID.
* @param conversationId Conversation ID.
* @return Cache key.
*/
protected getCacheKeyForConversationMessages(userId: number, conversationId: number): string {
return ROOT_CACHE_KEY + 'conversationMessages:' + userId + ':' + conversationId;
}
/**
* Get cache key for get conversations.
*
* @param userId User ID.
* @param type Filter by type.
* @param favourites Filter favourites.
* @return Cache key.
*/
protected getCacheKeyForConversations(userId: number, type?: number, favourites?: boolean): string {
return this.getCommonCacheKeyForUserConversations(userId) + ':' + type + ':' + favourites;
}
/**
* Get cache key for conversation counts.
*
* @return Cache key.
*/
protected getCacheKeyForConversationCounts(): string {
return ROOT_CACHE_KEY + 'conversationCounts';
}
/**
* Get cache key for member info.
*
* @param userId User ID.
* @param otherUserId The other user ID.
* @return Cache key.
*/
protected getCacheKeyForMemberInfo(userId: number, otherUserId: number): string {
return ROOT_CACHE_KEY + 'memberInfo:' + userId + ':' + otherUserId;
}
/**
* Get cache key for get self conversation.
*
* @param userId User ID.
* @return Cache key.
*/
protected getCacheKeyForSelfConversation(userId: number): string {
return ROOT_CACHE_KEY + 'selfconversation:' + userId;
}
/**
* Get common cache key for get user conversations.
*
* @param userId User ID.
* @return Cache key.
*/
protected getCommonCacheKeyForUserConversations(userId: number): string {
return this.getRootCacheKeyForConversations() + userId;
}
/**
* Get root cache key for get conversations.
*
* @return Cache key.
*/
protected getRootCacheKeyForConversations(): string {
return ROOT_CACHE_KEY + 'conversations:';
}
/**
* Get all the contacts of the current user.
*
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the WS data.
* @deprecatedonmoodle since Moodle 3.6
*/
async getAllContacts(siteId?: string): Promise<AddonMessagesGetContactsWSResponse> {
siteId = siteId || CoreSites.getCurrentSiteId();
const contacts = await this.getContacts(siteId);
try {
const blocked = await this.getBlockedContacts(siteId);
contacts.blocked = blocked.users;
this.storeUsersFromAllContacts(contacts);
return contacts;
} catch {
// The WS for blocked contacts might fail, but we still want the contacts.
contacts.blocked = [];
this.storeUsersFromAllContacts(contacts);
return contacts;
}
}
/**
* Get all the users blocked by the current user.
*
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the WS data.
*/
async getBlockedContacts(siteId?: string): Promise<AddonMessagesGetBlockedUsersWSResponse> {
const site = await CoreSites.getSite(siteId);
const userId = site.getUserId();
const params: AddonMessagesGetBlockedUsersWSParams = {
userid: userId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForBlockedContacts(userId),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
};
return site.read('core_message_get_blocked_users', params, preSets);
}
/**
* Get the contacts of the current user.
*
* This excludes the blocked users.
*
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the WS data.
* @deprecatedonmoodle since Moodle 3.6
*/
async getContacts(siteId?: string): Promise<AddonMessagesGetContactsWSResponse> {
const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForContacts(),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
};
const contacts = await site.read<AddonMessagesGetContactsWSResponse>('core_message_get_contacts', undefined, preSets);
// Filter contacts with negative ID, they are notifications.
const validContacts: AddonMessagesGetContactsWSResponse = {
online: [],
offline: [],
strangers: [],
};
for (const typeName in contacts) {
if (!validContacts[typeName]) {
validContacts[typeName] = [];
}
contacts[typeName].forEach((contact: AddonMessagesGetContactsContact) => {
if (contact.id > 0) {
validContacts[typeName].push(contact);
}
});
}
return validContacts;
}
/**
* Get the list of user contacts.
*
* @param limitFrom Position of the first contact to fetch.
* @param limitNum Number of contacts to fetch. Default is AddonMessagesProvider.LIMIT_CONTACTS.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the list of user contacts.
* @since 3.6
*/
async getUserContacts(
limitFrom: number = 0,
limitNum: number = AddonMessagesProvider.LIMIT_CONTACTS,
siteId?: string,
): Promise<{contacts: AddonMessagesConversationMember[]; canLoadMore: boolean}> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesGetUserContactsWSParams = {
userid: site.getUserId(),
limitfrom: limitFrom,
limitnum: limitNum <= 0 ? 0 : limitNum + 1,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForUserContacts(),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
};
const contacts = await site.read<AddonMessagesGetUserContactsWSResponse>('core_message_get_user_contacts', params, preSets);
if (!contacts || !contacts.length) {
return { contacts: [], canLoadMore: false };
}
CoreUser.storeUsers(contacts, site.id);
if (limitNum <= 0) {
return { contacts, canLoadMore: false };
}
return {
contacts: contacts.slice(0, limitNum),
canLoadMore: contacts.length > limitNum,
};
}
/**
* Get the contact request sent to the current user.
*
* @param limitFrom Position of the first contact request to fetch.
* @param limitNum Number of contact requests to fetch. Default is AddonMessagesProvider.LIMIT_CONTACTS.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the list of contact requests.
* @since 3.6
*/
async getContactRequests(
limitFrom: number = 0,
limitNum: number = AddonMessagesProvider.LIMIT_CONTACTS,
siteId?: string,
): Promise<{requests: AddonMessagesConversationMember[]; canLoadMore: boolean}> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesGetContactRequestsWSParams = {
userid: site.getUserId(),
limitfrom: limitFrom,
limitnum: limitNum <= 0 ? 0 : limitNum + 1,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForContactRequests(),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
};
const requests = await site.read<AddonMessagesGetContactRequestsWSResponse>(
'core_message_get_contact_requests',
params,
preSets,
);
if (!requests || !requests.length) {
return { requests: [], canLoadMore: false };
}
CoreUser.storeUsers(requests, site.id);
if (limitNum <= 0) {
return { requests, canLoadMore: false };
}
return {
requests: requests.slice(0, limitNum),
canLoadMore: requests.length > limitNum,
};
}
/**
* Get the number of contact requests sent to the current user.
*
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with the number of contact requests.
* @since 3.6
*/
async getContactRequestsCount(siteId?: string): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesGetReceivedContactRequestsCountWSParams = {
userid: site.getUserId(),
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForContactRequestsCount(),
typeExpected: 'number',
};
const data: AddonMessagesContactRequestCountEventData = {
count: await site.read('core_message_get_received_contact_requests_count', params, preSets),
};
// Notify the new count so all badges are updated.
CoreEvents.trigger(AddonMessagesProvider.CONTACT_REQUESTS_COUNT_EVENT, data , site.id);
return data.count;
}
/**
* Get a conversation by the conversation ID.
*
* @param conversationId Conversation ID to fetch.
* @param includeContactRequests Include contact requests.
* @param includePrivacyInfo Include privacy info.
* @param messageOffset Offset for messages list.
* @param messageLimit Limit of messages. Defaults to 1 (last message).
* We recommend getConversationMessages to get them.
* @param memberOffset Offset for members list.
* @param memberLimit Limit of members. Defaults to 2 (to be able to know the other user in individual ones).
* We recommend getConversationMembers to get them.
* @param newestFirst Whether to order messages by newest first.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Promise resolved with the response.
* @since 3.6
*/
async getConversation(
conversationId: number,
includeContactRequests: boolean = false,
includePrivacyInfo: boolean = false,
messageOffset: number = 0,
messageLimit: number = 1,
memberOffset: number = 0,
memberLimit: number = 2,
newestFirst: boolean = true,
siteId?: string,
userId?: number,
): Promise<AddonMessagesConversationFormatted> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversation(userId, conversationId),
};
const params: AddonMessagesGetConversationWSParams = {
userid: userId,
conversationid: conversationId,
includecontactrequests: includeContactRequests,
includeprivacyinfo: includePrivacyInfo,
messageoffset: messageOffset,
messagelimit: messageLimit,
memberoffset: memberOffset,
memberlimit: memberLimit,
newestmessagesfirst: newestFirst,
};
const conversation = await site.read<AddonMessagesGetConversationWSResponse>(
'core_message_get_conversation',
params,
preSets,
);
return this.formatConversation(conversation, userId);
}
/**
* Get a conversation between two users.
*
* @param otherUserId The other user ID.
* @param includeContactRequests Include contact requests.
* @param includePrivacyInfo Include privacy info.
* @param messageOffset Offset for messages list.
* @param messageLimit Limit of messages. Defaults to 1 (last message).
* We recommend getConversationMessages to get them.
* @param memberOffset Offset for members list.
* @param memberLimit Limit of members. Defaults to 2 (to be able to know the other user in individual ones).
* We recommend getConversationMembers to get them.
* @param newestFirst Whether to order messages by newest first.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @param preferCache True if shouldn't call WS if data is cached, false otherwise.
* @return Promise resolved with the response.
* @since 3.6
*/
async getConversationBetweenUsers(
otherUserId: number,
includeContactRequests?: boolean,
includePrivacyInfo?: boolean,
messageOffset: number = 0,
messageLimit: number = 1,
memberOffset: number = 0,
memberLimit: number = 2,
newestFirst: boolean = true,
siteId?: string,
userId?: number,
preferCache?: boolean,
): Promise<AddonMessagesConversationFormatted> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversationBetweenUsers(userId, otherUserId),
omitExpires: !!preferCache,
};
const params: AddonMessagesGetConversationBetweenUsersWSParams = {
userid: userId,
otheruserid: otherUserId,
includecontactrequests: !!includeContactRequests,
includeprivacyinfo: !!includePrivacyInfo,
messageoffset: messageOffset,
messagelimit: messageLimit,
memberoffset: memberOffset,
memberlimit: memberLimit,
newestmessagesfirst: !!newestFirst,
};
const conversation: AddonMessagesConversation =
await site.read('core_message_get_conversation_between_users', params, preSets);
return this.formatConversation(conversation, userId);
}
/**
* Get a conversation members.
*
* @param conversationId Conversation ID to fetch.
* @param limitFrom Offset for members list.
* @param limitTo Limit of members.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in
* @since 3.6
*/
async getConversationMembers(
conversationId: number,
limitFrom: number = 0,
limitTo?: number,
includeContactRequests?: boolean,
siteId?: string,
userId?: number,
): Promise<{members: AddonMessagesConversationMember[]; canLoadMore: boolean}> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
limitTo = limitTo ?? AddonMessagesProvider.LIMIT_MESSAGES;
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversationMembers(userId, conversationId),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
};
const params: AddonMessagesGetConversationMembersWSParams = {
userid: userId,
conversationid: conversationId,
limitfrom: limitFrom,
limitnum: limitTo < 1 ? limitTo : limitTo + 1,
includecontactrequests: !!includeContactRequests,
includeprivacyinfo: true,
};
const members: AddonMessagesConversationMember[] =
await site.read('core_message_get_conversation_members', params, preSets);
if (limitTo < 1) {
return {
canLoadMore: false,
members: members,
};
}
return {
canLoadMore: members.length > limitTo,
members: members.slice(0, limitTo),
};
}
/**
* Get a conversation by the conversation ID.
*
* @param conversationId Conversation ID to fetch.
* @param options Options.
* @return Promise resolved with the response.
* @since 3.6
*/
async getConversationMessages(
conversationId: number,
options: AddonMessagesGetConversationMessagesOptions = {},
): Promise<AddonMessagesGetConversationMessagesResult> {
const site = await CoreSites.getSite(options.siteId);
options.userId = options.userId || site.getUserId();
options.limitFrom = options.limitFrom || 0;
options.limitTo = options.limitTo ?? AddonMessagesProvider.LIMIT_MESSAGES;
options.timeFrom = options.timeFrom || 0;
options.newestFirst = options.newestFirst ?? true;
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversationMessages(options.userId, conversationId),
};
const params: AddonMessagesGetConversationMessagesWSParams = {
currentuserid: options.userId,
convid: conversationId,
limitfrom: options.limitFrom,
limitnum: options.limitTo < 1 ? options.limitTo : options.limitTo + 1, // If there's a limit, get 1 more than requested.
newest: !!options.newestFirst,
timefrom: options.timeFrom,
};
if (options.limitFrom > 0) {
// Do not use cache when retrieving older messages.
// This is to prevent storing too much data and to prevent inconsistencies between "pages" loaded.
preSets.getFromCache = false;
preSets.saveToCache = false;
preSets.emergencyCache = false;
} else if (options.forceCache) {
preSets.omitExpires = true;
} else if (options.ignoreCache) {
preSets.getFromCache = false;
preSets.emergencyCache = false;
}
const result: AddonMessagesGetConversationMessagesResult =
await site.read('core_message_get_conversation_messages', params, preSets);
if (options.limitTo < 1) {
result.canLoadMore = false;
} else {
result.canLoadMore = result.messages.length > options.limitTo;
result.messages = result.messages.slice(0, options.limitTo);
}
result.messages.forEach((message) => {
// Convert time to milliseconds.
message.timecreated = message.timecreated ? message.timecreated * 1000 : 0;
});
if (options.excludePending) {
// No need to get offline messages, return the ones we have.
return result;
}
// Get offline messages.
const offlineMessages =
await AddonMessagesOffline.getConversationMessages(conversationId, options.userId, site.getId());
result.messages = result.messages.concat(offlineMessages);
return result;
}
/**
* Get the discussions of a certain user. This function is used in Moodle sites higher than 3.6.
* If the site is older than 3.6, please use getDiscussions.
*
* @param type Filter by type.
* @param favourites Whether to restrict the results to contain NO favourite conversations (false), ONLY favourite
* conversation (true), or ignore any restriction altogether (undefined or null).
* @param limitFrom The offset to start at.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @param forceCache True if it should return cached data. Has priority over ignoreCache.
* @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @return Promise resolved with the conversations.
* @since 3.6
*/
async getConversations(
type?: number,
favourites?: boolean,
limitFrom: number = 0,
siteId?: string,
userId?: number,
forceCache?: boolean,
ignoreCache?: boolean,
): Promise<{conversations: AddonMessagesConversationFormatted[]; canLoadMore: boolean}> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversations(userId, type, favourites),
};
const params: AddonMessagesGetConversationsWSParams = {
userid: userId,
limitfrom: limitFrom,
limitnum: AddonMessagesProvider.LIMIT_MESSAGES + 1,
};
if (forceCache) {
preSets.omitExpires = true;
} else if (ignoreCache) {
preSets.getFromCache = false;
preSets.emergencyCache = false;
}
if (type !== undefined && type != null) {
params.type = type;
}
if (favourites !== undefined && favourites != null) {
params.favourites = !!favourites;
}
if (site.isVersionGreaterEqualThan('3.7') && type != AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_GROUP) {
// Add self conversation to the list.
params.mergeself = true;
}
let response: AddonMessagesGetConversationsResult;
try {
response = await site.read('core_message_get_conversations', params, preSets);
} catch (error) {
if (params.mergeself) {
// Try again without the new param. Maybe the user is offline and he has a previous request cached.
delete params.mergeself;
return site.read('core_message_get_conversations', params, preSets);
}
throw error;
}
// Format the conversations, adding some calculated fields.
const conversations = response.conversations
.slice(0, AddonMessagesProvider.LIMIT_MESSAGES)
.map((conversation) => this.formatConversation(conversation, userId!));
return {
conversations,
canLoadMore: response.conversations.length > AddonMessagesProvider.LIMIT_MESSAGES,
};
}
/**
* Get conversation counts by type.
*
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with favourite,
* individual, group and self conversation counts.
* @since 3.6
*/
async getConversationCounts(siteId?: string): Promise<{favourites: number; individual: number; group: number; self: number}> {
const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForConversationCounts(),
};
const result = await site.read<AddonMessagesGetConversationCountsWSResponse>(
'core_message_get_conversation_counts',
{ },
preSets,
);
const counts = {
favourites: result.favourites,
individual: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_INDIVIDUAL],
group: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_GROUP],
self: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_SELF] || 0,
};
return counts;
}
/**
* Return the current user's discussion with another user.
*
* @param userId The ID of the other user.
* @param excludePending True to exclude messages pending to be sent.
* @param lfReceivedUnread Number of unread received messages already fetched, so fetch will be done from this.
* @param lfReceivedRead Number of read received messages already fetched, so fetch will be done from this.
* @param lfSentUnread Number of unread sent messages already fetched, so fetch will be done from this.
* @param lfSentRead Number of read sent messages already fetched, so fetch will be done from this.
* @param notUsed Deprecated since 3.9.5
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with messages and a boolean telling if can load more messages.
*/
async getDiscussion(
userId: number,
excludePending: boolean,
lfReceivedUnread: number = 0,
lfReceivedRead: number = 0,
lfSentUnread: number = 0,
lfSentRead: number = 0,
notUsed: boolean = false, // eslint-disable-line @typescript-eslint/no-unused-vars
siteId?: string,
): Promise<AddonMessagesGetDiscussionMessages> {
const site = await CoreSites.getSite(siteId);
const result: AddonMessagesGetDiscussionMessages = {
messages: [],
canLoadMore: false,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForDiscussion(userId),
};
const params: AddonMessagesGetMessagesWSParams = {
useridto: site.getUserId(),
useridfrom: userId,
limitnum: AddonMessagesProvider.LIMIT_MESSAGES,
};
if (lfReceivedUnread > 0 || lfReceivedRead > 0 || lfSentUnread > 0 || lfSentRead > 0) {
// Do not use cache when retrieving older messages.
// This is to prevent storing too much data and to prevent inconsistencies between "pages" loaded.
preSets.getFromCache = false;
preSets.saveToCache = false;
preSets.emergencyCache = false;
}
// Get message received by current user.
const received = await this.getRecentMessages(params, preSets, lfReceivedUnread, lfReceivedRead, undefined, site.getId());
result.messages = received;
const hasReceived = received.length > 0;
// Get message sent by current user.
params.useridto = userId;
params.useridfrom = site.getUserId();
const sent = await this.getRecentMessages(params, preSets, lfSentUnread, lfSentRead, undefined, siteId);
result.messages = result.messages.concat(sent);
const hasSent = sent.length > 0;
if (result.messages.length > AddonMessagesProvider.LIMIT_MESSAGES) {
// Sort messages and get the more recent ones.
result.canLoadMore = true;
result.messages = this.sortMessages(result['messages']);
result.messages = result.messages.slice(-AddonMessagesProvider.LIMIT_MESSAGES);
} else {
result.canLoadMore = result.messages.length == AddonMessagesProvider.LIMIT_MESSAGES && (!hasReceived || !hasSent);
}
if (excludePending) {
// No need to get offline messages, return the ones we have.
return result;
}
// Get offline messages.
const offlineMessages = await AddonMessagesOffline.getMessages(userId, site.getId());
result.messages = result.messages.concat(offlineMessages);
return result;
}
/**
* Get the discussions of the current user. This function is used in Moodle sites older than 3.6.
* If the site is 3.6 or higher, please use getConversations.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with an object where the keys are the user ID of the other user.
*/
async getDiscussions(siteId?: string): Promise<{[userId: number]: AddonMessagesDiscussion}> {
const discussions: { [userId: number]: AddonMessagesDiscussion } = {};
/**
* Convenience function to treat a recent message, adding it to discussions list if needed.
*/
const treatRecentMessage = (
message: AddonMessagesGetMessagesMessage |
AddonMessagesOfflineConversationMessagesDBRecordFormatted |
AddonMessagesOfflineMessagesDBRecordFormatted,
userId: number,
userFullname: string,
): void => {
if (discussions[userId] === undefined) {
discussions[userId] = {
fullname: userFullname,
profileimageurl: '',
};
if ((!('timeread' in message) || !message.timeread) && !message.pending && message.useridfrom != currentUserId) {
discussions[userId].unread = true;
}
}
const messageId = ('id' in message) ? message.id : 0;
// Extract the most recent message. Pending messages are considered more recent than messages already sent.
const discMessage = discussions[userId].message;
if (discMessage === undefined || (!discMessage.pending && message.pending) ||
(discMessage.pending == message.pending && (discMessage.timecreated < message.timecreated ||
(discMessage.timecreated == message.timecreated && discMessage.id < messageId)))) {
discussions[userId].message = {
id: messageId,
user: userId,
message: message.text || '',
timecreated: message.timecreated,
pending: !!message.pending,
};
}
};
const site = await CoreSites.getSite(siteId);
const currentUserId = site.getUserId();
const params: AddonMessagesGetMessagesWSParams = {
useridto: currentUserId,
useridfrom: 0,
limitnum: AddonMessagesProvider.LIMIT_MESSAGES,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForDiscussions(),
};
const received = await this.getRecentMessages(params, preSets, undefined, undefined, undefined, site.getId());
// Extract the discussions by filtering same senders.
received.forEach((message) => {
treatRecentMessage(message, message.useridfrom, message.userfromfullname);
});
// Now get the last messages sent by the current user.
params.useridfrom = params.useridto;
params.useridto = 0;
const sent = await this.getRecentMessages(params, preSets);
// Extract the discussions by filtering same senders.
sent.forEach((message) => {
treatRecentMessage(message, message.useridto, message.usertofullname);
});
const offlineMessages = await AddonMessagesOffline.getAllMessages(site.getId());
offlineMessages.forEach((message) => {
treatRecentMessage(message, 'touserid' in message ? message.touserid : 0, '');
});
const discussionsWithUserImg = await this.getDiscussionsUserImg(discussions, site.getId());
this.storeUsersFromDiscussions(discussionsWithUserImg);
return discussionsWithUserImg;
}
/**
* Get user images for all the discussions that don't have one already.
*
* @param discussions List of discussions.
* @param siteId Site ID. If not defined, current site.
* @return Promise always resolved. Resolve param is the formatted discussions.
*/
protected async getDiscussionsUserImg(
discussions: { [userId: number]: AddonMessagesDiscussion },
siteId?: string,
): Promise<{[userId: number]: AddonMessagesDiscussion}> {
const promises: Promise<void>[] = [];
for (const userId in discussions) {
if (!discussions[userId].profileimageurl && discussions[userId].message) {
// We don't have the user image. Try to retrieve it.
promises.push(CoreUser.getProfile(discussions[userId].message!.user, 0, true, siteId).then((user) => {
discussions[userId].profileimageurl = user.profileimageurl;
return;
}).catch(() => {
// Error getting profile, resolve promise without adding any extra data.
}));
}
}
await Promise.all(promises);
return discussions;
}
/**
* Get conversation member info by user id, works even if no conversation betwen the users exists.
*
* @param otherUserId The other user ID.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Promise resolved with the member info.
* @since 3.6
*/
async getMemberInfo(otherUserId: number, siteId?: string, userId?: number): Promise<AddonMessagesConversationMember> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForMemberInfo(userId, otherUserId),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
};
const params: AddonMessagesGetMemberInfoWSParams = {
referenceuserid: userId,
userids: [otherUserId],
includecontactrequests: true,
includeprivacyinfo: true,
};
const members: AddonMessagesConversationMember[] = await site.read('core_message_get_member_info', params, preSets);
if (!members || members.length < 1) {
// Should never happen.
throw new CoreError('Error fetching member info.');
}
return members[0];
}
/**
* Get the cache key for the get message preferences call.
*
* @return Cache key.
*/
protected getMessagePreferencesCacheKey(): string {
return ROOT_CACHE_KEY + 'messagePreferences';
}
/**
* Get message preferences.
*
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the message preferences.
*/
async getMessagePreferences(siteId?: string): Promise<AddonMessagesMessagePreferences> {
this.logger.debug('Get message preferences');
const site = await CoreSites.getSite(siteId);
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getMessagePreferencesCacheKey(),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
};
const data = await site.read<AddonMessagesGetUserMessagePreferencesWSResponse>(
'core_message_get_user_message_preferences',
{},
preSets,
);
if (data.preferences) {
data.preferences.blocknoncontacts = data.blocknoncontacts;
return data.preferences;
}
throw new CoreError('Error getting message preferences');
}
/**
* Get messages according to the params.
*
* @param params Parameters to pass to the WS.
* @param preSets Set of presets for the WS.
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the data.
*/
protected async getMessages(
params: AddonMessagesGetMessagesWSParams,
preSets: CoreSiteWSPreSets,
siteId?: string,
): Promise<AddonMessagesGetMessagesResult> {
params.type = 'conversations';
params.newestfirst = true;
const site = await CoreSites.getSite(siteId);
const response: AddonMessagesGetMessagesResult = await site.read('core_message_get_messages', params, preSets);
response.messages.forEach((message) => {
message.read = !!params.read;
// Convert times to milliseconds.
message.timecreated = message.timecreated ? message.timecreated * 1000 : 0;
message.timeread = message.timeread ? message.timeread * 1000 : 0;
});
return response;
}
/**
* Get the most recent messages.
*
* @param params Parameters to pass to the WS.
* @param preSets Set of presets for the WS.
* @param limitFromUnread Number of read messages already fetched, so fetch will be done from this number.
* @param limitFromRead Number of unread messages already fetched, so fetch will be done from this number.
* @param notUsed // Deprecated 3.9.5
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the data.
*/
async getRecentMessages(
params: AddonMessagesGetMessagesWSParams,
preSets: CoreSiteWSPreSets,
limitFromUnread: number = 0,
limitFromRead: number = 0,
notUsed: boolean = false, // eslint-disable-line @typescript-eslint/no-unused-vars
siteId?: string,
): Promise<AddonMessagesGetMessagesMessage[]> {
limitFromUnread = limitFromUnread || 0;
limitFromRead = limitFromRead || 0;
params.read = false;
params.limitfrom = limitFromUnread;
const response = await this.getMessages(params, preSets, siteId);
let messages = response.messages;
if (!messages) {
throw new CoreError('Error fetching recent messages');
}
if (messages.length >= (params.limitnum || 0)) {
return messages;
}
// We need to fetch more messages.
params.limitnum = (params.limitnum || 0) - messages.length;
params.read = true;
params.limitfrom = limitFromRead;
try {
const response = await this.getMessages(params, preSets, siteId);
if (response.messages) {
messages = messages.concat(response.messages);
}
return messages;
} catch {
return messages;
}
}
/**
* Get a self conversation.
*
* @param messageOffset Offset for messages list.
* @param messageLimit Limit of messages. Defaults to 1 (last message).
* We recommend getConversationMessages to get them.
* @param newestFirst Whether to order messages by newest first.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID to get the self conversation for. If not defined, current user in the site.
* @return Promise resolved with the response.
* @since 3.7
*/
async getSelfConversation(
messageOffset: number = 0,
messageLimit: number = 1,
newestFirst: boolean = true,
siteId?: string,
userId?: number,
): Promise<AddonMessagesConversationFormatted> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForSelfConversation(userId),
};
const params: AddonMessagesGetSelfConversationWSParams = {
userid: userId,
messageoffset: messageOffset,
messagelimit: messageLimit,
newestmessagesfirst: !!newestFirst,
};
const conversation = await site.read<AddonMessagesConversation>('core_message_get_self_conversation', params, preSets);
return this.formatConversation(conversation, userId);
}
/**
* Get unread conversation counts by type.
*
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with the unread favourite, individual and group conversation counts.
*/
async getUnreadConversationCounts(
siteId?: string,
): Promise<{favourites: number; individual: number; group: number; self: number; orMore?: boolean}> {
const site = await CoreSites.getSite(siteId);
let counts: AddonMessagesUnreadConversationCountsEventData;
if (this.isGroupMessagingEnabled()) {
// @since 3.6
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForUnreadConversationCounts(),
};
const result: AddonMessagesGetConversationCountsWSResponse =
await site.read('core_message_get_unread_conversation_counts', {}, preSets);
counts = {
favourites: result.favourites,
individual: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_INDIVIDUAL],
group: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_GROUP],
self: result.types[AddonMessagesProvider.MESSAGE_CONVERSATION_TYPE_SELF] || 0,
};
} else {
const params: AddonMessageGetUnreadConversationsCountWSParams = {
useridto: site.getUserId(),
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getCacheKeyForMessageCount(site.getUserId()),
typeExpected: 'number',
};
const count = await site.read<number>('core_message_get_unread_conversations_count', params, preSets);
counts = { favourites: 0, individual: count, group: 0, self: 0 };
}
// Notify the new counts so all views are updated.
CoreEvents.trigger(AddonMessagesProvider.UNREAD_CONVERSATION_COUNTS_EVENT, counts, site.id);
return counts;
}
/**
* Get the latest unread received messages.
*
* @param toDisplay True if messages will be displayed to the user, either in view or in a notification.
* @param forceCache True if it should return cached data. Has priority over ignoreCache.
* @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @param siteId Site ID. If not defined, use current site.
* @return Promise resolved with the message unread count.
*/
async getUnreadReceivedMessages(
notUsed: boolean = true, // eslint-disable-line @typescript-eslint/no-unused-vars
forceCache: boolean = false,
ignoreCache: boolean = false,
siteId?: string,
): Promise<AddonMessagesGetMessagesResult> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesGetMessagesWSParams = {
read: false,
limitfrom: 0,
limitnum: AddonMessagesProvider.LIMIT_MESSAGES,
useridto: site.getUserId(),
useridfrom: 0,
};
const preSets: CoreSiteWSPreSets = {};
if (forceCache) {
preSets.omitExpires = true;
} else if (ignoreCache) {
preSets.getFromCache = false;
preSets.emergencyCache = false;
}
return await this.getMessages(params, preSets, siteId);
}
/**
* Invalidate all contacts cache.
*
* @param userId The user ID.
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateAllContactsCache(siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
await this.invalidateContactsCache(siteId);
await this.invalidateBlockedContactsCache(siteId);
}
/**
* Invalidate blocked contacts cache.
*
* @param userId The user ID.
* @param siteId Site ID. If not defined, current site.
*/
async invalidateBlockedContactsCache(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const userId = site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForBlockedContacts(userId));
}
/**
* Invalidate contacts cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateContactsCache(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getCacheKeyForContacts());
}
/**
* Invalidate user contacts cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateUserContacts(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getCacheKeyForUserContacts());
}
/**
* Invalidate contact requests cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateContactRequestsCache(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
return site.invalidateWsCacheForKey(this.getCacheKeyForContactRequests());
}
/**
* Invalidate contact requests count cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateContactRequestsCountCache(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getCacheKeyForContactRequestsCount());
}
/**
* Invalidate conversation.
*
* @param conversationId Conversation ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateConversation(conversationId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForConversation(userId, conversationId));
}
/**
* Invalidate conversation between users.
*
* @param otherUserId Other user ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateConversationBetweenUsers(otherUserId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForConversationBetweenUsers(userId, otherUserId));
}
/**
* Invalidate conversation members cache.
*
* @param conversationId Conversation ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateConversationMembers(conversationId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForConversationMembers(userId, conversationId));
}
/**
* Invalidate conversation messages cache.
*
* @param conversationId Conversation ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateConversationMessages(conversationId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForConversationMessages(userId, conversationId));
}
/**
* Invalidate conversations cache.
*
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateConversations(siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKeyStartingWith(this.getCommonCacheKeyForUserConversations(userId));
}
/**
* Invalidate conversation counts cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateConversationCounts(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getCacheKeyForConversationCounts());
}
/**
* Invalidate discussion cache.
*
* @param userId The user ID with whom the current user is having the discussion.
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateDiscussionCache(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getCacheKeyForDiscussion(userId));
}
/**
* Invalidate discussions cache.
*
* Note that {@link this.getDiscussions} uses the contacts, so we need to invalidate contacts too.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateDiscussionsCache(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const promises: Promise<void>[] = [];
promises.push(site.invalidateWsCacheForKey(this.getCacheKeyForDiscussions()));
promises.push(this.invalidateContactsCache(site.getId()));
await Promise.all(promises);
}
/**
* Invalidate member info cache.
*
* @param otherUserId The other user ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateMemberInfo(otherUserId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForMemberInfo(userId, otherUserId));
}
/**
* Invalidate get message preferences.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data is invalidated.
*/
async invalidateMessagePreferences(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getMessagePreferencesCacheKey());
}
/**
* Invalidate all cache entries with member info.
*
* @param userId Id of the user to invalidate.
* @param site Site object.
* @return Promise resolved when done.
*/
protected async invalidateAllMemberInfo(userId: number, site: CoreSite): Promise<void> {
await CoreUtils.allPromises([
this.invalidateMemberInfo(userId, site.id),
this.invalidateUserContacts(site.id),
this.invalidateBlockedContactsCache(site.id),
this.invalidateContactRequestsCache(site.id),
this.invalidateConversations(site.id),
this.getConversationBetweenUsers(
userId,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
site.id,
undefined,
true,
).then((conversation) => CoreUtils.allPromises([
this.invalidateConversation(conversation.id),
this.invalidateConversationMembers(conversation.id, site.id),
])).catch(() => {
// The conversation does not exist or we can't fetch it now, ignore it.
}),
]);
}
/**
* Invalidate a self conversation.
*
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async invalidateSelfConversation(siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getCacheKeyForSelfConversation(userId));
}
/**
* Invalidate unread conversation counts cache.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when done.
*/
async invalidateUnreadConversationCounts(siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
if (this.isGroupMessagingEnabled()) {
// @since 3.6
return site.invalidateWsCacheForKey(this.getCacheKeyForUnreadConversationCounts());
} else {
return site.invalidateWsCacheForKey(this.getCacheKeyForMessageCount(site.getUserId()));
}
}
/**
* Checks if the a user is blocked by the current user.
*
* @param userId The user ID to check against.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with boolean, rejected when we do not know.
*/
async isBlocked(userId: number, siteId?: string): Promise<boolean> {
if (this.isGroupMessagingEnabled()) {
const member = await this.getMemberInfo(userId, siteId);
return member.isblocked;
}
const blockedContacts = await this.getBlockedContacts(siteId);
if (!blockedContacts.users || blockedContacts.users.length < 1) {
return false;
}
return blockedContacts.users.some((user) => userId == user.id);
}
/**
* Checks if the a user is a contact of the current user.
*
* @param userId The user ID to check against.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with boolean, rejected when we do not know.
*/
async isContact(userId: number, siteId?: string): Promise<boolean> {
if (this.isGroupMessagingEnabled()) {
const member = await this.getMemberInfo(userId, siteId);
return member.iscontact;
}
const contacts = await this.getContacts(siteId);
return ['online', 'offline'].some((type) => {
if (contacts[type] && contacts[type].length > 0) {
return contacts[type].some((user: AddonMessagesGetContactsContact) => userId == user.id);
}
return false;
});
}
/**
* Returns whether or not group messaging is supported.
*
* @return If related WS is available on current site.
* @since 3.6
*/
isGroupMessagingEnabled(): boolean {
return CoreSites.wsAvailableInCurrentSite('core_message_get_conversations');
}
/**
* Returns whether or not group messaging is supported in a certain site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether related WS is available on a certain site.
* @since 3.6
*/
async isGroupMessagingEnabledInSite(siteId?: string): Promise<boolean> {
try {
const site = await CoreSites.getSite(siteId);
return site.wsAvailable('core_message_get_conversations');
} catch {
return false;
}
}
/**
* Returns whether or not messaging is enabled for a certain site.
*
* This could call a WS so do not abuse this method.
*
* @param siteId Site ID. If not defined, current site.
* @return Resolved when enabled, otherwise rejected.
*/
async isMessagingEnabledForSite(siteId?: string): Promise<void> {
const enabled = await this.isPluginEnabled(siteId);
if (!enabled) {
throw new CoreError('Messaging not enabled for the site');
}
}
/**
* Returns whether or not a site supports muting or unmuting a conversation.
*
* @param site The site to check, undefined for current site.
* @return If related WS is available on current site.
* @since 3.7
*/
isMuteConversationEnabled(site?: CoreSite): boolean {
site = site || CoreSites.getCurrentSite();
return !!site?.wsAvailable('core_message_mute_conversations');
}
/**
* Returns whether or not a site supports muting or unmuting a conversation.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether related WS is available on a certain site.
* @since 3.7
*/
async isMuteConversationEnabledInSite(siteId?: string): Promise<boolean> {
try {
const site = await CoreSites.getSite(siteId);
return this.isMuteConversationEnabled(site);
} catch {
return false;
}
}
/**
* Returns whether or not the plugin is enabled in a certain site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with true if enabled, rejected or resolved with false otherwise.
*/
async isPluginEnabled(siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
return site.canUseAdvancedFeature('messaging');
}
/**
* Returns whether or not self conversation is supported in a certain site.
*
* @param site Site. If not defined, current site.
* @return If related WS is available on the site.
* @since 3.7
*/
isSelfConversationEnabled(site?: CoreSite): boolean {
site = site || CoreSites.getCurrentSite();
return !!site?.wsAvailable('core_message_get_self_conversation');
}
/**
* Returns whether or not self conversation is supported in a certain site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean: whether related WS is available on a certain site.
* @since 3.7
*/
async isSelfConversationEnabledInSite(siteId?: string): Promise<boolean> {
try {
const site = await CoreSites.getSite(siteId);
return this.isSelfConversationEnabled(site);
} catch {
return false;
}
}
/**
* Mark message as read.
*
* @param messageId ID of message to mark as read
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with boolean marking success or not.
*/
async markMessageRead(messageId: number, siteId?: string): Promise<AddonMessagesMarkMessageReadResult> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesMarkMessageReadWSParams = {
messageid: messageId,
timeread: CoreTimeUtils.timestamp(),
};
return site.write('core_message_mark_message_read', params);
}
/**
* Mark all messages of a conversation as read.
*
* @param conversationId Conversation ID.
* @return Promise resolved if success.
* @since 3.6
*/
async markAllConversationMessagesRead(conversationId: number): Promise<void> {
const params: AddonMessagesMarkAllConversationMessagesAsReadWSParams = {
userid: CoreSites.getCurrentSiteUserId(),
conversationid: conversationId,
};
const preSets: CoreSiteWSPreSets = {
responseExpected: false,
};
await CoreSites.getCurrentSite()?.write('core_message_mark_all_conversation_messages_as_read', params, preSets);
}
/**
* Mark all messages of a discussion as read.
*
* @param userIdFrom User Id for the sender.
* @return Promise resolved with boolean marking success or not.
* @deprecatedonmoodle since Moodle 3.6
*/
async markAllMessagesRead(userIdFrom?: number): Promise<boolean> {
const params: AddonMessagesMarkAllMessagesAsReadWSParams = {
useridto: CoreSites.getCurrentSiteUserId(),
useridfrom: userIdFrom,
};
const preSets: CoreSiteWSPreSets = {
typeExpected: 'boolean',
};
const site = CoreSites.getCurrentSite();
if (!site) {
return false;
}
return site.write('core_message_mark_all_messages_as_read', params, preSets);
}
/**
* Mute or unmute a conversation.
*
* @param conversationId Conversation ID.
* @param set Whether to mute or unmute.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async muteConversation(conversationId: number, set: boolean, siteId?: string, userId?: number): Promise<void> {
await this.muteConversations([conversationId], set, siteId, userId);
}
/**
* Mute or unmute some conversations.
*
* @param conversations Conversation IDs.
* @param set Whether to mute or unmute.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async muteConversations(conversations: number[], set: boolean, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const params: AddonMessagesMuteConversationsWSParams = {
userid: userId,
conversationids: conversations,
};
const wsName = set ? 'core_message_mute_conversations' : 'core_message_unmute_conversations';
await site.write(wsName, params);
// Invalidate the conversations data.
const promises = conversations.map((conversationId) => this.invalidateConversation(conversationId, site.getId(), userId));
try {
await Promise.all(promises);
} catch {
// Ignore errors.
}
}
/**
* Refresh the number of contact requests sent to the current user.
*
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with the number of contact requests.
* @since 3.6
*/
async refreshContactRequestsCount(siteId?: string): Promise<number> {
siteId = siteId || CoreSites.getCurrentSiteId();
await this.invalidateContactRequestsCountCache(siteId);
return this.getContactRequestsCount(siteId);
}
/**
* Refresh unread conversation counts and trigger event.
*
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with the unread favourite, individual and group conversation counts.
*/
async refreshUnreadConversationCounts(
siteId?: string,
): Promise<{favourites: number; individual: number; group: number; orMore?: boolean}> {
siteId = siteId || CoreSites.getCurrentSiteId();
await this.invalidateUnreadConversationCounts(siteId);
return this.getUnreadConversationCounts(siteId);
}
/**
* Remove a contact.
*
* @param userId User ID of the person to remove.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
*/
async removeContact(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesDeleteContactsWSParams = {
userids: [userId],
};
const preSets: CoreSiteWSPreSets = {
responseExpected: false,
};
await site.write('core_message_delete_contacts', params, preSets);
return CoreUtils.allPromises([
this.invalidateUserContacts(site.id),
this.invalidateAllMemberInfo(userId, site),
this.invalidateContactsCache(site.id),
]).then(() => {
const data: AddonMessagesMemberInfoChangedEventData = { userId, contactRemoved: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
return;
});
}
/**
* Search for contacts.
*
* By default this only returns the first 100 contacts, but note that the WS can return thousands
* of results which would take a while to process. The limit here is just a convenience to
* prevent viewed to crash because too many DOM elements are created.
*
* @param query The query string.
* @param limit The number of results to return, 0 for none.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the contacts.
*/
async searchContacts(query: string, limit: number = 100, siteId?: string): Promise<AddonMessagesSearchContactsContact[]> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesSearchContactsWSParams = {
searchtext: query,
onlymycourses: false,
};
const preSets: CoreSiteWSPreSets = {
getFromCache: false,
};
let contacts: AddonMessagesSearchContactsContact[] = await site.read('core_message_search_contacts', params, preSets);
if (limit && contacts.length > limit) {
contacts = contacts.splice(0, limit);
}
CoreUser.storeUsers(contacts);
return contacts;
}
/**
* Search for all the messges with a specific text.
*
* @param query The query string.
* @param userId The user ID. If not defined, current user.
* @param limitFrom Position of the first result to get. Defaults to 0.
* @param limitNum Number of results to get. Defaults to AddonMessagesProvider.LIMIT_SEARCH.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the results.
*/
async searchMessages(
query: string,
userId?: number,
limitFrom: number = 0,
limitNum: number = AddonMessagesProvider.LIMIT_SEARCH,
siteId?: string,
): Promise<{messages: AddonMessagesMessageAreaContact[]; canLoadMore: boolean}> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesDataForMessageareaSearchMessagesWSParams = {
userid: userId || site.getUserId(),
search: query,
limitfrom: limitFrom,
limitnum: limitNum <= 0 ? 0 : limitNum + 1,
};
const preSets: CoreSiteWSPreSets = {
getFromCache: false,
};
const result: AddonMessagesDataForMessageareaSearchMessagesWSResponse =
await site.read('core_message_data_for_messagearea_search_messages', params, preSets);
if (!result.contacts || !result.contacts.length) {
return { messages: [], canLoadMore: false };
}
const users: CoreUserBasicData[] = result.contacts.map((contact) => ({
id: contact.userid,
fullname: contact.fullname,
profileimageurl: contact.profileimageurl,
}));
CoreUser.storeUsers(users, site.id);
if (limitNum <= 0) {
return { messages: result.contacts, canLoadMore: false };
}
return {
messages: result.contacts.slice(0, limitNum),
canLoadMore: result.contacts.length > limitNum,
};
}
/**
* Search for users.
*
* @param query Text to search for.
* @param limitFrom Position of the first found user to fetch.
* @param limitNum Number of found users to fetch. Defaults to AddonMessagesProvider.LIMIT_SEARCH.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved with two lists of found users: contacts and non-contacts.
* @since 3.6
*/
async searchUsers(
query: string,
limitFrom: number = 0,
limitNum: number = AddonMessagesProvider.LIMIT_SEARCH,
siteId?: string,
): Promise<{
contacts: AddonMessagesConversationMember[];
nonContacts: AddonMessagesConversationMember[];
canLoadMoreContacts: boolean;
canLoadMoreNonContacts: boolean;
}> {
const site = await CoreSites.getSite(siteId);
const params: AddonMessagesMessageSearchUsersWSParams = {
userid: site.getUserId(),
search: query,
limitfrom: limitFrom,
limitnum: limitNum <= 0 ? 0 : limitNum + 1,
};
const preSets: CoreSiteWSPreSets = {
getFromCache: false,
};
const result: AddonMessagesSearchUsersWSResponse = await site.read('core_message_message_search_users', params, preSets);
const contacts = result.contacts || [];
const nonContacts = result.noncontacts || [];
CoreUser.storeUsers(contacts, site.id);
CoreUser.storeUsers(nonContacts, site.id);
if (limitNum <= 0) {
return { contacts, nonContacts, canLoadMoreContacts: false, canLoadMoreNonContacts: false };
}
return {
contacts: contacts.slice(0, limitNum),
nonContacts: nonContacts.slice(0, limitNum),
canLoadMoreContacts: contacts.length > limitNum,
canLoadMoreNonContacts: nonContacts.length > limitNum,
};
}
/**
* Send a message to someone.
*
* @param userIdTo User ID to send the message to.
* @param message The message to send
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with:
* - sent (Boolean) True if message was sent to server, false if stored in device.
* - message (Object) If sent=false, contains the stored message.
*/
async sendMessage(
toUserId: number,
message: string,
siteId?: string,
): Promise<AddonMessagesSendMessageResults> {
// Convenience function to store a message to be synchronized later.
const storeOffline = async (): Promise<AddonMessagesSendMessageResults> => {
const entry = await AddonMessagesOffline.saveMessage(toUserId, message, siteId);
return {
sent: false,
message: {
msgid: -1,
text: entry.smallmessage,
timecreated: entry.timecreated,
conversationid: 0,
useridfrom: entry.useridfrom,
candeletemessagesforallusers: true,
},
};
};
siteId = siteId || CoreSites.getCurrentSiteId();
if (!CoreApp.isOnline()) {
// App is offline, store the message.
return storeOffline();
}
// Check if this conversation already has offline messages.
// If so, store this message since they need to be sent in order.
let hasStoredMessages = false;
try {
hasStoredMessages = await AddonMessagesOffline.hasMessages(toUserId, siteId);
} catch {
// Error, it's safer to assume it has messages.
hasStoredMessages = true;
}
if (hasStoredMessages) {
return storeOffline();
}
try {
// Online and no messages stored. Send it to server.
const result = await this.sendMessageOnline(toUserId, message);
return {
sent: true,
message: result,
};
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// It's a WebService error, the user cannot send the message so don't store it.
throw error;
}
// Error sending message, store it to retry later.
return storeOffline();
}
}
/**
* Send a message to someone. It will fail if offline or cannot connect.
*
* @param toUserId User ID to send the message to.
* @param message The message to send
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if success, rejected if failure.
*/
async sendMessageOnline(toUserId: number, message: string, siteId?: string): Promise<AddonMessagesSendInstantMessagesMessage> {
siteId = siteId || CoreSites.getCurrentSiteId();
const messages = [
{
touserid: toUserId,
text: message,
textformat: 1,
},
];
const response = await this.sendMessagesOnline(messages, siteId);
if (response && response[0] && response[0].msgid === -1) {
// There was an error, and it should be translated already.
throw new CoreError(response[0].errormessage);
}
try {
await this.invalidateDiscussionCache(toUserId, siteId);
} catch {
// Ignore errors.
}
return response[0];
}
/**
* Send some messages. It will fail if offline or cannot connect.
* IMPORTANT: Sending several messages at once for the same discussions can cause problems with display order,
* since messages with same timecreated aren't ordered by ID.
*
* @param messages Messages to send. Each message must contain touserid, text and textformat.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if success, rejected if failure. Promise resolved doesn't mean that messages
* have been sent, the resolve param can contain errors for messages not sent.
*/
async sendMessagesOnline(
messages: AddonMessagesMessageData[],
siteId?: string,
): Promise<AddonMessagesSendInstantMessagesMessage[]> {
const site = await CoreSites.getSite(siteId);
const data: AddonMessagesSendInstantMessagesWSParams = {
messages,
};
return await site.write('core_message_send_instant_messages', data);
}
/**
* Send a message to a conversation.
*
* @param conversation Conversation.
* @param message The message to send.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with:
* - sent (boolean) True if message was sent to server, false if stored in device.
* - message (any) If sent=false, contains the stored message.
* @since 3.6
*/
async sendMessageToConversation(
conversation: AddonMessagesConversation,
message: string,
siteId?: string,
): Promise<AddonMessagesSendMessageResults> {
const site = await CoreSites.getSite(siteId);
siteId = site.getId();
// Convenience function to store a message to be synchronized later.
const storeOffline = async(): Promise<AddonMessagesSendMessageResults> => {
const entry = await AddonMessagesOffline.saveConversationMessage(conversation, message, siteId);
return {
sent: false,
message: {
id: -1,
useridfrom: site.getUserId(),
text: entry.text,
timecreated: entry.timecreated,
},
};
};
if (!CoreApp.isOnline()) {
// App is offline, store the message.
return storeOffline();
}
// Check if this conversation already has offline messages.
// If so, store this message since they need to be sent in order.
let hasStoredMessages = false;
try {
hasStoredMessages = await AddonMessagesOffline.hasConversationMessages(conversation.id, siteId);
} catch {
// Error, it's safer to assume it has messages.
hasStoredMessages = true;
}
if (hasStoredMessages) {
return storeOffline();
}
try {
// Online and no messages stored. Send it to server.
const result = await this.sendMessageToConversationOnline(conversation.id, message, siteId);
return {
sent: true,
message: result,
};
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// It's a WebService error, the user cannot send the message so don't store it.
throw error;
}
// Error sending message, store it to retry later.
return storeOffline();
}
}
/**
* Send a message to a conversation. It will fail if offline or cannot connect.
*
* @param conversationId Conversation ID.
* @param message The message to send
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if success, rejected if failure.
* @since 3.6
*/
async sendMessageToConversationOnline(
conversationId: number,
message: string,
siteId?: string,
): Promise<AddonMessagesSendMessagesToConversationMessage> {
siteId = siteId || CoreSites.getCurrentSiteId();
const messages = [
{
text: message,
textformat: 1,
},
];
const response = await this.sendMessagesToConversationOnline(conversationId, messages, siteId);
try {
await this.invalidateConversationMessages(conversationId, siteId);
} catch {
// Ignore errors.
}
return response[0];
}
/**
* Send some messages to a conversation. It will fail if offline or cannot connect.
*
* @param conversationId Conversation ID.
* @param messages Messages to send. Each message must contain text and, optionally, textformat.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if success, rejected if failure.
* @since 3.6
*/
async sendMessagesToConversationOnline(
conversationId: number,
messages: CoreMessageSendMessagesToConversationMessageData[],
siteId?: string,
): Promise<AddonMessagesSendMessagesToConversationMessage[]> {
const site = await CoreSites.getSite(siteId);
const params: CoreMessageSendMessagesToConversationWSParams = {
conversationid: conversationId,
messages: messages.map((message) => ({
text: message.text,
textformat: message.textformat !== undefined ? message.textformat : 1,
})),
};
return await site.write('core_message_send_messages_to_conversation', params);
}
/**
* Set or unset a conversation as favourite.
*
* @param conversationId Conversation ID.
* @param set Whether to set or unset it as favourite.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
setFavouriteConversation(conversationId: number, set: boolean, siteId?: string, userId?: number): Promise<void> {
return this.setFavouriteConversations([conversationId], set, siteId, userId);
}
/**
* Set or unset some conversations as favourites.
*
* @param conversations Conversation IDs.
* @param set Whether to set or unset them as favourites.
* @param siteId Site ID. If not defined, use current site.
* @param userId User ID. If not defined, current user in the site.
* @return Resolved when done.
*/
async setFavouriteConversations(conversations: number[], set: boolean, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
const params: AddonMessagesSetFavouriteConversationsWSParams = {
userid: userId,
conversations: conversations,
};
const wsName = set ? 'core_message_set_favourite_conversations' : 'core_message_unset_favourite_conversations';
await site.write(wsName, params);
// Invalidate the conversations data.
const promises = conversations.map((conversationId) => this.invalidateConversation(conversationId, site.getId(), userId));
try {
await Promise.all(promises);
} catch {
// Ignore errors.
}
}
/**
* Helper method to sort conversations by last message time.
*
* @param conversations Array of conversations.
* @return Conversations sorted with most recent last.
*/
sortConversations(conversations: AddonMessagesConversationFormatted[]): AddonMessagesConversationFormatted[] {
return conversations.sort((a, b) => {
const timeA = Number(a.lastmessagedate);
const timeB = Number(b.lastmessagedate);
if (timeA == timeB && a.id) {
// Same time, sort by ID.
return a.id <= b.id ? 1 : -1;
}
return timeA <= timeB ? 1 : -1;
});
}
/**
* Helper method to sort messages by time.
*
* @param messages Array of messages containing the key 'timecreated'.
* @return Messages sorted with most recent last.
*/
sortMessages(messages: AddonMessagesConversationMessageFormatted[]): AddonMessagesConversationMessageFormatted[];
sortMessages(
messages: (AddonMessagesGetMessagesMessage | AddonMessagesOfflineMessagesDBRecordFormatted)[],
): (AddonMessagesGetMessagesMessage | AddonMessagesOfflineMessagesDBRecordFormatted)[];
sortMessages(messages: AddonMessagesOfflineAnyMessagesFormatted[]): AddonMessagesOfflineAnyMessagesFormatted[];
sortMessages(
messages: (AddonMessagesGetMessagesMessage | AddonMessagesOfflineMessagesDBRecordFormatted)[] |
AddonMessagesOfflineAnyMessagesFormatted[] |
AddonMessagesConversationMessageFormatted[],
): (AddonMessagesGetMessagesMessage | AddonMessagesOfflineMessagesDBRecordFormatted)[] |
AddonMessagesOfflineAnyMessagesFormatted[] |
AddonMessagesConversationMessageFormatted[] {
return messages.sort((a, b) => {
// Pending messages last.
if (a.pending && !b.pending) {
return 1;
} else if (!a.pending && b.pending) {
return -1;
}
const timecreatedA = a.timecreated;
const timecreatedB = b.timecreated;
if (timecreatedA == timecreatedB && 'id' in a) {
const bId = 'id' in b ? b.id : 0;
// Same time, sort by ID.
return a.id >= bId ? 1 : -1;
}
return timecreatedA >= timecreatedB ? 1 : -1;
});
}
/**
* Store user data from contacts in local DB.
*
* @param contactTypes List of contacts grouped in types.
*/
protected storeUsersFromAllContacts(contactTypes: AddonMessagesGetContactsWSResponse): void {
for (const x in contactTypes) {
CoreUser.storeUsers(contactTypes[x]);
}
}
/**
* Store user data from discussions in local DB.
*
* @param discussions List of discussions.
* @param siteId Site ID. If not defined, current site.
*/
protected storeUsersFromDiscussions(discussions: { [userId: number]: AddonMessagesDiscussion }, siteId?: string): void {
const users: CoreUserBasicData[] = [];
for (const userId in discussions) {
users.push({
id: parseInt(userId, 10),
fullname: discussions[userId].fullname,
profileimageurl: discussions[userId].profileimageurl,
});
}
CoreUser.storeUsers(users, siteId);
}
/**
* Unblock a user.
*
* @param userId User ID of the person to unblock.
* @param siteId Site ID. If not defined, use current site.
* @return Resolved when done.
*/
async unblockContact(userId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
try {
if (site.wsAvailable('core_message_unblock_user')) {
// Since Moodle 3.6
const params: AddonMessagesUnblockUserWSParams = {
userid: site.getUserId(),
unblockeduserid: userId,
};
await site.write('core_message_unblock_user', params);
} else {
const params: { userids: number[] } = {
userids: [userId],
};
const preSets: CoreSiteWSPreSets = {
responseExpected: false,
};
await site.write('core_message_unblock_contacts', params, preSets);
}
await this.invalidateAllMemberInfo(userId, site);
} finally {
const data: AddonMessagesMemberInfoChangedEventData = { userId, userUnblocked: true };
CoreEvents.trigger(AddonMessagesProvider.MEMBER_INFO_CHANGED_EVENT, data, site.id);
}
}
}
export const AddonMessages = makeSingleton(AddonMessagesProvider);
/**
* Options to pass to getConversationMessages.
*/
export type AddonMessagesGetConversationMessagesOptions = {
excludePending?: boolean; // True to exclude messages pending to be sent.
limitFrom?: number; // Offset for messages list. Defaults to 0.
limitTo?: number; // Limit of messages.
newestFirst?: boolean; // Whether to order messages by newest first.
timeFrom?: number; // The timestamp from which the messages were created (in seconds). Defaults to 0.
siteId?: string; // Site ID. If not defined, use current site.
userId?: number; // User ID. If not defined, current user in the site.
forceCache?: boolean; // True if it should return cached data. Has priority over ignoreCache.
ignoreCache?: boolean; // True if it should ignore cached data (it will always fail in offline or server down).
};
/**
* Data returned by core_message_get_self_conversation WS.
*/
export type AddonMessagesConversation = {
id: number; // The conversation id.
name?: string; // The conversation name, if set.
subname?: string; // A subtitle for the conversation name, if set.
imageurl?: string; // A link to the conversation picture, if set.
type: number; // The type of the conversation (1=individual,2=group,3=self).
membercount: number; // Total number of conversation members.
ismuted: boolean; // If the user muted this conversation.
isfavourite: boolean; // If the user marked this conversation as a favourite.
isread: boolean; // If the user has read all messages in the conversation.
unreadcount?: number; // The number of unread messages in this conversation.
members: AddonMessagesConversationMember[];
messages: AddonMessagesConversationMessage[];
candeletemessagesforallusers: boolean; // @since 3.7. If the user can delete messages in the conversation for all users.
};
/**
* Params of core_message_get_conversation WS.
*/
type AddonMessagesGetConversationWSParams = {
userid: number; // The id of the user who we are viewing conversations for.
conversationid: number; // The id of the conversation to fetch.
includecontactrequests: boolean; // Include contact requests in the members.
includeprivacyinfo: boolean; // Include privacy info in the members.
memberlimit?: number; // Limit for number of members.
memberoffset?: number; // Offset for member list.
messagelimit?: number; // Limit for number of messages.
messageoffset?: number; // Offset for messages list.
newestmessagesfirst?: boolean; // Order messages by newest first.
};
/**
* Data returned by core_message_get_conversation WS.
*/
type AddonMessagesGetConversationWSResponse = AddonMessagesConversation;
/**
* Params of core_message_get_self_conversation WS.
*/
type AddonMessagesGetSelfConversationWSParams = {
userid: number; // The id of the user who we are viewing self-conversations for.
messagelimit?: number; // Limit for number of messages.
messageoffset?: number; // Offset for messages list.
newestmessagesfirst?: boolean; // Order messages by newest first.
};
/**
* Conversation with some calculated data.
*/
export type AddonMessagesConversationFormatted = AddonMessagesConversation & {
lastmessage?: string; // Calculated in the app. Last message.
lastmessagedate?: number; // Calculated in the app. Date the last message was sent.
sentfromcurrentuser?: boolean; // Calculated in the app. Whether last message was sent by the current user.
name?: string; // Calculated in the app. If private conversation, name of the other user.
userid?: number; // Calculated in the app. URL. If private conversation, ID of the other user.
showonlinestatus?: boolean; // Calculated in the app. If private conversation, whether to show online status of the other user.
isonline?: boolean; // Calculated in the app. If private conversation, whether the other user is online.
isblocked?: boolean; // Calculated in the app. If private conversation, whether the other user is blocked.
otherUser?: AddonMessagesConversationMember; // Calculated in the app. Other user in the conversation.
};
/**
* Params of core_message_get_conversation_between_users WS.
*/
type AddonMessagesGetConversationBetweenUsersWSParams = {
userid: number; // The id of the user who we are viewing conversations for.
otheruserid: number; // The other user id.
includecontactrequests: boolean; // Include contact requests in the members.
includeprivacyinfo: boolean; // Include privacy info in the members.
memberlimit?: number; // Limit for number of members.
memberoffset?: number; // Offset for member list.
messagelimit?: number; // Limit for number of messages.
messageoffset?: number; // Offset for messages list.
newestmessagesfirst?: boolean; // Order messages by newest first.
};
/**
* Params of core_message_get_member_info WS.
*/
type AddonMessagesGetMemberInfoWSParams = {
referenceuserid: number; // Id of the user.
userids: number[];
includecontactrequests?: boolean; // Include contact requests in response.
includeprivacyinfo?: boolean; // Include privacy info in response.
};
/**
* Params of core_message_get_conversation_members WS.
*/
type AddonMessagesGetConversationMembersWSParams = {
userid: number; // The id of the user we are performing this action on behalf of.
conversationid: number; // The id of the conversation.
includecontactrequests?: boolean; // Do we want to include contact requests?.
includeprivacyinfo?: boolean; // Do we want to include privacy info?.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Conversation member returned by core_message_get_member_info and core_message_get_conversation_members WS.
*/
export type AddonMessagesConversationMember = {
id: number; // The user id.
fullname: string; // The user's name.
profileurl: string; // The link to the user's profile page.
profileimageurl: string; // User picture URL.
profileimageurlsmall: string; // Small user picture URL.
isonline: boolean; // The user's online status.
showonlinestatus: boolean; // Show the user's online status?.
isblocked: boolean; // If the user has been blocked.
iscontact: boolean; // Is the user a contact?.
isdeleted: boolean; // Is the user deleted?.
canmessageevenifblocked: boolean; // @since 3.8. If the user can still message even if they get blocked.
canmessage: boolean; // If the user can be messaged.
requirescontact: boolean; // If the user requires to be contacts.
contactrequests?: { // The contact requests.
id: number; // The id of the contact request.
userid: number; // The id of the user who created the contact request.
requesteduserid: number; // The id of the user confirming the request.
timecreated: number; // The timecreated timestamp for the contact request.
}[];
conversations?: { // Conversations between users.
id: number; // Conversations id.
type: number; // Conversation type: private or public.
name: string; // Multilang compatible conversation name2.
timecreated: number; // The timecreated timestamp for the conversation.
}[];
};
/**
* Conversation message.
*/
export type AddonMessagesConversationMessage = {
id: number; // The id of the message.
useridfrom: number; // The id of the user who sent the message.
text: string; // The text of the message.
timecreated: number; // The timecreated timestamp for the message.
};
/**
* Conversation message with some calculated data.
*/
export type AddonMessagesConversationMessageFormatted =
(AddonMessagesConversationMessage
| AddonMessagesGetMessagesMessage
| AddonMessagesOfflineMessagesDBRecordFormatted
| AddonMessagesOfflineConversationMessagesDBRecordFormatted) & {
pending?: boolean; // Calculated in the app. Whether the message is pending to be sent.
sending?: boolean; // Calculated in the app. Whether the message is being sent right now.
hash?: string; // Calculated in the app. A hash to identify the message.
showDate?: boolean; // Calculated in the app. Whether to show the date before the message.
showUserData?: boolean; // Calculated in the app. Whether to show the user data in the message.
showTail?: boolean; // Calculated in the app. Whether to show a "tail" in the message.
};
/**
* Data returned by core_message_get_user_message_preferences WS.
*/
export type AddonMessagesGetUserMessagePreferencesWSResponse = {
preferences: AddonMessagesMessagePreferences;
blocknoncontacts: number; // Privacy messaging setting to define who can message you.
entertosend: boolean; // User preference for using enter to send messages.
warnings?: CoreWSExternalWarning[];
};
/**
* Message preferences.
*/
export type AddonMessagesMessagePreferences = {
userid: number; // User id.
disableall: number; // Whether all the preferences are disabled.
processors: { // Config form values.
displayname: string; // Display name.
name: string; // Processor name.
hassettings: boolean; // Whether has settings.
contextid: number; // Context id.
userconfigured: number; // Whether is configured by the user.
}[];
components: { // Available components.
displayname: string; // Display name.
notifications: AddonMessagesMessagePreferencesNotification[]; // List of notificaitons for the component.
}[];
} & AddonMessagesMessagePreferencesCalculatedData;
/**
* Notification processor in message preferences.
*/
export type AddonMessagesMessagePreferencesNotification = {
displayname: string; // Display name.
preferencekey: string; // Preference key.
processors: AddonMessagesMessagePreferencesNotificationProcessor[]; // Processors values for this notification.
};
/**
* Notification processor in message preferences.
*/
export type AddonMessagesMessagePreferencesNotificationProcessor = {
displayname: string; // Display name.
name: string; // Processor name.
locked: boolean; // Is locked by admin?.
lockedmessage?: string; // @since 3.6. Text to display if locked.
userconfigured: number; // Is configured?.
enabled?: boolean; // @since 4.0. Processor enabled.
loggedin: AddonNotificationsPreferencesNotificationProcessorState; // @deprecated removed on 4.0.
loggedoff: AddonNotificationsPreferencesNotificationProcessorState; // @deprecated removed on 4.0.
};
/**
* Message discussion (before 3.6).
*/
export type AddonMessagesDiscussion = {
fullname: string; // Full name of the other user in the discussion.
profileimageurl?: string; // Profile image of the other user in the discussion.
message?: { // Last message.
id: number; // Message ID.
user: number; // User ID that sent the message.
message: string; // Text of the message.
timecreated: number; // Time the message was sent.
pending?: boolean; // Whether the message is pending to be sent.
};
unread?: boolean; // Whether the discussion has unread messages.
};
/**
* Contact for message area.
*/
export type AddonMessagesMessageAreaContact = {
userid: number; // The user's id.
fullname: string; // The user's name.
profileimageurl: string; // User picture URL.
profileimageurlsmall: string; // Small user picture URL.
ismessaging: boolean; // If we are messaging the user.
sentfromcurrentuser: boolean; // Was the last message sent from the current user?.
lastmessage: string; // The user's last message.
lastmessagedate: number; // @since 3.6. Timestamp for last message.
messageid: number; // The unique search message id.
showonlinestatus: boolean; // Show the user's online status?.
isonline: boolean; // The user's online status.
isread: boolean; // If the user has read the message.
isblocked: boolean; // If the user has been blocked.
unreadcount: number; // The number of unread messages in this conversation.
conversationid: number; // @since 3.6. The id of the conversation.
} & AddonMessagesMessageAreaContactCalculatedData;
/**
* Params of core_message_get_blocked_users WS.
*/
type AddonMessagesGetBlockedUsersWSParams = {
userid: number; // The user whose blocked users we want to retrieve.
};
/**
* Result of WS core_message_get_blocked_users.
*/
export type AddonMessagesGetBlockedUsersWSResponse = {
users: AddonMessagesBlockedUser[]; // List of blocked users.
warnings?: CoreWSExternalWarning[];
};
/**
* User data returned by core_message_get_blocked_users.
*/
export type AddonMessagesBlockedUser = {
id: number; // User ID.
fullname: string; // User full name.
profileimageurl?: string; // User picture URL.
};
/**
* Result of WS core_message_get_contacts.
*/
export type AddonMessagesGetContactsWSResponse = {
online: AddonMessagesGetContactsContact[]; // List of online contacts.
offline: AddonMessagesGetContactsContact[]; // List of offline contacts.
strangers: AddonMessagesGetContactsContact[]; // List of users that are not in the user's contact list but have sent a message.
} & AddonMessagesGetContactsCalculatedData;
/**
* User data returned by core_message_get_contacts.
*/
export type AddonMessagesGetContactsContact = {
id: number; // User ID.
fullname: string; // User full name.
profileimageurl?: string; // User picture URL.
profileimageurlsmall?: string; // Small user picture URL.
unread: number; // Unread message count.
};
/**
* Params of core_message_search_contacts WS.
*/
type AddonMessagesSearchContactsWSParams = {
searchtext: string; // String the user's fullname has to match to be found.
onlymycourses?: boolean; // Limit search to the user's courses.
};
/**
* User data returned by core_message_search_contacts.
*/
export type AddonMessagesSearchContactsContact = {
id: number; // User ID.
fullname: string; // User full name.
profileimageurl?: string; // User picture URL.
profileimageurlsmall?: string; // Small user picture URL.
};
/**
* Params of core_message_get_conversation_messages WS.
*/
type AddonMessagesGetConversationMessagesWSParams = {
currentuserid: number; // The current user's id.
convid: number; // The conversation id.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
newest?: boolean; // Newest first?.
timefrom?: number; // The timestamp from which the messages were created.
};
/**
* Data returned by core_message_get_conversation_messages WS.
*/
type AddonMessagesGetConversationMessagesWSResponse = {
id: number; // The conversation id.
members: AddonMessagesConversationMember[];
messages: AddonMessagesConversationMessage[];
};
/**
* Result formatted of WS core_message_get_conversation_messages.
*/
export type AddonMessagesGetConversationMessagesResult = Omit<AddonMessagesGetConversationMessagesWSResponse, 'messages'> & {
messages: (AddonMessagesConversationMessage | AddonMessagesOfflineConversationMessagesDBRecordFormatted)[];
} & AddonMessagesGetConversationMessagesCalculatedData;
/**
* Params of core_message_get_conversations WS.
*/
type AddonMessagesGetConversationsWSParams = {
userid: number; // The id of the user who we are viewing conversations for.
limitfrom?: number; // The offset to start at.
limitnum?: number; // Limit number of conversations to this.
type?: number; // Filter by type.
favourites?: boolean; // Whether to restrict the results to contain NO favourite conversations (false), ONLY favourite
// conversation(true), or ignore any restriction altogether(null).
mergeself?: boolean; // Whether to include self-conversations (true) or ONLY private conversations (false) when private
// conversations are requested.
};
/**
* Result of WS core_message_get_conversations.
*/
export type AddonMessagesGetConversationsResult = {
conversations: AddonMessagesConversation[];
};
/**
* Params of core_message_get_messages WS.
*/
export type AddonMessagesGetMessagesWSParams = {
useridto: number; // The user id who received the message, 0 for any user.
useridfrom?: number; // The user id who send the message, 0 for any user. -10 or -20 for no-reply or support user.
type?: string; // Type of message to return, expected values are: notifications, conversations and both.
read?: boolean; // True for getting read messages, false for unread.
newestfirst?: boolean; // True for ordering by newest first, false for oldest first.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Result of WS core_message_get_messages.
*/
export type AddonMessagesGetMessagesResult = {
messages: AddonMessagesGetMessagesMessage[];
warnings?: CoreWSExternalWarning[];
};
/**
* Message data returned by core_message_get_messages.
*/
export type AddonMessagesGetMessagesMessage = {
id: number; // Message id.
useridfrom: number; // User from id.
useridto: number; // User to id.
subject: string; // The message subject.
text: string; // The message text formated.
fullmessage: string; // The message.
fullmessageformat: number; // Fullmessage format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
fullmessagehtml: string; // The message in html.
smallmessage: string; // The shorten message.
notification: number; // Is a notification?.
contexturl: string; // Context URL.
contexturlname: string; // Context URL link name.
timecreated: number; // Time created.
timeread: number; // Time read.
usertofullname: string; // User to full name.
userfromfullname: string; // User from full name.
component?: string; // @since 3.7. The component that generated the notification.
eventtype?: string; // @since 3.7. The type of notification.
customdata?: string; // @since 3.7. Custom data to be passed to the message processor.
} & AddonMessagesGetMessagesMessageCalculatedData;
/**
* Response object on get discussion.
*/
export type AddonMessagesGetDiscussionMessages = {
messages: (AddonMessagesGetMessagesMessage | AddonMessagesOfflineMessagesDBRecordFormatted)[];
canLoadMore: boolean;
};
/**
* Params of core_message_data_for_messagearea_search_messages WS.
*/
type AddonMessagesDataForMessageareaSearchMessagesWSParams = {
userid: number; // The id of the user who is performing the search.
search: string; // The string being searched.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Result of WS core_message_data_for_messagearea_search_messages.
*/
export type AddonMessagesDataForMessageareaSearchMessagesWSResponse = {
contacts: AddonMessagesMessageAreaContact[];
};
/**
* Params of core_message_message_search_users WS.
*/
type AddonMessagesMessageSearchUsersWSParams = {
userid: number; // The id of the user who is performing the search.
search: string; // The string being searched.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Result of WS core_message_message_search_users.
*/
export type AddonMessagesSearchUsersWSResponse = {
contacts: AddonMessagesConversationMember[];
noncontacts: AddonMessagesConversationMember[];
};
/**
* Params of core_message_mark_message_read WS.
*/
type AddonMessagesMarkMessageReadWSParams = {
messageid: number; // Id of the message in the messages table.
timeread?: number; // Timestamp for when the message should be marked read.
};
/**
* Result of WS core_message_mark_message_read.
*/
export type AddonMessagesMarkMessageReadResult = {
messageid: number; // The id of the message in the messages table.
warnings?: CoreWSExternalWarning[];
};
/**
* Result of WS core_message_send_instant_messages.
*/
export type AddonMessagesSendInstantMessagesMessage = {
msgid: number; // Test this to know if it succeeds: i of the created message if it succeeded, -1 when failed.
clientmsgid?: string; // Your own id for the message.
errormessage?: string; // Error message - if it failed.
text?: string; // @since 3.6. The text of the message.
timecreated?: number; // @since 3.6. The timecreated timestamp for the message.
conversationid?: number; // @since 3.6. The conversation id for this message.
useridfrom?: number; // @since 3.6. The user id who sent the message.
candeletemessagesforallusers: boolean; // @since 3.7. If the user can delete messages in the conversation for all users.
};
export type CoreMessageSendMessagesToConversationMessageData ={
text: string; // The text of the message.
textformat?: number; // Text format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
};
/**
* Params of core_message_send_messages_to_conversation WS.
*/
type CoreMessageSendMessagesToConversationWSParams = {
conversationid: number; // Id of the conversation.
messages: CoreMessageSendMessagesToConversationMessageData[];
};
/**
* Result of WS core_message_send_messages_to_conversation.
*/
export type AddonMessagesSendMessagesToConversationMessage = {
id: number; // The id of the message.
useridfrom: number; // The id of the user who sent the message.
text: string; // The text of the message.
timecreated: number; // The timecreated timestamp for the message.
};
/**
* Result for Send Messages functions trying online or storing in offline.
*/
export type AddonMessagesSendMessageResults = {
sent: boolean;
message: AddonMessagesSendMessagesToConversationMessage | AddonMessagesSendInstantMessagesMessage;
};
/**
* Calculated data for core_message_get_contacts.
*/
export type AddonMessagesGetContactsCalculatedData = {
blocked?: AddonMessagesBlockedUser[]; // Calculated in the app. List of blocked users.
};
/**
* Calculated data for core_message_get_conversation_messages.
*/
export type AddonMessagesGetConversationMessagesCalculatedData = {
canLoadMore?: boolean; // Calculated in the app. Whether more messages can be loaded.
};
/**
* Calculated data for message preferences.
*/
export type AddonMessagesMessagePreferencesCalculatedData = {
blocknoncontacts?: number; // Calculated in the app. Based on the result of core_message_get_user_message_preferences.
};
/**
* Calculated data for messages returned by core_message_get_messages.
*/
export type AddonMessagesGetMessagesMessageCalculatedData = {
pending?: boolean; // Calculated in the app. Whether the message is pending to be sent.
read?: boolean; // Calculated in the app. Whether the message has been read.
};
/**
* Calculated data for contact for message area.
*/
export type AddonMessagesMessageAreaContactCalculatedData = {
id?: number; // Calculated in the app. User ID.
};
/**
* Params of core_message_block_user WS.
*/
type AddonMessagesBlockUserWSParams = {
userid: number; // The id of the user who is blocking.
blockeduserid: number; // The id of the user being blocked.
};
/**
* Params of core_message_unblock_user WS.
*/
type AddonMessagesUnblockUserWSParams = {
userid: number; // The id of the user who is unblocking.
unblockeduserid: number; // The id of the user being unblocked.
};
/**
* Params of core_message_confirm_contact_request WS.
*/
type AddonMessagesConfirmContactRequestWSParams = {
userid: number; // The id of the user making the request.
requesteduserid: number; // The id of the user being requested.
};
/**
* Params of core_message_create_contact_request WS.
*/
type AddonMessagesCreateContactRequestWSParams = AddonMessagesConfirmContactRequestWSParams;
/**
* Data returned by core_message_create_contact_request WS.
*/
export type AddonMessagesCreateContactRequestWSResponse = {
request?: {
id: number; // Message id.
userid: number; // User from id.
requesteduserid: number; // User to id.
timecreated: number; // Time created.
}; // Request record.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of core_message_decline_contact_request WS.
*/
type AddonMessagesDeclineContactRequestWSParams = AddonMessagesConfirmContactRequestWSParams;
/**
* Params of core_message_delete_conversations_by_id WS.
*/
type AddonMessagesDeleteConversationsByIdWSParams = {
userid: number; // The user id of who we want to delete the conversation for.
conversationids: number[]; // List of conversation IDs.
};
/**
* Params of core_message_delete_message WS.
*/
type AddonMessagesDeleteMessageWSParams = {
messageid: number; // The message id.
userid: number; // The user id of who we want to delete the message for.
read?: boolean; // If is a message read.
};
/**
* Params of core_message_delete_message_for_all_users WS.
*/
type AddonMessagesDeleteMessageForAllUsersWSParams = {
messageid: number; // The message id.
userid: number; // The user id of who we want to delete the message for all users.
};
/**
* Params of core_message_get_user_contacts WS.
*/
type AddonMessagesGetUserContactsWSParams = {
userid: number; // The id of the user who we retrieving the contacts for.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Data returned by core_message_get_user_contacts WS.
*/
export type AddonMessagesGetUserContactsWSResponse = {
id: number; // The user id.
fullname: string; // The user's name.
profileurl: string; // The link to the user's profile page.
profileimageurl: string; // User picture URL.
profileimageurlsmall: string; // Small user picture URL.
isonline: boolean; // The user's online status.
showonlinestatus: boolean; // Show the user's online status?.
isblocked: boolean; // If the user has been blocked.
iscontact: boolean; // Is the user a contact?.
isdeleted: boolean; // Is the user deleted?.
canmessageevenifblocked: boolean; // If the user can still message even if they get blocked.
canmessage: boolean; // If the user can be messaged.
requirescontact: boolean; // If the user requires to be contacts.
contactrequests?: { // The contact requests.
id: number; // The id of the contact request.
userid: number; // The id of the user who created the contact request.
requesteduserid: number; // The id of the user confirming the request.
timecreated: number; // The timecreated timestamp for the contact request.
}[];
conversations?: { // Conversations between users.
id: number; // Conversations id.
type: number; // Conversation type: private or public.
name: string; // Multilang compatible conversation name2.
timecreated: number; // The timecreated timestamp for the conversation.
}[];
}[];
/**
* Params of core_message_get_contact_requests WS.
*/
type AddonMessagesGetContactRequestsWSParams = {
userid: number; // The id of the user we want the requests for.
limitfrom?: number; // Limit from.
limitnum?: number; // Limit number.
};
/**
* Data returned by core_message_get_contact_requests WS.
*/
export type AddonMessagesGetContactRequestsWSResponse = {
id: number; // The user id.
fullname: string; // The user's name.
profileurl: string; // The link to the user's profile page.
profileimageurl: string; // User picture URL.
profileimageurlsmall: string; // Small user picture URL.
isonline: boolean; // The user's online status.
showonlinestatus: boolean; // Show the user's online status?.
isblocked: boolean; // If the user has been blocked.
iscontact: boolean; // Is the user a contact?.
isdeleted: boolean; // Is the user deleted?.
canmessageevenifblocked: boolean; // If the user can still message even if they get blocked.
canmessage: boolean; // If the user can be messaged.
requirescontact: boolean; // If the user requires to be contacts.
contactrequests?: { // The contact requests.
id: number; // The id of the contact request.
userid: number; // The id of the user who created the contact request.
requesteduserid: number; // The id of the user confirming the request.
timecreated: number; // The timecreated timestamp for the contact request.
}[];
conversations?: { // Conversations between users.
id: number; // Conversations id.
type: number; // Conversation type: private or public.
name: string; // Multilang compatible conversation name2.
timecreated: number; // The timecreated timestamp for the conversation.
}[];
}[];
/**
* Params of core_message_get_received_contact_requests_count WS.
*/
type AddonMessagesGetReceivedContactRequestsCountWSParams = {
userid: number; // The id of the user we want to return the number of received contact requests for.
};
/**
* Params of core_message_mark_all_conversation_messages_as_read WS.
*/
type AddonMessagesMarkAllConversationMessagesAsReadWSParams = {
userid: number; // The user id who who we are marking the messages as read for.
conversationid: number; // The conversation id who who we are marking the messages as read for.
};
/**
* Params of core_message_mark_all_messages_as_read WS. Deprecated on Moodle 3.6
*/
type AddonMessagesMarkAllMessagesAsReadWSParams = {
useridto: number; // The user id who received the message, 0 for any user.
useridfrom?: number; // The user id who send the message, 0 for any user. -10 or -20 for no-reply or support user.
};
/**
* Params of core_message_mute_conversations and core_message_unmute_conversations WS.
*/
type AddonMessagesMuteConversationsWSParams = {
userid: number; // The id of the user who is blocking.
conversationids: number[];
};
/**
* Params of core_message_delete_contacts WS.
*/
type AddonMessagesDeleteContactsWSParams = {
userids: number[]; // List of user IDs.
userid?: number; // The id of the user we are deleting the contacts for, 0 for the current user.
};
/**
* One message data.
*/
export type AddonMessagesMessageData = {
touserid: number; // Id of the user to send the private message.
text: string; // The text of the message.
textformat?: number; // Text format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
clientmsgid?: string; // Your own client id for the message. If this id is provided, the fail message id will be returned.
};
/**
* Params of core_message_send_instant_messages WS.
*/
type AddonMessagesSendInstantMessagesWSParams = {
messages: AddonMessagesMessageData[];
};
/**
* Data returned by core_message_get_conversation_counts and core_message_get_unread_conversation_counts WS.
*/
export type AddonMessagesGetConversationCountsWSResponse = {
favourites: number; // Total number of favourite conversations.
types: {
1: number; // Total number of individual conversations.
2: number; // Total number of group conversations.
3: number; // Total number of self conversations.
};
};
/**
* Params of core_message_set_favourite_conversations and core_message_unset_favourite_conversations WS.
*/
type AddonMessagesSetFavouriteConversationsWSParams = {
userid?: number; // Id of the user, 0 for current user.
conversations: number[];
};
/**
* Params of core_message_get_unread_conversations_count WS.
*/
type AddonMessageGetUnreadConversationsCountWSParams = {
useridto: number; // The user id who received the message, 0 for any user.
};
/**
* Data sent by UNREAD_CONVERSATION_COUNTS_EVENT event.
*/
export type AddonMessagesUnreadConversationCountsEventData = {
favourites: number;
individual: number;
group: number;
self: number;
orMore?: boolean;
};
/**
* Data sent by CONTACT_REQUESTS_COUNT_EVENT event.
*/
export type AddonMessagesContactRequestCountEventData = {
count: number;
};
/**
* Data sent by MEMBER_INFO_CHANGED_EVENT event.
*/
export type AddonMessagesMemberInfoChangedEventData = {
userId: number;
userBlocked?: boolean;
userUnblocked?: boolean;
contactRequestConfirmed?: boolean;
contactRequestCreated?: boolean;
contactRequestDeclined?: boolean;
contactRemoved?: boolean;
};
/**
* Data sent by READ_CHANGED_EVENT event.
*/
export type AddonMessagesReadChangedEventData = {
userId?: number;
conversationId?: number;
};
/**
* Data sent by NEW_MESSAGE_EVENT event.
*/
export type AddonMessagesNewMessagedEventData = {
conversationId?: number;
userId?: number;
message: string;
timecreated: number;
isfavourite: boolean;
type?: number;
};
/**
* Data sent by UPDATE_CONVERSATION_LIST_EVENT event.
*/
export type AddonMessagesUpdateConversationListEventData = {
conversationId: number;
action: string;
value?: boolean;
};
/**
* Data sent by OPEN_CONVERSATION_EVENT event.
*/
export type AddonMessagesOpenConversationEventData = {
userId?: number;
conversationId?: number;
}; | the_stack |
import * as Clutter from 'clutter';
import * as Gio from 'gio';
import * as GObject from 'gobject';
import { TaskBarItem } from 'src/layout/msWorkspace/horizontalPanel/taskBar';
import { MsWindow } from 'src/layout/msWorkspace/msWindow';
import { MainCategories } from 'src/layout/msWorkspace/msWorkspaceCategory';
import { PanelIconStyleEnum } from 'src/manager/msThemeManager';
import { MsWorkspaceManager } from 'src/manager/msWorkspaceManager';
import { assert } from 'src/utils/assert';
import { Allocate, SetAllocation } from 'src/utils/compatibility';
import { registerGObjectClass } from 'src/utils/gjs';
import { MatButton } from 'src/widget/material/button';
import { ReorderableList } from 'src/widget/reorderableList';
import * as St from 'st';
import { main as Main, popupMenu } from 'ui';
import { MsWorkspace } from '../msWorkspace/msWorkspace';
const DND = imports.ui.dnd;
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
@registerGObjectClass
export class WorkspaceList extends St.Widget {
private _delegate: this;
msWorkspaceButtonMap: Map<any, any>;
msWorkspaceManager: MsWorkspaceManager;
menuManager: popupMenu.PopupMenuManager;
buttonList: ReorderableList;
workspaceActiveIndicator: St.Widget;
workspaceSignal: number;
buttonActive: St.Widget | undefined;
constructor() {
super({
clip_to_allocation: true,
style_class: 'workspace-list',
reactive: true,
});
this._delegate = this;
this.connect('destroy', this._onDestroy.bind(this));
this.msWorkspaceButtonMap = new Map();
this.msWorkspaceManager = Me.msWorkspaceManager;
this.menuManager = new popupMenu.PopupMenuManager(this);
this.buttonList = new ReorderableList(true);
this.buttonList.connect('actor-moved', (_, actor, index) => {
this.msWorkspaceManager.setMsWorkspaceAt(actor.msWorkspace, index);
});
this.add_child(this.buttonList);
this.workspaceActiveIndicator = new St.Widget({
style_class: 'workspace-active-indicator',
height: Me.msThemeManager.getPanelSize(
Main.layoutManager.primaryIndex
),
});
Me.msThemeManager.connect('panel-size-changed', () => {
this.workspaceActiveIndicator.set_height(
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex)
);
this.queue_relayout();
});
this.workspaceActiveIndicator.add_style_class_name('primary-bg');
this.add_child(this.workspaceActiveIndicator);
this.connect('notify::mapped', () => {
if (this.mapped) {
this.buildButtons();
this.activeButtonForIndex(
global.workspace_manager.get_active_workspace_index()
);
}
});
this.msWorkspaceManager.connect(
'dynamic-super-workspaces-changed',
() => {
this.buildButtons();
}
);
this.workspaceSignal = global.workspace_manager.connect(
'active-workspace-changed',
() => {
this.activeButtonForIndex(
global.workspace_manager.get_active_workspace_index()
);
}
);
this.connect('scroll-event', (_, event) => {
switch (event.get_scroll_direction()) {
case Clutter.ScrollDirection.UP:
this.msWorkspaceManager.activatePreviousMsWorkspace();
break;
case Clutter.ScrollDirection.DOWN:
this.msWorkspaceManager.activateNextMsWorkspace();
break;
}
});
}
buildButtons() {
this.msWorkspaceManager.primaryMsWorkspaces.forEach(
(msWorkspace, index) => {
if (!this.msWorkspaceButtonMap.has(msWorkspace)) {
const workspaceButton = new WorkspaceButton(
this.msWorkspaceManager,
msWorkspace
);
this.menuManager.addMenu(workspaceButton.menu);
/* workspaceButton._draggable.connect('drag-begin', () => {
let workspaceButtonIndex = this.msWorkspaceManager.primaryMsWorkspaces.indexOf(
msWorkspace
);
this.tempDragData = {
workspaceButton: workspaceButton,
initialIndex: workspaceButtonIndex,
};
this.dropPlaceholder.resize(workspaceButton);
this.buttonList.add_child(this.dropPlaceholder);
this.buttonList.set_child_at_index(
this.dropPlaceholder,
workspaceButtonIndex
);
this.workspaceActiveIndicator.hide();
});
workspaceButton._draggable.connect(
'drag-cancelled',
() => {
delete this.tempDragData.draggedOver;
delete this.tempDragData.draggedBefore;
this.buttonList.set_child_at_index(
this.dropPlaceholder,
this.tempDragData.initialIndex
);
}
);
workspaceButton._draggable.connect(
'drag-end',
this._onDragEnd.bind(this)
); */
/* workspaceButton.connect('drag-over', (_, before) => {
this.tempDragData.draggedOverByChild = true;
this._onDragOver(workspaceButton, before);
//this.buttonList.set_child_before(this.dropPlaceholder, this.tempDragData.draggedBefore ? index : index + 1);
});
workspaceButton.connect('drag-dropped', () => {
this.tempDragData.workspaceButton
.get_parent()
.remove_child(
this.tempDragData.workspaceButton
);
this.buttonList.add_child(
this.tempDragData.workspaceButton
);
}); */
this.buttonList.insert_child_at_index(
workspaceButton,
index
);
this.msWorkspaceButtonMap.set(msWorkspace, workspaceButton);
} else {
const button = this.msWorkspaceButtonMap.get(msWorkspace);
const index =
this.msWorkspaceManager.primaryMsWorkspaces.indexOf(
msWorkspace
);
this.buttonList.set_child_at_index(button, index);
}
}
);
//Check if some msWorkspace has been destroyed
this.msWorkspaceButtonMap.forEach((button, msWorkspace) => {
if (
!this.msWorkspaceManager.primaryMsWorkspaces.includes(
msWorkspace
)
) {
this.menuManager.removeMenu(button.menu);
button.menu.destroy();
button.destroy();
this.msWorkspaceButtonMap.delete(msWorkspace);
}
});
}
/* handleDragOver(source, _actor, _x, _y) {
if (source instanceof WorkspaceButton) {
// Needed for dragging over tasks
if (!this.tempDragData.draggedOverByChild) {
let workspaceButton =
this.items[this.items.length - 1] ===
this.tempDragData.workspaceButton
? this.items[this.items.length - 2]
: this.items[this.items.length - 1];
this._onDragOver(workspaceButton, false);
} else {
this.tempDragData.draggedOverByChild = false;
}
}
return DND.DragMotionResult.MOVE_DROP;
} */
/* _onDragEnd() {
this.buttonList.remove_child(this.dropPlaceholder);
if (this.tempDragData.draggedOver) {
let toIndex = this.msWorkspaceManager.primaryMsWorkspaces.indexOf(
this.tempDragData.draggedOver.msWorkspace
);
if (this.tempDragData.draggedBefore) {
toIndex =
toIndex -
(this.tempDragData.initialIndex < toIndex ? 1 : 0);
this.buttonList.set_child_at_index(
this.tempDragData.workspaceButton,
toIndex
);
this.msWorkspaceManager.setMsWorkspaceAt(
this.tempDragData.workspaceButton.msWorkspace,
toIndex
);
} else {
toIndex =
toIndex +
(this.tempDragData.initialIndex < toIndex ? 0 : 1);
this.buttonList.set_child_at_index(
this.tempDragData.workspaceButton,
toIndex
);
this.msWorkspaceManager.setMsWorkspaceAt(
this.tempDragData.workspaceButton.msWorkspace,
toIndex
);
}
} else {
this.buttonList.set_child_at_index(
this.tempDragData.workspaceButton,
this.tempDragData.initialIndex
);
}
this.workspaceActiveIndicator.show();
delete this.tempDragData;
}
_onDragOver(workspaceButton, before) {
this.tempDragData.draggedOver = workspaceButton;
this.tempDragData.draggedBefore = before;
this.dropPlaceholder.resize(this.tempDragData.workspaceButton);
let dropPlaceholderIndex = this.buttonList
.get_children()
.indexOf(this.dropPlaceholder);
let workspaceButtonIndex = this.buttonList
.get_children()
.indexOf(workspaceButton);
let toIndex =
dropPlaceholderIndex < workspaceButtonIndex
? workspaceButtonIndex - 1
: workspaceButtonIndex;
if (this.tempDragData.draggedBefore) {
this.buttonList.set_child_at_index(
this.dropPlaceholder,
toIndex
);
} else {
this.buttonList.set_child_at_index(
this.dropPlaceholder,
toIndex + 1
);
}
} */
activeButtonForIndex(index: number) {
if (this.buttonActive) {
if (this.buttonActive.has_style_class_name('active')) {
this.buttonActive.remove_style_class_name('active');
}
const child = this.buttonList.get_child_at_index(index);
assert(child instanceof St.Widget, 'Child was not a widget');
this.buttonActive = child;
this.buttonActive.add_style_class_name('active');
}
this.workspaceActiveIndicator.ease({
translation_y: this.get_preferred_width(-1)[1]! * index,
duration: 250,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
});
}
/**
* Just the parent width
*/
vfunc_get_preferred_width(_forHeight: number): [number, number] {
return [
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
];
}
_onDestroy() {
global.workspace_manager.disconnect(this.workspaceSignal);
}
}
@registerGObjectClass
export class WorkspaceButton extends MatButton {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'WorkspaceButton',
Signals: {
'drag-dropped': {},
'drag-over': {
param_types: [GObject.TYPE_BOOLEAN],
},
},
};
msWorkspace: MsWorkspace;
msWorkspaceManager: MsWorkspaceManager;
workspaceButtonIcon: WorkspaceButtonIcon;
private _delegate: this;
menu: any;
mouseData: {
pressed: boolean;
dragged: boolean;
originalCoords: null;
originalSequence: null;
};
panelIconStyleHybridRadio: any;
panelIconStyleCategoryRadio: any;
panelIconStyleApplicationRadio: any;
subMenu: any;
_draggable: any;
constructor(
msWorkspaceManager: MsWorkspaceManager,
msWorkspace: MsWorkspace
) {
const workspaceButtonIcon = new WorkspaceButtonIcon(msWorkspace);
super({
child: workspaceButtonIcon,
});
this.msWorkspaceManager = msWorkspaceManager;
this.msWorkspace = msWorkspace;
this.workspaceButtonIcon = workspaceButtonIcon;
this._delegate = this;
this.buildMenu();
Me.msThemeManager.connect('panel-size-changed', () => {
this.queue_relayout();
});
this.connect('primary-action', () => {
this.msWorkspace.activate();
});
this.connect('secondary-action', () => {
this.menu.toggle();
});
this.connect('clicked', (actor, button) => {
if (button === Clutter.BUTTON_MIDDLE) {
if (
this.msWorkspaceManager.primaryMsWorkspaces.indexOf(
this.msWorkspace
) !==
this.msWorkspaceManager.primaryMsWorkspaces.length - 1
)
msWorkspace.close();
}
});
this.mouseData = {
pressed: false,
dragged: false,
originalCoords: null,
originalSequence: null,
};
}
get draggable() {
return (
this.msWorkspaceManager.primaryMsWorkspaces.indexOf(
this.msWorkspace
) !==
this.msWorkspaceManager.primaryMsWorkspaces.length - 1
);
}
buildMenu() {
this.menu = new popupMenu.PopupMenu(this, 0.5, St.Side.LEFT);
this.menu.actor.add_style_class_name('panel-menu');
this.menu.addMenuItem(
new popupMenu.PopupSeparatorMenuItem(_('Panel icons style'))
);
this.panelIconStyleHybridRadio = this.menu.addAction(
_('Hybrid'),
() => {
Me.msThemeManager.panelIconStyle = PanelIconStyleEnum.HYBRID;
},
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.HYBRID
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
this.panelIconStyleCategoryRadio = this.menu.addAction(
_('Categories only'),
() => {
Me.msThemeManager.panelIconStyle = PanelIconStyleEnum.CATEGORY;
},
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.CATEGORY
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
this.panelIconStyleApplicationRadio = this.menu.addAction(
_('Applications preview'),
() => {
Me.msThemeManager.panelIconStyle =
PanelIconStyleEnum.APPLICATION;
},
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.APPLICATION
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
Me.msThemeManager.connect('panel-icon-style-changed', () => {
this.panelIconStyleHybridRadio._icon.set_gicon(
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.HYBRID
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
this.panelIconStyleCategoryRadio._icon.set_gicon(
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.CATEGORY
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
this.panelIconStyleApplicationRadio._icon.set_gicon(
Gio.icon_new_for_string(
`${Me.path}/assets/icons/radiobox-${
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.APPLICATION
? 'marked'
: 'blank'
}-symbolic.svg`
)
);
});
this.menu.addMenuItem(
new popupMenu.PopupSeparatorMenuItem(_('Override category'))
);
const autoSentence = _('Determined automatically');
this.subMenu = new popupMenu.PopupSubMenuMenuItem(
this.msWorkspace.msWorkspaceCategory.forcedCategory || autoSentence
);
const setCategory = (category?: string) => {
this.msWorkspace.msWorkspaceCategory.forceCategory(category);
this.workspaceButtonIcon.buildIcons();
this.subMenu.label.text = category || autoSentence;
};
this.subMenu.menu.addAction(autoSentence, () => {
setCategory();
});
MainCategories.forEach((key) => {
this.subMenu.menu.addAction(
key,
() => {
setCategory(key);
},
Gio.icon_new_for_string(
`${
Me.path
}/assets/icons/category/${key.toLowerCase()}-symbolic.svg`
)
);
});
this.menu.addMenuItem(this.subMenu);
Main.layoutManager.uiGroup.add_actor(this.menu.actor);
this.menu.close();
}
initDrag() {
this._draggable = DND.makeDraggable(this, {
restoreOnSuccess: false,
manualMode: true,
});
this._draggable.connect('drag-end', () => {
this.mouseData.pressed = false;
this.mouseData.dragged = false;
});
}
handleDragOver(source: any, actor: Clutter.Actor, x: number, y: number) {
if (source instanceof TaskBarItem) {
return DND.DragMotionResult.MOVE_DROP;
}
return DND.DragMotionResult.NO_DROP;
}
acceptDrop(source: any) {
if (source instanceof TaskBarItem) {
if (source.tileable instanceof MsWindow) {
Me.msWorkspaceManager.setWindowToMsWorkspace(
source.tileable,
this.msWorkspace
);
this.msWorkspaceManager.stateChanged();
this.msWorkspace.activate();
}
return true;
}
return false;
}
/**
* Just the parent width
*/
vfunc_get_preferred_width(_forHeight: number): [number, number] {
return [
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
];
}
/**
* Just the child height
*/
vfunc_get_preferred_height(_forWidth: number): [number, number] {
return [
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
Me.msThemeManager.getPanelSize(Main.layoutManager.primaryIndex),
];
}
}
function isMsWindow(argument: any): argument is MsWindow {
return argument instanceof MsWindow;
}
@registerGObjectClass
export class WorkspaceButtonIcon extends St.Widget {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'WorkspaceButtonIcon',
};
msWorkspace: MsWorkspace;
appIconList: St.Icon[];
desaturateEffect: Clutter.DesaturateEffect | undefined;
constructor(msWorkspace: MsWorkspace) {
super();
this.msWorkspace = msWorkspace;
this.appIconList = [];
this.desaturateIcons();
this.connect('notify::mapped', () => {
if (this.mapped) {
this.buildIcons();
}
});
this.msWorkspace.connect('tileableList-changed', (_) => {
this.buildIcons();
});
Me.msThemeManager.connect('panel-icon-style-changed', () => {
this.buildIcons();
});
Me.msThemeManager.connect('panel-icon-color-changed', () => {
this.desaturateIcons();
});
Me.msThemeManager.connect('panel-size-changed', () => {
this.buildIcons();
});
}
desaturateIcons() {
const shouldDesaturate = !Me.msThemeManager.panelIconColor;
const isDesaturate =
this.desaturateEffect !== undefined &&
this.desaturateEffect === this.get_effect('desaturate_icons');
if (shouldDesaturate === isDesaturate) return;
if (shouldDesaturate) {
this.desaturateEffect = new Clutter.DesaturateEffect();
this.add_effect_with_name(
'desaturate_icons',
this.desaturateEffect
);
} else {
assert(this.desaturateEffect !== undefined, 'true by construction');
this.remove_effect(this.desaturateEffect);
delete this.desaturateEffect;
}
}
buildIcons() {
this.appIconList.forEach((icon) => {
icon.destroy();
});
const appList = this.msWorkspace.tileableList
.filter(isMsWindow)
.map((msWindow) => {
return msWindow.app;
});
this.appIconList = [];
if (appList.length) {
const numberOfEachAppMap = new Map();
appList.forEach((app) => {
if (numberOfEachAppMap.has(app)) {
numberOfEachAppMap.set(
app,
numberOfEachAppMap.get(app) + 1
);
} else {
numberOfEachAppMap.set(app, 1);
}
});
const sortedByInstanceAppList = [...numberOfEachAppMap.entries()]
.sort((a, b) => {
return b[1] - a[1];
})
.map((entry) => {
return entry[0];
});
if (
this.msWorkspace.msWorkspaceCategory.forcedCategory ||
Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.CATEGORY ||
(Me.msThemeManager.panelIconStyle ===
PanelIconStyleEnum.HYBRID &&
sortedByInstanceAppList.length > 1)
) {
const category =
this.msWorkspace.msWorkspaceCategory.category || '';
const icon = new St.Icon({
gicon: Gio.icon_new_for_string(
`${
Me.path
}/assets/icons/category/${category.toLowerCase()}-symbolic.svg`
),
icon_size: Me.msThemeManager.getPanelSizeNotScaled() / 2,
});
this.appIconList.push(icon);
this.add_child(icon);
} else {
sortedByInstanceAppList.forEach((app) => {
const icon = app.create_icon_texture(
Me.msThemeManager.getPanelSizeNotScaled() / 2
);
this.appIconList.push(icon);
this.add_child(icon);
});
}
} else {
const icon = new St.Icon({
gicon: Gio.icon_new_for_string(
`${Me.path}/assets/icons/plus-symbolic.svg`
),
icon_size: Me.msThemeManager.getPanelSizeNotScaled() / 2,
});
this.appIconList.push(icon);
this.add_child(icon);
}
}
vfunc_allocate(
allocationBox: Clutter.ActorBox,
flags?: Clutter.AllocationFlags
) {
SetAllocation(this, allocationBox, flags);
const themeNode = this.get_theme_node();
allocationBox = themeNode.get_content_box(allocationBox);
const portion = (allocationBox.x2 - allocationBox.x1) / 8;
if (this.appIconList.length === 1) {
const centerBox = new Clutter.ActorBox();
centerBox.x1 = allocationBox.x1 + 2 * portion;
centerBox.x2 = allocationBox.x2 - 2 * portion;
centerBox.y1 = allocationBox.y1 + 2 * portion;
centerBox.y2 = allocationBox.y2 - 2 * portion;
Allocate(this.appIconList[0], centerBox, flags);
} else {
this.appIconList.forEach((icon, index) => {
const box = new Clutter.ActorBox();
switch (index) {
case 0:
box.x1 = allocationBox.x1 + portion;
box.x2 = allocationBox.x2 - 3 * portion;
box.y1 = allocationBox.y1 + 2 * portion;
box.y2 = allocationBox.y2 - 2 * portion;
Allocate(icon, box, flags);
break;
case 1:
box.x1 = allocationBox.x1 + 3 * portion;
box.x2 = allocationBox.x2 - portion;
box.y1 = allocationBox.y1 + 3 * portion;
box.y2 = allocationBox.y2 - portion;
Allocate(icon, box, flags);
break;
case 2:
box.x1 = allocationBox.x1 + 4 * portion;
box.x2 = allocationBox.x2 - portion;
box.y1 = allocationBox.y1 + portion;
box.y2 = allocationBox.y2 - 4 * portion;
Allocate(icon, box, flags);
break;
}
});
}
}
} | the_stack |
import _ from 'lodash'
import React from 'react'
import { connect as reduxConnect, Options as ReduxConnectOptions } from 'react-redux'
import { Action, Dispatch } from 'redux'
import { Shell, AnyFunction, ObservableState, StateObserverUnsubscribe } from './API'
import { ErrorBoundary } from './errorBoundary'
import { ShellContext } from './shellContext'
import { StoreContext } from './storeContext'
import { propsDeepEqual } from './propsDeepEqual'
interface WrapperMembers<S, OP, SP, DP> {
connectedComponent: any
mapStateToProps(state: S, ownProps?: OP): SP
mapDispatchToProps(dispatch: Dispatch<Action>, ownProps?: OP): DP
}
type Maybe<T> = T | undefined
type Returns<T> = () => T
type MapStateToProps<S, OP, SP> = Maybe<(shell: Shell, state: S, ownProps?: OP) => SP>
type MapDispatchToProps<OP, DP> = Maybe<(shell: Shell, dispatch: Dispatch<Action>, ownProps?: OP) => DP>
type WithChildren<OP> = OP & { children?: React.ReactNode }
type WrappedComponentOwnProps<OP> = OP & { shell: Shell }
type Mandatory<T> = { [K in keyof T]-?: T[K] }
const reduxConnectOptions: ReduxConnectOptions & Pick<Mandatory<ReduxConnectOptions>, 'areStatePropsEqual' | 'areOwnPropsEqual'> = {
context: StoreContext,
pure: true,
areStatePropsEqual: propsDeepEqual,
areOwnPropsEqual: propsDeepEqual
}
function wrapWithShouldUpdate<F extends AnyFunction>(shouldUpdate: Maybe<(shell: Shell) => boolean>, func: F, shell: Shell): F {
return ((...args: Parameters<F>) => (shouldUpdate && !shouldUpdate(shell) ? true : func(...args))) as F
}
function wrapWithShellContext<S, OP, SP, DP>(
component: React.ComponentType<OP & SP & DP>,
mapStateToProps: MapStateToProps<S, OP, SP>,
mapDispatchToProps: MapDispatchToProps<OP, DP>,
boundShell: Shell,
options: ConnectWithShellOptions = {}
) {
class ConnectedComponent extends React.Component<WrappedComponentOwnProps<OP>> implements WrapperMembers<S, OP, SP, DP> {
public connectedComponent: React.ComponentType<OP>
public mapStateToProps: (state: S, ownProps?: OP) => SP
public mapDispatchToProps: (dispatch: Dispatch<Action>, ownProps?: OP) => DP
constructor(props: WrappedComponentOwnProps<OP>) {
super(props)
this.mapStateToProps = mapStateToProps
? (__, ownProps?) => {
return this.props.shell.log.monitor(`connectWithShell.mapStateToProps ${this.props.shell.name}`, {}, () =>
mapStateToProps(this.props.shell, this.props.shell.getStore<S>().getState(), ownProps)
)
}
: (_.stubObject as Returns<SP>)
this.mapDispatchToProps = mapDispatchToProps
? (dispatch, ownProps?) => {
return this.props.shell.log.monitor(`connectWithShell.mapDispatchToProps ${this.props.shell.name}`, {}, () =>
mapDispatchToProps(this.props.shell, dispatch, ownProps)
)
}
: (_.stubObject as Returns<DP>)
const shouldComponentUpdate =
options.shouldComponentUpdate && this.props.shell.memoizeForState(options.shouldComponentUpdate, () => '*')
const memoWithShouldUpdate = <F extends AnyFunction>(f: F): F => {
let last: ReturnType<F> | null = null
return ((...args) => {
if (last && shouldComponentUpdate && !shouldComponentUpdate(this.props.shell)) {
return last
}
last = f(...args)
return last
}) as F
}
this.connectedComponent = reduxConnect<SP, DP, OP, S>(
memoWithShouldUpdate(this.mapStateToProps),
this.mapDispatchToProps,
undefined,
options.shouldComponentUpdate
? {
...reduxConnectOptions,
areStatePropsEqual: wrapWithShouldUpdate(
shouldComponentUpdate,
reduxConnectOptions.areStatePropsEqual,
boundShell
),
areOwnPropsEqual: wrapWithShouldUpdate(shouldComponentUpdate, reduxConnectOptions.areOwnPropsEqual, boundShell)
}
: reduxConnectOptions
)(component as React.ComponentType<any>) as React.ComponentType<any> // TODO: Fix 'as any'
}
public render() {
const Component = this.connectedComponent
const props = _.omit(this.props, 'shell') as OP
return <Component {...props} />
}
}
const wrapChildrenIfNeeded = (props: WithChildren<OP>, originalShell: Shell): WithChildren<OP> =>
props.children
? {
...props,
children: <ShellContext.Provider value={originalShell}>{props.children}</ShellContext.Provider>
}
: props
return (props: WithChildren<OP>) => (
<ShellContext.Consumer>
{shell => {
return (
<ErrorBoundary shell={boundShell} componentName={options.componentName}>
{<ConnectedComponent {...wrapChildrenIfNeeded(props, shell)} shell={boundShell} />}
</ErrorBoundary>
)
}}
</ShellContext.Consumer>
)
}
export interface ConnectWithShellOptions {
readonly componentName?: string
readonly allowOutOfEntryPoint?: boolean
shouldComponentUpdate?(shell: Shell): boolean
}
export type ConnectedComponentFactory<S = {}, OP = {}, SP = {}, DP = {}, OPPure = OP> = (
component: React.ComponentType<OPPure & SP & DP>
) => (props: WithChildren<OP>) => JSX.Element
export function connectWithShell<S = {}, OP = {}, SP = {}, DP = {}>(
mapStateToProps: MapStateToProps<S, OP, SP>,
mapDispatchToProps: MapDispatchToProps<OP, DP>,
boundShell: Shell,
options: ConnectWithShellOptions = {}
): ConnectedComponentFactory<S, OP, SP, DP> {
const validateLifecycle = (component: React.ComponentType<any>) => {
if (boundShell.wasInitializationCompleted() && !options.allowOutOfEntryPoint) {
const componentText = component.displayName || component.name || component
const errorText =
`connectWithShell(${boundShell.name})(${componentText}): ` +
'attempt to create component type outside of Entry Point lifecycle. ' +
'To fix this, call connectWithShell() from Entry Point attach() or extend(). ' +
'If you really have to create this component type dynamically, ' +
'either pass {allowOutOfEntryPoint:true} in options, or use shell.runLateInitializer().'
//TODO: replace with throw after a grace period
boundShell.log.warning(errorText)
}
}
return (component: React.ComponentType<OP & SP & DP>) => {
validateLifecycle(component)
return wrapWithShellContext(component, mapStateToProps, mapDispatchToProps, boundShell, options)
}
}
export interface ObservablesMap {
[key: string]: ObservableState<any>
}
export type ObservedSelectorsMap<M> = {
[K in keyof M]: M[K] extends ObservableState<infer S> ? S : undefined
}
export type OmitObservedSelectors<T, M> = Omit<T, keyof M>
export function mapObservablesToSelectors<M extends ObservablesMap>(map: M): ObservedSelectorsMap<M> {
const result = _.mapValues(map, observable => {
const selector = observable.current()
return selector
})
return result
}
export function observeWithShell<OM extends ObservablesMap, OP extends ObservedSelectorsMap<OM>>(
observables: OM,
boundShell: Shell
): <S, SP, DP>(
innerFactory: ConnectedComponentFactory<S, OP, SP, DP>
) => ConnectedComponentFactory<S, OmitObservedSelectors<OP, OM>, SP, DP, OP> {
return <S, SP, DP>(innerFactory: ConnectedComponentFactory<S, OP, SP, DP>) => {
// exclude observed selectors from wrapper props, because we want those selectors to be in the wrapper's state instead
type ObservableWrapperProps = OmitObservedSelectors<OP, OM>
type ObservableWrapperState = ObservedSelectorsMap<OM>
const observableConnectedComponentFactory: ConnectedComponentFactory<S, ObservableWrapperProps, SP, DP, OP> = pureComponent => {
class ObservableWrapperComponent extends React.Component<ObservableWrapperProps, ObservableWrapperState> {
public connectedComponent: React.ComponentType<OP>
public unsubscribes: StateObserverUnsubscribe[]
constructor(props: OP) {
super(props)
this.connectedComponent = innerFactory(pureComponent)
this.unsubscribes = []
this.state = mapObservablesToSelectors(observables)
}
public componentDidMount() {
for (const key in observables) {
const unsubscribe = observables[key].subscribe(boundShell, () => {
const newState = mapObservablesToSelectors(observables)
this.setState(newState)
})
this.unsubscribes.push(unsubscribe)
}
}
public componentWillUnmount() {
this.unsubscribes.forEach(unsubscribe => unsubscribe())
this.unsubscribes = []
}
public render() {
const ConnectedComponent = this.connectedComponent
const connectedComponentProps: OP = {
...this.props, // OP excluding observed selectors
...this.state // observed selectors
} as OP // TypeScript doesn't get it
return <ConnectedComponent {...connectedComponentProps} />
}
}
const hoc = (props: WithChildren<OmitObservedSelectors<OP, OM>>) => {
return <ObservableWrapperComponent {...props} {...mapObservablesToSelectors(observables)} />
}
return hoc
}
return observableConnectedComponentFactory
}
}
export function connectWithShellAndObserve<OM extends ObservablesMap, OP extends ObservedSelectorsMap<OM>, S = {}, SP = {}, DP = {}>(
observables: OM,
mapStateToProps: MapStateToProps<S, OP, SP>,
mapDispatchToProps: MapDispatchToProps<OP, DP>,
boundShell: Shell,
options: ConnectWithShellOptions = {}
): ConnectedComponentFactory<S, OmitObservedSelectors<OP, OM>, SP, DP, OP> {
const innerFactory = connectWithShell(mapStateToProps, mapDispatchToProps, boundShell, options)
const wrapperFactory = observeWithShell<OM, OP>(observables, boundShell)(innerFactory)
return wrapperFactory
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/* eslint-disable dot-notation */
import { TelemetrySender } from './telemetry_sender';
import { mockTelemetryService } from '../mocks';
import { REPORT_INTERVAL_MS, LOCALSTORAGE_KEY } from '../../common/constants';
class LocalStorageMock implements Partial<Storage> {
getItem = jest.fn();
setItem = jest.fn();
}
const mockLocalStorage = new LocalStorageMock();
const originalLocalStorage = window.localStorage;
Object.defineProperty(window, 'localStorage', {
value: mockLocalStorage,
});
describe('TelemetrySender', () => {
beforeEach(() => {
mockLocalStorage.getItem.mockClear();
mockLocalStorage.setItem.mockClear();
});
afterAll(() =>
Object.defineProperty(window, 'localStorage', {
value: originalLocalStorage,
})
);
describe('constructor', () => {
it('defaults lastReport if unset', () => {
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
expect(telemetrySender['lastReported']).toBeUndefined();
expect(mockLocalStorage.getItem).toBeCalledTimes(1);
expect(mockLocalStorage.getItem).toHaveBeenCalledWith(LOCALSTORAGE_KEY);
});
it('uses lastReport if set', () => {
const lastReport = `${Date.now()}`;
mockLocalStorage.getItem.mockReturnValueOnce(JSON.stringify({ lastReport }));
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
expect(telemetrySender['lastReported']).toBe(lastReport);
});
});
describe('saveToBrowser', () => {
it('uses lastReport', () => {
const lastReport = `${Date.now()}`;
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['lastReported'] = lastReport;
telemetrySender['saveToBrowser']();
expect(mockLocalStorage.setItem).toHaveBeenCalledTimes(1);
expect(mockLocalStorage.setItem).toHaveBeenCalledWith(
LOCALSTORAGE_KEY,
JSON.stringify({ lastReport })
);
});
});
describe('shouldSendReport', () => {
it('returns false whenever optIn is false', () => {
const telemetryService = mockTelemetryService();
telemetryService.getIsOptedIn = jest.fn().mockReturnValue(false);
const telemetrySender = new TelemetrySender(telemetryService);
const shouldSendRerpot = telemetrySender['shouldSendReport']();
expect(telemetryService.getIsOptedIn).toBeCalledTimes(1);
expect(shouldSendRerpot).toBe(false);
});
it('returns true if lastReported is undefined', () => {
const telemetryService = mockTelemetryService();
telemetryService.getIsOptedIn = jest.fn().mockReturnValue(true);
const telemetrySender = new TelemetrySender(telemetryService);
const shouldSendRerpot = telemetrySender['shouldSendReport']();
expect(telemetrySender['lastReported']).toBeUndefined();
expect(shouldSendRerpot).toBe(false);
});
it('returns true if lastReported passed REPORT_INTERVAL_MS', () => {
const lastReported = Date.now() - (REPORT_INTERVAL_MS + 1000);
const telemetryService = mockTelemetryService();
telemetryService.getIsOptedIn = jest.fn().mockReturnValue(true);
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['lastReported'] = `${lastReported}`;
const shouldSendRerpot = telemetrySender['shouldSendReport']();
expect(shouldSendRerpot).toBe(false);
});
it('returns false if lastReported is within REPORT_INTERVAL_MS', () => {
const lastReported = Date.now() + 1000;
const telemetryService = mockTelemetryService();
telemetryService.getIsOptedIn = jest.fn().mockReturnValue(true);
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['lastReported'] = `${lastReported}`;
const shouldSendRerpot = telemetrySender['shouldSendReport']();
expect(shouldSendRerpot).toBe(false);
});
it('returns true if lastReported is malformed', () => {
const telemetryService = mockTelemetryService();
telemetryService.getIsOptedIn = jest.fn().mockReturnValue(true);
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['lastReported'] = `random_malformed_string`;
const shouldSendRerpot = telemetrySender['shouldSendReport']();
expect(shouldSendRerpot).toBe(false);
});
describe('sendIfDue', () => {
let originalFetch: typeof window['fetch'];
let mockFetch: jest.Mock<typeof window['fetch']>;
beforeAll(() => {
originalFetch = window.fetch;
});
// @ts-ignore
beforeEach(() => (window.fetch = mockFetch = jest.fn()));
// @ts-ignore
afterAll(() => (window.fetch = originalFetch));
it('does not send if already sending', async () => {
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['shouldSendReport'] = jest.fn();
telemetrySender['isSending'] = true;
await telemetrySender['sendIfDue']();
expect(telemetrySender['shouldSendReport']).toBeCalledTimes(0);
expect(mockFetch).toBeCalledTimes(0);
});
it('does not send if shouldSendReport returns false', async () => {
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender['shouldSendReport'] = jest.fn().mockReturnValue(false);
telemetrySender['isSending'] = false;
await telemetrySender['sendIfDue']();
expect(telemetrySender['shouldSendReport']).toBeCalledTimes(1);
expect(mockFetch).toBeCalledTimes(0);
});
it('sends report if due', async () => {
const mockTelemetryUrl = 'telemetry_cluster_url';
const mockTelemetryPayload = ['hashed_cluster_usage_data1'];
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetryService.getTelemetryUrl = jest.fn().mockReturnValue(mockTelemetryUrl);
telemetryService.fetchTelemetry = jest.fn().mockReturnValue(mockTelemetryPayload);
telemetrySender['shouldSendReport'] = jest.fn().mockReturnValue(true);
telemetrySender['isSending'] = false;
await telemetrySender['sendIfDue']();
expect(telemetryService.fetchTelemetry).toBeCalledTimes(0);
expect(mockFetch).toBeCalledTimes(0);
});
it('sends report separately for every cluster', async () => {
const mockTelemetryUrl = 'telemetry_cluster_url';
const mockTelemetryPayload = ['hashed_cluster_usage_data1', 'hashed_cluster_usage_data2'];
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetryService.getTelemetryUrl = jest.fn().mockReturnValue(mockTelemetryUrl);
telemetryService.fetchTelemetry = jest.fn().mockReturnValue(mockTelemetryPayload);
telemetrySender['shouldSendReport'] = jest.fn().mockReturnValue(true);
telemetrySender['isSending'] = false;
await telemetrySender['sendIfDue']();
expect(telemetryService.fetchTelemetry).toBeCalledTimes(0);
expect(mockFetch).toBeCalledTimes(0);
});
it('updates last lastReported and calls saveToBrowser', async () => {
const mockTelemetryUrl = 'telemetry_cluster_url';
const mockTelemetryPayload = ['hashed_cluster_usage_data1'];
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetryService.getTelemetryUrl = jest.fn().mockReturnValue(mockTelemetryUrl);
telemetryService.fetchTelemetry = jest.fn().mockReturnValue(mockTelemetryPayload);
telemetrySender['shouldSendReport'] = jest.fn().mockReturnValue(true);
telemetrySender['saveToBrowser'] = jest.fn();
await telemetrySender['sendIfDue']();
expect(mockFetch).toBeCalledTimes(0);
expect(telemetrySender['lastReported']).toBeDefined();
expect(telemetrySender['saveToBrowser']).toBeCalledTimes(1);
expect(telemetrySender['isSending']).toBe(false);
});
it('catches fetchTelemetry errors and sets isSending to false', async () => {
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetryService.getTelemetryUrl = jest.fn();
telemetryService.fetchTelemetry = jest.fn().mockImplementation(() => {
throw Error('Error fetching usage');
});
await telemetrySender['sendIfDue']();
expect(telemetryService.fetchTelemetry).toBeCalledTimes(0);
expect(telemetrySender['lastReported']).toBeUndefined();
expect(telemetrySender['isSending']).toBe(false);
});
it('catches fetch errors and sets isSending to false', async () => {
const mockTelemetryPayload = ['hashed_cluster_usage_data1', 'hashed_cluster_usage_data2'];
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetryService.getTelemetryUrl = jest.fn();
telemetryService.fetchTelemetry = jest.fn().mockReturnValue(mockTelemetryPayload);
mockFetch.mockImplementation(() => {
throw Error('Error sending usage');
});
await telemetrySender['sendIfDue']();
expect(telemetryService.fetchTelemetry).toBeCalledTimes(0);
expect(mockFetch).toBeCalledTimes(0);
expect(telemetrySender['lastReported']).toBeUndefined();
expect(telemetrySender['isSending']).toBe(false);
});
});
});
describe('startChecking', () => {
let originalSetInterval: typeof window['setInterval'];
let mockSetInterval: jest.Mock<typeof window['setInterval']>;
beforeAll(() => {
originalSetInterval = window.setInterval;
});
// @ts-ignore
beforeEach(() => (window.setInterval = mockSetInterval = jest.fn()));
// @ts-ignore
afterAll(() => (window.setInterval = originalSetInterval));
it('calls sendIfDue every 60000 ms', () => {
const telemetryService = mockTelemetryService();
const telemetrySender = new TelemetrySender(telemetryService);
telemetrySender.startChecking();
expect(mockSetInterval).toBeCalledTimes(1);
expect(mockSetInterval).toBeCalledWith(telemetrySender['sendIfDue'], 60000);
});
});
}); | the_stack |
jest.mock('../../src/js/wrapper', () => {
return {
NATIVE: {
fetchNativeFrames: jest.fn(),
disableNativeFramesTracking: jest.fn(),
enableNative: true,
},
};
});
import { Transaction } from '@sentry/tracing';
import { EventProcessor } from '@sentry/types';
import { NativeFramesInstrumentation } from '../../src/js/tracing/nativeframes';
import { NATIVE } from '../../src/js/wrapper';
import { mockFunction } from '../testutils';
beforeEach(() => {
jest.useFakeTimers();
});
describe('NativeFramesInstrumentation', () => {
it('Sets start frames to trace context on transaction start.', (done) => {
const startFrames = {
totalFrames: 100,
slowFrames: 20,
frozenFrames: 5,
};
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(startFrames);
const instance = new NativeFramesInstrumentation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_eventProcessor) => {},
() => true
);
const transaction = new Transaction({ name: 'test' });
instance.onTransactionStart(transaction);
setImmediate(() => {
expect(transaction.data.__startFrames).toMatchObject(startFrames);
expect(transaction.getTraceContext().data?.__startFrames).toMatchObject(
startFrames
);
done();
});
});
it('Sets measurements on the transaction event and removes startFrames from trace context.', (done) => {
const startFrames = {
totalFrames: 100,
slowFrames: 20,
frozenFrames: 5,
};
const finishFrames = {
totalFrames: 200,
slowFrames: 40,
frozenFrames: 10,
};
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(startFrames);
let eventProcessor: EventProcessor;
const instance = new NativeFramesInstrumentation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_eventProcessor) => {
eventProcessor = _eventProcessor;
},
() => true
);
const transaction = new Transaction({ name: 'test' });
instance.onTransactionStart(transaction);
setImmediate(() => {
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(finishFrames);
const finishTimestamp = Date.now() / 1000;
instance.onTransactionFinish(transaction);
setImmediate(async () => {
try {
expect(eventProcessor).toBeDefined();
if (eventProcessor) {
const event = await eventProcessor({
event_id: '0',
type: 'transaction',
transaction: transaction.name,
contexts: {
trace: transaction.getTraceContext(),
},
start_timestamp: finishTimestamp - 10,
timestamp: finishTimestamp,
});
jest.runOnlyPendingTimers();
// This setImmediate needs to be here for the assertions to not be caught by the promise handler.
expect(event).toBeDefined();
if (event) {
expect(event.measurements).toBeDefined();
if (event.measurements) {
expect(event.measurements.frames_total.value).toBe(
finishFrames.totalFrames - startFrames.totalFrames
);
expect(event.measurements.frames_slow.value).toBe(
finishFrames.slowFrames - startFrames.slowFrames
);
expect(event.measurements.frames_frozen.value).toBe(
finishFrames.frozenFrames - startFrames.frozenFrames
);
}
expect(event.contexts?.trace?.data).toBeDefined();
if (event.contexts?.trace?.data) {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(event.contexts.trace.data as any).__startFrames
).toBeUndefined();
}
}
}
done();
} catch (e) {
done(e);
}
});
});
});
it('Does not set measurements on transactions without startFrames.', (done) => {
const finishFrames = {
totalFrames: 200,
slowFrames: 40,
frozenFrames: 10,
};
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(finishFrames);
let eventProcessor: EventProcessor;
const instance = new NativeFramesInstrumentation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_eventProcessor) => {
eventProcessor = _eventProcessor;
},
() => true
);
const transaction = new Transaction({ name: 'test' });
transaction.setData('test', {});
setImmediate(() => {
const finishTimestamp = Date.now() / 1000;
instance.onTransactionFinish(transaction);
setImmediate(async () => {
expect(eventProcessor).toBeDefined();
if (eventProcessor) {
const event = await eventProcessor({
event_id: '0',
type: 'transaction',
transaction: transaction.name,
contexts: {
trace: transaction.getTraceContext(),
},
start_timestamp: finishTimestamp - 10,
timestamp: finishTimestamp,
measurements: {},
});
jest.runOnlyPendingTimers();
// This setImmediate needs to be here for the assertions to not be caught by the promise handler.
setImmediate(() => {
expect(event).toBeDefined();
if (event) {
expect(event.measurements).toBeDefined();
if (event.measurements) {
expect(event.measurements.frames_total).toBeUndefined();
expect(event.measurements.frames_slow).toBeUndefined();
expect(event.measurements.frames_frozen).toBeUndefined();
}
expect(event.contexts?.trace?.data).toBeDefined();
if (event.contexts?.trace?.data) {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(event.contexts.trace.data as any).__startFrames
).toBeUndefined();
}
}
done();
});
}
});
});
});
it('Sets measurements on the transaction event and removes startFrames if finishFrames is null.', (done) => {
const startFrames = {
totalFrames: 100,
slowFrames: 20,
frozenFrames: 5,
};
const finishFrames = null;
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(startFrames);
let eventProcessor: EventProcessor;
const instance = new NativeFramesInstrumentation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_eventProcessor) => {
eventProcessor = _eventProcessor;
},
() => true
);
const transaction = new Transaction({ name: 'test' });
instance.onTransactionStart(transaction);
setImmediate(() => {
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(finishFrames);
const finishTimestamp = Date.now() / 1000;
instance.onTransactionFinish(transaction);
setImmediate(async () => {
try {
expect(eventProcessor).toBeDefined();
if (eventProcessor) {
const event = await eventProcessor({
event_id: '0',
type: 'transaction',
transaction: transaction.name,
contexts: {
trace: transaction.getTraceContext(),
},
start_timestamp: finishTimestamp - 10,
timestamp: finishTimestamp,
});
jest.runOnlyPendingTimers();
expect(event).toBeDefined();
if (event) {
expect(event.measurements).toBeUndefined();
expect(event.contexts?.trace?.data).toBeDefined();
if (event.contexts?.trace?.data) {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(event.contexts.trace.data as any).__startFrames
).toBeUndefined();
}
}
}
done();
} catch (e) {
done(e);
}
});
});
});
it('Does not set measurements on the transaction event and removes startFrames if finishFrames times out.', (done) => {
jest.useRealTimers();
const startFrames = {
totalFrames: 100,
slowFrames: 20,
frozenFrames: 5,
};
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockResolvedValue(startFrames);
let eventProcessor: EventProcessor;
const instance = new NativeFramesInstrumentation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
(_eventProcessor) => {
eventProcessor = _eventProcessor;
},
() => true
);
const transaction = new Transaction({ name: 'test' });
instance.onTransactionStart(transaction);
setImmediate(() => {
// eslint-disable-next-line @typescript-eslint/unbound-method
mockFunction(NATIVE.fetchNativeFrames).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-empty-function
async () => new Promise(() => {})
);
const finishTimestamp = Date.now() / 1000;
instance.onTransactionFinish(transaction);
setImmediate(async () => {
try {
expect(eventProcessor).toBeDefined();
if (eventProcessor) {
const event = await eventProcessor({
event_id: '0',
type: 'transaction',
transaction: transaction.name,
contexts: {
trace: transaction.getTraceContext(),
},
start_timestamp: finishTimestamp - 10,
timestamp: finishTimestamp,
});
expect(event).toBeDefined();
if (event) {
expect(event.measurements).toBeUndefined();
expect(event.contexts?.trace?.data).toBeDefined();
if (event.contexts?.trace?.data) {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(event.contexts.trace.data as any).__startFrames
).toBeUndefined();
}
}
}
done();
} catch (e) {
done(e);
}
});
});
});
}); | the_stack |
module PhaserAds {
export module AdProvider {
export enum GameDistributionAdType {
interstitial = 'interstitial',
rewarded = 'rewarded',
display = 'display'
}
export enum GameDistributionBannerSize {
LargeRectangle, // 336x280
MediumRectangle, // 300x250
Billboard, // 970x250
Leaderboard, // 728x90
Skyscraper, // 120x600
WideSkyscraper // 160x600
}
export enum GameDistributionAlignment {
TopLeft,
TopCenter,
TopRight,
CenterLeft,
Center,
CenterRight,
BottomLeft,
BottomCenter,
BottomRight
}
export class GameDistributionBanner {
public element: HTMLElement;
private resizeListener: () => void;
private parent: HTMLElement;
private alignment: GameDistributionAlignment;
private width: number;
private height: number;
private offsetX: number = 0;
private offsetY: number = 0;
constructor() {
this.element = document.createElement('div');
this.element.style.position = 'absolute';
this.element.style.top = `0px`;
this.element.style.left = `0px`;
this.element.id = `banner-${Date.now()}${Math.random() * 10000000 | 0}`;
document.body.appendChild(this.element);
};
public loadBanner(): void {
return gdsdk.showAd(GameDistributionAdType.display, {
containerId: this.element.id
});
}
public destroy(): void {
document.body.removeChild(this.element);
this.element = null;
this.parent = null;
this.alignment = null;
if (this.resizeListener) {
window.removeEventListener('resize', this.resizeListener);
}
}
public alignIn(element: HTMLElement, position: GameDistributionAlignment): void {
this.parent = element;
this.alignment = position;
this.resizeListener = () => this.resize();
window.addEventListener('resize', this.resizeListener);
this.resize();
}
public setOffset(x: number = 0, y: number = 0): void {
this.offsetX = x;
this.offsetY = y;
this.resize();
}
private resize(): void {
const parentBoundingRect: ClientRect = this.parent.getBoundingClientRect();
switch (this.alignment) {
case GameDistributionAlignment.TopLeft:
this.position(
parentBoundingRect.left,
parentBoundingRect.top
);
break;
case GameDistributionAlignment.TopCenter:
this.position(
parentBoundingRect.left + parentBoundingRect.width / 2 - this.width / 2,
parentBoundingRect.top
);
break;
case GameDistributionAlignment.TopRight:
this.position(
parentBoundingRect.left + parentBoundingRect.width - this.width,
parentBoundingRect.top
);
break;
case GameDistributionAlignment.CenterLeft:
this.position(
parentBoundingRect.left,
parentBoundingRect.top + parentBoundingRect.height / 2 - this.height / 2
);
break;
case GameDistributionAlignment.Center:
this.position(
parentBoundingRect.left + parentBoundingRect.width / 2 - this.width / 2,
parentBoundingRect.top + parentBoundingRect.height / 2 - this.height / 2
);
break;
case GameDistributionAlignment.CenterRight:
this.position(
parentBoundingRect.left + parentBoundingRect.width - this.width,
parentBoundingRect.top + parentBoundingRect.height / 2 - this.height / 2
);
break;
case GameDistributionAlignment.BottomLeft:
this.position(
parentBoundingRect.left,
parentBoundingRect.top + parentBoundingRect.height - this.height
);
break;
case GameDistributionAlignment.BottomCenter:
this.position(
parentBoundingRect.left + parentBoundingRect.width / 2 - this.width / 2,
parentBoundingRect.top + parentBoundingRect.height - this.height
);
break;
case GameDistributionAlignment.BottomRight:
this.position(
parentBoundingRect.left + parentBoundingRect.width - this.width,
parentBoundingRect.top + parentBoundingRect.height - this.height
);
break;
}
}
public setSize(size: GameDistributionBannerSize): void {
let width: number, height: number;
switch (size) {
default:
case GameDistributionBannerSize.LargeRectangle:
width = 336;
height = 280;
break;
case GameDistributionBannerSize.MediumRectangle:
width = 300;
height = 250;
break;
case GameDistributionBannerSize.Billboard:
width = 970;
height = 250;
break;
case GameDistributionBannerSize.Leaderboard:
width = 728;
height = 90;
break;
case GameDistributionBannerSize.Skyscraper:
width = 120;
height = 600;
break;
case GameDistributionBannerSize.WideSkyscraper:
width = 160;
height = 600;
break;
}
this.width = width;
this.height = height;
this.element.style.width = `${width}px`;
this.element.style.height = `${height}px`;
}
public position(x: number, y: number): void {
this.element.style.left = `${x + this.offsetX}px`;
this.element.style.top = `${y + this.offsetY}px`;
}
}
export class GameDistributionAds implements PhaserAds.AdProvider.IProvider {
public adManager: AdManager;
public adsEnabled: boolean = true;
public hasRewarded: boolean = false;
constructor(game: Phaser.Game, gameId: string, userId: string = '') {
this.areAdsEnabled();
GD_OPTIONS = <IGameDistributionSettings>{
gameId: gameId,
advertisementSettings: {
autoplay: false
},
onEvent: (event: any): void => {
switch (event.name as string) {
case 'SDK_GAME_PAUSE':
// pause game logic / mute audio
this.adManager.onContentPaused.dispatch();
break;
default:
break;
}
}
};
//Include script. even when adblock is enabled, this script also allows us to track our users;
(function (d: Document, s: string, id: string): void {
let js: HTMLScriptElement;
let fjs: HTMLScriptElement = <HTMLScriptElement>d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = <HTMLScriptElement>d.createElement(s);
js.id = id;
js.src = '//html5.api.gamedistribution.com/main.min.js';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'gamedistribution-jssdk'));
}
public setManager(manager: PhaserAds.AdManager): void {
this.adManager = manager;
}
public showAd(adType: AdType, containerId?: string): void {
if (!this.adsEnabled) {
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch();
return;
}
if (typeof gdsdk === 'undefined' || (gdsdk && typeof gdsdk.showAd === 'undefined')) {
//So gdApi isn't available OR
//gdApi is available, but showBanner is not there (weird but can happen)
this.adsEnabled = false;
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch();
return;
}
if (adType === PhaserAds.AdType.rewarded && this.hasRewarded === false) {
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch();
return;
}
gdsdk.showAd((adType === PhaserAds.AdType.rewarded) ? GameDistributionAdType.rewarded : GameDistributionAdType.interstitial).then(() => {
if (adType === PhaserAds.AdType.rewarded && this.hasRewarded === true) {
this.adManager.onAdRewardGranted.dispatch();
this.hasRewarded = false;
}
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch();
}).catch(() => {
if (adType === PhaserAds.AdType.rewarded && this.hasRewarded === true) {
this.hasRewarded = false;
}
this.adManager.unMuteAfterAd();
this.adManager.onContentResumed.dispatch();
});
}
public loadBanner(size: GameDistributionBannerSize): GameDistributionBanner {
const banner: GameDistributionBanner = new GameDistributionBanner();
banner.setSize(size);
banner.loadBanner();
return banner;
}
//Does nothing, but needed for Provider interface
public preloadAd(adType: PhaserAds.AdType): void {
if (this.hasRewarded) {
return;
}
gdsdk.preloadAd(GameDistributionAdType.rewarded).then(() => {
this.hasRewarded = true;
this.adManager.onAdLoaded.dispatch(adType);
});
}
//Does nothing, but needed for Provider interface
public destroyAd(): void {
return;
}
//Does nothing, but needed for Provider interface
public hideAd(): void {
return;
}
/**
* Checks if the ads are enabled (e.g; adblock is enabled or not)
* @returns {boolean}
*/
private areAdsEnabled(): void {
let test: HTMLElement = document.createElement('div');
test.innerHTML = ' ';
test.className = 'adsbox';
test.style.position = 'absolute';
test.style.fontSize = '10px';
document.body.appendChild(test);
// let adsEnabled: boolean;
let isEnabled: () => boolean = () => {
let enabled: boolean = true;
if (test.offsetHeight === 0) {
enabled = false;
}
test.parentNode.removeChild(test);
return enabled;
};
window.setTimeout(() => {
this.adsEnabled = isEnabled();
}, 100);
}
}
}
} | the_stack |
import { XmlGeneralNode, XmlNode, XmlParser, XmlTextNode } from '../xml';
import { Zip } from '../zip';
import { Docx } from './docx';
export class DocxParser {
/*
* Word markup intro:
*
* In Word text nodes are contained in "run" nodes (which specifies text
* properties such as font and color). The "run" nodes in turn are
* contained in paragraph nodes which is the core unit of content.
*
* Example:
*
* <w:p> <-- paragraph
* <w:r> <-- run
* <w:rPr> <-- run properties
* <w:b/> <-- bold
* </w:rPr>
* <w:t>This is text.</w:t> <-- actual text
* </w:r>
* </w:p>
*
* see: http://officeopenxml.com/WPcontentOverview.php
*/
public static readonly PARAGRAPH_NODE = 'w:p';
public static readonly PARAGRAPH_PROPERTIES_NODE = 'w:pPr';
public static readonly RUN_NODE = 'w:r';
public static readonly RUN_PROPERTIES_NODE = 'w:rPr';
public static readonly TEXT_NODE = 'w:t';
public static readonly TABLE_ROW_NODE = 'w:tr';
public static readonly TABLE_CELL_NODE = 'w:tc';
public static readonly NUMBER_PROPERTIES_NODE = 'w:numPr';
//
// constructor
//
constructor(
private readonly xmlParser: XmlParser
) {
}
//
// parse document
//
public load(zip: Zip): Promise<Docx> {
return Docx.open(zip, this.xmlParser);
}
//
// content manipulation
//
/**
* Split the text node into two text nodes, each with it's own wrapping <w:t> node.
* Returns the newly created text node.
*
* @param textNode
* @param splitIndex
* @param addBefore Should the new node be added before or after the original node.
*/
public splitTextNode(textNode: XmlTextNode, splitIndex: number, addBefore: boolean): XmlTextNode {
let firstXmlTextNode: XmlTextNode;
let secondXmlTextNode: XmlTextNode;
// split nodes
const wordTextNode = this.containingTextNode(textNode);
const newWordTextNode = XmlNode.cloneNode(wordTextNode, true);
// set space preserve to prevent display differences after splitting
// (otherwise if there was a space in the middle of the text node and it
// is now at the beginning or end of the text node it will be ignored)
this.setSpacePreserveAttribute(wordTextNode);
this.setSpacePreserveAttribute(newWordTextNode);
if (addBefore) {
// insert new node before existing one
XmlNode.insertBefore(newWordTextNode, wordTextNode);
firstXmlTextNode = XmlNode.lastTextChild(newWordTextNode);
secondXmlTextNode = textNode;
} else {
// insert new node after existing one
const curIndex = wordTextNode.parentNode.childNodes.indexOf(wordTextNode);
XmlNode.insertChild(wordTextNode.parentNode, newWordTextNode, curIndex + 1);
firstXmlTextNode = textNode;
secondXmlTextNode = XmlNode.lastTextChild(newWordTextNode);
}
// edit text
const firstText = firstXmlTextNode.textContent;
const secondText = secondXmlTextNode.textContent;
firstXmlTextNode.textContent = firstText.substring(0, splitIndex);
secondXmlTextNode.textContent = secondText.substring(splitIndex);
return (addBefore ? firstXmlTextNode : secondXmlTextNode);
}
/**
* Split the paragraph around the specified text node.
*
* @returns Two paragraphs - `left` and `right`. If the `removeTextNode` argument is
* `false` then the original text node is the first text node of `right`.
*/
public splitParagraphByTextNode(paragraph: XmlNode, textNode: XmlTextNode, removeTextNode: boolean): [XmlNode, XmlNode] {
// input validation
const containingParagraph = this.containingParagraphNode(textNode);
if (containingParagraph != paragraph)
throw new Error(`Node '${nameof(textNode)}' is not a descendant of '${nameof(paragraph)}'.`);
const runNode = this.containingRunNode(textNode);
const wordTextNode = this.containingTextNode(textNode);
// create run clone
const leftRun = XmlNode.cloneNode(runNode, false);
const rightRun = runNode;
XmlNode.insertBefore(leftRun, rightRun);
// copy props from original run node (preserve style)
const runProps = rightRun.childNodes.find(node => node.nodeName === DocxParser.RUN_PROPERTIES_NODE);
if (runProps) {
const leftRunProps = XmlNode.cloneNode(runProps, true);
XmlNode.appendChild(leftRun, leftRunProps);
}
// move nodes from 'right' to 'left'
const firstRunChildIndex = (runProps ? 1 : 0);
let curChild = rightRun.childNodes[firstRunChildIndex];
while (curChild != wordTextNode) {
XmlNode.remove(curChild);
XmlNode.appendChild(leftRun, curChild);
curChild = rightRun.childNodes[firstRunChildIndex];
}
// remove text node
if (removeTextNode) {
XmlNode.removeChild(rightRun, firstRunChildIndex);
}
// create paragraph clone
const leftPara = XmlNode.cloneNode(containingParagraph, false);
const rightPara = containingParagraph;
XmlNode.insertBefore(leftPara, rightPara);
// copy props from original paragraph (preserve style)
const paragraphProps = rightPara.childNodes.find(node => node.nodeName === DocxParser.PARAGRAPH_PROPERTIES_NODE);
if (paragraphProps) {
const leftParagraphProps = XmlNode.cloneNode(paragraphProps, true);
XmlNode.appendChild(leftPara, leftParagraphProps);
}
// move nodes from 'right' to 'left'
const firstParaChildIndex = (paragraphProps ? 1 : 0);
curChild = rightPara.childNodes[firstParaChildIndex];
while (curChild != rightRun) {
XmlNode.remove(curChild);
XmlNode.appendChild(leftPara, curChild);
curChild = rightPara.childNodes[firstParaChildIndex];
}
// clean paragraphs - remove empty runs
if (this.isEmptyRun(leftRun))
XmlNode.remove(leftRun);
if (this.isEmptyRun(rightRun))
XmlNode.remove(rightRun);
return [leftPara, rightPara];
}
/**
* Move all text between the 'from' and 'to' nodes to the 'from' node.
*/
public joinTextNodesRange(from: XmlTextNode, to: XmlTextNode): void {
// find run nodes
const firstRunNode = this.containingRunNode(from);
const secondRunNode = this.containingRunNode(to);
const paragraphNode = firstRunNode.parentNode;
if (secondRunNode.parentNode !== paragraphNode)
throw new Error('Can not join text nodes from separate paragraphs.');
// find "word text nodes"
const firstWordTextNode = this.containingTextNode(from);
const secondWordTextNode = this.containingTextNode(to);
const totalText: string[] = [];
// iterate runs
let curRunNode = firstRunNode;
while (curRunNode) {
// iterate text nodes
let curWordTextNode: XmlNode;
if (curRunNode === firstRunNode) {
curWordTextNode = firstWordTextNode;
} else {
curWordTextNode = this.firstTextNodeChild(curRunNode);
}
while (curWordTextNode) {
if (curWordTextNode.nodeName !== DocxParser.TEXT_NODE)
continue;
// move text to first node
const curXmlTextNode = XmlNode.lastTextChild(curWordTextNode);
totalText.push(curXmlTextNode.textContent);
// next text node
const textToRemove = curWordTextNode;
if (curWordTextNode === secondWordTextNode) {
curWordTextNode = null;
} else {
curWordTextNode = curWordTextNode.nextSibling;
}
// remove current text node
if (textToRemove !== firstWordTextNode) {
XmlNode.remove(textToRemove);
}
}
// next run
const runToRemove = curRunNode;
if (curRunNode === secondRunNode) {
curRunNode = null;
} else {
curRunNode = curRunNode.nextSibling;
}
// remove current run
if (!runToRemove.childNodes || !runToRemove.childNodes.length) {
XmlNode.remove(runToRemove);
}
}
// set the text content
const firstXmlTextNode = XmlNode.lastTextChild(firstWordTextNode);
firstXmlTextNode.textContent = totalText.join('');
}
/**
* Take all runs from 'second' and move them to 'first'.
*/
public joinParagraphs(first: XmlNode, second: XmlNode): void {
if (first === second)
return;
let childIndex = 0;
while (second.childNodes && childIndex < second.childNodes.length) {
const curChild = second.childNodes[childIndex];
if (curChild.nodeName === DocxParser.RUN_NODE) {
XmlNode.removeChild(second, childIndex);
XmlNode.appendChild(first, curChild);
} else {
childIndex++;
}
}
}
public setSpacePreserveAttribute(node: XmlGeneralNode): void {
if (!node.attributes) {
node.attributes = {};
}
if (!node.attributes['xml:space']) {
node.attributes['xml:space'] = 'preserve';
}
}
//
// node queries
//
public isTextNode(node: XmlNode): boolean {
return node.nodeName === DocxParser.TEXT_NODE;
}
public isRunNode(node: XmlNode): boolean {
return node.nodeName === DocxParser.RUN_NODE;
}
public isRunPropertiesNode(node: XmlNode): boolean {
return node.nodeName === DocxParser.RUN_PROPERTIES_NODE;
}
public isTableCellNode(node: XmlNode): boolean {
return node.nodeName === DocxParser.TABLE_CELL_NODE;
}
public isParagraphNode(node: XmlNode): boolean {
return node.nodeName === DocxParser.PARAGRAPH_NODE;
}
public isListParagraph(paragraphNode: XmlNode): boolean {
const paragraphProperties = this.paragraphPropertiesNode(paragraphNode);
const listNumberProperties = XmlNode.findChildByName(paragraphProperties, DocxParser.NUMBER_PROPERTIES_NODE);
return !!listNumberProperties;
}
public paragraphPropertiesNode(paragraphNode: XmlNode): XmlNode {
if (!this.isParagraphNode(paragraphNode))
throw new Error(`Expected paragraph node but received a '${paragraphNode.nodeName}' node.`);
return XmlNode.findChildByName(paragraphNode, DocxParser.PARAGRAPH_PROPERTIES_NODE);
}
/**
* Search for the first direct child **Word** text node (i.e. a <w:t> node).
*/
public firstTextNodeChild(node: XmlNode): XmlNode {
if (!node)
return null;
if (node.nodeName !== DocxParser.RUN_NODE)
return null;
if (!node.childNodes)
return null;
for (const child of node.childNodes) {
if (child.nodeName === DocxParser.TEXT_NODE)
return child;
}
return null;
}
/**
* Search **upwards** for the first **Word** text node (i.e. a <w:t> node).
*/
public containingTextNode(node: XmlTextNode): XmlGeneralNode {
if (!node)
return null;
if (!XmlNode.isTextNode(node))
throw new Error(`'Invalid argument ${nameof(node)}. Expected a XmlTextNode.`);
return XmlNode.findParentByName(node, DocxParser.TEXT_NODE) as XmlGeneralNode;
}
/**
* Search **upwards** for the first run node.
*/
public containingRunNode(node: XmlNode): XmlNode {
return XmlNode.findParentByName(node, DocxParser.RUN_NODE);
}
/**
* Search **upwards** for the first paragraph node.
*/
public containingParagraphNode(node: XmlNode): XmlNode {
return XmlNode.findParentByName(node, DocxParser.PARAGRAPH_NODE);
}
/**
* Search **upwards** for the first "table row" node.
*/
public containingTableRowNode(node: XmlNode): XmlNode {
return XmlNode.findParentByName(node, DocxParser.TABLE_ROW_NODE);
}
//
// advanced node queries
//
public isEmptyTextNode(node: XmlNode): boolean {
if (!this.isTextNode(node))
throw new Error(`Text node expected but '${node.nodeName}' received.`);
if (!node.childNodes?.length)
return true;
const xmlTextNode = node.childNodes[0];
if (!XmlNode.isTextNode(xmlTextNode))
throw new Error("Invalid XML structure. 'w:t' node should contain a single text node only.");
if (!xmlTextNode.textContent)
return true;
return false;
}
public isEmptyRun(node: XmlNode): boolean {
if (!this.isRunNode(node))
throw new Error(`Run node expected but '${node.nodeName}' received.`);
for (const child of (node.childNodes ?? [])) {
if (this.isRunPropertiesNode(child))
continue;
if (this.isTextNode(child) && this.isEmptyTextNode(child))
continue;
return false;
}
return true;
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/hcxEnterpriseSitesMappers";
import * as Parameters from "../models/parameters";
import { AvsClientContext } from "../avsClientContext";
/** Class representing a HcxEnterpriseSites. */
export class HcxEnterpriseSites {
private readonly client: AvsClientContext;
/**
* Create a HcxEnterpriseSites.
* @param {AvsClientContext} client Reference to the service client.
*/
constructor(client: AvsClientContext) {
this.client = client;
}
/**
* @summary List HCX Enterprise Sites in a private cloud
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param [options] The optional parameters
* @returns Promise<Models.HcxEnterpriseSitesListResponse>
*/
list(resourceGroupName: string, privateCloudName: string, options?: msRest.RequestOptionsBase): Promise<Models.HcxEnterpriseSitesListResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param callback The callback
*/
list(resourceGroupName: string, privateCloudName: string, callback: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param options The optional parameters
* @param callback The callback
*/
list(resourceGroupName: string, privateCloudName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): void;
list(resourceGroupName: string, privateCloudName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HcxEnterpriseSiteList>, callback?: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): Promise<Models.HcxEnterpriseSitesListResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
privateCloudName,
options
},
listOperationSpec,
callback) as Promise<Models.HcxEnterpriseSitesListResponse>;
}
/**
* @summary Get an HCX Enterprise Site by name in a private cloud
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param [options] The optional parameters
* @returns Promise<Models.HcxEnterpriseSitesGetResponse>
*/
get(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options?: msRest.RequestOptionsBase): Promise<Models.HcxEnterpriseSitesGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param callback The callback
*/
get(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, callback: msRest.ServiceCallback<Models.HcxEnterpriseSite>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HcxEnterpriseSite>): void;
get(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HcxEnterpriseSite>, callback?: msRest.ServiceCallback<Models.HcxEnterpriseSite>): Promise<Models.HcxEnterpriseSitesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
privateCloudName,
hcxEnterpriseSiteName,
options
},
getOperationSpec,
callback) as Promise<Models.HcxEnterpriseSitesGetResponse>;
}
/**
* @summary Create or update an HCX Enterprise Site in a private cloud
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName The name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param hcxEnterpriseSite The HCX Enterprise Site
* @param [options] The optional parameters
* @returns Promise<Models.HcxEnterpriseSitesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, hcxEnterpriseSite: any, options?: msRest.RequestOptionsBase): Promise<Models.HcxEnterpriseSitesCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName The name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param hcxEnterpriseSite The HCX Enterprise Site
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, hcxEnterpriseSite: any, callback: msRest.ServiceCallback<Models.HcxEnterpriseSite>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName The name of the private cloud.
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param hcxEnterpriseSite The HCX Enterprise Site
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, hcxEnterpriseSite: any, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HcxEnterpriseSite>): void;
createOrUpdate(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, hcxEnterpriseSite: any, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HcxEnterpriseSite>, callback?: msRest.ServiceCallback<Models.HcxEnterpriseSite>): Promise<Models.HcxEnterpriseSitesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
privateCloudName,
hcxEnterpriseSiteName,
hcxEnterpriseSite,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.HcxEnterpriseSitesCreateOrUpdateResponse>;
}
/**
* @summary Delete an HCX Enterprise Site in a private cloud
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param privateCloudName Name of the private cloud
* @param hcxEnterpriseSiteName Name of the HCX Enterprise Site in the private cloud
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, privateCloudName: string, hcxEnterpriseSiteName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
privateCloudName,
hcxEnterpriseSiteName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* @summary List HCX Enterprise Sites in a private cloud
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.HcxEnterpriseSitesListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.HcxEnterpriseSitesListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.HcxEnterpriseSiteList>, callback?: msRest.ServiceCallback<Models.HcxEnterpriseSiteList>): Promise<Models.HcxEnterpriseSitesListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.HcxEnterpriseSitesListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/hcxEnterpriseSites",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.privateCloudName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.HcxEnterpriseSiteList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/hcxEnterpriseSites/{hcxEnterpriseSiteName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.privateCloudName,
Parameters.hcxEnterpriseSiteName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.HcxEnterpriseSite
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/hcxEnterpriseSites/{hcxEnterpriseSiteName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.privateCloudName,
Parameters.hcxEnterpriseSiteName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "hcxEnterpriseSite",
mapper: {
required: true,
serializedName: "hcxEnterpriseSite",
type: {
name: "Object"
}
}
},
responses: {
200: {
bodyMapper: Mappers.HcxEnterpriseSite
},
201: {
bodyMapper: Mappers.HcxEnterpriseSite
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/hcxEnterpriseSites/{hcxEnterpriseSiteName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.privateCloudName,
Parameters.hcxEnterpriseSiteName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.HcxEnterpriseSiteList
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import createLayout from 'justified-layout'
import { profileLibraryLayout, profileThumbnailRenderer } from 'common/LogConstants'
import { PhotoSectionId, PhotoSectionById, LoadedPhotoSection, isLoadedPhotoSection, Photo, PhotoId, PhotoSet } from 'common/CommonTypes'
import CancelablePromise, { isCancelError } from 'common/util/CancelablePromise'
import { getMasterPath } from 'common/util/DataUtil'
import { assertRendererProcess } from 'common/util/ElectronUtil'
import Profiler from 'common/util/Profiler'
import SerialJobQueue from 'common/util/SerialJobQueue'
import BackgroundClient from 'app/BackgroundClient'
import { showError } from 'app/ErrorPresenter'
import { GridSectionLayout, GridLayout, JustifiedLayoutBox } from 'app/UITypes'
import { sectionHeadHeight } from 'app/ui/library/GridSection'
import { forgetSectionPhotosAction, fetchSectionPhotosAction } from 'app/state/actions'
import store from 'app/state/store'
import { getThumbnailSrc } from './PhotoController'
import { collectionContainsSection } from 'app/util/PhotoCollectionResolver'
assertRendererProcess()
/**
* A nailed grid position.
*
* **Background:** If the grid data is updated or if sizes are changing, we don't want the grid to keep its scroll
* position in terms of pixels. Instead we want the grid to stay at the same photos it showed before.
* A `NailedGridPosition` describes the position of photos shown by the grid at a certain moment.
* This information is used to restore that position after the mentioned changes were applied.
*/
export interface NailedGridPosition {
/** The position of the photos in view */
positions: PhotoGridPosition[]
}
/** A y-position within a photo */
export interface PhotoGridPosition {
sectionId: PhotoSectionId
photoId: PhotoId
/**
* The relative position within the photo.
* Has a value between `0` and `1`: `0` = photo's top, `1` = photo's bottom
*/
relativeY: number
/**
* The offset to apply (in pixels).
*
* This is normally `0`. Will be set to another value if the position is outside the photo
* - so `relativeY` is either `0` or `1`.
*/
offsetY: number
}
const pagesToKeep = 4
const pagesToPreload = 3
const averageAspect = 3 / 2
const containerPadding = 10
export const boxSpacing = 4
const sectionSpacingX = 30
const targetRowHeightTolerance = 0.25
let prevSectionIds: PhotoSectionId[] = []
let prevSectionById: PhotoSectionById = {}
let prevGridLayout: GridLayout = { fromSectionIndex: 0, toSectionIndex: 0, sectionLayouts: [] }
let prevScrollTop = 0
let prevViewportWidth = 0
let prevViewportHeight = 0
let prevGridRowHeight = -1
let isFetchingSectionPhotos = false
export function getPrevGridLayout(): GridLayout {
return prevGridLayout
}
export type GetGridLayoutFunction = typeof getGridLayoutWithoutStoreUpdate
export function getGridLayoutWithoutStoreUpdate(sectionIds: PhotoSectionId[], sectionById: PhotoSectionById,
scrollTop: number, viewportWidth: number, viewportHeight: number, gridRowHeight: number,
nailedGridPosition: NailedGridPosition | null):
GridLayout
{
const profiler = profileLibraryLayout ? new Profiler(`Calculating layout for ${sectionIds.length} sections`) : null
let sectionsChanged = false
let fromSectionIndex: number | null = null
let toSectionIndex: number | null = null
const prevGridLayoutIsDirty = (viewportWidth !== prevViewportWidth) || (gridRowHeight !== prevGridRowHeight)
// Step 1: Section-internal layout (layout photos inside each section):
//
// - Create a layout for each section
// - Define `width` and `height`
// - Define `boxes` for loaded sections
const sectionCount = sectionIds.length
const sectionLayouts: GridSectionLayout[] = []
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
const sectionId = sectionIds[sectionIndex]
const section = sectionById[sectionId]
const usePlaceholder = !isLoadedPhotoSection(section)
const prevLayout = (sectionId === prevSectionIds[sectionIndex]) ? prevGridLayout.sectionLayouts[sectionIndex] : null
const prevLayoutIsDirty = prevGridLayoutIsDirty ||
(!usePlaceholder && section !== prevSectionById[prevSectionIds[sectionIndex]])
// We have to compare sections, not section IDs in order to detect changes inside the section.
// See `createLayoutForLoadedSection`
let layout: GridSectionLayout | null = null
if (prevLayout && !prevLayoutIsDirty) {
const prevLayoutIsPlaceholder = !prevLayout.boxes
if (usePlaceholder == prevLayoutIsPlaceholder) {
layout = prevLayout
}
}
if (!layout) {
sectionsChanged = true
// We have to update the layout
if (usePlaceholder) {
if (prevLayout && !prevLayoutIsDirty) {
// Section data was dropped -> Drop layout boxes as well
layout = {
left: 0,
top: 0,
width: prevLayout.width,
height: prevLayout.height
}
} else {
layout = estimateSectionLayout(section.count, viewportWidth, gridRowHeight)
}
} else {
// Calculate boxes
layout = createLayoutForLoadedSection(section as LoadedPhotoSection, viewportWidth, gridRowHeight)
}
}
sectionLayouts.push(layout)
}
if (profiler) {
profiler.addPoint('Section-internal layout')
}
// Step 2: Inter-section layout:
//
// - Define `left` and `top`
// - Do block-align for small sections shown in one row. This may scale those sections, so their
// `width` and `height` change
let x = 0
let y = 0
let rowStartSectionIndex = 0
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
const layout = sectionLayouts[sectionIndex]
const originalLayout = layout.originalLayout || layout
if (x != 0 && viewportWidth > 0 && x + originalLayout.width > viewportWidth) {
// This section goes into a new row
// Layout the row before
const hasChange = layoutSectionRow(y, rowStartSectionIndex, sectionIndex - 1, sectionLayouts, viewportWidth)
if (hasChange) {
sectionsChanged = true
}
// Start a new row
const prevLayout = sectionLayouts[sectionIndex - 1]
x = 0
y += prevLayout.height
rowStartSectionIndex = sectionIndex
}
// Prepare next iteration
x += originalLayout.width + sectionSpacingX
}
// Layout the last row
const hasChange = layoutSectionRow(y, rowStartSectionIndex, sectionCount - 1, sectionLayouts, viewportWidth)
if (hasChange) {
sectionsChanged = true
}
if (profiler) {
profiler.addPoint('Inter-section layout')
}
// Step 3: Mark visible parts of sections:
//
// - Define `fromBoxIndex` and `toBoxIndex`
let inDomMinY: number | null = null
let inDomMaxY: number | null = null
if (nailedGridPosition === null) {
inDomMinY = scrollTop - pagesToPreload * viewportHeight
inDomMaxY = scrollTop + (pagesToPreload + 1) * viewportHeight
}
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
const sectionId = sectionIds[sectionIndex]
const layout = sectionLayouts[sectionIndex]
const sectionBottom = layout.top + layout.height
if (inDomMinY === null || inDomMaxY === null) {
// We have a NailedGridPosition
// -> Just keep the previous `fromBoxIndex` and `toBoxIndex`
const prevLayout = (sectionId === prevSectionIds[sectionIndex]) ? prevGridLayout.sectionLayouts[sectionIndex] : null
if (layout.boxes && prevLayout && prevLayout.boxes && layout.boxes.length === prevLayout.boxes.length) {
layout.fromBoxIndex = prevLayout.fromBoxIndex
layout.toBoxIndex = prevLayout.toBoxIndex
}
} else {
// We have no NailedGridPosition
// -> Set `fromBoxIndex` and `toBoxIndex` in order to control which photos are added to the DOM
if (sectionBottom >= inDomMinY && layout.top <= inDomMaxY) {
// Show section in DOM
const section = sectionById[sectionId]
if (fromSectionIndex === null) {
fromSectionIndex = sectionIndex
}
if (!layout.boxes) {
// Section is not loaded yet, but will be shown in DOM -> Create dummy boxes
const sectionBodyHeight = layout.height - sectionHeadHeight
layout.boxes = createDummyLayoutBoxes(layout.width, sectionBodyHeight, gridRowHeight, section.count)
}
const prevFromBoxIndex = layout.fromBoxIndex
const prevToBoxIndex = layout.toBoxIndex
layout.fromBoxIndex = 0
layout.toBoxIndex = section.count
if (layout.top < inDomMinY || sectionBottom > inDomMaxY) {
// This section is partly visible -> Go throw the boxes and find the correct boundaries
const boxes = layout.boxes
const boxCount = boxes.length
let searchingStart = true
for (let boxIndex = 0; boxIndex < boxCount; boxIndex++) {
const box = boxes[boxIndex]
const boxTop = layout.top + sectionHeadHeight + box.top
const boxBottom = boxTop + box.height
if (searchingStart) {
if (boxBottom >= inDomMinY) {
layout.fromBoxIndex = boxIndex
searchingStart = false
}
} else if (boxTop > inDomMaxY) {
layout.toBoxIndex = boxIndex
break
}
}
}
if (layout.fromBoxIndex !== prevFromBoxIndex || layout.toBoxIndex !== prevToBoxIndex) {
sectionsChanged = true
}
} else {
// Remove section from DOM
if (toSectionIndex === null && fromSectionIndex !== null) {
// This is the first section to remove from DOM -> Remember its index
toSectionIndex = sectionIndex
}
if (layout.boxes) {
// This section is fully invisible -> Keep the layout but add no photos to the DOM
layout.fromBoxIndex = undefined
layout.toBoxIndex = undefined
}
}
}
}
if (toSectionIndex === null) {
toSectionIndex = sectionCount
}
if (profiler) {
profiler.addPoint('Mark visible parts of sections')
}
let nextGridLayout: GridLayout
if (sectionsChanged
|| fromSectionIndex !== prevGridLayout.fromSectionIndex
|| toSectionIndex !== prevGridLayout.toSectionIndex)
{
nextGridLayout = {
fromSectionIndex: fromSectionIndex || 0,
toSectionIndex: toSectionIndex || 0,
sectionLayouts
}
} else {
nextGridLayout = prevGridLayout
}
prevSectionIds = sectionIds
prevSectionById = sectionById
prevGridLayout = nextGridLayout
if (nailedGridPosition === null) {
prevScrollTop = scrollTop
}
prevViewportWidth = viewportWidth
prevViewportHeight = viewportHeight
prevGridRowHeight = gridRowHeight
if (profiler) {
profiler.addPoint('Finish layout')
profiler.logResult()
}
return nextGridLayout
}
export function getGridLayoutAndUpdateStore(sectionIds: PhotoSectionId[], sectionById: PhotoSectionById,
scrollTop: number, viewportWidth: number, viewportHeight: number, gridRowHeight: number,
nailedGridPosition: NailedGridPosition | null):
GridLayout
{
const gridLayout = getGridLayoutWithoutStoreUpdate(sectionIds, sectionById, scrollTop, viewportWidth, viewportHeight, gridRowHeight,
nailedGridPosition)
if (nailedGridPosition === null) {
forgetAndFetchSections(sectionIds, sectionById, scrollTop, viewportHeight, gridLayout.sectionLayouts)
}
return gridLayout
}
export function createLayoutForLoadedSection(section: LoadedPhotoSection, viewportWidth: number, targetRowHeight: number): GridSectionLayout {
const { photoData } = section
const aspects = section.photoIds.map(photoId => {
const photo = photoData[photoId]
const { edited_width, edited_height } = photo
// If we have no edited size yet (which happens when loading an old DB were it was missing), the following will happen:
// - We calculate a layout using the average aspect (which is how the loading rect of the photo is shown)
// - `PhotoRenderer.renderPhoto` will detect that the edited size is missing and will update the DB
// - The Grid will trigger a layout, because the photo has changed in the app state
// - `getLayoutForSections` will detect that the section changed and so it will get a ney layout using the correct edited size
return (edited_width && edited_height) ? (edited_width / edited_height) : averageAspect
})
const layoutResult = createLayout(aspects, { containerPadding, boxSpacing, containerWidth: viewportWidth, targetRowHeight, targetRowHeightTolerance })
const { boxes } = layoutResult
const firstBox = boxes[0]
const lastBox = boxes[boxes.length - 1]
const isSingleRow = (lastBox.top === firstBox.top)
const bodyHeight = Math.round(layoutResult.containerHeight)
return {
left: 0,
top: 0,
width: isSingleRow ? Math.ceil(lastBox.left + lastBox.width + containerPadding) : viewportWidth,
height: sectionHeadHeight + bodyHeight,
boxes
}
}
export function estimateSectionLayout(photoCount: number, viewportWidth: number, gridRowHeight: number, ): GridSectionLayout {
let bodyWidth: number
let bodyHeight: number
if (viewportWidth === 0) {
bodyWidth = 0
bodyHeight = 2 * containerPadding + photoCount * gridRowHeight + (photoCount - 1) * boxSpacing
} else {
// Estimate section height (assuming a normal landscape aspect ratio of 3:2)
const photoWidth = averageAspect * gridRowHeight
const unwrappedWidth = photoCount * photoWidth
const rows = Math.ceil(unwrappedWidth / viewportWidth)
bodyWidth = Math.min(unwrappedWidth, viewportWidth)
bodyHeight = 2 * containerPadding + rows * gridRowHeight + (rows - 1) * boxSpacing
}
return {
left: 0,
top: 0,
width: bodyWidth,
height: sectionHeadHeight + bodyHeight
}
}
function layoutSectionRow(rowTop: number, rowStartSectionIndex: number, rowEndSectionIndex: number, sectionLayouts: GridSectionLayout[],
viewportWidth: number): boolean
{
let sectionsChanged = false
let scaleFactor = 1
if (rowStartSectionIndex !== rowEndSectionIndex) {
// This row has multiple sections -> Determine the scale factor in order to block-align them
let allLayoutsHaveBoxes = true
let totalBoxWidth = 0
let totalSpacingWidth = -sectionSpacingX
for (let sectionIndex = rowStartSectionIndex; sectionIndex <= rowEndSectionIndex; sectionIndex++) {
const layout = sectionLayouts[sectionIndex]
const originalLayout = layout.originalLayout || layout
if (originalLayout.boxes) {
totalSpacingWidth += sectionSpacingX + 2 * containerPadding + (originalLayout.boxes.length - 1) * boxSpacing
for (const box of originalLayout.boxes) {
totalBoxWidth += box.width
}
} else {
allLayoutsHaveBoxes = false
break
}
}
if (allLayoutsHaveBoxes) {
const wantedTotalBoxWidth = viewportWidth - totalSpacingWidth
scaleFactor = wantedTotalBoxWidth / totalBoxWidth
if (scaleFactor > 1 + targetRowHeightTolerance) {
scaleFactor = 1
}
}
}
let x = 0
for (let sectionIndex = rowStartSectionIndex; sectionIndex <= rowEndSectionIndex; sectionIndex++) {
let layout = sectionLayouts[sectionIndex]
if (scaleFactor === 1) {
if (layout.originalLayout) {
// Use the original (unscaled) layout
layout = layout.originalLayout
sectionLayouts[rowStartSectionIndex] = layout
sectionsChanged = true
}
} else if (layout.scaleFactor !== scaleFactor) {
const originalLayout = layout.originalLayout || layout
const originalBoxes = originalLayout.boxes!
const boxHeight = originalBoxes[0].height * scaleFactor
const boxes: JustifiedLayoutBox[] = []
let boxLeft = containerPadding
for (const originalBox of originalBoxes) {
const boxWidth = boxHeight * originalBox.aspectRatio
boxes.push({
aspectRatio: originalBox.aspectRatio,
left: boxLeft,
top: containerPadding,
width: boxWidth,
height: boxHeight
})
boxLeft += boxWidth + boxSpacing
}
layout = {
left: x,
top: rowTop,
width: Math.ceil(boxLeft - boxSpacing + containerPadding),
height: Math.round(sectionHeadHeight + boxHeight + 2 * containerPadding),
boxes,
scaleFactor,
originalLayout
}
sectionLayouts[sectionIndex] = layout
sectionsChanged = true
}
if (layout.left !== x) {
layout.left = x
sectionsChanged = true
}
if (layout.top !== rowTop) {
layout.top = rowTop
sectionsChanged = true
}
x += layout.width + sectionSpacingX
}
return sectionsChanged
}
export function createDummyLayoutBoxes(sectionBodyWidth: number, sectionBodyHeight: number, gridRowHeight: number, photoCount: number): JustifiedLayoutBox[] {
const rowCount = Math.round((sectionBodyHeight - 2 * containerPadding + boxSpacing) / (gridRowHeight + boxSpacing)) // Reverse `estimateContainerHeight`
let boxes: JustifiedLayoutBox[] = []
for (let row = 0; row < rowCount; row++) {
const lastBoxIndex = Math.ceil(photoCount * (row + 1) / rowCount) // index is excluding
const colCount = lastBoxIndex - boxes.length
let boxWidth = (sectionBodyWidth - 2 * containerPadding - (colCount - 1) * boxSpacing) / colCount
if (row === rowCount - 1) {
boxWidth = Math.min(boxWidth, averageAspect * gridRowHeight)
}
const aspectRatio = boxWidth / gridRowHeight
for (let col = 0; col < colCount; col++) {
if (boxes.length >= photoCount) {
break
}
boxes.push({
aspectRatio,
left: containerPadding + col * boxWidth + (col - 1) * boxSpacing,
top: containerPadding + row * (gridRowHeight + boxSpacing),
width: boxWidth,
height: gridRowHeight
})
}
}
return boxes
}
/** Determines which sections we have to load or forget */
function forgetAndFetchSections(sectionIds: PhotoSectionId[], sectionById: PhotoSectionById,
viewportTop: number, viewportHeight: number, sectionLayouts: GridSectionLayout[])
{
let sectionIdsToForget: { [index: string]: true } | null = null
let sectionIdsToLoad: PhotoSectionId[] | null = null
const isScrollingDown = (viewportTop >= prevScrollTop)
const keepMinY = viewportTop - pagesToKeep * viewportHeight
const keepMaxY = viewportTop + (pagesToKeep + 1) * viewportHeight
const preloadMinY = viewportTop - (isScrollingDown ? 0 : pagesToPreload) * viewportHeight
const preloadMaxY = viewportTop + ((isScrollingDown ? pagesToPreload : 0) + 1) * viewportHeight
for (let sectionIndex = 0, sectionCount = sectionIds.length; sectionIndex < sectionCount; sectionIndex++) {
const sectionId = sectionIds[sectionIndex]
const section = sectionById[sectionId]
const layout = sectionLayouts[sectionIndex]
const sectionTop = layout.top
const sectionBottom = sectionTop + layout.height
if (isLoadedPhotoSection(section)) {
const keepSection = sectionBottom > keepMinY && sectionTop < keepMaxY
if (!keepSection && !isProtectedSection(sectionId)) {
if (!sectionIdsToForget) {
sectionIdsToForget = {}
}
sectionIdsToForget[sectionId] = true
}
} else if (!isFetchingSectionPhotos) {
const loadSection = sectionBottom > preloadMinY && sectionTop < preloadMaxY
if (loadSection) {
if (!sectionIdsToLoad) {
sectionIdsToLoad = [ sectionId ]
} else {
sectionIdsToLoad.push(sectionId)
}
}
}
}
if (sectionIdsToForget) {
const nailedSectionIdsToForget = sectionIdsToForget
setTimeout(() => store.dispatch(forgetSectionPhotosAction(nailedSectionIdsToForget)))
}
if (sectionIdsToLoad && !isFetchingSectionPhotos) {
isFetchingSectionPhotos = true
fetchSectionPhotos(sectionIdsToLoad)
.catch(error => {
showError(`Fetching photos for sections ${sectionIds.join(', ')} failed`, error)
})
.finally(() => {
isFetchingSectionPhotos = false
})
}
}
function isProtectedSection(sectionId: PhotoSectionId): boolean {
const state = store.getState()
return !!(
state.library.selection?.sectionSelectionById[sectionId] ||
(sectionId === state.library.activePhoto?.sectionId) ||
(sectionId === state.detail?.currentPhoto.sectionId) ||
(sectionId === state.info.photoData?.sectionId) ||
collectionContainsSection(state.export?.photos, sectionId)
)
}
export async function fetchSectionPhotos(sectionIds: PhotoSectionId[]): Promise<PhotoSet[]> {
const { filter } = store.getState().library
const photoSets = await BackgroundClient.fetchSectionPhotos(sectionIds, filter)
store.dispatch(fetchSectionPhotosAction(sectionIds, photoSets))
return photoSets
}
type CreateThumbnailJob = { isCancelled: boolean, sectionId: PhotoSectionId, photo: Photo, profiler: Profiler | null }
const createThumbnailQueue = new SerialJobQueue(
(newJob, existingJob) => (newJob.photo.id === existingJob.photo.id) ? newJob : null,
createNextThumbnail,
getThumbnailPriority)
export function createThumbnail(sectionId: PhotoSectionId, photo: Photo): CancelablePromise<string> {
const profiler = profileThumbnailRenderer ? new Profiler(`Creating thumbnail for ${getMasterPath(photo)}`) : null
const job: CreateThumbnailJob = { isCancelled: false, sectionId, photo, profiler }
return new CancelablePromise<string>(
createThumbnailQueue.addJob(job)
.then(() => {
if (profiler) profiler.logResult()
return getThumbnailSrc(photo)
})
)
.catch(error => {
if (isCancelError(error)) {
job.isCancelled = true
}
throw error
})
}
async function createNextThumbnail(job: CreateThumbnailJob): Promise<void> {
if (job.isCancelled) {
return
}
await BackgroundClient.createThumbnail(job.photo)
if (job.profiler) {
job.profiler.addPoint('Create thumbnail on disk')
}
}
function getThumbnailPriority(job: CreateThumbnailJob): number {
const { sectionId, photo } = job
const sectionIndex = prevSectionIds.indexOf(sectionId)
const section = prevSectionById[sectionId]
const layout = prevGridLayout.sectionLayouts[sectionIndex]
if (!isLoadedPhotoSection(section) || !layout || !layout.boxes) {
return Number.MIN_VALUE
}
const photoIndex = section.photoIds.indexOf(photo.id)
const box = layout.boxes[photoIndex]
if (!box) {
return Number.MIN_VALUE
}
const boxTop = layout.top + sectionHeadHeight + box.top
if (boxTop < prevScrollTop) {
// Box is above viewport (or only partly visible) -> Use a negative prio reflecting the distance
return boxTop - prevScrollTop
}
const boxBottom = boxTop + box.height
const scrollBottom = prevScrollTop + prevViewportHeight
if (boxBottom > scrollBottom) {
// Box is below viewport (or only partly visible) -> Use a negative prio reflecting the distance
return scrollBottom - boxBottom
}
// Box is fully visible -> Use a positive prio reflecting position (images should appear in reading order)
const prio = (scrollBottom - boxTop) + (prevViewportWidth - box.left) / prevViewportWidth
return prio
} | the_stack |
import React, {Suspense} from 'react';
import {
Logger,
logServerResponse,
logCacheControlHeaders,
logQueryTimings,
getLoggerWithContext,
} from './utilities/log';
import {getErrorMarkup} from './utilities/error';
import type {
AssembleHtmlParams,
RunSsrParams,
RunRscParams,
ResolvedHydrogenConfig,
ResolvedHydrogenRoutes,
} from './types';
import {Html, applyHtmlHead} from './foundation/Html/Html';
import {HydrogenResponse} from './foundation/HydrogenResponse/HydrogenResponse.server';
import {
HydrogenRequest,
RuntimeContext,
} from './foundation/HydrogenRequest/HydrogenRequest.server';
import {
preloadRequestCacheData,
ServerRequestProvider,
} from './foundation/ServerRequestProvider';
import type {ServerResponse, IncomingMessage} from 'http';
import type {PassThrough as PassThroughType} from 'stream';
import {
getApiRouteFromURL,
renderApiRoute,
getApiRoutes,
} from './utilities/apiRoutes';
import {ServerPropsProvider} from './foundation/ServerPropsProvider';
import {isBotUA} from './utilities/bot-ua';
import {setCache} from './foundation/runtime';
import {
ssrRenderToPipeableStream,
ssrRenderToReadableStream,
rscRenderToReadableStream,
createFromReadableStream,
bufferReadableStream,
} from './streaming.server';
import {RSC_PATHNAME, EVENT_PATHNAME, EVENT_PATHNAME_REGEX} from './constants';
import {stripScriptsFromTemplate} from './utilities/template';
import {setLogger, RenderType} from './utilities/log/log';
import {Analytics} from './foundation/Analytics/Analytics.server';
import {ServerAnalyticsRoute} from './foundation/Analytics/ServerAnalyticsRoute.server';
import {getSyncSessionApi} from './foundation/session/session';
import {parseJSON} from './utilities/parse';
import {htmlEncode} from './utilities';
import {splitCookiesString} from 'set-cookie-parser';
declare global {
// This is provided by a Vite plugin
// and will trigger tree-shaking.
// eslint-disable-next-line no-var
var __HYDROGEN_WORKER__: boolean;
}
const DOCTYPE = '<!DOCTYPE html>';
const CONTENT_TYPE = 'Content-Type';
const HTML_CONTENT_TYPE = 'text/html; charset=UTF-8';
interface RequestHandlerOptions {
indexTemplate:
| string
| ((url: string) => Promise<string | {default: string}>);
cache?: Cache;
streamableResponse?: ServerResponse;
dev?: boolean;
context?: RuntimeContext;
nonce?: string;
buyerIpHeader?: string;
}
export interface RequestHandler {
(request: Request | IncomingMessage, options: RequestHandlerOptions): Promise<
Response | undefined
>;
}
export const renderHydrogen = (App: any) => {
const handleRequest: RequestHandler = async function (rawRequest, options) {
const {
dev,
nonce,
cache,
context,
buyerIpHeader,
indexTemplate,
streamableResponse: nodeResponse,
} = options;
const request = new HydrogenRequest(rawRequest);
const url = new URL(request.url);
const {default: inlineHydrogenConfig} = await import(
// @ts-ignore
// eslint-disable-next-line node/no-missing-import
'virtual__hydrogen.config.ts'
);
const {default: hydrogenRoutes} = await import(
// @ts-ignore
// eslint-disable-next-line node/no-missing-import
'virtual__hydrogen-routes.server.jsx'
);
const hydrogenConfig: ResolvedHydrogenConfig = {
...inlineHydrogenConfig,
routes: hydrogenRoutes,
};
request.ctx.hydrogenConfig = hydrogenConfig;
request.ctx.buyerIpHeader = buyerIpHeader;
setLogger(hydrogenConfig.logger);
const log = getLoggerWithContext(request);
const response = new HydrogenResponse();
const sessionApi = hydrogenConfig.session
? hydrogenConfig.session(log)
: undefined;
request.ctx.session = getSyncSessionApi(request, response, log, sessionApi);
/**
* Inject the cache & context into the module loader so we can pull it out for subrequests.
*/
request.ctx.runtime = context;
setCache(cache);
if (
url.pathname === EVENT_PATHNAME ||
EVENT_PATHNAME_REGEX.test(url.pathname)
) {
return ServerAnalyticsRoute(
request,
hydrogenConfig.serverAnalyticsConnectors
);
}
const isRSCRequest = url.pathname === RSC_PATHNAME;
const apiRoute = !isRSCRequest && getApiRoute(url, hydrogenConfig.routes);
// The API Route might have a default export, making it also a server component
// If it does, only render the API route if the request method is GET
if (
apiRoute &&
(!apiRoute.hasServerComponent || request.method !== 'GET')
) {
const apiResponse = await renderApiRoute(
request,
apiRoute,
hydrogenConfig.shopify,
sessionApi
);
return apiResponse instanceof Request
? handleRequest(apiResponse, options)
: apiResponse;
}
const state: Record<string, any> = isRSCRequest
? parseJSON(url.searchParams.get('state') || '{}')
: {pathname: url.pathname, search: url.search};
const rsc = runRSC({App, state, log, request, response});
if (isRSCRequest) {
const buffered = await bufferReadableStream(rsc.readable.getReader());
postRequestTasks('rsc', 200, request, response);
return new Response(buffered, {
headers: {'cache-control': response.cacheControlHeader},
});
}
if (isBotUA(url, request.headers.get('user-agent'))) {
response.doNotStream();
}
return runSSR({
log,
dev,
rsc,
nonce,
state,
request,
response,
nodeResponse,
template: await getTemplate(indexTemplate, url),
});
};
if (__HYDROGEN_WORKER__) return handleRequest;
return ((rawRequest, options) =>
handleFetchResponseInNode(
handleRequest(rawRequest, options),
options.streamableResponse
)) as RequestHandler;
};
async function getTemplate(
indexTemplate:
| string
| ((url: string) => Promise<string | {default: string}>),
url: URL
) {
let template =
typeof indexTemplate === 'function'
? await indexTemplate(url.toString())
: indexTemplate;
if (template && typeof template !== 'string') {
template = template.default;
}
return template;
}
function getApiRoute(url: URL, routes: ResolvedHydrogenRoutes) {
const apiRoutes = getApiRoutes(routes);
return getApiRouteFromURL(url, apiRoutes);
}
function assembleHtml({
ssrHtml,
rscPayload,
request,
template,
}: AssembleHtmlParams) {
let html = applyHtmlHead(ssrHtml, request.ctx.head, template);
if (rscPayload) {
html = html.replace(
'</body>',
// This must be a function to avoid replacing
// special patterns like `$1` in `String.replace`.
() => flightContainer(rscPayload) + '</body>'
);
}
return html;
}
/**
* Run the SSR/Fizz part of the App. If streaming is disabled,
* this buffers the output and applies SEO enhancements.
*/
async function runSSR({
rsc,
state,
request,
response,
nodeResponse,
template,
nonce,
dev,
log,
}: RunSsrParams) {
let ssrDidError: Error | undefined;
const didError = () => rsc.didError() ?? ssrDidError;
const [rscReadableForFizz, rscReadableForFlight] = rsc.readable.tee();
const rscResponse = createFromReadableStream(rscReadableForFizz);
const RscConsumer = () => rscResponse.readRoot();
const {noScriptTemplate, bootstrapScripts, bootstrapModules} =
stripScriptsFromTemplate(template);
const AppSSR = (
<Html
template={response.canStream() ? noScriptTemplate : template}
hydrogenConfig={request.ctx.hydrogenConfig!}
>
<ServerRequestProvider request={request} isRSC={false}>
<ServerPropsProvider
initialServerProps={state as any}
setServerPropsForRsc={() => {}}
>
<PreloadQueries request={request}>
<Suspense fallback={null}>
<RscConsumer />
</Suspense>
<Suspense fallback={null}>
<Analytics />
</Suspense>
</PreloadQueries>
</ServerPropsProvider>
</ServerRequestProvider>
</Html>
);
log.trace('start ssr');
const rscReadable = response.canStream()
? new ReadableStream({
start(controller) {
log.trace('rsc start chunks');
const encoder = new TextEncoder();
bufferReadableStream(rscReadableForFlight.getReader(), (chunk) => {
const metaTag = flightContainer(chunk);
controller.enqueue(encoder.encode(metaTag));
}).then(() => {
log.trace('rsc finish chunks');
return controller.close();
});
},
})
: rscReadableForFlight;
if (__HYDROGEN_WORKER__) {
const encoder = new TextEncoder();
const transform = new TransformStream();
const writable = transform.writable.getWriter();
const responseOptions = {} as ResponseOptions;
let ssrReadable: Awaited<ReturnType<typeof ssrRenderToReadableStream>>;
try {
ssrReadable = await ssrRenderToReadableStream(AppSSR, {
nonce,
bootstrapScripts,
bootstrapModules,
onError(error) {
ssrDidError = error;
if (dev && !writable.closed && !!responseOptions.status) {
writable.write(getErrorMarkup(error));
}
log.error(error);
},
});
} catch (error: unknown) {
log.error(error);
return new Response(
template + (dev ? getErrorMarkup(error as Error) : ''),
{
status: 500,
headers: {[CONTENT_TYPE]: HTML_CONTENT_TYPE},
}
);
}
if (response.canStream()) log.trace('worker ready to stream');
ssrReadable.allReady.then(() => log.trace('worker complete ssr'));
const prepareForStreaming = () => {
Object.assign(responseOptions, getResponseOptions(response, didError()));
/**
* TODO: This assumes `response.cache()` has been called _before_ any
* queries which might be caught behind Suspense. Clarify this or add
* additional checks downstream?
*/
/**
* TODO: Also add `Vary` headers for `accept-language` and any other keys
* we want to shard our full-page cache for all Hydrogen storefronts.
*/
responseOptions.headers.set('cache-control', response.cacheControlHeader);
if (isRedirect(responseOptions)) {
return false;
}
responseOptions.headers.set(CONTENT_TYPE, HTML_CONTENT_TYPE);
writable.write(encoder.encode(DOCTYPE));
const error = didError();
if (error) {
// This error was delayed until the headers were properly sent.
writable.write(encoder.encode(dev ? getErrorMarkup(error) : template));
}
return true;
};
const shouldFlushBody = response.canStream()
? prepareForStreaming()
: await ssrReadable.allReady.then(prepareForStreaming);
if (shouldFlushBody) {
let bufferedSsr = '';
let isPendingSsrWrite = false;
const writingSSR = bufferReadableStream(
ssrReadable.getReader(),
response.canStream()
? (chunk) => {
bufferedSsr += chunk;
if (!isPendingSsrWrite) {
isPendingSsrWrite = true;
setTimeout(() => {
isPendingSsrWrite = false;
// React can write fractional chunks synchronously.
// This timeout ensures we only write full HTML tags
// in order to allow RSC writing concurrently.
if (bufferedSsr) {
writable.write(encoder.encode(bufferedSsr));
bufferedSsr = '';
}
}, 0);
}
}
: undefined
);
const writingRSC = bufferReadableStream(
rscReadable.getReader(),
response.canStream()
? (scriptTag) => writable.write(encoder.encode(scriptTag))
: undefined
);
Promise.all([writingSSR, writingRSC]).then(([ssrHtml, rscPayload]) => {
if (!response.canStream()) {
const html = assembleHtml({ssrHtml, rscPayload, request, template});
writable.write(encoder.encode(html));
}
// Last SSR write might be pending, delay closing the writable one tick
setTimeout(() => writable.close(), 0);
postRequestTasks('str', responseOptions.status, request, response);
});
} else {
// Redirects do not write body
writable.close();
postRequestTasks('str', responseOptions.status, request, response);
}
if (response.canStream()) {
return new Response(transform.readable, responseOptions);
}
const bufferedBody = await bufferReadableStream(
transform.readable.getReader()
);
return new Response(bufferedBody, responseOptions);
} else if (nodeResponse) {
const {pipe} = ssrRenderToPipeableStream(AppSSR, {
nonce,
bootstrapScripts,
bootstrapModules,
onShellReady() {
log.trace('node ready to stream');
/**
* TODO: This assumes `response.cache()` has been called _before_ any
* queries which might be caught behind Suspense. Clarify this or add
* additional checks downstream?
*/
writeHeadToNodeResponse(nodeResponse, response, log, didError());
if (isRedirect(nodeResponse)) {
// Return redirects early without further rendering/streaming
return nodeResponse.end();
}
if (!response.canStream()) return;
startWritingToNodeResponse(nodeResponse, dev ? didError() : undefined);
setTimeout(() => {
log.trace('node pipe response');
pipe(nodeResponse);
}, 0);
bufferReadableStream(rscReadable.getReader(), (chunk) => {
log.trace('rsc chunk');
return nodeResponse.write(chunk);
});
},
async onAllReady() {
log.trace('node complete ssr');
if (response.canStream() || nodeResponse.writableEnded) {
postRequestTasks('str', nodeResponse.statusCode, request, response);
return;
}
writeHeadToNodeResponse(nodeResponse, response, log, didError());
if (isRedirect(nodeResponse)) {
// Redirects found after any async code
return nodeResponse.end();
}
const bufferedResponse = await createNodeWriter();
const bufferedRscPromise = bufferReadableStream(
rscReadable.getReader()
);
let ssrHtml = '';
bufferedResponse.on('data', (chunk) => (ssrHtml += chunk.toString()));
bufferedResponse.once('error', (error) => (ssrDidError = error));
bufferedResponse.once('end', async () => {
const rscPayload = await bufferedRscPromise;
const error = didError();
startWritingToNodeResponse(nodeResponse, dev ? error : undefined);
let html = template;
if (!error) {
html = assembleHtml({ssrHtml, rscPayload, request, template});
postRequestTasks('ssr', nodeResponse.statusCode, request, response);
}
nodeResponse.write(html);
nodeResponse.end();
});
pipe(bufferedResponse);
},
onShellError(error: any) {
log.error(error);
if (!nodeResponse.writableEnded) {
writeHeadToNodeResponse(nodeResponse, response, log, error);
startWritingToNodeResponse(nodeResponse, dev ? error : undefined);
nodeResponse.write(template);
nodeResponse.end();
}
},
onError(error: any) {
ssrDidError = error;
if (dev && nodeResponse.headersSent) {
// Calling write would flush headers automatically.
// Delay this error until headers are properly sent.
nodeResponse.write(getErrorMarkup(error));
}
log.error(error);
},
});
}
}
/**
* Run the RSC/Flight part of the App
*/
function runRSC({App, state, log, request, response}: RunRscParams) {
const serverProps = {...state, request, response, log};
request.ctx.router.serverProps = serverProps;
const AppRSC = (
<ServerRequestProvider request={request} isRSC={true}>
<PreloadQueries request={request}>
<App {...serverProps} />
<Suspense fallback={null}>
<Analytics />
</Suspense>
</PreloadQueries>
</ServerRequestProvider>
);
let rscDidError: Error;
const rscReadable = rscRenderToReadableStream(AppRSC, {
onError(e) {
rscDidError = e;
log.error(e);
},
});
return {readable: rscReadable, didError: () => rscDidError};
}
function PreloadQueries({
request,
children,
}: {
request: HydrogenRequest;
children: React.ReactNode;
}) {
const preloadQueries = request.getPreloadQueries();
preloadRequestCacheData(request, preloadQueries);
return <>{children}</>;
}
export default renderHydrogen;
function startWritingToNodeResponse(
nodeResponse: ServerResponse,
error?: Error
) {
if (!nodeResponse.headersSent) {
nodeResponse.setHeader(CONTENT_TYPE, HTML_CONTENT_TYPE);
nodeResponse.write(DOCTYPE);
}
if (error) {
// This error was delayed until the headers were properly sent.
nodeResponse.write(getErrorMarkup(error));
}
}
type ResponseOptions = {
headers: Headers;
status: number;
statusText?: string;
};
function getResponseOptions(
{headers, status, statusText}: HydrogenResponse,
error?: Error
) {
const responseInit = {
headers,
status: error ? 500 : status,
} as ResponseOptions;
if (!error && statusText) {
responseInit.statusText = statusText;
}
return responseInit;
}
function writeHeadToNodeResponse(
nodeResponse: ServerResponse,
componentResponse: HydrogenResponse,
log: Logger,
error?: Error
) {
if (nodeResponse.headersSent) return;
log.trace('writeHeadToNodeResponse');
/**
* TODO: Also add `Vary` headers for `accept-language` and any other keys
* we want to shard our full-page cache for all Hydrogen storefronts.
*/
nodeResponse.setHeader('cache-control', componentResponse.cacheControlHeader);
const {headers, status, statusText} = getResponseOptions(
componentResponse,
error
);
nodeResponse.statusCode = status;
if (statusText) {
nodeResponse.statusMessage = statusText;
}
setNodeHeaders(headers, nodeResponse);
}
function isRedirect(response: {status?: number; statusCode?: number}) {
const status = response.status ?? response.statusCode ?? 0;
return status >= 300 && status < 400;
}
async function createNodeWriter() {
// Importing 'stream' directly breaks Vite resolve
// when building for workers, even though this code
// does not run in a worker. Looks like tree-shaking
// kicks in after the import analysis/bundle.
const streamImport = __HYDROGEN_WORKER__ ? '' : 'stream';
const {PassThrough} = await import(streamImport);
return new PassThrough() as InstanceType<typeof PassThroughType>;
}
function flightContainer(chunk: string) {
return `<meta data-flight="${htmlEncode(chunk)}" />`;
}
function postRequestTasks(
type: RenderType,
status: number,
request: HydrogenRequest,
response: HydrogenResponse
) {
logServerResponse(type, request, status);
logCacheControlHeaders(type, request, response);
logQueryTimings(type, request);
request.savePreloadQueries();
}
/**
* Ensure Node.js environments handle the fetch Response correctly.
*/
function handleFetchResponseInNode(
fetchResponsePromise: Promise<Response | undefined>,
nodeResponse?: ServerResponse
) {
if (nodeResponse) {
fetchResponsePromise.then((response) => {
if (!response) return;
setNodeHeaders(response.headers, nodeResponse);
nodeResponse.statusCode = response.status;
if (response.body) {
if (response.body instanceof ReadableStream) {
bufferReadableStream(response.body.getReader(), (chunk) => {
nodeResponse.write(chunk);
}).then(() => nodeResponse.end());
} else {
nodeResponse.write(response.body);
nodeResponse.end();
}
} else {
nodeResponse.end();
}
});
}
return fetchResponsePromise;
}
/**
* Convert Headers to outgoing Node.js headers.
* Specifically, parse set-cookie headers to split them properly as separate
* `set-cookie` headers rather than a single, combined header.
*/
function setNodeHeaders(headers: Headers, nodeResponse: ServerResponse) {
for (const [key, value] of headers.entries()) {
if (key.toLowerCase() === 'set-cookie') {
nodeResponse.setHeader(key, splitCookiesString(value));
} else {
nodeResponse.setHeader(key, value);
}
}
} | the_stack |
import React, { useMemo, useState, useReducer, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import Link from "@material-ui/core/Link";
import DialogContent from "@material-ui/core/DialogContent";
import IconButton from "@material-ui/core/IconButton";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import Select from "@material-ui/core/Select";
import Button from "@material-ui/core/Button";
import PublishIcon from "@material-ui/icons/Publish";
import CreateIcon from "@material-ui/icons/Create";
import { NumberParam, StringParam, useQueryParam } from "use-query-params";
import ExifReader from "exifreader";
import ImageBlobReduce from "image-blob-reduce";
import Pica from "pica";
// this is needed to disable the default features including webworkers, which
// cra has trouble with currently
const pica = Pica({ features: ["js", "wasm", "cib"] });
const reduce = new ImageBlobReduce({ pica });
// generated with ls | jq -R -s -c 'split("\n")[:-1]' > gifs.json
import gifs from "./gifs.json";
import borders from "./borders.json";
const myimages = shuffle(gifs);
const myborders = shuffle(borders);
const PAGE_SIZE = 10;
const API_ENDPOINT = "https://fjgbqj4324.execute-api.us-east-2.amazonaws.com";
const BUCKET =
"https://sam-app-s3uploadbucket-1fyrebt7g2tr3.s3.us-east-2.amazonaws.com";
//from https://stackoverflow.com/questions/43083993/javascript-how-to-convert-exif-date-time-data-to-timestamp
const parseExifDate = (s: string) => {
const [year, month, date, hour, min, sec] = s.split(/\D/);
return new Date(+year, +month - 1, +date, +hour, +min, +sec);
};
const useStyles = makeStyles(() => ({
app: {
color: "white",
backgroundColor: "#927EE4",
textAlign: "center",
padding: "0.5em",
},
embeddedGuestbook: {
display: "block",
borderStyle: "solid",
borderColor: "black",
borderWidth: "0 0 1px 1px",
borderRadius: 25,
position: "relative",
float: "right",
width: "25%",
minWidth: 300,
padding: "1em",
},
posts: {
background: "#ddd",
},
gallery: {
textAlign: "center",
borderRadius: 25,
border: "1px solid black",
},
post: {
padding: "0.5em",
},
space: {
padding: "2em",
},
error: {
color: "red",
},
rainbow: {
backgroundImage:
"linear-gradient(to left, violet, indigo, blue, green, yellow, orange, red); -webkit-background-clip: text",
color: "transparent",
},
}));
function shuffle<T>(array: T[]) {
var currentIndex = array.length,
temporaryValue,
randomIndex;
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
async function myfetch(params: string, opts?: any) {
const response = await fetch(params, opts);
if (!response.ok) {
throw new Error(`HTTP ${response.status} ${response.statusText}`);
}
return response;
}
async function myfetchjson(params: string, opts?: any) {
const res = await myfetch(params, opts);
return res.json();
}
interface Comment {
timestamp: number;
user?: string;
message: string;
date: string;
}
function CommentForm({
filename,
forceRefresh,
}: {
filename: string;
forceRefresh: Function;
}) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const [user, setUser] = useState("");
const [message, setMessage] = useState("");
const [password] = useQueryParam("password", StringParam);
const classes = useStyles();
return (
<div>
{error ? (
<div className={classes.error}>{`${error}`}</div>
) : loading ? (
<p>Loading...</p>
) : (
<p>Write a comment...</p>
)}
<CreateIcon />
<label htmlFor="user">name (optional)</label>
<input
id="user"
type="text"
value={user}
onChange={(event) => setUser(event.target.value)}
/>
<textarea
style={{ width: "90%", height: 50 }}
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
<button
disabled={loading}
onClick={async () => {
try {
if (user || message) {
setLoading(true);
setError(undefined);
const data = new FormData();
data.append("message", message);
data.append("user", user);
data.append("filename", filename);
data.append("password", password || "");
await myfetchjson(API_ENDPOINT + "/postComment", {
method: "POST",
body: data,
});
setUser("");
setMessage("");
forceRefresh();
}
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}}
>
Submit
</button>
</div>
);
}
function PictureDialog({ onClose, file }: { onClose: Function; file?: File }) {
const [comments, setComments] = useState<Comment[]>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const [counter, setCounter] = useState(0);
const [password] = useQueryParam("password", StringParam);
const classes = useStyles();
const handleClose = () => {
setLoading(false);
setError(undefined);
onClose();
};
useEffect(() => {
(async () => {
try {
if (file) {
const result = await myfetchjson(
API_ENDPOINT + `/getComments?filename=${file?.filename}`
);
setComments(result);
}
} catch (e) {
setError(e);
}
})();
}, [file, counter]);
return (
<Dialog onClose={handleClose} open={Boolean(file)} maxWidth="lg">
<DialogTitle>{file ? file.filename : ""}</DialogTitle>
<DialogContent>
{file ? (
<Media file={file} style={{ width: "80%", maxHeight: "70%" }}>
{getCaption(file)}
</Media>
) : null}
{error ? (
<div className={classes.error}>{`${error}`}</div>
) : loading ? (
"Loading..."
) : comments ? (
<div className={classes.posts}>
{comments
.sort((a, b) => a.timestamp - b.timestamp)
.map((comment) => {
const { user, timestamp, message } = comment;
return (
<div
key={JSON.stringify(comment)}
className={classes.post}
style={{ background: "#ddd" }}
>
<div>
{user ? user + " - " : ""}
{new Date(timestamp).toLocaleString()}
</div>
<div>{message}</div>
</div>
);
})}
</div>
) : null}
{file && password ? (
<CommentForm
filename={file.filename}
forceRefresh={() => setCounter(counter + 1)}
/>
) : null}
</DialogContent>
</Dialog>
);
}
function GuestbookDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const [error, setError] = useState<Error>();
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<string>("");
const [password] = useQueryParam("password", StringParam);
const [user, setUser] = useState<string>("");
const handleClose = () => {
setError(undefined);
onClose();
};
return (
<Dialog onClose={handleClose} open={open}>
<DialogTitle>write a message about dixie</DialogTitle>
<DialogContent>
<label htmlFor="user">Your name:</label>
<input
id="user"
type="text"
value={user}
onChange={(event) => setUser(event.target.value)}
/>
<br />
<label htmlFor="message">Message</label>
<textarea
id="message"
rows={10}
value={message}
style={{ width: "100%" }}
onChange={(event) => setMessage(event.target.value)}
/>
{loading ? "Uploading..." : null}
{error ? <div className="error">{`${error}`}</div> : null}
<DialogActions>
<Button
style={{ textTransform: "none" }}
disabled={loading}
onClick={async () => {
try {
if (user || message) {
setLoading(true);
const data = new FormData();
data.append("message", message);
data.append("user", user);
data.append("password", password || "");
await myfetchjson(API_ENDPOINT + "/postGuestbookComment", {
method: "POST",
body: data,
});
setTimeout(() => {
handleClose();
}, 500);
}
} catch (e) {
setError(e);
} finally {
setLoading(false);
}
}}
color="primary"
>
submit
</Button>
<Button
onClick={handleClose}
color="primary"
style={{ textTransform: "none" }}
>
cancel
</Button>
</DialogActions>
</DialogContent>
</Dialog>
);
}
function UploadDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const [images, setImages] = useState<FileList>();
const [error, setError] = useState<Error>();
const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0);
const [completed, setCompleted] = useState(0);
const [user, setUser] = useState("");
const [message, setMessage] = useState("");
const [password] = useQueryParam("password", StringParam);
const classes = useStyles();
const handleClose = () => {
setError(undefined);
setLoading(false);
setImages(undefined);
setCompleted(0);
setTotal(0);
setMessage("");
onClose();
};
return (
<Dialog onClose={handleClose} open={open}>
<DialogTitle>upload a dixie (supports picture or video)</DialogTitle>
<DialogContent>
<label htmlFor="user">name (optional) </label>
<input
type="text"
value={user}
onChange={(event) => setUser(event.target.value)}
id="user"
/>
<br />
<label htmlFor="user">album name (optional) </label>
<input
type="text"
value={message}
onChange={(event) => setMessage(event.target.value)}
id="message"
/>
<br />
<input
multiple
type="file"
onChange={(e) => {
let files = e.target.files;
if (files && files.length) {
setImages(files);
}
}}
/>
{error ? (
<div className={classes.error}>{`${error}`}</div>
) : loading ? (
`Uploading...${completed}/${total}`
) : completed ? (
<h2>Uploaded </h2>
) : null}
<DialogActions>
<Button
style={{ textTransform: "none" }}
onClick={async () => {
try {
if (images) {
setLoading(true);
setError(undefined);
setCompleted(0);
setTotal(images.length);
for (const image of Array.from(images)) {
const exifData: {
DateTime?: { description: string };
} = await new Promise((resolve, reject) => {
var reader = new FileReader();
reader.onload = function (e) {
if (e.target && e.target.result) {
try {
resolve(
ExifReader.load(e.target.result as ArrayBuffer)
);
} catch (e) {
/* swallow error because exif error not that important maybe */
}
}
resolve({});
};
reader.onerror = reject;
reader.readAsArrayBuffer(image);
});
const data = new FormData();
data.append("message", message);
data.append("user", user);
data.append("filename", image.name);
data.append("contentType", image.type);
data.append("password", password || "");
if (exifData.DateTime) {
const exifTimestamp = +parseExifDate(
exifData.DateTime.description
);
data.append("exifTimestamp", `${exifTimestamp}`);
} else {
data.append("exifTimestamp", `${+new Date("1960")}`);
}
const res = await myfetchjson(API_ENDPOINT + "/postFile", {
method: "POST",
body: data,
});
if (res.uploadThumbnailURL) {
const reducedImage = await reduce.toBlob(image, {
max: 500,
});
await myfetch(res.uploadThumbnailURL, {
method: "PUT",
body: reducedImage,
});
}
await myfetch(res.uploadURL, {
method: "PUT",
body: image,
});
setCompleted((completed) => completed + 1);
}
setTimeout(() => {
handleClose();
}, 500);
}
} catch (e) {
setError(e);
}
}}
color="primary"
>
upload
</Button>
<Button
onClick={handleClose}
color="primary"
style={{ textTransform: "none" }}
>
cancel
</Button>
</DialogActions>
</DialogContent>
</Dialog>
);
}
interface Item {
message: string;
user: string;
timestamp: number;
}
function Guestbook({ className }: { className?: string }) {
const classes = useStyles();
const [posts, setPosts] = useState<Item[]>();
const [writing, setWriting] = useState(false);
const [error, setError] = useState<Error>();
const [password] = useQueryParam("password", StringParam);
const [counter, forceUpdate] = useReducer((x) => x + 1, 0);
useEffect(() => {
(async () => {
try {
const result = await myfetchjson(
API_ENDPOINT + "/getGuestbookComments"
);
setPosts(result.Items);
} catch (e) {
setError(e);
}
})();
}, [counter]);
return (
<div className={className}>
<h2>Guestbook</h2>
<div>
{error ? (
<div className="error">{`${error}`}</div>
) : posts ? (
posts.map((post) => (
<div className={classes.post} key={JSON.stringify(post)}>
<div className="user">
{post.user} wrote on{" "}
{new Date(post.timestamp).toLocaleDateString()}:
</div>
<div className="message">{post.message}</div>
</div>
))
) : null}
{password ? (
<IconButton
color="secondary"
size="small"
onClick={() => setWriting(true)}
>
write a msg
<CreateIcon />
</IconButton>
) : null}
</div>
<GuestbookDialog
open={writing}
onClose={() => {
setWriting(false);
forceUpdate();
}}
/>
</div>
);
}
interface File {
timestamp: number;
filename: string;
user: string;
message: string;
date: string;
contentType: string;
comments: unknown[];
exifTimestamp: number;
}
function Media({
file,
style,
onClick,
children,
}: {
file: File;
onClick?: Function;
style?: React.CSSProperties;
children?: React.ReactNode;
}) {
const { filename, contentType } = file;
const src = `${BUCKET}/${filename}`;
return (
<figure style={{ display: "inline-block" }}>
<picture>
{contentType.startsWith("video") ? (
<video
style={style}
src={src}
controls
onClick={(event) => {
if (onClick) {
onClick(event);
event.preventDefault();
}
}}
/>
) : (
<img style={style} src={src} onClick={onClick as any} />
)}
</picture>
<figcaption>{children}</figcaption>
</figure>
);
}
function getCaption(file: File) {
const { user, message, timestamp, exifTimestamp } = file;
return `${
user || message
? `${user ? user + " - " : ""}${message ? message : ""}`
: " "
} posted ${new Date(timestamp).toLocaleDateString()} ${
exifTimestamp && exifTimestamp !== +new Date("1960")
? `| taken ${new Date(exifTimestamp).toLocaleDateString()}`
: ""
}`;
}
function Gallery({ children }: { children: React.ReactNode }) {
const [files, setFiles] = useState<File[]>();
const [error, setError] = useState<Error>();
const [uploading, setUploading] = useState(false);
const [initialStart, setParamStart] = useQueryParam("start", NumberParam);
const [initialSort, setSortParam] = useQueryParam("sort", StringParam);
const [initialFilter, setFilterParam] = useQueryParam("filter", StringParam);
const [password] = useQueryParam("password", StringParam);
const [counter, setCounter] = useState(0);
const [filter, setFilter] = useState(initialFilter || "all");
const [sort, setSort] = useState(initialSort || "date_uploaded_dec");
const [start, setStart] = useState(initialStart || 0);
const [dialogFile, setDialogFile] = useState<File>();
const classes = useStyles();
useEffect(() => {
(async () => {
try {
const result = await myfetchjson(API_ENDPOINT + "/getFiles");
setFiles(result.Items);
} catch (e) {
setError(e);
}
})();
}, [counter]);
const filteredFiles = useMemo(() => {
if (files) {
if (filter === "videos") {
return files.filter((f) => f.contentType.startsWith("video"));
} else if (filter === "no_videos") {
return files.filter((f) => !f.contentType.startsWith("video"));
} else if (filter === "commented_on") {
return files.filter(
(f) => f.comments !== undefined && f.comments.length > 0
);
} else return files;
}
}, [files, filter]);
const fileList = useMemo(() => {
const future = +new Date("3000");
const past = +new Date("1960");
function getTimestamp(t: { exifTimestamp?: number }, repl: number) {
return !t.exifTimestamp || t.exifTimestamp === past
? repl
: t.exifTimestamp;
}
if (filteredFiles) {
if (sort === "date_uploaded_asc") {
return filteredFiles.sort((a, b) => a.timestamp - b.timestamp);
}
if (sort === "date_uploaded_dec") {
return filteredFiles.sort((a, b) => b.timestamp - a.timestamp);
}
if (sort === "date_exif_asc") {
return filteredFiles.sort(
(a, b) => getTimestamp(a, future) - getTimestamp(b, future)
);
}
if (sort === "date_exif_dec") {
return filteredFiles.sort(
(a, b) => getTimestamp(b, past) - getTimestamp(a, past)
);
}
if (sort === "random") {
return shuffle(filteredFiles);
}
}
}, [filteredFiles, sort]);
return (
<div className={classes.gallery}>
{children}
<div>
<h2>Dixies</h2>
<p>Click image to open full size</p>
<InputLabel id="demo-simple-select-label">Filter</InputLabel>
<Select
value={filter}
onChange={(event) => {
setFilter(event.target.value);
setFilterParam(event.target.value);
setStart(0);
setParamStart(0);
}}
>
<MenuItem value={"all"}>all</MenuItem>
<MenuItem value={"commented_on"}>has been commented on</MenuItem>
<MenuItem value={"videos"}>videos only</MenuItem>
<MenuItem value={"no_videos"}>no videos</MenuItem>
</Select>
<InputLabel>Sort</InputLabel>
<Select
value={sort}
onChange={(event) => {
setSort(event.target.value);
setSortParam(event.target.value);
}}
>
<MenuItem value={"random"}>random</MenuItem>
<MenuItem value={"date_exif_asc"}>exif date (asc)</MenuItem>
<MenuItem value={"date_exif_dec"}>exif date (dec)</MenuItem>
<MenuItem value={"date_uploaded_asc"}>date uploaded (asc)</MenuItem>
<MenuItem value={"date_uploaded_dec"}>date uploaded (dec)</MenuItem>
</Select>
<br />
{password ? (
<IconButton
color="primary"
size="small"
onClick={() => setUploading(true)}
>
add a dixie pic/video
<PublishIcon />
</IconButton>
) : null}
</div>
<UploadDialog
open={uploading}
onClose={() => {
setUploading(false);
setCounter(counter + 1);
}}
/>
<PictureDialog
file={dialogFile}
onClose={() => {
setDialogFile(undefined);
}}
/>
{error ? (
<div className={classes.error}>{`${error}`}</div>
) : fileList ? (
fileList.slice(start, start + PAGE_SIZE).map((file) => {
const { comments = [] } = file;
const token = myimages[Math.floor(Math.random() * myimages.length)];
const border =
myborders[Math.floor(Math.random() * myborders.length)];
const mod = 4;
const useBorder = Math.floor(Math.random() * mod) === 0;
const useImage = Math.floor(Math.random() * mod) === 0;
const style: React.CSSProperties = {
maxWidth: "90%",
maxHeight: 400,
boxSizing: "border-box",
border: useBorder ? "30px solid" : undefined,
borderImage: useBorder
? `url(borders/${border}) 30 round`
: undefined,
};
return (
<React.Fragment key={JSON.stringify(file)}>
<Media
file={{
...file,
filename:
(file.contentType.startsWith("image") ? "thumbnail-" : "") +
file.filename,
}}
onClick={() => {
setDialogFile(file);
}}
style={style}
>
{getCaption(file)}
<Link
href="#"
onClick={() => {
setDialogFile(file);
}}
>
{" "}
({comments.length} comments)
</Link>
</Media>
{useImage ? (
<img
style={{
maxWidth: "20%",
maxHeight: 100 + Math.random() * 50,
padding: 20,
}}
src={`img/${token}`}
/>
) : null}
</React.Fragment>
);
})
) : null}
{filteredFiles ? (
<div>
<button
onClick={() => {
setStart(0);
setParamStart(0);
}}
disabled={start === 0}
>
<< First
</button>
<button
onClick={() => {
setStart(start - PAGE_SIZE);
setParamStart(start - PAGE_SIZE);
}}
disabled={start - PAGE_SIZE < 0}
>
< Previous
</button>
<div style={{ display: "inline" }}>
{Math.floor(start / PAGE_SIZE)} /{" "}
{Math.floor(filteredFiles.length / PAGE_SIZE)}
</div>
<button
onClick={() => {
setStart(start + PAGE_SIZE);
setParamStart(start + PAGE_SIZE);
}}
disabled={start + PAGE_SIZE >= filteredFiles.length}
>
Next >
</button>
<button
onClick={() => {
setStart(
filteredFiles.length - (filteredFiles.length % PAGE_SIZE)
);
setParamStart(
filteredFiles.length - (filteredFiles.length % PAGE_SIZE)
);
}}
disabled={start + PAGE_SIZE >= filteredFiles.length}
>
>> Last
</button>
</div>
) : null}
</div>
);
}
function Header() {
const classes = useStyles();
return (
<div>
<div className={classes.space}>
<h1>
<a style={{ color: "white" }} href="/">
dixie
</a>
<img
src="img/animated-candle-image-0093.gif"
style={{ height: "1em" }}
/>
</h1>
<p>a pig that u never forget</p>
<h3>2008-2020</h3>
</div>
</div>
);
}
function App() {
const classes = useStyles();
const [width, setWidth] = useState(window.innerWidth);
const breakpoint = 700;
useEffect(() => {
const handleWindowResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleWindowResize);
return () => window.removeEventListener("resize", handleWindowResize);
}, []);
return (
<div className={classes.app}>
<Header />
<div>
<Gallery>
{width > breakpoint ? (
<Guestbook className={classes.embeddedGuestbook} />
) : null}
</Gallery>
{width < breakpoint ? <Guestbook /> : null}
</div>
<div
style={{
margin: "0 auto",
padding: "1em",
width: "25%",
minWidth: 300,
}}
>
<p className={classes.rainbow}>
created with love for the beautiful pig who touched our hearts
</p>
<img src="img/unnamed.gif" width={20} />
<a href="mailto:colin.diesh@gmail.com">contact</a>
</div>
</div>
);
}
export default App; | the_stack |
import { DisplayMode } from '@microsoft/sp-core-library';
import { clone } from '@microsoft/sp-lodash-subset';
import {
Checkbox,
DefaultButton,
findIndex,
Icon,
IconButton,
ISlider,
Panel,
PanelType,
Slider,
TextField
} from 'office-ui-fabric-react';
import * as React from 'react';
import ImageCrop from './components/ImageCrop';
import ImageGrid from './components/ImageGrid';
import ItemOrder from './components/ItemOrder';
import { GrayscaleFilter } from './Filter/GrayscaleFilter';
import { SepiaFilter } from './Filter/SepiaFilter';
import styles from './ImageManipulation.module.scss';
import {
FilterType,
filterTypeData,
ICrop,
ICropSettings,
IFilterSettings,
IFlipSettings,
IImageManipulationSettings,
IManipulationTypeDataDetails,
IResizeSettings,
IRotateSettings,
IScaleSettings,
ManipulationType,
manipulationTypeData,
SettingPanelType
} from './ImageManipulation.types';
// tslint:disable-next-line: no-any
const flipVerticalIcon: any = require('../../svg/flipVertical.svg');
// tslint:disable-next-line: no-any
const flipHorizontalIcon: any = require('../../svg/flipHorizontal.svg');
import * as strings from 'ImageManipulationStrings';
import { historyItem } from './HistoryItem';
export interface IImageManipulationConfig {
rotateButtons: number[];
}
export interface IImageManipulationProps {
src: string;
settings?: IImageManipulationSettings[];
settingsChanged?: (settings: IImageManipulationSettings[]) => void;
imgLoadError?: () => void;
editMode?: (mode: boolean) => void;
configSettings: IImageManipulationConfig;
displayMode: DisplayMode;
}
export interface IImageManipulationState {
settingPanel: SettingPanelType;
redosettings: IImageManipulationSettings[];
}
export class ImageManipulation extends React.Component<IImageManipulationProps, IImageManipulationState> {
private img: HTMLImageElement = undefined;
private wrapperRef: HTMLDivElement = undefined;
private bufferRef: HTMLCanvasElement = undefined;
private bufferCtx: CanvasRenderingContext2D = undefined;
private canvasRef: HTMLCanvasElement = undefined;
private canvasCtx: CanvasRenderingContext2D = undefined;
private manipulateRef: HTMLCanvasElement = undefined;
private manipulateCtx: CanvasRenderingContext2D = undefined;
constructor(props: IImageManipulationProps) {
super(props);
this.state = {
settingPanel: SettingPanelType.Closed,
redosettings: []
};
this.openPanel = this.openPanel.bind(this);
this.setRotate = this.setRotate.bind(this);
this.calcRotate = this.calcRotate.bind(this);
this.setCanvasRef = this.setCanvasRef.bind(this);
this.setBufferRef = this.setBufferRef.bind(this);
this.setManipulateRef = this.setManipulateRef.bind(this);
this.setScale = this.setScale.bind(this);
this.closeFilter = this.closeFilter.bind(this);
}
public componentDidMount(): void {
this.imageChanged(this.props.src);
}
public componentDidUpdate(prevProps: IImageManipulationProps): void {
if (prevProps.src !== this.props.src) {
this.imageChanged(this.props.src);
} else {
this.applySettings();
}
}
private imageChanged(url: string): void {
this.img = new Image();
this.img.src = url;
this.img.crossOrigin = 'Anonymous';
this.img.onload = () => {
this.applySettings();
};
this.img.onerror = (event: Event | string) => {
if (this.props.imgLoadError) {
this.props.imgLoadError();
}
};
}
private applySettings(): void {
this.canvasRef.width = this.img.width;
this.canvasRef.height = this.img.height;
this.bufferRef.width = this.img.width;
this.bufferRef.height = this.img.height;
this.manipulateRef.width = this.img.width;
this.manipulateRef.height = this.img.height;
let currentwidth: number = this.img.width;
let currentheight: number = this.img.height;
let newwidth: number = currentwidth;
let newheight: number = currentheight;
this.bufferCtx.clearRect(0, 0, currentwidth, currentheight);
this.bufferCtx.drawImage(this.img, 0, 0);
if (this.props.settings) {
this.props.settings.forEach((element, index) => {
this.manipulateCtx.clearRect(0, 0, currentwidth, currentheight);
this.manipulateRef.width = currentwidth;
this.manipulateRef.height = currentheight;
this.manipulateCtx.save();
let nothingToDo: boolean = false;
switch (element.type) {
case ManipulationType.Flip:
const filp: IFlipSettings = element as IFlipSettings;
if (filp.flipY) {
this.manipulateCtx.translate(0, currentheight);
this.manipulateCtx.scale(1, -1);
}
if (filp.flipX) {
this.manipulateCtx.translate(currentwidth, 0);
this.manipulateCtx.scale(-1, 1);
}
this.manipulateCtx.drawImage(this.bufferRef, 0, 0);
break;
case ManipulationType.Rotate:
const rotate: IRotateSettings = element as IRotateSettings;
if (!rotate.rotate || rotate.rotate === 0 || isNaN(rotate.rotate)) {
nothingToDo = true;
break;
}
if (rotate.rotate) {
const angelcalc = rotate.rotate * Math.PI / 180;
const oldwidth = currentwidth;
const oldheight = currentheight;
let offsetwidth = 0;
let offsetheight = 0;
const a: number = oldwidth * Math.abs(Math.cos(angelcalc));
const b: number = oldheight * Math.abs(Math.sin(angelcalc));
const p: number = oldwidth * Math.abs(Math.sin(angelcalc));
const q: number = oldheight * Math.abs(Math.cos(angelcalc));
newwidth = a + b;
newheight = p + q;
offsetwidth = (newwidth - oldwidth) / 2;
offsetheight = (newheight - oldheight) / 2;
this.manipulateRef.width = newwidth;
this.manipulateRef.height = newheight;
this.manipulateCtx.translate(newwidth / 2, newheight / 2);
this.manipulateCtx.rotate(angelcalc);
this.manipulateCtx.translate(newwidth / 2 * -1, newheight / 2 * -1);
this.manipulateCtx.drawImage(this.bufferRef, offsetwidth, offsetheight);
}
break;
case ManipulationType.Scale:
const scale: IScaleSettings = element as IScaleSettings;
if (scale.scale) {
this.manipulateCtx.translate(currentwidth / 2, currentheight / 2);
this.manipulateCtx.scale(scale.scale, scale.scale);
this.manipulateCtx.translate(currentwidth / 2 * -1, currentheight / 2 * -1);
this.manipulateCtx.drawImage(this.bufferRef, 0, 0);
}
break;
case ManipulationType.Crop:
const last: boolean = this.props.settings.length === index + 1;
if (last && this.state.settingPanel === SettingPanelType.Crop) {
// Do nothing is last and current edit
nothingToDo = true;
} else {
const crop: ICropSettings = element as ICropSettings;
const sourceX: number = crop.sx;
const sourceY: number = crop.sy;
newwidth = crop.width;
newheight = crop.height;
this.manipulateRef.width = newwidth;
this.manipulateRef.height = newheight;
this.manipulateCtx.drawImage(
this.bufferRef,
sourceX,
sourceY,
newwidth,
newheight,
0,
0,
newwidth,
newheight);
}
break;
case ManipulationType.Resize:
const resize: IResizeSettings = element as IResizeSettings;
newwidth = resize.width;
newheight = resize.height;
this.manipulateCtx.drawImage(this.bufferRef, 0, 0);
break;
case ManipulationType.Filter:
nothingToDo = true;
const filter = element as IFilterSettings;
var imageData = this.bufferCtx.getImageData(0, 0, currentwidth, currentheight);
switch (filter.filterType) {
case FilterType.Grayscale:
imageData = new GrayscaleFilter().process(imageData, currentwidth, currentheight, undefined, undefined);
break;
case FilterType.Sepia:
imageData = new SepiaFilter().process(imageData, currentwidth, currentheight, undefined, undefined);
break;
}
this.bufferCtx.putImageData(imageData, 0, 0);
break;
}
this.manipulateCtx.restore();
if (!nothingToDo) {
this.bufferCtx.clearRect(0, 0, currentwidth, currentheight);
this.bufferRef.width = newwidth;
this.bufferRef.height = newheight;
this.bufferCtx.clearRect(0, 0, newwidth, newheight);
this.bufferCtx.drawImage(this.manipulateRef, 0, 0, newwidth, newheight);
currentwidth = newwidth;
currentheight = newheight;
}
});
}
/*this.canvasCtx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height)
// this.canvasCtx.drawImage(this.bufferRef, 0, 0);
const sourceX = 400;
const sourceY = 200;
const sourceWidth = 1200;
const sourceHeight = 600;
this.canvasCtx.drawImage(
this.bufferRef, sourceX, sourceY, sourceWidth,
sourceHeight, 0, 0, this.canvasRef.width, this.canvasRef.height);
*/
this.canvasCtx.clearRect(0, 0, currentwidth, currentheight);
this.canvasRef.width = currentwidth;
this.canvasRef.height = currentheight;
this.canvasCtx.drawImage(this.bufferRef, 0, 0);
// this.canvasCtx.drawImage(this.bufferRef, 0, 0, currentwidth, currentheight);
this.wrapperRef.style.width = currentwidth + 'px';
// this.wrapperRef.style.height = currentheight + 'px';
// let height = this.canvasRef.height;
// let width = this.canvasRef.width;
// this.canvasctx.translate(this.canvasRef.width / 2 * -1, this.canvasRef.height / 2 * -1);
}
public render(): React.ReactElement<IImageManipulationProps> {
return (
<div className={styles.imageEditor} style={{
marginTop: this.props.displayMode === DisplayMode.Edit ? '40px' : '0px',
}} >
{this.props.displayMode === DisplayMode.Edit && this.getCommandBar()}
<div className={styles.imageplaceholder + ' ' + this.getMaxWidth()}
ref={(element: HTMLDivElement) => { this.wrapperRef = element; }}
style={this.canvasRef && { width: '' + this.canvasRef.width + 'px' }}
>
<canvas className={this.getMaxWidth()}
style={{ display: 'none' }}
ref={this.setBufferRef}></canvas>
<canvas className={this.getMaxWidth()}
style={{ display: 'none' }}
ref={this.setManipulateRef}></canvas>
<canvas className={this.getMaxWidth()} ref={this.setCanvasRef} ></canvas>
{this.state.settingPanel === SettingPanelType.Crop && (this.getCropGrid())}
{this.state.settingPanel === SettingPanelType.Resize && (this.getResizeGrid())}
</div>
</div>
);
}
private getCropGrid(): JSX.Element {
const lastset: ICropSettings = this.getLastManipulation() as ICropSettings;
let lastdata: ICrop = { sx: 0, sy: 0, width: 0, height: 0 };
if (lastset && lastset.type === ManipulationType.Crop) {
lastdata = lastset;
}
return (<ImageCrop
crop={lastdata}
showRuler
sourceHeight={this.img.height}
sourceWidth={this.img.width}
onChange={(crop) => {
this.setCrop(crop.sx, crop.sy, crop.width, crop.height, crop.aspect);
}
}
/>);
}
private getResizeGrid(): JSX.Element {
const lastset: IResizeSettings = this.getLastManipulation() as IResizeSettings;
if (lastset && lastset.type === ManipulationType.Resize) {
return (<ImageGrid
width={lastset.width} height={lastset.height}
aspect={lastset.aspect}
onChange={(size) => this.setResize(size.width, size.height, lastset.aspect)}
/>);
}
return (<ImageGrid
onChange={(size) => this.setResize(size.width, size.height, undefined)}
// aspect={this.getAspect()}
width={this.canvasRef.width} height={this.canvasRef.height} />);
}
private getMaxWidth(): string {
const { settingPanel } = this.state;
if (settingPanel === SettingPanelType.Crop || settingPanel === SettingPanelType.Resize) {
return '';
}
return styles.canvasmaxwidth;
}
private isFilterActive(type: FilterType): boolean {
return (this.props.settings && this.props.settings.filter(
(f) => f.type === ManipulationType.Filter
&& (f as IFilterSettings).filterType === type).length > 0);
}
private closeFilter(): void {
this.setState({
settingPanel: SettingPanelType.Closed
}, () => this.toggleEditMode(false));
}
private getPanelHeader(settingPanel: SettingPanelType): string {
switch (settingPanel) {
case SettingPanelType.Filter:
return strings.ManipulationTypeFilter;
case SettingPanelType.Flip:
return strings.ManipulationTypeFlip;
case SettingPanelType.Rotate:
return strings.ManipulationTypeRotate;
case SettingPanelType.Scale:
return strings.ManipulationTypeScale;
case SettingPanelType.Crop:
return strings.ManipulationTypeCrop;
case SettingPanelType.Resize:
return strings.ManipulationTypeResize;
case SettingPanelType.History:
return strings.SettingPanelHistory;
}
}
private onRenderFooterContent(): JSX.Element {
return (
<div> </div>
);
}
private renderPanelContent(): JSX.Element {
switch (this.state.settingPanel) {
case SettingPanelType.Filter:
return this.getFilterSettings();
case SettingPanelType.Flip:
return this.getFlipSettings();
case SettingPanelType.Rotate:
return this.getRotateSettings();
case SettingPanelType.Scale:
return this.getScaleSettings();
case SettingPanelType.Crop:
return this.getCropSettings();
case SettingPanelType.Resize:
return this.getResizeSettings();
case SettingPanelType.History:
return this.getHistorySettings();
}
}
private openPanel(settingPanel: SettingPanelType): void {
this.setState({
settingPanel: settingPanel
}, () => this.toggleEditMode(true));
}
private toggleEditMode(mode: boolean): void {
if (this.props.editMode) {
this.props.editMode(mode);
}
}
private getHistorySettings(): JSX.Element {
return (<ItemOrder
label={''}
disabled={false}
moveUpIconName={'ChevronUpSmall'}
moveDownIconName={'ChevronDownSmall'}
disableDragAndDrop={false}
removeArrows={false}
items={this.props.settings}
valueChanged={(newhist) => {
if (this.state.redosettings && this.state.redosettings.length > 0) {
this.setState({ redosettings: [] }, () => {
if (this.props.settingsChanged) {
this.props.settingsChanged(newhist);
}
});
} else {
if (this.props.settingsChanged) {
this.props.settingsChanged(newhist);
}
}
}}
onRenderItem={historyItem}
/>);
}
private getFilterSettings(): JSX.Element {
return (<div>
{
Object.keys(filterTypeData).map((key, index) => {
return (<Checkbox
key={'Filter' + index}
label={filterTypeData[key]}
checked={this.isFilterActive((+key) as FilterType)}
onChange={() => this.toggleFilter((+key) as FilterType)}
/>);
})
}</div>);
}
private toggleFilter(type: FilterType, nvalue: number = undefined, svalue: string = undefined): void {
let tmpsettings: IImageManipulationSettings[] = clone(this.props.settings);
if (!tmpsettings) { tmpsettings = []; }
if (tmpsettings.filter(
(f) => f.type === ManipulationType.Filter && (f as IFilterSettings).filterType === type).length > 0) {
const removeindex: number = findIndex(tmpsettings,
(f) => f.type === ManipulationType.Filter && (f as IFilterSettings).filterType === type);
tmpsettings.splice(removeindex, 1);
} else {
tmpsettings.push({
type: ManipulationType.Filter,
filterType: type,
nvalue: nvalue,
svalue: svalue
});
}
if (this.props.settingsChanged) {
this.props.settingsChanged(tmpsettings);
}
}
private getFlipSettings(): JSX.Element {
return (<div className={styles.buttonHolderPanel} >
<IconButton
iconProps={{ iconName: 'SwitcherStartEnd' }}
onRenderIcon={() => {
// tslint:disable-next-line: react-a11y-img-has-alt
return (<img className={styles.svgbuttonPanel} src={flipVerticalIcon} />);
}}
title={strings.FlipHorizontal}
ariaLabel={strings.FlipHorizontal}
onClick={() => {
const last: IImageManipulationSettings = this.getLastManipulation();
if (last && last.type === ManipulationType.Flip) {
(last as IFlipSettings).flipX = !(last as IFlipSettings).flipX;
if ((last as IFlipSettings).flipX === false &&
(last as IFlipSettings).flipY === false) {
this.removeLastManipulation();
} else {
this.addOrUpdateLastManipulation(last);
}
} else {
this.addOrUpdateLastManipulation({ type: ManipulationType.Flip, flipX: true, flipY: false });
}
}}
/>
<IconButton
onRenderIcon={() => {
// tslint:disable-next-line: react-a11y-img-has-alt
return (<img className={styles.svgbuttonPanel} src={flipHorizontalIcon} />);
}}
title={strings.FlipVertical}
ariaLabel={strings.FlipVertical}
onClick={() => {
const last: IImageManipulationSettings = this.getLastManipulation();
if (last && last.type === ManipulationType.Flip) {
(last as IFlipSettings).flipY = !(last as IFlipSettings).flipY;
if ((last as IFlipSettings).flipX === false &&
(last as IFlipSettings).flipY === false) {
this.removeLastManipulation();
} else {
this.addOrUpdateLastManipulation(last);
}
} else {
this.addOrUpdateLastManipulation({ type: ManipulationType.Flip, flipX: false, flipY: true });
}
}}
/>
</div>);
}
private getRotateSettings(): JSX.Element {
const lastvalue: IImageManipulationSettings = this.getLastManipulation();
let rotatevalue: number = 0;
if (lastvalue && lastvalue.type === ManipulationType.Rotate) {
rotatevalue = (lastvalue as IRotateSettings).rotate ? (lastvalue as IRotateSettings).rotate : 0;
}
return (<div>
<div>
{this.props.configSettings.rotateButtons.map((value: number, index: number) => {
let icon: string = 'CompassNW';
if (value !== 0) { icon = 'Rotate'; }
return (<DefaultButton
key={'rotate' + index}
onClick={() => {
if (value === 0) {
this.setRotate(value);
} else {
this.calcRotate(value);
}
}}
className={styles.iconbtn}
>
<Icon iconName={icon} style={value < 0 ? { transform: 'scaleX(-1)' } : {}} className={styles.imgicon} />
<span className={styles.imgtext} >{'' + value}</span></DefaultButton>);
})}
</div>
<Slider
label=''
min={-180}
max={180}
value={rotatevalue}
onChange={this.setRotate}
showValue={true}
componentRef={(component: ISlider | null) => {
// Initial Value has a bug 0 is min value only min value is negative
// tslint:disable-next-line: no-any
const correctBugComponent: any = component as any;
if (correctBugComponent
&& correctBugComponent.state
&& correctBugComponent.value !== correctBugComponent.props.value) {
correctBugComponent.setState({ value: 0, renderedValue: 0 });
}
}}
// originFromZero
/>
<IconButton
key={'resetrotate'}
disabled={!(lastvalue && lastvalue.type === ManipulationType.Rotate)}
iconProps={{ iconName: 'Undo' }}
ariaLabel={strings.CommandBarReset}
onClick={() => { this.removeLastManipulation(); }
}
/>
</div >);
}
private getCropSettings(): JSX.Element {
const crop: ICropSettings = this.getCropValues();
return (<div>
<Checkbox
label={strings.LockAspect}
checked={!isNaN(crop.aspect)}
onChange={() => {
if (isNaN(crop.aspect)) {
this.setCrop(undefined, undefined, undefined, undefined, this.getAspect());
} else {
this.setCrop(undefined, undefined, undefined, undefined, undefined);
}
}}
/>
<TextField
label={strings.SourceX}
value={'' + crop.sx}
// tslint:disable-next-line: radix
onChanged={(x) => this.setCrop(parseInt(x), undefined, undefined, undefined, crop.aspect)} />
<TextField
label={strings.SourceY}
value={'' + crop.sy}
// tslint:disable-next-line: radix
onChanged={(y) => this.setCrop(undefined, parseInt(y), undefined, undefined, crop.aspect)} />
<TextField
label={strings.Width}
value={'' + crop.width}
// tslint:disable-next-line: radix
onChanged={(w) => this.setCrop(undefined, undefined, parseInt(w), undefined, crop.aspect)} />
<TextField
label={strings.Height}
value={'' + crop.height}
// tslint:disable-next-line: radix
onChanged={(h) => this.setCrop(undefined, undefined, undefined, parseInt(h), crop.aspect)} />
</div>);
}
private getResizeSettings(): JSX.Element {
const resize: IResizeSettings = this.getResizeValues();
return (<div>
<Checkbox
label={strings.LockAspect}
checked={!isNaN(resize.aspect)}
onChange={() => {
if (isNaN(resize.aspect)) {
this.setResize(undefined, undefined, this.getAspect());
} else {
this.setResize(undefined, undefined, undefined);
}
}}
/>
<TextField label={strings.Width}
value={'' + resize.width}
// tslint:disable-next-line: radix
onChanged={(w) => this.setResize(parseInt(w), undefined, resize.aspect)}
/>
<TextField label={strings.Height} value={'' + resize.height}
// tslint:disable-next-line: radix
onChanged={(h) => this.setResize(undefined, parseInt(h), resize.aspect)}
/>
</div>);
}
private getAspect(): number {
return this.canvasRef.width / this.canvasRef.height;
}
private getScaleSettings(): JSX.Element {
const lastvalue: IImageManipulationSettings = this.getLastManipulation();
let scalevalue: number = 1;
if (lastvalue && lastvalue.type === ManipulationType.Scale) {
scalevalue = (lastvalue as IScaleSettings).scale ?
(lastvalue as IScaleSettings).scale : 1;
}
return (<div>
<Slider
label=''
min={0.1}
max={5}
step={0.1}
value={scalevalue}
onChange={this.setScale}
showValue={true}
/>
<IconButton
key={'resetscale'}
disabled={!(lastvalue && lastvalue.type === ManipulationType.Scale)}
iconProps={{ iconName: 'Undo' }}
title={strings.CommandBarReset}
ariaLabel={strings.CommandBarReset}
onClick={() => { this.setScale(1); }
}
/>
</div>);
}
private getResizeValues(): IResizeSettings {
const state: IImageManipulationSettings = this.getLastManipulation();
let values: IResizeSettings = {
type: ManipulationType.Resize,
height: this.bufferRef.height,
width: this.bufferRef.width
};
if (state && state.type === ManipulationType.Resize) {
values = state as IResizeSettings;
}
return values;
}
private setResize(width: number, height: number, aspect: number): void {
const values: IResizeSettings = this.getResizeValues();
if (width) {
values.width = width;
if (aspect) {
values.height = values.width / aspect;
}
}
if (height) {
values.height = height;
if (aspect) {
values.width = values.height * aspect;
}
}
values.aspect = aspect;
this.addOrUpdateLastManipulation(values);
}
private getCropValues(): ICropSettings {
const state: IImageManipulationSettings = this.getLastManipulation();
let values: ICropSettings = {
type: ManipulationType.Crop,
sx: 0,
sy: 0,
height: this.bufferRef.height,
width: this.bufferRef.width
};
if (state && state.type === ManipulationType.Crop) {
values = state as ICropSettings;
}
return values;
}
private setCrop(sx: number, sy: number, width: number, height: number, aspect: number): void {
const values: ICropSettings = this.getCropValues();
const currentheight: number = this.bufferRef.height;
const currentwidth: number = this.bufferRef.width;
if (!isNaN(sx) && sx >= 0) {
if (sx >= currentwidth) {
values.sx = currentwidth - 1;
} else {
values.sx = sx;
}
// limit max width
if ((values.width + values.sx) > currentwidth) {
values.width = currentwidth - values.sx;
}
}
if (!isNaN(sy) && sy >= 0) {
if (sy >= currentheight) {
values.sy = currentheight - 1;
} else {
values.sy = sy;
}
// limit max height
if ((values.height + values.sy) > currentheight) {
values.height = currentheight - values.sy;
}
}
if (!isNaN(width) && width >= 0) {
if ((width + values.sx) > currentwidth) {
values.width = currentwidth - values.sx;
} else {
values.width = width;
}
}
if (!isNaN(height) && height >= 0) {
if ((height + values.sy) > currentheight) {
values.height = currentheight - values.sy;
} else {
values.height = height;
}
}
if (isNaN(values.aspect) && !isNaN(aspect)) {
// aspect added
// limit w
if ((values.width + values.sx) > currentwidth) {
values.width = currentwidth - values.sx;
}
values.height = values.width / aspect;
// limit h adn recalulate w
if ((values.height + values.sy) > currentheight) {
values.height = currentheight - values.sy;
values.width = values.height * aspect;
}
}
values.aspect = aspect;
if (aspect && (!isNaN(sx) || !isNaN(width))) {
values.height = values.width / aspect;
}
if (aspect && (!isNaN(sy) || !isNaN(height))) {
values.width = values.height * aspect;
}
this.addOrUpdateLastManipulation(values);
}
private setRotate(value: number): void {
this.addOrUpdateLastManipulation({
type: ManipulationType.Rotate,
rotate: value
});
}
private setScale(value: number): void {
this.addOrUpdateLastManipulation({
type: ManipulationType.Scale,
scale: value
});
}
private calcRotate(value: number): void {
const lastVal: IImageManipulationSettings = this.getLastManipulation();
let cvalue: number = 0;
if (lastVal && lastVal.type === ManipulationType.Rotate) {
cvalue = (lastVal as IRotateSettings).rotate;
}
cvalue = cvalue + value;
if (cvalue < -180) { cvalue = -180; }
if (cvalue > 180) { cvalue = 180; }
this.addOrUpdateLastManipulation({
type: ManipulationType.Rotate,
rotate: cvalue
});
}
private setCanvasRef(element: HTMLCanvasElement): void {
this.canvasRef = element;
if (this.canvasRef) {
this.canvasCtx = element.getContext('2d');
} else {
console.log('no canvas context ');
}
}
private setBufferRef(element: HTMLCanvasElement): void {
this.bufferRef = element;
if (this.bufferRef) {
this.bufferCtx = element.getContext('2d');
} else {
console.log('no buffer context ');
}
}
private setManipulateRef(element: HTMLCanvasElement): void {
this.manipulateRef = element;
if (this.manipulateRef) {
this.manipulateCtx = element.getContext('2d');
} else {
console.log('no manipulation context ');
}
}
private getLastManipulation(): IImageManipulationSettings {
if (this.props.settings && this.props.settings.length > 0) {
return this.props.settings[this.props.settings.length - 1];
}
return undefined;
}
private addOrUpdateLastManipulation(changed: IImageManipulationSettings): void {
let state: IImageManipulationSettings[] = clone(this.props.settings);
if (!state) {
state = [];
}
if (state.length > 0 && state[state.length - 1].type === changed.type) {
state[state.length - 1] = changed;
} else {
state.push(changed);
}
if (this.state.redosettings && this.state.redosettings.length > 0) {
this.setState({ redosettings: [] }, () => {
if (this.props.settingsChanged) {
this.props.settingsChanged(state);
}
});
} else {
if (this.props.settingsChanged) {
this.props.settingsChanged(state);
}
}
}
private removeLastManipulation(): void {
if (this.props.settings && this.props.settings.length > 0) {
const state: IImageManipulationSettings[] = clone(this.props.settings);
state.splice(state.length - 1, 1);
if (this.props.settingsChanged) {
this.props.settingsChanged(clone(state));
}
}
}
private getActionHeaderButton(options: IManipulationTypeDataDetails): JSX.Element {
return (<IconButton
iconProps={{ iconName: options.iconName }}
onRenderIcon={(p, defaultrenderer) => {
if (options.svgIcon) {
// tslint:disable-next-line: react-a11y-img-has-alt
return (<img className={styles.svgbutton} src={options.svgIcon} />);
}
return defaultrenderer(p);
}}
title={options.text}
ariaLabel={options.text}
onClick={() => this.openPanel(options.settingPanelType)}
/>);
}
private getCommandBar(): JSX.Element {
return (<div className={styles.commandBar}>
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Resize])}
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Crop])}
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Flip])}
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Rotate])}
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Scale])}
{this.getActionHeaderButton(manipulationTypeData[ManipulationType.Filter])}
<IconButton
iconProps={{ iconName: 'Undo' }}
title={strings.CommandBarUndo}
ariaLabel={strings.CommandBarUndo}
disabled={!this.props.settings || this.props.settings.length < 1}
onClick={() => {
const settings: IImageManipulationSettings[] = clone(this.props.settings);
const last: IImageManipulationSettings = settings.pop();
const redo: IImageManipulationSettings[] = clone(this.state.redosettings);
redo.push(last);
this.setState({ redosettings: redo },
() => {
if (this.props.settingsChanged) {
this.props.settingsChanged(settings);
}
});
}}
/>
<IconButton
iconProps={{ iconName: 'Redo' }}
title={strings.CommandBarRedo}
ariaLabel={strings.CommandBarRedo}
disabled={!this.state.redosettings || this.state.redosettings.length < 1}
onClick={() => {
const redosettings: IImageManipulationSettings[] = clone(this.state.redosettings);
const redo: IImageManipulationSettings = redosettings.pop();
const settings: IImageManipulationSettings[] = clone(this.props.settings);
settings.push(redo);
this.setState({ redosettings: redosettings },
() => {
if (this.props.settingsChanged) {
this.props.settingsChanged(settings);
}
});
}}
/>
<IconButton
iconProps={{ iconName: 'Delete' }}
title={strings.CommandBarReset}
ariaLabel={strings.CommandBarReset}
disabled={!this.props.settings || this.props.settings.length < 1}
onClick={() => {
this.setState({ redosettings: [] },
() => {
if (this.props.settingsChanged) {
this.props.settingsChanged([]);
}
});
}}
/>
<IconButton
iconProps={{ iconName: 'History' }}
title={strings.SettingPanelHistory}
ariaLabel={strings.SettingPanelHistory}
disabled={!this.props.settings || this.props.settings.length < 1}
onClick={() => this.openPanel(SettingPanelType.History)}
/>
<Panel
isOpen={this.state.settingPanel !== SettingPanelType.Closed}
type={PanelType.smallFixedFar}
onDismiss={this.closeFilter}
headerText={this.getPanelHeader(this.state.settingPanel)}
closeButtonAriaLabel={strings.SettingPanelClose}
isBlocking={false}
onRenderFooterContent={this.onRenderFooterContent}
>
{this.renderPanelContent()}
</Panel>
</div>);
}
} | the_stack |
import { GraphQLSchema, GraphQLScalarType, Kind, SelectionSetNode, graphql, OperationTypeNode } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { wrapSchema, WrapQuery, ExtractField, TransformQuery } from '@graphql-tools/wrap';
import { delegateToSchema, defaultMergedResolver } from '@graphql-tools/delegate';
import { createGraphQLError } from '@graphql-tools/utils';
function createError<T>(message: string, extra?: T) {
const error = new Error(message);
Object.assign(error, extra);
return error as Error & T;
}
describe('transforms', () => {
describe('base transform function', () => {
const scalarTest = /* GraphQL */ `
scalar TestScalar
type TestingScalar {
value: TestScalar
}
type Query {
testingScalar(input: TestScalar): TestingScalar
}
`;
const scalarSchema = makeExecutableSchema({
typeDefs: scalarTest,
resolvers: {
TestScalar: new GraphQLScalarType({
name: 'TestScalar',
description: undefined,
serialize: value => (value as string).slice(1),
parseValue: value => `_${value as string}`,
parseLiteral: (ast: any) => `_${ast.value as string}`,
}),
Query: {
testingScalar(_parent, args) {
return {
value: args.input[0] === '_' ? args.input : null,
};
},
},
},
});
test('should work', async () => {
const schema = wrapSchema({ schema: scalarSchema });
const result = await graphql({
schema,
source: /* GraphQL */ `
query ($input: TestScalar) {
testingScalar(input: $input) {
value
}
}
`,
variableValues: {
input: 'test',
},
});
expect(result).toEqual({
data: {
testingScalar: {
value: 'test',
},
},
});
});
test('should work when specified as a subschema configuration object', async () => {
const schema = wrapSchema({
schema: scalarSchema,
transforms: [],
});
const result = await graphql({
schema,
source: /* GraphQL */ `
query ($input: TestScalar) {
testingScalar(input: $input) {
value
}
}
`,
variableValues: {
input: 'test',
},
});
expect(result).toEqual({
data: {
testingScalar: {
value: 'test',
},
},
});
});
test('should not change error type', async () => {
const customError = createError('TestError', {
data: { code: '123' },
message: 'TestError Error',
});
const subschema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Query {
errorTest: String
}
`,
resolvers: {
Query: {
errorTest: () => customError,
},
},
});
const schema = wrapSchema({ schema: subschema });
const query = /* GraphQL */ `
query {
errorTest
}
`;
const originalResult = await graphql({
schema: subschema,
source: query,
});
const transformedResult = await graphql({
schema,
source: query,
});
expect(originalResult).toEqual(transformedResult);
});
});
describe('tree operations', () => {
let data: any;
let subschema: GraphQLSchema;
let schema: GraphQLSchema;
beforeAll(() => {
data = {
u1: {
id: 'u1',
username: 'alice',
address: {
streetAddress: 'Windy Shore 21 A 7',
zip: '12345',
},
},
u2: {
id: 'u2',
username: 'bob',
address: {
streetAddress: 'Snowy Mountain 5 B 77',
zip: '54321',
},
},
};
subschema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type User {
id: ID!
username: String
address: Address
}
type Address {
streetAddress: String
zip: String
}
input UserInput {
id: ID!
username: String
}
input AddressInput {
id: ID!
streetAddress: String
zip: String
}
type Query {
userById(id: ID!): User
}
type Mutation {
setUser(input: UserInput!): User
setAddress(input: AddressInput!): Address
}
`,
resolvers: {
Query: {
userById(_parent, { id }) {
return data[id];
},
},
Mutation: {
setUser(_parent, { input }) {
if (data[input.id]) {
return {
...data[input.id],
...input,
};
}
},
setAddress(_parent, { input }) {
if (data[input.id]) {
return {
...data[input.id].address,
...input,
};
}
},
},
},
});
schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type User {
id: ID!
username: String
address: Address
}
type Address {
streetAddress: String
zip: String
}
input UserInput {
id: ID!
username: String
streetAddress: String
zip: String
}
type Query {
addressByUser(id: ID!): Address
}
type Mutation {
setUserAndAddress(input: UserInput!): User
}
`,
resolvers: {
Query: {
addressByUser(_parent, { id }, context, info) {
return delegateToSchema({
schema: subschema,
operation: 'query' as OperationTypeNode,
fieldName: 'userById',
args: { id },
context,
info,
transforms: [
// Wrap document takes a subtree as an AST node
new WrapQuery(
// path at which to apply wrapping and extracting
['userById'],
(subtree: SelectionSetNode) => ({
// we create a wrapping AST Field
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
// that field is `address`
value: 'address',
},
// Inside the field selection
selectionSet: subtree,
}),
// how to process the data result at path
result => result?.address
),
],
});
},
},
Mutation: {
async setUserAndAddress(_parent, { input }, context, info) {
const addressResult = await delegateToSchema({
schema: subschema,
operation: 'mutation' as OperationTypeNode,
fieldName: 'setAddress',
args: {
input: {
id: input.id,
streetAddress: input.streetAddress,
zip: input.zip,
},
},
context,
info,
transforms: [
// ExtractField takes a path from which to extract the query
// for delegation and path to which to move it
new ExtractField({
from: ['setAddress', 'address'],
to: ['setAddress'],
}),
],
});
const userResult = await delegateToSchema({
schema: subschema,
operation: 'mutation' as OperationTypeNode,
fieldName: 'setUser',
args: {
input: {
id: input.id,
username: input.username,
},
},
context,
info,
});
return {
...userResult,
address: addressResult,
};
},
},
},
});
});
test('wrapping delegation', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
query {
addressByUser(id: "u1") {
streetAddress
zip
}
}
`,
});
expect(result).toEqual({
data: {
addressByUser: {
streetAddress: 'Windy Shore 21 A 7',
zip: '12345',
},
},
});
});
test('extracting delegation', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
mutation ($input: UserInput!) {
setUserAndAddress(input: $input) {
username
address {
zip
streetAddress
}
}
}
# fragment UserFragment on User {
# address {
# zip
# ...AddressFragment
# }
# }
#
# fragment AddressFragment on Address {
# streetAddress
# }
`,
variableValues: {
input: {
id: 'u2',
username: 'new-username',
streetAddress: 'New Address 555',
zip: '22222',
},
},
});
expect(result).toEqual({
data: {
setUserAndAddress: {
username: 'new-username',
address: {
streetAddress: 'New Address 555',
zip: '22222',
},
},
},
});
});
});
describe('TransformQuery', () => {
let data: any;
let subschema: GraphQLSchema;
let schema: GraphQLSchema;
beforeAll(() => {
data = {
u1: {
id: 'u1',
username: 'alice',
address: {
streetAddress: 'Windy Shore 21 A 7',
zip: '12345',
},
},
u2: {
id: 'u2',
username: 'bob',
address: {
streetAddress: 'Snowy Mountain 5 B 77',
zip: '54321',
},
},
};
subschema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type User {
id: ID!
username: String
address: Address
errorTest: Address
}
type Address {
streetAddress: String
zip: String
errorTest: String
}
scalar PageInfo
type UserConnection {
pageInfo: PageInfo!
nodes: [User!]
}
type Query {
userById(id: ID!): User
usersByIds(ids: [ID!]): UserConnection!
}
`,
resolvers: {
User: {
errorTest: () => {
throw new Error('Test Error!');
},
},
Address: {
errorTest: () => {
throw new Error('Test Error!');
},
},
Query: {
userById(_parent, { id }) {
return data[id];
},
usersByIds(_parent, { ids }) {
return {
nodes: Object.entries(data)
.filter(([id, _value]) => ids.includes(id))
.map(([_id, value]) => value),
pageInfo: '1',
};
},
},
},
});
schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
type Address {
streetAddress: String
zip: String
errorTest: String
}
scalar PageInfo
type AddressConnection {
pageInfo: PageInfo!
nodes: [Address!]
}
type Query {
addressByUser(id: ID!): Address
errorTest(id: ID!): Address
addressesByUsers(ids: [ID!]): AddressConnection!
}
`,
resolvers: {
Query: {
addressByUser(_parent, { id }, context, info) {
return delegateToSchema({
schema: subschema,
operation: 'query' as OperationTypeNode,
fieldName: 'userById',
args: { id },
context,
info,
transforms: [
// Wrap document takes a subtree as an AST node
new TransformQuery({
// path at which to apply wrapping and extracting
path: ['userById'],
queryTransformer: (subtree: SelectionSetNode | undefined) => ({
kind: Kind.SELECTION_SET,
selections: [
{
// we create a wrapping AST Field
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
// that field is `address`
value: 'address',
},
// Inside the field selection
selectionSet: subtree,
},
],
}),
// how to process the data result at path
resultTransformer: result => result?.address,
errorPathTransformer: path => path.slice(1),
}),
],
});
},
addressesByUsers(_parent, { ids }, context, info) {
return delegateToSchema({
schema: subschema,
operation: 'query' as OperationTypeNode,
fieldName: 'usersByIds',
args: { ids },
context,
info,
transforms: [
// Wrap document takes a subtree as an AST node
new TransformQuery({
// longer path, useful when transforming paginated results
path: ['usersByIds', 'nodes'],
queryTransformer: (subtree: SelectionSetNode | undefined) => ({
// same query transformation as above
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: 'address',
},
selectionSet: subtree,
},
],
}),
// how to process the data result at path
resultTransformer: result => result.map((u: any) => u.address),
errorPathTransformer: path => path.slice(1),
}),
],
});
},
errorTest(_parent, { id }, context, info) {
return delegateToSchema({
schema: subschema,
operation: 'query' as OperationTypeNode,
fieldName: 'userById',
args: { id },
context,
info,
transforms: [
new TransformQuery({
path: ['userById'],
queryTransformer: (subtree: SelectionSetNode | undefined) => ({
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: {
kind: Kind.NAME,
value: 'errorTest',
},
selectionSet: subtree,
},
],
}),
resultTransformer: result => result?.address,
errorPathTransformer: path => path.slice(1),
}),
],
});
},
},
},
});
});
test('wrapping delegation', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
query {
addressByUser(id: "u1") {
streetAddress
zip
}
}
`,
});
expect(result).toEqual({
data: {
addressByUser: {
streetAddress: 'Windy Shore 21 A 7',
zip: '12345',
},
},
});
});
test('preserves errors from underlying fields', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
query {
addressByUser(id: "u1") {
errorTest
}
}
`,
fieldResolver: defaultMergedResolver,
});
expect(result).toEqual({
data: {
addressByUser: {
errorTest: null,
},
},
errors: [
createGraphQLError('Test Error!', {
positions: [15, 4],
path: ['addressByUser', 'errorTest'],
}),
],
});
});
test('preserves errors when delegating from a root field to an error', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
query {
errorTest(id: "u1") {
errorTest
}
}
`,
fieldResolver: defaultMergedResolver,
});
expect(result).toEqual({
data: {
errorTest: null,
},
errors: [new Error('Test Error!')],
});
});
test('nested path produces nested result, other fields get preserved', async () => {
const result = await graphql({
schema,
source: /* GraphQL */ `
query {
addressesByUsers(ids: ["u1", "u2"]) {
nodes {
streetAddress
zip
}
pageInfo
}
}
`,
});
expect(result).toEqual({
data: {
addressesByUsers: {
nodes: [
{
streetAddress: 'Windy Shore 21 A 7',
zip: '12345',
},
{
streetAddress: 'Snowy Mountain 5 B 77',
zip: '54321',
},
],
pageInfo: '1',
},
},
});
});
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A Certificate corresponds to a signed X.509 certificate issued by a Certificate.
*
* > **Note:** The Certificate Authority that is referenced by this resource **must** be
* `tier = "ENTERPRISE"`
*
* ## Example Usage
* ### Privateca Certificate Config
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const test_ca = new gcp.certificateauthority.Authority("test-ca", {
* certificateAuthorityId: "my-certificate-authority",
* location: "us-central1",
* pool: "",
* ignoreActiveCertificatesOnDeletion: true,
* config: {
* subjectConfig: {
* subject: {
* organization: "HashiCorp",
* commonName: "my-certificate-authority",
* },
* subjectAltName: {
* dnsNames: ["hashicorp.com"],
* },
* },
* x509Config: {
* caOptions: {
* isCa: true,
* },
* keyUsage: {
* baseKeyUsage: {
* certSign: true,
* crlSign: true,
* },
* extendedKeyUsage: {
* serverAuth: true,
* },
* },
* },
* },
* keySpec: {
* algorithm: "RSA_PKCS1_4096_SHA256",
* },
* });
* const _default = new gcp.certificateauthority.Certificate("default", {
* pool: "",
* location: "us-central1",
* certificateAuthority: test_ca.certificateAuthorityId,
* lifetime: "860s",
* config: {
* subjectConfig: {
* subject: {
* commonName: "san1.example.com",
* countryCode: "us",
* organization: "google",
* organizationalUnit: "enterprise",
* locality: "mountain view",
* province: "california",
* streetAddress: "1600 amphitheatre parkway",
* },
* subjectAltName: {
* emailAddresses: ["email@example.com"],
* ipAddresses: ["127.0.0.1"],
* uris: ["http://www.ietf.org/rfc/rfc3986.txt"],
* },
* },
* x509Config: {
* caOptions: {
* nonCa: true,
* isCa: false,
* },
* keyUsage: {
* baseKeyUsage: {
* crlSign: false,
* decipherOnly: false,
* },
* extendedKeyUsage: {
* serverAuth: false,
* },
* },
* },
* publicKey: {
* format: "PEM",
* key: Buffer.from(fs.readFileSync("test-fixtures/rsa_public.pem"), 'binary').toString('base64'),
* },
* },
* });
* ```
* ### Privateca Certificate With Template
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const template = new gcp.certificateauthority.CertificateTemplate("template", {
* location: "us-central1",
* description: "An updated sample certificate template",
* identityConstraints: {
* allowSubjectAltNamesPassthrough: true,
* allowSubjectPassthrough: true,
* celExpression: {
* description: "Always true",
* expression: "true",
* location: "any.file.anywhere",
* title: "Sample expression",
* },
* },
* passthroughExtensions: {
* additionalExtensions: [{
* objectIdPaths: [
* 1,
* 6,
* ],
* }],
* knownExtensions: ["EXTENDED_KEY_USAGE"],
* },
* predefinedValues: {
* additionalExtensions: [{
* objectId: {
* objectIdPaths: [
* 1,
* 6,
* ],
* },
* value: "c3RyaW5nCg==",
* critical: true,
* }],
* aiaOcspServers: ["string"],
* caOptions: {
* isCa: false,
* maxIssuerPathLength: 6,
* },
* keyUsage: {
* baseKeyUsage: {
* certSign: false,
* contentCommitment: true,
* crlSign: false,
* dataEncipherment: true,
* decipherOnly: true,
* digitalSignature: true,
* encipherOnly: true,
* keyAgreement: true,
* keyEncipherment: true,
* },
* extendedKeyUsage: {
* clientAuth: true,
* codeSigning: true,
* emailProtection: true,
* ocspSigning: true,
* serverAuth: true,
* timeStamping: true,
* },
* unknownExtendedKeyUsages: [{
* objectIdPaths: [
* 1,
* 6,
* ],
* }],
* },
* policyIds: [{
* objectIdPaths: [
* 1,
* 6,
* ],
* }],
* },
* });
* const test_ca = new gcp.certificateauthority.Authority("test-ca", {
* pool: "",
* certificateAuthorityId: "my-certificate-authority",
* location: "us-central1",
* config: {
* subjectConfig: {
* subject: {
* organization: "HashiCorp",
* commonName: "my-certificate-authority",
* },
* subjectAltName: {
* dnsNames: ["hashicorp.com"],
* },
* },
* x509Config: {
* caOptions: {
* isCa: true,
* },
* keyUsage: {
* baseKeyUsage: {
* certSign: true,
* crlSign: true,
* },
* extendedKeyUsage: {
* serverAuth: false,
* },
* },
* },
* },
* keySpec: {
* algorithm: "RSA_PKCS1_4096_SHA256",
* },
* });
* const _default = new gcp.certificateauthority.Certificate("default", {
* pool: "",
* location: "us-central1",
* certificateAuthority: test_ca.certificateAuthorityId,
* lifetime: "860s",
* pemCsr: fs.readFileSync("test-fixtures/rsa_csr.pem"),
* certificateTemplate: template.id,
* });
* ```
* ### Privateca Certificate Csr
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const test_ca = new gcp.certificateauthority.Authority("test-ca", {
* pool: "",
* certificateAuthorityId: "my-certificate-authority",
* location: "us-central1",
* config: {
* subjectConfig: {
* subject: {
* organization: "HashiCorp",
* commonName: "my-certificate-authority",
* },
* subjectAltName: {
* dnsNames: ["hashicorp.com"],
* },
* },
* x509Config: {
* caOptions: {
* isCa: true,
* },
* keyUsage: {
* baseKeyUsage: {
* certSign: true,
* crlSign: true,
* },
* extendedKeyUsage: {
* serverAuth: false,
* },
* },
* },
* },
* keySpec: {
* algorithm: "RSA_PKCS1_4096_SHA256",
* },
* });
* const _default = new gcp.certificateauthority.Certificate("default", {
* pool: "",
* location: "us-central1",
* certificateAuthority: test_ca.certificateAuthorityId,
* lifetime: "860s",
* pemCsr: fs.readFileSync("test-fixtures/rsa_csr.pem"),
* });
* ```
* ### Privateca Certificate No Authority
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const authority = new gcp.certificateauthority.Authority("authority", {
* pool: "",
* certificateAuthorityId: "my-authority",
* location: "us-central1",
* config: {
* subjectConfig: {
* subject: {
* organization: "HashiCorp",
* commonName: "my-certificate-authority",
* },
* subjectAltName: {
* dnsNames: ["hashicorp.com"],
* },
* },
* x509Config: {
* caOptions: {
* isCa: true,
* },
* keyUsage: {
* baseKeyUsage: {
* digitalSignature: true,
* certSign: true,
* crlSign: true,
* },
* extendedKeyUsage: {
* serverAuth: true,
* },
* },
* },
* },
* lifetime: "86400s",
* keySpec: {
* algorithm: "RSA_PKCS1_4096_SHA256",
* },
* });
* const _default = new gcp.certificateauthority.Certificate("default", {
* pool: "",
* location: "us-central1",
* lifetime: "860s",
* config: {
* subjectConfig: {
* subject: {
* commonName: "san1.example.com",
* countryCode: "us",
* organization: "google",
* organizationalUnit: "enterprise",
* locality: "mountain view",
* province: "california",
* streetAddress: "1600 amphitheatre parkway",
* postalCode: "94109",
* },
* },
* x509Config: {
* caOptions: {
* nonCa: true,
* isCa: false,
* },
* keyUsage: {
* baseKeyUsage: {
* crlSign: true,
* },
* extendedKeyUsage: {
* serverAuth: true,
* },
* },
* },
* publicKey: {
* format: "PEM",
* key: Buffer.from(fs.readFileSync("test-fixtures/rsa_public.pem"), 'binary').toString('base64'),
* },
* },
* }, {
* dependsOn: [authority],
* });
* ```
*
* ## Import
*
* Certificate can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:certificateauthority/certificate:Certificate default projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificates/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:certificateauthority/certificate:Certificate default {{project}}/{{location}}/{{pool}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:certificateauthority/certificate:Certificate default {{location}}/{{pool}}/{{name}}
* ```
*/
export class Certificate extends pulumi.CustomResource {
/**
* Get an existing Certificate 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?: CertificateState, opts?: pulumi.CustomResourceOptions): Certificate {
return new Certificate(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:certificateauthority/certificate:Certificate';
/**
* Returns true if the given object is an instance of Certificate. 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 Certificate {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Certificate.__pulumiType;
}
/**
* Certificate Authority name.
*/
public readonly certificateAuthority!: pulumi.Output<string | undefined>;
/**
* Output only. Details regarding the revocation of this Certificate. This Certificate is considered revoked if and only if
* this field is present.
*/
public /*out*/ readonly certificateDescriptions!: pulumi.Output<outputs.certificateauthority.CertificateCertificateDescription[]>;
/**
* The resource name for a CertificateTemplate used to issue this certificate,
* in the format `projects/*/locations/*/certificateTemplates/*`. If this is specified,
* the caller must have the necessary permission to use this template. If this is
* omitted, no template will be used. This template must be in the same location
* as the Certificate.
*/
public readonly certificateTemplate!: pulumi.Output<string | undefined>;
/**
* The config used to create a self-signed X.509 certificate or CSR.
* Structure is documented below.
*/
public readonly config!: pulumi.Output<outputs.certificateauthority.CertificateConfig | undefined>;
/**
* The time that this resource was created on the server. This is in RFC3339 text format.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Labels with user-defined metadata to apply to this resource.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The desired lifetime of the CA certificate. Used to create the "notBeforeTime" and
* "notAfterTime" fields inside an X.509 certificate. A duration in seconds with up to nine
* fractional digits, terminated by 's'. Example: "3.5s".
*/
public readonly lifetime!: pulumi.Output<string | undefined>;
/**
* Location of the Certificate. A full list of valid locations can be found by
* running `gcloud privateca locations list`.
*/
public readonly location!: pulumi.Output<string>;
/**
* The name for this Certificate.
*/
public readonly name!: pulumi.Output<string>;
/**
* Output only. The pem-encoded, signed X.509 certificate.
*/
public /*out*/ readonly pemCertificate!: pulumi.Output<string>;
/**
* Required. Expected to be in leaf-to-root order according to RFC 5246.
*/
public /*out*/ readonly pemCertificates!: pulumi.Output<string[]>;
/**
* Immutable. A pem-encoded X.509 certificate signing request (CSR).
*/
public readonly pemCsr!: pulumi.Output<string | undefined>;
/**
* The name of the CaPool this Certificate belongs to.
*/
public readonly pool!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Output only. Details regarding the revocation of this Certificate. This Certificate is considered revoked if and only if
* this field is present.
*/
public /*out*/ readonly revocationDetails!: pulumi.Output<outputs.certificateauthority.CertificateRevocationDetail[]>;
/**
* Output only. The time at which this CertificateAuthority was updated. This is in RFC3339 text format.
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Create a Certificate 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: CertificateArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: CertificateArgs | CertificateState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as CertificateState | undefined;
inputs["certificateAuthority"] = state ? state.certificateAuthority : undefined;
inputs["certificateDescriptions"] = state ? state.certificateDescriptions : undefined;
inputs["certificateTemplate"] = state ? state.certificateTemplate : undefined;
inputs["config"] = state ? state.config : undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["lifetime"] = state ? state.lifetime : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["pemCertificate"] = state ? state.pemCertificate : undefined;
inputs["pemCertificates"] = state ? state.pemCertificates : undefined;
inputs["pemCsr"] = state ? state.pemCsr : undefined;
inputs["pool"] = state ? state.pool : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["revocationDetails"] = state ? state.revocationDetails : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
} else {
const args = argsOrState as CertificateArgs | undefined;
if ((!args || args.location === undefined) && !opts.urn) {
throw new Error("Missing required property 'location'");
}
if ((!args || args.pool === undefined) && !opts.urn) {
throw new Error("Missing required property 'pool'");
}
inputs["certificateAuthority"] = args ? args.certificateAuthority : undefined;
inputs["certificateTemplate"] = args ? args.certificateTemplate : undefined;
inputs["config"] = args ? args.config : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["lifetime"] = args ? args.lifetime : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["pemCsr"] = args ? args.pemCsr : undefined;
inputs["pool"] = args ? args.pool : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["certificateDescriptions"] = undefined /*out*/;
inputs["createTime"] = undefined /*out*/;
inputs["pemCertificate"] = undefined /*out*/;
inputs["pemCertificates"] = undefined /*out*/;
inputs["revocationDetails"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Certificate.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Certificate resources.
*/
export interface CertificateState {
/**
* Certificate Authority name.
*/
certificateAuthority?: pulumi.Input<string>;
/**
* Output only. Details regarding the revocation of this Certificate. This Certificate is considered revoked if and only if
* this field is present.
*/
certificateDescriptions?: pulumi.Input<pulumi.Input<inputs.certificateauthority.CertificateCertificateDescription>[]>;
/**
* The resource name for a CertificateTemplate used to issue this certificate,
* in the format `projects/*/locations/*/certificateTemplates/*`. If this is specified,
* the caller must have the necessary permission to use this template. If this is
* omitted, no template will be used. This template must be in the same location
* as the Certificate.
*/
certificateTemplate?: pulumi.Input<string>;
/**
* The config used to create a self-signed X.509 certificate or CSR.
* Structure is documented below.
*/
config?: pulumi.Input<inputs.certificateauthority.CertificateConfig>;
/**
* The time that this resource was created on the server. This is in RFC3339 text format.
*/
createTime?: pulumi.Input<string>;
/**
* Labels with user-defined metadata to apply to this resource.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The desired lifetime of the CA certificate. Used to create the "notBeforeTime" and
* "notAfterTime" fields inside an X.509 certificate. A duration in seconds with up to nine
* fractional digits, terminated by 's'. Example: "3.5s".
*/
lifetime?: pulumi.Input<string>;
/**
* Location of the Certificate. A full list of valid locations can be found by
* running `gcloud privateca locations list`.
*/
location?: pulumi.Input<string>;
/**
* The name for this Certificate.
*/
name?: pulumi.Input<string>;
/**
* Output only. The pem-encoded, signed X.509 certificate.
*/
pemCertificate?: pulumi.Input<string>;
/**
* Required. Expected to be in leaf-to-root order according to RFC 5246.
*/
pemCertificates?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Immutable. A pem-encoded X.509 certificate signing request (CSR).
*/
pemCsr?: pulumi.Input<string>;
/**
* The name of the CaPool this Certificate belongs to.
*/
pool?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Output only. Details regarding the revocation of this Certificate. This Certificate is considered revoked if and only if
* this field is present.
*/
revocationDetails?: pulumi.Input<pulumi.Input<inputs.certificateauthority.CertificateRevocationDetail>[]>;
/**
* Output only. The time at which this CertificateAuthority was updated. This is in RFC3339 text format.
*/
updateTime?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Certificate resource.
*/
export interface CertificateArgs {
/**
* Certificate Authority name.
*/
certificateAuthority?: pulumi.Input<string>;
/**
* The resource name for a CertificateTemplate used to issue this certificate,
* in the format `projects/*/locations/*/certificateTemplates/*`. If this is specified,
* the caller must have the necessary permission to use this template. If this is
* omitted, no template will be used. This template must be in the same location
* as the Certificate.
*/
certificateTemplate?: pulumi.Input<string>;
/**
* The config used to create a self-signed X.509 certificate or CSR.
* Structure is documented below.
*/
config?: pulumi.Input<inputs.certificateauthority.CertificateConfig>;
/**
* Labels with user-defined metadata to apply to this resource.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The desired lifetime of the CA certificate. Used to create the "notBeforeTime" and
* "notAfterTime" fields inside an X.509 certificate. A duration in seconds with up to nine
* fractional digits, terminated by 's'. Example: "3.5s".
*/
lifetime?: pulumi.Input<string>;
/**
* Location of the Certificate. A full list of valid locations can be found by
* running `gcloud privateca locations list`.
*/
location: pulumi.Input<string>;
/**
* The name for this Certificate.
*/
name?: pulumi.Input<string>;
/**
* Immutable. A pem-encoded X.509 certificate signing request (CSR).
*/
pemCsr?: pulumi.Input<string>;
/**
* The name of the CaPool this Certificate belongs to.
*/
pool: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
} | the_stack |
import * as _ from "lodash"
import * as RedisInst from "redis"
const EventEmitter = require("events").EventEmitter
/*
To create a new instance use:
RedisSMQ = require("rsmq")
rsmq = new RedisSMQ()
Paramenters for RedisSMQ:
* `host` (String): *optional (Default: "127.0.0.1")* The Redis server
* `port` (Number): *optional (Default: 6379)* The Redis port
* `options` (Object): *optional (Default: {})* The Redis options object.
* `client` (RedisClient): *optional* A existing redis client instance. `host` and `server` will be ignored.
* `ns` (String): *optional (Default: "rsmq")* The namespace prefix used for all keys created by **rsmq**
* `realtime` (Boolean): *optional (Default: false)* Enable realtime PUBLISH of new messages
*/
class RedisSMQ extends EventEmitter {
constructor (options: any = {}) {
super(options);
if (Promise) {
// create async versions of methods
_.forEach([
"changeMessageVisibility",
"createQueue",
"deleteMessage",
"deleteQueue",
"getQueueAttributes",
"listQueues",
"popMessage",
"receiveMessage",
"sendMessage",
"setQueueAttributes",
"quit"
], this.asyncify);
}
const opts = _.extend({
host: "127.0.0.1",
port: 6379,
options: {
password: options.password || null
},
client: null,
ns: "rsmq",
realtime: false
}, options);
opts.options.host = opts.host;
opts.options.port = opts.port;
this.realtime = opts.realtime;
this.redisns = opts.ns + ":";
if (opts.client && options.client.constructor.name === "RedisClient") {
this.redis = opts.client
}
else {
this.redis = RedisInst.createClient(opts)
}
this.connected = this.redis.connected || false;
// If external client is used it might alrdy be connected. So we check here:
if (this.connected) {
this.emit("connect");
this.initScript();
}
// Once the connection is up
this.redis.on("connect", () => {
this.connected = true;
this.emit("connect");
this.initScript();
});
this.redis.on("error", (err) => {
if (err.message.indexOf( "ECONNREFUSED" )) {
this.connected = false;
this.emit("disconnect");
}
else {
console.error( "Redis ERROR", err )
this.emit( "error" )
}
});
this._initErrors();
}
// helper to create async versions of our public methods (ie. methods that return promises)
// example: getQueue -> getQueueAsync
private asyncify = (methodKey) => {
const asyncMethodKey = methodKey + "Async";
this[asyncMethodKey] = (...args) => {
return new Promise((resolve, reject) => {
this[methodKey](...args, (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
}
}
// kill the connection of the redis client, so your node script will be able to exit.
public quit = (cb) => {
if (cb === undefined) {
cb = () => {}
}
this.redis.quit(cb);
}
private _getQueue = (qname, uid, cb) => {
const mc = [
["hmget", `${this.redisns}${qname}:Q`, "vt", "delay", "maxsize"],
["time"]
];
this.redis.multi(mc).exec( (err, resp) => {
if (err) { this._handleError(cb, err); return; }
if (resp[0][0] === null || resp[0][1] === null || resp[0][2] === null) {
this._handleError(cb, "queueNotFound");
return;
}
// Make sure to always have correct 6digit millionth seconds from redis
const ms: any = this._formatZeroPad(Number(resp[1][1]), 6);
// Create the epoch time in ms from the redis timestamp
const ts = Number(resp[1][0] + ms.toString(10).slice(0, 3));
const q: any = {
vt: parseInt(resp[0][0], 10),
delay: parseInt(resp[0][1], 10),
maxsize: parseInt(resp[0][2], 10),
ts: ts
};
// Need to create a uniqueid based on the redis timestamp,
// the queue name and a random number.
// The first part is the redis time.toString(36) which
// lets redis order the messages correctly even when they are
// in the same millisecond.
if (uid) {
uid = this._makeid(22);
q.uid = Number(resp[1][0] + ms).toString(36) + uid;
}
cb(null, q);
});
}
// This must be done via LUA script
// We can only set a visibility of a message if it really exists.
public changeMessageVisibility = (options, cb) => {
if (this._validate(options, ["qname","id","vt"], cb) === false)
return;
this._getQueue(options.qname, false, (err, q) => {
if (err) {
this._handleError(cb, err);
return;
}
// Make really sure that the LUA script is loaded
if (this.changeMessageVisibility_sha1) {
this._changeMessageVisibility(options, q, cb)
return
}
this.on("scriptload:changeMessageVisibility", () => {
this._changeMessageVisibility(options, q, cb);
});
});
}
private _changeMessageVisibility = (options, q, cb) => {
this.redis.evalsha(this.changeMessageVisibility_sha1, 3, `${this.redisns}${options.qname}`, options.id, q.ts + options.vt * 1000, (err, resp) => {
if (err) {
this._handleError(cb, err);
return;
}
cb(null, resp);
});
}
public createQueue = (options, cb) => {
const key = `${this.redisns}${options.qname}:Q`;
options.vt = options.vt != null ? options.vt : 30;
options.delay = options.delay != null ? options.delay : 0;
options.maxsize = options.maxsize != null ? options.maxsize : 65536;
if (this._validate(options, ["qname", "vt", "delay", "maxsize"], cb) === false)
return;
this.redis.time( (err, resp) => {
if (err) {
this._handleError(cb, err);
return
}
const mc = [
["hsetnx", key, "vt", options.vt],
["hsetnx", key, "delay", options.delay],
["hsetnx", key, "maxsize", options.maxsize],
["hsetnx", key, "created", resp[0]],
["hsetnx", key, "modified", resp[0]],
];
this.redis.multi(mc).exec( (err, resp) => {
if (err) {
this._handleError(cb, err);
return
}
if (resp[0] === 0) {
this._handleError(cb, "queueExists");
return;
}
// We created a new queue
// Also store it in the global set to keep an index of all queues
this.redis.sadd(`${this.redisns}QUEUES`, options.qname, (err, resp) => {
if (err) {
this._handleError(cb, err);
return;
}
cb(null, 1);
});
});
});
}
public deleteMessage = (options, cb) => {
if (this._validate(options, ["qname","id"],cb) === false)
return;
const key = `${this.redisns}${options.qname}`;
const mc = [
["zrem", key, options.id],
["hdel", `${key}:Q`, `${options.id}`, `${options.id}:rc`, `${options.id}:fr`]
];
this.redis.multi(mc).exec( (err, resp) => {
if (err) { this._handleError(cb, err); return; }
if (resp[0] === 1 && resp[1] > 0) {
cb(null, 1)
}
else {
cb(null, 0)
}
});
}
public deleteQueue = (options, cb) => {
if (this._validate(options, ["qname"],cb) === false)
return;
const key = `${this.redisns}${options.qname}`;
const mc = [
["del", `${key}:Q`, key], // The queue hash and messages zset
["srem", `${this.redisns}QUEUES`, options.qname]
];
this.redis.multi(mc).exec( (err,resp) => {
if (err) { this._handleError(cb, err); return; }
if (resp[0] === 0) {
this._handleError(cb, "queueNotFound");
return;
}
cb(null, 1);
});
}
public getQueueAttributes = (options, cb) => {
if (this._validate(options, ["qname"],cb) === false)
return;
const key = `${this.redisns}${options.qname}`;
this.redis.time( (err, resp) => {
if (err) { this._handleError(cb, err); return; }
// Get basic attributes and counter
// Get total number of messages
// Get total number of messages in flight (not visible yet)
const mc = [
["hmget", `${key}:Q`, "vt", "delay", "maxsize", "totalrecv", "totalsent", "created", "modified"],
["zcard", key],
["zcount", key, resp[0] + "000", "+inf"]
];
this.redis.multi(mc).exec( (err, resp) => {
if (err) {
this._handleError(cb, err);
return;
}
if (resp[0][0] === null) {
this._handleError(cb, "queueNotFound")
return
}
const o = {
vt: parseInt(resp[0][0], 10),
delay: parseInt(resp[0][1], 10),
maxsize: parseInt(resp[0][2], 10),
totalrecv: parseInt(resp[0][3], 10) || 0,
totalsent: parseInt(resp[0][4], 10) || 0,
created: parseInt(resp[0][5], 10),
modified: parseInt(resp[0][6], 10),
msgs: resp[1],
hiddenmsgs: resp[2]
};
cb(null, o);
});
});
}
private _handleReceivedMessage = (cb) => {
return (err, resp) => {
if (err) { this._handleError(cb, err); return; }
if (!resp.length) {
cb(null, {});
return;
}
const o = {
id: resp[0],
message: resp[1],
rc: resp[2],
fr: Number(resp[3]),
sent: Number(parseInt(resp[0].slice(0, 10), 36) / 1000)
}
cb(null, o);
}
}
private initScript = () => {
// The popMessage LUA Script
//
// Parameters:
//
// KEYS[1]: the zset key
// KEYS[2]: the current time in ms
//
// * Find a message id
// * Get the message
// * Increase the rc (receive count)
// * Use hset to set the fr (first receive) time
// * Return the message and the counters
//
// Returns:
//
// {id, message, rc, fr}
const script_popMessage = `local msg = redis.call("ZRANGEBYSCORE", KEYS[1], "-inf", KEYS[2], "LIMIT", "0", "1")
if #msg == 0 then
return {}
end
redis.call("HINCRBY", KEYS[1] .. ":Q", "totalrecv", 1)
local mbody = redis.call("HGET", KEYS[1] .. ":Q", msg[1])
local rc = redis.call("HINCRBY", KEYS[1] .. ":Q", msg[1] .. ":rc", 1)
local o = {msg[1], mbody, rc}
if rc==1 then
table.insert(o, KEYS[2])
else
local fr = redis.call("HGET", KEYS[1] .. ":Q", msg[1] .. ":fr")
table.insert(o, fr)
end
redis.call("ZREM", KEYS[1], msg[1])
redis.call("HDEL", KEYS[1] .. ":Q", msg[1], msg[1] .. ":rc", msg[1] .. ":fr")
return o`
// The receiveMessage LUA Script
//
// Parameters:
//
// KEYS[1]: the zset key
// KEYS[2]: the current time in ms
// KEYS[3]: the new calculated time when the vt runs out
//
// * Find a message id
// * Get the message
// * Increase the rc (receive count)
// * Use hset to set the fr (first receive) time
// * Return the message and the counters
//
// Returns:
//
// {id, message, rc, fr}
const script_receiveMessage = `local msg = redis.call("ZRANGEBYSCORE", KEYS[1], "-inf", KEYS[2], "LIMIT", "0", "1")
if #msg == 0 then
return {}
end
redis.call("ZADD", KEYS[1], KEYS[3], msg[1])
redis.call("HINCRBY", KEYS[1] .. ":Q", "totalrecv", 1)
local mbody = redis.call("HGET", KEYS[1] .. ":Q", msg[1])
local rc = redis.call("HINCRBY", KEYS[1] .. ":Q", msg[1] .. ":rc", 1)
local o = {msg[1], mbody, rc}
if rc==1 then
redis.call("HSET", KEYS[1] .. ":Q", msg[1] .. ":fr", KEYS[2])
table.insert(o, KEYS[2])
else
local fr = redis.call("HGET", KEYS[1] .. ":Q", msg[1] .. ":fr")
table.insert(o, fr)
end
return o`;
// The changeMessageVisibility LUA Script
//
// Parameters:
//
// KEYS[1]: the zset key
// KEYS[2]: the message id
//
//
// * Find the message id
// * Set the new timer
//
// Returns:
//
// 0 or 1
const script_changeMessageVisibility = `local msg = redis.call("ZSCORE", KEYS[1], KEYS[2])
if not msg then
return 0
end
redis.call("ZADD", KEYS[1], KEYS[3], KEYS[2])
return 1`
this.redis.script("load", script_popMessage, (err, resp) => {
if (err) { console.log(err); return; }
this.popMessage_sha1 = resp;
this.emit("scriptload:popMessage");
});
this.redis.script("load", script_receiveMessage, (err, resp) => {
if (err) { console.log(err); return; }
this.receiveMessage_sha1 = resp;
this.emit("scriptload:receiveMessage");
});
this.redis.script("load", script_changeMessageVisibility, (err, resp) => {
if (err) { console.log(err); return; }
this.changeMessageVisibility_sha1 = resp;
this.emit('scriptload:changeMessageVisibility');
});
}
public listQueues = (cb) => {
this.redis.smembers(`${this.redisns}QUEUES`, (err, resp) => {
if (err) { this._handleError(cb, err); return; }
cb(null, resp)
});
}
public popMessage = (options, cb) => {
if (this._validate(options, ["qname"],cb) === false)
return;
this._getQueue(options.qname, false, (err, q) => {
if (err) { this._handleError(cb, err); return; }
// Make really sure that the LUA script is loaded
if (this.popMessage_sha1) {
this._popMessage(options, q, cb);
return;
}
this.on("scriptload:popMessage", () => {
this._popMessage(options, q, cb);
});
});
}
public receiveMessage = (options, cb) => {
if (this._validate(options, ["qname"], cb) === false)
return;
this._getQueue(options.qname, false, (err, q) => {
if (err) { this._handleError(cb, err); return; }
// Now that we got the default queue settings
options.vt = options.vt != null ? options.vt : q.vt;
if (this._validate(options, ["vt"], cb) === false)
return;
// Make really sure that the LUA script is loaded
if (this.receiveMessage_sha1) {
this._receiveMessage(options, q, cb)
return;
}
this.on("scriptload:receiveMessage", () => {
this._receiveMessage(options, q, cb)
});
});
}
private _popMessage = (options, q, cb) => {
this.redis.evalsha(this.popMessage_sha1, 2, `${this.redisns}${options.qname}`, q.ts, this._handleReceivedMessage(cb));
}
private _receiveMessage = (options, q, cb) => {
this.redis.evalsha(this.receiveMessage_sha1, 3, `${this.redisns}${options.qname}`, q.ts, q.ts + options.vt * 1000, this._handleReceivedMessage(cb));
}
public sendMessage = (options, cb) => {
if (this._validate(options, ["qname"],cb) === false)
return
this._getQueue(options.qname, true, (err, q) => {
if (err) { this._handleError(cb, err); return; }
// Now that we got the default queue settings
options.delay = options.delay != null ? options.delay : q.delay;
if (this._validate(options, ["delay"],cb) === false)
return;
// Check the message
if (typeof options.message !== "string") {
this._handleError(cb, "messageNotString");
return;
}
// Check the message size
if (q.maxsize !== -1 && options.message.length > q.maxsize) {
this._handleError(cb, "messageTooLong");
return;
}
// Ready to store the message
const key = `${this.redisns}${options.qname}`;
const mc = [
["zadd", key, q.ts + options.delay * 1000, q.uid],
["hset", `${key}:Q`, q.uid, options.message],
["hincrby", `${key}:Q`, "totalsent", 1]
];
if (this.realtime) {
mc.push(["zcard", key]);
}
this.redis.multi(mc).exec( (err, resp) => {
if (err) {
this._handleError(cb, err);
return;
}
if (this.realtime) {
this.redis.publish(`${this.redisns}rt:${options.qname}`, resp[3]);
}
cb(null, q.uid);
});
});
}
public setQueueAttributes = (options, cb) => {
const props = ["vt", "maxsize", "delay"]
let k = []
for (let item of props) {
if (options[item] != null) {
k.push(item);
}
}
// Not a single key was supplied
if (k.length === 0) {
this._handleError(cb, "noAttributeSupplied");
return;
}
if (this._validate(options, ["qname"].concat(k), cb) === false)
return
const key = `${this.redisns}${options.qname}`;
this._getQueue(options.qname, false, (err, q) => {
if (err) { this._handleError(cb, err); return; }
this.redis.time( (err, resp) => {
if (err) {
this._handleError(cb, err);
return;
}
const mc = [
["hset", `${this.redisns}${options.qname}:Q`, "modified", resp[0]]
];
for (let item of k) {
mc.push(["hset", `${this.redisns}${options.qname}:Q`, item, options[item]])
};
this.redis.multi(mc).exec( (err) => {
if (err) {
this._handleError(cb, err);
return;
}
this.getQueueAttributes(options, cb);
})
});
});
}
// Helpers
private _formatZeroPad (num, count) {
return ((Math.pow(10, count) + num) + "").substr(1);
}
private _handleError = (cb, err, data = {}) => {
// try to create a error Object with humanized message
let _err = null;
if (_.isString(err)) {
_err = new Error();
_err.name = err;
// _err.message = this._ERRORS?[err]?(data) || "unkown";
let ref = null;
_err.message = ((ref = this._ERRORS) != null ? typeof ref[err] === "function" ? ref[err](data) : void 0 : void 0) || "unkown";
}
else {
_err = err
}
cb(_err)
}
private _initErrors = () => {
this._ERRORS = {};
for (let key in this.ERRORS) {
this._ERRORS[key] = _.template(this.ERRORS[key]);
}
}
private _makeid (len) {
let text = "";
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let i = 0;
for (i = 0; i < len; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
private _VALID = {
qname: /^([a-zA-Z0-9_-]){1,160}$/,
id: /^([a-zA-Z0-9:]){32}$/
}
private _validate = (o, items, cb) => {
for (let item of items) {
switch (item) {
case "qname":
case "id":
if (!o[item]) {
this._handleError(cb, "missingParameter", {item:item});
return false;
}
o[item] = o[item].toString()
if (!this._VALID[item].test(o[item])) {
this._handleError(cb, "invalidFormat", {item:item});
return false;
}
break;
case "vt":
case "delay":
o[item] = parseInt(o[item],10);
if (_.isNaN(o[item]) || !_.isNumber(o[item]) || o[item] < 0 || o[item] > 9999999) {
this._handleError(cb, "invalidValue", {item: item, min: 0, max: 9999999});
return false;
}
break;
case "maxsize":
o[item] = parseInt(o[item], 10)
if (_.isNaN(o[item]) || !_.isNumber(o[item]) || o[item] < 1024 || o[item] > 65536) {
// Allow unlimited messages
if (o[item] !== -1) {
this._handleError(cb, "invalidValue", {item: item, min: 1024, max: 65536});
return false;
}
}
break;
}
};
return o;
}
private ERRORS = {
"noAttributeSupplied": "No attribute was supplied",
"missingParameter": "No <%= item %> supplied",
"invalidFormat": "Invalid <%= item %> format",
"invalidValue": "<%= item %> must be between <%= min %> and <%= max %>",
"messageNotString": "Message must be a string",
"messageTooLong": "Message too long",
"queueNotFound": "Queue not found",
"queueExists": "Queue exists"
}
}
module.exports = RedisSMQ; | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import * as vscode from 'vscode';
import * as lsp from 'vscode-languageclient/node';
import {ProjectLoadingFinish, ProjectLoadingStart, SuggestStrictMode, SuggestStrictModeParams} from '../common/notifications';
import {NgccProgress, NgccProgressToken, NgccProgressType} from '../common/progress';
import {GetComponentsWithTemplateFile, GetTcbRequest, GetTemplateLocationForComponent, IsInAngularProject} from '../common/requests';
import {resolve, Version} from '../common/resolver';
import {isInsideComponentDecorator, isInsideInlineTemplateRegion, isInsideStringLiteral} from './embedded_support';
import {ProgressReporter} from './progress-reporter';
interface GetTcbResponse {
uri: vscode.Uri;
content: string;
selections: vscode.Range[];
}
export class AngularLanguageClient implements vscode.Disposable {
private client: lsp.LanguageClient|null = null;
private readonly disposables: vscode.Disposable[] = [];
private readonly outputChannel: vscode.OutputChannel;
private readonly clientOptions: lsp.LanguageClientOptions;
private readonly name = 'Angular Language Service';
private readonly virtualDocumentContents = new Map<string, string>();
/** A map that indicates whether Angular could be found in the file's project. */
private readonly fileToIsInAngularProjectMap = new Map<string, boolean>();
constructor(private readonly context: vscode.ExtensionContext) {
vscode.workspace.registerTextDocumentContentProvider('angular-embedded-content', {
provideTextDocumentContent: uri => {
return this.virtualDocumentContents.get(uri.toString());
}
});
this.outputChannel = vscode.window.createOutputChannel(this.name);
// Options to control the language client
this.clientOptions = {
// Register the server for Angular templates and TypeScript documents
documentSelector: [
// scheme: 'file' means listen to changes to files on disk only
// other option is 'untitled', for buffer in the editor (like a new doc)
{scheme: 'file', language: 'html'},
{scheme: 'file', language: 'typescript'},
],
synchronize: {
fileEvents: [
// Notify the server about file changes to tsconfig.json contained in the workspace
vscode.workspace.createFileSystemWatcher('**/tsconfig.json'),
]
},
// Don't let our output console pop open
revealOutputChannelOn: lsp.RevealOutputChannelOn.Never,
outputChannel: this.outputChannel,
middleware: {
prepareRename: async (
document: vscode.TextDocument, position: vscode.Position,
token: vscode.CancellationToken, next: lsp.PrepareRenameSignature) => {
// We are able to provide renames for many types of string literals: template strings,
// pipe names, and hopefully in the future selectors and input/output aliases. Because
// TypeScript isn't able to provide renames for these, we can more or less
// guarantee that the Angular Language service will be called for the rename as the
// fallback. We specifically do not provide renames outside of string literals
// because we cannot ensure our extension is prioritized for renames in TS files (see
// https://github.com/microsoft/vscode/issues/115354) we disable renaming completely so we
// can provide consistent expectations.
if (await this.isInAngularProject(document) &&
isInsideStringLiteral(document, position)) {
return next(document, position, token);
}
},
provideDefinition: async (
document: vscode.TextDocument, position: vscode.Position,
token: vscode.CancellationToken, next: lsp.ProvideDefinitionSignature) => {
if (await this.isInAngularProject(document) &&
isInsideComponentDecorator(document, position)) {
return next(document, position, token);
}
},
provideTypeDefinition: async (
document: vscode.TextDocument, position: vscode.Position,
token: vscode.CancellationToken, next) => {
if (await this.isInAngularProject(document) &&
isInsideInlineTemplateRegion(document, position)) {
return next(document, position, token);
}
},
provideHover: async (
document: vscode.TextDocument, position: vscode.Position,
token: vscode.CancellationToken, next: lsp.ProvideHoverSignature) => {
if (!(await this.isInAngularProject(document)) ||
!isInsideInlineTemplateRegion(document, position)) {
return;
}
const angularResultsPromise = next(document, position, token);
// Include results for inline HTML via virtual document and native html providers.
if (document.languageId === 'typescript') {
const vdocUri = this.createVirtualHtmlDoc(document);
const htmlProviderResultsPromise = vscode.commands.executeCommand<vscode.Hover[]>(
'vscode.executeHoverProvider', vdocUri, position);
const [angularResults, htmlProviderResults] =
await Promise.all([angularResultsPromise, htmlProviderResultsPromise]);
return angularResults ?? htmlProviderResults?.[0];
}
return angularResultsPromise;
},
provideSignatureHelp: async (
document: vscode.TextDocument, position: vscode.Position,
context: vscode.SignatureHelpContext, token: vscode.CancellationToken,
next: lsp.ProvideSignatureHelpSignature) => {
if (await this.isInAngularProject(document) &&
isInsideInlineTemplateRegion(document, position)) {
return next(document, position, context, token);
}
},
provideCompletionItem: async (
document: vscode.TextDocument, position: vscode.Position,
context: vscode.CompletionContext, token: vscode.CancellationToken,
next: lsp.ProvideCompletionItemsSignature) => {
// If not in inline template, do not perform request forwarding
if (!(await this.isInAngularProject(document)) ||
!isInsideInlineTemplateRegion(document, position)) {
return;
}
const angularCompletionsPromise = next(document, position, context, token) as
Promise<vscode.CompletionItem[]|null|undefined>;
// Include results for inline HTML via virtual document and native html providers.
if (document.languageId === 'typescript') {
const vdocUri = this.createVirtualHtmlDoc(document);
// This will not include angular stuff because the vdoc is not associated with an
// angular component
const htmlProviderCompletionsPromise =
vscode.commands.executeCommand<vscode.CompletionList>(
'vscode.executeCompletionItemProvider', vdocUri, position,
context.triggerCharacter);
const [angularCompletions, htmlProviderCompletions] =
await Promise.all([angularCompletionsPromise, htmlProviderCompletionsPromise]);
return [...(angularCompletions ?? []), ...(htmlProviderCompletions?.items ?? [])];
}
return angularCompletionsPromise;
}
}
};
}
private async isInAngularProject(doc: vscode.TextDocument): Promise<boolean> {
if (this.client === null) {
return false;
}
const uri = doc.uri.toString();
if (this.fileToIsInAngularProjectMap.has(uri)) {
return this.fileToIsInAngularProjectMap.get(uri)!;
}
try {
const response = await this.client.sendRequest(IsInAngularProject, {
textDocument: this.client.code2ProtocolConverter.asTextDocumentIdentifier(doc),
});
if (response == null) {
// If the response indicates the answer can't be determined at the moment, return `false`
// but do not cache the result so we can try to get the real answer on follow-up requests.
return false;
}
this.fileToIsInAngularProjectMap.set(uri, response);
return response;
} catch {
return false;
}
}
private createVirtualHtmlDoc(document: vscode.TextDocument): vscode.Uri {
const originalUri = document.uri.toString();
const vdocUri = vscode.Uri.file(encodeURIComponent(originalUri) + '.html')
.with({scheme: 'angular-embedded-content', authority: 'html'});
this.virtualDocumentContents.set(vdocUri.toString(), document.getText());
return vdocUri;
}
/**
* Spin up the language server in a separate process and establish a connection.
*/
async start(): Promise<void> {
if (this.client !== null) {
throw new Error(`An existing client is running. Call stop() first.`);
}
// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
const serverOptions: lsp.ServerOptions = {
run: getServerOptions(this.context, false /* debug */),
debug: getServerOptions(this.context, true /* debug */),
};
// Create the language client and start the client.
const forceDebug = process.env['NG_DEBUG'] === 'true';
this.client = new lsp.LanguageClient(
// This is the ID for Angular-specific configurations, like "angular.log".
// See contributes.configuration in package.json.
'angular',
this.name,
serverOptions,
this.clientOptions,
forceDebug,
);
this.disposables.push(this.client.start());
await this.client.onReady();
// Must wait for the client to be ready before registering notification
// handlers.
this.disposables.push(registerNotificationHandlers(this.client));
this.disposables.push(registerProgressHandlers(this.client));
}
/**
* Kill the language client and perform some clean ups.
*/
async stop(): Promise<void> {
if (this.client === null) {
return;
}
await this.client.stop();
this.outputChannel.clear();
this.dispose();
this.client = null;
this.fileToIsInAngularProjectMap.clear();
this.virtualDocumentContents.clear();
}
/**
* Requests a template typecheck block at the current cursor location in the
* specified editor.
*/
async getTcbUnderCursor(textEditor: vscode.TextEditor): Promise<GetTcbResponse|undefined> {
if (this.client === null) {
return undefined;
}
const c2pConverter = this.client.code2ProtocolConverter;
// Craft a request by converting vscode params to LSP. The corresponding
// response is in LSP.
const response = await this.client.sendRequest(GetTcbRequest, {
textDocument: c2pConverter.asTextDocumentIdentifier(textEditor.document),
position: c2pConverter.asPosition(textEditor.selection.active),
});
if (response === null) {
return undefined;
}
const p2cConverter = this.client.protocol2CodeConverter;
// Convert the response from LSP back to vscode.
return {
uri: p2cConverter.asUri(response.uri),
content: response.content,
selections: p2cConverter.asRanges(response.selections),
};
}
get initializeResult(): lsp.InitializeResult|undefined {
return this.client?.initializeResult;
}
async getComponentsForOpenExternalTemplate(textEditor: vscode.TextEditor):
Promise<vscode.Location[]|undefined> {
if (this.client === null) {
return undefined;
}
const response = await this.client.sendRequest(GetComponentsWithTemplateFile, {
textDocument:
this.client.code2ProtocolConverter.asTextDocumentIdentifier(textEditor.document),
});
if (response === undefined) {
return undefined;
}
const p2cConverter = this.client.protocol2CodeConverter;
return response.map(
v => new vscode.Location(p2cConverter.asUri(v.uri), p2cConverter.asRange(v.range)));
}
async getTemplateLocationForComponent(textEditor: vscode.TextEditor):
Promise<vscode.Location|null> {
if (this.client === null) {
return null;
}
const c2pConverter = this.client.code2ProtocolConverter;
// Craft a request by converting vscode params to LSP. The corresponding
// response is in LSP.
const response = await this.client.sendRequest(GetTemplateLocationForComponent, {
textDocument: c2pConverter.asTextDocumentIdentifier(textEditor.document),
position: c2pConverter.asPosition(textEditor.selection.active),
});
if (response === null) {
return null;
}
const p2cConverter = this.client.protocol2CodeConverter;
return new vscode.Location(
p2cConverter.asUri(response.uri), p2cConverter.asRange(response.range));
}
dispose() {
for (let d = this.disposables.pop(); d !== undefined; d = this.disposables.pop()) {
d.dispose();
}
}
}
function registerNotificationHandlers(client: lsp.LanguageClient): vscode.Disposable {
const disposables: vscode.Disposable[] = [];
disposables.push(client.onNotification(ProjectLoadingStart, () => {
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Window,
title: 'Initializing Angular language features',
},
() => new Promise<void>((resolve) => {
client.onNotification(ProjectLoadingFinish, resolve);
}),
);
}));
disposables.push(client.onNotification(SuggestStrictMode, async (params: SuggestStrictModeParams) => {
const config = vscode.workspace.getConfiguration();
if (config.get('angular.enable-strict-mode-prompt') === false) {
return;
}
const openTsConfig = 'Open tsconfig.json';
// Markdown is not generally supported in `showInformationMessage()`,
// but links are supported. See
// https://github.com/microsoft/vscode/issues/20595#issuecomment-281099832
const doNotPromptAgain = 'Do not show again for this workspace';
const selection = await vscode.window.showInformationMessage(
'Some language features are not available. To access all features, enable ' +
'[strictTemplates](https://angular.io/guide/angular-compiler-options#stricttemplates) in ' +
'[angularCompilerOptions](https://angular.io/guide/angular-compiler-options).',
openTsConfig,
doNotPromptAgain,
);
if (selection === openTsConfig) {
const document = await vscode.workspace.openTextDocument(params.configFilePath);
vscode.window.showTextDocument(document);
} else if (selection === doNotPromptAgain) {
config.update(
'angular.enable-strict-mode-prompt', false, vscode.ConfigurationTarget.Workspace);
}
}));
return vscode.Disposable.from(...disposables);
}
function registerProgressHandlers(client: lsp.LanguageClient) {
const progressReporters = new Map<string, ProgressReporter>();
const disposable =
client.onProgress(NgccProgressType, NgccProgressToken, async (params: NgccProgress) => {
const {configFilePath} = params;
if (!progressReporters.has(configFilePath)) {
progressReporters.set(configFilePath, new ProgressReporter());
}
const reporter = progressReporters.get(configFilePath)!;
if (params.done) {
reporter.finish();
progressReporters.delete(configFilePath);
if (!params.success) {
const selection = await vscode.window.showErrorMessage(
`Angular extension might not work correctly because ngcc operation failed. ` +
`Try to invoke ngcc manually by running 'npm/yarn run ngcc'. ` +
`Please see the extension output for more information.`,
'Show output',
);
if (selection) {
client.outputChannel.show();
}
}
} else {
reporter.report(params.message);
}
});
const reporterDisposer = vscode.Disposable.from({
dispose() {
for (const reporter of progressReporters.values()) {
reporter.finish();
}
disposable.dispose();
}
});
return reporterDisposer;
}
/**
* Return the paths for the module that corresponds to the specified `configValue`,
* and use the specified `bundled` as fallback if none is provided.
* @param configName
* @param bundled
*/
function getProbeLocations(bundled: string): string[] {
const locations = [];
// Prioritize the bundled version
locations.push(bundled);
// Look in workspaces currently open
const workspaceFolders = vscode.workspace.workspaceFolders || [];
for (const folder of workspaceFolders) {
locations.push(folder.uri.fsPath);
}
return locations;
}
/**
* Construct the arguments that's used to spawn the server process.
* @param ctx vscode extension context
*/
function constructArgs(ctx: vscode.ExtensionContext, viewEngine: boolean): string[] {
const config = vscode.workspace.getConfiguration();
const args: string[] = ['--logToConsole'];
const ngLog: string = config.get('angular.log', 'off');
if (ngLog !== 'off') {
// Log file does not yet exist on disk. It is up to the server to create the file.
const logFile = path.join(ctx.logUri.fsPath, 'nglangsvc.log');
args.push('--logFile', logFile);
args.push('--logVerbosity', ngLog);
}
const ngProbeLocations = getProbeLocations(ctx.extensionPath);
if (viewEngine) {
args.push('--viewEngine');
args.push('--ngProbeLocations', [
path.join(ctx.extensionPath, 'v12_language_service'),
...ngProbeLocations,
].join(','));
} else {
args.push('--ngProbeLocations', ngProbeLocations.join(','));
}
const includeAutomaticOptionalChainCompletions =
config.get<boolean>('angular.suggest.includeAutomaticOptionalChainCompletions');
if (includeAutomaticOptionalChainCompletions) {
args.push('--includeAutomaticOptionalChainCompletions');
}
const includeCompletionsWithSnippetText =
config.get<boolean>('angular.suggest.includeCompletionsWithSnippetText');
if (includeCompletionsWithSnippetText) {
args.push('--includeCompletionsWithSnippetText');
}
const tsdk: string|null = config.get('typescript.tsdk', null);
const tsProbeLocations = [tsdk, ...getProbeLocations(ctx.extensionPath)];
args.push('--tsProbeLocations', tsProbeLocations.join(','));
return args;
}
function getServerOptions(ctx: vscode.ExtensionContext, debug: boolean): lsp.NodeModule {
// Environment variables for server process
const prodEnv = {};
const devEnv = {
...prodEnv,
NG_DEBUG: true,
};
// Because the configuration is typed as "boolean" in package.json, vscode
// will return false even when the value is not set. If value is false, then
// we need to check if all projects support Ivy language service.
const config = vscode.workspace.getConfiguration();
const viewEngine: boolean = config.get('angular.view-engine') || !allProjectsSupportIvy();
// Node module for the language server
const args = constructArgs(ctx, viewEngine);
const prodBundle = ctx.asAbsolutePath('server');
const devBundle = ctx.asAbsolutePath(path.join('dist', 'server', 'server.js'));
// VS Code Insider launches extensions in debug mode by default but users
// install prod bundle so we have to check whether dev bundle exists.
const latestServerModule = debug && fs.existsSync(devBundle) ? devBundle : prodBundle;
const v12ServerModule = ctx.asAbsolutePath(
path.join('v12_language_service', 'node_modules', '@angular', 'language-server'));
const module = viewEngine ? v12ServerModule : latestServerModule;
// Argv options for Node.js
const prodExecArgv: string[] = [];
const devExecArgv: string[] = [
// do not lazily evaluate the code so all breakpoints are respected
'--nolazy',
// If debugging port is changed, update .vscode/launch.json as well
'--inspect=6009',
];
return {
module,
transport: lsp.TransportKind.ipc,
args,
options: {
env: debug ? devEnv : prodEnv,
execArgv: debug ? devExecArgv : prodExecArgv,
},
};
}
/**
* Returns true if all projects in the workspace support Ivy LS, otherwise
* return false.
*/
function allProjectsSupportIvy() {
const workspaceFolders = vscode.workspace.workspaceFolders || [];
for (const workspaceFolder of workspaceFolders) {
const angularCore = resolve('@angular/core', workspaceFolder.uri.fsPath);
if (angularCore?.version.greaterThanOrEqual(new Version('9')) === false) {
return false;
}
}
return true;
} | the_stack |
import {Clipper} from "../../scripts/clipperUI/frontEndGlobals";
import {BookmarkError, BookmarkHelper, BookmarkResult, MetadataKeyValuePair} from "../../scripts/contentCapture/bookmarkHelper";
import {ObjectUtils} from "../../scripts/objectUtils";
import {StubSessionLogger} from "../../scripts/logging/stubSessionLogger";
import {TestModule} from "../testModule";
export class BookmarkHelperTests extends TestModule {
protected module() {
return "bookmarkHelper";
}
protected beforeEach() {
Clipper.logger = new StubSessionLogger();
}
protected tests() {
test("bookmarkPage rejects when url is undefined or empty", (assert: QUnitAssert) => {
let done = assert.async();
let metadata = TestHelper.createListOfMetaTags([TestHelper.StandardMetadata.PrimaryDescription, TestHelper.StandardMetadata.PrimaryThumbnail]);
BookmarkHelper.bookmarkPage(undefined, TestHelper.Content.testPageTitle, metadata).then(() => {
ok(false, "undefined url should not resolve");
done();
}, () => {
BookmarkHelper.bookmarkPage("", TestHelper.Content.testPageTitle, metadata).then(() => {
ok(false, "empty url should not resolve");
}).catch(() => {
ok(true, "empty url should reject");
}).then(() => {
done();
});
});
});
test("bookmarkPage returns complete BookmarkResult when fully-formed list of metadata exists", (assert: QUnitAssert) => {
let done = assert.async();
let expectedResult: BookmarkResult = {
url: TestHelper.Content.testBookmarkUrl,
title: TestHelper.Content.testPageTitle,
description: TestHelper.Content.testDescriptionValue
};
let metadata = TestHelper.createListOfMetaTags([TestHelper.StandardMetadata.PrimaryDescription]);
BookmarkHelper.bookmarkPage(expectedResult.url, TestHelper.Content.testPageTitle, metadata).then((result: BookmarkResult) => {
strictEqual(result.url, expectedResult.url, "bookmarked url is incorrect");
strictEqual(result.description, expectedResult.description, "bookmarked description is incorrect");
strictEqual(result.thumbnailSrc, expectedResult.thumbnailSrc, "bookmarked thumbnail source is incorrect");
}).catch((error: BookmarkError) => {
ok(false, "fully-formed list of metadata should not reject. error: " + error);
}).then(() => {
done();
});
});
test("bookmarkPage returns BookmarkResult with just a url when list of metadata does not exist", (assert: QUnitAssert) => {
let done = assert.async();
let expectedResult: BookmarkResult = {
url: TestHelper.Content.testBookmarkUrl,
title: TestHelper.Content.testPageTitle
};
BookmarkHelper.bookmarkPage(expectedResult.url, TestHelper.Content.testPageTitle, undefined).then((result: BookmarkResult) => {
strictEqual(result.url, expectedResult.url, "bookmarked url is incorrect");
strictEqual(result.description, undefined, "bookmarked description should be undefined. actual: '" + result.description + "'");
strictEqual(result.thumbnailSrc, undefined, "bookmarked thumbnail source should be undefined. actual: '" + result.thumbnailSrc + "'");
}).catch((error: BookmarkError) => {
ok(false, "undefined list of metadata should not reject. error: " + error);
}).then(() => {
done();
});
});
test("bookmarkPage returns BookmarkResult with just a url when list of metadata is empty", (assert: QUnitAssert) => {
let done = assert.async();
let expectedResult: BookmarkResult = {
url: TestHelper.Content.testBookmarkUrl,
title: TestHelper.Content.testPageTitle
};
BookmarkHelper.bookmarkPage(expectedResult.url, TestHelper.Content.testPageTitle, new Array<HTMLMetaElement>()).then((result: BookmarkResult) => {
strictEqual(result.url, expectedResult.url, "bookmarked url is incorrect");
strictEqual(result.description, undefined, "bookmarked description should be undefined. actual: '" + result.description + "'");
strictEqual(result.thumbnailSrc, undefined, "bookmarked thumbnail source should be undefined. actual: '" + result.thumbnailSrc + "'");
}).catch((error: BookmarkError) => {
ok(false, "empty list of metadata should not reject. error: " + error);
}).then(() => {
done();
});
});
test("bookmarkPage returns BookmarkResult with just a url when list of metadata contains no useful information", (assert: QUnitAssert) => {
let done = assert.async();
let expectedResult: BookmarkResult = {
url: TestHelper.Content.testBookmarkUrl,
title: TestHelper.Content.testPageTitle
};
let metadata = TestHelper.createListOfMetaTags([TestHelper.StandardMetadata.Fake]);
BookmarkHelper.bookmarkPage(expectedResult.url, TestHelper.Content.testPageTitle, metadata).then((result: BookmarkResult) => {
strictEqual(result.url, expectedResult.url, "bookmarked url is incorrect");
strictEqual(result.description, undefined, "bookmarked description should be undefined. actual: '" + result.description + "'");
strictEqual(result.thumbnailSrc, undefined, "bookmarked thumbnail source should be undefined. actual: '" + result.thumbnailSrc + "'");
}).catch((error: BookmarkError) => {
ok(false, "useless list of metadata should not reject. error: " + error);
}).then(() => {
done();
});
});
test("getPrimaryDescription returns undefined if og:description meta tag does not exist", () => {
strictEqual(BookmarkHelper.getPrimaryDescription(undefined), undefined, "undefined list of meta tags should return undefined. actual: '" + BookmarkHelper.getPrimaryDescription(undefined));
let metaTags = new Array<HTMLMetaElement>();
strictEqual(BookmarkHelper.getPrimaryDescription(metaTags), undefined, "empty list of meta tags should return undefined");
metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.FallbackDescription,
TestHelper.StandardMetadata.FallbackDescription,
TestHelper.StandardMetadata.FallbackThumbnail,
TestHelper.StandardMetadata.FallbackThumbnail,
TestHelper.StandardMetadata.PrimaryThumbnail
]);
let result = BookmarkHelper.getPrimaryDescription(metaTags);
strictEqual(result, undefined, "missing og:description should return undefined. actual: '" + result + "'");
});
test("getPrimaryDescription returns content of og:description meta tag", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.PrimaryDescription
]);
strictEqual(BookmarkHelper.getPrimaryDescription(metaTags).description, TestHelper.Content.testDescriptionValue, "description is incorrect");
});
test("getFallbackDescription returns undefined if fallback description meta tags do not exist", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.PrimaryDescription,
TestHelper.StandardMetadata.PrimaryThumbnail,
TestHelper.StandardMetadata.Fake,
TestHelper.StandardMetadata.FallbackThumbnail
]);
let result = BookmarkHelper.getFallbackDescription(metaTags);
strictEqual(BookmarkHelper.getFallbackDescription(metaTags), undefined, "missing fallback description should return undefined. actual: '" + result + "'");
});
test("getFallbackDescription returns content if fallback description meta tags with content exist", () => {
let metaTags = new Array<HTMLMetaElement>();
// add all fallback description attributes to tag list
for (let iFallback = 0; iFallback < BookmarkHelper.fallbackDescriptionKeyValuePairs.length; iFallback++) {
metaTags.push(TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.FallbackDescription
], iFallback)[0]);
}
let assertCounter = 0;
while (metaTags.length > 0) {
let descResult = BookmarkHelper.getFallbackDescription(metaTags);
let expectedDesc = TestHelper.Content.fallbackDescContentPrefix + assertCounter;
strictEqual(descResult.description, expectedDesc, "content is incorrect - is fallback order incorrect?");
assertCounter++;
if (metaTags.length > 1) {
// remove content and make sure it falls back to next in line
metaTags[0].removeAttribute("content");
descResult = BookmarkHelper.getFallbackDescription(metaTags);
expectedDesc = TestHelper.Content.fallbackDescContentPrefix + assertCounter;
strictEqual(descResult.description, expectedDesc, "content is incorrect - are we incorrectly falling back to undefined content?");
}
metaTags.shift();
}
});
test("getPrimaryThumbnailSrc returns undefined if og:image meta tag does not exist", () => {
strictEqual(BookmarkHelper.getPrimaryThumbnailSrc(undefined), undefined, "undefined list of meta tags should return undefined");
let metaTags = new Array<HTMLMetaElement>();
strictEqual(BookmarkHelper.getPrimaryThumbnailSrc(metaTags), undefined, "empty list of meta tags should return undefined");
metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.FallbackDescription,
TestHelper.StandardMetadata.FallbackDescription,
TestHelper.StandardMetadata.FallbackThumbnail,
TestHelper.StandardMetadata.FallbackThumbnail,
TestHelper.StandardMetadata.PrimaryDescription
]);
let result = BookmarkHelper.getPrimaryThumbnailSrc(metaTags);
strictEqual(result, undefined, "missing og:image should return undefined. actual: '" + result + "'");
});
test("getPrimaryThumbnailSrc returns content of og:image meta tag", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.PrimaryThumbnail
]);
strictEqual(BookmarkHelper.getPrimaryThumbnailSrc(metaTags).thumbnailSrc, TestHelper.Content.testThumbnailSrcValue, "thumbnail source is incorrect");
});
test("getFallbackThumbnailSrc returns undefined if fallback thumbnail src meta tags do not exist", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.PrimaryDescription,
TestHelper.StandardMetadata.PrimaryThumbnail,
TestHelper.StandardMetadata.Fake,
TestHelper.StandardMetadata.FallbackDescription
]);
let result = BookmarkHelper.getFallbackThumbnailSrc(metaTags);
strictEqual(result, undefined, "missing fallback thumbnail src should return undefined. actual: '" + result + "'");
});
test("getFallbackThumbnailSrc returns content if fallback thumbnail src meta tags with content exist", () => {
let metaTags = new Array<HTMLMetaElement>();
// add all fallback thumbnail src attributes to tag list
for (let iFallback = 0; iFallback < BookmarkHelper.fallbackThumbnailKeyValuePairs.length; iFallback++) {
metaTags.push(TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.FallbackThumbnail
], iFallback)[0]);
}
let assertCounter = 0;
while (metaTags.length > 0) {
let thumbnailSrcResult = BookmarkHelper.getFallbackThumbnailSrc(metaTags);
let expectedThumbnailSrc = TestHelper.Content.fallbackThumbnailSrcContentBase + assertCounter;
strictEqual(thumbnailSrcResult.thumbnailSrc, expectedThumbnailSrc, "content is incorrect - is fallback order incorrect?");
assertCounter++;
if (metaTags.length > 1) {
// remove content and make sure it falls back to next in line
metaTags[0].removeAttribute("content");
thumbnailSrcResult = BookmarkHelper.getFallbackThumbnailSrc(metaTags);
expectedThumbnailSrc = TestHelper.Content.fallbackThumbnailSrcContentBase + assertCounter;
strictEqual(thumbnailSrcResult.thumbnailSrc, expectedThumbnailSrc, "content is incorrect - are we incorrectly falling back to undefined content?");
}
metaTags.shift();
}
});
test("getFirstImageOnPage returns undefined if image tags do not exist", () => {
let thumbnailSrcResult = BookmarkHelper.getFirstImageOnPage(undefined);
strictEqual(thumbnailSrcResult, undefined, "undefined list of image elements should return undefined");
let images: HTMLImageElement[] = new Array<HTMLImageElement>();
thumbnailSrcResult = BookmarkHelper.getFirstImageOnPage(images);
strictEqual(thumbnailSrcResult, undefined, "empty list of image elements should return undefined");
});
test("getFirstImageOnPage returns undefined if image tag without src values exist", () => {
let images: HTMLImageElement[] = new Array<HTMLImageElement>();
images.push(TestHelper.createHTMLImageElement(undefined));
images.push(TestHelper.createHTMLImageElement(""));
let thumbnailSrcResult = BookmarkHelper.getFirstImageOnPage(images);
strictEqual(thumbnailSrcResult, undefined, "list of image elements without src values should return undefined");
});
test("getFirstImageOnPage returns content if image tag with content exist", () => {
let images: HTMLImageElement[] = new Array<HTMLImageElement>();
images.push(TestHelper.createHTMLImageElement(TestHelper.Content.fallbackThumbnailSrcContentBase + "0"));
images.push(TestHelper.createHTMLImageElement(TestHelper.Content.fallbackThumbnailSrcContentBase + "1"));
let thumbnailSrcResult = BookmarkHelper.getFirstImageOnPage(images);
strictEqual(thumbnailSrcResult.thumbnailSrc, TestHelper.Content.fallbackThumbnailSrcContentBase + "0");
});
test("getMetaContent returns undefined if metatags are undefined", () => {
let result = BookmarkHelper.getMetaContent(undefined, BookmarkHelper.primaryThumbnailKeyValuePair);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns undefined if metatags are empty", () => {
let result = BookmarkHelper.getMetaContent(new Array<HTMLMetaElement>(), BookmarkHelper.primaryThumbnailKeyValuePair);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns undefined if metadata is undefined", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.Fake
]);
let result = BookmarkHelper.getMetaContent(metaTags, undefined);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns undefined if metadata is empty", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.Fake
]);
let emptyMetadata: MetadataKeyValuePair = { key: BookmarkHelper.propertyAttrName, value: "" };
let result = BookmarkHelper.getMetaContent(metaTags, emptyMetadata);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns undefined if the metadata exists but the content is undefined", () => {
// non-standard metadata, so not using TestHelper.createListOfMetaTags
let metaTags = new Array<HTMLMetaElement>();
metaTags.push(TestHelper.createHTMLMetaElement(BookmarkHelper.primaryThumbnailKeyValuePair, undefined));
let result = BookmarkHelper.getMetaContent(metaTags, BookmarkHelper.primaryThumbnailKeyValuePair);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns undefined if the metadata exists but the content is empty", () => {
// non-standard metadata, so not using TestHelper.createListOfMetaTags
let metaTags = new Array<HTMLMetaElement>();
metaTags.push(TestHelper.createHTMLMetaElement(BookmarkHelper.primaryThumbnailKeyValuePair, ""));
let result = BookmarkHelper.getMetaContent(metaTags, BookmarkHelper.primaryThumbnailKeyValuePair);
strictEqual(result, undefined, "actual: " + result);
});
test("getMetaContent returns content if it exists", () => {
let metaTags = TestHelper.createListOfMetaTags([
TestHelper.StandardMetadata.PrimaryThumbnail
]);
let result = BookmarkHelper.getMetaContent(metaTags, BookmarkHelper.primaryThumbnailKeyValuePair);
strictEqual(result, TestHelper.Content.testThumbnailSrcValue, "actual: " + result);
});
}
}
module TestHelper {
export module Content {
export let testDescriptionValue = "test description";
export let testThumbnailSrcValue = "http://www.abc.com/thumbnail.jpg";
export let testBookmarkUrl = "https://www.onenote.com";
export let fallbackDescContentPrefix = "test fallback description ";
export let fallbackThumbnailSrcContentBase = "http://www.abc.com/fallback.jpg?src=";
export let testPageTitle = "";
}
export function createHTMLMetaElement(attribute: MetadataKeyValuePair, content: string): HTMLMetaElement {
let metaElement: HTMLMetaElement = document.createElement("meta") as HTMLMetaElement;
metaElement.setAttribute(attribute.key, attribute.value);
if (content) {
metaElement.content = content;
}
return metaElement;
}
export function createHTMLImageElement(srcUrl: string): HTMLImageElement {
let imgElement: HTMLImageElement = document.createElement("img") as HTMLImageElement;
if (srcUrl) {
imgElement.setAttribute(BookmarkHelper.srcAttrName, srcUrl);
}
return imgElement;
}
export enum StandardMetadata {
Fake,
FallbackDescription,
FallbackThumbnail,
PrimaryDescription,
PrimaryThumbnail
}
export function createListOfMetaTags(metadataTypes: StandardMetadata[], fallbackIndexer?: number): HTMLMetaElement[] {
let metaTags = new Array<HTMLMetaElement>();
for (let type of metadataTypes) {
switch (type) {
case StandardMetadata.PrimaryDescription:
metaTags.push(
TestHelper.createHTMLMetaElement(
BookmarkHelper.primaryDescriptionKeyValuePair,
TestHelper.Content.testDescriptionValue
)
);
break;
case StandardMetadata.PrimaryThumbnail:
metaTags.push(
TestHelper.createHTMLMetaElement(
BookmarkHelper.primaryThumbnailKeyValuePair,
TestHelper.Content.testThumbnailSrcValue
)
);
break;
case StandardMetadata.Fake:
let uselessMetadata: MetadataKeyValuePair = {
key: BookmarkHelper.propertyAttrName,
value: "attributeFake"
};
metaTags.push(
TestHelper.createHTMLMetaElement(
uselessMetadata,
"content fake"
)
);
break;
case StandardMetadata.FallbackDescription:
let descIndexer: number;
if (ObjectUtils.isNullOrUndefined(fallbackIndexer)) {
// if not provided, get a random fallback description
descIndexer = TestHelper.getRandomNumber(BookmarkHelper.fallbackDescriptionKeyValuePairs.length - 1);
} else {
descIndexer = fallbackIndexer;
}
let descMetadata: MetadataKeyValuePair = BookmarkHelper.fallbackDescriptionKeyValuePairs[descIndexer];
metaTags.push(
TestHelper.createHTMLMetaElement(
descMetadata,
TestHelper.Content.fallbackDescContentPrefix + descIndexer
)
);
break;
case StandardMetadata.FallbackThumbnail:
let thumbnailIndexer: number;
if (ObjectUtils.isNullOrUndefined(fallbackIndexer)) {
// if not provided, get a random fallback thumbnail src
thumbnailIndexer = TestHelper.getRandomNumber(BookmarkHelper.fallbackThumbnailKeyValuePairs.length - 1);
} else {
thumbnailIndexer = fallbackIndexer;
}
let thumbnailMetadata: MetadataKeyValuePair = BookmarkHelper.fallbackThumbnailKeyValuePairs[thumbnailIndexer];
metaTags.push(
TestHelper.createHTMLMetaElement(
thumbnailMetadata,
TestHelper.Content.fallbackThumbnailSrcContentBase + thumbnailIndexer
)
);
break;
default:
break;
}
}
return metaTags;
}
export function getRandomNumber(maxInclusive: number): number {
return Math.floor(Math.random() * (maxInclusive + 1));
}
}
(new BookmarkHelperTests()).runTests(); | the_stack |
import * as XmlNames from './../defs/xml-names';
import * as XmlUtils from './../utils/xml-utils';
import { KdbxTimes } from './kdbx-times';
import { KdbxUuid } from './kdbx-uuid';
import { KdbxEntry } from './kdbx-entry';
import { KdbxCustomData, KdbxCustomDataMap } from './kdbx-custom-data';
import { Icons } from '../defs/consts';
import { KdbxContext } from './kdbx-context';
import { MergeObjectMap } from './kdbx';
export class KdbxGroup {
uuid = new KdbxUuid();
name: string | undefined;
notes: string | undefined;
icon: number | undefined;
customIcon: KdbxUuid | undefined;
tags: string[] = [];
times = new KdbxTimes();
expanded: boolean | undefined;
defaultAutoTypeSeq: string | undefined;
enableAutoType: boolean | null | undefined;
enableSearching: boolean | null | undefined;
lastTopVisibleEntry: KdbxUuid | undefined;
groups: KdbxGroup[] = [];
entries: KdbxEntry[] = [];
parentGroup: KdbxGroup | undefined;
previousParentGroup: KdbxUuid | undefined;
customData: KdbxCustomDataMap | undefined;
get lastModTime(): number {
return this.times.lastModTime?.getTime() ?? 0;
}
get locationChanged(): number {
return this.times.locationChanged?.getTime() ?? 0;
}
private readNode(node: Element, ctx: KdbxContext) {
switch (node.tagName) {
case XmlNames.Elem.Uuid:
this.uuid = XmlUtils.getUuid(node) ?? new KdbxUuid();
break;
case XmlNames.Elem.Name:
this.name = XmlUtils.getText(node);
break;
case XmlNames.Elem.Notes:
this.notes = XmlUtils.getText(node);
break;
case XmlNames.Elem.Icon:
this.icon = XmlUtils.getNumber(node);
break;
case XmlNames.Elem.CustomIconID:
this.customIcon = XmlUtils.getUuid(node);
break;
case XmlNames.Elem.Tags:
this.tags = XmlUtils.getTags(node);
break;
case XmlNames.Elem.Times:
this.times = KdbxTimes.read(node);
break;
case XmlNames.Elem.IsExpanded:
this.expanded = XmlUtils.getBoolean(node) ?? undefined;
break;
case XmlNames.Elem.GroupDefaultAutoTypeSeq:
this.defaultAutoTypeSeq = XmlUtils.getText(node);
break;
case XmlNames.Elem.EnableAutoType:
this.enableAutoType = XmlUtils.getBoolean(node);
break;
case XmlNames.Elem.EnableSearching:
this.enableSearching = XmlUtils.getBoolean(node);
break;
case XmlNames.Elem.LastTopVisibleEntry:
this.lastTopVisibleEntry = XmlUtils.getUuid(node);
break;
case XmlNames.Elem.Group:
this.groups.push(KdbxGroup.read(node, ctx, this));
break;
case XmlNames.Elem.Entry:
this.entries.push(KdbxEntry.read(node, ctx, this));
break;
case XmlNames.Elem.CustomData:
this.customData = KdbxCustomData.read(node);
break;
case XmlNames.Elem.PreviousParentGroup:
this.previousParentGroup = XmlUtils.getUuid(node);
break;
}
}
write(parentNode: Node, ctx: KdbxContext): void {
const node = XmlUtils.addChildNode(parentNode, XmlNames.Elem.Group);
XmlUtils.setUuid(XmlUtils.addChildNode(node, XmlNames.Elem.Uuid), this.uuid);
XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.Name), this.name);
XmlUtils.setText(XmlUtils.addChildNode(node, XmlNames.Elem.Notes), this.notes);
XmlUtils.setNumber(XmlUtils.addChildNode(node, XmlNames.Elem.Icon), this.icon);
if (this.tags.length && ctx.kdbx.versionIsAtLeast(4, 1)) {
XmlUtils.setTags(XmlUtils.addChildNode(node, XmlNames.Elem.Tags), this.tags);
}
if (this.customIcon) {
XmlUtils.setUuid(
XmlUtils.addChildNode(node, XmlNames.Elem.CustomIconID),
this.customIcon
);
}
if (this.previousParentGroup !== undefined && ctx.kdbx.versionIsAtLeast(4, 1)) {
XmlUtils.setUuid(
XmlUtils.addChildNode(node, XmlNames.Elem.PreviousParentGroup),
this.previousParentGroup
);
}
if (this.customData) {
KdbxCustomData.write(node, ctx, this.customData);
}
this.times.write(node, ctx);
XmlUtils.setBoolean(XmlUtils.addChildNode(node, XmlNames.Elem.IsExpanded), this.expanded);
XmlUtils.setText(
XmlUtils.addChildNode(node, XmlNames.Elem.GroupDefaultAutoTypeSeq),
this.defaultAutoTypeSeq
);
XmlUtils.setBoolean(
XmlUtils.addChildNode(node, XmlNames.Elem.EnableAutoType),
this.enableAutoType
);
XmlUtils.setBoolean(
XmlUtils.addChildNode(node, XmlNames.Elem.EnableSearching),
this.enableSearching
);
XmlUtils.setUuid(
XmlUtils.addChildNode(node, XmlNames.Elem.LastTopVisibleEntry),
this.lastTopVisibleEntry
);
for (const group of this.groups) {
group.write(node, ctx);
}
for (const entry of this.entries) {
entry.write(node, ctx);
}
}
*allGroups(): IterableIterator<KdbxGroup> {
yield this;
for (const group of this.groups) {
for (const g of group.allGroups()) {
yield g;
}
}
}
*allEntries(): IterableIterator<KdbxEntry> {
for (const group of this.allGroups()) {
for (const entry of group.entries) {
yield entry;
}
}
}
*allGroupsAndEntries(): IterableIterator<KdbxGroup | KdbxEntry> {
yield this;
for (const entry of this.entries) {
yield entry;
}
for (const group of this.groups) {
for (const item of group.allGroupsAndEntries()) {
yield item;
}
}
}
merge(objectMap: MergeObjectMap): void {
const remoteGroup = objectMap.remoteGroups.get(this.uuid.id);
if (!remoteGroup) {
return;
}
if (remoteGroup.lastModTime > this.lastModTime) {
this.copyFrom(remoteGroup);
}
this.groups = this.mergeCollection(
this.groups,
remoteGroup.groups,
objectMap.groups,
objectMap.remoteGroups,
objectMap.deleted
);
this.entries = this.mergeCollection(
this.entries,
remoteGroup.entries,
objectMap.entries,
objectMap.remoteEntries,
objectMap.deleted
);
for (const group of this.groups) {
group.merge(objectMap);
}
for (const entry of this.entries) {
entry.merge(objectMap);
}
}
/**
* Merge object collection with remote collection
* Implements 2P-set CRDT with tombstones stored in objectMap.deleted
* Assumes tombstones are already merged
*/
private mergeCollection<T extends KdbxGroup | KdbxEntry>(
collection: T[],
remoteCollection: T[],
objectMapItems: Map<string, T>,
remoteObjectMapItems: Map<string, T>,
deletedObjects: Map<string, Date>
): T[] {
const newItems: T[] = [];
for (const item of collection) {
if (!item.uuid || deletedObjects.has(item.uuid.id)) {
continue; // item deleted
}
const remoteItem = remoteObjectMapItems.get(item.uuid.id);
if (!remoteItem) {
newItems.push(item); // item added locally
} else if (remoteItem.locationChanged <= item.locationChanged) {
newItems.push(item); // item not changed or moved to this group locally later than remote
}
}
let ix = -1;
for (const remoteItem of remoteCollection) {
ix++;
if (!remoteItem.uuid || deletedObjects.has(remoteItem.uuid.id)) {
continue; // item already processed as local item or deleted
}
const item = objectMapItems.get(remoteItem.uuid.id);
if (item && remoteItem.locationChanged > item.locationChanged) {
item.parentGroup = this; // item moved to this group remotely later than local
newItems.splice(KdbxGroup.findInsertIx(newItems, remoteCollection, ix), 0, item);
} else if (!item) {
// item created remotely
let newItem: T;
if (remoteItem instanceof KdbxGroup) {
const group = new KdbxGroup();
group.copyFrom(remoteItem);
newItem = <T>group;
} else if (remoteItem instanceof KdbxEntry) {
const entry = new KdbxEntry();
entry.copyFrom(remoteItem);
newItem = <T>entry;
} else {
continue;
}
newItem.parentGroup = this;
newItems.splice(KdbxGroup.findInsertIx(newItems, remoteCollection, ix), 0, newItem);
}
}
return newItems;
}
/**
* Finds a best place to insert new item into collection
*/
private static findInsertIx<T extends KdbxGroup | KdbxEntry>(
dst: T[],
src: T[],
srcIx: number
): number {
let selectedIx = dst.length,
selectedScore = -1;
for (let dstIx = 0; dstIx <= dst.length; dstIx++) {
let score = 0;
const srcPrev = srcIx > 0 ? src[srcIx - 1].uuid.id : undefined,
srcNext = srcIx + 1 < src.length ? src[srcIx + 1].uuid.id : undefined,
dstPrev = dstIx > 0 ? dst[dstIx - 1].uuid.id : undefined,
dstNext = dstIx < dst.length ? dst[dstIx].uuid.id : undefined;
if (!srcPrev && !dstPrev) {
score += 1; // start of sequence
} else if (srcPrev === dstPrev) {
score += 5; // previous element equals
}
if (!srcNext && !dstNext) {
score += 2; // end of sequence
} else if (srcNext === dstNext) {
score += 5; // next element equals
}
if (score > selectedScore) {
selectedIx = dstIx;
selectedScore = score;
}
}
return selectedIx;
}
copyFrom(group: KdbxGroup): void {
this.uuid = group.uuid;
this.name = group.name;
this.notes = group.notes;
this.icon = group.icon;
this.customIcon = group.customIcon;
this.times = group.times.clone();
this.expanded = group.expanded;
this.defaultAutoTypeSeq = group.defaultAutoTypeSeq;
this.enableAutoType = group.enableAutoType;
this.enableSearching = group.enableSearching;
this.lastTopVisibleEntry = group.lastTopVisibleEntry;
}
static create(name: string, parentGroup?: KdbxGroup): KdbxGroup {
const group = new KdbxGroup();
group.uuid = KdbxUuid.random();
group.icon = Icons.Folder;
group.times = KdbxTimes.create();
group.name = name;
group.parentGroup = parentGroup;
group.expanded = true;
group.enableAutoType = null;
group.enableSearching = null;
group.lastTopVisibleEntry = new KdbxUuid();
return group;
}
static read(xmlNode: Node, ctx: KdbxContext, parentGroup?: KdbxGroup): KdbxGroup {
const grp = new KdbxGroup();
for (let i = 0, cn = xmlNode.childNodes, len = cn.length; i < len; i++) {
const childNode = <Element>cn[i];
if (childNode.tagName) {
grp.readNode(childNode, ctx);
}
}
if (grp.uuid.empty) {
// some clients don't write ids
grp.uuid = KdbxUuid.random();
}
grp.parentGroup = parentGroup;
return grp;
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class MigrationHubStrategy extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: MigrationHubStrategy.Types.ClientConfiguration)
config: Config & MigrationHubStrategy.Types.ClientConfiguration;
/**
* Retrieves details about an application component.
*/
getApplicationComponentDetails(params: MigrationHubStrategy.Types.GetApplicationComponentDetailsRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetApplicationComponentDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetApplicationComponentDetailsResponse, AWSError>;
/**
* Retrieves details about an application component.
*/
getApplicationComponentDetails(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetApplicationComponentDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetApplicationComponentDetailsResponse, AWSError>;
/**
* Retrieves a list of all the recommended strategies and tools for an application component running on a server.
*/
getApplicationComponentStrategies(params: MigrationHubStrategy.Types.GetApplicationComponentStrategiesRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetApplicationComponentStrategiesResponse) => void): Request<MigrationHubStrategy.Types.GetApplicationComponentStrategiesResponse, AWSError>;
/**
* Retrieves a list of all the recommended strategies and tools for an application component running on a server.
*/
getApplicationComponentStrategies(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetApplicationComponentStrategiesResponse) => void): Request<MigrationHubStrategy.Types.GetApplicationComponentStrategiesResponse, AWSError>;
/**
* Retrieves the status of an on-going assessment.
*/
getAssessment(params: MigrationHubStrategy.Types.GetAssessmentRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetAssessmentResponse) => void): Request<MigrationHubStrategy.Types.GetAssessmentResponse, AWSError>;
/**
* Retrieves the status of an on-going assessment.
*/
getAssessment(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetAssessmentResponse) => void): Request<MigrationHubStrategy.Types.GetAssessmentResponse, AWSError>;
/**
* Retrieves the details about a specific import task.
*/
getImportFileTask(params: MigrationHubStrategy.Types.GetImportFileTaskRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.GetImportFileTaskResponse, AWSError>;
/**
* Retrieves the details about a specific import task.
*/
getImportFileTask(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.GetImportFileTaskResponse, AWSError>;
/**
* Retrieves your migration and modernization preferences.
*/
getPortfolioPreferences(params: MigrationHubStrategy.Types.GetPortfolioPreferencesRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetPortfolioPreferencesResponse) => void): Request<MigrationHubStrategy.Types.GetPortfolioPreferencesResponse, AWSError>;
/**
* Retrieves your migration and modernization preferences.
*/
getPortfolioPreferences(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetPortfolioPreferencesResponse) => void): Request<MigrationHubStrategy.Types.GetPortfolioPreferencesResponse, AWSError>;
/**
* Retrieves overall summary including the number of servers to rehost and the overall number of anti-patterns.
*/
getPortfolioSummary(params: MigrationHubStrategy.Types.GetPortfolioSummaryRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetPortfolioSummaryResponse) => void): Request<MigrationHubStrategy.Types.GetPortfolioSummaryResponse, AWSError>;
/**
* Retrieves overall summary including the number of servers to rehost and the overall number of anti-patterns.
*/
getPortfolioSummary(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetPortfolioSummaryResponse) => void): Request<MigrationHubStrategy.Types.GetPortfolioSummaryResponse, AWSError>;
/**
* Retrieves detailed information about the specified recommendation report.
*/
getRecommendationReportDetails(params: MigrationHubStrategy.Types.GetRecommendationReportDetailsRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetRecommendationReportDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetRecommendationReportDetailsResponse, AWSError>;
/**
* Retrieves detailed information about the specified recommendation report.
*/
getRecommendationReportDetails(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetRecommendationReportDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetRecommendationReportDetailsResponse, AWSError>;
/**
* Retrieves detailed information about a specified server.
*/
getServerDetails(params: MigrationHubStrategy.Types.GetServerDetailsRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetServerDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetServerDetailsResponse, AWSError>;
/**
* Retrieves detailed information about a specified server.
*/
getServerDetails(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetServerDetailsResponse) => void): Request<MigrationHubStrategy.Types.GetServerDetailsResponse, AWSError>;
/**
* Retrieves recommended strategies and tools for the specified server.
*/
getServerStrategies(params: MigrationHubStrategy.Types.GetServerStrategiesRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetServerStrategiesResponse) => void): Request<MigrationHubStrategy.Types.GetServerStrategiesResponse, AWSError>;
/**
* Retrieves recommended strategies and tools for the specified server.
*/
getServerStrategies(callback?: (err: AWSError, data: MigrationHubStrategy.Types.GetServerStrategiesResponse) => void): Request<MigrationHubStrategy.Types.GetServerStrategiesResponse, AWSError>;
/**
* Retrieves a list of all the application components (processes).
*/
listApplicationComponents(params: MigrationHubStrategy.Types.ListApplicationComponentsRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListApplicationComponentsResponse) => void): Request<MigrationHubStrategy.Types.ListApplicationComponentsResponse, AWSError>;
/**
* Retrieves a list of all the application components (processes).
*/
listApplicationComponents(callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListApplicationComponentsResponse) => void): Request<MigrationHubStrategy.Types.ListApplicationComponentsResponse, AWSError>;
/**
* Retrieves a list of all the installed collectors.
*/
listCollectors(params: MigrationHubStrategy.Types.ListCollectorsRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListCollectorsResponse) => void): Request<MigrationHubStrategy.Types.ListCollectorsResponse, AWSError>;
/**
* Retrieves a list of all the installed collectors.
*/
listCollectors(callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListCollectorsResponse) => void): Request<MigrationHubStrategy.Types.ListCollectorsResponse, AWSError>;
/**
* Retrieves a list of all the imports performed.
*/
listImportFileTask(params: MigrationHubStrategy.Types.ListImportFileTaskRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.ListImportFileTaskResponse, AWSError>;
/**
* Retrieves a list of all the imports performed.
*/
listImportFileTask(callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.ListImportFileTaskResponse, AWSError>;
/**
* Returns a list of all the servers.
*/
listServers(params: MigrationHubStrategy.Types.ListServersRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListServersResponse) => void): Request<MigrationHubStrategy.Types.ListServersResponse, AWSError>;
/**
* Returns a list of all the servers.
*/
listServers(callback?: (err: AWSError, data: MigrationHubStrategy.Types.ListServersResponse) => void): Request<MigrationHubStrategy.Types.ListServersResponse, AWSError>;
/**
* Saves the specified migration and modernization preferences.
*/
putPortfolioPreferences(params: MigrationHubStrategy.Types.PutPortfolioPreferencesRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.PutPortfolioPreferencesResponse) => void): Request<MigrationHubStrategy.Types.PutPortfolioPreferencesResponse, AWSError>;
/**
* Saves the specified migration and modernization preferences.
*/
putPortfolioPreferences(callback?: (err: AWSError, data: MigrationHubStrategy.Types.PutPortfolioPreferencesResponse) => void): Request<MigrationHubStrategy.Types.PutPortfolioPreferencesResponse, AWSError>;
/**
* Starts the assessment of an on-premises environment.
*/
startAssessment(params: MigrationHubStrategy.Types.StartAssessmentRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartAssessmentResponse) => void): Request<MigrationHubStrategy.Types.StartAssessmentResponse, AWSError>;
/**
* Starts the assessment of an on-premises environment.
*/
startAssessment(callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartAssessmentResponse) => void): Request<MigrationHubStrategy.Types.StartAssessmentResponse, AWSError>;
/**
* Starts a file import.
*/
startImportFileTask(params: MigrationHubStrategy.Types.StartImportFileTaskRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.StartImportFileTaskResponse, AWSError>;
/**
* Starts a file import.
*/
startImportFileTask(callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartImportFileTaskResponse) => void): Request<MigrationHubStrategy.Types.StartImportFileTaskResponse, AWSError>;
/**
* Starts generating a recommendation report.
*/
startRecommendationReportGeneration(params: MigrationHubStrategy.Types.StartRecommendationReportGenerationRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartRecommendationReportGenerationResponse) => void): Request<MigrationHubStrategy.Types.StartRecommendationReportGenerationResponse, AWSError>;
/**
* Starts generating a recommendation report.
*/
startRecommendationReportGeneration(callback?: (err: AWSError, data: MigrationHubStrategy.Types.StartRecommendationReportGenerationResponse) => void): Request<MigrationHubStrategy.Types.StartRecommendationReportGenerationResponse, AWSError>;
/**
* Stops the assessment of an on-premises environment.
*/
stopAssessment(params: MigrationHubStrategy.Types.StopAssessmentRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.StopAssessmentResponse) => void): Request<MigrationHubStrategy.Types.StopAssessmentResponse, AWSError>;
/**
* Stops the assessment of an on-premises environment.
*/
stopAssessment(callback?: (err: AWSError, data: MigrationHubStrategy.Types.StopAssessmentResponse) => void): Request<MigrationHubStrategy.Types.StopAssessmentResponse, AWSError>;
/**
* Updates the configuration of an application component.
*/
updateApplicationComponentConfig(params: MigrationHubStrategy.Types.UpdateApplicationComponentConfigRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.UpdateApplicationComponentConfigResponse) => void): Request<MigrationHubStrategy.Types.UpdateApplicationComponentConfigResponse, AWSError>;
/**
* Updates the configuration of an application component.
*/
updateApplicationComponentConfig(callback?: (err: AWSError, data: MigrationHubStrategy.Types.UpdateApplicationComponentConfigResponse) => void): Request<MigrationHubStrategy.Types.UpdateApplicationComponentConfigResponse, AWSError>;
/**
* Updates the configuration of the specified server.
*/
updateServerConfig(params: MigrationHubStrategy.Types.UpdateServerConfigRequest, callback?: (err: AWSError, data: MigrationHubStrategy.Types.UpdateServerConfigResponse) => void): Request<MigrationHubStrategy.Types.UpdateServerConfigResponse, AWSError>;
/**
* Updates the configuration of the specified server.
*/
updateServerConfig(callback?: (err: AWSError, data: MigrationHubStrategy.Types.UpdateServerConfigResponse) => void): Request<MigrationHubStrategy.Types.UpdateServerConfigResponse, AWSError>;
}
declare namespace MigrationHubStrategy {
export type AntipatternReportStatus = "FAILED"|"IN_PROGRESS"|"SUCCESS"|string;
export interface AntipatternSeveritySummary {
/**
* Contains the count of anti-patterns.
*/
count?: Integer;
/**
* Contains the severity of anti-patterns.
*/
severity?: Severity;
}
export type AppType = "DotNetFramework"|"Java"|"SQLServer"|"IIS"|"Oracle"|"Other"|string;
export type ApplicationComponentCriteria = "NOT_DEFINED"|"APP_NAME"|"SERVER_ID"|"APP_TYPE"|"STRATEGY"|"DESTINATION"|string;
export interface ApplicationComponentDetail {
/**
* The status of analysis, if the application component has source code or an associated database.
*/
analysisStatus?: SrcCodeOrDbAnalysisStatus;
/**
* The S3 bucket name and the Amazon S3 key name for the anti-pattern report.
*/
antipatternReportS3Object?: S3Object;
/**
* The status of the anti-pattern report generation.
*/
antipatternReportStatus?: AntipatternReportStatus;
/**
* The status message for the anti-pattern.
*/
antipatternReportStatusMessage?: StatusMessage;
/**
* The type of application component.
*/
appType?: AppType;
/**
* The ID of the server that the application component is running on.
*/
associatedServerId?: ServerId;
/**
* Configuration details for the database associated with the application component.
*/
databaseConfigDetail?: DatabaseConfigDetail;
/**
* The ID of the application component.
*/
id?: ResourceId;
/**
* Indicates whether the application component has been included for server recommendation or not.
*/
inclusionStatus?: InclusionStatus;
/**
* The timestamp of when the application component was assessed.
*/
lastAnalyzedTimestamp?: TimeStamp;
/**
* A list of anti-pattern severity summaries.
*/
listAntipatternSeveritySummary?: ListAntipatternSeveritySummary;
/**
* Set to true if the application component is running on multiple servers.
*/
moreServerAssociationExists?: Boolean;
/**
* The name of application component.
*/
name?: ResourceName;
/**
* OS driver.
*/
osDriver?: String;
/**
* OS version.
*/
osVersion?: String;
/**
* The top recommendation set for the application component.
*/
recommendationSet?: RecommendationSet;
/**
* The application component subtype.
*/
resourceSubType?: ResourceSubType;
/**
* Details about the source code repository associated with the application component.
*/
sourceCodeRepositories?: SourceCodeRepositories;
/**
* A detailed description of the analysis status and any failure message.
*/
statusMessage?: StatusMessage;
}
export type ApplicationComponentDetails = ApplicationComponentDetail[];
export type ApplicationComponentId = string;
export type ApplicationComponentStrategies = ApplicationComponentStrategy[];
export interface ApplicationComponentStrategy {
/**
* Set to true if the recommendation is set as preferred.
*/
isPreferred?: Boolean;
/**
* Strategy recommendation for the application component.
*/
recommendation?: RecommendationSet;
/**
* The recommendation status of a strategy for an application component.
*/
status?: StrategyRecommendation;
}
export interface ApplicationComponentSummary {
/**
* Contains the name of application types.
*/
appType?: AppType;
/**
* Contains the count of application type.
*/
count?: Integer;
}
export interface ApplicationPreferences {
/**
* Application preferences that you specify to prefer managed environment.
*/
managementPreference?: ManagementPreference;
}
export type AssessmentStatus = "IN_PROGRESS"|"COMPLETE"|"FAILED"|"STOPPED"|string;
export interface AssessmentSummary {
/**
* The Amazon S3 object containing the anti-pattern report.
*/
antipatternReportS3Object?: S3Object;
/**
* The status of the anti-pattern report.
*/
antipatternReportStatus?: AntipatternReportStatus;
/**
* The status message of the anti-pattern report.
*/
antipatternReportStatusMessage?: StatusMessage;
/**
* The time the assessment was performed.
*/
lastAnalyzedTimestamp?: TimeStamp;
/**
* List of AntipatternSeveritySummary.
*/
listAntipatternSeveritySummary?: ListAntipatternSeveritySummary;
/**
* List of ApplicationComponentStrategySummary.
*/
listApplicationComponentStrategySummary?: ListStrategySummary;
/**
* List of ApplicationComponentSummary.
*/
listApplicationComponentSummary?: ListApplicationComponentSummary;
/**
* List of ServerStrategySummary.
*/
listServerStrategySummary?: ListStrategySummary;
/**
* List of ServerSummary.
*/
listServerSummary?: ListServerSummary;
}
export interface AssociatedApplication {
/**
* ID of the application as defined in Application Discovery Service.
*/
id?: String;
/**
* Name of the application as defined in Application Discovery Service.
*/
name?: String;
}
export type AssociatedApplications = AssociatedApplication[];
export type AssociatedServerIDs = String[];
export type AsyncTaskId = string;
export interface AwsManagedResources {
/**
* The choice of application destination that you specify.
*/
targetDestination: AwsManagedTargetDestinations;
}
export type AwsManagedTargetDestination = "None specified"|"AWS Elastic BeanStalk"|"AWS Fargate"|string;
export type AwsManagedTargetDestinations = AwsManagedTargetDestination[];
export type Boolean = boolean;
export interface BusinessGoals {
/**
* Business goal to reduce license costs.
*/
licenseCostReduction?: BusinessGoalsInteger;
/**
* Business goal to modernize infrastructure by moving to cloud native technologies.
*/
modernizeInfrastructureWithCloudNativeTechnologies?: BusinessGoalsInteger;
/**
* Business goal to reduce the operational overhead on the team by moving into managed services.
*/
reduceOperationalOverheadWithManagedServices?: BusinessGoalsInteger;
/**
* Business goal to achieve migration at a fast pace.
*/
speedOfMigration?: BusinessGoalsInteger;
}
export type BusinessGoalsInteger = number;
export interface Collector {
/**
* Indicates the health of a collector.
*/
collectorHealth?: CollectorHealth;
/**
* The ID of the collector.
*/
collectorId?: String;
/**
* Current version of the collector that is running in the environment that you specify.
*/
collectorVersion?: String;
/**
* Hostname of the server that is hosting the collector.
*/
hostName?: String;
/**
* IP address of the server that is hosting the collector.
*/
ipAddress?: String;
/**
* Time when the collector last pinged the service.
*/
lastActivityTimeStamp?: String;
/**
* Time when the collector registered with the service.
*/
registeredTimeStamp?: String;
}
export type CollectorHealth = "COLLECTOR_HEALTHY"|"COLLECTOR_UNHEALTHY"|string;
export type Collectors = Collector[];
export interface DataCollectionDetails {
/**
* The time the assessment completes.
*/
completionTime?: TimeStamp;
/**
* The number of failed servers in the assessment.
*/
failed?: Integer;
/**
* The number of servers with the assessment status IN_PROGESS.
*/
inProgress?: Integer;
/**
* The total number of servers in the assessment.
*/
servers?: Integer;
/**
* The start time of assessment.
*/
startTime?: TimeStamp;
/**
* The status of the assessment.
*/
status?: AssessmentStatus;
/**
* The number of successful servers in the assessment.
*/
success?: Integer;
}
export type DataSourceType = "ApplicationDiscoveryService"|"MPA"|string;
export interface DatabaseConfigDetail {
/**
* AWS Secrets Manager key that holds the credentials that you use to connect to a database.
*/
secretName?: String;
}
export type DatabaseManagementPreference = "AWS-managed"|"Self-manage"|"No preference"|string;
export interface DatabaseMigrationPreference {
/**
* Indicates whether you are interested in moving from one type of database to another. For example, from SQL Server to Amazon Aurora MySQL-Compatible Edition.
*/
heterogeneous?: Heterogeneous;
/**
* Indicates whether you are interested in moving to the same type of database into AWS. For example, from SQL Server in your environment to SQL Server on AWS.
*/
homogeneous?: Homogeneous;
/**
* Indicated that you do not prefer heterogeneous or homogeneous.
*/
noPreference?: NoDatabaseMigrationPreference;
}
export interface DatabasePreferences {
/**
* Specifies whether you're interested in self-managed databases or databases managed by AWS.
*/
databaseManagementPreference?: DatabaseManagementPreference;
/**
* Specifies your preferred migration path.
*/
databaseMigrationPreference?: DatabaseMigrationPreference;
}
export interface GetApplicationComponentDetailsRequest {
/**
* The ID of the application component. The ID is unique within an AWS account.
*/
applicationComponentId: ApplicationComponentId;
}
export interface GetApplicationComponentDetailsResponse {
/**
* Detailed information about an application component.
*/
applicationComponentDetail?: ApplicationComponentDetail;
/**
* The associated application group as defined in AWS Application Discovery Service.
*/
associatedApplications?: AssociatedApplications;
/**
* A list of the IDs of the servers on which the application component is running.
*/
associatedServerIds?: AssociatedServerIDs;
/**
* Set to true if the application component belongs to more than one application group.
*/
moreApplicationResource?: Boolean;
}
export interface GetApplicationComponentStrategiesRequest {
/**
* The ID of the application component. The ID is unique within an AWS account.
*/
applicationComponentId: ApplicationComponentId;
}
export interface GetApplicationComponentStrategiesResponse {
/**
* A list of application component strategy recommendations.
*/
applicationComponentStrategies?: ApplicationComponentStrategies;
}
export interface GetAssessmentRequest {
/**
* The assessmentid returned by StartAssessment.
*/
id: AsyncTaskId;
}
export interface GetAssessmentResponse {
/**
* Detailed information about the assessment.
*/
dataCollectionDetails?: DataCollectionDetails;
/**
* The ID for the specific assessment task.
*/
id?: AsyncTaskId;
}
export interface GetImportFileTaskRequest {
/**
* The ID of the import file task. This ID is returned in the response of StartImportFileTask.
*/
id: String;
}
export interface GetImportFileTaskResponse {
/**
* The time that the import task completed.
*/
completionTime?: TimeStamp;
/**
* The import file task id returned in the response of StartImportFileTask.
*/
id?: String;
/**
* The name of the import task given in StartImportFileTask.
*/
importName?: String;
/**
* The S3 bucket where import file is located.
*/
inputS3Bucket?: importS3Bucket;
/**
* The Amazon S3 key name of the import file.
*/
inputS3Key?: importS3Key;
/**
* The number of records that failed to be imported.
*/
numberOfRecordsFailed?: Integer;
/**
* The number of records successfully imported.
*/
numberOfRecordsSuccess?: Integer;
/**
* Start time of the import task.
*/
startTime?: TimeStamp;
/**
* Status of import file task.
*/
status?: ImportFileTaskStatus;
/**
* The S3 bucket name for status report of import task.
*/
statusReportS3Bucket?: importS3Bucket;
/**
* The Amazon S3 key name for status report of import task. The report contains details about whether each record imported successfully or why it did not.
*/
statusReportS3Key?: importS3Key;
}
export interface GetPortfolioPreferencesRequest {
}
export interface GetPortfolioPreferencesResponse {
/**
* The transformation preferences for non-database applications.
*/
applicationPreferences?: ApplicationPreferences;
/**
* The transformation preferences for database applications.
*/
databasePreferences?: DatabasePreferences;
/**
* The rank of business goals based on priority.
*/
prioritizeBusinessGoals?: PrioritizeBusinessGoals;
}
export interface GetPortfolioSummaryRequest {
}
export interface GetPortfolioSummaryResponse {
/**
* An assessment summary for the portfolio including the number of servers to rehost and the overall number of anti-patterns.
*/
assessmentSummary?: AssessmentSummary;
}
export interface GetRecommendationReportDetailsRequest {
/**
* The recommendation report generation task id returned by StartRecommendationReportGeneration.
*/
id: RecommendationTaskId;
}
export interface GetRecommendationReportDetailsResponse {
/**
* The ID of the recommendation report generation task. See the response of StartRecommendationReportGeneration.
*/
id?: RecommendationTaskId;
/**
* Detailed information about the recommendation report.
*/
recommendationReportDetails?: RecommendationReportDetails;
}
export interface GetServerDetailsRequest {
/**
* The maximum number of items to include in the response. The maximum value is 100.
*/
maxResults?: MaxResult;
/**
* The token from a previous call that you use to retrieve the next set of results. For example, if a previous call to this action returned 100 items, but you set maxResults to 10. You'll receive a set of 10 results along with a token. You then use the returned token to retrieve the next set of 10.
*/
nextToken?: NextToken;
/**
* The ID of the server.
*/
serverId: ServerId;
}
export interface GetServerDetailsResponse {
/**
* The associated application group the server belongs to, as defined in AWS Application Discovery Service.
*/
associatedApplications?: AssociatedApplications;
/**
* The token you use to retrieve the next set of results, or null if there are no more results.
*/
nextToken?: String;
/**
* Detailed information about the server.
*/
serverDetail?: ServerDetail;
}
export interface GetServerStrategiesRequest {
/**
* The ID of the server.
*/
serverId: ServerId;
}
export interface GetServerStrategiesResponse {
/**
* A list of strategy recommendations for the server.
*/
serverStrategies?: ServerStrategies;
}
export interface Group {
/**
* The key of the specific import group.
*/
name?: GroupName;
/**
* The value of the specific import group.
*/
value?: String;
}
export type GroupIds = Group[];
export type GroupName = "ExternalId"|string;
export interface Heterogeneous {
/**
* The target database engine for heterogeneous database migration preference.
*/
targetDatabaseEngine: HeterogeneousTargetDatabaseEngines;
}
export type HeterogeneousTargetDatabaseEngine = "None specified"|"Amazon Aurora"|"AWS PostgreSQL"|"MySQL"|"Microsoft SQL Server"|"Oracle Database"|"MariaDB"|"SAP"|"Db2 LUW"|"MongoDB"|string;
export type HeterogeneousTargetDatabaseEngines = HeterogeneousTargetDatabaseEngine[];
export interface Homogeneous {
/**
* The target database engine for homogeneous database migration preferences.
*/
targetDatabaseEngine?: HomogeneousTargetDatabaseEngines;
}
export type HomogeneousTargetDatabaseEngine = "None specified"|string;
export type HomogeneousTargetDatabaseEngines = HomogeneousTargetDatabaseEngine[];
export type IPAddress = string;
export interface ImportFileTaskInformation {
/**
* The time that the import task completes.
*/
completionTime?: TimeStamp;
/**
* The ID of the import file task.
*/
id?: String;
/**
* The name of the import task given in StartImportFileTask.
*/
importName?: String;
/**
* The S3 bucket where the import file is located.
*/
inputS3Bucket?: importS3Bucket;
/**
* The Amazon S3 key name of the import file.
*/
inputS3Key?: importS3Key;
/**
* The number of records that failed to be imported.
*/
numberOfRecordsFailed?: Integer;
/**
* The number of records successfully imported.
*/
numberOfRecordsSuccess?: Integer;
/**
* Start time of the import task.
*/
startTime?: TimeStamp;
/**
* Status of import file task.
*/
status?: ImportFileTaskStatus;
/**
* The S3 bucket name for status report of import task.
*/
statusReportS3Bucket?: importS3Bucket;
/**
* The Amazon S3 key name for status report of import task. The report contains details about whether each record imported successfully or why it did not.
*/
statusReportS3Key?: importS3Key;
}
export type ImportFileTaskStatus = "ImportInProgress"|"ImportFailed"|"ImportPartialSuccess"|"ImportSuccess"|"DeleteInProgress"|"DeleteFailed"|"DeletePartialSuccess"|"DeleteSuccess"|string;
export type InclusionStatus = "excludeFromAssessment"|"includeInAssessment"|string;
export type Integer = number;
export type InterfaceName = string;
export type ListAntipatternSeveritySummary = AntipatternSeveritySummary[];
export type ListApplicationComponentSummary = ApplicationComponentSummary[];
export interface ListApplicationComponentsRequest {
/**
* Criteria for filtering the list of application components.
*/
applicationComponentCriteria?: ApplicationComponentCriteria;
/**
* Specify the value based on the application component criteria type. For example, if applicationComponentCriteria is set to SERVER_ID and filterValue is set to server1, then ListApplicationComponents returns all the application components running on server1.
*/
filterValue?: ListApplicationComponentsRequestFilterValueString;
/**
* The group ID specified in to filter on.
*/
groupIdFilter?: GroupIds;
/**
* The maximum number of items to include in the response. The maximum value is 100.
*/
maxResults?: MaxResult;
/**
* The token from a previous call that you use to retrieve the next set of results. For example, if a previous call to this action returned 100 items, but you set maxResults to 10. You'll receive a set of 10 results along with a token. You then use the returned token to retrieve the next set of 10.
*/
nextToken?: NextToken;
/**
* Specifies whether to sort by ascending (ASC) or descending (DESC) order.
*/
sort?: SortOrder;
}
export type ListApplicationComponentsRequestFilterValueString = string;
export interface ListApplicationComponentsResponse {
/**
* The list of application components with detailed information about each component.
*/
applicationComponentInfos?: ApplicationComponentDetails;
/**
* The token you use to retrieve the next set of results, or null if there are no more results.
*/
nextToken?: NextToken;
}
export interface ListCollectorsRequest {
/**
* The maximum number of items to include in the response. The maximum value is 100.
*/
maxResults?: MaxResult;
/**
* The token from a previous call that you use to retrieve the next set of results. For example, if a previous call to this action returned 100 items, but you set maxResults to 10. You'll receive a set of 10 results along with a token. You then use the returned token to retrieve the next set of 10.
*/
nextToken?: NextToken;
}
export interface ListCollectorsResponse {
/**
* The list of all the installed collectors.
*/
Collectors?: Collectors;
/**
* The token you use to retrieve the next set of results, or null if there are no more results.
*/
nextToken?: NextToken;
}
export type ListImportFileTaskInformation = ImportFileTaskInformation[];
export interface ListImportFileTaskRequest {
/**
* The total number of items to return. The maximum value is 100.
*/
maxResults?: Integer;
/**
* The token from a previous call that you use to retrieve the next set of results. For example, if a previous call to this action returned 100 items, but you set maxResults to 10. You'll receive a set of 10 results along with a token. You then use the returned token to retrieve the next set of 10.
*/
nextToken?: String;
}
export interface ListImportFileTaskResponse {
/**
* The token you use to retrieve the next set of results, or null if there are no more results.
*/
nextToken?: String;
/**
* Lists information about the files you import.
*/
taskInfos?: ListImportFileTaskInformation;
}
export type ListServerSummary = ServerSummary[];
export interface ListServersRequest {
/**
* Specifies the filter value, which is based on the type of server criteria. For example, if serverCriteria is OS_NAME, and the filterValue is equal to WindowsServer, then ListServers returns all of the servers matching the OS name WindowsServer.
*/
filterValue?: String;
/**
* Specifies the group ID to filter on.
*/
groupIdFilter?: GroupIds;
/**
* The maximum number of items to include in the response. The maximum value is 100.
*/
maxResults?: MaxResult;
/**
* The token from a previous call that you use to retrieve the next set of results. For example, if a previous call to this action returned 100 items, but you set maxResults to 10. You'll receive a set of 10 results along with a token. You then use the returned token to retrieve the next set of 10.
*/
nextToken?: NextToken;
/**
* Criteria for filtering servers.
*/
serverCriteria?: ServerCriteria;
/**
* Specifies whether to sort by ascending (ASC) or descending (DESC) order.
*/
sort?: SortOrder;
}
export interface ListServersResponse {
/**
* The token you use to retrieve the next set of results, or null if there are no more results.
*/
nextToken?: NextToken;
/**
* The list of servers with detailed information about each server.
*/
serverInfos?: ServerDetails;
}
export type ListStrategySummary = StrategySummary[];
export type Location = string;
export type MacAddress = string;
export interface ManagementPreference {
/**
* Indicates interest in solutions that are managed by AWS.
*/
awsManagedResources?: AwsManagedResources;
/**
* No specific preference.
*/
noPreference?: NoManagementPreference;
/**
* Indicates interest in managing your own resources on AWS.
*/
selfManageResources?: SelfManageResources;
}
export type MaxResult = number;
export type NetMask = string;
export interface NetworkInfo {
/**
* Information about the name of the interface of the server for which the assessment was run.
*/
interfaceName: InterfaceName;
/**
* Information about the IP address of the server for which the assessment was run.
*/
ipAddress: IPAddress;
/**
* Information about the MAC address of the server for which the assessment was run.
*/
macAddress: MacAddress;
/**
* Information about the subnet mask of the server for which the assessment was run.
*/
netMask: NetMask;
}
export type NetworkInfoList = NetworkInfo[];
export type NextToken = string;
export interface NoDatabaseMigrationPreference {
/**
* The target database engine for database migration preference that you specify.
*/
targetDatabaseEngine: TargetDatabaseEngines;
}
export interface NoManagementPreference {
/**
* The choice of application destination that you specify.
*/
targetDestination: NoPreferenceTargetDestinations;
}
export type NoPreferenceTargetDestination = "None specified"|"AWS Elastic BeanStalk"|"AWS Fargate"|"Amazon Elastic Cloud Compute (EC2)"|"Amazon Elastic Container Service (ECS)"|"Amazon Elastic Kubernetes Service (EKS)"|string;
export type NoPreferenceTargetDestinations = NoPreferenceTargetDestination[];
export interface OSInfo {
/**
* Information about the type of operating system.
*/
type?: OSType;
/**
* Information about the version of operating system.
*/
version?: OSVersion;
}
export type OSType = "LINUX"|"WINDOWS"|string;
export type OSVersion = string;
export type OutputFormat = "Excel"|"Json"|string;
export interface PrioritizeBusinessGoals {
/**
* Rank of business goals based on priority.
*/
businessGoals?: BusinessGoals;
}
export interface PutPortfolioPreferencesRequest {
/**
* The transformation preferences for non-database applications.
*/
applicationPreferences?: ApplicationPreferences;
/**
* The transformation preferences for database applications.
*/
databasePreferences?: DatabasePreferences;
/**
* The rank of the business goals based on priority.
*/
prioritizeBusinessGoals?: PrioritizeBusinessGoals;
}
export interface PutPortfolioPreferencesResponse {
}
export interface RecommendationReportDetails {
/**
* The time that the recommendation report generation task completes.
*/
completionTime?: RecommendationReportTimeStamp;
/**
* The S3 bucket where the report file is located.
*/
s3Bucket?: String;
/**
* The Amazon S3 key name of the report file.
*/
s3Keys?: S3Keys;
/**
* The time that the recommendation report generation task starts.
*/
startTime?: RecommendationReportTimeStamp;
/**
* The status of the recommendation report generation task.
*/
status?: RecommendationReportStatus;
/**
* The status message for recommendation report generation.
*/
statusMessage?: RecommendationReportStatusMessage;
}
export type RecommendationReportStatus = "FAILED"|"IN_PROGRESS"|"SUCCESS"|string;
export type RecommendationReportStatusMessage = string;
export type RecommendationReportTimeStamp = Date;
export interface RecommendationSet {
/**
* The recommended strategy.
*/
strategy?: Strategy;
/**
* The recommended target destination.
*/
targetDestination?: TargetDestination;
/**
* The target destination for the recommendation set.
*/
transformationTool?: TransformationTool;
}
export type RecommendationTaskId = string;
export type ResourceId = string;
export type ResourceName = string;
export type ResourceSubType = "Database"|"Process"|"DatabaseProcess"|string;
export type RunTimeAssessmentStatus = "dataCollectionTaskToBeScheduled"|"dataCollectionTaskScheduled"|"dataCollectionTaskStarted"|"dataCollectionTaskStopped"|"dataCollectionTaskSuccess"|"dataCollectionTaskFailed"|"dataCollectionTaskPartialSuccess"|string;
export type S3Bucket = string;
export type S3Key = string;
export type S3Keys = String[];
export interface S3Object {
/**
* The S3 bucket name.
*/
s3Bucket?: S3Bucket;
/**
* The Amazon S3 key name.
*/
s3key?: S3Key;
}
export type SecretsManagerKey = string;
export interface SelfManageResources {
/**
* Self-managed resources target destination.
*/
targetDestination: SelfManageTargetDestinations;
}
export type SelfManageTargetDestination = "None specified"|"Amazon Elastic Cloud Compute (EC2)"|"Amazon Elastic Container Service (ECS)"|"Amazon Elastic Kubernetes Service (EKS)"|string;
export type SelfManageTargetDestinations = SelfManageTargetDestination[];
export type ServerCriteria = "NOT_DEFINED"|"OS_NAME"|"STRATEGY"|"DESTINATION"|"SERVER_ID"|string;
export interface ServerDetail {
/**
* The S3 bucket name and Amazon S3 key name for anti-pattern report.
*/
antipatternReportS3Object?: S3Object;
/**
* The status of the anti-pattern report generation.
*/
antipatternReportStatus?: AntipatternReportStatus;
/**
* A message about the status of the anti-pattern report generation.
*/
antipatternReportStatusMessage?: StatusMessage;
/**
* A list of strategy summaries.
*/
applicationComponentStrategySummary?: ListStrategySummary;
/**
* The status of assessment for the server.
*/
dataCollectionStatus?: RunTimeAssessmentStatus;
/**
* The server ID.
*/
id?: ResourceId;
/**
* The timestamp of when the server was assessed.
*/
lastAnalyzedTimestamp?: TimeStamp;
/**
* A list of anti-pattern severity summaries.
*/
listAntipatternSeveritySummary?: ListAntipatternSeveritySummary;
/**
* The name of the server.
*/
name?: ResourceName;
/**
* A set of recommendations.
*/
recommendationSet?: RecommendationSet;
/**
* The type of server.
*/
serverType?: String;
/**
* A message about the status of data collection, which contains detailed descriptions of any error messages.
*/
statusMessage?: StatusMessage;
/**
* System information about the server.
*/
systemInfo?: SystemInfo;
}
export type ServerDetails = ServerDetail[];
export type ServerId = string;
export type ServerOsType = "WindowsServer"|"AmazonLinux"|"EndOfSupportWindowsServer"|"Redhat"|"Other"|string;
export type ServerStrategies = ServerStrategy[];
export interface ServerStrategy {
/**
* Set to true if the recommendation is set as preferred.
*/
isPreferred?: Boolean;
/**
* The number of application components with this strategy recommendation running on the server.
*/
numberOfApplicationComponents?: Integer;
/**
* Strategy recommendation for the server.
*/
recommendation?: RecommendationSet;
/**
* The recommendation status of the strategy for the server.
*/
status?: StrategyRecommendation;
}
export interface ServerSummary {
/**
* Type of operating system for the servers.
*/
ServerOsType?: ServerOsType;
/**
* Number of servers.
*/
count?: Integer;
}
export type Severity = "HIGH"|"MEDIUM"|"LOW"|string;
export type SortOrder = "ASC"|"DESC"|string;
export interface SourceCode {
/**
* The repository name for the source code.
*/
location?: Location;
/**
* The branch of the source code.
*/
sourceVersion?: SourceVersion;
/**
* The type of repository to use for the source code.
*/
versionControl?: VersionControl;
}
export type SourceCodeList = SourceCode[];
export type SourceCodeRepositories = SourceCodeRepository[];
export interface SourceCodeRepository {
/**
* The branch of the source code.
*/
branch?: String;
/**
* The repository name for the source code.
*/
repository?: String;
/**
* The type of repository to use for the source code.
*/
versionControlType?: String;
}
export type SourceVersion = string;
export type SrcCodeOrDbAnalysisStatus = "ANALYSIS_TO_BE_SCHEDULED"|"ANALYSIS_STARTED"|"ANALYSIS_SUCCESS"|"ANALYSIS_FAILED"|string;
export interface StartAssessmentRequest {
/**
* The S3 bucket used by the collectors to send analysis data to the service. The bucket name must begin with migrationhub-strategy-.
*/
s3bucketForAnalysisData?: StartAssessmentRequestS3bucketForAnalysisDataString;
/**
* The S3 bucket where all the reports generated by the service are stored. The bucket name must begin with migrationhub-strategy-.
*/
s3bucketForReportData?: StartAssessmentRequestS3bucketForReportDataString;
}
export type StartAssessmentRequestS3bucketForAnalysisDataString = string;
export type StartAssessmentRequestS3bucketForReportDataString = string;
export interface StartAssessmentResponse {
/**
* The ID of the assessment.
*/
assessmentId?: AsyncTaskId;
}
export interface StartImportFileTaskRequest {
/**
* The S3 bucket where the import file is located. The bucket name is required to begin with migrationhub-strategy-.
*/
S3Bucket: importS3Bucket;
/**
* Specifies the source that the servers are coming from. By default, Strategy Recommendations assumes that the servers specified in the import file are available in AWS Application Discovery Service.
*/
dataSourceType?: DataSourceType;
/**
* Groups the resources in the import file together with a unique name. This ID can be as filter in ListApplicationComponents and ListServers.
*/
groupId?: GroupIds;
/**
* A descriptive name for the request.
*/
name: StartImportFileTaskRequestNameString;
/**
* The S3 bucket where Strategy Recommendations uploads import results. The bucket name is required to begin with migrationhub-strategy-.
*/
s3bucketForReportData?: StartImportFileTaskRequestS3bucketForReportDataString;
/**
* The Amazon S3 key name of the import file.
*/
s3key: String;
}
export type StartImportFileTaskRequestNameString = string;
export type StartImportFileTaskRequestS3bucketForReportDataString = string;
export interface StartImportFileTaskResponse {
/**
* The ID for a specific import task. The ID is unique within an AWS account.
*/
id?: String;
}
export interface StartRecommendationReportGenerationRequest {
/**
* Groups the resources in the recommendation report with a unique name.
*/
groupIdFilter?: GroupIds;
/**
* The output format for the recommendation report file. The default format is Microsoft Excel.
*/
outputFormat?: OutputFormat;
}
export interface StartRecommendationReportGenerationResponse {
/**
* The ID of the recommendation report generation task.
*/
id?: RecommendationTaskId;
}
export type StatusMessage = string;
export interface StopAssessmentRequest {
/**
* The assessmentId returned by StartAssessment.
*/
assessmentId: AsyncTaskId;
}
export interface StopAssessmentResponse {
}
export type Strategy = "Rehost"|"Retirement"|"Refactor"|"Replatform"|"Retain"|"Relocate"|"Repurchase"|string;
export interface StrategyOption {
/**
* Indicates if a specific strategy is preferred for the application component.
*/
isPreferred?: Boolean;
/**
* Type of transformation. For example, Rehost, Replatform, and so on.
*/
strategy?: Strategy;
/**
* Destination information about where the application component can migrate to. For example, EC2, ECS, and so on.
*/
targetDestination?: TargetDestination;
/**
* The name of the tool that can be used to transform an application component using this strategy.
*/
toolName?: TransformationToolName;
}
export type StrategyRecommendation = "recommended"|"viableOption"|"notRecommended"|string;
export interface StrategySummary {
/**
* The count of recommendations per strategy.
*/
count?: Integer;
/**
* The name of recommended strategy.
*/
strategy?: Strategy;
}
export type String = string;
export interface SystemInfo {
/**
* CPU architecture type for the server.
*/
cpuArchitecture?: String;
/**
* File system type for the server.
*/
fileSystemType?: String;
/**
* Networking information related to a server.
*/
networkInfoList?: NetworkInfoList;
/**
* Operating system corresponding to a server.
*/
osInfo?: OSInfo;
}
export type TargetDatabaseEngine = "None specified"|"Amazon Aurora"|"AWS PostgreSQL"|"MySQL"|"Microsoft SQL Server"|"Oracle Database"|"MariaDB"|"SAP"|"Db2 LUW"|"MongoDB"|string;
export type TargetDatabaseEngines = TargetDatabaseEngine[];
export type TargetDestination = "None specified"|"AWS Elastic BeanStalk"|"AWS Fargate"|"Amazon Elastic Cloud Compute (EC2)"|"Amazon Elastic Container Service (ECS)"|"Amazon Elastic Kubernetes Service (EKS)"|"Aurora MySQL"|"Aurora PostgreSQL"|"Amazon Relational Database Service on MySQL"|"Amazon Relational Database Service on PostgreSQL"|"Amazon DocumentDB"|"Amazon DynamoDB"|"Amazon Relational Database Service"|string;
export type TimeStamp = Date;
export type TranformationToolDescription = string;
export type TranformationToolInstallationLink = string;
export interface TransformationTool {
/**
* Description of the tool.
*/
description?: TranformationToolDescription;
/**
* Name of the tool.
*/
name?: TransformationToolName;
/**
* URL for installing the tool.
*/
tranformationToolInstallationLink?: TranformationToolInstallationLink;
}
export type TransformationToolName = "App2Container"|"Porting Assistant For .NET"|"End of Support Migration"|"Windows Web Application Migration Assistant"|"Application Migration Service"|"Strategy Recommendation Support"|"In Place Operating System Upgrade"|"Schema Conversion Tool"|"Database Migration Service"|"Native SQL Server Backup/Restore"|string;
export interface UpdateApplicationComponentConfigRequest {
/**
* The ID of the application component. The ID is unique within an AWS account.
*/
applicationComponentId: ApplicationComponentId;
/**
* Indicates whether the application component has been included for server recommendation or not.
*/
inclusionStatus?: InclusionStatus;
/**
* Database credentials.
*/
secretsManagerKey?: SecretsManagerKey;
/**
* The list of source code configurations to update for the application component.
*/
sourceCodeList?: SourceCodeList;
/**
* The preferred strategy options for the application component. Use values from the GetApplicationComponentStrategies response.
*/
strategyOption?: StrategyOption;
}
export interface UpdateApplicationComponentConfigResponse {
}
export interface UpdateServerConfigRequest {
/**
* The ID of the server.
*/
serverId: ServerId;
/**
* The preferred strategy options for the application component. See the response from GetServerStrategies.
*/
strategyOption?: StrategyOption;
}
export interface UpdateServerConfigResponse {
}
export type VersionControl = "GITHUB"|"GITHUB_ENTERPRISE"|string;
export type importS3Bucket = string;
export type importS3Key = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2020-02-19"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the MigrationHubStrategy client.
*/
export import Types = MigrationHubStrategy;
}
export = MigrationHubStrategy; | the_stack |
import {HfDriver} from "../../src/drivers/hfdriver";
import {TrustIdHf} from "../../src/core/trustidHF";
import {DID} from "../../src/core/did";
import {Wallet} from "../../src/wallet";
import { AccessPolicy, PolicyType} from "../../src/core/trustid";
/* global describe, it, before, after */
const {expect} = require("chai");
const sinon = require("sinon");
describe("TrustHF - Test", async() => {
let config = {
stateStore: "/tmp/statestore",
caURL: "https://ca.org1.telefonica.com:7054",
caName: "ca.org1.telefonica.com",
caAdmin: "adminCA",
caPassword: "adminpw",
tlsOptions: {
trustedRoots:
"-----BEGIN CERTIFICATE-----MIICTjCCAfSgAwIBAgIRAPz6Z66RGDs2BDghYGuShw4wCgYIKoZIzj0EAwIwcTELMAkGA1UEBhMCRVMxDzANBgNVBAgTBk1hZHJpZDEPMA0GA1UEBxMGTWFkcmlkMRwwGgYDVQQKExNvcmcxLnRlbGVmb25pY2EuY29tMSIwIAYDVQQDExl0bHNjYS5vcmcxLnRlbGVmb25pY2EuY29tMB4XDTIwMDUxMjEzMDIwMFoXDTMwMDUxMDEzMDIwMFowcTELMAkGA1UEBhMCRVMxDzANBgNVBAgTBk1hZHJpZDEPMA0GA1UEBxMGTWFkcmlkMRwwGgYDVQQKExNvcmcxLnRlbGVmb25pY2EuY29tMSIwIAYDVQQDExl0bHNjYS5vcmcxLnRlbGVmb25pY2EuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaJraPeAMD+qMba9gNfzwhhfSQNDStqhkvGdPKfxjl+5YoZ+AZkf5qXUPCbSVFh2rlIagZQzcxLnxRmwguEDJjaNtMGswDgYDVR0PAQH/BAQDAgGmMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdDgQiBCDxTrECkDkA2zbsZ7US807jJKKmZ6E90QYkjC7szbQrQDAKBggqhkjOPQQDAgNIADBFAiEAmFFB79r8Jqu4QEgNRQEWEWrY9g70pEUIL4cwq7Zj//UCIDoOuRhihvbFsLTSNbK31VzmL5lXvZGwzvS60n9xk33B-----END CERTIFICATE-----",
verify: false,
},
mspId: "org1MSP",
walletID: "admin",
asLocalhost: true,
ccp: "",
chaincodeName: "identitycc",
fcn: "proxy",
channel: "telefonicachannel",
};
const wal = Wallet.Instance;
let identity = await wal.generateDID("RSA", "default", "secret");
await identity.unlockAccount("secret");
before(() => {});
describe("Configure Driver ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "connect").resolves();
driverStub.onSecondCall().rejects(new Error("Error connecting"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Configure Success", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.configureDriver();
sinon.assert.calledOnce(driverStub);
} catch (err) {
console.log(err);
}
});
it("Configure Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.configureDriver();
} catch (err) {
expect(err.message).to.equal("Error connecting");
sinon.assert.calledTwice(driverStub);
}
});
});
describe("Disconnect Driver ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "disconnect").resolves();
driverStub.onSecondCall().rejects(new Error("Error disconnect"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Configure Success", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.disconnectDriver();
sinon.assert.calledOnce(driverStub);
} catch (err) {
console.log(err);
}
});
it("Configure Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.disconnectDriver();
} catch (err) {
expect(err.message).to.equal("Error disconnect");
sinon.assert.calledTwice(driverStub);
}
});
});
describe("Create self identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Create self Identity", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.createSelfIdentity(identity);
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Crete self Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.createSelfIdentity(identity);
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Create identity ", async () => {
const didController = await wal.generateDID('RSA', 'default', 'pass')
let driverStubw: any;
before((done) => {
driverStubw = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStubw.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
//driverStubw.restore();
done();
});
it("Create Identity", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.createIdentity(identity, didController);
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Create Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.createIdentity(identity, didController);
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Verify identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Verify IdentitY", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.verifyIdentity(identity, "id");
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Verify Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.verifyIdentity(identity, "id");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Revoke identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Revoke IdentitY Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.revokeIdentity(identity, "id");
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Revoke Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.revokeIdentity(identity, "id");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Get identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("This is identity");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Get IdentitY Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.getIdentity(identity, "id");
expect(result).to.equal("This is identity");
} catch (err) {
console.log(err);
}
});
it("Get identity Fail", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.getIdentity(identity, "id");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Import Signed Identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Import Signed Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.importSignedIdentity("did", "payload");
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Import signed Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.importSignedIdentity("id", "payload");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Import Identity ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Import Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.importIdentity(identity);
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Import Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.importIdentity(identity);
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Create Service ", () => {
let driverStub: any;
let access: AccessPolicy = {policy: PolicyType.PublicPolicy, threshold: 0, registry: {}};
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Create Service Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.createService(identity, "id", "name", access, "channel");
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Create Service Fail", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.createService(identity, "id", "name", access, "channel");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Update Service ", () => {
let driverStub2: any;
before((done) => {
driverStub2 = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("OK");
driverStub2.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub2.restore();
done();
});
let access: AccessPolicy = {policy: PolicyType.PublicPolicy, threshold: 0, registry: {}};
it("Update Service Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.updateServiceAccess(identity, "id", access);
expect(result).to.equal("OK");
} catch (err) {
console.log(err);
}
});
it("Update Service Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.updateServiceAccess(identity, "id", access);
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Get Service ", () => {
let driverStub: any;
before((done) => {
const service = {service: "service"}
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves(JSON.stringify(service));
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
let access: AccessPolicy = {policy: PolicyType.PublicPolicy, threshold: 0, registry: {}};
it("Get Service Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.getService(identity, "id");
expect(result.service).to.equal("service");
} catch (err) {
console.log(err);
}
});
it("Get Service Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.getService(identity, "id");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Invoke Service ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Invoke Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.invoke(identity, "id", ["a"], "channel1");
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Invoke Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.invoke(identity, "id", ["a"], "channel1");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Query Service ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "getContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Query Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.query(identity, "id", ["a"], "channel1");
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Query Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.query(identity, "id", ["a"], "channel1");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Invoke Signed Service ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "callContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Invoke Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.invokeSigned("did", "payload");
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Invoke Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.invokeSigned("id", "payload");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
describe("Query Signed Service ", () => {
let driverStub: any;
before((done) => {
driverStub = sinon.stub(HfDriver.prototype, "getContractTransaction").resolves("result");
driverStub.onSecondCall().rejects(new Error("Error calling contract"));
done();
});
after((done) => {
driverStub.restore();
done();
});
it("Query Success", async () => {
try {
const trustID = new TrustIdHf(config);
const result = await trustID.querySigned("did", "payload");
expect(result).to.equal("result");
} catch (err) {
console.log(err);
}
});
it("Query Fail", async () => {
try {
const trustID = new TrustIdHf(config);
await trustID.querySigned("id", "payload");
} catch (err) {
expect(err.message).to.equal("Error calling contract");
}
});
});
}); | the_stack |
import { KeyCodes, MouseButtons } from './input_lite';
export enum OpCode {
CONTINUATION = 0,
TEXT = 1,
BINARY = 2,
CLOSE = 8,
PING = 9,
PONG = 10,
INVALID = 255
}
;
export enum ImageEncoding {
COLOR,
GRAYSCALE
}
;
export enum ClipboardSharing {
NOT_SHARED,
SHARED
}
;
export class WSMessage {
data: DataView;
code: OpCode;
};
export class Point {
X: number;
Y: number;
};
export class Rect {
Origin: Point;
Height: number;
Width: number;
};
export class Monitor {
Id: number;
Index: number;
Height: number;
Width: number;
// Offsets are the number of pixels that a monitor can be from the origin. For example, users can shuffle their
// monitors around so this affects their offset.
OffsetX: number;
OffsetY: number;
Name: string;
Scaling: number;
};
export class ClientSettings {
ShareClip = ClipboardSharing.NOT_SHARED;
ImageCompressionSetting = 70;
EncodeImagesAsGrayScale = ImageEncoding.COLOR;
MonitorsToWatch = new Array<Monitor>();
};
export enum PACKET_TYPES {
INVALID,
HTTP_MSG,
ONMONITORSCHANGED,
ONFRAMECHANGED,
ONNEWFRAME,
ONMOUSEIMAGECHANGED,
ONMOUSEPOSITIONCHANGED,
ONKEYUP,
ONKEYDOWN,
ONMOUSEUP,
ONMOUSEDOWN,
ONMOUSESCROLL,
ONCLIPBOARDTEXTCHANGED,
ONCLIENTSETTINGSCHANGED,
// use LAST_PACKET_TYPE as the starting point of your custom packet types. Everything before this is used internally by the library
LAST_PACKET_TYPE
}
;
export class IClientDriver {
protected ShareClip = false;
protected Monitors = new Array<Monitor>();
protected WebSocket_: WebSocket;
protected onConnection_: (ws: WebSocket, ev: Event) => void;
protected onMessage_: (ws: WebSocket, message: WSMessage) => void;
protected onDisconnection_: (ws: WebSocket, code: number, message: string) => void;
protected onMonitorsChanged_: (monitors: Monitor[]) => void;
protected onFrameChanged_: (image: HTMLImageElement, monitor: Monitor, rect: Rect) => void;
protected onNewFrame_: (image: HTMLImageElement, monitor: Monitor, rect: Rect) => void;
protected onMouseImageChanged_: (image: ImageData) => void;
protected onMousePositionChanged_: (point: Point) => void;
protected onClipboardChanged_: (clipstring: string) => void;
protected onBytesPerSecondChanged: (bytespersecond: number) => void;
protected ConnectedToSelf_ = false;
protected BytesPerSecond = 0;
protected SecondTimer = 0;
setShareClipboard(share: boolean): void { this.ShareClip = share; }
getShareClipboard(): boolean { return this.ShareClip; }
SendKeyUp(key: KeyCodes): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 1);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONKEYUP, true);
dataview.setUint8(4, key);
this.WebSocket_.send(data.buffer);
}
SendKeyDown(key: KeyCodes): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 1);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONKEYDOWN, true);
dataview.setUint8(4, key);
this.WebSocket_.send(data.buffer);
}
SendMouseUp(button: MouseButtons): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 1);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONMOUSEUP, true);
dataview.setUint8(4, button);
this.WebSocket_.send(data.buffer);
}
SendMouseDown(button: MouseButtons): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 1);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONMOUSEDOWN, true);
dataview.setUint8(4, button);
this.WebSocket_.send(data.buffer);
}
SendMouseScroll(offset: number): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 4);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONMOUSESCROLL, true);
dataview.setUint32(4, offset, true);
this.WebSocket_.send(data.buffer);
}
SendMousePosition(pos: Point): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + 8);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONMOUSEPOSITIONCHANGED, true);
dataview.setInt32(4, pos.X, true);
dataview.setInt32(8, pos.Y, true);
this.WebSocket_.send(data.buffer);
}
SendClipboardChanged(text: string): void
{
if (this.ConnectedToSelf_)
return;
var data = new Uint8Array(4 + text.length);
var dataview = new DataView(data.buffer);
dataview.setUint32(0, PACKET_TYPES.ONMOUSESCROLL, true);
for (var i = 0; i < text.length; i++) {
data[4 + i] = text.charCodeAt(0);
}
this.WebSocket_.send(data.buffer);
}
SendClientSettingsChanged(clientsettings: ClientSettings): void
{
if (!clientsettings || !clientsettings.MonitorsToWatch || clientsettings.MonitorsToWatch.length <= 0)
return;
var beginsize = 1 + 4 + 1;
var data = new Uint8Array(4 + beginsize + (4 * clientsettings.MonitorsToWatch.length));
var dataview = new DataView(data.buffer);
var offset = 0;
dataview.setUint32(offset, PACKET_TYPES.ONCLIENTSETTINGSCHANGED, true);
offset += 4;
dataview.setUint8(offset, clientsettings.ShareClip);
offset += 1;
dataview.setInt32(offset, clientsettings.ImageCompressionSetting, true);
offset += 4;
dataview.setUint8(offset, clientsettings.EncodeImagesAsGrayScale);
offset += 1;
for (var i = 0; i < clientsettings.MonitorsToWatch.length; i++) {
dataview.setInt32(offset, clientsettings.MonitorsToWatch[i].Id, true);
offset += 4;
}
this.WebSocket_.send(data.buffer);
}
};
export class IClientDriverConfiguration extends IClientDriver {
onBytesPerSecond(callback: (bytespersecond: number) => void): IClientDriverConfiguration
{
this.onBytesPerSecondChanged = callback;
return this;
}
onConnection(callback: (ws: WebSocket, ev: Event) => void): IClientDriverConfiguration
{
this.onConnection_ = callback;
return this;
}
onMessage(callback: (ws: WebSocket, message: WSMessage) => void): IClientDriverConfiguration
{
this.onMessage_ = callback;
return this;
}
onDisconnection(callback: (ws: WebSocket, code: number, message: string) => void): IClientDriverConfiguration
{
this.onDisconnection_ = callback;
return this;
}
onMonitorsChanged(callback: (monitors: Monitor[]) => void): IClientDriverConfiguration
{
this.onMonitorsChanged_ = callback;
return this;
}
onFrameChanged(callback: (image: HTMLImageElement, monitor: Monitor, rect: Rect) => void): IClientDriverConfiguration
{
this.onFrameChanged_ = callback;
return this;
}
onNewFrame(callback: (image: HTMLImageElement, monitor: Monitor, rect: Rect) => void): IClientDriverConfiguration
{
this.onNewFrame_ = callback;
return this;
}
onMouseImageChanged(callback: (image: ImageData) => void): IClientDriverConfiguration
{
this.onMouseImageChanged_ = callback;
return this;
}
onMousePositionChanged(callback: (point: Point) => void): IClientDriverConfiguration
{
this.onMousePositionChanged_ = callback;
return this;
}
onClipboardChanged(callback: (clipstring: string) => void): IClientDriverConfiguration
{
this.onClipboardChanged_ = callback;
return this;
}
private _arrayBufferToBase64(buffer: Uint8Array): string
{
var binary = '';
for (var i = 0; i < buffer.byteLength; i++) {
binary += String.fromCharCode(buffer[i]);
}
return window.btoa(binary);
}
private MonitorsChanged(ws: WebSocket, dataview: DataView)
{
if (!this.onMonitorsChanged_)
return;
let sizeofmonitor = 7 * 4 + 128;
let num = dataview.byteLength / sizeofmonitor;
if (dataview.byteLength == num * sizeofmonitor && num < 8) {
this.Monitors = new Array<Monitor>();
let currentoffset = 0;
for (var i = 0; i < num; i++) {
currentoffset = i * sizeofmonitor;
var name = '';
for (var j = 0, strLen = 128; j < strLen; j++) {
var char = String.fromCharCode(dataview.getUint8((24 + j) + currentoffset));
if (char == '\0') {
break;
}
name += char;
}
this.Monitors.push({
Id : dataview.getInt32(0 + currentoffset, true),
Index : dataview.getInt32(4 + currentoffset, true),
Height : dataview.getInt32(8 + currentoffset, true),
Width : dataview.getInt32(12 + currentoffset, true),
OffsetX : dataview.getInt32(16 + currentoffset, true),
OffsetY : dataview.getInt32(20 + currentoffset, true),
Name : name,
Scaling : dataview.getFloat32(24 + 128 + currentoffset, true)
});
}
return this.onMonitorsChanged_(this.Monitors);
}
else if (dataview.byteLength == 0) {
// it is possible to have no monitors.. shouldnt disconnect in that case
return this.onMonitorsChanged_(this.Monitors);
}
if (this.onDisconnection_) {
this.onDisconnection_(ws, 1000, "Invalid Monitor Count");
}
ws.close(1000, "Invalid Monitor Count");
}
private Frame(ws: WebSocket, dataview: DataView, callback: (image: HTMLImageElement, monitor: Monitor, rect: Rect) => void)
{
if (dataview.byteLength >= 4 * 4 + 4) {
var monitorid = dataview.getInt32(0, true);
var rect = {
Origin : {X : dataview.getInt32(4, true), Y : dataview.getInt32(8, true)},
Height : dataview.getInt32(12, true),
Width : dataview.getInt32(16, true)
};
var foundmonitor = this.Monitors.filter(a => a.Id == monitorid);
if (foundmonitor.length > 0) {
var i = new Image();
i.src = "data:image/jpeg;base64," + this._arrayBufferToBase64(new Uint8Array(dataview.buffer, 20 + dataview.byteOffset));
i.onload = (ev: Event) => { callback(i, foundmonitor[0], rect); };
i.onerror = (ev: Event) => { console.log(ev); };
i.oninvalid = (ev: Event) => { console.log(ev); };
}
return;
}
if (this.onDisconnection_) {
this.onDisconnection_(ws, 1000, "Received invalid lenght on onMouseImageChanged");
}
ws.close(1000, "Received invalid lenght on onMouseImageChanged");
}
private MouseImageChanged(ws: WebSocket, dataview: DataView)
{
if (!this.onMouseImageChanged_)
return;
if (dataview.byteLength >= 4 * 4) {
var rect = {
Origin : {X : dataview.getInt32(0, true), Y : dataview.getInt32(4, true)},
Height : dataview.getInt32(8, true),
Width : dataview.getInt32(12, true)
};
var canvas = document.createElement('canvas');
var imageData = canvas.getContext('2d').createImageData(rect.Width, rect.Height);
for (var i = 16; i < dataview.byteLength; i++) {
imageData.data[i] = dataview[i];
}
if (dataview.byteLength >= 4 * 4 + (rect.Width * rect.Height * 4)) {
return this.onMouseImageChanged_(imageData);
}
}
if (this.onDisconnection_) {
this.onDisconnection_(ws, 1000, "Received invalid lenght on onMouseImageChanged");
}
ws.close(1000, "Received invalid lenght on onMouseImageChanged");
}
private MousePositionChanged(ws: WebSocket, dataview: DataView)
{
if (!this.onMousePositionChanged_)
return;
if (dataview.byteLength == 8) {
var p = {X : dataview.getInt32(0, true), Y : dataview.getInt32(4, true)};
return this.onMousePositionChanged_(p);
}
if (this.onDisconnection_) {
this.onDisconnection_(ws, 1000, "Received invalid lenght on onMousePositionChanged");
}
ws.close(1000, "Received invalid lenght on onMousePositionChanged");
}
private ClipboardTextChanged(dataview: DataView)
{
if (!this.ShareClip || !this.onClipboardChanged_)
return;
if (dataview.byteLength < 1024 * 100) { // 100K max
var text = '';
for (var i = 0, strLen = 128; i < strLen; i++) {
text += String.fromCharCode.apply(dataview.getUint8(20 + i));
}
this.onClipboardChanged_(text);
}
}
Build(ws: WebSocket): IClientDriver
{
this.WebSocket_ = ws;
var self = this;
ws.binaryType = 'arraybuffer';
this.ConnectedToSelf_ = ws.url.toLowerCase().indexOf('127.0.0.1') != -1 || ws.url.toLowerCase().indexOf('localhost') != -1 ||
ws.url.toLowerCase().indexOf('::1') != -1;
this.SecondTimer = performance.now();
ws.onopen = (ev: Event) => {
console.log('onopen');
if (self.onConnection_) {
self.onConnection_(ws, ev);
}
};
ws.onclose = (ev: CloseEvent) => {
console.log('onclose');
if (self.onDisconnection_) {
self.onDisconnection_(ws, ev.code, ev.reason);
}
};
ws.onmessage = (ev: MessageEvent) => {
var t0 = performance.now();
if (t0 - this.SecondTimer > 1000) {
this.onBytesPerSecondChanged(this.BytesPerSecond);
this.SecondTimer = t0;
this.BytesPerSecond = 0;
}
var data = new DataView(ev.data);
this.BytesPerSecond += data.byteLength;
var packettype = <PACKET_TYPES>data.getInt32(0, true);
var self = this;
// console.log('received: ' + packettype);
switch (packettype) {
case PACKET_TYPES.ONMONITORSCHANGED:
this.MonitorsChanged(ws, new DataView(ev.data, 4));
break;
case PACKET_TYPES.ONFRAMECHANGED:
if (this.onFrameChanged_) {
this.Frame(ws, new DataView(ev.data, 4), this.onFrameChanged_);
}
break;
case PACKET_TYPES.ONNEWFRAME:
if (this.onNewFrame_) {
this.Frame(ws, new DataView(ev.data, 4), this.onNewFrame_);
}
break;
case PACKET_TYPES.ONMOUSEIMAGECHANGED:
this.MouseImageChanged(ws, new DataView(ev.data, 4));
break;
case PACKET_TYPES.ONMOUSEPOSITIONCHANGED:
this.MousePositionChanged(ws, new DataView(ev.data, 4));
break;
case PACKET_TYPES.ONCLIPBOARDTEXTCHANGED:
this.ClipboardTextChanged(new DataView(ev.data, 4));
break;
default:
if (this.onMessage_) {
var r = new WSMessage();
r.data = new DataView(ev.data, 4);
if (ev.data instanceof ArrayBuffer) {
r.code = OpCode.BINARY;
}
else if (typeof ev.data === "string") {
r.code = OpCode.TEXT;
}
this.onMessage_(ws, r); // pass up the chain
}
break;
}
var t1 = performance.now();
// console.log("took " + (t1 - t0) + " milliseconds to process the receive loop");
};
return this;
}
};
export function CreateClientDriverConfiguration(): IClientDriverConfiguration { return new IClientDriverConfiguration(); } | the_stack |
import * as assert from "assert";
import * as Azure from "azure-storage";
import { configLogger } from "../../../src/common/Logger";
import StorageError from "../../../src/table/errors/StorageError";
import TableServer from "../../../src/table/TableServer";
import {
getUniqueName,
overrideRequest,
restoreBuildRequestOptions
} from "../../testutils";
import {
createBasicEntityForTest,
createConnectionStringForTest,
createTableServerForTest
} from "./table.entity.test.utils";
import { TestEntity } from "./TestEntity";
// Set true to enable debug log
configLogger(false);
// For convenience, we have a switch to control the use
// of a local Azurite instance, otherwise we need an
// ENV VAR called AZURE_TABLE_STORAGE added to mocha
// script or launch.json containing
// Azure Storage Connection String (using SAS or Key).
const testLocalAzuriteInstance = true;
describe("table Entity APIs test", () => {
let server: TableServer;
const tableService = Azure.createTableService(
createConnectionStringForTest(testLocalAzuriteInstance)
);
// ToDo: added due to problem with batch responses not finishing properly - Need to investigate batch response
tableService.enableGlobalHttpAgent = true;
let tableName: string = getUniqueName("table");
const requestOverride = { headers: {} };
before(async () => {
overrideRequest(requestOverride, tableService);
server = createTableServerForTest();
tableName = getUniqueName("table");
await server.start();
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const created = new Promise((resolve, reject) => {
tableService.createTable(tableName, (error, result, response) => {
if (error) {
reject();
} else {
resolve(response);
}
});
});
// we need to await here as we now also test against the service
// which is not as fast as our in memory DBs
await created.then().catch((createError) => {
throw new Error("failed to create table");
});
});
after(async () => {
restoreBuildRequestOptions(tableService);
tableService.removeAllListeners();
await server.close();
});
// Simple test in here until we have the full set checked in, as we need
// a starting point for delete and query entity APIs
it("Should insert new Entity, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-entity
const entity = createBasicEntityForTest();
tableService.insertEntity<TestEntity>(
tableName,
entity,
(error, result, response) => {
assert.ifError(error);
assert.strictEqual(response.statusCode, 201);
if (result !== undefined) {
const matches = result[".metadata"].etag.match(
"W/\"datetime'\\d{4}-\\d{2}-\\d{2}T\\d{2}%3A\\d{2}%3A\\d{2}.\\d{7}Z'\""
);
assert.notStrictEqual(matches, undefined, "Unable to validate etag");
}
assert.notStrictEqual(
result,
undefined,
"did not get expected result object"
);
done();
}
);
});
// Insert entity property with type "Edm.DateTime", server will convert to UTC time
it("Insert new Entity property with type Edm.DateTime will convert to UTC, @loki", (done) => {
const timeValue = "2012-01-02T23:00:00";
const entity = {
PartitionKey: "part1",
RowKey: "utctest",
myValue: timeValue,
"myValue@odata.type": "Edm.DateTime"
};
tableService.insertEntity(
tableName,
entity,
(insertError, insertResult, insertResponse) => {
if (!insertError) {
tableService.retrieveEntity<TestEntity>(
tableName,
"part1",
"utctest",
(error, result) => {
const insertedEntity: TestEntity = result;
assert.strictEqual(
insertedEntity.myValue._.toString(),
new Date(timeValue + "Z").toString()
);
done();
}
);
} else {
assert.ifError(insertError);
done();
}
}
);
});
// Simple test in here until we have the full set checked in, as we need
// a starting point for delete and query entity APIs
it("Should insert new Entity with empty RowKey, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-entity
const entity = createBasicEntityForTest();
entity.RowKey._ = "";
tableService.insertEntity<TestEntity>(
tableName,
entity,
(error, result, response) => {
assert.ifError(error);
assert.strictEqual(response.statusCode, 201);
if (result !== undefined) {
const matches = result[".metadata"].etag.match(
"W/\"datetime'\\d{4}-\\d{2}-\\d{2}T\\d{2}%3A\\d{2}%3A\\d{2}.\\d{7}Z'\""
);
assert.notStrictEqual(matches, undefined, "Unable to validate etag");
}
assert.notStrictEqual(
result,
undefined,
"did not get expected result object"
);
done();
}
);
});
it("Should retrieve entity with empty RowKey, @loki", (done) => {
const entityInsert = createBasicEntityForTest();
entityInsert.RowKey._ = "";
entityInsert.myValue._ = getUniqueName("uniqueValue");
tableService.insertOrReplaceEntity(
tableName,
entityInsert,
(insertError, insertResult, insertResponse) => {
if (!insertError) {
tableService.retrieveEntity<TestEntity>(
tableName,
entityInsert.PartitionKey._,
"",
(queryError, queryResult, queryResponse) => {
if (!queryError) {
if (queryResult && queryResponse) {
assert.strictEqual(queryResponse.statusCode, 200);
assert.strictEqual(
queryResult.myValue._,
entityInsert.myValue._
);
done();
} else {
assert.fail("Test failed to retrieve the entity.");
}
} else {
assert.ifError(queryError);
done();
}
}
);
} else {
assert.ifError(insertError);
done();
}
}
);
});
it("Should delete an Entity using etag wildcard, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/delete-entity1
const entity = createBasicEntityForTest();
tableService.insertEntity<TestEntity>(
tableName,
entity,
(error, result, response) => {
assert.strictEqual(response.statusCode, 201);
/* https://docs.microsoft.com/en-us/rest/api/storageservices/delete-entity1#request-headers
If-Match Required. The client may specify the ETag for the entity on the request in
order to compare to the ETag maintained by the service for the purpose of optimistic concurrency.
The delete operation will be performed only if the ETag sent by the client matches the value
maintained by the server, indicating that the entity has not been modified since it was retrieved by the client.
To force an unconditional delete, set If-Match to the wildcard character (*). */
result[".metadata"].etag = "*";
tableService.deleteEntity(
tableName,
result,
(deleteError, deleteResponse) => {
assert.ifError(deleteError);
assert.strictEqual(deleteResponse.statusCode, 204);
done();
}
);
}
);
});
it("Should not delete an Entity not matching Etag, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/delete-entity1
const entityInsert = createBasicEntityForTest();
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.insertEntity(
tableName,
entityInsert,
(insertError, insertResult, insertResponse) => {
if (!insertError) {
requestOverride.headers = {};
insertResult[".metadata"].etag = insertResult[
".metadata"
].etag.replace("20", "21"); // test will be valid for 100 years... if it causes problems then, I shall be very proud
tableService.deleteEntity(
tableName,
insertResult,
(deleteError, deleteResponse) => {
assert.strictEqual(deleteResponse.statusCode, 412); // Precondition failed
done();
}
);
} else {
assert.ifError(insertError);
done();
}
}
);
});
it("Should delete a matching Etag, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/delete-entity1
const entityInsert = createBasicEntityForTest();
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.insertEntity(
tableName,
entityInsert,
(error, result, insertresponse) => {
if (!error) {
requestOverride.headers = {};
tableService.deleteEntity(
tableName,
result, // SDK defined entity type...
(deleteError, deleteResponse) => {
if (!deleteError) {
assert.strictEqual(deleteResponse.statusCode, 204); // Precondition succeeded
done();
} else {
assert.ifError(deleteError);
done();
}
}
);
} else {
assert.ifError(error);
done();
}
}
);
});
it("Update an Entity that exists, @loki", (done) => {
const entityInsert = createBasicEntityForTest();
tableService.insertEntity(
tableName,
entityInsert,
(error, result, insertresponse) => {
if (!error) {
requestOverride.headers = {};
tableService.replaceEntity(
tableName,
{
PartitionKey: entityInsert.PartitionKey,
RowKey: entityInsert.RowKey,
myValue: "newValue"
},
(updateError, updateResult, updateResponse) => {
if (!updateError) {
assert.strictEqual(updateResponse.statusCode, 204); // Precondition succeeded
done();
} else {
assert.ifError(updateError);
done();
}
}
);
} else {
assert.ifError(error);
done();
}
}
);
});
it("Fails to update an Entity that does not exist, @loki", (done) => {
const entityToUpdate = createBasicEntityForTest();
tableService.replaceEntity(
tableName,
entityToUpdate,
(updateError, updateResult, updateResponse) => {
const castUpdateStatusCode = (updateError as StorageError).statusCode;
if (updateError) {
assert.strictEqual(castUpdateStatusCode, 404);
done();
} else {
assert.fail("Test failed to throw the right Error" + updateError);
}
}
);
});
it("Should not update an Entity not matching Etag, @loki", (done) => {
const entityInsert = createBasicEntityForTest();
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.insertEntity(
tableName,
entityInsert,
(insertError, insertResult, insertResponse) => {
if (!insertError) {
requestOverride.headers = {};
const entityUpdate = insertResult;
entityUpdate[".metadata"].etag = insertResult[
".metadata"
].etag.replace("20", "21"); // test will be valid for 100 years... if it causes problems then, I shall be very proud
tableService.replaceEntity(
tableName,
entityUpdate,
(updateError, updateResponse) => {
const castUpdateStatusCode = (updateError as StorageError)
.statusCode;
assert.strictEqual(castUpdateStatusCode, 412); // Precondition failed
done();
}
);
} else {
assert.ifError(insertError);
done();
}
}
);
});
it("Should update, if Etag matches, @loki", (done) => {
const entityTemplate = createBasicEntityForTest();
const entityInsert = {
PartitionKey: entityTemplate.PartitionKey,
RowKey: entityTemplate.RowKey,
myValue: "oldValue"
};
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.insertEntity(
tableName,
entityInsert,
(error, result, insertresponse) => {
const etagOld = result[".metadata"].etag;
const entityUpdate = {
PartitionKey: entityTemplate.PartitionKey,
RowKey: entityTemplate.RowKey,
myValue: "oldValueUpdate",
".metadata": {
etag: etagOld
}
};
if (!error) {
requestOverride.headers = {};
tableService.replaceEntity(
tableName,
entityUpdate,
(updateError, updateResult, updateResponse) => {
if (!updateError) {
assert.strictEqual(updateResponse.statusCode, 204); // Precondition succeeded
done();
} else {
assert.ifError(updateError);
done();
}
}
);
} else {
assert.ifError(error);
done();
}
}
);
});
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-or-replace-entity
it("Insert or Replace (upsert) on an Entity that does not exist, @loki", (done) => {
const entityToInsert = createBasicEntityForTest();
tableService.insertOrReplaceEntity(
tableName,
entityToInsert,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
// x-ms-version:'2018-03-28'
assert.strictEqual(updateResponse.statusCode, 204);
tableService.retrieveEntity<TestEntity>(
tableName,
entityToInsert.PartitionKey._,
entityToInsert.RowKey._,
(error, result) => {
assert.strictEqual(
result.myValue._,
entityToInsert.myValue._,
"Value was incorrect on retrieved entity"
);
done();
}
);
}
}
);
});
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-or-replace-entity
it("Insert or Replace (upsert) on an Entity that exists, @loki", (done) => {
const upsertEntity = createBasicEntityForTest();
tableService.insertEntity(tableName, upsertEntity, () => {
upsertEntity.myValue._ = "updated";
tableService.insertOrReplaceEntity(
tableName,
upsertEntity,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 204);
tableService.retrieveEntity<TestEntity>(
tableName,
upsertEntity.PartitionKey._,
upsertEntity.RowKey._,
(error, result) => {
assert.strictEqual(
result.myValue._,
upsertEntity.myValue._,
"Value was incorrect on retrieved entity"
);
done();
}
);
}
}
);
});
});
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-or-merge-entity
it("Insert or Merge on an Entity that exists, @loki", (done) => {
const entityInsert = createBasicEntityForTest();
tableService.insertEntity(
tableName,
entityInsert,
(insertError, insertResult, insertresponse) => {
entityInsert.myValue._ = "new value";
if (!insertError) {
requestOverride.headers = {};
tableService.insertOrMergeEntity(
tableName,
entityInsert,
(updateError, updateResult, updateResponse) => {
if (!updateError) {
assert.strictEqual(updateResponse.statusCode, 204); // Precondition succeeded
tableService.retrieveEntity<TestEntity>(
tableName,
entityInsert.PartitionKey._,
entityInsert.RowKey._,
(error, result) => {
assert.strictEqual(
result.myValue._,
entityInsert.myValue._,
"Value was incorrect on retrieved entity"
);
done();
}
);
} else {
assert.ifError(updateError);
done();
}
}
);
} else {
assert.ifError(insertError);
done();
}
}
);
});
it("Insert or Merge on an Entity that does not exist, @loki", (done) => {
const entityToInsertOrMerge = createBasicEntityForTest();
tableService.insertOrMergeEntity(
tableName,
entityToInsertOrMerge,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 204);
tableService.retrieveEntity<TestEntity>(
tableName,
entityToInsertOrMerge.PartitionKey._,
entityToInsertOrMerge.RowKey._,
(error, result) => {
assert.strictEqual(
result.myValue._,
entityToInsertOrMerge.myValue._,
"Inserted value did not match"
);
done();
}
);
}
}
);
});
// Start of Batch Tests:
it("Simple Insert Or Replace of a SINGLE entity as a BATCH, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT_OR_REPLACE", batchEntity1); // resulting in PUT
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
}
done();
}
);
}
}
);
});
it("Simple batch test: Inserts multiple entities as a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
const batchEntity2 = createBasicEntityForTest();
const batchEntity3 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT", batchEntity1, { echoContent: true });
entityBatch.addOperation("INSERT", batchEntity2, { echoContent: true });
entityBatch.addOperation("INSERT", batchEntity3, { echoContent: true });
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202); // No content
// Now that QueryEntity is done - validate Entity Properties as follows:
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
done();
}
);
}
}
);
});
it("Simple batch test: Delete multiple entities as a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
// First insert multiple entities to delete
const batchEntity1 = createBasicEntityForTest();
const batchEntity2 = createBasicEntityForTest();
const batchEntity3 = createBasicEntityForTest();
assert.notDeepEqual(
batchEntity1.RowKey,
batchEntity2.RowKey,
"failed to create unique test entities 1 & 2"
);
assert.notDeepEqual(
batchEntity1.RowKey,
batchEntity3.RowKey,
"failed to create unique test entities 2 & 3"
);
const insertEntityBatch: Azure.TableBatch = new Azure.TableBatch();
insertEntityBatch.addOperation("INSERT", batchEntity1, {
echoContent: true
});
insertEntityBatch.addOperation("INSERT", batchEntity2, {
echoContent: true
});
insertEntityBatch.addOperation("INSERT", batchEntity3, {
echoContent: true
});
const deleteEntityBatch: Azure.TableBatch = new Azure.TableBatch();
deleteEntityBatch.deleteEntity(batchEntity1);
deleteEntityBatch.deleteEntity(batchEntity2);
deleteEntityBatch.deleteEntity(batchEntity3);
tableService.executeBatch(
tableName,
insertEntityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202); // No content
// Now that QueryEntity is done - validate Entity Properties as follows:
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.notEqual(error, null);
done();
}
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
// now that we have confirmed that our test entities are created, we can try to delete them
tableService.executeBatch(
tableName,
deleteEntityBatch,
(
deleteUpdateError,
deleteUpdateResult,
deleteUpdateResponse
) => {
if (deleteUpdateError) {
assert.ifError(deleteUpdateError);
done();
} else {
assert.strictEqual(deleteUpdateResponse.statusCode, 202); // No content
// Now that QueryEntity is done - validate Entity Properties as follows:
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(finalRetrieveError, finalRetrieveResult) => {
const retrieveError: StorageError = finalRetrieveError as StorageError;
assert.strictEqual(
retrieveError.statusCode,
404,
"status code was not equal to 404!"
);
done();
}
);
}
}
);
}
);
}
}
);
});
it("Insert Or Replace multiple entities as a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
const batchEntity2 = createBasicEntityForTest();
const batchEntity3 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT_OR_REPLACE", batchEntity1);
entityBatch.addOperation("INSERT_OR_REPLACE", batchEntity2);
entityBatch.addOperation("INSERT_OR_REPLACE", batchEntity3);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
}
done();
}
);
}
}
);
});
it("Insert Or Merge multiple entities as a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
const batchEntity2 = createBasicEntityForTest();
const batchEntity3 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT_OR_MERGE", batchEntity1);
entityBatch.addOperation("INSERT_OR_MERGE", batchEntity2);
entityBatch.addOperation("INSERT_OR_MERGE", batchEntity3);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
}
done();
}
);
}
}
);
});
it("Insert and Update entity via a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity(
tableName,
batchEntity1,
(initialInsertError, initialInsertResult) => {
assert.ifError(initialInsertError);
const batchEntity2 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT", batchEntity2, { echoContent: true });
batchEntity1.myValue._ = "value2";
entityBatch.replaceEntity(batchEntity1);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.ifError(error);
done();
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(
entity.myValue._,
batchEntity1.myValue._
);
}
done();
}
);
}
}
);
}
);
});
it("Insert and Merge entity via a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity(
tableName,
batchEntity1,
(initialInsertError, initialInsertResult) => {
assert.ifError(initialInsertError);
const batchEntity2 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT", batchEntity2, { echoContent: true });
batchEntity1.myValue._ = "value2";
entityBatch.mergeEntity(batchEntity1);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(
entity.myValue._,
batchEntity1.myValue._
);
}
done();
}
);
}
}
);
}
);
});
it("Insert and Delete entity via a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity(
tableName,
batchEntity1,
(initialInsertError, initialInsertResult) => {
assert.ifError(initialInsertError);
const batchEntity2 = createBasicEntityForTest();
// Should fail
// The batch request contains multiple changes with same row key. An entity can appear only once in a batch request.
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT", batchEntity2, { echoContent: true });
entityBatch.deleteEntity(batchEntity1);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result) => {
const retrieveError: StorageError = error as StorageError;
assert.strictEqual(
retrieveError.statusCode,
404,
"status code was not equal to 404!"
);
done();
}
);
}
}
);
}
);
});
it("Query / Retrieve single entity via a batch, requestion Options undefined / default @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity(tableName, batchEntity1, (error, result) => {
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.retrieveEntity(
batchEntity1.PartitionKey._,
batchEntity1.RowKey._
);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
const batchRetrieveEntityResult = updateResponse.body
? updateResponse.body
: "";
assert.notEqual(batchRetrieveEntityResult.indexOf("value1"), -1);
done();
}
}
);
});
});
it("Single Delete entity via a batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity<TestEntity>(tableName, batchEntity1, () => {
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.deleteEntity(batchEntity1);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error: any, result) => {
assert.strictEqual(
error.statusCode,
404,
"status code was not equal to 404!"
);
done();
}
);
}
}
);
});
});
// this covers the following issues
// https://github.com/Azure/Azurite/issues/750
// https://github.com/Azure/Azurite/issues/733
// https://github.com/Azure/Azurite/issues/745
it("Operates on batch items with complex row keys, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const insertEntity1 = createBasicEntityForTest();
insertEntity1.RowKey._ = "8b0a63c8-9542-49d8-9dd2-d7af9fa8790f_0B";
const insertEntity2 = createBasicEntityForTest();
insertEntity2.RowKey._ = "8b0a63c8-9542-49d8-9dd2-d7af9fa8790f_0C";
const insertEntity3 = createBasicEntityForTest();
insertEntity3.RowKey._ = "8b0a63c8-9542-49d8-9dd2-d7af9fa8790f_0D";
const insertEntity4 = createBasicEntityForTest();
insertEntity4.RowKey._ = "8b0a63c8-9542-49d8-9dd2-d7af9fa8790f_0E";
tableService.insertEntity<TestEntity>(tableName, insertEntity1, () => {
tableService.insertEntity<TestEntity>(tableName, insertEntity2, () => {
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.insertEntity(insertEntity3, { echoContent: true });
entityBatch.insertEntity(insertEntity4, {});
entityBatch.deleteEntity(insertEntity1);
entityBatch.deleteEntity(insertEntity2);
tableService.executeBatch(
tableName,
entityBatch,
(batchError, batchResult, batchResponse) => {
if (batchError) {
assert.ifError(batchError);
done();
} else {
assert.strictEqual(batchResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity3.PartitionKey._,
insertEntity3.RowKey._,
(error: any, result, response) => {
assert.strictEqual(
response.statusCode,
200,
"We did not find the 3rd entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity4.PartitionKey._,
insertEntity4.RowKey._,
(error2: any, result2, response2) => {
assert.strictEqual(
response2.statusCode,
200,
"We did not find the 4th entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity1.PartitionKey._,
insertEntity1.RowKey._,
(error3: any, result3, response3) => {
assert.strictEqual(
response3.statusCode,
404,
"We did not delete the 1st entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity2.PartitionKey._,
insertEntity2.RowKey._,
(error4: any, result4, response4) => {
assert.strictEqual(
response4.statusCode,
404,
"We did not delete the 2nd entity!"
);
done();
}
);
}
);
}
);
}
);
}
}
);
});
});
});
// this covers https://github.com/Azure/Azurite/issues/741
it("Operates on batch items with complex partition keys, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const insertEntity1 = createBasicEntityForTest();
insertEntity1.PartitionKey._ =
"@DurableTask.AzureStorage.Tests.AzureStorageScenarioTests+Orchestrations+AutoStartOrchestration+Responder";
const insertEntity2 = createBasicEntityForTest();
insertEntity2.PartitionKey._ =
"@DurableTask.AzureStorage.Tests.AzureStorageScenarioTests+Orchestrations+AutoStartOrchestration+Responder";
const insertEntity3 = createBasicEntityForTest();
insertEntity3.PartitionKey._ =
"@DurableTask.AzureStorage.Tests.AzureStorageScenarioTests+Orchestrations+AutoStartOrchestration+Responder";
const insertEntity4 = createBasicEntityForTest();
insertEntity4.PartitionKey._ =
"@DurableTask.AzureStorage.Tests.AzureStorageScenarioTests+Orchestrations+AutoStartOrchestration+Responder";
tableService.insertEntity<TestEntity>(tableName, insertEntity1, () => {
tableService.insertEntity<TestEntity>(tableName, insertEntity2, () => {
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.insertEntity(insertEntity3, { echoContent: true });
entityBatch.insertEntity(insertEntity4, {});
entityBatch.deleteEntity(insertEntity1);
entityBatch.deleteEntity(insertEntity2);
tableService.executeBatch(
tableName,
entityBatch,
(batchError, batchResult, batchResponse) => {
if (batchError) {
assert.ifError(batchError);
done();
} else {
assert.strictEqual(batchResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity3.PartitionKey._,
insertEntity3.RowKey._,
(error: any, result, response) => {
assert.strictEqual(
response.statusCode,
200,
"We did not find the 3rd entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity4.PartitionKey._,
insertEntity4.RowKey._,
(error2: any, result2, response2) => {
assert.strictEqual(
response2.statusCode,
200,
"We did not find the 4th entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity1.PartitionKey._,
insertEntity1.RowKey._,
(error3: any, result3, response3) => {
assert.strictEqual(
response3.statusCode,
404,
"We did not delete the 1st entity!"
);
tableService.retrieveEntity<TestEntity>(
tableName,
insertEntity2.PartitionKey._,
insertEntity2.RowKey._,
(error4: any, result4, response4) => {
assert.strictEqual(
response4.statusCode,
404,
"We did not delete the 2nd entity!"
);
done();
}
);
}
);
}
);
}
);
}
}
);
});
});
});
it("Ensure Valid Etag format from Batch, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const batchEntity1 = createBasicEntityForTest();
tableService.insertEntity<TestEntity>(tableName, batchEntity1, () => {
const batchEntity2 = createBasicEntityForTest();
const entityBatch: Azure.TableBatch = new Azure.TableBatch();
entityBatch.addOperation("INSERT", batchEntity2, { echoContent: true });
batchEntity1.myValue._ = "value2";
entityBatch.mergeEntity(batchEntity1);
tableService.executeBatch(
tableName,
entityBatch,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 202);
tableService.retrieveEntity<TestEntity>(
tableName,
batchEntity1.PartitionKey._,
batchEntity1.RowKey._,
(error, result, response) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, batchEntity1.myValue._);
if (response !== null) {
const body: any = response?.body;
assert.notStrictEqual(body, null, "response empty");
if (body != null) {
assert.strictEqual(
body["odata.etag"].match(/(%3A)/).length,
2,
"did not find the expected number of escaped sequences"
);
}
}
}
done();
}
);
}
}
);
});
});
it("Should have a valid OData Metadata value when inserting an entity, @loki", (done) => {
// https://docs.microsoft.com/en-us/rest/api/storageservices/insert-entity
const entityInsert = createBasicEntityForTest();
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
tableService.insertEntity(
tableName,
entityInsert,
(error, result, insertresponse) => {
if (
!error &&
insertresponse !== undefined &&
insertresponse.body !== undefined
) {
const body = insertresponse.body as object;
const meta: string = body["odata.metadata" as keyof object];
assert.strictEqual(meta.endsWith("/@Element"), true);
done();
} else {
assert.ifError(error);
done();
}
}
);
});
it("Can create entities with empty string for row and partition key, @loki", (done) => {
requestOverride.headers = {
Prefer: "return-content",
accept: "application/json;odata=fullmetadata"
};
const emptyKeysEntity = createBasicEntityForTest();
emptyKeysEntity.PartitionKey._ = "";
emptyKeysEntity.RowKey._ = "";
tableService.insertEntity<TestEntity>(
tableName,
emptyKeysEntity,
(updateError, updateResult, updateResponse) => {
if (updateError) {
assert.ifError(updateError);
done();
} else {
assert.strictEqual(updateResponse.statusCode, 201);
tableService.retrieveEntity<TestEntity>(
tableName,
"",
"",
(error, result, response) => {
if (error) {
assert.ifError(error);
} else if (result) {
const entity: TestEntity = result;
assert.strictEqual(entity.myValue._, emptyKeysEntity.myValue._);
}
done();
}
);
}
}
);
});
}); | the_stack |
import {DemoSharedBase} from '../utils';
import {Screen, Utils} from "@nativescript/core";
import {func, images} from "./games/utils";
declare let Phaser: any, UIDevice;
interface AccelerometerData {
x: number;
y: number;
z: number;
}
type SensorDelay = "normal" | "game" | "ui" | "fastest";
interface AccelerometerOptions {
sensorDelay?: SensorDelay;
}
export const stopButNotStarted = "[nativescript-accelerometer] stopAccelerometerUpdates() called, but currently not listening. Ignoring...";
export const startButNotStopped = "[nativescript-accelerometer] startAccelerometerUpdates() called, but there is active listener. Will stop the current listener and switch to the new one.";
class Accelerometer {
static baseAcceleration = -9.81;
static sensorListener: android.hardware.SensorEventListener;
static sensorManager: android.hardware.SensorManager;
static accelerometerSensor: android.hardware.Sensor;
static accManager;
static isListeningForUpdates = false;
static main_queue = global.isIOS ? dispatch_get_current_queue() : null;
static getNativeDelay(options?: AccelerometerOptions): number {
if (global.isAndroid) {
if (!options || !options.sensorDelay) {
return android.hardware.SensorManager.SENSOR_DELAY_NORMAL;
}
switch (options.sensorDelay) {
case "normal":
return android.hardware.SensorManager.SENSOR_DELAY_NORMAL;
case "game":
return android.hardware.SensorManager.SENSOR_DELAY_GAME;
case "ui":
return android.hardware.SensorManager.SENSOR_DELAY_UI;
case "fastest":
return android.hardware.SensorManager.SENSOR_DELAY_FASTEST;
}
} else {
if (!options || !options.sensorDelay) {
return 0.2;
}
switch (options.sensorDelay) {
case "normal":
return 0.2;
case "ui":
return 0.06;
case "game":
return 0.02
case "fastest":
return 0.001;
}
}
}
static startAccelerometerUpdates(callback: (data: AccelerometerData) => void, options?: AccelerometerOptions) {
if (global.isAndroid) {
if (Accelerometer.isListening()) {
console.log(startButNotStopped);
Accelerometer.stopAccelerometerUpdates();
}
const wrappedCallback = zonedCallback(callback);
const context: android.content.Context = Utils.ad.getApplicationContext();
if (!context) {
throw Error("Could not get Android application context.")
}
if (!Accelerometer.sensorManager) {
Accelerometer.sensorManager = context.getSystemService(android.content.Context.SENSOR_SERVICE);
if (!Accelerometer.sensorManager) {
throw Error("Could not initialize SensorManager.")
}
}
if (!Accelerometer.accelerometerSensor) {
Accelerometer.accelerometerSensor = Accelerometer.sensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_ACCELEROMETER);
if (!Accelerometer.accelerometerSensor) {
throw Error("Could get accelerometer sensor.")
}
}
Accelerometer.sensorListener = new android.hardware.SensorEventListener({
onAccuracyChanged: (sensor, accuracy) => {
},
onSensorChanged: (event) => {
wrappedCallback({
x: event.values[0] / Accelerometer.baseAcceleration,
y: event.values[1] / Accelerometer.baseAcceleration,
z: event.values[2] / Accelerometer.baseAcceleration
})
}
});
const nativeDelay = Accelerometer.getNativeDelay(options);
Accelerometer.sensorManager.registerListener(
Accelerometer.sensorListener,
Accelerometer.accelerometerSensor,
nativeDelay
);
} else {
if (Accelerometer.isListeningForUpdates) {
console.log(startButNotStopped);
Accelerometer.stopAccelerometerUpdates();
}
const wrappedCallback = zonedCallback(callback);
if (!Accelerometer.accManager) {
Accelerometer.accManager = CMMotionManager.alloc().init();
if (!Accelerometer.accManager.gyroAvailable) {
return;
}
}
Accelerometer.accManager.accelerometerUpdateInterval = Accelerometer.getNativeDelay(options);
if (Accelerometer.accManager.accelerometerAvailable) {
var queue = NSOperationQueue.alloc().init();
Accelerometer.accManager.startAccelerometerUpdatesToQueueWithHandler(queue, (data, error) => {
dispatch_async(Accelerometer.main_queue, () => {
wrappedCallback({
x: data.acceleration.x,
y: data.acceleration.y,
z: data.acceleration.z
})
})
});
Accelerometer.isListeningForUpdates = true;
} else {
throw new Error("Accelerometer not available.")
}
}
}
static stopAccelerometerUpdates() {
if (global.isAndroid) {
if (Accelerometer.sensorListener) {
Accelerometer.sensorManager.unregisterListener(Accelerometer.sensorListener);
Accelerometer.sensorListener = undefined;
} else {
console.log(stopButNotStarted);
}
} else {
if (Accelerometer.isListeningForUpdates) {
Accelerometer.accManager.stopAccelerometerUpdates();
Accelerometer.isListeningForUpdates = false;
} else {
console.log(stopButNotStarted);
}
}
}
static isListening(): boolean {
if (global.isAndroid) {
return !!Accelerometer.sensorListener;
} else {
return Accelerometer.isListeningForUpdates;
}
}
}
export class DemoSharedCanvasPhaserCe extends DemoSharedBase {
canvas;
fps = 0;
canvasLoaded(args) {
this.canvas = args.object;
this.setupGame(this.canvas);
}
gamePause: boolean = false;
isLoading: boolean = true;
kills: number = 0;
score: number = 0;
shotsFired: number = 0;
displayAccuracy: string | null = null;
game: CustomGame;
didInit: boolean = false;
didSubscribe: boolean = false;
useAccelerometer: boolean = true;
constructor() {
super();
this.on("propertyChange", (args) => {
if (!this.isLoading && !this.didSubscribe) {
this.subscribe();
this.set("didSubscribe", true);
}
});
this.updateStats = this.updateStats.bind(this);
//this.preloadAssetsAsync = this.preloadAssetsAsync.bind(this);
this.preloadAssetsAsync();
this.handleTogglePause = this.handleTogglePause.bind(this);
this.onTouchesBegan = this.onTouchesBegan.bind(this);
this.onTouchesEnded = this.onTouchesEnded.bind(this);
}
onTouch(event) {
if (event.eventName === "touch") {
switch (event.action) {
case "down":
this.onTouchesBegan();
break;
case "up":
this.onTouchesEnded();
break;
case "cancel":
this.onTouchesEnded();
break;
default:
break;
}
} else if (event.eventName === "pan") {
if (!this.useAccelerometer) {
// TODO allow update position with pan
//this.game.updateControls(event.deltaX);
}
}
}
subscribe() {
if (!this.useAccelerometer) {
return;
}
if (global.isIOS) {
if (
!CMMotionManager.alloc().init().gyroAvailable
) {
return;
}
}
if (Accelerometer.isListening) {
Accelerometer.stopAccelerometerUpdates();
}
Accelerometer.startAccelerometerUpdates(
(changed) => {
if (this.game) {
this.game.updateControls(changed.x);
}
},
{
sensorDelay: "ui",
}
);
}
unsubscribe() {
if (!this.useAccelerometer) {
return;
}
if (global.isIOS) {
return (
UIDevice.currentDevice.name
.toLowerCase()
.indexOf("simulator") !== -1
);
}
if (Accelerometer.isListening) {
Accelerometer.stopAccelerometerUpdates();
}
}
async preloadAssetsAsync() {
const imageAssets = func.cacheImages(images.files);
await Promise.all([...imageAssets]).then((image) => {
this.set("isLoading", false);
}).catch(e => {
console.log('e:', e);
});
}
updateStats(data) {
this.set("kills", data.kills);
this.set("score", data.score);
this.set("shotsFired", data.shotsFired);
}
handleTogglePause() {
this.set("gamePause", !this.gamePause);
}
onTouchesBegan() {
if (!this.game) {
return false;
}
return this.game.onTouchesBegan();
}
onTouchesEnded() {
if (!this.game) {
return false;
}
return this.game.onTouchesEnded();
}
setupGame(canvas) {
this.game = new CustomGame({
canvas,
gamePause: this.gamePause,
updateStats: this.updateStats,
});
}
}
export class CustomGame {
game;
playable: Playable;
constructor({canvas, gamePause, updateStats}) {
const TNSPhaser = require("@nativescript/canvas-phaser-ce");
this.game = TNSPhaser.Game({canvas});
this.playable = new Playable({
game: this.game,
gamePause,
updateStats,
});
this.game.state.add("Playable", this.playable);
this.game.state.start("Playable");
//this.onTouchesBegan = this.onTouchesBegan.bind(this);
//this.onTouchesEnded = this.onTouchesEnded.bind(this);
}
updateControls(velocity) {
if (this.playable) {
this.playable.updateControls({velocity});
}
}
onTouchesBegan() {
if (!this.playable) {
return false;
}
return this.playable.onTouchesBegan();
}
onTouchesEnded() {
if (!this.playable) {
return false;
}
return this.playable.onTouchesEnded();
}
onTogglePause(paused) {
this.playable.pauseGame(paused);
}
}
const scale = Screen.mainScreen.scale;
class SettingsConfig {
explosion: number;
invader: number;
playerSpeed: number;
constructor() {
this.explosion = 128; // * scale;
this.invader = 32; // * scale;
this.playerSpeed = 600;
}
}
const Settings = new SettingsConfig();
export class Playable {
context;
game;
gamePause;
updateStats;
startLives: number;
alienRows: number;
initialGameState: any;
aliens: any;
bullets: any;
bulletTime: number;
enemyBullet: any;
explosions: any;
firingTimer: number;
lives: any;
livingEnemies: any[];
player: any;
score: number;
shotsFired: number;
kills: number;
starfield: any;
stateText: any;
pressing: boolean;
enemyBullets: any;
live: any;
bullet: any;
constructor({game, gamePause, updateStats}) {
// prevent warnings for Phaser.Cache
(console as any).disableYellowBox = true;
this.updateStats = updateStats;
// game config
this.startLives = 3;
this.alienRows = 4;
this.initialGameState = gamePause;
// default states
this.aliens = null;
this.bullets = null;
this.bulletTime = 0;
// this.cursors = null;
this.enemyBullet = null;
this.explosions = null;
// this.fireButton = null;
this.firingTimer = 0;
this.lives = null;
this.livingEnemies = [];
this.player = null;
this.starfield = null;
this.stateText = null;
// player stats
this.kills = 0;
this.shotsFired = 0;
this.score = 0;
this.game = game;
}
preload() {
const {files} = images;
this.game.load.image("bullet", func.uri(files.bullet));
this.game.load.image("enemyBullet", func.uri(files.enemyBullet));
this.game.load.spritesheet(
"invader",
func.uri(files.invader),
Settings.invader,
Settings.invader
);
this.game.load.image("ship", func.uri(files.player));
this.game.load.spritesheet(
"kaboom",
func.uri(files.explode),
Settings.explosion,
Settings.explosion
);
this.game.load.image("starfield", func.uri(files.starfield));
}
updateControls({velocity}) {
const {player} = this;
if (player && player.alive) {
const speed = Math.floor(velocity * Settings.playerSpeed);
// reset the player, then check for movement keys
player.body.velocity.setTo(0, 0);
player.body.velocity.x = speed;
}
}
scaleNode(node) {
node.width *= scale;
node.height *= scale;
}
onTouchesBegan() {
this.pressing = true;
}
onTouchesEnded() {
this.pressing = false;
if (this.player) {
if (this.player.alive) {
this.fireBullet();
} else {
this.restart();
}
}
}
pauseGame(paused) {
const {game} = this;
game.paused = paused;
}
create() {
const {game, startLives} = this;
const {world} = game;
const {height, width} = world;
//Why ios needs this ?
world.alpha = 2;
// game.stage.backgroundColor = '#4488AA';
game.stage.backgroundColor = "#000";
game.physics.startSystem(Phaser.Physics.ARCADE);
// initial game state paused?
game.paused = this.initialGameState;
/**
*
* A TileSprite is a Sprite that has a repeating texture.
* The texture can be scrolled and scaled independently of the TileSprite itself.
* Textures will automatically wrap and are designed so that you can create game
* backdrops using seamless textures as a source.
*
* */
// the scrolling starfield background
// this.starfield = game.add.tileSprite(0, 0, width, height, 'starfield');
this.starfield = game.add.sprite(0, 0, "starfield");
this.starfield.height = height;
this.starfield.width = width;
// our bullet group
this.bullets = game.add.group();
this.bullets.enableBody = true;
this.bullets.physicsBodyType = Phaser.Physics.ARCADE;
this.bullets.createMultiple(30, "bullet");
this.bullets.setAll("anchor.x", 0.5);
this.bullets.setAll("anchor.y", 1);
this.bullets.setAll("width", 6 * scale);
this.bullets.setAll("height", 36 * scale);
this.bullets.setAll("outOfBoundsKill", true);
this.bullets.setAll("checkWorldBounds", true);
// the enemy's bullets
this.enemyBullets = game.add.group();
this.enemyBullets.enableBody = true;
this.enemyBullets.physicsBodyType = Phaser.Physics.ARCADE;
this.enemyBullets.createMultiple(30, "enemyBullet");
this.enemyBullets.setAll("anchor.x", 0.5);
this.enemyBullets.setAll("anchor.y", 1);
this.enemyBullets.setAll("width", 9 * scale);
this.enemyBullets.setAll("height", 9 * scale);
this.enemyBullets.setAll("outOfBoundsKill", true);
this.enemyBullets.setAll("checkWorldBounds", true);
// the hero!
this.player = game.add.sprite(
width * 0.5,
height * 0.833333333,
"ship"
);
this.player.anchor.setTo(0.5, 0.5);
this.scaleNode(this.player);
game.physics.enable(this.player, Phaser.Physics.ARCADE);
// the baddies!
this.aliens = game.add.group();
this.aliens.enableBody = true;
this.aliens.physicsBodyType = Phaser.Physics.ARCADE;
this.createAliens();
// lives
this.lives = game.add.group();
// game.add.text(game.world.width - 100, 10, 'Lives : ', { font: '34px Arial', fill: '#fff' });
// text
// this.stateText = game.add.text(game.world.centerX,game.world.centerY,' ', { font: '84px Arial', fill: '#fff' });
// this.stateText.anchor.setTo(0.5, 0.5);
// this.stateText.visible = false;
const shipOffset = width * 0.125;
const initialshipXoffset = width - shipOffset * startLives;
const shipInterval = 30 * scale;
const shipY = 60 * scale;
for (let i = 0; i < startLives; i += 1) {
const ship = this.lives.create(
initialshipXoffset + shipInterval * i,
shipY,
"ship"
);
this.scaleNode(ship);
ship.anchor.setTo(0.5, 0.5);
ship.angle = 90;
ship.alpha = 0.4;
}
// an explosion pool
this.explosions = game.add.group();
// this.explosions.scale = scale;
this.explosions.createMultiple(30, "kaboom");
this.explosions.setAll("height", 128 * scale);
this.explosions.setAll("width", 128 * scale);
this.explosions.setAll("transparent", true);
this.explosions.forEach(this.setupInvader, this);
// and some controls to play the game with
// this.cursors = game.input.keyboard.createCursorKeys();
// this.fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
}
createAliens() {
const {alienRows, game} = this;
const {world} = game;
const {height, width} = world;
const alienDelta = width * 0.25;
const alienAvailableSpace = width - alienDelta;
const alienWidth = 32 * scale;
const alienPadding = 12;
const aliens = Math.floor(
alienAvailableSpace / (alienPadding + alienWidth)
);
const dimensions = {
columns: aliens,
rows: alienRows,
};
const alienOffset = {
x: alienAvailableSpace / dimensions.columns,
};
for (let y = 0; y < dimensions.rows; y += 1) {
for (let x = 0; x < dimensions.columns; x += 1) {
const alien = this.aliens.create(
x * alienOffset.x,
y * alienOffset.x,
"invader"
);
this.scaleNode(alien);
alien.anchor.setTo(0.5, 0.5);
alien.animations.add("fly", [0, 1, 2, 3], 20, true);
alien.play("fly");
alien.body.moves = false;
}
}
// const alienOffset = this.game.world.width
this.aliens.x = alienWidth / 2;
this.aliens.y = height * 0.0625;
// all this does is basically start the invaders moving. notice we're
// moving the Group they belong to, rather than the invaders directly.
const tween = this.game.add
.tween(this.aliens)
.to(
{x: width - alienAvailableSpace + alienWidth / 2},
2000,
Phaser.Easing.Linear.None,
true,
0,
1000,
true
);
// when the tween loops it calls descend
tween.onRepeat.add(this.descend, this);
}
setupInvader(invader) {
invader.anchor.x = 0.5;
invader.anchor.y = 0.5;
invader.animations.add("kaboom");
}
descend() {
const {game} = this;
const {world} = game;
const {height} = world;
console.log("Loop");
this.aliens.y += height * 0.0166666667;
}
collisionHandler(bullet, alien) {
// when a bullet hits an alien we kill them both
bullet.kill();
alien.kill();
// increase the kills
this.kills += 1;
// increase the score
this.score += 20;
// and create an explosion :)
const explosion = this.explosions.getFirstExists(false);
if (explosion) {
explosion.reset(alien.body.x, alien.body.y);
explosion.play("kaboom", 30, false, true);
}
if (this.aliens.countLiving() === 0) {
this.score += 1000;
this.player.kill();
this.enemyBullets.callAll("kill");
// this.stateText.text = " You Won, \n Click to restart";
// this.stateText.visible = true;
// the "click to restart" handler
console.log("--------------------");
console.log("you beat this level!");
console.log("--------------------");
this.game.input.onTap.addOnce(this.restart, this);
}
}
enemyHitsPlayer(player, bullet) {
bullet.kill();
this.live = this.lives.getFirstAlive();
if (this.live) {
this.live.kill();
}
// and create an explosion :)
const explosion = this.explosions.getFirstExists(false);
if (explosion) {
explosion.reset(player.body.x, player.body.y);
explosion.play("kaboom", 30, false, true);
}
// when the player dies
if (this.lives.countLiving() < 1) {
player.kill();
this.enemyBullets.callAll("kill");
// this.stateText.text=" GAME OVER \n Click to restart";
// this.stateText.visible = true;
// the "click to restart" handler
console.log("--------------------");
console.log("you lost, game over!");
console.log("--------------------");
this.game.input.onTap.addOnce(this.restart, this);
// game.input.onTap.addOnce(this.restart, this);
}
}
enemyFires() {
const {game} = this;
// grab the first bullet we can from the pool
this.enemyBullet = this.enemyBullets.getFirstExists(false);
this.livingEnemies.length = 0;
this.aliens.forEachAlive((alien) => {
// put every living enemy in an array
this.livingEnemies.push(alien);
});
if (this.enemyBullet && this.livingEnemies.length > 0) {
const random = game.rnd.integerInRange(
0,
this.livingEnemies.length - 1
);
// randomly select one of them
const shooter = this.livingEnemies[random];
// and fire the bullet from this enemy
this.enemyBullet.reset(shooter.body.x, shooter.body.y);
game.physics.arcade.moveToObject(
this.enemyBullet,
this.player,
120
);
this.firingTimer = game.time.now + 2000;
}
}
fireBullet() {
// const { bullets, game, player } = this;
// let { bulletTime, bullet } = this;
// to avoid them being allowed to fire too fast we set a time limit
if (this.game.time.now > this.bulletTime) {
// grab the first bullet we can from the pool
this.bullet = this.bullets.getFirstExists(false);
if (this.bullet) {
this.shotsFired += 1;
// and fire it
this.bullet.reset(this.player.x, this.player.y + 8 * scale);
this.bullet.body.velocity.y = -400 * scale;
this.bulletTime = this.game.time.now + 200 * scale;
}
}
}
// resetBullet(bullet) {
resetBullet() {
// called if the bullet goes out of the screen
this.bullet.kill();
}
restart() {
const {lives, aliens, player} = this;
// a new level starts
// resets the life count
lives.callAll("revive");
// and brings the aliens back from the dead :)
aliens.removeAll();
this.createAliens();
// revives the player
player.revive();
// hides the text
// stateText.visible = false;
}
cycleNode(node) {
const {game} = this;
const {world} = game;
const {width} = world;
const half = node.width / 2;
if (node.x < -half) {
node.x = width + half;
} else if (node.x > width + half) {
node.x = -half;
}
}
update() {
const {
aliens,
bullets,
collisionHandler,
enemyBullets,
enemyHitsPlayer,
firingTimer,
game,
player,
starfield,
} = this;
// scroll the background
if (starfield.tilePosition) {
starfield.tilePosition.y += 2;
}
this.updateStats({
kills: this.kills,
score: this.score,
shotsFired: this.shotsFired,
});
if (player.alive) {
// firing?
if (game.time.now > firingTimer) {
this.enemyFires();
}
this.cycleNode(player);
if (this.aliens.y >= player.y && this.lives.countLiving() > 0) {
player.kill();
this.enemyBullets.callAll("kill");
// this.stateText.text=" GAME OVER \n Click to restart";
// this.stateText.visible = true;
// the "click to restart" handler
game.input.onTap.addOnce(this.restart, this);
}
// run collision
game.physics.arcade.overlap(
bullets,
aliens,
collisionHandler,
null,
this
);
game.physics.arcade.overlap(
enemyBullets,
player,
enemyHitsPlayer,
null,
this
);
}
}
} | the_stack |
module TDev {
export var runnerHost : RunnerHost = null;
export class RunnerHost
extends RuntimeHostBase {
currentRt: Runtime;
runMain: () =>void;
constructor () {
super();
var script = (<any>TDev).precompiledScript;
this.currentRt = new Runtime();
this.currentRt.devMode = false;
}
runAsync() {
RunnerSettings.reportLaunch();
SizeMgr.applySizes();
var rt = this.currentRt;
var cs = new CompiledScript();
cs.initFromPrecompiled();
if (!cs.baseScriptId)
cs.baseScriptId = cs.scriptId;
if (!cs.scriptTitle)
cs.scriptTitle = (<any>window).webAppName;
rt.initFrom(cs);
rt.setHost(this);
this.showWall();
rt.initPageStack();
rt.applyPageAttributes();
SizeMgr.applySizes();
this.runMain = () => {
var fn = cs.actionsByName[cs.mainActionName];
if (cs.pagesByName[cs.mainActionName] !== undefined) {
fn = Runtime.syntheticFrame((s) => s.rt.postAutoPage("this", cs.mainActionName));
}
rt.run(fn, null);
};
this.runMain();
return Promise.as();
}
notifyHideWall() {
this.runMain();
}
public agreeTermsOfUseAsync(): Promise {
return RunnerSettings.agreeTermsAsync();
}
}
function initEditor() {
SizeMgr.earlyInit();
document.onkeypress = Util.catchErrors("documentKeyPress", (e) => KeyboardMgr.instance.processKey(e));
document.onkeydown = Util.catchErrors("documentKeyDown", (e) => KeyboardMgr.instance.processKey(e));
document.onkeyup = Util.catchErrors("documentKeyUp", (e) => KeyboardMgr.instance.keyUp(e));
document.onselectstart = () => { return <any> false; };
window.onunload = () => {
};
function saveState() {
Ticker.saveCurrent()
RT.Perf.saveCurrentAsync().done();
}
(<any>window).tdevSaveState = saveState;
var e = elt("loading");
if (e) e.removeSelf();
var r = divId("scriptEditor", null,
divId("wallOverlay", null));
elt("root").appendChild(r);
}
function initWebRunnerApis() {
// api keys needed to make maps work
TDev.RT.ApiManager.bingMapsKey = 'AsnQk63tYReqttLHcIL1RUsc_0h0BwCOib6j0Zvk8QjWs4FQjM9JRM9wEKescphX';
TDev.RT.ArtCache.enabled = false; // disable art caching
TDev.RT.ApiManager.getKeyAsync = function (url: string): Promise { return Promise.as(undefined); }
//TDev.RT.Web.create_request = function (url: string): TDev.RT.WebRequest { return TDev.RT.WebRequest.mk(url, undefined);};
//TDev.RT.Web.proxy = function (url: string): string { return url; }
TDev.RT.BingServices.searchAsync = function (
kind: string,
query: string,
loc: TDev.RT.Location_): Promise { return Promise.as([]); };
if (!Browser.webRunner) {
TDev.RT.Sound.patchLocalArtUrl = function (url: string): string {
if (/\.\/art\//.test(url) && !/\.(wav|m4a)\?a=/.test(url)) {
// adding 'a' argument to trigger caching
url = url + (Browser.audioWav ? '.wav' : '.m4a') + "?a=" + (<any>window).webAppGuid;
url = Util.toAbsoluteUrl(url); // enable local caching of these sounds
Util.log('patched local art sound: ' + url);
}
return url;
}
TDev.RT.Picture.patchLocalArtUrl = function (url: string): string {
if (/\.\/art\//.test(url) && !/\?a=/.test(url)) {
// adding 'a' argument to trigger caching
url += "?a=" + (<any>window).webAppGuid;
url = Util.toAbsoluteUrl(url); // enable local caching of these pictures
Util.log('patched local art picture: ' + url);
}
return url;
}
}
// office mix
if (TDev.Browser.webAppImplicit) {
// do not ask the authenticate
var auth = TDev.Cloud.authenticateAsync;
TDev.Cloud.authenticateAsync = (reason: string) => {
if (reason == "leaderboard")
return Promise.as(!Cloud.isAccessTokenExpired());
return auth(reason);
}
}
}
function initCompiledApp() {
TDev.RuntimeSettings.askSourceAccess = false;
TDev.Cloud.authenticateAsync = (reason:string) => Promise.as(true);
TDev.RT.ArtCache.enabled = false; // disable art caching
TDev.RT.ApiManager.getKeyAsync = (url: string): Promise => Promise.as(TDev.RT.ApiManager.keys[url] || undefined);
TDev.RT.BingServices.searchAsync = function (
kind: string,
query: string,
loc: TDev.RT.Location_): Promise {
if (!TDev.RT.ApiManager.bingSearchKey) {
TDev.RT.Time.log('Missing API Key for Bing search. Please edit /js/apikeys.js.');
return Promise.as([]);
}
var url = 'https://api.datamarket.azure.com/Bing/Search/v1/'
+ encodeURIComponent(kind) + "?Adult='Strict'&Query=" + encodeURIComponent("'" + query + "'");
if (loc) {
url += '&Latitude=' + encodeURIComponent(loc.latitude().toString()) + '&Longitude=' + encodeURIComponent(loc.longitude().toString());
}
var request = TDev.RT.WebRequest.mk(url, undefined);
request.set_credentials('', TDev.RT.ApiManager.bingSearchKey);
return request.sendAsync()
.then((response) => {
var r: TDev.RT.BingSearchResult[] = [];
var feed = TDev.RT.Web.feed(response.content());
for (var i = 0; i < feed.count(); ++i) {
var msg = feed.at(i);
var kind = msg.title();
var values = msg.values();
if (/^webresult$/i.test(kind)) {
r.push({
name: values.at('Title'),
url: values.at('Url'),
thumbUrl: null,
web: values.at('DisplayUrl')
});
} else if (/^imageresult$/i.test(kind)) {
r.push({
name: values.at('Title'),
url: values.at('MediaUrl'),
thumbUrl: null,
web: values.at('Url')
});
} else if (/^newsresult/i.test(kind)) {
var dt = Date.parse(values.at('Date'));
r.push({
name: values.at('Title') + ' - ' + values.at('Source') + ' - ' + Util.timeSince(dt),
url: values.at('Url'),
thumbUrl: null,
web: null
});
}
}
return r;
});
};
(<any>TDev.RT.Languages).translate = function translate(source_lang: string, target_lang: string, text: string, r : ResumeCtx)//: string
{
Util.log('translate: called');
if (!target_lang) {
TDev.RT.Time.log('languages->translate: no target language');
r.resumeVal(undefined);
return;
}
if (!text || source_lang === target_lang) {
r.resumeVal(text);
return;
}
if (!TDev.RT.ApiManager.microsoftTranslatorKey) {
TDev.RT.Time.log('Missing Microsoft Translator API Key.');
r.resumeVal(undefined);
return;
}
Util.log('translating text...');
var url = 'https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?'
+ 'Text=%27' + encodeURIComponent(text) + "%27"
+ '&To=%27' + encodeURIComponent(target_lang) + "%27";
if (source_lang)
url += '&From=%27' + encodeURIComponent(source_lang) + "%27";
TDev.RT.Time.log('languages->translate: sending request');
var request = TDev.RT.WebRequest.mk(url, undefined);
request.set_credentials('', TDev.RT.ApiManager.microsoftTranslatorKey);
request.sendAsync()
.done((response: TDev.RT.WebResponse) => {
var translated = TDev.RT.Web.feed(response.content());
if (translated && translated.count() > 0) {
var tr = translated.at(0);
var rts = tr.values().at('Text');
r.resumeVal(rts);
return;
}
r.resumeVal(undefined);
}, e => {
TDev.RT.Time.log('error while translating');
r.resumeVal(undefined);
});
};
(<any>TDev.RT.Languages).detect_language = function detect_language(text: string, r: ResumeCtx) //: string
{
if (!text) {
r.resumeVal(undefined);
return;
}
if (!TDev.RT.ApiManager.microsoftTranslatorKey) {
TDev.RT.Time.log('Missing Microsoft Translator API Key. Please edit /js/apikeys.js.');
r.resumeVal(undefined);
return;
}
var url = 'https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Detect?'
+ 'Text=%27' + encodeURIComponent(text) + "%27";
var request = TDev.RT.WebRequest.mk(url, undefined);
request.set_credentials('', TDev.RT.ApiManager.microsoftTranslatorKey);
request.sendAsync()
.done((response: TDev.RT.WebResponse) => {
var translated = TDev.RT.Web.feed(response.content());
if (translated && translated.count() > 0) {
var tr = translated.at(0);
var code = tr.values().at('Code');
r.resumeVal(code);
return;
}
r.resumeVal(undefined);
}, e => {
TDev.RT.Time.log('error while detecting language');
r.resumeVal(undefined);
});
};
TDev.RT.MicrosoftTranslator.speak = function (lang, text) {
if (lang.length == 0 || text.length == 0) return undefined;
if (!TDev.RT.ApiManager.microsoftTranslatorClientId ||
!TDev.RT.ApiManager.microsoftTranslatorClientSecret) {
TDev.RT.Time.log('Missing Microsoft Translator Client ID and Client Secret. Please edit /js/apikeys.js.');
return undefined;
}
var url = 'http://api.microsofttranslator.com/V2/Http.svc/Speak?'
+ 'language=' + encodeURIComponent(lang)
+ '&text=' + encodeURIComponent(text)
+ '&format=' + encodeURIComponent('audio/mp3')
+ '&options=MaxQuality';
var snd = TDev.RT.Sound.mk(url, TDev.RT.SoundUrlTokenDomain.MicrosoftTranslator, 'audio/mp4');
return snd;
}
}
function initAsync() : Promise
{
return init2Async();
}
function init2Async() : Promise
{
Ticker.disable();
tick(Ticks.mainInit);
Util.initHtmlExtensions();
Util.initGenericExtensions();
initEditor();
RT.RTValue.initApis();
if (Browser.webRunner)
initWebRunnerApis();
else if (Browser.isCompiledApp)
initCompiledApp();
var h = new HistoryMgr();
window.addEventListener("hashchange", Util.catchErrors("hashchange", function (ev) {
h.hashChange();
}), false);
window.addEventListener("popstate", Util.catchErrors("popState", function (ev) {
if (h.popState) {
h.popState(ev);
}
}), false);
runnerHost = new RunnerHost();
runnerHost.currentGuid = (<any>window).webAppGuid || "6B4CD5BD-8C23-458D-9422-E329520060AE";
window.addEventListener("resize", Util.catchErrors("windowResize", () => {
SizeMgr.applySizes();
runnerHost.currentRt.forcePageRefresh();
runnerHost.publishSizeUpdate();
}));
return runnerHost.runAsync();
}
function initJs()
{
window.onload = Util.catchErrors("windowOnLoad", () => {
initAsync().done();
});
}
export function globalInit()
{
window.onerror = (errMsg, url, lineNumber) => {
Util.log("error " + lineNumber + ":" + errMsg);
return false;
};
if ((<any>TDev).isWebserviceOnly) {
Util.navigateInWindow((<any>window).errorUrl + "#webservice")
return;
}
var cfg = (<any>window).tdConfig;
if (cfg) Object.keys(cfg).forEach(k => Cloud.config[k] = cfg[k]);
(<any>window).rootUrl = Cloud.config.rootUrl;
TDev.Browser.isCompiledApp = true;
TDev.Browser.detect();
Ticker.fillEditorInfoBugReport = (b: BugReport) => {
try {
b.currentUrl = "runner";
b.scriptId = "";
b.userAgent = Browser.isNodeJS ? "node" : window.navigator.userAgent;
b.resolution = "";
} catch (e) {
//debugger;
}
};
Runtime.initialUrl = document.URL
if (Browser.isNodeJS) {
if ((<any>TDev.RT).Node)
((<any>TDev.RT).Node).setup()
} else if (Browser.inCordova) {
TDev.RT.Cordova.setup(() => initAsync().done())
} else {
initJs();
}
}
export module RunnerSettings
{
// specified when baking the app
var _appid: string = undefined;
var _storeid: string = undefined;
export var showTermsOfUse = false;
export var showFeedback = false;
export var showSettings = false;
export var privacyStatement = "";
export var privacyStatementUrl = "";
export var termsOfUse = "";
export var termsOfUseUrl = "";
export var title = "";
export var author = "";
export var description = "";
export var isGame = false;
export function agreeTermsAsync(): Promise {
Util.log('checking agreed terms...');
if (!termsOfUseUrl && !privacyStatementUrl) return Promise.as();
var agreed = !!RuntimeSettings.readSetting("td.agreed.termsofuse");
if (agreed) return Promise.as();
Util.log('asking user to agree terms...');
return new Promise((onSuccess, onError, onProgress) => {
var m = new ModalDialog();
m.onDismiss = () => {
RuntimeSettings.storeSetting("td.agreed.termsofuse", true);
onSuccess(undefined);
}
m.canDismiss = false;
m.fullWhite();
m.addHTML("<div class='wall-dialog-body'>To use this app, you must agree to the <a href='" + RunnerSettings.termsOfUseUrl + "'>Terms of use</a> and <a href='" + RunnerSettings.termsOfUseUrl + "'>Privacy Statement</a>.</div>");
m.add(div('wall-dialog-buttons', HTML.mkButton(lf("I Agree"), () => {
m.canDismiss = true;
m.dismiss();
})));
m.show();
});
}
export function showPrivacyStatementDialog()
{
var m = new ModalDialog();
m.add(div('wall-dialog-header', lf("privacy statement")));
m.add(div('wall-dialog-body', RunnerSettings.privacyStatement));
m.setScroll()
m.addOk();
m.show();
}
export function showTermsOfUseDialog()
{
var m = new ModalDialog();
m.add(div('wall-dialog-header', lf("terms of use")));
m.add(div('wall-dialog-body', RunnerSettings.termsOfUse));
m.setScroll()
m.addOk();
m.show();
}
export function showAboutDialog() {
var m = new ModalDialog();
m.add(div('wall-dialog-header', lf("about")));
m.add(div('wall-dialog-body', RunnerSettings.title));
m.add(div('wall-dialog-body', lf("by {0}", RunnerSettings.author)));
m.add(div('wall-dialog-body', RunnerSettings.description));
m.setScroll()
m.addOk();
m.show();
}
export function showSettingsDialog() {
var locationcb = HTML.mkCheckBox(lf("access and use your location"), (b) => RuntimeSettings.setLocation(b), RuntimeSettings.location());
var soundcb = HTML.mkCheckBox(lf("sounds"), (b) => RuntimeSettings.setSounds(b), RuntimeSettings.sounds());
var m = new ModalDialog();
m.add(div('wall-dialog-header', lf("settings")));
m.add(div('wall-dialog-body', locationcb));
m.add(div('wall-dialog-body', soundcb));
m.addOk();
m.show();
}
var _launchReported = false;
export function reportLaunch() {
if (_appid && window.navigator.onLine && !_launchReported) {
TDev.RT.Bazaar.storeidAsync()
.done((sid : string) => {
if (sid) {
// analytics
var url = Cloud.getPrivateApiUrl("app/" + encodeURIComponent(_appid)
+ "/" + encodeURIComponent(userid())
+ "/launch/" + encodeURIComponent(sid) + "?store=" + encodeURIComponent(_storeid));
Util.log('runner: report launch ' + url);
var req = TDev.RT.WebRequest.mk(url, undefined);
req.show_notifications(false);
req.sendAsync().done(() => {
_launchReported = true;
}, e => {
Util.log('runner: launch report failed');
});
}
}, e => {});
}
}
export function launch(appid: string, storeid: string) {
_appid = appid || "invalid";
_storeid = storeid || "unknown";
RunnerSettings.reportLaunch();
// override leaderboards
(<any>TDev.RT.Bazaar).loadLeaderboardItemsAsync = function (scriptId: string) {
return Promise.as([]);
};
(<any>TDev.RT.Bazaar).leaderboard_score = function (r: ResumeCtx) {
if (window.navigator.onLine && (Browser.webRunner || Browser.webAppImplicit)) {
var url = Cloud.getPrivateApiUrl("app/" + encodeURIComponent(_appid)
+ "/" + encodeURIComponent(userid()) + "/leaderboardscored");
var req = TDev.RT.WebRequest.mk(url, undefined);
req.sendAsync()
.done((resp: TDev.RT.WebResponse) => {
updateScoreFromResponse(resp.content_as_json());
r.resumeVal(RunnerSettings.score());
}, (e) => r.resumeVal(RunnerSettings.score()));
}
else
r.resumeVal(RunnerSettings.score());
};
(<any>TDev.RT.Bazaar).post_leaderboard_score = function (score: number, r: ResumeCtx) {
var curr = RunnerSettings.score();
if (score < curr) {
r.resume();
}
else {
setScore(score);
if (window.navigator.onLine && (Browser.webRunner || Browser.webAppImplicit)) {
var url = Cloud.getPrivateApiUrl("app/" + encodeURIComponent(_appid)
+ "/" + encodeURIComponent(userid()) + "/leaderboard");
var req = TDev.RT.WebRequest.mk(url, undefined);
req.set_method('post');
req.set_content(JSON.stringify({ kind: "leaderboardscore", score: score }));
req.sendAsync()
.done((resp: TDev.RT.WebResponse) => {
updateScoreFromResponse(resp.content_as_json());
r.resume();
}, (e) => r.resume());
} else {
r.resume();
}
}
};
(<any>TDev.RT.Bazaar).post_leaderboard_to_wall = function (r: ResumeCtx) //: void
{
if (!Browser.webRunner && !Browser.webAppImplicit) {
TDev.RT.App.restart("", r);
return;
}
var leaderboardDiv = div('item', [div('item-title', lf("leaderboards"))]);
var rt = r.rt;
if (window.navigator.onLine) {
r.progress(lf("Loading leaderboards..."));
var url = Cloud.getPrivateApiUrl("app/" + encodeURIComponent(_appid) + "/" + encodeURIComponent(userid()) + "/leaderboard");
var request = TDev.RT.WebRequest.mk(url, undefined);
request.sendAsync()
.done((response: TDev.RT.WebResponse) =>
{
var json = response.content_as_json();
if (json) {
var items = json.field('items');
if (items) {
for (var i = 0; i < items.count(); ++i) {
var item = items.at(i);
if (item.string('kind') === 'leaderboardscore') {
var userid = item.string('userid');
var username = item.string('username');
var userscore = (item.number('score') || 0).toString();
var time = Util.timeSince(item.number('time'));
var imgDiv = div('leaderboard-img');
imgDiv.innerHTML = TDev.Util.svgGravatar(userid);
var scoreDiv = div('item leaderboard-item', [
imgDiv,
div('leaderboards-score', userscore),
div('leaderboard-center', [
div('item-title', username),
div('item-subtle', time)
])
]);
leaderboardDiv.appendChild(scoreDiv);
}
}
}
}
rt.postBoxedHtml(leaderboardDiv, rt.current.pc);
r.resume();
});
} else {
rt.postText(lf("Please connect to internet to see the leaderboard."), rt.current.pc);
r.resume();
}
}
}
function updateScoreFromResponse(response : TDev.RT.JsonObject) {
if (response) {
var score = response.number('score');
if (score)
RunnerSettings.setScore(score);
}
}
export function score() : Number {
return Number(RuntimeSettings.readSetting("td.score") || 0);
}
export function setScore(score: Number) {
if (score > RunnerSettings.score())
RuntimeSettings.storeSetting("td.score", score);
}
export function userid() : string {
var userid = RuntimeSettings.readSetting("td.userid");
if (!userid) {
// need new user id
userid = TDev.Util.guidGen();
RuntimeSettings.storeSetting("td.userid", userid);
}
return userid;
}
}
}
TDev.globalInit(); | the_stack |
import React, { useState, useMemo, useEffect, useLayoutEffect } from "react";
import { OrgComponent } from "@ui_types";
import { Api, Rbac } from "@core/types";
import { stripUndefinedRecursive } from "@core/lib/utils/object";
import { Link } from "react-router-dom";
import * as g from "@core/lib/graph";
import * as R from "ramda";
import {
DragDropContext,
Droppable,
Draggable,
DroppableProvided,
} from "react-beautiful-dnd";
import { SmallLoader, SvgImage } from "@images";
import { MIN_ACTION_DELAY_MS } from "@constants";
import { wait } from "@core/lib/utils/wait";
import * as styles from "@styles";
import { logAndAlertError } from "@ui_lib/errors";
export const ManageOrgEnvironmentRoles: OrgComponent = (props) => {
const { graph, graphUpdatedAt } = props.core;
const currentUserId = props.ui.loadedAccountId!;
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, []);
const {
environmentRoles,
environmentRoleIds,
environmentRolesById,
environmentRoleSettingsById,
} = useMemo(() => {
const environmentRoles = g.graphTypes(graph).environmentRoles;
const environmentRolesById = R.indexBy(R.prop("id"), environmentRoles);
return {
environmentRoles,
environmentRoleIds: environmentRoles.map(R.prop("id")),
environmentRolesById,
environmentRoleSettingsById: R.mapObjIndexed(
R.prop("settings"),
environmentRolesById
),
};
}, [graphUpdatedAt, currentUserId]);
const [
updatingEnvironmentRoleSettingsById,
setUpdatingEnvironmentRoleSettingsById,
] = useState<Record<string, true>>({});
const [
environmentRoleSettingsByIdState,
setEnvironmentRoleSettingsByIdState,
] = useState(environmentRoleSettingsById);
const [deletingEnvironmentRolesById, setDeletingEnvironmentRolesById] =
useState<Record<string, true>>({});
const [awaitingMinDelayByRoleId, setAwaitingMinDelayByRoleId] = useState<
Record<string, boolean>
>({});
const [order, setOrder] = useState<string[]>(environmentRoleIds);
const [updatingOrder, setUpdatingOrder] = useState(false);
const orderedEnvironmentRoles = useMemo(
() => R.sortBy(({ id }) => order.indexOf(id), environmentRoles),
[order, environmentRoles]
);
useEffect(() => {
const isEqual = R.equals(environmentRoleIds, order);
if (updatingOrder) {
if (isEqual && !Object.values(awaitingMinDelayByRoleId).some(Boolean)) {
setUpdatingOrder(false);
}
} else {
setOrder(environmentRoleIds);
}
}, [environmentRoleIds, JSON.stringify(awaitingMinDelayByRoleId)]);
useEffect(() => {
const toOmitDeleting: string[] = [];
for (let id in deletingEnvironmentRolesById) {
if (!environmentRolesById[id]) {
toOmitDeleting.push(id);
}
}
if (toOmitDeleting.length > 0) {
setDeletingEnvironmentRolesById(
R.omit(toOmitDeleting, deletingEnvironmentRolesById)
);
}
const toOmitSettings: string[] = [];
for (let id in environmentRoleSettingsByIdState) {
if (!environmentRolesById[id]) {
toOmitSettings.push(id);
}
}
if (toOmitSettings.length > 0) {
setEnvironmentRoleSettingsByIdState(
R.omit(toOmitSettings, environmentRoleSettingsByIdState)
);
}
}, [environmentRolesById, JSON.stringify(awaitingMinDelayByRoleId)]);
const environmentRoleSettingsUpdated = (roleId: string) => {
const environmentRole = environmentRolesById[roleId];
const settings = environmentRole.settings;
return !R.equals(
stripUndefinedRecursive(settings),
stripUndefinedRecursive(environmentRoleSettingsByIdState[roleId])
);
};
const dispatchEnvironmentSettingsUpdate = () => {
if (
Object.values(updatingEnvironmentRoleSettingsById).some(Boolean) ||
Object.values(deletingEnvironmentRolesById).some(Boolean) ||
updatingOrder
) {
return;
}
for (let roleId in environmentRoleSettingsByIdState) {
if (!environmentRoleSettingsUpdated(roleId)) {
continue;
}
setUpdatingEnvironmentRoleSettingsById({ [roleId]: true });
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: true,
});
wait(MIN_ACTION_DELAY_MS).then(() =>
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: false,
})
);
const environmentRole = environmentRolesById[roleId];
props
.dispatch({
type: Api.ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE_SETTINGS,
payload: {
id: environmentRole.id,
settings: environmentRoleSettingsByIdState[roleId],
},
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem updating environment role settings.`,
(res.resultAction as any)?.payload
);
}
});
}
};
useEffect(() => {
dispatchEnvironmentSettingsUpdate();
}, [JSON.stringify(environmentRoleSettingsByIdState)]);
useEffect(() => {
for (let roleId in environmentRoleSettingsByIdState) {
if (
updatingEnvironmentRoleSettingsById[roleId] &&
!awaitingMinDelayByRoleId[roleId]
) {
setUpdatingEnvironmentRoleSettingsById(
R.omit([roleId], updatingEnvironmentRoleSettingsById)
);
}
}
}, [
JSON.stringify(environmentRoleSettingsById),
JSON.stringify(awaitingMinDelayByRoleId),
]);
const reorder = (startIndex: number, endIndex: number) => {
if (
Object.values(updatingEnvironmentRoleSettingsById).some(Boolean) ||
Object.values(deletingEnvironmentRolesById).some(Boolean)
) {
return;
}
const res = Array.from(order);
const [removed] = res.splice(startIndex, 1);
res.splice(endIndex, 0, removed);
if (!R.equals(order, res)) {
setOrder(res);
setUpdatingOrder(true);
for (let roleId in environmentRoleSettingsById) {
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: true,
});
wait(MIN_ACTION_DELAY_MS).then(() =>
setAwaitingMinDelayByRoleId({
...awaitingMinDelayByRoleId,
[roleId]: false,
})
);
}
const newOrder = R.map(parseInt, R.invertObj(res)) as Record<
string,
number
>;
props
.dispatch({
type: Api.ActionType.RBAC_REORDER_ENVIRONMENT_ROLES,
payload: newOrder,
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem reoredering environment roles.`,
(res.resultAction as any)?.payload
);
}
});
}
};
const renderEnvironmentRole = (role: Rbac.EnvironmentRole, i: number) => {
const updating = Boolean(updatingEnvironmentRoleSettingsById[role.id]);
const autoCommit = environmentRoleSettingsByIdState[role.id]?.autoCommit;
if (deletingEnvironmentRolesById[role.id]) {
return (
<div>
<h4>
{role.name} <SmallLoader />
</h4>
</div>
);
}
return (
<div>
<Draggable key={role.id} draggableId={role.id} index={i}>
{(provided, snapshot) => {
const renderActions = () => {
if (
Object.values(updatingEnvironmentRoleSettingsById).some(
Boolean
) ||
Object.values(deletingEnvironmentRolesById).some(Boolean) ||
updatingOrder
) {
return;
}
return (
<div className="actions">
{role.isDefault ? (
""
) : (
<span
className="delete"
onClick={() => {
if (
Object.values(
updatingEnvironmentRoleSettingsById
).some(Boolean) ||
Object.values(deletingEnvironmentRolesById).some(
Boolean
) ||
updatingOrder
) {
return;
}
if (
confirm(
`Delete the ${role.name} Environment across all your organization's apps and blocks?`
)
) {
setDeletingEnvironmentRolesById({
...deletingEnvironmentRolesById,
[role.id]: true,
});
props
.dispatch({
type: Api.ActionType.RBAC_DELETE_ENVIRONMENT_ROLE,
payload: { id: role.id },
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem deleting the environment role.`,
(res.resultAction as any)?.payload
);
}
});
}
}}
>
<SvgImage type="x" />
<span>Delete</span>
</span>
)}
<Link
className="edit"
to={props.match.url.replace(
/\/environment-settings$/,
"/environment-settings/environment-role-form/" + role.id
)}
>
<SvgImage type="edit" />
<span>Edit {role.name} Details</span>
</Link>
<span
className="reorder"
{...(provided.dragHandleProps ?? {})}
>
<SvgImage type="reorder" />
<span>Drag To Change Default Order</span>
</span>
</div>
);
};
return (
<div ref={provided.innerRef} {...provided.draggableProps}>
<h4>
{role.name}
{updating || updatingOrder ? (
<SmallLoader />
) : (
renderActions()
)}
</h4>
{role.description ? (
<div className="field no-margin">
<p>{role.description}</p>
</div>
) : (
""
)}
{/* <div
className={
"field checkbox" +
(updating || updatingOrder ? " disabled" : "") +
(autoCommit ? " selected" : "")
}
onClick={() =>
setEnvironmentRoleSettingsByIdState({
...environmentRoleSettingsByIdState,
[role.id]: stripUndefinedRecursive({
...(environmentRoleSettingsByIdState[role.id] ?? {}),
autoCommit: !autoCommit,
}),
})
}
>
<label>Default Auto-Commit On Change</label>
<input type="checkbox" checked={autoCommit} />
</div> */}
</div>
);
}}
</Draggable>
</div>
);
};
return (
<div className={styles.OrgContainer}>
<h3>
Manage Org <strong>Environments</strong>
</h3>
<DragDropContext
onDragEnd={(res) => {
// dropped outside the list
if (!res.destination) {
return;
}
reorder(res.source.index, res.destination.index);
}}
>
<Droppable droppableId="droppable">
{(provided, snapshot) => (
<div {...provided.droppableProps} ref={provided.innerRef}>
{orderedEnvironmentRoles.map(renderEnvironmentRole)}
{provided.placeholder}
</div>
)}
</Droppable>
</DragDropContext>
<div className="buttons">
<Link
className="primary"
to={props.match.url.replace(
/\/environment-settings$/,
"/environment-settings/environment-role-form"
)}
>
Add Base Environment
</Link>
</div>
</div>
);
}; | the_stack |
import { CancelablePromise } from './util/promise';
import { indexAsync } from './api/processor';
import {
DltFilterConf,
DltLogLevel,
IIndexDltParams,
dltOverSocket,
ISocketConfig,
IMulticastInfo,
indexPcapDlt,
pcap2dlt
} from './api/dlt';
import indexer, { DLT, Merge, Progress } from './index';
import { ITicks, IChunk, AsyncResult, INeonNotification, IDiscoverItem, IMergerItemOptions } from './util/progress';
import * as log from 'loglevel';
import { IConcatFilesParams, ConcatenatorInput } from './api/merger';
import { StdoutController } from 'custom.stdout';
import { Detect } from '../../../common/interfaces/index';
import * as fs from 'fs';
import { createGrabberAsync } from './api/grabber';
import { discoverTimespanAsync, checkFormat } from './api/timestamps';
const stdout = new StdoutController(process.stdout, { handleStdoutGlobal: true });
export const examplePath: String = '/Users/muellero/tmp/logviewer_usecases';
// testing
function measure({ desc, f }: { desc: String; f: () => void }) {
const hrstart = process.hrtime();
try {
f();
} catch (error) {
log.error('error %s: %s', desc, error);
}
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.info('Execution time %s : %dms', desc, ms);
}
export function testCallMergeFiles(mergeConf: string, out: string) {
log.setDefaultLevel(log.levels.WARN);
log.debug(`calling testCallMergeFiles with mergeConf: ${mergeConf}, out: ${out}`);
const bar = stdout.createProgressBar({ caption: 'merging files', width: 60 });
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onNotification = (notification: INeonNotification) => {
log.debug('TTT: testCallMergeFiles: received notification:' + JSON.stringify(notification));
};
log.debug('before measure');
measure({
desc: 'TTT: merge with config: ' + mergeConf + ', output: ' + out,
f: () => {
let merged_lines: number = 0;
let onResult = (res: IChunk) => {
log.debug('rowsEnd= ' + JSON.stringify(res));
merged_lines = res.rowsEnd;
};
log.debug('inside f measure');
const contents = fs.readFileSync(mergeConf, 'utf8');
log.debug(`contents is: ${contents}`);
const config: Array<IMergerItemOptions> = JSON.parse(contents);
log.debug(`config is: ${JSON.stringify(config)}`);
const filePath = require('path').dirname(mergeConf);
const absolutePathConfig: Array<IMergerItemOptions> = config.map((input: IMergerItemOptions) => {
log.debug(`input is: ${JSON.stringify(input)}`);
input.path = require('path').resolve(filePath, input.path);
return input;
});
log.debug(`absolutePathConfig: ${JSON.stringify(absolutePathConfig)}`);
const promise: CancelablePromise<
void,
void,
Merge.TMergeFilesEvents,
Merge.TMergeFilesEventObject
> = indexer
.mergeFilesAsync(absolutePathConfig, out, {
append: true
})
.then(() => {
log.debug('TTT: done');
log.debug(`merged_lines: ${merged_lines}`);
})
.catch((error: Error) => {
log.debug(`Fail to merge due error: ${error.message}`);
})
.on('result', (event: IChunk) => {
onResult(event);
})
.on('progress', (event: ITicks) => {
onProgress(event);
})
.on('notification', (event: INeonNotification) => {
onNotification(event);
});
}
});
}
export function testCallConcatFiles(concatConfig: string, out: string, chunk_size: number) {
log.setDefaultLevel(log.levels.WARN);
const bar = stdout.createProgressBar({ caption: 'concatenating files', width: 60 });
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onResult = (res: IChunk) => {
log.debug('TTT: concatenated res: ' + JSON.stringify(res));
};
let onNotification = (notification: INeonNotification) => {
log.debug('TTT: testCallConcatFiles: received notification:' + JSON.stringify(notification));
};
measure({
desc: 'TTT: concatenate with config: ' + concatConfig + ', output: ' + out,
f: () => {
const concatFilesParams: IConcatFilesParams = {
configFile: concatConfig,
out,
append: false
};
const contents = fs.readFileSync(concatConfig, 'utf8');
const config: Array<ConcatenatorInput> = JSON.parse(contents);
const filePath = require('path').dirname(concatConfig);
const absolutePathConfig: Array<ConcatenatorInput> = config.map((input: ConcatenatorInput) => {
input.path = require('path').resolve(filePath, input.path);
return input;
});
const promise: CancelablePromise<
void,
void,
Merge.TConcatFilesEvents,
Merge.TConcatFilesEventObject
> = indexer
.concatFilesAsync(absolutePathConfig, out, {
append: true,
chunk_size
})
.then(() => {
log.debug('TTT: done ');
// progressBar.update(1.0);
})
.catch((error: Error) => {
log.debug(`Fail to merge due error: ${error.message}`);
})
.on('result', (event: IChunk) => {
onResult(event);
})
.on('progress', (event: ITicks) => {
onProgress(event);
})
.on('notification', (event: INeonNotification) => {
onNotification(event);
});
}
});
}
export function testCheckFormatString(
input: string,
flags: Detect.ICheckFormatFlags = { miss_year: false, miss_month: false, miss_day: false }
) {
log.setDefaultLevel(log.levels.DEBUG);
log.debug(`calling testCheckFormatString with ${input}`);
const hrstart = process.hrtime();
try {
let onProgress = (ticks: ITicks) => {
log.trace('progress: ' + Math.round(100 * ticks.ellapsed / ticks.total) + '%');
};
let onNotification = (notification: INeonNotification) => {
log.debug('testCheckFormatString: received notification:' + JSON.stringify(notification));
};
checkFormat(input, flags)
.then(() => {
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.info('Execution time for format check : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.IFormatCheckResult) => {
log.debug('received ' + JSON.stringify(event));
log.debug('event.FormatInvalid: ' + event.FormatInvalid);
log.debug('event.FormatRegex: ' + event.FormatRegex);
// log.debug('event.format.Err ' + JSON.stringify(event.format?.Err));
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (event: Progress.INeonNotification) => {
onNotification(event);
});
} catch (error) {
log.error('error %s', error);
}
}
export function testCallDltStats(file: string) {
log.setDefaultLevel(log.levels.DEBUG);
const hrstart = process.hrtime();
try {
let onProgress = (ticks: ITicks) => {
log.trace('progress: ' + JSON.stringify(ticks));
};
let onConf = (conf: DLT.StatisticInfo) => {
log.debug('testCallDltStats.onConf:');
log.debug('conf.app_ids: ' + JSON.stringify(conf.app_ids));
log.debug('conf.ecu_ids: ' + JSON.stringify(conf.ecu_ids));
log.debug('conf.context_ids: ' + JSON.stringify(conf.context_ids));
};
measure({
desc: 'stats for ' + file,
f: () => {
indexer
.dltStatsAsync(file)
.then(() => {
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.debug('COMPLETELY DONE');
log.info('Execution time for getting DLT stats : %dms', ms);
})
.catch((error: Error) => {
log.warn(`Failed with error: ${error.message}`);
})
.on('config', (event: DLT.StatisticInfo) => {
onConf(event);
})
.on('notification', (event: INeonNotification) => {
log.debug(`notification: ${JSON.stringify(event)}`);
})
.on('progress', (ticks: Progress.ITicks) => {
onProgress(ticks);
});
}
});
} catch (error) {
log.error('error %s', error);
}
}
export function testDiscoverTimestampAsync(files: string[]) {
log.setDefaultLevel(log.levels.DEBUG);
log.debug(`calling testDiscoverTimestampAsync with ${files}`);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'discover timestamp', width: 60 });
try {
let onProgress = (ticks: ITicks) => {
log.debug('onProgress');
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onNotification = (notification: INeonNotification) => {
log.debug('testDiscoverTimestampAsync: received notification:' + JSON.stringify(notification));
};
let items: IDiscoverItem[] = files.map((file: string) => {
return {
path: file,
format_string: 'YYYY-MM-DD hh:mm:ss.s'
};
});
discoverTimespanAsync(items)
.then(() => {
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
bar.update(100);
log.debug('COMPLETELY DONE');
log.info('Execution time for indexing : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.ITimestampFormatResult) => {
log.debug('received ' + JSON.stringify(event));
log.debug('event.format ' + JSON.stringify(event.format));
// log.debug('event.format.Ok ' + JSON.stringify(event.format?.Ok));
// log.debug('event.format.Err ' + JSON.stringify(event.format?.Err));
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (event: Progress.INeonNotification) => {
onNotification(event);
});
} catch (error) {
log.error('error %s', error);
}
}
export function testConvertPcapToDlt(input: string) {
log.setDefaultLevel(log.levels.DEBUG);
log.debug(`calling testConvertPcapToDlt with ${input}`);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'convert pcap2dlt', width: 60 });
try {
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onNotification = (notification: INeonNotification) => {
log.debug('testConvertPcapToDlt: received notification:' + JSON.stringify(notification));
};
let output = `${input}.out.dlt`
pcap2dlt(input, output)
.then(() => {
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
bar.update(100);
log.info('Execution time for conversion : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (event: Progress.INeonNotification) => {
onNotification(event);
});
} catch (error) {
log.error('error %s', error);
}
}
class IndexingHelper {
bar: any;
hrstart: [number, number];
notificationCount: number = 0;
constructor(name: string) {
this.bar = stdout.createProgressBar({ caption: name, width: 60 });
this.hrstart = process.hrtime();
// this.onProgress = this.onProgress.bind(this);
// this.onChunk = this.onChunk.bind(this);
// this.onNotification = this.onNotification.bind(this);
// this.done = this.done.bind(this);
}
public onProgress = (ticks: ITicks) => {
this.bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
public onChunk = (_chunk: IChunk) => {};
public onNotification = (notification: INeonNotification) => {
this.notificationCount += 1;
};
public done = (x: AsyncResult) => {
this.bar.update(100);
const hrend = process.hrtime(this.hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.debug(`COMPLETELY DONE (last result was: "${AsyncResult[x]}") (notifications: ${this.notificationCount})`);
log.info('Execution time for indexing : %dms', ms);
};
}
export function testCancelledAsyncDltIndexing(
fileToIndex: string,
outPath: string,
timeoutMs: number,
fibexPath?: string
) {
log.setDefaultLevel(log.levels.WARN);
const bar = stdout.createProgressBar({ caption: 'dlt indexing', width: 60 });
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onNotification = (notification: INeonNotification) => {
log.debug('test: received notification:' + notification);
};
let helper = new IndexingHelper('dlt async indexing');
const filterConfig: DltFilterConf = {
min_log_level: DltLogLevel.Debug,
app_id_count: 0,
context_id_count: 0,
};
const dltParams: IIndexDltParams = {
dltFile: fileToIndex,
filterConfig,
fibex: { fibex_file_paths: [] },
tag: 'TAG',
out: outPath,
chunk_size: 500,
append: false,
stdout: false,
statusUpdates: true
};
const task = indexer
.indexDltAsync(dltParams)
.then(() => {
clearTimeout(timerId);
helper.done(AsyncResult.Completed);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.canceled(() => {
log.debug(`Operation was canceled`);
})
.on('chunk', (event: Progress.IChunk) => {
helper.onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
helper.onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
helper.onNotification(notification);
});
const timerId = setTimeout(function() {
log.debug('cancelling operation after timeout');
task.abort();
}, 500);
}
export function testDltIndexingAsync(fileToIndex: string, outPath: string, timeoutMs: number, fibexPath?: string) {
log.setDefaultLevel(log.levels.DEBUG);
log.debug(`testDltIndexingAsync for ${fileToIndex} (out: "${outPath}")`);
let helper = new IndexingHelper('dlt async indexing');
try {
const filterConfig: DltFilterConf = {
min_log_level: DltLogLevel.Warn,
app_ids: [
'Cdng',
'Coor',
'LOGC',
'UTC',
'Hlth',
'FuSa',
'AM',
'EM',
'DEM',
'Mdtr',
'-NI-',
'Omc',
'Bs',
'MON',
'psn',
'SYS',
'DltL',
'Heat',
'DR',
'Fasi',
'DET',
'psl',
'DLTD',
'CryD',
'PTS',
'VSom',
'PwrM',
'PTC',
'MTSC',
'udsd',
'cras',
'Vin',
'Stm',
'StdD',
'Diag',
'FRay',
'Bsd3',
'Para',
'Bsd2',
'PSEL',
'Darh',
'Bsd1',
'TEMP',
'Dlog',
'FOSE',
'NONE',
'Plan',
'MSM',
'Perc',
'SysT',
'SINA',
'DA1'
],
app_id_count: 52,
context_id_count: 0,
};
const fibex_paths = fibexPath === undefined ? [] : [ fibexPath ];
const dltParams: IIndexDltParams = {
dltFile: fileToIndex,
filterConfig,
fibex: { fibex_file_paths: fibex_paths },
tag: 'TAG',
out: outPath,
chunk_size: 500,
append: false,
stdout: false,
statusUpdates: true
};
log.debug('calling indexDltAsync with fibex: ' + fibexPath);
const promise = indexer.indexDltAsync(dltParams);
promise
.then(() => {
clearTimeout(timerId);
helper.done(AsyncResult.Completed);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.canceled(() => {
log.debug(`Operation was canceled`);
})
.on('chunk', (event: Progress.IChunk) => {
helper.onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
helper.onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
helper.onNotification(notification);
});
const timerId = setTimeout(function() {
log.debug('cancelling operation after timeout');
promise.abort();
}, timeoutMs);
} catch (error) {
log.debug('error %s', error);
}
log.debug('done with dlt test');
}
export function testIndexingPcap(fileToIndex: string, outPath: string) {
log.setDefaultLevel(log.levels.WARN);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'index file', width: 60 });
try {
let chunks: number = 0;
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onChunk = (chunk: IChunk) => {
chunks += 1;
if (chunks % 100 === 0) {
process.stdout.write('.');
}
};
let onNotification = (notification: INeonNotification) => {
log.debug('testIndexingPcap: received notification:' + JSON.stringify(notification));
};
const filterConfig: DltFilterConf = {
min_log_level: DltLogLevel.Debug,
app_id_count: 0,
context_id_count: 0,
};
const dltParams: IIndexDltParams = {
dltFile: fileToIndex,
filterConfig,
fibex: { fibex_file_paths: [] },
tag: 'TAG',
out: outPath,
chunk_size: 500,
append: false,
stdout: false,
statusUpdates: true
};
indexPcapDlt(dltParams)
.then(() => {
bar.update(100);
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.debug('COMPLETELY DONE');
log.info('Execution time for indexing : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.IChunk) => {
onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
onNotification(notification);
});
} catch (error) {
log.error('error %s', error);
}
}
export function testIndexingAsync(inFile: string, outPath: string, chunkSize: number) {
log.setDefaultLevel(log.levels.DEBUG);
log.debug(`testIndexingAsync for ${inFile} (chunkSize: ${chunkSize}, type: ${typeof chunkSize})`);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'index file', width: 60 });
try {
let chunks: number = 0;
let onProgress = (ticks: ITicks) => {
log.trace('progress: ' + Math.round(100 * ticks.ellapsed / ticks.total) + '%');
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onChunk = (chunk: IChunk) => {
// log.debug(`onChunk: ${JSON.stringify(chunk)}`)
chunks += 1;
if (chunks % 100 === 0) {
// process.stdout.write('.');
}
};
let onNotification = (notification: INeonNotification) => {
log.debug('testIndexingAsync: received notification:' + JSON.stringify(notification));
};
indexAsync(inFile, outPath, 'TAG', { chunkSize })
.then(() => {
bar.update(100);
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
log.debug('COMPLETELY DONE');
log.info('Execution time for indexing : %dms', ms);
const hrstart2 = process.hrtime();
// 2nd time
indexAsync(inFile, outPath, 'TAG', { chunkSize })
.then(() => {
bar.update(100);
const hrend2 = process.hrtime(hrstart2);
const ms = Math.round(hrend2[0] * 1000 + hrend2[1] / 1000000);
log.debug('COMPLETELY DONE 2nd time');
log.info('Execution time for indexing : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.IChunk) => {
onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
onNotification(notification);
});
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.IChunk) => {
onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
onNotification(notification);
});
} catch (error) {
log.error('error %s', error);
}
}
export function testSocketDlt(outPath: string) {
log.setDefaultLevel(log.levels.WARN);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'index file', width: 60 });
try {
let chunks: number = 0;
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onChunk = (chunk: IChunk) => {
chunks += 1;
if (chunks % 100 === 0) {
process.stdout.write('.');
}
};
let onNotification = (notification: INeonNotification) => {
log.debug('testSocketDlt: received notification:' + JSON.stringify(notification));
};
const filterConfig: DltFilterConf = {
min_log_level: DltLogLevel.Debug,
app_id_count: 0,
context_id_count: 0,
};
const multicastInfo: IMulticastInfo = {
multiaddr: '234.2.2.2',
interface: undefined
};
const sockConf: ISocketConfig = {
multicast_addr: [{
multiaddr: '234.2.2.2',
interface: undefined,
}],
bind_addr: '0.0.0.0',
port: '8888',
target: 'Udp',
};
const session_id = `dlt_${new Date().toISOString()}`;
const promise = dltOverSocket(
session_id,
{
filterConfig,
fibex: { fibex_file_paths: [] },
tag: 'TAG',
out: outPath,
stdout: false,
statusUpdates: false
},
sockConf
)
.then(() => {
bar.update(100);
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
clearTimeout(timerId);
log.debug('COMPLETELY DONE');
log.info('socket dlt ended after: %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.on('chunk', (event: Progress.IChunk) => {
onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
onNotification(notification);
});
const timerId = setTimeout(function() {
log.debug('cancelling operation after timeout');
promise.abort();
}, 1000);
} catch (error) {
log.error('error %s', error);
}
}
export function testCancelledAsyncIndexing(fileToIndex: string, outPath: string) {
log.setDefaultLevel(log.levels.WARN);
const hrstart = process.hrtime();
const bar = stdout.createProgressBar({ caption: 'concatenating files', width: 60 });
let onProgress = (ticks: ITicks) => {
bar.update(Math.round(100 * ticks.ellapsed / ticks.total));
};
let onNotification = (notification: INeonNotification) => {
log.debug('test: received notification:' + notification);
};
let onChunk = (chunk: IChunk) => {};
const promise = indexAsync(fileToIndex, outPath, 'TAG', { chunkSize: 500 })
.then(() => {
const hrend = process.hrtime(hrstart);
const ms = Math.round(hrend[0] * 1000 + hrend[1] / 1000000);
clearTimeout(timerId);
log.debug('first event emitter task finished');
log.info('Execution time for indexing : %dms', ms);
})
.catch((error: Error) => {
log.debug(`Failed with error: ${error.message}`);
})
.canceled(() => {
log.debug(`Operation was canceled`);
})
.on('chunk', (event: Progress.IChunk) => {
onChunk(event);
})
.on('progress', (event: Progress.ITicks) => {
onProgress(event);
})
.on('notification', (notification: Progress.INeonNotification) => {
onNotification(notification);
});
const timerId = setTimeout(function() {
log.debug('cancelling operation after timeout');
promise.abort();
}, 500);
}
export function testGrabLinesInFile(path: string) {
log.setDefaultLevel(log.levels.DEBUG);
// if (process.env.NODE_ENV !== 'test') {
// addon.fibonacci(500000, (err: any, result: any) => {
// console.log('async result:');
// console.log(result);
// });
// console.log('computing fibonacci(500000) in background thread...');
// console.log('main thread is still responsive!');
// }
// return;
try {
const hrstart_create = process.hrtime();
createGrabberAsync(path).then((grabber) => {
const hrend_create = process.hrtime(hrstart_create);
const ms = Math.round(hrend_create[0] * 1000 + hrend_create[1] / 1000000);
log.info('time to create grabber: %dms', ms);
log.info('total lines in file: %d', grabber.total_entries());
const hrstart_index = process.hrtime();
grabber.create_metadata();
const hrend_index = process.hrtime(hrstart_index);
const ms_index = Math.round(hrend_index[0] * 1000 + hrend_index[1] / 1000000);
log.info('time to create metadata: %dms', ms_index);
log.info('total lines in file: %d', grabber.total_entries());
let entry_cnt = grabber.total_entries();
if (entry_cnt !== undefined) {
const hrstart = process.hrtime();
const start_line = entry_cnt - 1000;
const lines_to_grab = 200;
const lines = grabber.grab(start_line, lines_to_grab);
const hrend = process.hrtime(hrstart);
const us = Math.round(hrend[0] * 1000 + hrend[1] / 1000);
log.info('Execution time for grabbing %d lines from index %d: %dus', lines_to_grab, start_line, us);
let i = 0;
for (const line of lines) {
log.debug('line %d =-----> %s', start_line + i, line);
i += 1;
if (i > 5) {
break;
}
}
}
}).catch((e) => {
log.warn(`Error during grabbing: ${e}`);
});
log.info("waiting for grabber...");
} catch (error) {
log.warn('Error from RustGrabber: %s', error.message);
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export const CreateConversionSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "CreateConversionSettings",
modelProperties: {
settings: {
serializedName: "settings",
type: {
name: "Composite",
className: "AssetConversionSettings"
}
}
}
}
};
export const AssetConversionSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AssetConversionSettings",
modelProperties: {
inputSettings: {
serializedName: "inputLocation",
type: {
name: "Composite",
className: "AssetConversionInputSettings"
}
},
outputSettings: {
serializedName: "outputLocation",
type: {
name: "Composite",
className: "AssetConversionOutputSettings"
}
}
}
}
};
export const AssetConversionInputSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AssetConversionInputSettings",
modelProperties: {
storageContainerUrl: {
serializedName: "storageContainerUri",
required: true,
type: {
name: "String"
}
},
storageContainerReadListSas: {
serializedName: "storageContainerReadListSas",
type: {
name: "String"
}
},
blobPrefix: {
serializedName: "blobPrefix",
type: {
name: "String"
}
},
relativeInputAssetPath: {
serializedName: "relativeInputAssetPath",
required: true,
type: {
name: "String"
}
}
}
}
};
export const AssetConversionOutputSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AssetConversionOutputSettings",
modelProperties: {
storageContainerUrl: {
serializedName: "storageContainerUri",
required: true,
type: {
name: "String"
}
},
storageContainerWriteSas: {
serializedName: "storageContainerWriteSas",
type: {
name: "String"
}
},
blobPrefix: {
serializedName: "blobPrefix",
type: {
name: "String"
}
},
outputAssetFilename: {
serializedName: "outputAssetFilename",
type: {
name: "String"
}
}
}
}
};
export const Conversion: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Conversion",
modelProperties: {
conversionId: {
serializedName: "id",
required: true,
type: {
name: "String"
}
},
settings: {
serializedName: "settings",
type: {
name: "Composite",
className: "AssetConversionSettings"
}
},
output: {
serializedName: "output",
type: {
name: "Composite",
className: "AssetConversionOutput"
}
},
error: {
serializedName: "error",
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal"
}
},
status: {
serializedName: "status",
required: true,
type: {
name: "String"
}
},
createdOn: {
serializedName: "creationTime",
required: true,
type: {
name: "DateTime"
}
}
}
}
};
export const AssetConversionOutput: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AssetConversionOutput",
modelProperties: {
outputAssetUrl: {
serializedName: "outputAssetUri",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingServiceErrorInternal: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal",
modelProperties: {
code: {
serializedName: "code",
required: true,
type: {
name: "String"
}
},
message: {
serializedName: "message",
required: true,
type: {
name: "String"
}
},
details: {
serializedName: "details",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal"
}
}
}
},
target: {
serializedName: "target",
readOnly: true,
type: {
name: "String"
}
},
innerError: {
serializedName: "innerError",
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal"
}
}
}
}
};
export const ErrorResponse: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal"
}
}
}
}
};
export const ConversionList: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ConversionList",
modelProperties: {
conversions: {
serializedName: "conversions",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Conversion"
}
}
}
},
nextLink: {
serializedName: "@nextLink",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const RenderingSessionSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RenderingSessionSettings",
modelProperties: {
maxLeaseTimeInMinutes: {
serializedName: "maxLeaseTimeMinutes",
required: true,
type: {
name: "Number"
}
},
size: {
serializedName: "size",
required: true,
type: {
name: "String"
}
}
}
}
};
export const SessionProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SessionProperties",
modelProperties: {
sessionId: {
serializedName: "id",
required: true,
type: {
name: "String"
}
},
arrInspectorPort: {
constraints: {
InclusiveMaximum: 65534,
InclusiveMinimum: 49152
},
serializedName: "arrInspectorPort",
readOnly: true,
type: {
name: "Number"
}
},
handshakePort: {
constraints: {
InclusiveMaximum: 65534,
InclusiveMinimum: 49152
},
serializedName: "handshakePort",
readOnly: true,
type: {
name: "Number"
}
},
elapsedTimeInMinutes: {
serializedName: "elapsedTimeMinutes",
readOnly: true,
type: {
name: "Number"
}
},
host: {
serializedName: "hostname",
readOnly: true,
type: {
name: "String"
}
},
maxLeaseTimeInMinutes: {
serializedName: "maxLeaseTimeMinutes",
readOnly: true,
type: {
name: "Number"
}
},
size: {
serializedName: "size",
required: true,
type: {
name: "String"
}
},
status: {
serializedName: "status",
required: true,
type: {
name: "String"
}
},
teraflops: {
serializedName: "teraflops",
readOnly: true,
type: {
name: "Number"
}
},
error: {
serializedName: "error",
type: {
name: "Composite",
className: "RemoteRenderingServiceErrorInternal"
}
},
createdOn: {
serializedName: "creationTime",
readOnly: true,
type: {
name: "DateTime"
}
}
}
}
};
export const UpdateSessionSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "UpdateSessionSettings",
modelProperties: {
maxLeaseTimeInMinutes: {
serializedName: "maxLeaseTimeMinutes",
required: true,
type: {
name: "Number"
}
}
}
}
};
export const SessionsList: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SessionsList",
modelProperties: {
sessions: {
serializedName: "sessions",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SessionProperties"
}
}
}
},
nextLink: {
serializedName: "@nextLink",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingCreateConversionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingCreateConversionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingCreateConversionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingCreateConversionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingGetConversionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingGetConversionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
retryAfter: {
serializedName: "retry-after",
type: {
name: "Number"
}
}
}
}
};
export const RemoteRenderingGetConversionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingGetConversionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListConversionsHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListConversionsHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListConversionsExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListConversionsExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingCreateSessionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingCreateSessionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingCreateSessionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingCreateSessionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingGetSessionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingGetSessionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingUpdateSessionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingUpdateSessionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingStopSessionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingStopSessionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingStopSessionExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingStopSessionExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListSessionsExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListSessionsExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListConversionsNextHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListConversionsNextHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListConversionsNextExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListConversionsNextExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
};
export const RemoteRenderingListSessionsNextExceptionHeaders: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RemoteRenderingListSessionsNextExceptionHeaders",
modelProperties: {
mscv: {
serializedName: "ms-cv",
type: {
name: "String"
}
},
wWWAuthenticate: {
serializedName: "www-authenticate",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import React, {
useCallback,
useContext,
useEffect,
useMemo,
ChangeEvent,
ReactElement,
} from 'react';
import { useDispatch } from 'react-redux';
import moment from 'moment';
import { get, actions } from '../../store';
import {
translate as $t,
localeComparator,
endOfMonth,
NONE_CATEGORY_ID,
useKresusState,
} from '../../helpers';
import { BUDGET_DISPLAY_PERCENT, BUDGET_DISPLAY_NO_THRESHOLD } from '../../../shared/settings';
import { useGenericError, useNotifyError } from '../../hooks';
import BudgetListItem, { UncategorizedTransactionsItem } from './item';
import { Switch, Popover, Form } from '../ui';
import { ViewContext } from '../drivers';
import type { Budget, Operation } from '../../models';
import './budgets.css';
interface BudgetsPopoverProps {
// Called whenever the value "Show empty budgets" switch state has changed.
toggleWithoutThreshold: (state: boolean) => void;
showEmptyBudgets: boolean;
// Called whenever the value "Display in percent" switch state has changed.
toggleDisplayPercent: (state: boolean) => void;
displayPercent: boolean;
}
function PrefsPopover(props: BudgetsPopoverProps) {
return (
<Popover
trigger={
<button className="btn btn-info">{$t('client.general.default_parameters')}</button>
}
content={
<>
<Form.Input
inline={true}
label={$t('client.budget.show_empty_budgets')}
help={$t('client.budget.show_empty_budgets_desc')}
id="show-without-threshold">
<Switch
ariaLabel={$t('client.budget.show_empty_budgets')}
onChange={props.toggleWithoutThreshold}
checked={props.showEmptyBudgets}
/>
</Form.Input>
<Form.Input
inline={true}
label={$t('client.budget.display_in_percent')}
id="display-in-percent">
<Switch
ariaLabel={$t('client.budget.display_in_percent')}
onChange={props.toggleDisplayPercent}
checked={props.displayPercent}
/>
</Form.Input>
</>
}
/>
);
}
const computePeriodsListFromTransactions = (transactions: Operation[]): ReactElement[] => {
const periods: { month: number; year: number }[] = [];
if (transactions.length) {
const periodsSet = new Set();
for (const transaction of transactions) {
const { budgetDate } = transaction;
const budgetMonth = budgetDate.getMonth();
const budgetYear = budgetDate.getFullYear();
if (!periodsSet.has(`${budgetMonth}-${budgetYear}`)) {
periodsSet.add(`${budgetMonth}-${budgetYear}`);
periods.push({ month: budgetMonth, year: budgetYear });
}
}
}
// Always add the current month year as there might be no transactions at the beginning of
// the month but the user might still want to set their budgets.
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth();
if (!periods.some(p => p.month === currentMonth && p.year === currentYear)) {
periods.push({
month: currentMonth,
year: currentYear,
});
}
// As the transactions are sorted by date, and the list is made of budget dates,
// it may be necessary to sort the list in descending order.
periods.sort((a, b) => {
if (a.year !== b.year) {
return a.year > b.year ? -1 : 1;
}
return a.month > b.month ? -1 : 1;
});
return periods.map(period => {
const monthId = `${period.year}-${period.month}`;
let label = '';
if (period.month === currentMonth && period.year === currentYear) {
label = $t('client.budget.this_month');
} else {
label = `${moment.months(period.month)} ${period.year}`;
}
return (
<option value={monthId} key={monthId}>
{label}
</option>
);
});
};
const BudgetsList = (): ReactElement => {
const dispatch = useDispatch();
const currentView = useContext(ViewContext);
const setPeriod = useCallback(
(year, month) => actions.setBudgetsPeriod(dispatch, year, month),
[dispatch]
);
const fetchBudgets = useGenericError(
useCallback(
(year, month) => actions.fetchBudgetsByYearMonth(dispatch, year, month),
[dispatch]
)
);
const accountTransactions: Operation[] = currentView.transactions;
const displayPercent = useKresusState(state => get.boolSetting(state, BUDGET_DISPLAY_PERCENT));
const showEmptyBudgets = useKresusState(state =>
get.boolSetting(state, BUDGET_DISPLAY_NO_THRESHOLD)
);
const { year, month } = useKresusState(state => get.budgetSelectedPeriod(state));
const budgets: Budget[] | null = useKresusState(state => get.budgetsFromSelectedPeriod(state));
const categoriesNamesMap = useKresusState(state => {
const cats = get.categoriesButNone(state);
const categoriesNames = new Map();
for (const cat of cats) {
categoriesNames.set(cat.id, cat.label);
}
return categoriesNames;
});
const onChange = useCallback(
async (event: ChangeEvent<HTMLSelectElement>) => {
const period = event.currentTarget.value.split('-');
await setPeriod(parseInt(period[0], 10), parseInt(period[1], 10));
},
[setPeriod]
);
const toggleWithoutThreshold = useNotifyError(
'client.general.update_fail',
useCallback(
(checked: boolean) => {
return actions.setBoolSetting(dispatch, BUDGET_DISPLAY_NO_THRESHOLD, checked);
},
[dispatch]
)
);
const toggleDisplayPercent = useNotifyError(
'client.general.update_fail',
useCallback(
(checked: boolean) => {
return actions.setBoolSetting(dispatch, BUDGET_DISPLAY_PERCENT, checked);
},
[dispatch]
)
);
const showTransactions = useCallback(
(catId: number) => {
// From beginning of the month to its end.
const fromDate = new Date(year, month, 1, 0, 0, 0, 0);
const toDate = endOfMonth(fromDate);
actions.setSearchFields(dispatch, {
dateLow: fromDate,
dateHigh: toDate,
categoryIds: [catId],
});
},
[dispatch, year, month]
);
// On mount, fetch the budgets.
useEffect(() => {
if (!budgets) {
void fetchBudgets(year, month);
}
}, [year, month, budgets, fetchBudgets]);
// TODO: use useMemo for sumAmounts, sumThresholds, remaining and items computation.
let sumAmounts = 0;
let sumThresholds = 0;
let remaining = '-';
let items = null;
if (budgets) {
// From beginning of the month to its end.
const fromDate = new Date(year, month, 1, 0, 0, 0, 0);
const toDate = endOfMonth(fromDate);
const dateFilter = (op: Operation) => op.budgetDate >= fromDate && op.budgetDate <= toDate;
const transactions = accountTransactions.filter(dateFilter);
const sortedBudgets = budgets.slice().sort((prev, next) => {
return localeComparator(
categoriesNamesMap.get(prev.categoryId) as string,
categoriesNamesMap.get(next.categoryId) as string
);
});
items = [];
for (const budget of sortedBudgets) {
const key = `${budget.categoryId}${budget.year}${budget.month}`;
const budgetTransactions = transactions.filter(
transaction => budget.categoryId === transaction.categoryId
);
const amount = budgetTransactions.reduce(
(acc, transaction) => acc + transaction.amount,
0
);
sumAmounts += amount;
sumThresholds += budget.threshold || 0;
if (showEmptyBudgets || budgetTransactions.length > 0 || budget.threshold !== null) {
items.push(
<BudgetListItem
key={key}
id={key}
budget={budget}
showTransactions={showTransactions}
amount={parseFloat(amount.toFixed(2))}
displayPercent={displayPercent}
/>
);
}
}
// Uncategorized transactions.
const uncategorizedTransactions = transactions.filter(
transaction => transaction.categoryId === NONE_CATEGORY_ID
);
if (uncategorizedTransactions.length > 0) {
const amount = uncategorizedTransactions.reduce(
(acc, transaction) => acc + transaction.amount,
0
);
sumAmounts += amount;
items.push(
<UncategorizedTransactionsItem
key={`uncategorized-${amount}`}
amount={amount}
showTransactions={showTransactions}
currentDriver={currentView.driver}
/>
);
}
// Number.EPSILON would still be inferior to any rounding issue
// since we make several additions so we use 0.000001.
if (Math.abs(sumAmounts) <= 0.000001) {
sumAmounts = 0;
}
if (Math.abs(sumThresholds) <= 0.000001) {
sumThresholds = 0;
}
if (sumAmounts) {
if (displayPercent) {
if (sumThresholds) {
const rem = (100 * (sumAmounts - sumThresholds)) / sumThresholds;
remaining = `${rem.toFixed(2)}%`;
} else {
remaining = '-';
}
} else {
remaining = (sumAmounts - sumThresholds).toFixed(2);
}
}
} else {
items = (
<tr>
<td colSpan={5}>
<i className="fa fa-spinner" />
</td>
</tr>
);
}
const months = useMemo(
() => computePeriodsListFromTransactions(accountTransactions),
[accountTransactions]
);
return (
<div className="budgets">
<div className="toolbar">
<label htmlFor="budget-period" className="budget-period-label">
{$t('client.budget.period')}:
<select
id="budget-period"
onChange={onChange}
defaultValue={`${year}-${month}`}>
{months}
</select>
</label>
<PrefsPopover
toggleWithoutThreshold={toggleWithoutThreshold}
toggleDisplayPercent={toggleDisplayPercent}
displayPercent={displayPercent}
showEmptyBudgets={showEmptyBudgets}
/>
</div>
<table className="striped budget">
<thead>
<tr>
<th className="category-name">{$t('client.budget.category')}</th>
<th className="category-amount">{$t('client.budget.amount')}</th>
<th className="category-threshold">
{$t('client.budget.threshold')}
<span
className="tooltipped tooltipped-s"
aria-label={$t('client.budget.threshold_help')}>
<span className="fa fa-question-circle clickable" />
</span>
</th>
<th className="category-diff">{$t('client.budget.difference')}</th>
<th className="category-button"> </th>
</tr>
</thead>
<tbody>{items}</tbody>
<tfoot>
<tr>
<th className="category-name">{$t('client.budget.total')}</th>
<th className="category-amount amount">{sumAmounts.toFixed(2)}</th>
<th className="category-threshold amount">{sumThresholds.toFixed(2)}</th>
<th className="category-diff amount">{remaining}</th>
<th className="category-button"> </th>
</tr>
</tfoot>
</table>
</div>
);
};
export default BudgetsList; | the_stack |
export interface paths {
"/": {
get: {
responses: {
/** OK */
200: unknown;
};
};
};
"/_prisma_migrations": {
get: {
parameters: {
query: {
id?: parameters["rowFilter._prisma_migrations.id"];
checksum?: parameters["rowFilter._prisma_migrations.checksum"];
finished_at?: parameters["rowFilter._prisma_migrations.finished_at"];
migration_name?: parameters["rowFilter._prisma_migrations.migration_name"];
logs?: parameters["rowFilter._prisma_migrations.logs"];
rolled_back_at?: parameters["rowFilter._prisma_migrations.rolled_back_at"];
started_at?: parameters["rowFilter._prisma_migrations.started_at"];
applied_steps_count?: parameters["rowFilter._prisma_migrations.applied_steps_count"];
/** Filtering Columns */
select?: parameters["select"];
/** Ordering */
order?: parameters["order"];
/** Limiting and Pagination */
offset?: parameters["offset"];
/** Limiting and Pagination */
limit?: parameters["limit"];
};
header: {
/** Limiting and Pagination */
Range?: parameters["range"];
/** Limiting and Pagination */
"Range-Unit"?: parameters["rangeUnit"];
/** Preference */
Prefer?: parameters["preferCount"];
};
};
responses: {
/** OK */
200: {
schema: definitions["_prisma_migrations"][];
};
/** Partial Content */
206: unknown;
};
};
post: {
parameters: {
body: {
/** _prisma_migrations */
_prisma_migrations?: definitions["_prisma_migrations"];
};
query: {
/** Filtering Columns */
select?: parameters["select"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** Created */
201: unknown;
};
};
delete: {
parameters: {
query: {
id?: parameters["rowFilter._prisma_migrations.id"];
checksum?: parameters["rowFilter._prisma_migrations.checksum"];
finished_at?: parameters["rowFilter._prisma_migrations.finished_at"];
migration_name?: parameters["rowFilter._prisma_migrations.migration_name"];
logs?: parameters["rowFilter._prisma_migrations.logs"];
rolled_back_at?: parameters["rowFilter._prisma_migrations.rolled_back_at"];
started_at?: parameters["rowFilter._prisma_migrations.started_at"];
applied_steps_count?: parameters["rowFilter._prisma_migrations.applied_steps_count"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
patch: {
parameters: {
query: {
id?: parameters["rowFilter._prisma_migrations.id"];
checksum?: parameters["rowFilter._prisma_migrations.checksum"];
finished_at?: parameters["rowFilter._prisma_migrations.finished_at"];
migration_name?: parameters["rowFilter._prisma_migrations.migration_name"];
logs?: parameters["rowFilter._prisma_migrations.logs"];
rolled_back_at?: parameters["rowFilter._prisma_migrations.rolled_back_at"];
started_at?: parameters["rowFilter._prisma_migrations.started_at"];
applied_steps_count?: parameters["rowFilter._prisma_migrations.applied_steps_count"];
};
body: {
/** _prisma_migrations */
_prisma_migrations?: definitions["_prisma_migrations"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
};
"/language": {
get: {
parameters: {
query: {
project_id?: parameters["rowFilter.language.project_id"];
file?: parameters["rowFilter.language.file"];
code?: parameters["rowFilter.language.code"];
/** Filtering Columns */
select?: parameters["select"];
/** Ordering */
order?: parameters["order"];
/** Limiting and Pagination */
offset?: parameters["offset"];
/** Limiting and Pagination */
limit?: parameters["limit"];
};
header: {
/** Limiting and Pagination */
Range?: parameters["range"];
/** Limiting and Pagination */
"Range-Unit"?: parameters["rangeUnit"];
/** Preference */
Prefer?: parameters["preferCount"];
};
};
responses: {
/** OK */
200: {
schema: definitions["language"][];
};
/** Partial Content */
206: unknown;
};
};
post: {
parameters: {
body: {
/** language */
language?: definitions["language"];
};
query: {
/** Filtering Columns */
select?: parameters["select"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** Created */
201: unknown;
};
};
delete: {
parameters: {
query: {
project_id?: parameters["rowFilter.language.project_id"];
file?: parameters["rowFilter.language.file"];
code?: parameters["rowFilter.language.code"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
patch: {
parameters: {
query: {
project_id?: parameters["rowFilter.language.project_id"];
file?: parameters["rowFilter.language.file"];
code?: parameters["rowFilter.language.code"];
};
body: {
/** language */
language?: definitions["language"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
};
"/project": {
get: {
parameters: {
query: {
id?: parameters["rowFilter.project.id"];
name?: parameters["rowFilter.project.name"];
created_at?: parameters["rowFilter.project.created_at"];
api_key?: parameters["rowFilter.project.api_key"];
created_by_user_id?: parameters["rowFilter.project.created_by_user_id"];
base_language_code?: parameters["rowFilter.project.base_language_code"];
/** Filtering Columns */
select?: parameters["select"];
/** Ordering */
order?: parameters["order"];
/** Limiting and Pagination */
offset?: parameters["offset"];
/** Limiting and Pagination */
limit?: parameters["limit"];
};
header: {
/** Limiting and Pagination */
Range?: parameters["range"];
/** Limiting and Pagination */
"Range-Unit"?: parameters["rangeUnit"];
/** Preference */
Prefer?: parameters["preferCount"];
};
};
responses: {
/** OK */
200: {
schema: definitions["project"][];
};
/** Partial Content */
206: unknown;
};
};
post: {
parameters: {
body: {
/** project */
project?: definitions["project"];
};
query: {
/** Filtering Columns */
select?: parameters["select"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** Created */
201: unknown;
};
};
delete: {
parameters: {
query: {
id?: parameters["rowFilter.project.id"];
name?: parameters["rowFilter.project.name"];
created_at?: parameters["rowFilter.project.created_at"];
api_key?: parameters["rowFilter.project.api_key"];
created_by_user_id?: parameters["rowFilter.project.created_by_user_id"];
base_language_code?: parameters["rowFilter.project.base_language_code"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
patch: {
parameters: {
query: {
id?: parameters["rowFilter.project.id"];
name?: parameters["rowFilter.project.name"];
created_at?: parameters["rowFilter.project.created_at"];
api_key?: parameters["rowFilter.project.api_key"];
created_by_user_id?: parameters["rowFilter.project.created_by_user_id"];
base_language_code?: parameters["rowFilter.project.base_language_code"];
};
body: {
/** project */
project?: definitions["project"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
};
"/project_member": {
get: {
parameters: {
query: {
project_id?: parameters["rowFilter.project_member.project_id"];
user_id?: parameters["rowFilter.project_member.user_id"];
/** Filtering Columns */
select?: parameters["select"];
/** Ordering */
order?: parameters["order"];
/** Limiting and Pagination */
offset?: parameters["offset"];
/** Limiting and Pagination */
limit?: parameters["limit"];
};
header: {
/** Limiting and Pagination */
Range?: parameters["range"];
/** Limiting and Pagination */
"Range-Unit"?: parameters["rangeUnit"];
/** Preference */
Prefer?: parameters["preferCount"];
};
};
responses: {
/** OK */
200: {
schema: definitions["project_member"][];
};
/** Partial Content */
206: unknown;
};
};
post: {
parameters: {
body: {
/** project_member */
project_member?: definitions["project_member"];
};
query: {
/** Filtering Columns */
select?: parameters["select"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** Created */
201: unknown;
};
};
delete: {
parameters: {
query: {
project_id?: parameters["rowFilter.project_member.project_id"];
user_id?: parameters["rowFilter.project_member.user_id"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
patch: {
parameters: {
query: {
project_id?: parameters["rowFilter.project_member.project_id"];
user_id?: parameters["rowFilter.project_member.user_id"];
};
body: {
/** project_member */
project_member?: definitions["project_member"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
};
"/user": {
get: {
parameters: {
query: {
id?: parameters["rowFilter.user.id"];
email?: parameters["rowFilter.user.email"];
created_at?: parameters["rowFilter.user.created_at"];
/** Filtering Columns */
select?: parameters["select"];
/** Ordering */
order?: parameters["order"];
/** Limiting and Pagination */
offset?: parameters["offset"];
/** Limiting and Pagination */
limit?: parameters["limit"];
};
header: {
/** Limiting and Pagination */
Range?: parameters["range"];
/** Limiting and Pagination */
"Range-Unit"?: parameters["rangeUnit"];
/** Preference */
Prefer?: parameters["preferCount"];
};
};
responses: {
/** OK */
200: {
schema: definitions["user"][];
};
/** Partial Content */
206: unknown;
};
};
post: {
parameters: {
body: {
/** user */
user?: definitions["user"];
};
query: {
/** Filtering Columns */
select?: parameters["select"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** Created */
201: unknown;
};
};
delete: {
parameters: {
query: {
id?: parameters["rowFilter.user.id"];
email?: parameters["rowFilter.user.email"];
created_at?: parameters["rowFilter.user.created_at"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
patch: {
parameters: {
query: {
id?: parameters["rowFilter.user.id"];
email?: parameters["rowFilter.user.email"];
created_at?: parameters["rowFilter.user.created_at"];
};
body: {
/** user */
user?: definitions["user"];
};
header: {
/** Preference */
Prefer?: parameters["preferReturn"];
};
};
responses: {
/** No Content */
204: never;
};
};
};
"/rpc/get_user_id_from_email": {
post: {
parameters: {
body: {
args: {
/** Format: text */
email: string;
};
};
header: {
/** Preference */
Prefer?: parameters["preferParams"];
};
};
responses: {
/** OK */
200: unknown;
};
};
};
"/rpc/handle_insert_user": {
post: {
parameters: {
body: {
args: { [key: string]: unknown };
};
header: {
/** Preference */
Prefer?: parameters["preferParams"];
};
};
responses: {
/** OK */
200: unknown;
};
};
};
"/rpc/handle_insert_project": {
post: {
parameters: {
body: {
args: { [key: string]: unknown };
};
header: {
/** Preference */
Prefer?: parameters["preferParams"];
};
};
responses: {
/** OK */
200: unknown;
};
};
};
"/rpc/is_member_of_project": {
post: {
parameters: {
body: {
args: {
/** Format: uuid */
project_id: string;
};
};
header: {
/** Preference */
Prefer?: parameters["preferParams"];
};
};
responses: {
/** OK */
200: unknown;
};
};
};
}
export interface definitions {
_prisma_migrations: {
/**
* Format: character varying
* @description Note:
* This is a Primary Key.<pk/>
*/
id: string;
/** Format: character varying */
checksum: string;
/** Format: timestamp with time zone */
finished_at?: string;
/** Format: character varying */
migration_name: string;
/** Format: text */
logs?: string;
/** Format: timestamp with time zone */
rolled_back_at?: string;
/**
* Format: timestamp with time zone
* @default now()
*/
started_at: string;
/** Format: integer */
applied_steps_count: number;
};
language: {
/**
* Format: uuid
* @description Note:
* This is a Primary Key.<pk/>
* This is a Foreign Key to `project.id`.<fk table='project' column='id'/>
*/
project_id: string;
/** Format: text */
file: string;
/**
* Format: public.iso_639_1
* @description Note:
* This is a Primary Key.<pk/>
*/
code:
| "ab"
| "aa"
| "af"
| "ak"
| "sq"
| "am"
| "ar"
| "an"
| "hy"
| "as"
| "av"
| "ae"
| "ay"
| "az"
| "bm"
| "ba"
| "eu"
| "be"
| "bn"
| "bh"
| "bi"
| "bs"
| "br"
| "bg"
| "my"
| "ca"
| "km"
| "ch"
| "ce"
| "ny"
| "zh"
| "cu"
| "cv"
| "kw"
| "co"
| "cr"
| "hr"
| "cs"
| "da"
| "dv"
| "nl"
| "dz"
| "en"
| "eo"
| "et"
| "ee"
| "fo"
| "fj"
| "fi"
| "fr"
| "ff"
| "gd"
| "gl"
| "lg"
| "ka"
| "de"
| "ki"
| "el"
| "kl"
| "gn"
| "gu"
| "ht"
| "ha"
| "he"
| "hz"
| "hi"
| "ho"
| "hu"
| "is"
| "io"
| "ig"
| "id"
| "ia"
| "ie"
| "iu"
| "ik"
| "ga"
| "it"
| "ja"
| "jv"
| "kn"
| "kr"
| "ks"
| "kk"
| "rw"
| "kv"
| "kg"
| "ko"
| "kj"
| "ku"
| "ky"
| "lo"
| "la"
| "lv"
| "lb"
| "li"
| "ln"
| "lt"
| "lu"
| "mk"
| "mg"
| "ms"
| "ml"
| "mt"
| "gv"
| "mi"
| "mr"
| "mh"
| "ro"
| "mn"
| "na"
| "nv"
| "nd"
| "ng"
| "ne"
| "se"
| "no"
| "nb"
| "nn"
| "ii"
| "oc"
| "oj"
| "or"
| "om"
| "os"
| "pi"
| "pa"
| "ps"
| "fa"
| "pl"
| "pt"
| "qu"
| "rm"
| "rn"
| "ru"
| "sm"
| "sg"
| "sa"
| "sc"
| "sr"
| "sn"
| "sd"
| "si"
| "sk"
| "sl"
| "so"
| "st"
| "nr"
| "es"
| "su"
| "sw"
| "ss"
| "sv"
| "tl"
| "ty"
| "tg"
| "ta"
| "tt"
| "te"
| "th"
| "bo"
| "ti"
| "to"
| "ts"
| "tn"
| "tr"
| "tk"
| "tw"
| "ug"
| "uk"
| "ur"
| "uz"
| "ve"
| "vi"
| "vo"
| "wa"
| "cy"
| "fy"
| "wo"
| "xh"
| "yi"
| "yo"
| "za"
| "zu";
};
project: {
/**
* Format: uuid
* @description Note:
* This is a Primary Key.<pk/>
* @default gen_random_uuid()
*/
id: string;
/** Format: text */
name: string;
/**
* Format: timestamp without time zone
* @default CURRENT_TIMESTAMP
*/
created_at: string;
/**
* Format: uuid
* @default gen_random_uuid()
*/
api_key: string;
/** Format: uuid */
created_by_user_id: string;
/** Format: public.iso_639_1 */
base_language_code:
| "ab"
| "aa"
| "af"
| "ak"
| "sq"
| "am"
| "ar"
| "an"
| "hy"
| "as"
| "av"
| "ae"
| "ay"
| "az"
| "bm"
| "ba"
| "eu"
| "be"
| "bn"
| "bh"
| "bi"
| "bs"
| "br"
| "bg"
| "my"
| "ca"
| "km"
| "ch"
| "ce"
| "ny"
| "zh"
| "cu"
| "cv"
| "kw"
| "co"
| "cr"
| "hr"
| "cs"
| "da"
| "dv"
| "nl"
| "dz"
| "en"
| "eo"
| "et"
| "ee"
| "fo"
| "fj"
| "fi"
| "fr"
| "ff"
| "gd"
| "gl"
| "lg"
| "ka"
| "de"
| "ki"
| "el"
| "kl"
| "gn"
| "gu"
| "ht"
| "ha"
| "he"
| "hz"
| "hi"
| "ho"
| "hu"
| "is"
| "io"
| "ig"
| "id"
| "ia"
| "ie"
| "iu"
| "ik"
| "ga"
| "it"
| "ja"
| "jv"
| "kn"
| "kr"
| "ks"
| "kk"
| "rw"
| "kv"
| "kg"
| "ko"
| "kj"
| "ku"
| "ky"
| "lo"
| "la"
| "lv"
| "lb"
| "li"
| "ln"
| "lt"
| "lu"
| "mk"
| "mg"
| "ms"
| "ml"
| "mt"
| "gv"
| "mi"
| "mr"
| "mh"
| "ro"
| "mn"
| "na"
| "nv"
| "nd"
| "ng"
| "ne"
| "se"
| "no"
| "nb"
| "nn"
| "ii"
| "oc"
| "oj"
| "or"
| "om"
| "os"
| "pi"
| "pa"
| "ps"
| "fa"
| "pl"
| "pt"
| "qu"
| "rm"
| "rn"
| "ru"
| "sm"
| "sg"
| "sa"
| "sc"
| "sr"
| "sn"
| "sd"
| "si"
| "sk"
| "sl"
| "so"
| "st"
| "nr"
| "es"
| "su"
| "sw"
| "ss"
| "sv"
| "tl"
| "ty"
| "tg"
| "ta"
| "tt"
| "te"
| "th"
| "bo"
| "ti"
| "to"
| "ts"
| "tn"
| "tr"
| "tk"
| "tw"
| "ug"
| "uk"
| "ur"
| "uz"
| "ve"
| "vi"
| "vo"
| "wa"
| "cy"
| "fy"
| "wo"
| "xh"
| "yi"
| "yo"
| "za"
| "zu";
};
project_member: {
/**
* Format: uuid
* @description Note:
* This is a Primary Key.<pk/>
* This is a Foreign Key to `project.id`.<fk table='project' column='id'/>
*/
project_id: string;
/**
* Format: uuid
* @description Note:
* This is a Primary Key.<pk/>
* This is a Foreign Key to `user.id`.<fk table='user' column='id'/>
*/
user_id: string;
};
user: {
/**
* Format: uuid
* @description Note:
* This is a Primary Key.<pk/>
*/
id: string;
/** Format: text */
email: string;
/**
* Format: timestamp without time zone
* @default CURRENT_TIMESTAMP
*/
created_at: string;
};
}
export interface parameters {
/** @description Preference */
preferParams: "params=single-object";
/** @description Preference */
preferReturn: "return=representation" | "return=minimal" | "return=none";
/** @description Preference */
preferCount: "count=none";
/** @description Filtering Columns */
select: string;
/** @description On Conflict */
on_conflict: string;
/** @description Ordering */
order: string;
/** @description Limiting and Pagination */
range: string;
/**
* @description Limiting and Pagination
* @default items
*/
rangeUnit: string;
/** @description Limiting and Pagination */
offset: string;
/** @description Limiting and Pagination */
limit: string;
/** @description _prisma_migrations */
"body._prisma_migrations": definitions["_prisma_migrations"];
/** Format: character varying */
"rowFilter._prisma_migrations.id": string;
/** Format: character varying */
"rowFilter._prisma_migrations.checksum": string;
/** Format: timestamp with time zone */
"rowFilter._prisma_migrations.finished_at": string;
/** Format: character varying */
"rowFilter._prisma_migrations.migration_name": string;
/** Format: text */
"rowFilter._prisma_migrations.logs": string;
/** Format: timestamp with time zone */
"rowFilter._prisma_migrations.rolled_back_at": string;
/** Format: timestamp with time zone */
"rowFilter._prisma_migrations.started_at": string;
/** Format: integer */
"rowFilter._prisma_migrations.applied_steps_count": string;
/** @description language */
"body.language": definitions["language"];
/** Format: uuid */
"rowFilter.language.project_id": string;
/** Format: text */
"rowFilter.language.file": string;
/** Format: public.iso_639_1 */
"rowFilter.language.code": string;
/** @description project */
"body.project": definitions["project"];
/** Format: uuid */
"rowFilter.project.id": string;
/** Format: text */
"rowFilter.project.name": string;
/** Format: timestamp without time zone */
"rowFilter.project.created_at": string;
/** Format: uuid */
"rowFilter.project.api_key": string;
/** Format: uuid */
"rowFilter.project.created_by_user_id": string;
/** Format: public.iso_639_1 */
"rowFilter.project.base_language_code": string;
/** @description project_member */
"body.project_member": definitions["project_member"];
/** Format: uuid */
"rowFilter.project_member.project_id": string;
/** Format: uuid */
"rowFilter.project_member.user_id": string;
/** @description user */
"body.user": definitions["user"];
/** Format: uuid */
"rowFilter.user.id": string;
/** Format: text */
"rowFilter.user.email": string;
/** Format: timestamp without time zone */
"rowFilter.user.created_at": string;
}
export interface operations {}
export interface external {} | the_stack |
import { JDate } from './jdate';
import {InvalidJalaliDateError} from './InvalidJalaliDate.error';
describe('JDate', () => {
let jDate: JDate;
beforeEach(() => {
jDate = new JDate();
});
describe('JDate Constructor', () => {
it('should create an instance', () => {
expect(new JDate()).toBeTruthy();
});
it('should create a valid JDate object from date and time values', () => {
const jalayDate = new JDate(1397, 11, 12, 12, 13, 14, 255);
expect(jalayDate.format('yyyy-mm-dd HH:MM:SS.l')).toBe('1397-12-12 12:13:14.255');
});
});
describe('pars', () => {
[
['11 دی 1348 00:00:00', -12600000],
['11 Dey 1348 00:00:00', -12600000],
].forEach(([input, expectedOutput]) => {
it(`should return passed milliseconds from January 1, 1970, 00:00:00 UTC until given time`, () => {
// @ts-ignore
expect(JDate.parse(input)).toBe(expectedOutput);
});
});
['12:35:30', '11 Day 1348 00:12:00', '-12600000'].forEach(input => {
it(`should throw InvalidJalaliDate error when input value (${input}) does not follow the proper pattern`, () => {
expect(() => {
JDate.parse(input);
}).toThrow(new InvalidJalaliDateError());
});
});
});
describe('getDate', () => {
[
[new JDate(1397, 11, 29), 29],
[new JDate('11 دی 1348 00:12:00'), 11],
[new JDate(1375, 1, 1, 12, 32, 55, 321), 1]
].forEach(([jDateObj, day]) => {
it(`should returns the day of the month for the specified date`, () => {
// @ts-ignore
expect(jDateObj.getDate()).toBe(day);
});
});
});
describe('getDay', () => {
[
[new JDate(1397, 11, 24), 0],
[new JDate(1397, 2, 19), 1],
[new JDate(1370, 7, 5), 2],
[new JDate(1370, 7, 27), 3],
[new JDate(1370, 7, 21), 4],
[new JDate(1397, 11, 1), 5],
[new JDate(1397, 11, 23), 6],
].forEach(([jDateObj, dayOfWeek]) => {
it('should return number of the day in the week.', () => {
// @ts-ignore
expect(jDateObj.getDay()).toBe(dayOfWeek);
});
});
});
describe('getFullYear', () => {
[
[new JDate(1397, 11, 29), 1397],
[new JDate('11 دی 1348 00:12:00'), 1348],
[new JDate(1375, 1, 1, 12, 32, 55, 321), 1375]
].forEach(([jDateObj, day]) => {
it(`should returns the day of the month for the specified date`, () => {
// @ts-ignore
expect(jDateObj.getFullYear()).toBe(day);
});
});
});
describe('getHours', () => {
[
[new JDate(1397, 11, 29), 0],
[new JDate('11 دی 1348 00:12:00'), 0],
[new JDate(1375, 1, 1, 12, 32, 55, 321), 12]
].forEach(([jDateObj, hour]) => {
it(`should returns the day of the month for the specified date`, () => {
// @ts-ignore
expect(jDateObj.getHours()).toBe(hour);
});
});
});
describe('getMilliseconds', () => {
[
[new JDate(1397, 11, 29), 0],
[new JDate('11 دی 1348 00:12:00'), 0],
[new JDate(1375, 1, 1, 12, 32, 55, 321), 321]
].forEach(([jDateObj, milliseconds]) => {
it(`should returns the milliseconds of the time`, () => {
// @ts-ignore
expect(jDateObj.getMilliseconds()).toBe(milliseconds);
});
});
});
describe('getMinutes', () => {
[
[new JDate(1397, 11, 29), 0],
[new JDate('11 دی 1348 00:12:00'), 12],
[new JDate(1375, 1, 1, 12, 32, 55, 321), 32]
].forEach(([jDateObj, minutes]) => {
it(`should returns the getMinutes of the time`, () => {
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(minutes);
});
});
});
describe('getMonth', () => {
[
[new JDate('30 اسفند 1375 13:54:58'), 11],
[new JDate(1397, 0, 1), 0],
[new JDate(1375, 5, 1, 12, 32, 55, 321), 5]
].forEach(([jDateObj, month]) => {
it('should return number of the month in the date.', () => {
// @ts-ignore
expect(jDateObj.getMonth()).toBe(month);
});
});
});
describe('getSeconds', () => {
[
[new JDate('30 اسفند 1375 13:54:58'), 58],
[new JDate(1397, 0, 1), 0],
[new JDate(1375, 5, 1, 12, 32, 55, 321), 55]
].forEach(([jDateObj, seconds]) => {
it('should return number of the seconds in the date.', () => {
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(seconds);
});
});
});
describe('getTime', () => {
[
[new JDate('11 دی 1348 00:00:00'), -12600000],
[new JDate('11 Dey 1348 00:00:00'), -12600000],
].forEach(([jDateObj, time]) => {
it('should return number of milliseconds since the unix epoch', () => {
// @ts-ignore
expect(jDateObj.getTime()).toBe(time);
});
});
});
describe('setDate', () => {
[
[new JDate('29 دی 1348 00:00:00'), 11, -12600000],
[new JDate('03 Dey 1348 00:00:00'), 11, -12600000],
].forEach(([jDateObj, newDate, time]) => {
it('should return number of milliseconds since the unix epoch', () => {
// @ts-ignore
expect(jDateObj.setDate(newDate)).toBe(time);
// @ts-ignore
expect(jDateObj.getDate()).toBe(newDate);
});
});
});
describe('setFullYear', () => {
[
[new JDate('11 دی 1397 00:00:00'), 1348, -12600000],
[new JDate('11 Dey 1400 00:00:00'), 1348, -12600000],
].forEach(([jDateObj, newYear, time]) => {
it('should return number of milliseconds since the unix epoch', () => {
// @ts-ignore
expect(jDateObj.setFullYear(newYear)).toBe(time);
// @ts-ignore
expect(jDateObj.getFullYear()).toBe(newYear);
});
});
it('should return number of milliseconds since the unix epoch when year and month inputted', () => {
const jDateObj = new JDate('11 مهر 1397 00:00:00');
expect(jDateObj.setFullYear(1348, 9)).toBe(-12600000);
});
it('should return number of milliseconds since the unix epoch when year and month and day inputted', () => {
const jDateObj = new JDate('10 مهر 1397 00:00:00');
expect(jDateObj.setFullYear(1348, 9, 11)).toBe(-12600000);
});
});
describe('setHours', () => {
[
[new JDate('11 دی 1348 01:00:00'), 0, -12600000],
[new JDate('11 Dey 1348 23:00:00'), 0, -12600000],
].forEach(([jDateObj, hour, time]) => {
it('should return number of milliseconds since the unix epoch when only new hour inputted', () => {
// @ts-ignore
expect(jDateObj.setHours(hour)).toBe(time);
// @ts-ignore
expect(jDateObj.getHours()).toBe(hour);
});
});
[
[new JDate('11 دی 1348 01:20:00'), 0, 0, -12600000],
[new JDate('11 Dey 1348 23:59:00'), 0, 0, -12600000],
].forEach(([jDateObj, hour, min, time]) => {
it('should return number of milliseconds since the unix epoch when new hour and minutes inputted', () => {
// @ts-ignore
expect(jDateObj.setHours(hour, min)).toBe(time);
// @ts-ignore
expect(jDateObj.getHours()).toBe(hour);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
});
});
[
[new JDate('11 دی 1348 01:20:03'), 0, 0, 0, -12600000],
[new JDate('11 Dey 1348 23:59:29'), 0, 0, 0, -12600000],
].forEach(([jDateObj, hour, min, sec, time]) => {
it('should return number of milliseconds since the unix epoch when new hour, minutes and seconds inputted', () => {
// @ts-ignore
expect(jDateObj.setHours(hour, min, sec)).toBe(time);
// @ts-ignore
expect(jDateObj.getHours()).toBe(hour);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
});
});
[
[new JDate('11 دی 1348 01:20:03'), 0, 0, 0, 0, -12600000],
[new JDate('11 Dey 1348 23:59:29'), 0, 0, 0, 0, -12600000],
].forEach(([jDateObj, hour, min, sec, milli, time]) => {
it('should return number of milliseconds since the unix epoch when new hour, minutes, seconds and milliseconds inputted', () => {
// @ts-ignore
expect(jDateObj.setHours(hour, min, sec, milli)).toBe(time);
// @ts-ignore
expect(jDateObj.getHours()).toBe(hour);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
// @ts-ignore
expect(jDateObj.getMilliseconds()).toBe(milli);
});
});
});
describe('setMilliseconds', () => {
[
[new JDate('11 دی 1348 00:00:00'), 0, -12600000],
[new JDate('11 Dey 1348 00:00:00'), 0, -12600000],
].forEach(([jDateObj, milli, time]) => {
it('should return number of milliseconds since the unix epoch when new milliseconds inputted', () => {
// @ts-ignore
expect(jDateObj.setMilliseconds(milli)).toBe(time);
// @ts-ignore
expect(jDateObj.getMilliseconds()).toBe(milli);
});
});
});
describe('setMinutes', () => {
[
[new JDate('11 دی 1348 00:20:00'), 0, -12600000],
[new JDate('11 Dey 1348 00:59:00'), 0, -12600000],
].forEach(([jDateObj, min, time]) => {
it('should return number of milliseconds since the unix epoch when new minutes inputted', () => {
// @ts-ignore
expect(jDateObj.setMinutes(min)).toBe(time);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
});
});
[
[new JDate('11 دی 1348 00:20:03'), 0, 0, -12600000],
[new JDate('11 Dey 1348 00:59:29'), 0, 0, -12600000],
].forEach(([jDateObj, min, sec, time]) => {
it('should return number of milliseconds since the unix epoch when new minutes and seconds inputted', () => {
// @ts-ignore
expect(jDateObj.setMinutes(min, sec)).toBe(time);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
});
});
[
[new JDate('11 دی 1348 00:20:03'), 0, 0, 0, -12600000],
[new JDate('11 Dey 1348 00:59:29'), 0, 0, 0, -12600000],
].forEach(([jDateObj, min, sec, milli, time]) => {
it('should return number of milliseconds since the unix epoch when new minutes, seconds and milliseconds inputted', () => {
// @ts-ignore
expect(jDateObj.setMinutes(min, sec, milli)).toBe(time);
// @ts-ignore
expect(jDateObj.getMinutes()).toBe(min);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
// @ts-ignore
expect(jDateObj.getMilliseconds()).toBe(milli);
});
});
});
describe('setMonth', () => {
[
[new JDate('11 اسفند 1348 00:00:00'), 9, -12600000],
[new JDate('11 Tir 1348 00:00:00'), 9, -12600000],
].forEach(([jDateObj, month, time]) => {
it('should return number of milliseconds since the unix epoch when new Month inputted', () => {
// @ts-ignore
expect(jDateObj.setMonth(month)).toBe(time);
// @ts-ignore
expect(jDateObj.getMonth()).toBe(month);
});
});
[
[new JDate('27 خرداد 1348 00:00:00'), 9, 11, -12600000],
[new JDate('01 Mordad 1348 00:00:00'), 9, 11, -12600000],
].forEach(([jDateObj, month, date, time]) => {
it('should return number of milliseconds since the unix epoch when new month and day inputted', () => {
// @ts-ignore
expect(jDateObj.setMonth(month, date)).toBe(time);
// @ts-ignore
expect(jDateObj.getMonth()).toBe(month);
// @ts-ignore
expect(jDateObj.getDate()).toBe(date);
});
});
});
describe('setSeconds', () => {
[
[new JDate('11 دی 1348 00:00:03'), 0, -12600000],
[new JDate('11 Dey 1348 00:00:29'), 0, -12600000],
].forEach(([jDateObj, sec, time]) => {
it('should return number of milliseconds since the unix epoch when new seconds inputted', () => {
// @ts-ignore
expect(jDateObj.setSeconds(sec)).toBe(time);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
});
});
[
[new JDate('11 دی 1348 00:00:03'), 0, 0, -12600000],
[new JDate('11 Dey 1348 00:00:29'), 0, 0, -12600000],
].forEach(([jDateObj, sec, milli, time]) => {
it('should return number of milliseconds since the unix epoch when new seconds and milliseconds inputted', () => {
// @ts-ignore
expect(jDateObj.setSeconds(sec, milli)).toBe(time);
// @ts-ignore
expect(jDateObj.getSeconds()).toBe(sec);
// @ts-ignore
expect(jDateObj.getMilliseconds()).toBe(milli);
});
});
});
describe('setTime', () => {
[
[new JDate('11 دی 1348 00:00:00'), -12600000],
[new JDate('11 Dey 1348 00:00:00'), -12600000],
].forEach(([jDateObj, time]) => {
it('should create JDate object from number of milliseconds since January 1, 1970, 00:00:00 UTC', () => {
const newDate = new JDate();
// @ts-ignore
newDate.setTime(time);
// @ts-ignore
expect(jDateObj).toEqual(newDate);
});
});
});
describe('getNameOfTheDay', () => {
[
[new JDate(1397, 11, 24), 'جمعه'],
[new JDate(1397, 2, 19), 'شنبه'],
[new JDate(1370, 7, 5), 'یکشنبه'],
[new JDate(1370, 7, 27), 'دوشنبه'],
[new JDate(1370, 7, 21), 'سهشنبه'],
[new JDate(1397, 11, 1), 'چهارشنبه'],
[new JDate(1397, 11, 23), 'پنجشنبه'],
].forEach(([jDateObj, dayOfWeek]) => {
it('should return number of the day in the week.', () => {
// @ts-ignore
expect(jDateObj.getNameOfTheDay()).toBe(dayOfWeek);
});
});
});
describe('getNameOfTheMonth', () => {
[
[new JDate('30 اسفند 1375 13:54:58'), 'اسفند'],
[new JDate(1397, 0, 1), 'فروردین'],
[new JDate(1375, 5, 1, 12, 32, 55, 321), 'شهریور']
].forEach(([jDateObj, month]) => {
it('should return number of the month in the date.', () => {
// @ts-ignore
expect(jDateObj.getNameOfTheMonth()).toBe(month);
});
});
});
describe('toDateString', () => {
[
[new JDate('30 Esfand 1375 13:54:58'), 'پنجشنبه اسفند 30 1375'],
[new JDate(1397, 0, 1), 'چهارشنبه فروردین 1 1397'],
[new JDate(1377, 5, 1, 12, 32, 55, 321), 'یکشنبه شهریور 1 1377']
].forEach(([jDateObj, dateString]) => {
it('should return number of the month in the date.', () => {
// @ts-ignore
expect(jDateObj.toDateString()).toBe(dateString);
});
});
});
describe('getHours12hourClock', () => {
[ [new JDate(1397, 1, 1, 12), 12],
[new JDate(1397, 1, 1, 13), 1],
[new JDate(1397, 1, 1, 14), 2],
[new JDate(1397, 1, 1, 15), 3],
[new JDate(1397, 1, 1, 16), 4],
[new JDate(1397, 1, 1, 17), 5],
[new JDate(1397, 1, 1, 18), 6],
[new JDate(1397, 1, 1, 19), 7],
[new JDate(1397, 1, 1, 20), 8],
[new JDate(1397, 1, 1, 21), 9],
[new JDate(1397, 1, 1, 22), 10],
[new JDate(1397, 1, 1, 23), 11],
[new JDate(1397, 1, 1, 0), 12],
[new JDate(1397, 1, 1, 1), 1],
[new JDate(1397, 1, 1, 2), 2],
[new JDate(1397, 1, 1, 3), 3],
[new JDate(1397, 1, 1, 4), 4],
[new JDate(1397, 1, 1, 5), 5],
[new JDate(1397, 1, 1, 6), 6],
[new JDate(1397, 1, 1, 7), 7],
[new JDate(1397, 1, 1, 8), 8],
[new JDate(1397, 1, 1, 9), 9],
[new JDate(1397, 1, 1, 10), 10],
[new JDate(1397, 1, 1, 11), 11]].forEach(([jDateObj, hour]) => {
// @ts-ignore
it(`should convert JDate hour (${jDateObj.getHours()}) to 12-hour clock version (${hour})`, () => {
// @ts-ignore
expect(jDateObj.getHours12hourClock()).toBe(hour);
});
});
});
describe('getTimeMarker', () => {
[
[new JDate(1397, 1, 1, 0), false, 'قبل از ظهر'],
[new JDate(1397, 1, 1, 5), false, 'قبل از ظهر'],
[new JDate(1397, 1, 1, 13), false, 'بعد از ظهر'],
[new JDate(1397, 1, 1, 12), false, 'بعد از ظهر'],
[new JDate(1397, 1, 1, 0), true, 'ق.ظ'],
[new JDate(1397, 1, 1, 3), true, 'ق.ظ'],
[new JDate(1397, 1, 1, 13), true, 'ب.ظ'],
[new JDate(1397, 1, 1, 23), true, 'ب.ظ'],
].forEach(([jDateObj, isShortVersion, marker]) => {
it('should return time marker according to the hour value of the JDate object.', () => {
// @ts-ignore
expect(jDateObj.getTimeMarker(isShortVersion)).toBe(marker);
});
});
});
describe('format', () => {
[
[new JDate(1397, 11, 25, 11, 31, 30, 158), 'yyyy-mm-dd', '1397-12-25'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yyyy-m-d', '1397-1-1'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yyyy-mm-dd', '1397-01-01'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yy-mm-dd', '97-01-01'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yyyy', '1397'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yy', '97'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'mm', '01'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'm', '1'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'mmm', 'فروردین'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'mmmm', 'Farvardin'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'd', '1'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'dd', '01'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'ddd', 'چهارشنبه'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'dddd', 'Cheharshanbe'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'HH:MM:SS.l', '11:31:30.158'],
[new JDate(1397, 0, 1, 1, 31, 30, 158), 'HH', '01'],
[new JDate(1397, 0, 1, 1, 31, 30, 158), 'H', '1'],
[new JDate(1397, 0, 1, 13, 31, 30, 158), 'hh', '01'],
[new JDate(1397, 0, 1, 13, 31, 30, 158), 'h', '1'],
[new JDate(1397, 0, 1, 13, 4, 30, 158), 'MM', '04'],
[new JDate(1397, 0, 1, 13, 4, 30, 158), 'M', '4'],
[new JDate(1397, 0, 1, 13, 4, 3, 158), 'SS', '03'],
[new JDate(1397, 0, 1, 13, 4, 3, 158), 'S', '3'],
[new JDate(1397, 0, 1, 13, 4, 3, 158), 'l', '158'],
[new JDate(1397, 0, 1, 13, 4, 3, 158), 'T', 'بعد از ظهر'],
[new JDate(1397, 0, 1, 3, 4, 3, 158), 't', 'ق.ظ'],
[new JDate(1397, 0, 1, 11, 31, 30, 158), 'yyyy-mm-dd HH:MM:SS.l', '1397-01-01 11:31:30.158'],
].forEach(([jDateObj, pattern, formattedString]) => {
it(`should return formatted string from JDate object.`, () => {
// @ts-ignore
expect(jDateObj.format(pattern)).toBe(formattedString);
});
});
});
describe('toISOString', () => {
[
[new JDate(1397, 11, 12, 12, 12, 12, 0), '1397-12-12T12:12:12.0Z'],
[new JDate(1397, 0, 5, 1, 2, 9, 123), '1397-01-05T01:02:09.123Z'],
].forEach(([jDateObj, isoString]) => {
it('should return iso string from JDate object in Jalali Date', () => {
// @ts-ignore
expect(jDateObj.toISOString()).toBe(isoString);
});
});
});
describe('addMonth', () => {
[
[new JDate(1398, 0, 1), 1, '1398-2-1'],
[new JDate(1398, 0, 1), 10, '1398-11-1'],
[new JDate(1398, 0, 1), 0, '1398-1-1'],
[new JDate(1398, 0, 1), 12, '1399-1-1'],
[new JDate(1398, 11, 1), 12, '1399-12-1'],
].forEach(([jdate, increaseBy, result]) => {
it(`should change month and year (if month overflows) to the increased value and set date to ${result} when increase value
is ${increaseBy}`, () => {
// @ts-ignore
jdate.addMonth(increaseBy);
// @ts-ignore
expect(jdate.format('yyyy-m-d')).toBe(result);
});
});
});
}); | the_stack |
import * as parse from './parse';
describe('parse', () => {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
describe('getLines', () => {
it('single line', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual('id: abc');
expect(fieldLength).toEqual(2);
});
// act:
next(encoder.encode('id: abc\n'));
// assert:
expect(lineNum).toBe(1);
});
it('multiple lines', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(lineNum === 1 ? 'id: abc' : 'data: def');
expect(fieldLength).toEqual(lineNum === 1 ? 2 : 4);
});
// act:
next(encoder.encode('id: abc\n'));
next(encoder.encode('data: def\n'));
// assert:
expect(lineNum).toBe(2);
});
it('single line split across multiple arrays', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual('id: abc');
expect(fieldLength).toEqual(2);
});
// act:
next(encoder.encode('id: a'));
next(encoder.encode('bc\n'));
// assert:
expect(lineNum).toBe(1);
});
it('multiple lines split across multiple arrays', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(lineNum === 1 ? 'id: abc' : 'data: def');
expect(fieldLength).toEqual(lineNum === 1 ? 2 : 4);
});
// act:
next(encoder.encode('id: ab'));
next(encoder.encode('c\nda'));
next(encoder.encode('ta: def\n'));
// assert:
expect(lineNum).toBe(2);
});
it('new line', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual('');
expect(fieldLength).toEqual(-1);
});
// act:
next(encoder.encode('\n'));
// assert:
expect(lineNum).toBe(1);
});
it('comment line', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(': this is a comment');
expect(fieldLength).toEqual(0);
});
// act:
next(encoder.encode(': this is a comment\n'));
// assert:
expect(lineNum).toBe(1);
});
it('line with no field', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual('this is an invalid line');
expect(fieldLength).toEqual(-1);
});
// act:
next(encoder.encode('this is an invalid line\n'));
// assert:
expect(lineNum).toBe(1);
});
it('line with multiple colons', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual('id: abc: def');
expect(fieldLength).toEqual(2);
});
// act:
next(encoder.encode('id: abc: def\n'));
// assert:
expect(lineNum).toBe(1);
});
it('single byte array with multiple lines separated by \\n', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(lineNum === 1 ? 'id: abc' : 'data: def');
expect(fieldLength).toEqual(lineNum === 1 ? 2 : 4);
});
// act:
next(encoder.encode('id: abc\ndata: def\n'));
// assert:
expect(lineNum).toBe(2);
});
it('single byte array with multiple lines separated by \\r', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(lineNum === 1 ? 'id: abc' : 'data: def');
expect(fieldLength).toEqual(lineNum === 1 ? 2 : 4);
});
// act:
next(encoder.encode('id: abc\rdata: def\r'));
// assert:
expect(lineNum).toBe(2);
});
it('single byte array with multiple lines separated by \\r\\n', () => {
// arrange:
let lineNum = 0;
const next = parse.getLines((line, fieldLength) => {
++lineNum;
expect(decoder.decode(line)).toEqual(lineNum === 1 ? 'id: abc' : 'data: def');
expect(fieldLength).toEqual(lineNum === 1 ? 2 : 4);
});
// act:
next(encoder.encode('id: abc\r\ndata: def\r\n'));
// assert:
expect(lineNum).toBe(2);
});
});
describe('getMessages', () => {
it('happy path', () => {
// arrange:
let msgNum = 0;
const next = parse.getMessages(id => {
expect(id).toEqual('abc');
}, retry => {
expect(retry).toEqual(42);
}, msg => {
++msgNum;
expect(msg).toEqual({
retry: 42,
id: 'abc',
event: 'def',
data: 'ghi'
});
});
// act:
next(encoder.encode('retry: 42'), 5);
next(encoder.encode('id: abc'), 2);
next(encoder.encode('event:def'), 5);
next(encoder.encode('data:ghi'), 4);
next(encoder.encode(''), -1);
// assert:
expect(msgNum).toBe(1);
});
it('skip unknown fields', () => {
let msgNum = 0;
const next = parse.getMessages(id => {
expect(id).toEqual('abc');
}, _retry => {
fail('retry should not be called');
}, msg => {
++msgNum;
expect(msg).toEqual({
id: 'abc',
data: '',
event: '',
retry: undefined,
});
});
// act:
next(encoder.encode('id: abc'), 2);
next(encoder.encode('foo: null'), 3);
next(encoder.encode(''), -1);
// assert:
expect(msgNum).toBe(1);
});
it('ignore non-integer retry', () => {
let msgNum = 0;
const next = parse.getMessages(_id => {
fail('id should not be called');
}, _retry => {
fail('retry should not be called');
}, msg => {
++msgNum;
expect(msg).toEqual({
id: '',
data: '',
event: '',
retry: undefined,
});
});
// act:
next(encoder.encode('retry: def'), 5);
next(encoder.encode(''), -1);
// assert:
expect(msgNum).toBe(1);
});
it('skip comment-only messages', () => {
// arrange:
let msgNum = 0;
const next = parse.getMessages(id => {
expect(id).toEqual('123');
}, _retry => {
fail('retry should not be called');
}, msg => {
++msgNum;
expect(msg).toEqual({
retry: undefined,
id: '123',
event: 'foo ',
data: '',
});
});
// act:
next(encoder.encode('id:123'), 2);
next(encoder.encode(':'), 0);
next(encoder.encode(': '), 0);
next(encoder.encode('event: foo '), 5);
next(encoder.encode(''), -1);
// assert:
expect(msgNum).toBe(1);
});
it('should append data split across multiple lines', () => {
// arrange:
let msgNum = 0;
const next = parse.getMessages(_id => {
fail('id should not be called');
}, _retry => {
fail('retry should not be called');
}, msg => {
++msgNum;
expect(msg).toEqual({
data: 'YHOO\n+2\n\n10',
id: '',
event: '',
retry: undefined,
});
});
// act:
next(encoder.encode('data:YHOO'), 4);
next(encoder.encode('data: +2'), 4);
next(encoder.encode('data'), 4);
next(encoder.encode('data: 10'), 4);
next(encoder.encode(''), -1);
// assert:
expect(msgNum).toBe(1);
});
it('should reset id if sent multiple times', () => {
// arrange:
const expectedIds = ['foo', ''];
let idsIdx = 0;
let msgNum = 0;
const next = parse.getMessages(id => {
expect(id).toEqual(expectedIds[idsIdx]);
++idsIdx;
}, _retry => {
fail('retry should not be called');
}, msg => {
++msgNum;
expect(msg).toEqual({
data: '',
id: '',
event: '',
retry: undefined,
});
});
// act:
next(encoder.encode('id: foo'), 2);
next(encoder.encode('id'), 2);
next(encoder.encode(''), -1);
// assert:
expect(idsIdx).toBe(2);
expect(msgNum).toBe(1);
});
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.