text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import type {Mutable} from "../types/Mutable";
import {Timing} from "./Timing";
/** @public */
export type AnyEasing = Easing | EasingType;
/** @public */
export type EasingType = "linear" | "quad-in" | "quad-out" | "quad-in-out"
| "cubic-in" | "cubic-out" | "cubic-in-out"
| "quart-in" | "quart-out" | "quart-in-out"
| "expo-in" | "expo-out" | "expo-in-out"
| "circ-in" | "circ-out" | "circ-in-out"
| "back-in" | "back-out" | "back-in-out"
| "elastic-in" | "elastic-out" | "elastic-in-out"
| "bounce-in" | "bounce-out" | "bounce-in-out";
/** @public */
export interface Easing extends Timing {
readonly type: string;
readonly 0: 0;
readonly 1: 1;
readonly easing: this;
equivalentTo(that: unknown, epsilon?: number): boolean;
canEqual(that: unknown): boolean;
equals(that: unknown): boolean;
toString(): string;
}
/** @public */
export const Easing = (function (_super: typeof Timing) {
const Easing = function (type: string): Easing {
switch (type) {
case "linear": return Easing.linear;
case "quad-in": return Easing.quadIn;
case "quad-out": return Easing.quadOut;
case "quad-in-out": return Easing.quadInOut;
case "cubic-in": return Easing.cubicIn;
case "cubic-out": return Easing.cubicOut;
case "cubic-in-out": return Easing.cubicInOut;
case "quart-in": return Easing.quartIn;
case "quart-out": return Easing.quartOut;
case "quart-in-out": return Easing.quartInOut;
case "expo-in": return Easing.expoIn;
case "expo-out": return Easing.expoOut;
case "expo-in-out": return Easing.expoInOut;
case "circ-in": return Easing.circIn;
case "circ-out": return Easing.circOut;
case "circ-in-out": return Easing.circInOut;
case "back-in": return Easing.backIn;
case "back-out": return Easing.backOut;
case "back-in-out": return Easing.backInOut;
case "elastic-in": return Easing.elasticIn;
case "elastic-out": return Easing.elasticOut;
case "elastic-in-out": return Easing.elasticInOut;
case "bounce-in": return Easing.bounceIn;
case "bounce-out": return Easing.bounceOut;
case "bounce-in-out": return Easing.bounceInOut;
default: throw new Error("unknown easing: " + type);
}
} as {
(type: string): Easing;
/** @internal */
prototype: Easing;
readonly linear: Easing;
readonly quadIn: Easing;
readonly quadOut: Easing;
readonly quadInOut: Easing;
readonly cubicIn: Easing;
readonly cubicOut: Easing;
readonly cubicInOut: Easing;
readonly quartIn: Easing;
readonly quartOut: Easing;
readonly quartInOut: Easing;
readonly expoIn: Easing;
readonly expoOut: Easing;
readonly expoInOut: Easing;
readonly circIn: Easing;
readonly circOut: Easing;
readonly circInOut: Easing;
readonly backIn: Easing;
readonly backOut: Easing;
readonly backInOut: Easing;
readonly elasticIn: Easing;
readonly elasticOut: Easing;
readonly elasticInOut: Easing;
readonly bounceIn: Easing;
readonly bounceOut: Easing;
readonly bounceInOut: Easing;
fromAny(value: AnyEasing): Easing;
};
Easing.prototype = Object.create(_super.prototype);
Easing.prototype.constructor = Easing;
Object.defineProperty(Easing.prototype, 0, {
value: 0,
});
Object.defineProperty(Easing.prototype, 1, {
value: 1,
});
Object.defineProperty(Easing.prototype, "easing", {
get(this: Easing): Easing {
return this;
},
});
Easing.prototype.equivalentTo = function (that: unknown, epsilon?: number): boolean {
return this === that;
};
Easing.prototype.canEqual = function (that: unknown): boolean {
return that instanceof Easing;
};
Easing.prototype.equals = function (that: unknown): boolean {
return this === that;
};
Easing.prototype.toString = function (): string {
return "Easing(\"" + this.type + "\")";
};
Easing.fromAny = function (value: AnyEasing): Easing {
if (value instanceof Easing) {
return value;
} else if (typeof value === "string") {
return Easing(value);
}
throw new TypeError("" + value);
};
(Easing as Mutable<typeof Easing>).linear = function (u: number): number {
return u;
} as unknown as Easing;
Object.setPrototypeOf(Easing.linear, Easing.prototype);
(Easing.linear as Mutable<Easing>).type = "linear";
(Easing as Mutable<typeof Easing>).quadIn = function (u: number): number {
return u * u;
} as Easing;
Object.setPrototypeOf(Easing.quadIn, Easing.prototype);
(Easing.quadIn as Mutable<Easing>).type = "quad-in";
(Easing as Mutable<typeof Easing>).quadOut = function (u: number): number {
return u * (2 - u);
} as Easing;
Object.setPrototypeOf(Easing.quadOut, Easing.prototype);
(Easing.quadOut as Mutable<Easing>).type = "quad-out";
(Easing as Mutable<typeof Easing>).quadInOut = function (u: number): number {
u *= 2;
if (u <= 1) {
u = u * u;
} else {
u -= 1;
u = u * (2 - u);
u += 1;
}
u /= 2;
return u;
} as Easing;
Object.setPrototypeOf(Easing.quadInOut, Easing.prototype);
(Easing.quadInOut as Mutable<Easing>).type = "quad-in-out";
(Easing as Mutable<typeof Easing>).cubicIn = function (u: number): number {
return u * u * u;
} as Easing;
Object.setPrototypeOf(Easing.cubicIn, Easing.prototype);
(Easing.cubicIn as Mutable<Easing>).type = "cubic-in";
(Easing as Mutable<typeof Easing>).cubicOut = function (u: number): number {
u -= 1;
u = u * u * u;
u += 1;
return u;
} as Easing;
Object.setPrototypeOf(Easing.cubicOut, Easing.prototype);
(Easing.cubicOut as Mutable<Easing>).type = "cubic-out";
(Easing as Mutable<typeof Easing>).cubicInOut = function (u: number): number {
u *= 2;
if (u <= 1) {
u = u * u * u;
} else {
u -= 2;
u = u * u * u;
u += 2;
}
u /= 2;
return u;
} as Easing;
Object.setPrototypeOf(Easing.cubicInOut, Easing.prototype);
(Easing.cubicInOut as Mutable<Easing>).type = "cubic-in-out";
(Easing as Mutable<typeof Easing>).quartIn = function (u: number): number {
return u * u * u * u;
} as Easing;
Object.setPrototypeOf(Easing.quartIn, Easing.prototype);
(Easing.quartIn as Mutable<Easing>).type = "quart-in";
(Easing as Mutable<typeof Easing>).quartOut = function (u: number): number {
u -= 1;
return 1 - u * u * u * u;
} as Easing;
Object.setPrototypeOf(Easing.quartOut, Easing.prototype);
(Easing.quartOut as Mutable<Easing>).type = "quart-out";
(Easing as Mutable<typeof Easing>).quartInOut = function (u: number): number {
const v = u - 1;
return u < 0.5 ? 8 * u * u * u * u : 1 - 8 * v * v * v * v;
} as Easing;
Object.setPrototypeOf(Easing.quartInOut, Easing.prototype);
(Easing.quartInOut as Mutable<Easing>).type = "quart-in-out";
(Easing as Mutable<typeof Easing>).expoIn = function (u: number): number {
if (u === 0) {
return 0;
}
return Math.pow(2, 10 * (u - 1) );
} as Easing;
Object.setPrototypeOf(Easing.expoIn, Easing.prototype);
(Easing.expoIn as Mutable<Easing>).type = "expo-in";
(Easing as Mutable<typeof Easing>).expoOut = function (u: number): number {
if (u === 1) {
return 1;
}
return (-Math.pow(2, -10 * u) + 1);
} as Easing;
Object.setPrototypeOf(Easing.expoOut, Easing.prototype);
(Easing.expoOut as Mutable<Easing>).type = "expo-out";
(Easing as Mutable<typeof Easing>).expoInOut = function (u: number): number {
if (u === 1 || u === 0) {
return u;
}
u *= 2;
if (u < 1) {
return 0.5 * Math.pow(2, 10 * (u - 1));
}
return 0.5 * (-Math.pow(2, -10 * (u - 1)) + 2);
} as Easing;
Object.setPrototypeOf(Easing.expoInOut, Easing.prototype);
(Easing.expoInOut as Mutable<Easing>).type = "expo-in-out";
(Easing as Mutable<typeof Easing>).circIn = function (u: number): number {
return -1 * (Math.sqrt(1 - (u / 1) * u) - 1);
} as Easing;
Object.setPrototypeOf(Easing.circIn, Easing.prototype);
(Easing.circIn as Mutable<Easing>).type = "circ-in";
(Easing as Mutable<typeof Easing>).circOut = function (u: number): number {
u -= 1;
return Math.sqrt(1 - u * u);
} as Easing;
Object.setPrototypeOf(Easing.circOut, Easing.prototype);
(Easing.circOut as Mutable<Easing>).type = "circ-out";
(Easing as Mutable<typeof Easing>).circInOut = function (u: number): number {
u *= 2;
if (u < 1) {
return -0.5 * (Math.sqrt(1 - u * u) - 1);
}
const st = u - 2;
return 0.5 * (Math.sqrt(1 - st * st) + 1);
} as Easing;
Object.setPrototypeOf(Easing.circInOut, Easing.prototype);
(Easing.circInOut as Mutable<Easing>).type = "circ-in-out";
(Easing as Mutable<typeof Easing>).backIn = function (u: number): number {
const m = 1.70158; // m - Magnitude
return u * u * (( m + 1) * u - m);
} as Easing;
Object.setPrototypeOf(Easing.backIn, Easing.prototype);
(Easing.backIn as Mutable<Easing>).type = "back-in";
(Easing as Mutable<typeof Easing>).backOut = function (u: number): number {
const m = 1.70158;
const st = (u / 1) - 1;
return (st * st * ((m + 1) * m + m)) + 1;
} as Easing;
Object.setPrototypeOf(Easing.backOut, Easing.prototype);
(Easing.backOut as Mutable<Easing>).type = "back-out";
(Easing as Mutable<typeof Easing>).backInOut = function (u: number): number {
const m = 1.70158;
const s = m * 1.525;
if ((u *= 2) < 1) {
return 0.5 * u * u * (((s + 1) * u) - s);
}
const st = u - 2;
return 0.5 * (st * st * ((s + 1) * st + s) + 2);
} as Easing;
Object.setPrototypeOf(Easing.backInOut, Easing.prototype);
(Easing.backInOut as Mutable<Easing>).type = "back-in-out";
(Easing as Mutable<typeof Easing>).elasticIn = function (u: number): number {
if (u === 0 || u === 1) {
return u;
}
const m = 0.7;
const st = (u / 1) - 1;
const s = (1 - m) / 2 * Math.PI * Math.asin(1);
return -(Math.pow(2, 10 * st) * Math.sin((st - s) * 2 * Math.PI / (1 - m)));
} as Easing;
Object.setPrototypeOf(Easing.elasticIn, Easing.prototype);
(Easing.elasticIn as Mutable<Easing>).type = "elastic-in";
(Easing as Mutable<typeof Easing>).elasticOut = function (u: number): number {
if (u === 0 || u === 1) {
return u;
}
const m = 0.7;
const s = (1 - m) / (2 * Math.PI) * Math.asin(1);
u *= 2;
return (Math.pow(2, -10 * u) * Math.sin((u - s) * 2 * Math.PI / (1 - m))) + 1;
} as Easing;
Object.setPrototypeOf(Easing.elasticOut, Easing.prototype);
(Easing.elasticOut as Mutable<Easing>).type = "elastic-out";
(Easing as Mutable<typeof Easing>).elasticInOut = function (u: number): number {
if (u === 0 || u === 1) {
return u;
}
const m = 0.65;
const s = (1 - m) / (2 * Math.PI) * Math.asin(1);
const st = u * 2;
const st1 = st - 1;
if(st < 1) {
return -0.5 * (Math.pow(2, 10 * st1) * Math.sin((st1 - s) * 2 * Math.PI / (1 - m)));
}
return (Math.pow(2, -10 * st1) * Math.sin((st1 - s) * 2 * Math.PI / (1 - m)) * 0.5) + 1;
} as Easing;
Object.setPrototypeOf(Easing.elasticInOut, Easing.prototype);
(Easing.elasticInOut as Mutable<Easing>).type = "elastic-in-out";
(Easing as Mutable<typeof Easing>).bounceIn = function (u: number): number {
const p = 7.5625;
if ((u = 1 - u) < 1 / 2.75) {
return 1 - (p * u * u);
} else if (u < 2 / 2.75) {
return 1 - (p * (u -= 1.5 / 2.75) * u + 0.75);
} else if (u < 2.5 / 2.75) {
return 1 - (p * (u -= 2.25 / 2.75) * u + 0.9375);
}
return 1 - (p * (u -= 2.625 / 2.75) * u + 0.984375);
} as Easing;
Object.setPrototypeOf(Easing.bounceIn, Easing.prototype);
(Easing.bounceIn as Mutable<Easing>).type = "bounce-in";
(Easing as Mutable<typeof Easing>).bounceOut = function (u: number): number {
const p = 7.5625;
if (u < 1 / 2.75) {
return p * u * u;
} else if (u < 2 / 2.75) {
return p * (u -= 1.5 / 2.75) * u + 0.75;
} else if (u < 2.5 / 2.75) {
return p * (u -= 2.25 / 2.75) * u + 0.9375;
}
return p * (u -= 2.625 / 2.75) * u + 0.984375;
} as Easing;
Object.setPrototypeOf(Easing.bounceOut, Easing.prototype);
(Easing.bounceOut as Mutable<Easing>).type = "bounce-out";
(Easing as Mutable<typeof Easing>).bounceInOut = function (u: number): number {
const invert = u < 0.5;
u = invert ? 1 - (u * 2) : (u * 2) - 1;
const p = 7.5625;
if (u < 1 / 2.75) {
u = p * u * u;
} else if (u < 2 / 2.75) {
u = p * (u -= 1.5 / 2.75) * u + 0.75;
} else if (u < 2.5 / 2.75) {
u = p * (u -= 2.25 / 2.75) * u + 0.9375;
} else {
u = p * (u -= 2.625 / 2.75) * u + 0.984375;
}
return invert ? (1 - u) * 0.5 : u * 0.5 + 0.5;
} as Easing;
Object.setPrototypeOf(Easing.bounceInOut, Easing.prototype);
(Easing.bounceInOut as Mutable<Easing>).type = "bounce-in-out";
return Easing;
})(Timing); | the_stack |
import { assert, expect } from 'chai';
import 'mocha';
import { Index } from '../lib/index';
import { Series } from '../lib/series';
import { DataFrame } from '../lib/dataframe';
describe('Series join', () => {
it('can get union of 2 series with unique values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [7, 8] })
var result = series1.union(series2);
expect(result.toArray()).to.eql([5, 6, 7, 8]);
});
it('can get union of 2 series with overlapping values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [6, 7] })
var result = series1.union(series2);
expect(result.toArray()).to.eql([5, 6, 7]);
});
it('union can work with selector', () => {
var series1 = new Series({ values: [{ X: 5 }, { X: 6 }] })
var series2 = new Series({ values: [{ X: 6 }, { X: 7 }] })
var result = series1.union(series2, row=> row.X);
expect(result.toArray()).to.eql([ { X: 5 }, { X: 6 }, { X: 7 }]);
});
it('can get intersection of 2 series with overlapping values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [6, 7] })
var result = series1.intersection(series2);
expect(result.toArray()).to.eql([6]);
});
it('intersection result is empty for 2 series that have no overlapping values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [7, 8] })
var result = series1.intersection(series2);
expect(result.toArray()).to.eql([]);
});
it('intersection can work with selector', () => {
var series1 = new Series({ values: [{ X: 5 }, { X: 6 }] })
var series2 = new Series({ values: [{ X: 6 }, { X: 7 }] })
var result = series1.intersection(series2, left => left.X, right => right.X);
expect(result.toArray()).to.eql([ { X: 6 }, ]);
});
it('can get exception of 2 series with overlapping values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [6, 7] })
var result = series1.except(series2);
expect(result.toArray()).to.eql([5]);
});
it('exception result is empty for 2 series that have fully overlapping values', () => {
var series1 = new Series({ values: [5, 6] })
var series2 = new Series({ values: [5, 6] })
var result = series1.except(series2);
expect(result.toArray()).to.eql([]);
});
it('except can work with selector', () => {
var series1 = new Series({ values: [{ X: 5 }, { X: 6 }] })
var series2 = new Series({ values: [{ X: 6 }, { X: 7 }] })
var result = series1.except(series2, left => left.X, right => right.X);
expect(result.toArray()).to.eql([ { X: 5 }, ]);
});
it('can merge on column', () => {
var left = new Series([
{
mergeKey: 'foo',
leftVal: 1,
},
{
mergeKey: 'foo',
leftVal: 2,
},
]);
var right = new Series([
{
mergeKey: 'foo',
rightVal: 4,
otherRightVal: 100,
},
{
mergeKey: 'foo',
rightVal: 5,
otherRightVal: 200,
},
]);
var merged = left.join(
right,
leftRow => leftRow.mergeKey,
rightRow => rightRow.mergeKey,
(leftRow, rightRow) => {
return {
mergeKey: leftRow.mergeKey,
leftVal: leftRow.leftVal,
rightVal: rightRow.rightVal,
otherRightVal: rightRow.otherRightVal,
};
}
);
expect(merged.toArray()).to.eql([
{
mergeKey: "foo",
leftVal: 1,
rightVal: 4,
otherRightVal: 100,
},
{
mergeKey: "foo",
leftVal: 1,
rightVal: 5,
otherRightVal: 200,
},
{
mergeKey: "foo",
leftVal: 2,
rightVal: 4,
otherRightVal: 100,
},
{
mergeKey: "foo",
leftVal: 2,
rightVal: 5,
otherRightVal: 200,
},
]);
});
// http://blogs.geniuscode.net/RyanDHatch/?p=116
it('outer join', () => {
var ryan = { Name: "Ryan" };
var jer = { Name: "Jer" };
var people = new Series([ ryan, jer ]);
var camp = { Name: "Camp", Owner: "Ryan" };
var brody = { Name: "Brody", Owner: "Ryan", };
var homeless = { Name: "Homeless" };
var dogs = new Series([ camp, brody, homeless ]);
var join = people.joinOuter(
dogs,
person => person.Name,
dog => dog.Owner,
(person, dog) => {
var output: any = {};
if (person) {
output.Person = person.Name;
}
if (dog) {
output.Dog = dog.Name;
}
return output;
}
)
;
expect(join.toArray()).to.eql([
{
Person: "Jer",
},
{
Person: "Ryan",
Dog: "Camp",
},
{
Person: "Ryan",
Dog: "Brody",
},
{
Dog: "Homeless",
},
]);
});
/*TODO:
//
// These tests based on these examples:
//
// http://chrisalbon.com/python/pandas_join_merge_dataframe.html
//
describe('pandas-examples', () => {
var df_a;
var df_b;
var df_n;
beforeEach(() => {
df_a = new DataFrame({
columnNames: [
'subject_id',
'first_name',
'last_name',
],
values: [
[1, 'Alex', 'Anderson'],
[2, 'Amy', 'Ackerman'],
[3, 'Allen', 'Ali'],
[4, 'Alice', 'Aoni'],
[5, 'Ayoung', 'Aitches'],
],
});
df_b = new DataFrame({
columnNames: [
'subject_id',
'first_name',
'last_name',
],
values: [
[4, 'Billy', 'Bonder'],
[5, 'Brian', 'Black'],
[6, 'Bran', 'Balwner'],
[7, 'Bryce', 'Brice'],
[8, 'Betty', 'Btisan'],
],
});
df_n = new DataFrame({
columnNames: [
"subject_id",
"test_id",
],
values: [
[1, 51],
[2, 15],
[3, 15],
[4, 61],
[5, 16],
[7, 14],
[8, 15],
[9, 1],
[10, 61],
[11, 16],
],
});
});
it('Join the two dataframes along rows', () => {
var df_new = concatDataFrames([df_a, df_b]);
expect(df_new.getIndex().toArray()).to.eql([
0, 1, 2, 3, 4,
0, 1, 2, 3, 4,
]);
expect(df_new.toRows()).to.eql([
[1, 'Alex', 'Anderson'],
[2, 'Amy', 'Ackerman'],
[3, 'Allen', 'Ali'],
[4, 'Alice', 'Aoni'],
[5, 'Ayoung', 'Aitches'],
[4, 'Billy', 'Bonder'],
[5, 'Brian', 'Black'],
[6, 'Bran', 'Balwner'],
[7, 'Bryce', 'Brice'],
[8, 'Betty', 'Btisan'],
]);
});
it('Join the two dataframes along columns', () => {
var df_new = concatDataFrames([df_a, df_b], { axis: 1 });
expect(df_new.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_new.getColumnNames()).to.eql([
'subject_id.1',
'first_name.1',
'last_name.1',
'subject_id.2',
'first_name.2',
'last_name.2',
]);
expect(df_new.toRows()).to.eql([
[1, 'Alex', 'Anderson', 4, 'Billy', 'Bonder'],
[2, 'Amy', 'Ackerman', 5, 'Brian', 'Black'],
[3, 'Allen', 'Ali', 6, 'Bran', 'Balwner'],
[4, 'Alice', 'Aoni', 7, 'Bryce', 'Brice'],
[5, 'Ayoung', 'Aitches', 8, 'Betty', 'Btisan'],
]);
});
it('Merge two dataframes along the subject_id value', () => {
var df_new = concatDataFrames([df_a, df_b]);
var df_merged = df_new
.join(
df_n,
function (rowA) {
return rowA.subject_id;
},
function (rowB) {
return rowB.subject_id;
},
function (rowA, rowB) {
return {
subject_id: rowA.subject_id,
first_name: rowA.first_name,
last_name: rowA.last_name,
test_id: rowB.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
it('Merge two dataframes along the subject_id value', () => {
var df_new = concatDataFrames([df_a, df_b]);
var df_merged = df_new.join(
df_n,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
return {
subject_id: left.subject_id,
first_name: left.first_name,
last_name: left.last_name,
test_id: right.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
// Exactly the same as the previous example.
it('Merge two dataframes with both the left and right dataframes using the subject_id key', () => {
var df_new = concatDataFrames([df_a, df_b]);
var df_merged = df_new.join(
df_n,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
return {
subject_id: left.subject_id,
first_name: left.first_name,
last_name: left.last_name,
test_id: right.test_id,
};
}
)
;
expect(df_merged.getIndex().take(9).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7, 8,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name',
'last_name',
"test_id",
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 51],
[2, 'Amy', 'Ackerman', 15],
[3, 'Allen', 'Ali', 15],
[4, 'Alice', 'Aoni', 61],
[5, 'Ayoung', 'Aitches', 16],
[4, 'Billy', 'Bonder', 61], // Note this is slighly different to the ordering from Pandas.
[5, 'Brian', 'Black', 16],
[7, 'Bryce', 'Brice', 14],
[8, 'Betty', 'Btisan', 15],
]);
});
it('Merge with outer join', () => {
var df_merged = df_a.joinOuter(
df_b,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
var output = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(8).toArray()).to.eql([
0, 1, 2, 3, 4, 5, 6, 7
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
[6, undefined, undefined, 'Bran', 'Balwner'],
[7, undefined, undefined, 'Bryce', 'Brice'],
[8, undefined, undefined, 'Betty', 'Btisan'],
]);
});
it('Merge with inner join', () => {
var df_merged = df_a.join(
df_b,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
return {
subject_id: left.subject_id,
first_name_x: left.first_name,
last_name_x: left.last_name,
first_name_y: right.first_name,
last_name_y: right.last_name,
};
}
)
;
expect(df_merged.getIndex().take(2).toArray()).to.eql([
0, 1,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
it('Merge with right join', () => {
var df_merged = df_a.joinOuterRight(
df_b,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
var output = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
[6, undefined, undefined, 'Bran', 'Balwner'],
[7, undefined, undefined, 'Bryce', 'Brice'],
[8, undefined, undefined, 'Betty', 'Btisan'],
]);
});
it('Merge with left join', () => {
var df_merged = df_a.joinOuterLeft(
df_b,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
var output = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_x = left.first_name;
output.last_name_x = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_y = right.first_name;
output.last_name_y = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_x',
'last_name_x',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
it('Merge while adding a suffix to duplicate column names', () => {
var df_merged = df_a.joinOuterLeft(
df_b,
left => left.subject_id,
right => right.subject_id,
(left, right) => {
var output = {};
if (left) {
output.subject_id = left.subject_id;
output.first_name_left = left.first_name;
output.last_name_left = left.last_name;
}
if (right) {
output.subject_id = right.subject_id;
output.first_name_right = right.first_name;
output.last_name_right = right.last_name;
}
return output;
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id',
'first_name_left',
'last_name_left',
'first_name_right',
'last_name_right',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', undefined, undefined],
[2, 'Amy', 'Ackerman', undefined, undefined],
[3, 'Allen', 'Ali', undefined, undefined],
[4, 'Alice', 'Aoni', 'Billy', 'Bonder'],
[5, 'Ayoung', 'Aitches', 'Brian', 'Black'],
]);
});
it('Merge based on indexes', () => {
var df_merged = df_a.join(
df_b,
(left, index) => index,
(right, index) => index,
(left, right) => {
return {
subject_id_x: left.subject_id,
first_name_x: left.first_name,
last_name_x: left.last_name,
subject_id_y: right.subject_id,
first_name_y: right.first_name,
last_name_y: right.last_name,
};
}
)
;
expect(df_merged.getIndex().take(5).toArray()).to.eql([
0, 1, 2, 3, 4,
]);
expect(df_merged.getColumnNames()).to.eql([
'subject_id_x',
'first_name_x',
'last_name_x',
'subject_id_y',
'first_name_y',
'last_name_y',
]);
expect(df_merged.toRows()).to.eql([
[1, 'Alex', 'Anderson', 4, 'Billy', 'Bonder'],
[2, 'Amy', 'Ackerman', 5, 'Brian', 'Black'],
[3, 'Allen', 'Ali', 6, 'Bran', 'Balwner'],
[4, 'Alice', 'Aoni', 7, 'Bryce', 'Brice'],
[5, 'Ayoung', 'Aitches', 8, 'Betty', 'Btisan'],
]);
});
*/
}); | the_stack |
import * as _ from 'lodash';
import { Resource } from './resource'
export class Cluster implements Resource {
// http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-optimized_AMI_launch_latest.html
amiIds:any = {
'us-east-1': 'ami-275ffe31',
'us-east-2': 'ami-62745007',
'us-west-1': 'ami-689bc208',
'us-west-2': 'ami-62d35c02',
'eu-west-1': 'ami-95f8d2f3',
'eu-west-2': 'ami-bf9481db',
'eu-central-1': 'ami-085e8a67',
'ap-northeast-1': 'ami-f63f6f91',
'ap-southeast-1': 'ami-b4ae1dd7',
'ap-southeast-2': 'ami-fbe9eb98',
'ca-central-1': 'ami-ee58e58a'
}
public clusterName: string
public subnets: string
public privateSubnets: string
public vpcId: string
public certificate: string
public protocol: Array<string>
private _id: string
private _securityGroup: string
private capacity: number
private instance_type: string
private key_name: string
private max_size: number
private min_size: number
private region: string
private size: number
private max_memory_threshold: number
constructor(opts: any, clusterName: string) {
if (opts.id) {
this._id = opts.id
this._securityGroup = opts.security_group || this.requireSecurityGroup()
} else {
this.capacity = opts.capacity || 1
this.instance_type = opts.instance_type || 't2.micro'
this.key_name = opts.key_name || 'ecs-instance'
this.region = opts.region || 'ap-southeast-2'
this.size = opts.size || 1
this.max_size = opts.max_size || this.size + 1
this.min_size = opts.min_size || 1
this.max_memory_threshold = opts.max_memory_threshold || 80
}
// we always need a vpc and at least one subnet
this.vpcId = opts.vpcId || this.requireVpcId()
this.subnets = opts.subnets || this.requireSubnets()
if (opts.privateSubnets) {
this.privateSubnets = opts.privateSubnets
}
this.protocol = _.castArray(opts.protocol) || ['HTTP']
this.certificate = opts.certificate
this.clusterName = clusterName
if (!this.certificate && _.includes(this.protocol, 'HTTPS')) {
this.requireCertificate()
}
}
get defaultListenerName() {
let protocol = _.first(this.protocol);
return `Cls${protocol}Listener`;
}
get defaultTargetGroupName() {
let protocol = _.first(this.protocol);
return `Cls${protocol}TargetGroup`;
}
requireVpcId() {
throw new TypeError('Cluster requires a VPC Id');
}
requireCertificate() {
throw new TypeError('Cluster requires a Certificate ARN for HTTPS');
}
requireSubnets() {
throw new TypeError('Cluster requires at least one Subnet Id');
}
requireSecurityGroup() {
throw new TypeError('Cluster requires a Security Group for mapping the Load Balancer');
}
ami() {
return this.amiIds[this.region];
}
get name() {
return this.clusterName;
}
get id() {
if (this._id) {
return this._id;
} else {
return { 'Ref': 'ClsCluster'}
}
}
get securityGroup() {
if (this._securityGroup) {
return this._securityGroup;
} else {
return { 'Ref': 'ClsSecurityGroup'}
}
}
get elbRole() {
return { 'Ref': 'ClsELBRole'}
}
generate() {
if (this._id) return {}
return {
'ClsInstanceProfile': {
'Type': 'AWS::IAM::InstanceProfile',
'Properties': {
'Path': '/',
'Roles': [
{ 'Ref': 'ClsInstanceRole' }
]
}
},
'ClsCluster': {
'Type': 'AWS::ECS::Cluster',
'DependsOn': 'ClsELBRole'
},
'ClsLaunchConfiguration': {
'Type': 'AWS::AutoScaling::LaunchConfiguration',
'DependsOn': ['ClsInstanceProfile', 'ClsSecurityGroup'],
'Properties': {
'AssociatePublicIpAddress': true,
'IamInstanceProfile': {
'Ref': 'ClsInstanceProfile'
},
'ImageId': this.ami(),
'InstanceType': this.instance_type,
'KeyName': this.key_name,
'SecurityGroups': [
{
'Ref': 'ClsSecurityGroup'
}
],
'UserData': {
'Fn::Base64': {
'Fn::Sub': '#!/bin/bash -xe\nyum install -y aws-cfn-bootstrap\necho ECS_CLUSTER=${ClsCluster} >> /etc/ecs/ecs.config\n\n# /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --region ${AWS::Region}\n\n/opt/aws/bin/cfn-signal -e 0 --stack ${AWS::StackName} --resource ClsAutoScalingGroup --region ${AWS::Region}\n'
}
}
}
},
'ClsInstanceRole': {
'Type': 'AWS::IAM::Role',
'Properties': {
'AssumeRolePolicyDocument': {
'Statement': [
{
'Action': [
'sts:AssumeRole'
],
'Effect': 'Allow',
'Principal': {
'Service': [
'ec2.amazonaws.com'
]
}
}
]
},
'Path': '/',
'Policies': [
{
'PolicyDocument': {
'Statement': [
{
'Action': [
'ecs:CreateCluster',
'ecs:DeregisterContainerInstance',
'ecs:DiscoverPollEndpoint',
'ecs:Poll',
'ecs:RegisterContainerInstance',
'ecs:StartTelemetrySession',
'ecs:Submit*',
'ecr:BatchCheckLayerAvailability',
'ecr:BatchGetImage',
'ecr:GetDownloadUrlForLayer',
'ecr:GetAuthorizationToken',
'logs:CreateLogStream',
'logs:PutLogEvents'
],
'Effect': 'Allow',
'Resource': '*'
}
]
},
'PolicyName': 'ecs-service-instance'
}
]
},
},
'ClsSecurityGroup': {
'Properties': {
'GroupDescription': 'ECS Public Security Group',
'VpcId': this.vpcId
},
'Type': 'AWS::EC2::SecurityGroup'
},
'ClsSecurityGroupDynamicPorts': {
'Type': 'AWS::EC2::SecurityGroupIngress',
'Properties': {
'IpProtocol': 'tcp',
'FromPort': 31000,
'ToPort': 61000,
'GroupId': {
'Ref': 'ClsSecurityGroup'
},
'SourceSecurityGroupId': {
'Ref': 'ClsSecurityGroup'
}
}
},
'ClsSecurityGroupHTTP': {
'Type': 'AWS::EC2::SecurityGroupIngress',
'Properties': {
'CidrIp': '0.0.0.0/0',
'IpProtocol': 'tcp',
'FromPort': '80',
'ToPort': '80',
'GroupId': {
'Ref': 'ClsSecurityGroup'
}
},
},
'ClsSecurityGroupHTTPS': {
'Type': 'AWS::EC2::SecurityGroupIngress',
'Properties': {
'CidrIp': '0.0.0.0/0',
'IpProtocol': 'tcp',
'FromPort': '443',
'ToPort': '443',
'GroupId': {
'Ref': 'ClsSecurityGroup'
}
}
},
'ClsELBRole': {
'Type': 'AWS::IAM::Role',
'Properties': {
'AssumeRolePolicyDocument': {
'Statement': [
{
'Effect': 'Allow',
'Principal': {
'Service': [
'ecs.amazonaws.com'
]
},
'Action': [
'sts:AssumeRole'
]
}
]
},
'Path': '/',
'Policies': [
{
'PolicyName': 'elb-role-policy',
'PolicyDocument': {
'Statement': [
{
'Effect': 'Allow',
'Resource': '*',
'Action': [
'elasticloadbalancing:DeregisterInstancesFromLoadBalancer',
'elasticloadbalancing:DeregisterTargets',
'elasticloadbalancing:Describe*',
'elasticloadbalancing:RegisterInstancesWithLoadBalancer',
'elasticloadbalancing:RegisterTargets',
'ec2:Describe*',
'ec2:AuthorizeSecurityGroupIngress'
]
}
]
}
}
]
}
},
'ContainerlessASGRole': {
"Type":"AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Statement":[
{
"Effect":"Allow",
"Principal":{
"Service":[
"application-autoscaling.amazonaws.com"
]
},
"Action":[
"sts:AssumeRole"
]
}
]
},
"Path":"/",
"Policies":[
{
"PolicyName":"service-autoscaling",
"PolicyDocument":{
"Statement":[
{
"Effect":"Allow",
"Action":[
"application-autoscaling:*",
"cloudwatch:DescribeAlarms",
"cloudwatch:PutMetricAlarm",
"ecs:DescribeServices",
"ecs:UpdateService"
],
"Resource":"*"
}
]
}
}
]
}
},
'ClsAutoScalingGroup': {
'Type': 'AWS::AutoScaling::AutoScalingGroup',
'CreationPolicy': {
'ResourceSignal': {
'Timeout': 'PT5M'
}
},
'UpdatePolicy': {
'AutoScalingReplacingUpdate': {
'WillReplace': 'true'
},
'AutoScalingRollingUpdate': {
'MinInstancesInService': 1,
'MaxBatchSize': 1,
'PauseTime': 'PT15M',
'WaitOnResourceSignals': 'true'
}
},
'Properties': {
'DesiredCapacity': this.capacity,
'LaunchConfigurationName': {
'Ref': 'ClsLaunchConfiguration'
},
'MaxSize': this.max_size,
'MinSize': this.min_size,
'VPCZoneIdentifier': this.privateSubnets || this.subnets,
'Tags': [
{
'Key': 'Origin',
'Value': 'Containerless',
'PropagateAtLaunch': true
}, {
'Key': 'Name',
'Value': this.name,
'PropagateAtLaunch': true
}
]
}
},
'MemoryReservationScaleUpPolicy': {
'Type': 'AWS::AutoScaling::ScalingPolicy',
'Properties': {
'AdjustmentType': 'PercentChangeInCapacity',
'AutoScalingGroupName': {
'Ref': 'ClsAutoScalingGroup'
},
'Cooldown': '300',
'ScalingAdjustment': '30'
}
},
'MemoryReservationHighAlert': {
'Type': 'AWS::CloudWatch::Alarm',
'Properties': {
'EvaluationPeriods': '1',
'Statistic': 'Maximum',
'Threshold': this.max_memory_threshold,
'AlarmDescription': 'Alarm if CPU too high or metric disappears indicating instance is down',
'Period': '60',
'AlarmActions': [
{ 'Ref': 'MemoryReservationScaleUpPolicy' }
],
'Namespace': 'AWS/ECS',
'Dimensions': [
{
'Name': 'ClusterName',
'Value': {
'Ref': 'ClsCluster'
}
}
],
'ComparisonOperator': 'GreaterThanThreshold',
'MetricName': 'MemoryReservation'
}
}
}
}
} | the_stack |
import {
RadiobuttonIcon,
SliderIcon,
SwitchIcon,
TextIcon,
PlusIcon,
CursorArrowIcon,
FontFamilyIcon,
FontSizeIcon,
LineHeightIcon,
} from '@radix-ui/react-icons';
import React from 'react';
import { Box } from '../components/Box';
import { Button } from '../components/Button';
import { Code } from '../components/Code';
import { Container } from '../components/Container';
import { Flex } from '../components/Flex';
import { Grid } from '../components/Grid';
import { Heading } from '../components/Heading';
import { IconButton } from '../components/IconButton';
import { Paragraph } from '../components/Paragraph';
import { Section } from '../components/Section';
import { Separator } from '../components/Separator';
import { Text } from '../components/Text';
import { TextField } from '../components/TextField';
import { TreeItem } from '../components/TreeItem';
import { ColorTools } from '../custom/ColorTools';
import { darkTheme as darkThemeClassName } from '../stitches.config';
const sidebarWidth = 240;
export const loContrasts = ['lime', 'yellow', 'amber', 'sky', 'mint'];
export const colors = [
'gray',
'mauve',
'slate',
'sage',
'olive',
'sand',
'tomato',
'red',
'crimson',
'pink',
'plum',
'purple',
'violet',
'indigo',
'blue',
'cyan',
'teal',
'green',
'grass',
'brown',
'bronze',
'gold',
'sky',
'mint',
'lime',
'yellow',
'amber',
'orange',
] as const;
export default function Colors() {
const [palette, setPalette] = useLocalStorage('colors-palette', true);
const [layers, setLayers] = useLocalStorage('colors-layers', true);
const [layersAlpha, setLayersAlpha] = useLocalStorage('colors-layers-alpha', false);
const [alerts, setAlerts] = useLocalStorage('colors-alerts', true);
const [alertsAlpha, setAlertsAlpha] = useLocalStorage('colors-alerts-alpha', false);
const [buttons, setButtons] = useLocalStorage('colors-buttons', true);
const [lines, setLines] = useLocalStorage('colors-lines', true);
const [linesAlpha, setLinesAlpha] = useLocalStorage('colors-lines-alpha', false);
const [textBlocks, setTextBlocks] = useLocalStorage('colors-textBlocks', true);
const [alphaScales, setAlphaScales] = useLocalStorage('colors-alphaScales', false);
const [darkTheme, setDarkTheme] = useLocalStorage('colors-darkTheme', false);
const [grayscale, setGrayscale] = useLocalStorage('colors-grayscale', false);
const [blur, setBlur] = useLocalStorage('colors-blur', false);
const [gap, setGap] = useLocalStorage('colors-gap', true);
// No SSR please
if (typeof window === 'undefined') {
return null;
}
React.useLayoutEffect(() => {
document.body.style.filter = grayscale ? 'saturate(0)' : '';
}, [grayscale]);
React.useLayoutEffect(() => {
document.documentElement.classList.toggle('gap', gap);
}, [gap]);
React.useLayoutEffect(() => {
document.body.classList.toggle('theme-default', !darkTheme);
document.body.classList.toggle(darkThemeClassName, darkTheme);
document.documentElement.style.backgroundColor = darkTheme ? 'black' : '';
}, [darkTheme]);
return (
<>
<Section size="3" css={{ py: '$7', ml: sidebarWidth, overflowY: 'scroll', height: '100vh' }}>
<Container size="3" css={{ mb: '$5' }}>
<Box>
<Checkbox defaultChecked={palette} onChange={(e) => setPalette(e.target.checked)}>
Palette
</Checkbox>
<Checkbox defaultChecked={layers} onChange={(e) => setLayers(e.target.checked)}>
Layers
</Checkbox>
<Checkbox
defaultChecked={layersAlpha}
onChange={(e) => setLayersAlpha(e.target.checked)}
>
Layers (Alpha)
</Checkbox>
<Checkbox defaultChecked={buttons} onChange={(e) => setButtons(e.target.checked)}>
Buttons
</Checkbox>
<Checkbox defaultChecked={lines} onChange={(e) => setLines(e.target.checked)}>
Lines
</Checkbox>
<Checkbox defaultChecked={linesAlpha} onChange={(e) => setLinesAlpha(e.target.checked)}>
Lines (Alpha)
</Checkbox>
<Checkbox defaultChecked={alerts} onChange={(e) => setAlerts(e.target.checked)}>
Alerts
</Checkbox>
<Checkbox
defaultChecked={alertsAlpha}
onChange={(e) => setAlertsAlpha(e.target.checked)}
>
Alerts (Alpha)
</Checkbox>
<Checkbox defaultChecked={textBlocks} onChange={(e) => setTextBlocks(e.target.checked)}>
Text Blocks
</Checkbox>
<Separator css={{ my: '$3' }} />
<Checkbox defaultChecked={grayscale} onChange={(e) => setGrayscale(e.target.checked)}>
Grayscale
</Checkbox>
<Checkbox defaultChecked={gap} onChange={(e) => setGap(e.target.checked)}>
Gaps
</Checkbox>
<Checkbox defaultChecked={blur} onChange={(e) => setBlur(e.target.checked)}>
Blur
</Checkbox>
<Checkbox defaultChecked={darkTheme} onChange={(e) => setDarkTheme(e.target.checked)}>
Dark theme
</Checkbox>
<Separator css={{ my: '$3' }} />
<Checkbox
data-alpha-scales
defaultChecked={alphaScales}
onChange={(e) => setAlphaScales(e.target.checked)}
>
Show alpha scales
</Checkbox>
</Box>
</Container>
<div style={{ filter: blur ? 'blur(20px)' : undefined }}>
{palette && <Palette showAlphaScales={alphaScales} />}
{layers && <Layers />}
{layersAlpha && <LayersAlpha />}
{buttons && <Buttons />}
{lines && <Lines />}
{linesAlpha && <LinesAlpha />}
{alerts && <Alerts />}
{alertsAlpha && <AlertsAlpha />}
{textBlocks && <TextBlocks />}
</div>
</Section>
<Sidebar />
</>
);
}
function Sidebar() {
return (
<Box
css={{
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
bc: 'white',
overflowY: 'scroll',
boxShadow: '1px 0 $colors$gray6',
width: 240,
...darkThemeColor('black'),
}}
>
<ColorTools />
</Box>
);
}
function Layers() {
return (
<Container size="4" css={{ p: '$9' }}>
<Grid css={{ gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '$5' }}>
{colors.map((color) => (
<Box key={color}>
<TreeItem css={{ bc: `$${color}5` }}>
<Box css={{ mr: '$2' }}>
<RadiobuttonIcon />
</Box>
<Text size="1">Radio</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}3`,
'&:hover': { bc: `$${color}4` },
'&:active': { bc: `$${color}5` },
}}
>
<Box css={{ mr: '$2' }}>
<SliderIcon />
</Box>
<Text size="1">Slider</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}3`,
'&:hover': { bc: `$${color}4` },
'&:active': { bc: `$${color}5` },
}}
>
<Box css={{ mr: '$2' }}>
<SwitchIcon />
</Box>
<Text size="1">Switch</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}3`,
'&:hover': { bc: `$${color}4` },
'&:active': { bc: `$${color}5` },
}}
>
<Box css={{ mr: '$2' }}>
<TextIcon />
</Box>
<Text size="1">Text</Text>
</TreeItem>
</Box>
))}
</Grid>
</Container>
);
}
function LayersAlpha() {
return (
<Container size="4" css={{ p: '$9' }}>
<Grid css={{ gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: '$5' }}>
{colors.map((color) => (
<Box key={color}>
<TreeItem css={{ bc: `$${color}A5` }}>
<Box css={{ mr: '$2' }}>
<RadiobuttonIcon />
</Box>
<Text size="1">Radio</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}A3`,
'&:hover': { bc: `$${color}A4` },
'&:active': { bc: `$${color}A5` },
}}
>
<Box css={{ mr: '$2' }}>
<SliderIcon />
</Box>
<Text size="1">Slider</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}A3`,
'&:hover': { bc: `$${color}A4` },
'&:active': { bc: `$${color}A5` },
}}
>
<Box css={{ mr: '$2' }}>
<SwitchIcon />
</Box>
<Text size="1">Switch</Text>
</TreeItem>
<TreeItem
css={{
pl: 45,
bc: `$${color}A3`,
'&:hover': { bc: `$${color}A4` },
'&:active': { bc: `$${color}A5` },
}}
>
<Box css={{ mr: '$2' }}>
<TextIcon />
</Box>
<Text size="1">Text</Text>
</TreeItem>
</Box>
))}
</Grid>
</Container>
);
}
function Buttons() {
return (
<Container size="3" css={{ my: '$9' }}>
<Text size="6" as="h4" css={{ fontWeight: 500, lineHeight: '27px', mt: '$8', mb: '$5' }}>
Buttons & TextFields
</Text>
<Grid css={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: '$5' }}>
{colors.map((color) => (
<Box key={color} css={{ '&[class] * + *': { ml: '$2', verticalAlign: 'top' } }}>
<Button variant="gray">Neutral</Button>
<Button
css={{
fontWeight: 500,
textTransform: 'capitalize',
backgroundColor: `$${color}2`,
boxShadow: `inset 0 0 0 1px $colors$${color}7`,
color: `$${color}11`,
'@hover': {
'&:hover': {
boxShadow: `inset 0 0 0 1px $colors$${color}8`,
},
},
'&:active': {
backgroundColor: `$${color}3`,
boxShadow: `inset 0 0 0 1px $colors$${color}8`,
},
'&:focus': {
boxShadow: `inset 0 0 0 1px $colors$${color}8, 0 0 0 1px $colors$${color}8`,
},
}}
>
{color}
</Button>
<Button
css={{
fontWeight: 500,
textTransform: 'capitalize',
backgroundColor: `$${color}A2`,
boxShadow: `inset 0 0 0 1px $colors$${color}A7`,
color: `$${color}A11`,
'@hover': {
'&:hover': {
boxShadow: `inset 0 0 0 1px $colors$${color}A8`,
},
},
'&:active': {
backgroundColor: `$${color}A3`,
boxShadow: `inset 0 0 0 1px $colors$${color}A8`,
},
'&:focus': {
boxShadow: `inset 0 0 0 1px $colors$${color}A8, 0 0 0 1px $colors$${color}A8`,
},
}}
>
{color} A
</Button>
</Box>
))}
</Grid>
<Grid css={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: '$2', mt: '$7' }}>
{colors.map((color) => (
<Box
key={color}
css={{
...darkThemeColor(`$${color}1`),
p: '$2',
borderRadius: '$2',
boxShadow: `inset 0 0 0 1px $colors$${color}6`,
'&[class] * + *': { ml: '$1', verticalAlign: 'top' },
'@hover': {
'button:hover': {
backgroundColor: `$${color}A3`,
},
},
'button:focus': {
boxShadow: `inset 0 0 0 1px $colors$${color}A8, 0 0 0 1px $colors$${color}A8`,
},
'button:active': {
backgroundColor: `$${color}A4`,
},
}}
>
<IconButton>
<PlusIcon />
</IconButton>
<IconButton>
<CursorArrowIcon />
</IconButton>
<IconButton>
<TextIcon />
</IconButton>
<IconButton>
<FontFamilyIcon />
</IconButton>
<IconButton>
<FontSizeIcon />
</IconButton>
<IconButton>
<LineHeightIcon />
</IconButton>
<Text
size="2"
css={{ display: 'inline', lineHeight: '25px', textTransform: 'capitalize' }}
>
{color}
</Text>
</Box>
))}
</Grid>
<Grid css={{ gridTemplateColumns: 'repeat(4, 1fr)', gap: '$5', mt: '$7' }}>
<TextField
size="2"
placeholder="Gray"
css={{
...darkThemeColor('$gray1'),
boxShadow: 'inset 0 0 0 1px $colors$gray7',
color: '$gray12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$gray6, inset 0 0 0 100px $colors$gray3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$gray8, 0px 0px 0px 1px $colors$gray8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$gray8, 0px 0px 0px 1px $colors$gray8, inset 0 0 0 100px $colors$gray3',
},
},
'&::placeholder': {
color: '$gray9',
},
}}
/>
<TextField
size="2"
placeholder="Gray (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$grayA7',
color: '$grayA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$grayA6, inset 0 0 0 100px $colors$grayA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$grayA8, 0px 0px 0px 1px $colors$grayA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$grayA8, 0px 0px 0px 1px $colors$grayA8, inset 0 0 0 100px $colors$grayA3',
},
},
'&::placeholder': {
color: '$grayA9',
},
}}
/>
<TextField
size="2"
placeholder="Mauve & Plum"
css={{
...darkThemeColor('$mauve1'),
boxShadow: 'inset 0 0 0 1px $colors$mauve7',
color: '$mauve12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$plum6, inset 0 0 0 100px $colors$plum3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$plum8, 0px 0px 0px 1px $colors$plum8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$plum8, 0px 0px 0px 1px $colors$plum8, inset 0 0 0 100px $colors$plum3',
},
},
'&::placeholder': {
color: '$mauve9',
},
}}
/>
<TextField
size="2"
placeholder="Mauve & Plum (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$mauveA7',
color: '$mauveA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$plumA6, inset 0 0 0 100px $colors$plumA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$plumA8, 0px 0px 0px 1px $colors$plumA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$plumA8, 0px 0px 0px 1px $colors$plumA8, inset 0 0 0 100px $colors$plumA3',
},
},
'&::placeholder': {
color: '$mauveA9',
},
}}
/>
<TextField
size="2"
placeholder="Slate & Blue"
css={{
...darkThemeColor('$slate1'),
boxShadow: 'inset 0 0 0 1px $colors$slate7',
color: '$slate12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$blue6, inset 0 0 0 100px $colors$blue3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$blue8, 0px 0px 0px 1px $colors$blue8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$blue8, 0px 0px 0px 1px $colors$blue8, inset 0 0 0 100px $colors$blue3',
},
},
'&::placeholder': {
color: '$slate9',
},
}}
/>
<TextField
size="2"
placeholder="Slate & Blue (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$slateA7',
color: '$slateA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$blueA6, inset 0 0 0 100px $colors$blueA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$blueA8, 0px 0px 0px 1px $colors$blueA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$blueA8, 0px 0px 0px 1px $colors$blueA8, inset 0 0 0 100px $colors$blueA3',
},
},
'&::placeholder': {
color: '$slateA9',
},
}}
/>
<TextField
size="2"
placeholder="Sage & Teal"
css={{
...darkThemeColor('$sage1'),
boxShadow: 'inset 0 0 0 1px $colors$sage7',
color: '$sage12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$teal6, inset 0 0 0 100px $colors$teal3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$teal8, 0px 0px 0px 1px $colors$teal8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$teal8, 0px 0px 0px 1px $colors$teal8, inset 0 0 0 100px $colors$teal3',
},
},
'&::placeholder': {
color: '$sage9',
},
}}
/>
<TextField
size="2"
placeholder="Sage & Teal (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$sageA7',
color: '$sageA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$tealA6, inset 0 0 0 100px $colors$tealA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$tealA8, 0px 0px 0px 1px $colors$tealA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$tealA8, 0px 0px 0px 1px $colors$tealA8, inset 0 0 0 100px $colors$tealA3',
},
},
'&::placeholder': {
color: '$sageA9',
},
}}
/>
<TextField
size="2"
placeholder="Olive & Lime"
css={{
...darkThemeColor('$olive1'),
boxShadow: 'inset 0 0 0 1px $colors$olive7',
color: '$olive12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$lime6, inset 0 0 0 100px $colors$lime3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$lime8, 0px 0px 0px 1px $colors$lime8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$lime8, 0px 0px 0px 1px $colors$lime8, inset 0 0 0 100px $colors$lime3',
},
},
'&::placeholder': {
color: '$olive9',
},
}}
/>
<TextField
size="2"
placeholder="Olive & Lime (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$oliveA7',
color: '$oliveA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$limeA6, inset 0 0 0 100px $colors$limeA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$limeA8, 0px 0px 0px 1px $colors$limeA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$limeA8, 0px 0px 0px 1px $colors$limeA8, inset 0 0 0 100px $colors$limeA3',
},
},
'&::placeholder': {
color: '$oliveA9',
},
}}
/>
<TextField
size="2"
placeholder="Sand & Amber"
css={{
...darkThemeColor('$sand1'),
boxShadow: 'inset 0 0 0 1px $colors$sand7',
color: '$sand12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$amber6, inset 0 0 0 100px $colors$amber3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$amber8, 0px 0px 0px 1px $colors$amber8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$amber8, 0px 0px 0px 1px $colors$amber8, inset 0 0 0 100px $colors$amber3',
},
},
'&::placeholder': {
color: '$sand9',
},
}}
/>
<TextField
size="2"
placeholder="Sand & Amber (Alpha)"
css={{
bc: 'transparent',
boxShadow: 'inset 0 0 0 1px $colors$sandA7',
color: '$sandA12',
fontVariantNumeric: 'tabular-nums',
'&:-webkit-autofill': {
boxShadow: 'inset 0 0 0 1px $colors$amberA6, inset 0 0 0 100px $colors$amberA3',
},
'&:-webkit-autofill::first-line': {
fontFamily: '$untitled',
color: '$hiContrast',
},
'&:focus': {
boxShadow: 'inset 0px 0px 0px 1px $colors$amberA8, 0px 0px 0px 1px $colors$amberA8',
'&:-webkit-autofill': {
boxShadow:
'inset 0px 0px 0px 1px $colors$amberA8, 0px 0px 0px 1px $colors$amberA8, inset 0 0 0 100px $colors$amberA3',
},
},
'&::placeholder': {
color: '$sandA9',
},
}}
/>
</Grid>
<Grid css={{ gridTemplateColumns: 'repeat(8, 1fr)', gap: '$5', mt: '$9' }}>
{colors.map((color) => (
<Box key={color} css={{ '&[class] * + *': { ml: '$2', verticalAlign: 'top' } }}>
<Button
size="2"
css={{
// fontWeight: 5,
textTransform: 'capitalize',
backgroundColor: `$${color}9`,
color: getHiContrast(color),
boxShadow: 'none',
borderRadius: '$pill',
'@hover': {
'&:hover': {
color: getHiContrast(color),
boxShadow: 'none',
backgroundColor: `var(--colors-${color}10)`,
},
},
'&:active': {
boxShadow: 'none',
color: 'white',
backgroundColor: `$${color}11`,
},
'&:focus': {
boxShadow: `0 0 0 2px $colors$${color}7`,
},
}}
>
{color}
</Button>
</Box>
))}
</Grid>
</Container>
);
}
function Lines() {
return (
<Container size="2" css={{ my: '$9' }}>
<Text size="6" as="h4" css={{ fontWeight: 500, lineHeight: '27px', mt: '$8', mb: '$1' }}>
Lines
</Text>
<Paragraph css={{ mb: '$7' }}>
The <Code>6</Code> line should be very subtle, but visible on all backgrounds.
</Paragraph>
<Flex css={{ position: 'relative' }}>
<Box
css={{
fb: '0',
fg: 1,
height: 160,
backgroundColor: '$gray1',
}}
></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$gray2' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$gray3' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$gray4' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$gray5' }}></Box>
<Box
css={{
position: 'absolute',
top: '50%',
left: '0',
width: '100%',
height: 1,
backgroundColor: '$gray6',
}}
></Box>
</Flex>
</Container>
);
}
function LinesAlpha() {
return (
<Container size="2" css={{ my: '$9' }}>
<Text size="6" as="h4" css={{ fontWeight: 500, lineHeight: '27px', mt: '$8', mb: '$1' }}>
Lines (Alpha)
</Text>
<Paragraph css={{ mb: '$7' }}>
The <Code>6</Code> line should be very subtle, but visible on all backgrounds.
</Paragraph>
<Flex css={{ position: 'relative' }}>
<Box
css={{
fb: '0',
fg: 1,
height: 160,
backgroundColor: '$grayA1',
}}
></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$grayA2' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$grayA3' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$grayA4' }}></Box>
<Box css={{ fb: '0', fg: 1, height: 160, backgroundColor: '$grayA5' }}></Box>
<Box
css={{
position: 'absolute',
top: '50%',
left: '0',
width: '100%',
height: 1,
backgroundColor: '$grayA6',
}}
></Box>
</Flex>
</Container>
);
}
function Alerts() {
return (
<Container size="3" css={{ mb: '$9' }}>
<Text size="6" as="h4" css={{ fontWeight: 500, lineHeight: '27px', mt: '$8', mb: '$5' }}>
Alerts
</Text>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box key={color} css={{ p: '$4', borderRadius: '$3', bc: `$${color}9` }}>
<Text size="2" as="p" css={{ color: getHiContrast(color) }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
bc: `$${color}2`,
borderLeft: `2px solid $${color}6`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
bc: `$${color}2`,
borderLeft: `3px solid $${color}8`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
borderRadius: '$3',
bc: `$${color}3`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}12` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
borderRadius: '$3',
bc: `$${color}2`,
border: `1px solid $${color}6`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
</Container>
);
}
function AlertsAlpha() {
return (
<Container size="3" css={{ mb: '$9' }}>
<Text size="6" as="h4" css={{ fontWeight: 500, lineHeight: '27px', mt: '$8', mb: '$5' }}>
Alerts (Alpha)
</Text>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
bc: `$${color}A2`,
borderLeft: `2px solid $${color}A6`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}A11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
bc: `$${color}A2`,
borderLeft: `3px solid $${color}A8`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}A11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
borderRadius: '$3',
bc: `$${color}A3`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}A12` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
<Grid
css={{
gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',
gap: '$3',
mb: '$9',
ai: 'center',
}}
>
{colors.map((color) => (
<Box
key={color}
css={{
p: '$4',
borderRadius: '$3',
bc: `$${color}A2`,
border: `1px solid $${color}A6`,
}}
>
<Text size="2" as="p" css={{ color: `$${color}A11` }}>
Warning: obsessing over {color} is a terrible idea.
</Text>
</Box>
))}
</Grid>
</Container>
);
}
function TextBlocks() {
const text = `The pigeon guillemot (Cepphus columba) is a species of bird in the auk family, Alcidae.
One of three species in the genus Cepphus, it is most closely related to the spectacled
guillemot. There are five subspecies of the pigeon guillemot; all subspecies, when in
breeding plumage, are dark brown with a black iridescent sheen and a distinctive wing
patch broken by a brown-black wedge. Its non-breeding plumage has mottled grey and black
upperparts and white underparts. The long bill is black, as are the claws. The legs, feet,
and inside of the mouth are red. It closely resembles the black guillemot, which is
slightly smaller and lacks the dark wing wedge present in the pigeon guillemot. Combined,
the two form a superspecies.`;
return (
<Box css={{ mb: '$9' }}>
{colors.map((color) => {
const color1 = `$${color}1`;
const color2 = `$${color}2`;
const color3 = `$${color}3`;
const color9 = `$${color}9`;
const color12 = `$${color}12`;
return (
<Box key={color} css={{ 'html.gap &': { display: 'grid', gap: '$5' } }}>
<Box css={{ bc: color1, p: 200 }}>
<Container size="3">
<Heading css={{ mb: '$2', color: color12, textTransform: 'capitalize' }}>
{color}
</Heading>
<Text size="3" css={{ lineHeight: '25px', color: color12 }}>
{text}
</Text>
</Container>
</Box>
<Box css={{ bc: color2, p: 200 }}>
<Container size="3">
<Heading css={{ mb: '$2', color: color12, textTransform: 'capitalize' }}>
{color}
</Heading>
<Text size="3" css={{ lineHeight: '25px', color: color12 }}>
{text}
</Text>
</Container>
</Box>
<Box css={{ bc: color3, p: 200 }}>
<Container size="3">
<Heading css={{ mb: '$2', color: color12, textTransform: 'capitalize' }}>
{color}
</Heading>
<Text size="3" css={{ lineHeight: '25px', color: color12 }}>
{text}
</Text>
</Container>
</Box>
<Box css={{ bc: color9, p: 200 }}>
<Container size="3">
<Heading
css={{ mb: '$2', color: getHiContrast(color), textTransform: 'capitalize' }}
>
{color}
</Heading>
<Text size="3" css={{ lineHeight: '25px', color: getHiContrast(color) }}>
{text}
</Text>
</Container>
</Box>
<Box css={{ bc: color12, p: 200 }}>
<Container size="3">
<Heading css={{ mb: '$2', color: color2, textTransform: 'capitalize' }}>
{color}
</Heading>
<Text size="3" css={{ lineHeight: '25px', color: color2 }}>
{text}
</Text>
</Container>
</Box>
</Box>
);
})}
</Box>
);
}
function Palette({ showAlphaScales = false }: { showAlphaScales: boolean }) {
const gridStyle = {
gridAutoRows: '35px',
gridTemplateColumns: 'repeat(13, minmax(0, 1fr))',
'html.gap &': { gap: 2 },
};
return (
<Container size="3">
<Box css={{ mb: '$9', 'html.gap &': { display: 'grid', gap: 2 } }}>
<Grid css={gridStyle}>
<Box></Box>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>1</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>2</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>3</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>4</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>5</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>6</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>7</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>8</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>9</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>10</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>11</Text>
<Text css={{ color: '$gray9', fontSize: '$2', ta: 'center' }}>12</Text>
</Grid>
{colors.map((color) => (
<Grid css={gridStyle} key={color}>
<Box css={{ alignSelf: 'center' }}>
<Text size="2" css={{ textTransform: 'capitalize' }}>
{color}
</Text>
</Box>
<Box
css={{ bc: `$${color}1` }}
onClick={() => {
const thisColor = `var(--colors-${color}1)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}2` }}
onClick={() => {
const thisColor = `var(--colors-${color}2)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}3` }}
onClick={() => {
const thisColor = `var(--colors-${color}3)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}4` }}
onClick={() => {
const thisColor = `var(--colors-${color}4)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}5` }}
onClick={() => {
const thisColor = `var(--colors-${color}5)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}6` }}
onClick={() => {
const thisColor = `var(--colors-${color}6)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}7` }}
onClick={() => {
const thisColor = `var(--colors-${color}7)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}8` }}
onClick={() => {
const thisColor = `var(--colors-${color}8)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}9` }}
onClick={() => {
const thisColor = `var(--colors-${color}9)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}10` }}
onClick={() => {
const thisColor = `var(--colors-${color}10)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}11` }}
onClick={() => {
const thisColor = `var(--colors-${color}11)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
<Box
css={{ bc: `$${color}12` }}
onClick={() => {
const thisColor = `var(--colors-${color}12)`;
const newColor = document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
{showAlphaScales && (
<>
<Box />
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A1`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A1)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A2`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A2)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A3`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A3)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A4`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A4)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A5`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A5)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A6`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A6)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A7`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A7)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A8`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A8)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A9`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A9)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A10`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A10)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A11`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A11)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
<Box css={darkThemeColor(`$${color}1`)}>
<Box
css={{ bc: `$${color}A12`, width: '100%', height: '100%' }}
onClick={() => {
const thisColor = `var(--colors-${color}A12)`;
const newColor =
document.body.style.backgroundColor === thisColor ? '' : thisColor;
document.body.style.backgroundColor = newColor;
}}
/>
</Box>
</>
)}
</Grid>
))}
</Box>
</Container>
);
}
function Checkbox({
children,
...props
}: React.ComponentProps<'input'> & { children?: React.ReactNode }) {
return (
<Box>
<Text size="2" as="label" css={{ display: 'inline-block', lineHeight: '20px' }}>
<input
type="checkbox"
style={{ verticalAlign: 'middle', margin: 0, marginRight: 5, marginTop: -2 }}
{...props}
/>{' '}
{children}
</Text>
</Box>
);
}
export function getHiContrast(color: string) {
if (loContrasts.includes(color)) {
return 'hsl(0, 0%, 0%)';
}
return 'hsl(0, 0%, 100%)';
}
// https://usehooks.com/useLocalStorage/
function useLocalStorage(key: string, initialValue: any) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = React.useState(() => {
if (typeof window === 'undefined') {
return initialValue;
}
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue = (value: any) => {
try {
// Allow value to be a function so we have same API as useState
const valueToStore = value instanceof Function ? value(storedValue) : value;
// Save state
setStoredValue(valueToStore);
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
// A more advanced implementation would handle the error case
console.log(error);
}
};
return [storedValue, setValue];
}
function darkThemeColor(color: string): any {
return {
[`body.${darkThemeClassName} &`]: {
bc: color,
},
};
} | the_stack |
import { workspace, commands, InputBoxOptions, window } from 'vscode';
import { getSymbolKind, SystemVerilogSymbol } from '../symbol';
/**
* Processing states:
* --------------------------------------------
* INITIAL: before the ports/parameters header.
* PARAMETERS: inside the parameters header.
* PORTS: inside the ports header.
* COMPLETE: processing is finished.
* --------------------------------------------
*/
enum processingState {
INITIAL = 1,
PARAMETERS = 2,
PORTS = 3,
COMPLETE = 4
}
/**
* Key symbols
*/
const ports_key_symbols = ['input', 'output', 'inout'];
const parameter_key_symbol = 'parameter';
/**
* Space padding
*/
const padding = ' '.repeat(workspace.getConfiguration(null, null).get('editor.tabSize'));
/**
* Non-breaking white space
*/
const non_breaking_space = '\xa0';
/**
Checks if symbol is a port.
@param symbol the symbol
@return true, if symbol is a port
*/
function isPortSymbol(symbol: string): boolean {
if (isEmptyKey(symbol)) {
return false;
}
let exists = false;
// eslint-disable-next-line no-param-reassign
symbol = symbol.trim();
ports_key_symbols.forEach((key) => {
if (symbol === key) {
exists = true;
return false;
}
});
return exists;
}
/**
Checks if symbol is a parameter.
@param symbol the symbol
@return true, if symbol is a parameter
*/
function isParameterSymbol(symbol: string): boolean {
if (isEmptyKey(symbol)) {
return false;
}
symbol = symbol.trim();
return symbol === parameter_key_symbol;
}
/**
* Checks if the given key is empty
*
* @param key the key
* @return true, if the key is empty
*/
function isEmptyKey(key: string): boolean {
if (key === undefined || key == null || key === '') {
return true;
}
const regex = new RegExp(non_breaking_space, 'g');
key = key.replace(regex, '');
key = key.replace(/ +|\r\n|\n|\r/g, '');
return key.length === 0;
}
/**
Checks if the module is parameterized.
@param symbol the module's symbol
@param container the module's container
@return true, if the module is parameterized
*/
function moduleIsParameterized(symbol: string, container: string): boolean {
if (isEmptyKey(symbol) || isEmptyKey(container)) {
return false;
}
// Remove new lines
container = container.replace(/\r\n|\n|\r/g, ' ');
// Surround '#(' with space
container = container.replace(/#\(/g, ' #( ');
// Replace multiple white spaces with a single whitespace
container = container.replace(/ +/g, ' ');
const keys = container.split(' ');
if (keys.length < 3) {
return false;
}
if (keys[0] === 'module' && keys[1] === symbol && keys[2] === '#(') {
return true;
}
return false;
}
/**
* Module instantiator class which queries a given module, fetches the relative container, and parses an instance.
*/
export class SystemVerilogModuleInstantiator {
/**
Uses the given symbol to query the module's definition,
and then return the module's instance.
@param query the module's name
@return the module's instance.
*/
public auto_instantiate(query: string): Thenable<string> {
return new Promise((resolve, reject) =>
// return this.workspaceSymbolProvider.provideWorkspaceSymbols(query, undefined, true)
commands
.executeCommand('vscode.executeWorkspaceSymbolProvider', query, undefined, true)
.then((symbols: SystemVerilogSymbol[]) => {
for (let i = 0; i < symbols.length; i++) {
const s = symbols[i];
if (s.kind === getSymbolKind('module')) {
return s;
}
}
reject(new Error(`${query} module was not found in the workspace.`));
})
.then((s) => {
workspace.openTextDocument(s.location.uri).then((doc) => {
const container = doc.getText(s.location.range);
if (isEmptyKey(container)) {
reject(new Error(`${query}'s definition is undefined in the workspace.`));
}
let instance;
try {
instance = formatInstance(query, container);
} catch (error) {
console.log(error); // eslint-disable-line no-console
reject(new Error(`An error occurred when formatting the instance for ${query}: ${error}`));
}
if (instance === undefined) {
reject(new Error(`An error occurred when formatting the instance for ${query}.`));
}
resolve(instance);
});
})
);
}
/**
Gets module name from the user, and looks up in the workspaceSymbolProvider for a match.
Looks up the module's definition, and parses it to build the module's instance.
@return the module's instance, assigns the default parameter values.
*/
public instantiateModule() {
const options: InputBoxOptions = {
prompt: 'Enter the module name to instantiate',
placeHolder: 'Enter the module name to instantiate'
};
// request the module's name from the user
window.showInputBox(options).then((value) => {
if (!value) {
return;
}
// current editor
const editor = window.activeTextEditor;
// check if there is no selection
if (editor.selection.isEmpty) {
if (editor) {
this.auto_instantiate(value).then(
(v) => {
editor.edit((editBuilder) => {
editBuilder.replace(editor.selection, v);
});
},
(e) => {
window.showErrorMessage(e);
}
);
}
}
});
}
}
/**
Uses the given symbol, and given container to format the module's instance.
@param symbol string the module's name
@container the module's container
@return the module's instance.
@throws Array Out of Bounds error with incorrect syntax
*/
export function formatInstance(symbol: string, container: string): string {
if (isEmptyKey(symbol) || isEmptyKey(container)) {
return undefined;
}
const original_container = container;
container = cleanUpContainer(container);
const isParameterized = moduleIsParameterized(symbol, original_container);
const maxLength = findMaxLength(container, isParameterized);
container = parseContainer(symbol, container, isParameterized, maxLength);
return container;
}
/**
* Cleans up the container from extra characters, and surround delimiters with white space.
*
* @param container the module's container
* @return cleaned up container.
*/
function cleanUpContainer(container: string): string {
if (isEmptyKey(container)) {
return undefined;
}
// Replace white space with non-breaking white space
container = container.replace(/ /g, ` ${non_breaking_space} `);
// Surround ',' '=' '(' ')' '//' '/*' with whitespace
container = container.replace(/,/g, ' , ');
container = container.replace(/=/g, ' = ');
container = container.replace(/\(/g, ' ( ');
container = container.replace(/\)/g, ' ) ');
container = container.replace(/\/\//g, ' // ');
container = container.replace(/\/\*/g, ' /* ');
// Surround key symbols with space
let regex;
ports_key_symbols.forEach((key) => {
regex = new RegExp(key, 'g');
container = container.replace(regex, ` ${key} `);
});
regex = new RegExp(parameter_key_symbol, 'g');
container = container.replace(regex, ` ${parameter_key_symbol} `);
// Replace multiple white spaces with a single whitespace
container = container.replace(/ +/g, ' ');
container = container.trim();
return container;
}
/**
* Get the maximum length of the ports and parameters in the module container.
*
* @param container the module's container
* @param moduleIsParameterized whether the module has parameters or not
* @return the maximum length
*/
function findMaxLength(container: string, moduleIsParameterized: boolean): number {
if (isEmptyKey(container)) {
return undefined;
}
const keys = container.split(' ');
const output = [];
let maxLength = 0;
let lastPort;
let lastParameter;
let passedEqualSign = false;
let state = processingState.INITIAL;
for (let i = 0; i < keys.length; i++) {
if (keys[i] === undefined) {
continue; // eslint-disable-line no-continue
}
// Single comment
if (keys[i] === '//') {
i = getSingleComment(keys, output, i);
}
// Block comment
else if (keys[i] === '/*') {
i = getBlockComment(keys, output, i);
} else if (state === processingState.INITIAL) {
if (keys[i] === '(') {
if (moduleIsParameterized) {
state = processingState.PARAMETERS;
} else {
state = processingState.PORTS;
}
}
} else if (state === processingState.PARAMETERS) {
if (keys[i] === ')') {
state = processingState.PORTS;
} else if (keys[i] === ',' && lastParameter) {
maxLength = Math.max(lastParameter.length, maxLength);
lastParameter = undefined;
passedEqualSign = false;
} else if (keys[i] === '=') {
passedEqualSign = true;
} else if (!isParameterSymbol(keys[i]) && !isEmptyKey(keys[i])) {
if (!passedEqualSign) {
lastParameter = keys[i].trim();
}
}
} else if (state === processingState.PORTS) {
if (lastParameter) {
maxLength = Math.max(lastParameter.length, maxLength);
lastParameter = undefined;
}
if (keys[i] === ')') {
state = processingState.COMPLETE;
} else if (keys[i] === ',' && lastPort) {
maxLength = Math.max(lastPort.length, maxLength);
lastPort = undefined;
} else if (!isPortSymbol(keys[i]) && !isEmptyKey(keys[i])) {
lastPort = keys[i].trim();
}
}
// Last item
if (i >= keys.length - 1) {
if (state === processingState.PARAMETERS && lastParameter) {
maxLength = Math.max(lastParameter.length, maxLength);
} else if (state === processingState.PORTS && lastPort) {
maxLength = Math.max(lastPort.length, maxLength);
}
}
if (state === processingState.COMPLETE) {
if (lastPort) {
maxLength = Math.max(lastPort.length, maxLength);
}
break;
}
}
return maxLength;
}
/**
* Parse the container, and create the module's instance.
*
* @param symbol the module's symbol
* @param container the module's container
* @param moduleIsParameterized whether the module has parameters or not
* @param maxLength the maximum length of ports/parameters
* @return the module's instance
*/
function parseContainer(symbol: string, container: string, moduleIsParameterized: boolean, maxLength: number): string {
if (isEmptyKey(symbol) || isEmptyKey(container)) {
return undefined;
}
if (maxLength < 0) {
return undefined;
}
const output = [];
const keys = container.split(' ');
let lastPort;
let lastParameter;
let lastParameterDefault;
let passedEqualSign = false;
let state = processingState.INITIAL;
for (let i = 0; i < keys.length; i++) {
if (keys[i] === undefined) {
continue; // eslint-disable-line no-continue
}
// Single comment
if (keys[i] === '//') {
i = getSingleComment(keys, output, i);
}
// Block comment
else if (keys[i] === '/*') {
i = getBlockComment(keys, output, i);
} else if (state === processingState.INITIAL) {
if (keys[i] === '(') {
if (moduleIsParameterized) {
state = processingState.PARAMETERS;
} else {
state = processingState.PORTS;
}
}
} else if (state === processingState.PARAMETERS) {
if (keys[i] === ')') {
state = processingState.PORTS;
} else if (keys[i] === ',' && lastParameter) {
// Set with default value if it exists
if (passedEqualSign) {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameterDefault})`);
passedEqualSign = false;
} else {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameter})`);
}
output.push(',\n');
lastParameter = undefined;
} else if (keys[i] === '=') {
passedEqualSign = true;
} else if (!isParameterSymbol(keys[i]) && !isEmptyKey(keys[i])) {
if (passedEqualSign) {
lastParameterDefault = keys[i].trim();
} else {
lastParameter = keys[i].trim();
}
}
} else if (state === processingState.PORTS) {
if (lastParameter) {
// Set with default value if it exists
if (passedEqualSign) {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameterDefault})\n`);
passedEqualSign = false;
} else {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameter})\n`);
}
output.push(`) u_${symbol} (\n`);
lastParameter = undefined;
}
if (keys[i] === ')') {
state = processingState.COMPLETE;
} else if (keys[i] === ',' && lastPort) {
output.push(
`${padding}.${lastPort}${' '.repeat(maxLength - lastPort.length)}${' '.repeat(4)}(${lastPort})`
);
output.push(',\n');
lastPort = undefined;
} else if (!isPortSymbol(keys[i]) && !isEmptyKey(keys[i])) {
lastPort = keys[i].trim();
}
}
// Last item
if (i >= keys.length - 1) {
if (state === processingState.PARAMETERS && lastParameter) {
// Set with default value if it exists
if (passedEqualSign) {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameterDefault})\n`);
passedEqualSign = false;
} else {
output.push(
`${padding}.${lastParameter}${' '.repeat(maxLength - lastParameter.length)}${' '.repeat(4)}(`
);
output.push(`${lastParameter})\n`);
}
} else if (state === processingState.PORTS && lastPort) {
output.push(
`${padding}.${lastPort}${' '.repeat(maxLength - lastPort.length)}${' '.repeat(4)}(${lastPort})`
);
output.push('\n');
}
}
if (state === processingState.COMPLETE) {
if (lastPort) {
output.push(
`${padding}.${lastPort}${' '.repeat(maxLength - lastPort.length)}${' '.repeat(4)}(${lastPort})`
);
output.push('\n');
}
break;
}
}
const instance = [];
if (moduleIsParameterized) {
instance.push(`${symbol} #(\n`);
instance.push(`${output.join('')});`);
} else {
instance.push(`${symbol} u_${symbol}`);
instance.push(` (\n${output.join('')});`);
}
return instance.join('');
}
/**
* Parses a single comment from the container starting from a given index in keys.
*
* @param keys the container's keys.
* @param output the array to add the single comment to
* @param i the start index
* @return the index where the single comment ends
*/
function getSingleComment(keys: string[], output: string[], i: number): number {
if (!keys || !output) {
return undefined;
}
if (i < 0 || i > keys.length) {
return undefined;
}
const regex = new RegExp(non_breaking_space, 'g');
output.push(padding + keys[i].replace(regex, ' '));
if (!keys[i].includes('\n') && !keys[i].includes('\r')) {
i += 1;
while (i < keys.length && !keys[i].includes('\n') && !keys[i].includes('\r')) {
output.push(keys[i].replace(regex, ' '));
i += 1;
}
if (i < keys.length) {
output.push(keys[i].replace(regex, ' '));
} else {
output.push('\n');
}
}
return i;
}
/**
* Parses a block comment from the container starting from a given index in keys.
*
* @param keys the container's keys.
* @param output the array to add the block comment to
* @param i the start index
* @return the index where the block comment ends
*/
function getBlockComment(keys: string[], output: string[], i: number): number {
if (!keys || !output) {
return undefined;
}
if (i < 0 || i > keys.length) {
return undefined;
}
const regex = new RegExp(non_breaking_space, 'g');
output.push(padding + keys[i].replace(regex, ' '));
i += 1;
while (i < keys.length && !keys[i].trim().includes('*/')) {
// If there is an upcoming new line of comments, add padding
if (/\r|\n/.exec(keys[i])) {
output.push(keys[i].replace(regex, ' '));
i += 1;
if (i < keys.length) {
output.push(keys[i].replace(regex, ' '));
}
} else {
output.push(keys[i].replace(regex, ' '));
}
i += 1;
}
if (i < keys.length) {
output.push(keys[i].replace(regex, ' '));
}
return i;
} | the_stack |
import { Buffer } from "buffer";
import { Runtime, Collab } from "../core/";
import {
ArrayMessage,
CollabIDMessage,
DefaultSerializerMessage,
IDefaultSerializerMessage,
IOptionalSerializerMessage,
ObjectMessage,
OptionalSerializerMessage,
PairSerializerMessage,
} from "../../generated/proto_compiled";
import { Optional } from "./optional";
import { CollabID } from "./collab_id";
/**
* A serializer for values of type `T` (e.g., elements
* in Collabs collections), so that they can
* be sent to other replicas in Collabs operations.
*
* [[DefaultSerializer.getInstance]]`(runtime)` should suffice for most uses.
*/
export interface Serializer<T> {
serialize(value: T): Uint8Array;
deserialize(message: Uint8Array): T;
}
// In this file, we generally cache instances in case each
// element of a collection constructs a derived serializer
// from a fixed given one.
/**
* Default serializer.
*
* Supported types:
* - Primitive types (string, number, boolean, undefined, null)
* - [[CollabID]]s
* - Arrays and plain (non-class) objects, serialized recursively.
*
* All other types cause an error during [[serialize]].
*/
export class DefaultSerializer<T> implements Serializer<T> {
private constructor() {
// Constructor is just here to mark it as private.
}
// Only weak in keys, since we expect a Runtime's DefaultSerializer
// to exist for as long as the Runtime.
private static instance = new DefaultSerializer();
static getInstance<T>(): DefaultSerializer<T> {
return <DefaultSerializer<T>>this.instance;
}
serialize(value: T): Uint8Array {
let message: IDefaultSerializerMessage;
switch (typeof value) {
case "string":
message = { stringValue: value };
break;
case "number":
if (Number.isSafeInteger(value)) {
message = { intValue: value };
} else {
message = { doubleValue: value };
}
break;
case "boolean":
message = { booleanValue: value };
break;
case "undefined":
message = { undefinedValue: true };
break;
case "object":
if (value === null) {
message = { nullValue: true };
} else if (value instanceof CollabID) {
message = {
collabIDValue: CollabIDMessage.create({
pathToBase: value.namePath(),
}),
};
} else if (value instanceof Uint8Array) {
message = {
bytesValue: value,
};
} else if (Array.isArray(value)) {
// Technically types are bad for recursive
// call to this.serialize, but it's okay because
// we ignore our generic type.
message = {
arrayValue: ArrayMessage.create({
elements: value.map((element) => this.serialize(element)),
}),
};
} else {
const constructor = (<object>(<unknown>value)).constructor;
if (constructor === Object) {
// Technically types are bad for recursive
// call to this.serialize, but it's okay because
// we ignore our generic type.
const properties: { [key: string]: Uint8Array } = {};
for (const [key, property] of Object.entries(value)) {
properties[key] = this.serialize(property);
}
message = {
objectValue: ObjectMessage.create({
properties,
}),
};
} else if (value instanceof Collab) {
throw new Error(
"Collab serialization is not supported; serialize a CollabID instead"
);
} else {
throw new Error(
`Unsupported class type for DefaultSerializer: ${constructor.name}; you must use a custom serializer or a plain (non-class) Object`
);
}
}
break;
default:
throw new Error(
`Unsupported type for DefaultSerializer: ${typeof value}; you must use a custom Serializer`
);
}
return DefaultSerializerMessage.encode(message).finish();
}
deserialize(message: Uint8Array): T {
const decoded = DefaultSerializerMessage.decode(message);
let ans: unknown;
switch (decoded.value) {
case "stringValue":
ans = decoded.stringValue;
break;
case "intValue":
ans = int64AsNumber(decoded.intValue);
break;
case "doubleValue":
ans = decoded.doubleValue;
break;
case "booleanValue":
ans = decoded.booleanValue;
break;
case "undefinedValue":
ans = undefined;
break;
case "nullValue":
ans = null;
break;
case "collabIDValue":
ans = new CollabID(decoded.collabIDValue!.pathToBase!);
break;
case "arrayValue":
ans = decoded.arrayValue!.elements!.map((serialized) =>
this.deserialize(serialized)
);
break;
case "objectValue":
ans = {};
for (const [key, serialized] of Object.entries(
decoded.objectValue!.properties!
)) {
(<Record<string, unknown>>ans)[key] = this.deserialize(serialized);
}
break;
case "bytesValue":
ans = decoded.bytesValue;
break;
default:
throw new Error(`Bad message format: decoded.value=${decoded.value}`);
}
// No way of checking if it's really type T.
return ans as T;
}
}
export class TextSerializer implements Serializer<string> {
private constructor() {
// Use TextSerializer.instance instead.
}
serialize(value: string): Uint8Array {
return new Uint8Array(Buffer.from(value, "utf-8"));
}
deserialize(message: Uint8Array): string {
return Buffer.from(message).toString("utf-8");
}
static readonly instance = new TextSerializer();
}
/**
* Only works on char arrays (each element must be a
* single-character string).
*/
export class TextArraySerializer implements Serializer<string[]> {
private constructor() {
// Use TextArraySerializer.instance instead.
}
serialize(value: string[]): Uint8Array {
return new Uint8Array(Buffer.from(value.join(""), "utf-8"));
}
deserialize(message: Uint8Array): string[] {
return [...Buffer.from(message).toString("utf-8")];
}
static readonly instance = new TextArraySerializer();
}
/**
* Serializes [T] using a serializer for T. This is slightly more efficient
* than the default serializer, and also works with arbitrary T.
*/
export class SingletonSerializer<T> implements Serializer<[T]> {
private constructor(private readonly valueSerializer: Serializer<T>) {}
serialize(value: [T]): Uint8Array {
return this.valueSerializer.serialize(value[0]);
}
deserialize(message: Uint8Array): [T] {
return [this.valueSerializer.deserialize(message)];
}
// Weak in both keys and values.
private static cache = new WeakMap<
Serializer<unknown>,
WeakRef<SingletonSerializer<unknown>>
>();
static getInstance<T>(
valueSerializer: Serializer<T>
): SingletonSerializer<T> {
const existingWeak = SingletonSerializer.cache.get(valueSerializer);
if (existingWeak !== undefined) {
const existing = existingWeak.deref();
if (existing !== undefined) return <SingletonSerializer<T>>existing;
}
const ret = new SingletonSerializer(valueSerializer);
SingletonSerializer.cache.set(valueSerializer, new WeakRef(ret));
return ret;
}
}
/**
* Serializes strings that are outputs of
* [[bytesAsString]], using [[stringAsBytes]].
*
* This is more efficient than using a literal string
* encoding, since we know the strings have a restricted
* form.
*/
export class StringAsArraySerializer implements Serializer<string> {
private constructor() {
// Use StringAsArraySerializer.instance instead.
}
serialize(value: string): Uint8Array {
return stringAsBytes(value);
}
deserialize(message: Uint8Array): string {
return bytesAsString(message);
}
static readonly instance = new StringAsArraySerializer();
}
// OPT: cache instances?
export class PairSerializer<T, U> implements Serializer<[T, U]> {
constructor(
private readonly oneSerializer: Serializer<T>,
private readonly twoSerializer: Serializer<U>
) {}
serialize(value: [T, U]): Uint8Array {
const message = PairSerializerMessage.create({
one: this.oneSerializer.serialize(value[0]),
two: this.twoSerializer.serialize(value[1]),
});
return PairSerializerMessage.encode(message).finish();
}
deserialize(message: Uint8Array): [T, U] {
const decoded = PairSerializerMessage.decode(message);
return [
this.oneSerializer.deserialize(decoded.one),
this.twoSerializer.deserialize(decoded.two),
];
}
}
// OPT: cache instances?
/**
* Serializes [[CollabID]]s using their [[Collab]]'s name path with
* respect to a specified
* base [[Collab]] or [[Runtime]].
*
* The base must be an ancestor of all serialized `CollabID`s' `Collab`s.
*
* This is more efficient (in terms of serialized size)
* than using DefaultSerializer
* when base is not the [[Runtime]]. It is better
* the closer the serialized values are to base within
* the Collab hierarchy, and best when base is their parent.
*/
export class CollabIDSerializer<C extends Collab>
implements Serializer<CollabID<C>>
{
constructor(private readonly base?: Collab) {}
serialize(value: CollabID<C>): Uint8Array {
// OPT: interface with CollabID to cache this.base's namePath.length,
// instead of recalculating its whole namePath each time?
// Although then we lose the ability to check ancestry.
const message = CollabIDMessage.create({
pathToBase: value.namePath(this.base),
});
return CollabIDMessage.encode(message).finish();
}
deserialize(message: Uint8Array): CollabID<C> {
const decoded = CollabIDMessage.decode(message);
return new CollabID(decoded.pathToBase, this.base);
}
}
export class OptionalSerializer<T> implements Serializer<Optional<T>> {
private constructor(private readonly valueSerializer: Serializer<T>) {}
serialize(value: Optional<T>): Uint8Array {
const imessage: IOptionalSerializerMessage = {};
if (value.isPresent) {
imessage.valueIfPresent = this.valueSerializer.serialize(value.get());
}
const message = OptionalSerializerMessage.create(imessage);
return OptionalSerializerMessage.encode(message).finish();
}
deserialize(message: Uint8Array): Optional<T> {
const decoded = OptionalSerializerMessage.decode(message);
if (Object.hasOwnProperty.call(decoded, "valueIfPresent")) {
return Optional.of(
this.valueSerializer.deserialize(decoded.valueIfPresent)
);
} else return Optional.empty();
}
// Weak in both keys and values.
private static cache = new WeakMap<
Serializer<unknown>,
WeakRef<OptionalSerializer<unknown>>
>();
static getInstance<T>(valueSerializer: Serializer<T>): OptionalSerializer<T> {
const existingWeak = OptionalSerializer.cache.get(valueSerializer);
if (existingWeak !== undefined) {
const existing = existingWeak.deref();
if (existing !== undefined) return <OptionalSerializer<T>>existing;
}
const ret = new OptionalSerializer(valueSerializer);
OptionalSerializer.cache.set(valueSerializer, new WeakRef(ret));
return ret;
}
}
const ENCODING = "base64" as const;
export function bytesAsString(array: Uint8Array) {
return Buffer.from(array).toString(ENCODING);
}
export function stringAsBytes(str: string) {
return new Uint8Array(Buffer.from(str, ENCODING));
}
/**
* Compares two Uint8Array's for equality.
*/
export function byteArrayEquals(one: Uint8Array, two: Uint8Array): boolean {
if (one.length !== two.length) return false;
// OPT: convert to a Uint32Array
// and do 4-byte comparisons at a time?
for (let i = 0; i < one.length; i++) {
if (one[i] !== two[i]) return false;
}
return true;
}
/**
* Apply this function to protobuf.js uint64 and sint64 output values
* to convert them to the nearest JS number (double).
* For safe integers, this is exact.
*
* In theory you can "request" protobuf.js to not use
* Longs by not depending on the Long library, but that is
* flaky because a dependency might import it.
*/
export function int64AsNumber(num: number | Long): number {
if (typeof num === "number") return num;
else return num.toNumber();
} | the_stack |
import { print, TypeMessage } from '../../../adapters/messages/console-log';
import * as BpmnModdle from "bpmn-moddle";
import * as fs from "fs";
import * as path from "path";
import * as ejs from "ejs";
import BigNumber from "bignumber.js";
import {
SubProcessInfo,
IFlowInfo,
ElementIFlow,
IDataInfo,
ParamInfo,
EdgeScript,
} from "../../utils/structs/parsing-info";
const bpmn2solIDataEJS = fs.readFileSync(
path.join(__dirname, "./../../../../templates-ejs/interpretation-engine") +
"/bpmn2solIData.ejs",
"utf-8"
);
const factory2solEJS = fs.readFileSync(
path.join(__dirname, "./../../../../templates-ejs/interpretation-engine") +
"/factory2Solidity.ejs",
"utf-8"
);
let bpmn2solIDataTemplate = ejs.compile(bpmn2solIDataEJS);
let factory2solTemplate = ejs.compile(factory2solEJS);
let loadBPMN = async (bpmnDoc) => {
const { rootElement: definitions } = await moddle.fromXML(bpmnDoc);
return definitions;
};
let moddle = new BpmnModdle();
let parseBpmn = async (bpmnDoc) => {
return new Promise((resolve, reject) => {
try {
let definitions = loadBPMN(bpmnDoc);
resolve(definitions);
} catch (err) {
print("Invalid Process Model in the Input", TypeMessage.error);
reject(err);
}
});
};
export let parseBpmnModel = (bpmnModel: string) => {
return new Promise<SubProcessInfo>((resolve, reject) => {
parseBpmn(bpmnModel).then((definitions: any) => {
if (!definitions.diagrams || definitions.diagrams.length == 0) {
reject("ERROR: No diagram found in BPMN file");
}
try {
let proc = definitions.rootElements[0];
let processInfo: SubProcessInfo = buildProcessTree(proc, 1, false);
resolve(processInfo);
} catch (error) {
reject(error)
}
});
});
};
let buildProcessTree = (
proc: any,
instCount: number,
eventSubProc: boolean
) => {
let processNode: SubProcessInfo = new SubProcessInfo(instCount);
processNode.procName = getNodeName(proc);
processNode.procBpmnId = proc.id;
let iFlow: IFlowInfo = new IFlowInfo();
let iData: IDataInfo = new IDataInfo();
let arcCount = 1;
let elemCount = 1;
let preCMap: Map<number, Array<number>> = new Map();
let postCMap: Map<number, Array<number>> = new Map();
let nextMap: Map<number, Array<number>> = new Map();
let prevMap: Map<number, Array<number>> = new Map();
let typeInfoMap: Map<number, Array<number>> = new Map();
let isEvtGateway: Array<boolean> = new Array();
let eNames: Map<number, string> = new Map();
let isExternal: Array<boolean> = new Array();
// Numbering the elements/arcs in the current Sub-process
proc.flowElements.forEach((element) => {
switch (element.$type) {
case "bpmn:SequenceFlow": {
iFlow.edgeIndexMap.set(element.id, arcCount++);
break;
}
default: {
if (
element.$type === "bpmn:UserTask" ||
element.$type === "bpmn:ReceiveTask" ||
element.$type === "bpmn:ServiceTask"
)
isExternal[elemCount] = true;
iFlow.nodeIndexMap.set(element.id, elemCount);
eNames.set(elemCount, getNodeName(element));
preCMap.set(elemCount, new Array());
postCMap.set(elemCount, new Array());
nextMap.set(elemCount, new Array());
prevMap.set(elemCount++, new Array());
break;
}
}
});
if (proc.documentation) updateGlobalFields(proc.documentation[0].text, iData);
proc.flowElements.forEach((element) => {
let eInd: number = iFlow.nodeIndexMap.get(element.id);
let typeInfo: Array<number> = [];
let cardinality: number = 1;
if (is(element.$type, "task")) {
typeInfo[0] = 1; // Activity
typeInfo[3] = 1; // Task
} else if (is(element.$type, "gateway")) {
typeInfo[1] = 1;
} else if (is(element.$type, "event")) {
typeInfo[2] = 1;
iFlow.eventCodeMap.set(eInd, getNodeName(element));
setEventType(typeInfo, element);
}
// Multi-Instances
if (element.loopCharacteristics) {
if (element.loopCharacteristics.isSequential) typeInfo[7] = 1;
// Sequential
else typeInfo[6] = 1; // Parallel
if (element.loopCharacteristics.loopCardinality)
cardinality = parseInt(
element.loopCharacteristics.loopCardinality.body
);
}
switch (element.$type) {
case "bpmn:SequenceFlow": {
let prevInd: number = iFlow.nodeIndexMap.get(element.sourceRef.id);
let nextInd: number = iFlow.nodeIndexMap.get(element.targetRef.id);
let arcInd: number = iFlow.edgeIndexMap.get(element.id);
postCMap.get(prevInd)[arcInd] = 1;
if (!(isExternal[nextInd] === true)) nextMap.get(prevInd).push(nextInd);
preCMap.get(nextInd)[arcInd] = 1;
prevMap.get(nextInd).push(prevInd);
if (element.conditionExpression) {
if (!iData.gatewayScripts.has(prevInd))
iData.gatewayScripts.set(prevInd, new Array());
iData.gatewayScripts
.get(prevInd)
.push(
new EdgeScript(
iFlow.edgeIndexMap.get(element.id),
element.conditionExpression.body
)
);
}
break;
}
case "bpmn:UserTask": {
typeInfo[11] = 1;
if (element.documentation)
updateParameters(element.documentation[0].text, eInd, iData);
checkEmptyParameters(eInd, iData);
break;
}
case "bpmn:ScriptTask": {
typeInfo[12] = 1;
if (element.script) iData.scripts.set(eInd, element.script);
break;
}
case "bpmn:ServiceTask": {
typeInfo[13] = 1;
if (element.documentation)
updateParameters(element.documentation[0].text, eInd, iData);
checkEmptyParameters(eInd, iData);
break;
}
case "bpmn:ReceiveTask": {
typeInfo[14] = 1;
checkEmptyParameters(eInd, iData);
break;
}
case "bpmn:Task": {
typeInfo[10] = 1;
break;
}
case "bpmn:ExclusiveGateway": {
typeInfo[4] = 1;
break;
}
case "bpmn:ParallelGateway": {
typeInfo[5] = 1;
break;
}
case "bpmn:EventBasedGateway": {
typeInfo[7] = 1;
isEvtGateway[eInd] = true;
break;
}
case "bpmn:InclusiveGateway": {
typeInfo[6] = 1;
break;
}
case "bpmn:CallActivity": {
typeInfo[0] = 1;
typeInfo[4] = 1;
break;
}
case "bpmn:SubProcess": {
typeInfo[0] = 1;
typeInfo[5] = 1;
let evtSubP: boolean = false;
if (element.triggeredByEvent) {
// Event- SubProcess
typeInfo[12] = 1;
evtSubP = true;
} else {
// Expanded SubProcess
typeInfo[10] = 1;
}
let childProc: SubProcessInfo = buildProcessTree(
element,
cardinality,
evtSubP
);
childProc.parent = processNode;
processNode.children.push(childProc);
break;
}
case "bpmn:StartEvent": {
if (eventSubProc) {
typeInfo[6] = 1;
if (!element.isInterrupting === false) typeInfo[4] = 1; // Interrupting Event
} else typeInfo[5] = 1;
setEventType(typeInfo, element);
break;
}
case "bpmn:EndEvent": {
typeInfo[3] = 1; // Always Throw
typeInfo[9] = 1;
break;
}
case "bpmn:IntermediateThrowEvent": {
typeInfo[3] = 1;
typeInfo[7] = 1;
break;
}
case "bpmn:IntermediateCatchEvent": {
typeInfo[7] = 1;
break;
}
case "bpmn:BoundaryEvent": {
typeInfo[8] = 1;
let subPInd: number = iFlow.nodeIndexMap.get(element.attachedToRef.id);
if (!iFlow.attachedEvents.has(subPInd))
iFlow.attachedEvents.set(subPInd, new Array());
iFlow.attachedEvents.get(subPInd).push(eInd);
if (!(element.cancelActivity === false)) {
typeInfo[4] = 1;
}
break;
}
default: {
break;
}
}
typeInfoMap.set(eInd, typeInfo);
});
proc.flowElements.forEach((element) => {
if (is(element.$type, "gateway")) {
let eInd: number = iFlow.nodeIndexMap.get(element.id);
if (prevMap.get(eInd).length > 1) typeInfoMap.get(eInd)[3] = 1;
}
});
iFlow.nodeIndexMap.forEach((eInd, eId) => {
let elementInfo: ElementIFlow = new ElementIFlow(eInd, eNames.get(eInd));
elementInfo.typeInfo = toStrDecimal(typeInfoMap.get(eInd));
elementInfo.postC = toStrDecimal(postCMap.get(eInd));
elementInfo.next = nextMap.get(eInd);
if (prevMap.get(eInd).length > 0 && isEvtGateway[prevMap.get(eInd)[0]])
elementInfo.preC = toStrDecimal(postCMap.get(prevMap.get(eInd)[0]));
else elementInfo.preC = toStrDecimal(preCMap.get(eInd));
iFlow.elementInfo.set(eInd, elementInfo);
});
let codeGenerationInfo = {
contractName: getNodeName(proc),
globalFields: iData.globalFields,
elementBitMask: (eInd) => {
let bitarray = [];
bitarray[eInd] = 1;
let result = "0b";
for (let i = bitarray.length - 1; i >= 0; i--)
result += bitarray[i] ? "1" : "0";
return new BigNumber(result).toFixed();
},
indexArrayToBitSet: (indexArray: Array<number>) => {
return arrToStrDecimal(indexArray);
},
gatewayScript: iData.gatewayScripts,
taskScripts: iData.scripts,
postC: (eInd: number) => {
return iFlow.elementInfo.get(eInd).postC;
},
checkOutList: groupOutParam(iData.outParams),
checkOutReturn: (params: Array<string>, returnType: string) => {
let res = "";
for (let i = 0; i < params.length - 1; i++) res += " " + params[i] + ",";
if (params.length > 0)
res = returnType + "(" + res + params[params.length - 1] + ")";
return res;
},
checkInList: groupInParam(iData.inParams, iData.userScripts),
checkInParams: (params: Array<ParamInfo>, renamedParams: Array<string>) => {
let res = "";
for (let i = 0; i < params.length; i++)
res += ", " + params[i].type + " " + renamedParams[i];
return res;
},
};
iData.iDataSolidity = bpmn2solIDataTemplate(codeGenerationInfo);
iData.factorySolidity = factory2solTemplate(codeGenerationInfo);
processNode.iData = iData;
processNode.iflow = iFlow;
return processNode;
};
let groupOutParam = (candidates: Map<number, Array<ParamInfo>>) => {
let resMap: Map<string, number> = new Map();
let resArray: Array<any> = new Array();
candidates.forEach((params: Array<ParamInfo>, eInd: number) => {
let joinKey: string = "e";
let types: Array<String> = new Array();
let names: Array<String> = new Array();
let funcName: string = "checkOut";
params.forEach((param) => {
funcName +=
param.type.charAt(0).toLocaleUpperCase() + param.type.charAt(1);
joinKey += param.type;
types.push(param.type);
names.push(param.name);
});
if (!resMap.has(joinKey)) {
resMap.set(joinKey, resArray.length);
resArray.push({
funcName: funcName,
types: types,
eIndexes: new Array(),
paramNames: new Array(),
});
}
let arrInd: number = resMap.get(joinKey);
resArray[arrInd].eIndexes.push(eInd);
resArray[arrInd].paramNames.push(names);
});
return resArray;
};
let groupInParam = (
candidates: Map<number, Array<ParamInfo>>,
scripts: Map<number, string>
) => {
let resMap: Map<string, number> = new Map();
let resArray: Array<any> = new Array();
candidates.forEach((params: Array<ParamInfo>, eInd: number) => {
let joinKey: string = "e";
let renamedParams: Array<string> = new Array();
let renamedScript: string = scripts.get(eInd);
let i: number = 1;
params.forEach((param) => {
joinKey += param.type;
renamedParams.push("i" + i);
if (renamedScript)
renamedScript = renamedScript.replace(param.name, "i" + i++);
});
if (!resMap.has(joinKey)) {
resMap.set(joinKey, resArray.length);
resArray.push({
params: params,
renamedParams: renamedParams,
eIndexes: new Array(),
scripts: new Array(),
});
}
let arrInd: number = resMap.get(joinKey);
resArray[arrInd].eIndexes.push(eInd);
resArray[arrInd].scripts.push(renamedScript);
});
return resArray;
};
let sortParameters = (params: Array<ParamInfo>) => {
params.sort(compareTo);
};
let compareTo = (a: ParamInfo, b: ParamInfo) => {
if (a.type < b.type) return -1;
if (a.type > b.type) return 1;
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
};
let toStrDecimal = (bitArray) => {
let result = "0b";
for (let i = bitArray.length - 1; i >= 0; i--)
result += bitArray[i] ? "1" : "0";
return result === "0b" ? "0" : new BigNumber(result).toFixed();
};
let arrToStrDecimal = (indexArray: Array<number>) => {
let bitarray: Array<number> = new Array();
for (let i = 0; i < indexArray.length; i++) bitarray[indexArray[i]] = 1;
return toStrDecimal(bitarray);
};
let is = (element: string, type: string) => {
return element.toLocaleLowerCase().includes(type.toLocaleLowerCase());
};
let setEventType = (typeInfo: Array<Number>, element: any) => {
if (element.eventDefinitions) {
switch (element.eventDefinitions[0].$type) {
case "bpmn:ErrorEventDefinition": {
typeInfo[13] = 1;
break;
}
case "bpmn:EscalationEventDefinition": {
typeInfo[14] = 1;
break;
}
case "bpmn:MessageEventDefinition": {
typeInfo[12] = 1;
break;
}
case "bpmn:SignalEventDefinition": {
typeInfo[15] = 1;
break;
}
case "bpmn:TerminateEventDefinition": {
typeInfo[11] = 1;
break;
}
}
} else {
// Default (None) event
typeInfo[10] = 1;
}
};
let getNodeName = (node: any) =>
node.name ? node.name.replace(/\s+/g, "_") : node.id;
let updateGlobalFields = (cad: string, iData: IDataInfo) => {
if (!cad) return;
let arr = cad.split(";");
arr.forEach((gField) => {
if (gField.trim().length > 0) {
let arr1 = gField.trim().split(" ");
iData.globalFields.push(new ParamInfo(arr1[0], arr1[arr1.length - 1]));
}
});
};
let checkEmptyParameters = (eInd: number, iData: IDataInfo) => {
if (!iData.inParams.has(eInd)) iData.inParams.set(eInd, new Array());
if (!iData.outParams.has(eInd)) iData.outParams.set(eInd, new Array());
};
let updateParameters = (cad: string, eInd: number, iData: IDataInfo) => {
let arr = cad.split("@");
if (arr.length >= 3) {
// if(controlFlowInfo != null)
// controlFlowInfo.taskRoleMap.set(nodeId, arr[1].trim());
if (arr[2].length > 1) cad = arr[2];
else return;
// else
// return undefined;
}
// Processing Information of function parameters (both service and user tasks)
cad = cad.replace("(", " ").replace(")", " ").trim();
cad = cad.replace("(", " ").replace(")", " ").trim();
let firstSplit = cad.split(":");
if (firstSplit.length > 2) {
let aux = "";
for (let i = 1; i < firstSplit.length; i++) aux += firstSplit[i];
firstSplit = [firstSplit[0], aux];
}
let secondSplit = firstSplit[firstSplit.length - 1].trim().split("->");
let resMap: Map<string, Array<string>> = new Map();
let inputOutput = [firstSplit[0].trim(), secondSplit[0].trim()];
let parameterType = ["input", "output"];
resMap.set("body", [secondSplit[secondSplit.length - 1].trim()]);
for (let i = 0; i < inputOutput.length; i++) {
let temp = inputOutput[i].split(",");
let res = [];
temp.forEach((subCad) => {
let aux = subCad.trim().split(" ");
if (aux[0].trim().length > 0) {
res.push(aux[0].trim());
res.push(aux[aux.length - 1].trim());
}
});
resMap.set(parameterType[i], res);
}
let inParameters: Array<ParamInfo> = [];
let outParameters: Array<ParamInfo> = [];
let toIterate = resMap.get("output");
for (let i = 0; i < toIterate.length; i += 2)
inParameters.push(new ParamInfo(toIterate[i], toIterate[i + 1]));
sortParameters(inParameters);
iData.inParams.set(eInd, inParameters);
iData.userScripts.set(eInd, resMap.get("body")[0]);
toIterate = resMap.get("input");
for (let i = 0; i < toIterate.length; i += 2)
outParameters.push(new ParamInfo(toIterate[i], toIterate[i + 1]));
sortParameters(outParameters);
iData.outParams.set(eInd, outParameters);
}; | the_stack |
import React, { useState, useEffect } from "react";
import firebase from "firebase"
import "firebase/functions"
import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogContentText from "@material-ui/core/DialogContentText";
import DialogTitle from "@material-ui/core/DialogTitle";
import CircularProgress from "@material-ui/core/CircularProgress";
import DoneIcon from "@material-ui/icons/Done";
import Button from "@material-ui/core/Button";
import { useAuthUser } from "hooks/auth"
import Input, { useInput } from "components/Input"
import Select, { useSelect } from "components/Select"
import Account from "models/account/Account"
import { Create, Individual } from "common/commerce/account"
import Grid from "@material-ui/core/Grid";
import { Box } from "@material-ui/core";
import { SupportedCountries, CountryCode } from "common/Country";
import { nullFilter } from "utils"
import Loading from "components/Loading"
import RegisterableCountries from "config/RegisterableCountries"
const useStyles = makeStyles((theme: Theme) =>
createStyles({
box: {
padding: theme.spacing(2),
backgroundColor: "#fafafa"
},
bottomBox: {
padding: theme.spacing(2),
display: "flex",
justifyContent: "flex-end"
},
input: {
backgroundColor: "#fff"
},
cell: {
borderBottom: "none",
padding: theme.spacing(1),
},
cellStatus: {
borderBottom: "none",
padding: theme.spacing(1),
width: "48px",
},
cellStatusBox: {
display: "flex",
justifyContent: "center",
alignItems: "center"
}
}),
);
export default ({ individual, onCallback }: { individual: Partial<Individual>, onCallback?: (next: boolean) => void }) => {
const classes = useStyles()
const [authUser] = useAuthUser()
const [open, setOpen] = useState(false)
const [error, setError] = useState<string | undefined>()
const first_name = useInput(individual.first_name, { inputProps: { pattern: "[A-Za-z]{1,32}" }, required: true })
const last_name = useInput(individual.last_name, { inputProps: { pattern: "[A-Za-z]{1,32}" }, required: true })
const year = useInput(individual.dob?.year, { inputProps: { pattern: "^[12][0-9]{3}$" }, required: true })
const month = useInput(individual.dob?.month, { inputProps: { pattern: "^(0?[1-9]|1[012])$" }, required: true })
const day = useInput(individual.dob?.day, { inputProps: { pattern: "^(([0]?[1-9])|([1-2][0-9])|(3[01]))$" }, required: true })
const ssn_last_4 = useInput(individual.ssn_last_4, { inputProps: { pattern: "^[0-9]{4}$" }, required: true })
const country = useSelect({
initValue: individual.address?.country || "US",
inputProps: {
menu: SupportedCountries.map(country => {
return { value: country.alpha2, label: country.name }
})
},
controlProps: {
variant: "outlined"
}
})
const state = useInput(individual.address?.state, { required: true })
const city = useInput(individual.address?.city, { required: true })
const line1 = useInput(individual.address?.line1, { inputProps: { pattern: "[A-Za-z]{1,32}" }, required: true })
const line2 = useInput(individual.address?.line2)
const postal_code = useInput(individual.address?.postal_code, { required: true })
const email = useInput(individual.email, { required: true, type: "email" })
const phone = useInput(individual.phone, { required: true, type: "tel" })
const [front, setFront] = useState<string | undefined>()
const [back, setBack] = useState<string | undefined>()
const [isFrontLoading, setFrontLoading] = useState(false)
const [isBackLoading, setBackLoading] = useState(false)
const [isLoading, setLoading] = useState(false)
const handleClose = () => setOpen(false)
const handleSubmit = async (event) => {
event.preventDefault();
const uid = authUser?.uid
if (!uid) return
let data: Create = {
type: "custom",
country: "US",
business_type: "individual",
requested_capabilities: ["card_payments", "transfers"],
individual: {
last_name: last_name.value,
first_name: first_name.value,
dob: {
year: Number(year.value),
month: Number(month.value),
day: Number(day.value)
},
ssn_last_4: ssn_last_4.value,
address: {
country: country.value as string,
state: state.value,
city: city.value,
line1: line1.value,
line2: line2.value,
postal_code: postal_code.value
},
email: email.value,
phone: phone.value,
verification: {
document: {
front: front,
back: back
}
}
}
}
data = nullFilter(data)
setLoading(true)
const accountCreate = firebase.app().functions("us-central1").httpsCallable("account-v1-account-create")
try {
const response = await accountCreate(data)
const { result, error } = response.data
if (error) {
setError(error.message)
setLoading(false)
setOpen(true)
return
}
// const account = new Account(uid)
// account.accountID = result.id
// account.country = result.country
// account.businessType = result.business_type
// account.email = result.email
// account.individual = result.individual
// await account.save()
if (onCallback) {
onCallback(true)
}
setLoading(false)
} catch (error) {
setLoading(false)
setOpen(true)
console.log(error)
}
}
const handleFrontCapture = async ({ target }) => {
const uid = authUser?.uid
if (!uid) return
setFrontLoading(true)
const file = target.files[0] as File
const ref = firebase.storage().ref(new Account(uid).documentReference.path + "/verification/front.jpg")
ref.put(file).then(async (snapshot) => {
if (snapshot.state === "success") {
const metadata = snapshot.metadata
const { bucket, fullPath, name, contentType } = metadata
const uploadFile = firebase.functions().httpsCallable("stripe-v1-file-upload")
try {
const result = await uploadFile({ bucket, fullPath, name, contentType, purpose: "identity_document" })
const data = result.data
if (data) {
setFront(data.id)
}
} catch (error) {
console.error(error)
}
}
setFrontLoading(false)
})
}
const handleBackCapture = async ({ target }) => {
const uid = authUser?.uid
if (!uid) return
setBackLoading(true)
const file = target.files[0] as File
const ref = firebase.storage().ref(new Account(uid).documentReference.path + "/verification/back.jpg")
ref.put(file).then(async (snapshot) => {
if (snapshot.state === "success") {
const metadata = snapshot.metadata
const { bucket, fullPath, name, contentType } = metadata
const uploadFile = firebase.functions().httpsCallable("stripe-v1-file-upload")
try {
const result = await uploadFile({ bucket, fullPath, name, contentType, purpose: "identity_document" })
const data = result.data
if (data) {
setBack(data.id)
}
} catch (error) {
console.error(error)
}
}
setBackLoading(false)
})
}
return (
<>
<form onSubmit={handleSubmit}>
<Box className={classes.box} >
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<Table size="small">
<TableBody>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">First Name</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="first name" variant="outlined" margin="dense" size="small" {...first_name} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">Last Name</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="last name" variant="outlined" margin="dense" size="small" {...last_name} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">email</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="email" variant="outlined" margin="dense" size="small" {...email} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">Phone</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="phone" variant="outlined" margin="dense" size="small" {...phone} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">Birth date</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="year" type="number" variant="outlined" margin="dense" size="small" {...year} style={{ width: "80px", marginRight: "8px" }} />
<Input className={classes.input} label="month" type="number" variant="outlined" margin="dense" size="small" {...month} style={{ width: "66px", marginRight: "8px" }} />
<Input className={classes.input} label="day" type="number" variant="outlined" margin="dense" size="small" {...day} style={{ width: "66px" }} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">SSN Last 4</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="SSN last 4" variant="outlined" margin="dense" size="small" {...ssn_last_4} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}>
<Box className={classes.cellStatusBox}>
{isFrontLoading && <CircularProgress size={16} />}
{front && <DoneIcon color="primary" />}
</Box>
</TableCell>
<TableCell className={classes.cell} align="right">Passport or Local ID card. (front)</TableCell>
<TableCell className={classes.cell} align="left">
<input accept="image/jpeg,image/png,application/pdf" type="file" onChange={handleFrontCapture} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}>
<Box className={classes.cellStatusBox}>
{isBackLoading && <CircularProgress size={16} />}
{back && <DoneIcon color="primary" />}
</Box>
</TableCell>
<TableCell className={classes.cell} align="right">Passport or Local ID card. (Back)</TableCell>
<TableCell className={classes.cell} align="left">
<input accept="image/jpeg,image/png,application/pdf" type="file" onChange={handleBackCapture} />
</TableCell>
</TableRow>
</TableBody>
</Table>
</Grid>
<Grid item xs={12} sm={6}>
<Table size="small">
<TableBody>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">line1</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="line1" variant="outlined" margin="dense" size="small" {...line1} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">line2</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="line2" variant="outlined" margin="dense" size="small" {...line2} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">city</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="city" variant="outlined" margin="dense" size="small" {...city} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">state</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="state" variant="outlined" margin="dense" size="small" {...state} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">postal code</TableCell>
<TableCell className={classes.cell} align="left">
<Input className={classes.input} label="postal code" variant="outlined" margin="dense" size="small" {...postal_code} />
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.cellStatus}></TableCell>
<TableCell className={classes.cell} align="right">country</TableCell>
<TableCell className={classes.cell} align="left">
<Select {...country} />
</TableCell>
</TableRow>
</TableBody>
</Table>
</Grid>
</Grid>
</Box>
<Box className={classes.bottomBox} >
<Button style={{}} size="medium" color="primary" onClick={() => {
if (onCallback) {
onCallback(false)
}
}}>Back</Button>
<Button style={{}} variant="contained" size="medium" color="primary" type="submit">Save</Button>
</Box>
</form>
{isLoading && <Loading />}
<Dialog
open={open}
onClose={handleClose}
>
<DialogTitle>Error</DialogTitle>
<DialogContent>
<DialogContentText>
{error ? error : "Account registration failed."}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary" autoFocus>
OK
</Button>
</DialogActions>
</Dialog>
</>
)
} | the_stack |
import { user } from '../../sample-data/checkout-flow';
import { waitForOrderToBePlacedRequest } from '../../support/utils/order-placed';
export const productCode1 = '300938';
export const couponForCart = 'CouponForCart'; //Get $10 off your order
export const productCode2 = '493683';
export const couponForProduct = 'CouponForProduct'; //Get 25% off in all camera lenses
export const productCode3 = '1986316';
export const freeGiftCoupon = 'FreeGiftCoupon'; //Get a free gift when you buy Powershot A480 (1934796)
export const giftProductCode = '443175';
export const powerShotA480 = '1934793';
export const springFestivalCoupon = 'springfestival';
export const midAutumnCoupon = 'midautumn';
export function visitProductPage(productCode: string) {
registerProductDetailsRoute(productCode);
cy.visit(`/product/${productCode}`);
cy.wait('@product_details');
}
export function addProductToCart(productCode: string) {
cy.get('cx-add-to-cart')
.findAllByText(/Add To Cart/i)
.first()
.click();
cy.get('cx-added-to-cart-dialog').within(() => {
cy.get('.cx-code').should('contain', productCode);
cy.findByText(/view cart/i).click();
});
}
export function applyCoupon(couponCode: string) {
registerCartRefreshRoute();
applyCartCoupon(couponCode);
cy.wait('@refresh_cart').then((xhr) => {
const subtotal = xhr.response.body.subTotal.formattedValue;
const discount = xhr.response.body.totalDiscounts.formattedValue;
cy.get('cx-global-message').should(
'contain',
`${couponCode} has been applied`
);
getCouponItemFromCart(couponCode).should('exist');
cy.get('.cx-promotions > :nth-child(1)').should('exist');
//verify price
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-amount').should('contain', subtotal);
cy.get(':nth-child(5)').should('contain', `You saved: ${discount}`);
});
});
}
export function verifyMyCoupons() {
cy.get('.cx-available-coupon .coupon-id').should('have.length', 2);
cy.get('.cx-available-coupon .coupon-id').should(
'contain',
springFestivalCoupon
);
cy.get('.cx-available-coupon .coupon-id').should('contain', midAutumnCoupon);
}
export function ApplyMyCoupons(
couponCode: string,
checkOrderPromotion: boolean = false
) {
cy.get('.cx-available-coupon').within(() => {
cy.findByText(couponCode).parent().click();
});
cy.get('cx-global-message').should(
'contain',
`${couponCode} has been applied`
);
getCouponItemFromCart(couponCode).should('exist');
if (checkOrderPromotion) {
cy.get('.cx-available-coupon .coupon-id').should('not.contain', couponCode);
}
}
export function claimCoupon(couponCode: string) {
cy.request({
method: 'POST',
url: `${Cypress.env('API_URL')}/${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/customercoupons/${couponCode}/claim`,
headers: {
Authorization: `bearer ${
JSON.parse(localStorage.getItem('spartacus⚿⚿auth')).token.access_token
}`,
},
}).then((response) => {
expect(response.status).to.eq(201);
});
}
const cartCouponInput = 'input.input-coupon-code';
const cartCouponButton = 'button.apply-coupon-button';
const applyCartCoupon = (code: string) => {
cy.get('cx-cart-coupon').within(() => {
cy.get(cartCouponInput).type(code);
cy.get(cartCouponButton).click();
});
};
export function applyMyCouponAsAnonymous() {
visitProductPage(powerShotA480);
addProductToCart(powerShotA480);
applyCartCoupon(midAutumnCoupon);
getCouponItemFromCart(midAutumnCoupon).should('not.exist');
cy.get('cx-global-message .alert').should('exist');
}
export function registerProductDetailsRoute(productCode: string) {
const exp1 = `${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/products/${productCode}?fields=*&lang=en&curr=USD`;
cy.intercept('GET', exp1).as('product_details');
}
function registerCartRefreshRoute() {
// When adding a coupon to the cart, this route matches Selective carts first
//TODO matchers don't have proper regex (digits only). This might fail with a lot of carts in the system.
const exp1 = `${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/carts/0*?fields=*&lang=en&curr=USD`;
cy.intercept('GET', exp1).as('refresh_cart');
}
export function removeCoupon(couponCode: string) {
cy.get('.cx-coupon-apply > .close').click();
getCouponItemFromCart(couponCode).should('not.exist');
getCouponItemOrderSummary(couponCode).should('not.exist');
}
export function applyWrongCoupon() {
applyCartCoupon('wrongCouponCode');
cy.get('cx-global-message').should('contain', 'Invalid code provided.');
}
export function placeOrder(token: any) {
return cy
.get('.cx-total')
.first()
.then(($cart) => {
cy.log('Placing order asynchronously');
const cartId = $cart.text().match(/[0-9]+/)[0];
// Need to pass numeric CartId explicitly to avoid using the wrong cart for checkout
cy.requireShippingAddressAdded(user.address, token, cartId);
cy.requireShippingMethodSelected(token, cartId);
cy.requirePaymentDone(token, cartId);
return cy.requirePlacedOrder(token, cartId);
});
}
export function verifyOrderHistory(orderData: any, couponCode?: string) {
waitForOrderToBePlacedRequest(orderData.body.code);
registerOrderDetailsRoute(orderData.body.code);
cy.visit('my-account/orders');
cy.get('cx-order-history h3').should('contain', 'Order history');
cy.get('.cx-order-history-code ').within(() => {
cy.get('.cx-order-history-value')
.should('contain', orderData.body.code)
.click();
});
cy.wait('@order_details').then((xhr) => {
console.log(JSON.stringify(xhr.response.body));
const subtotal = xhr.response.body.subTotal.formattedValue;
const orderDiscount = xhr.response.body.totalDiscounts.formattedValue;
if (couponCode) {
getCouponItemOrderSummary(couponCode).should('exist');
cy.get('.cx-summary-partials > .cx-summary-row').should('have.length', 5);
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-amount').should('contain', subtotal);
cy.get(':nth-child(5)').should(
'contain',
`You saved: ${orderDiscount}`
);
});
} else {
verifyNoCouponInOrderHistory();
}
});
}
export function verifyCouponAndPromotion(
couponCode: string,
totalPrice: string,
savedPrice: string
) {
//verify coupon in cart
getCouponItemFromCart(couponCode).should('exist');
//verify promotion
cy.get('.cx-promotions > :nth-child(1)').should('exist');
//verify price
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-amount').should('contain', totalPrice);
cy.get(':nth-child(5)').should('contain', `You saved: ${savedPrice}`);
});
}
export function verifyCouponAndSavedPrice(
couponCode: string,
savedPrice: string
) {
//verify coupon in cart
getCouponItemFromCart(couponCode).should('exist');
//verify saved price
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-row').contains(`You saved: ${savedPrice}`);
});
}
export function verifyCouponAndSavedPriceInOrder(
couponCode: string,
savedPrice: string
) {
//verify coupon in order
getCouponItemOrderSummary(couponCode).should('exist');
//verify saved price
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-row').contains(`You saved: ${savedPrice}`);
});
}
export function verifyOrderHistoryForCouponAndPrice(
orderData: any,
couponCode?: string,
savedPrice?: string
) {
waitForOrderToBePlacedRequest(orderData.body.code);
navigateToOrderHistoryPage(orderData, couponCode);
if (couponCode) {
verifyCouponAndSavedPriceInOrder(couponCode, savedPrice);
} else {
verifyNoCouponInOrderHistory();
}
}
export function verifyGiftProductCoupon(productCode: string) {
cy.get('cx-cart-item-list')
.contains('cx-cart-item', productCode)
.within(() => {
cy.get('.cx-price > .cx-value').should('contain', '$0.00');
cy.get('cx-item-counter input').should('have.value', '1');
cy.get('.cx-total > .cx-value').should('contain', '$0.00');
});
}
export function verifyCouponInOrderHistory(
couponCode: string,
totalPrice: string,
savedPrice: string
) {
getCouponItemOrderSummary(couponCode).should('exist');
cy.get('.cx-summary-partials > .cx-summary-row').should('have.length', 5);
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-amount').should('contain', totalPrice);
cy.get(':nth-child(5)').should('contain', `You saved: ${savedPrice}`);
});
}
export function verifyNoCouponInOrderHistory() {
cy.get('cx-order-summary > cx-applied-coupons').should('not.be.visible');
cy.get('.cx-summary-partials > .cx-summary-row').should('have.length', 4);
cy.get('.cx-summary-partials').within(() => {
cy.get(':nth-child(5)').should('not.exist');
});
}
export function navigateToCheckoutPage() {
cy.get('cx-cart-totals > .btn')
.should('contain', 'Proceed to Checkout')
.click();
}
export function navigateToCartPage() {
cy.visit('cart');
}
export function registerOrderDetailsRoute(orderCode: string) {
cy.intercept(
'GET',
`${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/orders/${orderCode}?fields=*&lang=en&curr=USD`
).as('order_details');
}
export function navigateToOrderHistoryPage(orderData: any, couponCode: string) {
registerOrderDetailsRoute(orderData.body.code);
cy.visit('my-account/orders');
cy.get('cx-order-history h3').should('contain', 'Order history');
cy.get('.cx-order-history-code ').within(() => {
cy.get('.cx-order-history-value')
.should('contain', orderData.body.code)
.click();
});
cy.wait('@order_details').then((xhr) => {
const subtotal = xhr.response.body.subTotal.formattedValue;
const orderDiscount = xhr.response.body.totalDiscounts.formattedValue;
getCouponItemOrderSummary(couponCode).should('exist');
cy.get('.cx-summary-partials > .cx-summary-row').should('have.length', 5);
cy.get('.cx-summary-partials').within(() => {
cy.get('.cx-summary-amount').should('contain', subtotal);
cy.get(':nth-child(5)').should('contain', `You saved: ${orderDiscount}`);
});
});
}
export function getCouponItemFromCart(couponCode: string) {
return cy
.get('cx-cart-coupon > cx-applied-coupons > .row')
.contains('.cx-cart-coupon-code', couponCode);
}
export function getCouponItemOrderSummary(couponCode: string) {
return cy
.get('cx-order-summary cx-applied-coupons')
.contains('.cx-applied-coupon-code', couponCode);
}
export function verifyProductInCart(productCode: string) {
cy.get('cx-cart-item').within(() => {
cy.get('.cx-code').should('contain', productCode);
});
}
export function verifyOrderPlacingWithCouponAndCustomerCoupon() {
const stateAuth = JSON.parse(localStorage.getItem('spartacus⚿⚿auth')).token;
visitProductPage(powerShotA480);
addProductToCart(powerShotA480);
verifyProductInCart(powerShotA480);
cy.get('.cx-available-coupon').should('not.exist');
claimCoupon(springFestivalCoupon);
claimCoupon(midAutumnCoupon);
navigateToCartPage();
verifyMyCoupons();
ApplyMyCoupons(midAutumnCoupon, true);
applyCoupon(couponForCart);
//don't verify the total price which easy to changed by sample data
verifyCouponAndSavedPrice(midAutumnCoupon, '$30');
placeOrder(stateAuth).then((orderData: any) => {
verifyOrderHistoryForCouponAndPrice(orderData, midAutumnCoupon, '$30');
getCouponItemOrderSummary(couponForCart).should('exist');
});
}
export function verifyCustomerCouponRemoving() {
const stateAuth = JSON.parse(localStorage.getItem('spartacus⚿⚿auth')).token;
visitProductPage(powerShotA480);
claimCoupon(midAutumnCoupon);
addProductToCart(powerShotA480);
ApplyMyCoupons(midAutumnCoupon);
verifyCouponAndSavedPrice(midAutumnCoupon, '$20');
removeCoupon(midAutumnCoupon);
placeOrder(stateAuth).then((orderData: any) => {
verifyOrderHistory(orderData);
});
} | the_stack |
import * as ES from './ecmascript';
import { GetIntrinsic, MakeIntrinsicClass } from './intrinsicclass';
import { ISO_YEAR, ISO_MONTH, ISO_DAY, CALENDAR, GetSlot } from './slots';
import { Temporal } from '..';
import { DateTimeFormat } from './intl';
import type { FieldRecord, PlainYearMonthParams as Params, PlainYearMonthReturn as Return } from './internaltypes';
const ObjectCreate = Object.create;
const DISALLOWED_UNITS = [
'week',
'day',
'hour',
'minute',
'second',
'millisecond',
'microsecond',
'nanosecond'
] as const;
export class PlainYearMonth implements Temporal.PlainYearMonth {
constructor(
isoYearParam: Params['constructor'][0],
isoMonthParam: Params['constructor'][1],
calendarParam: Params['constructor'][2] = ES.GetISO8601Calendar(),
referenceISODayParam: Params['constructor'][3] = 1
) {
const isoYear = ES.ToIntegerThrowOnInfinity(isoYearParam);
const isoMonth = ES.ToIntegerThrowOnInfinity(isoMonthParam);
const calendar = ES.ToTemporalCalendar(calendarParam);
const referenceISODay = ES.ToIntegerThrowOnInfinity(referenceISODayParam);
// Note: if the arguments are not passed,
// ToIntegerThrowOnInfinity(undefined) will have returned 0, which will
// be rejected by RejectISODate in CreateTemporalYearMonthSlots. This
// check exists only to improve the error message.
if (arguments.length < 2) {
throw new RangeError('missing argument: isoYear and isoMonth are required');
}
ES.CreateTemporalYearMonthSlots(this, isoYear, isoMonth, calendar, referenceISODay);
}
get year(): Return['year'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarYear(GetSlot(this, CALENDAR), this);
}
get month(): Return['month'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonth(GetSlot(this, CALENDAR), this);
}
get monthCode(): Return['monthCode'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonthCode(GetSlot(this, CALENDAR), this);
}
get calendar(): Return['calendar'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return GetSlot(this, CALENDAR);
}
get era(): Return['era'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarEra(GetSlot(this, CALENDAR), this);
}
get eraYear(): Return['eraYear'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarEraYear(GetSlot(this, CALENDAR), this);
}
get daysInMonth(): Return['daysInMonth'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarDaysInMonth(GetSlot(this, CALENDAR), this);
}
get daysInYear(): Return['daysInYear'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarDaysInYear(GetSlot(this, CALENDAR), this);
}
get monthsInYear(): Return['monthsInYear'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarMonthsInYear(GetSlot(this, CALENDAR), this);
}
get inLeapYear(): Return['inLeapYear'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.CalendarInLeapYear(GetSlot(this, CALENDAR), this);
}
with(temporalYearMonthLike: Params['with'][0], optionsParam: Params['with'][1] = undefined): Return['with'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(temporalYearMonthLike)) {
throw new TypeError('invalid argument');
}
ES.RejectObjectWithCalendarOrTimeZone(temporalYearMonthLike);
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['month', 'monthCode', 'year'] as const);
const props = ES.ToPartialRecord(temporalYearMonthLike, fieldNames);
if (!props) {
throw new TypeError('invalid year-month-like');
}
let fields = ES.ToTemporalYearMonthFields(this, fieldNames);
fields = ES.CalendarMergeFields(calendar, fields, props);
fields = ES.ToTemporalYearMonthFields(fields, fieldNames);
const options = ES.GetOptionsObject(optionsParam);
return ES.YearMonthFromFields(calendar, fields, options);
}
add(temporalDurationLike: Params['add'][0], optionsParam: Params['add'][1] = undefined): Return['add'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
const duration = ES.ToLimitedTemporalDuration(temporalDurationLike);
let { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = duration;
({ days } = ES.BalanceDuration(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 'day'));
const options = ES.GetOptionsObject(optionsParam);
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const fields = ES.ToTemporalYearMonthFields(this, fieldNames);
const sign = ES.DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0);
const day = sign < 0 ? ES.ToPositiveInteger(ES.CalendarDaysInMonth(calendar, this)) : 1;
const startDate = ES.DateFromFields(calendar, { ...fields, day });
const optionsCopy = { ...options };
const addedDate = ES.CalendarDateAdd(calendar, startDate, { ...duration, days }, options);
const addedDateFields = ES.ToTemporalYearMonthFields(addedDate, fieldNames);
return ES.YearMonthFromFields(calendar, addedDateFields, optionsCopy);
}
subtract(
temporalDurationLike: Params['subtract'][0],
optionsParam: Params['subtract'][1] = undefined
): Return['subtract'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
let duration = ES.ToLimitedTemporalDuration(temporalDurationLike);
duration = {
years: -duration.years,
months: -duration.months,
weeks: -duration.weeks,
days: -duration.days,
hours: -duration.hours,
minutes: -duration.minutes,
seconds: -duration.seconds,
milliseconds: -duration.milliseconds,
microseconds: -duration.microseconds,
nanoseconds: -duration.nanoseconds
};
let { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = duration;
({ days } = ES.BalanceDuration(days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds, 'day'));
const options = ES.GetOptionsObject(optionsParam);
const calendar = GetSlot(this, CALENDAR);
const fieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const fields = ES.ToTemporalYearMonthFields(this, fieldNames);
const sign = ES.DurationSign(years, months, weeks, days, 0, 0, 0, 0, 0, 0);
const day = sign < 0 ? ES.ToPositiveInteger(ES.CalendarDaysInMonth(calendar, this)) : 1;
const startDate = ES.DateFromFields(calendar, { ...fields, day });
const optionsCopy = { ...options };
const addedDate = ES.CalendarDateAdd(calendar, startDate, { ...duration, days }, options);
const addedDateFields = ES.ToTemporalYearMonthFields(addedDate, fieldNames);
return ES.YearMonthFromFields(calendar, addedDateFields, optionsCopy);
}
until(otherParam: Params['until'][0], optionsParam: Params['until'][1] = undefined): Return['until'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalYearMonth(otherParam);
const calendar = GetSlot(this, CALENDAR);
const otherCalendar = GetSlot(other, CALENDAR);
const calendarID = ES.ToString(calendar);
const otherCalendarID = ES.ToString(otherCalendar);
if (calendarID !== otherCalendarID) {
throw new RangeError(
`cannot compute difference between months of ${calendarID} and ${otherCalendarID} calendars`
);
}
const options = ES.GetOptionsObject(optionsParam);
const smallestUnit = ES.ToSmallestTemporalUnit(options, 'month', DISALLOWED_UNITS);
const largestUnit = ES.ToLargestTemporalUnit(options, 'auto', DISALLOWED_UNITS, 'year');
ES.ValidateTemporalUnitRange(largestUnit, smallestUnit);
const roundingMode = ES.ToTemporalRoundingMode(options, 'trunc');
const roundingIncrement = ES.ToTemporalRoundingIncrement(options, undefined, false);
const fieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const otherFields = ES.ToTemporalYearMonthFields(other, fieldNames);
const thisFields = ES.ToTemporalYearMonthFields(this, fieldNames);
const otherDate = ES.DateFromFields(calendar, { ...otherFields, day: 1 });
const thisDate = ES.DateFromFields(calendar, { ...thisFields, day: 1 });
const untilOptions = { ...options, largestUnit };
const result = ES.CalendarDateUntil(calendar, thisDate, otherDate, untilOptions);
if (smallestUnit === 'month' && roundingIncrement === 1) return result;
let { years, months } = result;
({ years, months } = ES.RoundDuration(
years,
months,
0,
0,
0,
0,
0,
0,
0,
0,
roundingIncrement,
smallestUnit,
roundingMode,
thisDate
));
const Duration = GetIntrinsic('%Temporal.Duration%');
return new Duration(years, months, 0, 0, 0, 0, 0, 0, 0, 0);
}
since(otherParam: Params['since'][0], optionsParam: Params['since'][1] = undefined): Return['since'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalYearMonth(otherParam);
const calendar = GetSlot(this, CALENDAR);
const otherCalendar = GetSlot(other, CALENDAR);
const calendarID = ES.ToString(calendar);
const otherCalendarID = ES.ToString(otherCalendar);
if (calendarID !== otherCalendarID) {
throw new RangeError(
`cannot compute difference between months of ${calendarID} and ${otherCalendarID} calendars`
);
}
const options = ES.GetOptionsObject(optionsParam);
const smallestUnit = ES.ToSmallestTemporalUnit(options, 'month', DISALLOWED_UNITS);
const largestUnit = ES.ToLargestTemporalUnit(options, 'auto', DISALLOWED_UNITS, 'year');
ES.ValidateTemporalUnitRange(largestUnit, smallestUnit);
const roundingMode = ES.ToTemporalRoundingMode(options, 'trunc');
const roundingIncrement = ES.ToTemporalRoundingIncrement(options, undefined, false);
const fieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const otherFields = ES.ToTemporalYearMonthFields(other, fieldNames);
const thisFields = ES.ToTemporalYearMonthFields(this, fieldNames);
const otherDate = ES.DateFromFields(calendar, { ...otherFields, day: 1 });
const thisDate = ES.DateFromFields(calendar, { ...thisFields, day: 1 });
const untilOptions = { ...options, largestUnit };
let { years, months } = ES.CalendarDateUntil(calendar, thisDate, otherDate, untilOptions);
const Duration = GetIntrinsic('%Temporal.Duration%');
if (smallestUnit === 'month' && roundingIncrement === 1) {
return new Duration(-years, -months, 0, 0, 0, 0, 0, 0, 0, 0);
}
({ years, months } = ES.RoundDuration(
years,
months,
0,
0,
0,
0,
0,
0,
0,
0,
roundingIncrement,
smallestUnit,
ES.NegateTemporalRoundingMode(roundingMode),
thisDate
));
return new Duration(-years, -months, 0, 0, 0, 0, 0, 0, 0, 0);
}
equals(otherParam: Params['equals'][0]): Return['equals'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
const other = ES.ToTemporalYearMonth(otherParam);
for (const slot of [ISO_YEAR, ISO_MONTH, ISO_DAY]) {
const val1 = GetSlot(this, slot);
const val2 = GetSlot(other, slot);
if (val1 !== val2) return false;
}
return ES.CalendarEquals(GetSlot(this, CALENDAR), GetSlot(other, CALENDAR));
}
toString(optionsParam: Params['toString'][0] = undefined): string {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
const options = ES.GetOptionsObject(optionsParam);
const showCalendar = ES.ToShowCalendarOption(options);
return ES.TemporalYearMonthToString(this, showCalendar);
}
toJSON(): Return['toJSON'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return ES.TemporalYearMonthToString(this);
}
toLocaleString(
locales: Params['toLocaleString'][0] = undefined,
options: Params['toLocaleString'][1] = undefined
): string {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return new DateTimeFormat(locales, options).format(this);
}
valueOf(): never {
throw new TypeError('use compare() or equals() to compare Temporal.PlainYearMonth');
}
toPlainDate(item: Params['toPlainDate'][0]): Return['toPlainDate'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
if (!ES.IsObject(item)) throw new TypeError('argument should be an object');
const calendar = GetSlot(this, CALENDAR);
const receiverFieldNames = ES.CalendarFields(calendar, ['monthCode', 'year'] as const);
const fields = ES.ToTemporalYearMonthFields(this, receiverFieldNames);
const inputFieldNames = ES.CalendarFields(calendar, ['day']);
const inputEntries: FieldRecord<Temporal.PlainYearMonthLike & { day?: number }>[] = [['day']];
// Add extra fields from the calendar at the end
inputFieldNames.forEach((fieldName) => {
if (!inputEntries.some(([name]) => name === fieldName)) {
(inputEntries as unknown as Array<typeof inputEntries[number]>).push([
fieldName,
undefined
] as unknown as typeof inputEntries[number]); // Make TS ignore extra fields
}
});
const inputFields = ES.PrepareTemporalFields(item, inputEntries);
let mergedFields = ES.CalendarMergeFields(calendar, fields, inputFields);
const mergedFieldNames = [...new Set([...receiverFieldNames, ...inputFieldNames])];
const mergedEntries: FieldRecord<Temporal.PlainMonthDayLike>[] = [];
mergedFieldNames.forEach((fieldName) => {
if (!mergedEntries.some(([name]) => name === fieldName)) {
mergedEntries.push([fieldName, undefined] as typeof mergedEntries[number]);
}
});
mergedFields = ES.PrepareTemporalFields(mergedFields, mergedEntries);
const options = ObjectCreate(null);
options.overflow = 'reject';
return ES.DateFromFields(calendar, mergedFields, options);
}
getISOFields(): Return['getISOFields'] {
if (!ES.IsTemporalYearMonth(this)) throw new TypeError('invalid receiver');
return {
calendar: GetSlot(this, CALENDAR),
isoDay: GetSlot(this, ISO_DAY),
isoMonth: GetSlot(this, ISO_MONTH),
isoYear: GetSlot(this, ISO_YEAR)
};
}
static from(item: Params['from'][0], optionsParam: Params['from'][1] = undefined): Return['from'] {
const options = ES.GetOptionsObject(optionsParam);
if (ES.IsTemporalYearMonth(item)) {
ES.ToTemporalOverflow(options); // validate and ignore
return ES.CreateTemporalYearMonth(
GetSlot(item, ISO_YEAR),
GetSlot(item, ISO_MONTH),
GetSlot(item, CALENDAR),
GetSlot(item, ISO_DAY)
);
}
return ES.ToTemporalYearMonth(item, options);
}
static compare(oneParam: Params['compare'][0], twoParam: Params['compare'][1]): Return['compare'] {
const one = ES.ToTemporalYearMonth(oneParam);
const two = ES.ToTemporalYearMonth(twoParam);
return ES.CompareISODate(
GetSlot(one, ISO_YEAR),
GetSlot(one, ISO_MONTH),
GetSlot(one, ISO_DAY),
GetSlot(two, ISO_YEAR),
GetSlot(two, ISO_MONTH),
GetSlot(two, ISO_DAY)
);
}
[Symbol.toStringTag]!: 'Temporal.PlainYearMonth';
}
MakeIntrinsicClass(PlainYearMonth, 'Temporal.PlainYearMonth'); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Mappers from "./mappers";
import { Operation } from "./operation";
import * as Parameters from "./parameters";
const serializer = new msRest.Serializer(Mappers, true);
// specifications for new method group start
const serviceSetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype,
Parameters.comp0
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "storageServiceProperties",
mapper: {
...Mappers.StorageServiceProperties,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
202: {
headersMapper: Mappers.ServiceSetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype,
Parameters.comp0
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.StorageServiceProperties,
headersMapper: Mappers.ServiceGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceGetStatisticsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.restype,
Parameters.comp1
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.StorageServiceStats,
headersMapper: Mappers.ServiceGetStatisticsHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const serviceListQueuesSegmentOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.prefix,
Parameters.marker,
Parameters.maxresults,
Parameters.include,
Parameters.timeout,
Parameters.comp2
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: Mappers.ListQueuesSegmentResponse,
headersMapper: Mappers.ServiceListQueuesSegmentHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const queueCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.metadata,
Parameters.version,
Parameters.requestId
],
responses: {
201: {
headersMapper: Mappers.QueueCreateHeaders
},
204: {
headersMapper: Mappers.QueueCreateHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueDeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
204: {
headersMapper: Mappers.QueueDeleteHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueGetPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp3
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
headersMapper: Mappers.QueueGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueGetPropertiesWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp3
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
headersMapper: Mappers.QueueGetPropertiesWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueSetMetadataOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp3
],
headerParameters: [
Parameters.metadata,
Parameters.version,
Parameters.requestId
],
responses: {
204: {
headersMapper: Mappers.QueueSetMetadataHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueGetAccessPolicyOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp4
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: {
xmlElementName: "SignedIdentifier",
serializedName: "SignedIdentifiers",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SignedIdentifier"
}
}
}
},
headersMapper: Mappers.QueueGetAccessPolicyHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueGetAccessPolicyWithHeadOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp4
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: {
xmlElementName: "SignedIdentifier",
serializedName: "SignedIdentifiers",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SignedIdentifier"
}
}
}
},
headersMapper: Mappers.QueueGetAccessPolicyWithHeadHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const queueSetAccessPolicyOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{queueName}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout,
Parameters.comp4
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: [
"options",
"queueAcl"
],
mapper: {
xmlName: "SignedIdentifiers",
xmlElementName: "SignedIdentifier",
serializedName: "queueAcl",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SignedIdentifier"
}
}
}
}
},
contentType: "application/xml; charset=utf-8",
responses: {
204: {
headersMapper: Mappers.QueueSetAccessPolicyHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const messagesDequeueOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{queueName}/messages",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.numberOfMessages,
Parameters.visibilitytimeout0,
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: {
xmlElementName: "QueueMessage",
serializedName: "QueueMessagesList",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DequeuedMessageItem"
}
}
}
},
headersMapper: Mappers.MessagesDequeueHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const messagesClearOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{queueName}/messages",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
204: {
headersMapper: Mappers.MessagesClearHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const messagesEnqueueOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "{queueName}/messages",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.visibilitytimeout0,
Parameters.messageTimeToLive,
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "queueMessage",
mapper: {
...Mappers.QueueMessage,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
201: {
bodyMapper: {
xmlElementName: "QueueMessage",
serializedName: "QueueMessagesList",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "EnqueuedMessage"
}
}
}
},
headersMapper: Mappers.MessagesEnqueueHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const messagesPeekOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{queueName}/messages",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.numberOfMessages,
Parameters.timeout,
Parameters.peekonly
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
200: {
bodyMapper: {
xmlElementName: "QueueMessage",
serializedName: "QueueMessagesList",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "PeekedMessageItem"
}
}
}
},
headersMapper: Mappers.MessagesPeekHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
// specifications for new method group start
const messageIdUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{queueName}/messages/{messageid}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.popReceipt,
Parameters.visibilitytimeout1,
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
requestBody: {
parameterPath: "queueMessage",
mapper: {
...Mappers.QueueMessage,
required: true
}
},
contentType: "application/xml; charset=utf-8",
responses: {
204: {
headersMapper: Mappers.MessageIdUpdateHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const messageIdDeleteOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{queueName}/messages/{messageid}",
urlParameters: [
Parameters.url
],
queryParameters: [
Parameters.popReceipt,
Parameters.timeout
],
headerParameters: [
Parameters.version,
Parameters.requestId
],
responses: {
204: {
headersMapper: Mappers.MessageIdDeleteHeaders
},
default: {
bodyMapper: Mappers.StorageError
}
},
isXML: true,
serializer
};
const Specifications: { [key: number]: msRest.OperationSpec } = {};
Specifications[Operation.Service_SetProperties] = serviceSetPropertiesOperationSpec;
Specifications[Operation.Service_GetProperties] = serviceGetPropertiesOperationSpec;
Specifications[Operation.Service_GetStatistics] = serviceGetStatisticsOperationSpec;
Specifications[Operation.Service_ListQueuesSegment] = serviceListQueuesSegmentOperationSpec;
Specifications[Operation.Queue_Create] = queueCreateOperationSpec;
Specifications[Operation.Queue_Delete] = queueDeleteOperationSpec;
Specifications[Operation.Queue_GetProperties] = queueGetPropertiesOperationSpec;
Specifications[Operation.Queue_GetPropertiesWithHead] = queueGetPropertiesWithHeadOperationSpec;
Specifications[Operation.Queue_SetMetadata] = queueSetMetadataOperationSpec;
Specifications[Operation.Queue_GetAccessPolicy] = queueGetAccessPolicyOperationSpec;
Specifications[Operation.Queue_GetAccessPolicyWithHead] = queueGetAccessPolicyWithHeadOperationSpec;
Specifications[Operation.Queue_SetAccessPolicy] = queueSetAccessPolicyOperationSpec;
Specifications[Operation.Messages_Dequeue] = messagesDequeueOperationSpec;
Specifications[Operation.Messages_Clear] = messagesClearOperationSpec;
Specifications[Operation.Messages_Enqueue] = messagesEnqueueOperationSpec;
Specifications[Operation.Messages_Peek] = messagesPeekOperationSpec;
Specifications[Operation.MessageId_Update] = messageIdUpdateOperationSpec;
Specifications[Operation.MessageId_Delete] = messageIdDeleteOperationSpec;
export default Specifications; | the_stack |
declare namespace PhonegapFacebookPlugin {
//#region API Methods
interface FacebookConnectPluginStatic {
/**
* Allows access to the Facebook Graph API. This API allows for additional permission because, unlike login, the Graph API can
* accept multiple permissions. In order to make calls to the Graph API on behalf of a user, the user has to be logged into your
* app using Facebook login.
*
* @param graphPath The graph API path to use for the query.
* @param permissions The permissions to request.
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
api: (graphPath: string, permissions: string[], successCallback?: (result: any) => void, failureCallback?: (error: string) => void) => void;
/**
* Used to retreive the access token for the current user.
*
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
getAccessToken: (successCallback?: (token: string) => void, failureCallback?: (error: string) => void) => void;
/**
* Used to get the login status for the current user.
*
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
getLoginStatus: (successCallback?: (status: LoginResult) => void, failureCallback?: (error: string) => void) => void;
/**
* Used to log an event.
*
* @param name Name of the event.
* @param params Extra data to log with the event (optional).
* @param valueToSum a property which is an arbitrary number that can represent any value (e.g., a price or a quantity).
* When reported, all of the valueToSum properties will be summed together. For example, if 10 people each purchased
* one item that cost $10 (and passed in valueToSum) then they would be summed to report a number of $100. (optional)
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
logEvent: (name: string, params?: any, valueToSum?: number, successCallback?: () => void, failureCallback?: (error: string) => void) => void;
/**
* Used to log a purchase.
*
* @param value The value of the purchase.
* @param currency An ISO-4217 currency code.
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
logPurchase: (value: number, currency: string, successCallback?: () => void, failureCallback?: (error: string) => void) => void;
/**
* Used to log the user in via Facebook. Calling this will result in a Facebook login dialog (or external
* webpage) launching. Once the user completes the flow, one of the two callbacks will be executed.
*
* @param permissions The permissions to request during login.
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
login: (permissions: string[], successCallback?: (result: LoginResult) => void, failureCallback?: (error: string) => void) => void;
/**
* Used to log the user out of Facebook. This will invalidate their access token.
*
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
logout: (successCallback?: () => void, failureCallback?: (error: string) => void) => void;
/**
* Used to open a Facebook dialog.
*
* @param options The options that control the dialog and it's behavior.
* @param successCallback The callback to be executed when the call completes successfully.
* @param failureCallback The callback to be executed when the call fails.
*/
showDialog: (options: BaseDialogOptions, successCallback?: (status: BaseDialogResult) => void, failureCallback?: (error: string) => void) => void;
}
//#endregion
//#region Method Parameters
interface BaseDialogOptions {
/**
* The type of dialog to show, can be one of the following.
*
* Depeneding on the type, a different options object will be used:
*
* Method Options Type
* feed FeedDialogOptions
* send SendDialogOptions
* share ShareDialogOptions
* share_open_graph ShareOpenGraphDialogOptions
*/
method: string;
}
/**
* You can add the Feed Dialog to your app so people can publish individual stories to their timeline. This
* includes captions that your app manages and a personal comment from the person sharing the content.
*
* For use with showDialog() of method type 'feed'.
*/
interface FeedDialogOptions extends BaseDialogOptions {
/**
* The ID of the person posting the message. If this is unspecified, it defaults to the current person.
* If specified, it must be the ID of the person or of a page that the person administers.
*/
from?: string;
/**
* The ID of the profile that this story will be published to. If this is unspecified, it defaults to
* the value of from. The ID must be a friend who also uses your app.
*/
to?: string;
/**
* The link attached to this post.
*/
link?: string;
/**
* The URL of a picture attached to this post. The picture must be at least 200px by 200px.
*/
picture?: string;
/**
* The URL of a media file (either SWF or MP3) attached to this post. If SWF, you must also specify
* 'picture' to provide a thumbnail for the video.
*/
source?: string;
/**
* The name of the link attachment.
*/
name?: string;
/**
* The caption of the link (appears beneath the link name). If not specified, this field is automatically
* populated with the URL of the link.
*/
caption?: string;
/**
* The description of the link (appears beneath the link caption). If not specified, this field is
* automatically populated by information scraped from the link, typically the title of the page.
*/
description?: string;
/**
* This argument is a comma-separated list, consisting of at most 5 distinct items, each of length at
* least 1 and at most 15 characters drawn from the set
* '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_'.
* Each category is used in Facebook Insights to help you measure the performance of different types
* of post.
*/
ref?: string;
}
/**
* The Send Dialog lets people privately send content to specific friends. They'll have the option to privately
* share a link as a Facebook message or group post. The Send Dialog does not require any extended permissions.
*
* For use with showDialog() of method type 'send'.
*/
interface SendDialogOptions extends BaseDialogOptions {
/**
* A user ID of a recipient. Once the dialog comes up, the sender can specify additional people, and groups
* addresses as recipients. Sending content to a Facebook group will post it to the group's wall.
*/
to: string;
/**
* Required parameter. The URL that is being sent in the message.
*/
link: string;
}
/**
* The Share dialog prompts a person to publish an individual story or an Open Graph story to their timeline.
* This does not require Facebook Login or any extended permissions, so it is the easiest way to enable
* sharing on web.
*
* For use with showDialog() of method type 'share'.
*/
interface ShareDialogOptions extends BaseDialogOptions {
/**
* The link attached to this post. Required when using method share. Include open graph meta tags in the
* page at this URL to customize the story that is shared.
*/
href: string;
}
/**
* The Share dialog prompts a person to publish an individual story or an Open Graph story to their timeline.
* This does not require Facebook Login or any extended permissions, so it is the easiest way to enable
* sharing on web.
*
* For use with showDialog() of method type 'share_open_graph'.
*/
interface ShareOpenGraphDialogOptions extends BaseDialogOptions {
/**
* A string specifying which Open Graph action type to publish, e.g., og.likes for the built in like type.
* The dialog also supports approved custom types.
*/
action_type: string;
/**
* A JSON object of key/value pairs specifying parameters which correspond to the action_type being used.
* Valid key/value pairs are the same parameters that can be used when publishing Open Graph Actions using
* the API.
*/
action_properties: string;
}
//#endregion
//#region Callback Results
/**
* Result for the login() and getLoginStatus() success callbacks.
*/
interface LoginResult {
authResponse: {
accessToken: string;
expiresIn: string;
secret: string;
session_key: boolean;
sig: string;
userID: string;
},
status: string;
}
/**
* The base result type for all showDialog() success callbacks.
*/
interface BaseDialogResult {
error_code: string;
error_message: string;
}
/**
* The response object returned from a success callback for showDialog() of type 'feed'.
*/
interface FeedDialogResult extends BaseDialogResult {
/**
* The ID of the posted story, if the person chose to publish.
*/
post_id: string;
}
/**
* The response object returned from a success callback for showDialog() of type 'send'.
*/
interface SendDialogResult extends BaseDialogResult {
}
/**
* The response object returned from a success callback for showDialog() of type 'share' or 'share_open_graph'.
*/
interface ShareDialogResult extends BaseDialogResult {
/**
* Only available if the user is logged into your app using Facebook and has granted publish_actions.
* If present, this is the ID of the published Open Graph story.
*/
post_id: string;
}
//#endregion
}
declare var facebookConnectPlugin: PhonegapFacebookPlugin.FacebookConnectPluginStatic; | the_stack |
import { HttpResponse, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';import { HttpOptions } from './types';
import * as models from './models';
export interface APIClientInterface {
/**
* Arguments object for method `auth`.
*/
authParams?: {
/** Structure entity object that needs to be added */
body: models.AuthForm,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `passwordRestoreRequest`.
*/
passwordRestoreRequestParams?: {
/** Structure entity object that needs to be added */
body: models.RestoreForm,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `passwordRestoreEmailRequest`.
*/
passwordRestoreEmailRequestParams?: {
/** Structure entity object that needs to be added */
body: models.RestoreRequestForm,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `passwordRestoreCheckRestoreGuid`.
*/
passwordRestoreCheckRestoreGuidParams?: {
/** RestoreGuid for check */
restoreGuid: string,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Get list of roles to permissions mapping
* Response generated for [ 200 ] HTTP response code.
*/
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.AclItem[]>;
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.AclItem[]>>;
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.AclItem[]>>;
/**
* Get structure entities list
* Response generated for [ 200 ] HTTP response code.
*/
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure[]>;
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure[]>>;
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure[]>>;
/**
* Arguments object for method `addStructureEntity`.
*/
addStructureEntityParams?: {
/** Structure entity object that needs to be added */
body: models.StructureAddParameters,
};
/**
* Add a new structure entity
* Response generated for [ 200 ] HTTP response code.
*/
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure>;
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure>>;
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure>>;
/**
* Arguments object for method `updateStructureEntity`.
*/
updateStructureEntityParams?: {
/** structure id to update */
structureId: number,
/** Structure entity object that needs to be updated */
body: models.StructureForm,
};
/**
* Update an existing structure entity
* Response generated for [ 200 ] HTTP response code.
*/
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure>;
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure>>;
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure>>;
/**
* Arguments object for method `deleteStructureEntity`.
*/
deleteStructureEntityParams?: {
/** structure id to delete */
structureId: number,
};
/**
* Deletes a structure entity
* Response generated for [ 200 ] HTTP response code.
*/
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `getReportsList`.
*/
getReportsListParams?: {
/**
* - 1 Pending
* - 2 InProgress
* - 3 Complete
*
*/
status?: models.Status,
pageSize: number,
/** page number */
page: number,
/** id | title | subtitle | criticality | status | issues | deadline */
orderBy: ('id' | 'title' | 'subtitle' | 'criticality' | 'status' | 'issues' | 'deadline'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get reports list
* [Screenshot from design](http://prntscr.com/hy4z8d)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `getReportDetails`.
*/
getReportDetailsParams?: {
/** report id to get */
id: number,
};
/**
* Get report details
* [Screenshot from design](http://prntscr.com/hywkd5)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ReportItem[]>;
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ReportItem[]>>;
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ReportItem[]>>;
/**
* Arguments object for method `getReportPreview`.
*/
getReportPreviewParams?: {
/**
* [See #/definitions/ReportTemplate](#/Data_Import/getReportDetails)
*
*/
templateId: number,
pageSize: number,
/** page number */
page: number,
/** column id */
orderBy?: number,
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get report preview
* [Screenshot from design](http://prntscr.com/i3z8zb)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `getImportHistory`.
*/
getImportHistoryParams?: {
/**
* [See #/definitions/ReportTemplate](#/Data_Import/getReportDetails)
*
*/
templateId: number,
};
/**
* Get import history
* [Screenshot from design](http://prntscr.com/i3ym4j)
*
* Response generated for [ 200 ] HTTP response code.
*/
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ImportHistoryItem[]>;
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ImportHistoryItem[]>>;
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ImportHistoryItem[]>>;
/**
* Arguments object for method `uploadFile`.
*/
uploadFileParams?: {
/**
* [See #/definitions/ReportTemplate](#/Data_Import/getReportDetails)
*
*/
templateId: number,
/** file to upload */
file: File,
};
/**
* Upload a completed template
* [Screenshot from design](http://prntscr.com/hy521p)
*
* Response generated for [ 200 ] HTTP response code.
*/
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<number>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<number>>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<number>>;
/**
* Arguments object for method `listTemplateColumns`.
*/
listTemplateColumnsParams?: {
/**
* [See #/definitions/ReportTemplate](#/Data_Import/getReportDetails)
*
*/
templateId: number,
};
/**
* Get list of current Import template columns
* [Screenshot from design](http://prntscr.com/hy52hi)
*
* Response generated for [ 200 ] HTTP response code.
*/
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Column[]>;
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Column[]>>;
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Column[]>>;
/**
* Arguments object for method `listReportColumns`.
*/
listReportColumnsParams?: {
/** Id of current import */
id: number,
};
/**
* Get list of current Import template columns
* [Screenshot from design](http://prntscr.com/hy52zr)
*
* Response generated for [ 200 ] HTTP response code.
*/
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Column[]>;
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Column[]>>;
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Column[]>>;
/**
* Arguments object for method `saveColumnsMapping`.
*/
saveColumnsMappingParams?: {
/** Id of current import */
id: number,
/** Column mappint for current import */
body: models.ColumnMapping[],
};
/**
* Save columns mapping
* [Screenshot from design](http://prntscr.com/hy53jt)
*
* Response generated for [ 200 ] HTTP response code.
*/
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Table>;
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Table>>;
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Table>>;
/**
* Arguments object for method `getValidationTable`.
*/
getValidationTableParams?: {
/** Id of current import */
id: number,
};
/**
* Get validation table
* [Screenshot from design](http://prntscr.com/hy5fct)
*
* Response generated for [ 200 ] HTTP response code.
*/
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ValidatedTable>;
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ValidatedTable>>;
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ValidatedTable>>;
/**
* Arguments object for method `downloadImportedFile`.
*/
downloadImportedFileParams?: {
/** Id of current import */
id: number,
/** Indicator of downloading data(all or errors only) */
all?: boolean,
};
/**
* Download imported data
* [Screenshot from design](http://prntscr.com/hy55ga)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
/**
* Arguments object for method `importConfirmation`.
*/
importConfirmationParams?: {
/** Id of current import */
id: number,
};
/**
* Confirm final import
* [Screenshot from design](http://prntscr.com/hy57nj)
*
* Response generated for [ 200 ] HTTP response code.
*/
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ImportResponse>;
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ImportResponse>>;
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ImportResponse>>;
/**
* Arguments object for method `downloadImportOriginalFile`.
*/
downloadImportOriginalFileParams?: {
/** Id of current import */
id: number,
};
/**
* Download original file
* [Screenshot from design](http://prntscr.com/hy5a54)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
/**
* Arguments object for method `downloadImportSkippedFile`.
*/
downloadImportSkippedFileParams?: {
/** Id of current import */
id: number,
};
/**
* Download skipped rows file
* [Screenshot from design](http://prntscr.com/hy5ae7)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
/**
* Arguments object for method `cancelImport`.
*/
cancelImportParams?: {
/** Id of current import */
id: number,
};
/**
* Cancel current import
* [Screenshot from design](http://prntscr.com/hy5aqq)
*
* Response generated for [ 200 ] HTTP response code.
*/
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `overrideImport`.
*/
overrideImportParams?: {
/** Id of current import */
id: number,
/** description of override request */
description: string,
/** file to upload */
file: File,
};
/**
* Request override data for import
* [Screenshot from design](http://prntscr.com/hy5bi6)
*
* Response generated for [ 200 ] HTTP response code.
*/
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `geImportStats`.
*/
geImportStatsParams?: {
/**
* - 1 Year
* - 2 Month
* - 3 Week
*
*/
period?: models.Period,
};
/**
* Get import stats
* [Screenshot from design](http://prntscr.com/i4052r)
*
* Response generated for [ 200 ] HTTP response code.
*/
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.TotalImportStats>;
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.TotalImportStats>>;
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.TotalImportStats>>;
/**
* Arguments object for method `getIssuesList`.
*/
getIssuesListParams?: {
/**
* - 1 Year
* - 2 Month
* - 3 Week
*
*/
period?: models.Period,
/**
* - 1 Pending
* - 2 Resolved
*
*/
status?: models.IssueStatus,
pageSize: number,
/** page number */
page: number,
/** name | school | dueDate | alert */
orderBy: ('name' | 'school' | 'dueDate' | 'alert'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get issues list
* [Screenshot from design](http://prntscr.com/i40s18)
*
* Response generated for [ 200 ] HTTP response code.
*/
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `getStatusesList`.
*/
getStatusesListParams?: {
/**
* - 1 Year
* - 2 Month
* - 3 Week
*
*/
period?: models.Period,
/**
* - 1 Live
* - 2 PastDeadline
*
*/
status?: models.ImportStatus,
pageSize: number,
/** page number */
page: number,
/** name | issues | dueDate | progress */
orderBy: ('name' | 'issues' | 'dueDate' | 'progress'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get import statuses list
* [Screenshot from design](http://prntscr.com/i4byyx)
*
* Response generated for [ 200 ] HTTP response code.
*/
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `getUsersList`.
*/
getUsersListParams?: {
/**
* - 1 Year
* - 2 Month
* - 3 Week
*
*/
period?: models.Period,
/**
* - 1 Live
* - 2 PastDeadline
*
*/
status?: models.ImportStatus,
pageSize: number,
/** page number */
page: number,
/** name | issues | dueDate | progress */
orderBy: ('name' | 'issues' | 'dueDate' | 'progress'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
/** role id | [Screenshot from design](http://prntscr.com/ib9yal) */
assignedToRole?: number,
/** role id | [Screenshot from design](http://prntscr.com/ib9z16) */
unassignedFromRole?: number,
};
/**
* Get users list
* Response generated for [ 200 ] HTTP response code.
*/
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `createUser`.
*/
createUserParams?: {
/** User entity object that needs to be added */
body: models.UserDetails,
};
/**
* Create user
* Response generated for [ 200 ] HTTP response code.
*/
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails>>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails>>;
/**
* Get acl structure
* Response generated for [ 200 ] HTTP response code.
*/
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Acl[]>;
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Acl[]>>;
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Acl[]>>;
/**
* Arguments object for method `getUserDetails`.
*/
getUserDetailsParams?: {
id: number,
};
/**
* getUserDetails
* Response generated for [ 200 ] HTTP response code.
*/
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails[]>;
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails[]>>;
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails[]>>;
/**
* Arguments object for method `updateUser`.
*/
updateUserParams?: {
id: number,
/** User entity object that needs to be updated */
body: models.UserDetails,
};
/**
* update user by id
* Response generated for [ 200 ] HTTP response code.
*/
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails>>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails>>;
/**
* Arguments object for method `deleteUser`.
*/
deleteUserParams?: {
id: number,
};
/**
* delete user by id
* Response generated for [ 200 ] HTTP response code.
*/
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Get roles list
* [Screenshot from design](http://prntscr.com/i93q0s)
*
* Response generated for [ 200 ] HTTP response code.
*/
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleListItem[]>;
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleListItem[]>>;
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleListItem[]>>;
/**
* Arguments object for method `createRole`.
*/
createRoleParams?: {
/** Role entity object that needs to be added */
body: object,
};
/**
* Create role
* Response generated for [ 200 ] HTTP response code.
*/
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem>;
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem>>;
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem>>;
/**
* Get privileges list
* [Screenshot from design](http://prntscr.com/i947a3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PrivilegeTreeItem[]>;
getList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PrivilegeTreeItem[]>>;
getList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PrivilegeTreeItem[]>>;
/**
* Arguments object for method `getRoleDetails`.
*/
getRoleDetailsParams?: {
id: number,
};
/**
* Get role details
* Response generated for [ 200 ] HTTP response code.
*/
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem[]>;
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem[]>>;
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem[]>>;
/**
* Arguments object for method `updateRole`.
*/
updateRoleParams?: {
id: number,
body?: models.RoleUpdateDetails,
};
/**
* Update role by id
* Response generated for [ 200 ] HTTP response code.
*/
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem>;
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem>>;
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem>>;
/**
* Arguments object for method `deleteRole`.
*/
deleteRoleParams?: {
id: number,
};
/**
* Ddelete role by id
* Response generated for [ 200 ] HTTP response code.
*/
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Get unviewed notifications list
* [Screenshot from design](http://prntscr.com/iba7xr)
*
* Response generated for [ 200 ] HTTP response code.
*/
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationListItem[]>;
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationListItem[]>>;
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationListItem[]>>;
/**
* Arguments object for method `markViewedNotifications`.
*/
markViewedNotificationsParams?: {
body?: number[],
};
/**
* Mark notifications as viewed
* Response generated for [ 200 ] HTTP response code.
*/
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `getNotificationsList`.
*/
getNotificationsListParams?: {
pageSize: number,
/** page number */
page: number,
/** name | description | priority | date */
orderBy: ('name' | 'description' | 'priority' | 'date'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get user's notifications list
* [Screenshot from design](http://prntscr.com/iba8tq)
*
* Response generated for [ 200 ] HTTP response code.
*/
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Get modules list
* [Screenshot from design](http://prntscr.com/ibac47) |
* [Screenshot from design](http://prntscr.com/ibacgu)
*
* Response generated for [ 200 ] HTTP response code.
*/
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationModule[]>;
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationModule[]>>;
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationModule[]>>;
/**
* Get triggers list
* [Screenshot from design](http://prntscr.com/ibad9m)
*
* Response generated for [ 200 ] HTTP response code.
*/
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationTrigger[]>;
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationTrigger[]>>;
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationTrigger[]>>;
/**
* Arguments object for method `getModuleNotificationsList`.
*/
getModuleNotificationsListParams?: {
moduleId: number,
pageSize: number,
/** page number */
page: number,
/** name | description | priority | date */
orderBy: ('name' | 'description' | 'priority' | 'date'),
/**
* - asc
* - desc
*
*/
order?: models.Order,
};
/**
* Get module's notifications list
* [Screenshot from design](http://prntscr.com/iba8tq)
*
* Response generated for [ 200 ] HTTP response code.
*/
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `enableNotification`.
*/
enableNotificationParams?: {
id: number,
};
/**
* Enable notification
* Response generated for [ 200 ] HTTP response code.
*/
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `disableNotification`.
*/
disableNotificationParams?: {
id: number,
};
/**
* Disable notification
* Response generated for [ 200 ] HTTP response code.
*/
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `getNotification`.
*/
getNotificationParams?: {
id: number,
};
/**
* Get notification details
* Response generated for [ 200 ] HTTP response code.
*/
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationEditableListItem>;
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationEditableListItem>>;
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationEditableListItem>>;
/**
* Arguments object for method `updateNotification`.
*/
updateNotificationParams?: {
id: number,
body?: models.NotificationEditable,
};
/**
* Update notification
* Response generated for [ 200 ] HTTP response code.
*/
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `createNotification`.
*/
createNotificationParams?: {
body?: models.NotificationEditable,
};
/**
* Create notification
* Response generated for [ 200 ] HTTP response code.
*/
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<number>;
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<number>>;
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<number>>;
/**
* Get password verefication settings
* [Screenshot from design](http://prntscr.com/ijzt2b)
*
* Response generated for [ 200 ] HTTP response code.
*/
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordVerificationPolicies>;
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordVerificationPolicies>>;
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordVerificationPolicies>>;
/**
* Arguments object for method `udatePassVerificationPolicies`.
*/
udatePassVerificationPoliciesParams?: {
body?: models.PasswordVerificationPolicies,
};
/**
* Update password verefication settings
* [Screenshot from design](http://prntscr.com/ijzt2b)
*
* Response generated for [ 200 ] HTTP response code.
*/
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordVerificationPolicies>;
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordVerificationPolicies>>;
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordVerificationPolicies>>;
/**
* Get password creation settings
* [Screenshot from design](http://prntscr.com/ijzuv3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordCreationPolicies>;
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordCreationPolicies>>;
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordCreationPolicies>>;
/**
* Arguments object for method `udatePassCreationPolicies`.
*/
udatePassCreationPoliciesParams?: {
body?: models.PasswordCreationPolicies,
};
/**
* Update password creation settings
* [Screenshot from design](http://prntscr.com/ijzuv3)
*
* Response generated for [ 200 ] HTTP response code.
*/
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordCreationPolicies>;
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordCreationPolicies>>;
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordCreationPolicies>>;
/**
* Get other security settings settings
* [Screenshot from design](http://prntscr.com/ijzvo3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.OtherSecuritySettings>;
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.OtherSecuritySettings>>;
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.OtherSecuritySettings>>;
/**
* Arguments object for method `udateOtherSecuritySettings`.
*/
udateOtherSecuritySettingsParams?: {
body?: models.OtherSecuritySettings,
};
/**
* Update other security settings settings
* [Screenshot from design](http://prntscr.com/ijzvo3)
*
* Response generated for [ 200 ] HTTP response code.
*/
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.OtherSecuritySettings>;
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.OtherSecuritySettings>>;
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.OtherSecuritySettings>>;
} | the_stack |
import { IComponent, INvModule, ComponentList, DirectiveList, NvModule, InDiv, Vnode, utils, IDirective, lifecycleCaller, NvModuleFactory, Type, ErrorHandler } from '@indiv/core';
import { nvRouteStatus, NvLocation } from './location';
import { RouterTo, RouterFrom } from './directives';
import { getService, rootInjector } from '@indiv/di';
export type TChildModule = () => Promise<Type<INvModule>>;
export interface IComponentWithRoute extends IComponent {
nvRouteCanActive?: (lastRoute: string, newRoute: string) => boolean;
nvRouteChange?: (lastRoute?: string, newRoute?: string) => void;
}
export interface IDirectiveWithRoute extends IDirective {
nvRouteChange?: (lastRoute?: string, newRoute?: string) => void;
}
export type TRouter = {
path: string;
redirectTo?: string;
component?: string;
children?: TRouter[];
loadChild?: TChildModule;
routeCanActive?: (lastRoute: string, newRoute: string) => boolean;
routeChange?: (lastRoute?: string, newRoute?: string) => void;
};
@NvModule({
declarations: [
RouterTo,
RouterFrom,
],
providers: [
{
useClass: NvLocation,
provide: NvLocation,
},
],
exports: [
RouterTo,
RouterFrom,
],
})
export class RouteModule {
public routeChange?: (lastRoute?: string, nextRoute?: string) => void;
private routes: TRouter[];
private routesList: TRouter[] = [];
private currentUrl: string = '';
private lastRoute: string = null;
private hasRenderComponentList: IComponentWithRoute[] = [];
private needRedirectPath: string = null;
private isWatching: boolean = false;
private renderRouteList: string[] = [];
private loadModuleMap: Map<string, INvModule> = new Map();
private canWatch: boolean = false;
/**
* Creates an instance of RouteModule.
*
* if don't use static function forRoot, RouteModule.prototype.canWatch is false
* if RouteModule.prototype.canWatch is false, don't watch router
* if RouteModule.prototype.canWatch is true, watch router and reset RouteModule.prototype.canWatch
*
* @param {InDiv} indivInstance
* @param {NvLocation} nvLocation
* @memberof RouteModule
*/
constructor(
private indivInstance: InDiv,
private nvLocation: NvLocation,
) {
if (!RouteModule.prototype.canWatch) return;
RouteModule.prototype.canWatch = false;
if (!this.routes) this.routes = [];
if (!nvRouteStatus.nvRootPath) nvRouteStatus.nvRootPath = '/';
this.indivInstance.setRouteDOMKey('router-render');
// if isn't browser, will auto watch nvRouteStatus.nvRouteObject
if (!utils.hasWindowAndDocument()) return;
// if is browser, will watch nvRouteStatus.nvRouteObject by 'load' event of window
window.addEventListener('load', () => this.refresh(), false);
window.addEventListener('popstate', () => {
let path;
if (nvRouteStatus.nvRootPath === '/') {
path = location.pathname || '/';
} else {
path = location.pathname.replace(nvRouteStatus.nvRootPath, '') === '' ? '/' : location.pathname.replace(nvRouteStatus.nvRootPath, '');
}
nvRouteStatus.nvRouteObject = {
path,
query: {},
data: null,
};
nvRouteStatus.nvRouteParmasObject = {};
}, false);
}
/**
* init root data
*
* @static
* @param {{
* routes: TRouter[],
* rootPath?: string,
* routeChange?: (lastRoute?: string, nextRoute?: string) => void,
* }} routeData
* @returns {Function}
* @memberof RouteModule
*/
public static forRoot(routeData: {
routes: TRouter[],
rootPath?: string,
routeChange?: (lastRoute?: string, nextRoute?: string) => void,
}): Function {
if (routeData.rootPath) nvRouteStatus.nvRootPath = routeData.rootPath;
if (routeData.routeChange) RouteModule.prototype.routeChange = routeData.routeChange;
if (routeData.routes && routeData.routes instanceof Array) {
RouteModule.prototype.routes = routeData.routes;
} else {
throw new Error(`route error: no routes exit`);
}
RouteModule.prototype.canWatch = true;
return RouteModule;
}
/**
* build object by location.search
*
* @returns
* @memberof Utils
*/
private buildObjectFromLocationSearch(): Object {
if (!location.search) return {};
const returnValue: any = {};
const queryList = location.search.split('?')[1].split('&');
queryList.forEach(query => returnValue[query.split('=')[0]] = query.split('=')[1]);
return returnValue;
}
/**
* refresh if not watch $nvRouteObject
*
* @private
* @memberof Router
*/
private refresh(): void {
if (!nvRouteStatus.nvRouteObject || !this.isWatching) {
let path;
if (nvRouteStatus.nvRootPath === '/') path = location.pathname || '/';
else path = location.pathname.replace(nvRouteStatus.nvRootPath, '') === '' ? '/' : location.pathname.replace(nvRouteStatus.nvRootPath, '');
nvRouteStatus.nvRouteObject = {
path,
query: this.buildObjectFromLocationSearch(),
data: null,
};
nvRouteStatus.nvRouteParmasObject = {};
this.routeWatcher();
}
this.currentUrl = nvRouteStatus.nvRouteObject.path || '/';
this.routesList = [];
this.renderRouteList = this.currentUrl === '/' ? ['/'] : this.currentUrl.split('/');
this.renderRouteList[0] = '/';
this.distributeRoutes();
}
/**
* open watcher on nvRouteStatus.nvRouteObject
*
* @private
* @returns
* @memberof RouteModule
*/
private routeWatcher(): void {
const routeModuleInstance = this;
let val = nvRouteStatus.nvRouteObject;
Object.defineProperty(nvRouteStatus, 'nvRouteObject', {
configurable: true,
enumerable: true,
get() {
return val;
},
set(newVal: any) {
const _val = JSON.parse(JSON.stringify(val));
val = newVal;
if (newVal.path !== _val.path) routeModuleInstance.refresh();
},
});
this.isWatching = true;
}
/**
* distribute routes and decide insert or general Routes
*
* @private
* @returns {Promise<void>}
* @memberof Router
*/
private async distributeRoutes(): Promise<void> {
if (this.lastRoute && this.lastRoute !== this.currentUrl) {
// has rendered
nvRouteStatus.nvRouteParmasObject = {};
await this.insertRenderRoutes();
} else {
// first render child
await this.generalDistributeRoutes();
}
if (this.routeChange) this.routeChange(this.lastRoute, this.currentUrl);
this.lastRoute = this.currentUrl;
if (this.needRedirectPath) {
this.nvLocation.redirectTo(this.needRedirectPath, {}, null, null);
this.needRedirectPath = null;
}
}
/**
* insert Routes and render
*
* if has rendered Routes, it will find which is different and render it
*
* @private
* @returns {Promise<void>}
* @memberof Router
*/
private async insertRenderRoutes(): Promise<void> {
const lastRouteList = this.lastRoute === '/' ? ['/'] : this.lastRoute.split('/');
lastRouteList[0] = '/';
for (let index = 0; index < this.renderRouteList.length; index++) {
const path = this.renderRouteList[index];
if (index === 0) {
const rootRoute = this.routes.find(route => route.path === `${path}` || `${path}/` || /^\/\:.+/.test(route.path));
if (!rootRoute) throw new Error(`route error: wrong route instantiation in insertRenderRoutes: ${this.currentUrl}`);
this.routesList.push(rootRoute);
} else {
const lastRoute = this.routesList[index - 1].children;
if (!lastRoute || !(lastRoute instanceof Array)) throw new Error('route error: routes not exit or routes must be an array!');
const route = lastRoute.find((r: TRouter) => r.path === `/${path}` || `/${path}/` || /^\/\:.+/.test(r.path));
if (!route) throw new Error(`route error: wrong route instantiation: ${this.currentUrl}`);
this.routesList.push(route);
}
if (path !== lastRouteList[index]) {
const needRenderRoute = this.routesList[index];
if (!needRenderRoute) throw new Error(`route error: wrong route instantiation in insertRenderRoutes: ${this.currentUrl}`);
const nativeElement = this.indivInstance.getRenderer.getElementsByTagName('router-render')[index - 1];
let initVnode: Vnode[] = null;
if (this.hasRenderComponentList[index]) initVnode = this.hasRenderComponentList[index].$saveVnode;
if (!needRenderRoute.component && !needRenderRoute.redirectTo && !needRenderRoute.loadChild) throw new Error(`route error: path ${needRenderRoute.path} need a component which has children path or need a redirectTo which has't children path`);
if (/^\/\:.+/.test(needRenderRoute.path) && !needRenderRoute.redirectTo) {
const key = needRenderRoute.path.split('/:')[1];
nvRouteStatus.nvRouteParmasObject[key] = path;
}
let FindComponent = null;
let component = null;
let currentUrlPath = '';
// build current url with route.path
// because route has been pushed to this.routesList, don't use to += path
this.routesList.forEach((r, index) => { if (index !== 0) currentUrlPath += r.path; });
if (needRenderRoute.component) {
const findComponentFromModuleResult = this.findComponentFromModule(needRenderRoute.component, currentUrlPath);
FindComponent = findComponentFromModuleResult.component;
component = this.initComponent(FindComponent, nativeElement, findComponentFromModuleResult.loadModule);
}
if (needRenderRoute.loadChild) {
const loadModule = await this.NvModuleFactoryLoader(needRenderRoute.loadChild as TChildModule, currentUrlPath);
FindComponent = loadModule.$bootstrap;
component = this.initComponent(FindComponent, nativeElement, loadModule);
}
// navigation guards: route.routeCanActive component.nvRouteCanActive
if (needRenderRoute.routeCanActive && !needRenderRoute.routeCanActive(this.lastRoute, this.currentUrl)) break;
if (FindComponent) {
// insert needRenderComponent on index in this.hasRenderComponentList
// and remove other component which index >= index of FindComponent
if (component) {
if (component.nvRouteCanActive && !component.nvRouteCanActive(this.lastRoute, this.currentUrl)) break;
await this.runRender(component, nativeElement, initVnode);
if (this.hasRenderComponentList[index]) this.hasRenderComponentList.splice(index, 0, component);
else this.hasRenderComponentList[index] = component;
} else {
throw new Error(`route error: path ${needRenderRoute.path} need a component`);
}
this.routerChangeEvent(index);
}
if (needRenderRoute.redirectTo && /^\/.*/.test(needRenderRoute.redirectTo) && (index + 1) === this.renderRouteList.length) {
this.needRedirectPath = needRenderRoute.redirectTo;
return;
}
}
// add parmas in $nvRouteParmasObject
if (path === lastRouteList[index]) {
const needRenderRoute = this.routesList[index];
if (/^\/\:.+/.test(needRenderRoute.path) && !needRenderRoute.redirectTo) {
const key = needRenderRoute.path.split('/:')[1];
nvRouteStatus.nvRouteParmasObject[key] = path;
}
}
if (index === (this.renderRouteList.length - 1) && index < (lastRouteList.length - 1)) {
const nativeElement = this.indivInstance.getRenderer.getElementsByTagName('router-render')[index];
this.routerChangeEvent(index);
if (nativeElement && this.indivInstance.getRenderer.hasChildNodes(nativeElement)) this.indivInstance.getRenderer.getChildNodes(nativeElement).forEach(child => this.indivInstance.getRenderer.removeChild(nativeElement, child));
const needRenderRoute = this.routesList[index];
if (needRenderRoute.redirectTo && /^\/.*/.test(needRenderRoute.redirectTo) && (index + 1) === this.renderRouteList.length) {
this.needRedirectPath = needRenderRoute.redirectTo;
return;
}
}
}
}
/**
* render Routes
*
* first render
*
* @private
* @returns {Promise<void>}
* @memberof Router
*/
private async generalDistributeRoutes(): Promise<void> {
for (let index = 0; index < this.renderRouteList.length; index++) {
const path = this.renderRouteList[index];
if (index === 0) {
const rootRoute = this.routes.find(route => route.path === `${path}` || `${path}/` || /^\/\:.+/.test(route.path));
if (!rootRoute) throw new Error(`route error: wrong route instantiation in generalDistributeRoutes: ${this.currentUrl}`);
if (/^\/\:.+/.test(rootRoute.path)) {
const key = rootRoute.path.split('/:')[1];
nvRouteStatus.nvRouteParmasObject[key] = path;
}
this.routesList.push(rootRoute);
// push root component in InDiv instance
this.hasRenderComponentList.push(this.indivInstance.getBootstrapComponent);
if (rootRoute.routeCanActive) rootRoute.routeCanActive(this.lastRoute, this.currentUrl);
if ((this.indivInstance.getBootstrapComponent as IComponentWithRoute).nvRouteCanActive) (this.indivInstance.getBootstrapComponent as IComponentWithRoute).nvRouteCanActive(this.lastRoute, this.currentUrl);
if (index === this.renderRouteList.length - 1) this.routerChangeEvent(index);
if (rootRoute.redirectTo && /^\/.*/.test(rootRoute.redirectTo) && (index + 1) === this.renderRouteList.length) {
this.needRedirectPath = rootRoute.redirectTo;
this.renderRouteList.push(rootRoute.redirectTo);
return;
}
} else {
const lastRoute = this.routesList[index - 1].children;
if (!lastRoute || !(lastRoute instanceof Array)) throw new Error('route error: routes not exit or routes must be an array!');
const route = lastRoute.find(r => r.path === `/${path}` || `/${path}/` || /^\/\:.+/.test(r.path));
if (!route) throw new Error(`route error: wrong route instantiation: ${this.currentUrl}`);
const nativeElement = this.indivInstance.getRenderer.getElementsByTagName('router-render')[index - 1];
let initVnode: Vnode[] = null;
if (this.hasRenderComponentList[index]) initVnode = this.hasRenderComponentList[index].$saveVnode;
let FindComponent = null;
let component = null;
let currentUrlPath = '';
// build current url with route.path
// because rootRoute hasn't been pushed to this.routesList, we need to += route.path
this.routesList.forEach((r, index) => { if (index !== 0) currentUrlPath += r.path; });
currentUrlPath += route.path;
if (route.component) {
const findComponentFromModuleResult = this.findComponentFromModule(route.component, currentUrlPath);
FindComponent = findComponentFromModuleResult.component;
component = this.initComponent(FindComponent, nativeElement, findComponentFromModuleResult.loadModule);
}
if (route.loadChild) {
const loadModule = await this.NvModuleFactoryLoader(route.loadChild as TChildModule, currentUrlPath);
FindComponent = loadModule.$bootstrap;
component = this.initComponent(FindComponent, nativeElement, loadModule);
}
// navigation guards: route.routeCanActive component.nvRouteCanActive
if (route.routeCanActive && !route.routeCanActive(this.lastRoute, this.currentUrl)) break;
if (!route.component && !route.redirectTo && !route.loadChild) throw new Error(`route error: path ${route.path} need a component which has children path or need a redirectTo which has't children path`);
if (/^\/\:.+/.test(route.path)) {
const key = route.path.split('/:')[1];
nvRouteStatus.nvRouteParmasObject[key] = path;
}
this.routesList.push(route);
if (component) {
if (component.nvRouteCanActive && !component.nvRouteCanActive(this.lastRoute, this.currentUrl)) break;
await this.runRender(component, nativeElement, initVnode);
this.hasRenderComponentList.push(component);
}
if (index === this.renderRouteList.length - 1) this.routerChangeEvent(index);
if (route.redirectTo && /^\/.*/.test(route.redirectTo) && (index + 1) === this.renderRouteList.length) {
this.needRedirectPath = route.redirectTo;
return;
}
}
}
}
/**
* emit nvRouteChange and nvOnDestory for Components
*
* @private
* @param {number} index
* @memberof Router
*/
private routerChangeEvent(index: number): void {
try {
this.hasRenderComponentList.forEach((component, i) => {
if (component.nvRouteChange) component.nvRouteChange(this.lastRoute, this.currentUrl);
this.emitDirectiveEvent(component.$directiveList, 'nvRouteChange');
this.emitComponentEvent(component.$componentList, 'nvRouteChange');
if (i >= index + 1) {
this.emitDirectiveEvent(component.$directiveList, 'nvOnDestory');
this.emitComponentEvent(component.$componentList, 'nvOnDestory');
lifecycleCaller(component, 'nvOnDestory');
}
});
} catch (e) {
// 增加下错误处理,使用ErrorHandler
let errorHandler: ErrorHandler = null;
if (!errorHandler && this.indivInstance.getRootModule) {
const injector = this.indivInstance.getRootModule.$privateInjector || rootInjector;
// 在这里处理全局的handler
if (!injector.getProvider(ErrorHandler)) return;
errorHandler = getService(injector, ErrorHandler);
}
if (errorHandler) errorHandler.handleError(e);
else console.error('route error: call route event: ', e);
} finally {
this.hasRenderComponentList.length = index + 1;
}
}
/**
* emit nvRouteChange and nvOnDestory for Components with recursion
*
* @private
* @param {ComponentList[]} componentList
* @param {string} event
* @memberof Router
*/
private emitComponentEvent(componentList: ComponentList[], event: string): void {
if (event === 'nvRouteChange') {
componentList.forEach(component => {
if ((component.instanceScope as IComponentWithRoute).nvRouteChange) (component.instanceScope as IComponentWithRoute).nvRouteChange(this.lastRoute, this.currentUrl);
});
}
if (event === 'nvOnDestory') {
componentList.forEach(component => {
this.emitDirectiveEvent(component.instanceScope.$directiveList, event);
this.emitComponentEvent(component.instanceScope.$componentList, event);
lifecycleCaller(component.instanceScope, 'nvOnDestory');
});
}
}
/**
* emit nvRouteChange and nvOnDestory for Directives with recursion
*
* @private
* @param {DirectiveList[]} directiveList
* @param {string} event
* @memberof RouteModule
*/
private emitDirectiveEvent(directiveList: DirectiveList[], event: string): void {
if (event === 'nvRouteChange') {
directiveList.forEach(directive => {
if ((directive.instanceScope as IDirectiveWithRoute).nvRouteChange) (directive.instanceScope as IDirectiveWithRoute).nvRouteChange(this.lastRoute, this.currentUrl);
});
}
if (event === 'nvOnDestory') {
directiveList.forEach(directive => {
lifecycleCaller(directive.instanceScope, 'nvOnDestory');
});
}
}
/**
* instantiate Component
*
* use InDiv initComponent
*
* if argument has loadModule, use loadModule
* if argument has'nt loadModule, use rootModule in InDiv
*
* @private
* @param {Function} FindComponent
* @param {Element} nativeElement
* @param {INvModule} loadModule
* @returns {IComponentWithRoute}
* @memberof RouteModule
*/
private initComponent(FindComponent: Function, nativeElement: Element, loadModule: INvModule): IComponentWithRoute {
return this.indivInstance.initComponent(FindComponent, nativeElement, loadModule);
}
/**
* run renderer of Component
*
* if argument has initVnode, will use initVnode fro new Component instance
*
* @private
* @template R
* @param {IComponentWithRoute} FindComponent
* @param {R} nativeElement
* @param {Vnode[]} [initVnode]
* @returns {Promise<IComponentWithRoute>}
* @memberof RouteModule
*/
private runRender<R = Element>(FindComponent: IComponentWithRoute, nativeElement: R, initVnode?: Vnode[]): Promise<IComponentWithRoute> {
return this.indivInstance.runComponentRenderer(FindComponent, nativeElement, initVnode);
}
/**
* build Module and return Component for route.loadChild
*
* @private
* @param {(TChildModule)} loadChild
* @returns {Promise<INvModule>}
* @memberof Router
*/
private async NvModuleFactoryLoader(loadChild: TChildModule, currentUrlPath: string): Promise<INvModule> {
if (this.loadModuleMap.has(currentUrlPath)) return this.loadModuleMap.get(currentUrlPath);
const loadModule = await loadChild();
if (!loadModule) throw new Error('load child failed, please check your routes.');
const loadModuleInstance = NvModuleFactory(loadModule);
this.loadModuleMap.set(currentUrlPath, loadModuleInstance);
return loadModuleInstance;
}
/**
* find component from loadModule or rootModule
*
* if this.loadModuleMap.size === 0, only in rootModule
* if has loadModule, return component in loadModule firstly
*
*
* @private
* @param {string} selector
* @param {string} currentUrlPath
* @returns {{ component: Function, loadModule: INvModule }}
* @memberof Router
*/
private findComponentFromModule(selector: string, currentUrlPath: string): { component: Function, loadModule: INvModule } {
if (this.loadModuleMap.size === 0) return {
component: this.indivInstance.getDeclarations.find((component: any) => component.selector === selector && component.nvType === 'nvComponent'),
loadModule: null,
};
let component = null;
let loadModule = null;
this.loadModuleMap.forEach((value, key) => {
if (new RegExp(`^${key}.*`).test(currentUrlPath)) {
component = value.$declarations.find((component: any) => component.selector === selector && component.nvType === 'nvComponent');
loadModule = value;
}
});
if (!component) {
component = this.indivInstance.getDeclarations.find((component: any) => component.selector === selector && component.nvType === 'nvComponent');
loadModule = null;
}
return { component, loadModule };
}
} | the_stack |
import * as uuid from 'uuid';
import { nanoid } from 'nanoid';
import { JSONObject } from 'kuzzle-sdk';
import { RequestInput } from './requestInput';
import { RequestResponse } from './requestResponse';
import { RequestContext } from './requestContext';
import { KuzzleError, InternalError } from '../../kerror/errors';
import kerror from '../../kerror';
import { Deprecation, User } from '../../types';
import * as assert from '../../util/assertType';
import { get, isPlainObject } from '../../util/safeObject';
const assertionError = kerror.wrap('api', 'assert');
// private properties
// \u200b is a zero width space, used to masquerade console.log output
const _internalId = 'internalId\u200b';
const _status = 'status\u200b';
const _input = 'input\u200b';
const _error = 'error\u200b';
const _result = 'result\u200b';
const _context = 'context\u200b';
const _timestamp = 'timestamp\u200b';
const _response = 'response\u200b';
const _deprecations = 'deprecations\u200b';
/**
* The `KuzzleRequest` class represents a request being processed by Kuzzle.
*
* It contains every information used internally by Kuzzle to process the request
* like the client inputs, but also the response that will be sent back to the client.
*
*/
export class KuzzleRequest {
/**
* Request external ID (specified by "requestId" or random uuid)
*/
public id: string;
constructor (data: any, options: any) {
this[_internalId] = nanoid();
this[_status] = 102;
this[_input] = new RequestInput(data);
this[_context] = new RequestContext(options);
this[_error] = null;
this[_result] = null;
this[_response] = null;
this[_deprecations] = undefined;
// @deprecated - Backward compatibility with the RequestInput.headers
// property
this[_input].headers = this[_context].connection.misc.headers;
this.id = data.requestId
? assert.assertString('requestId', data.requestId)
: nanoid();
this[_timestamp] = data.timestamp || Date.now();
// handling provided options
if (options !== undefined && options !== null) {
if (typeof options !== 'object' || Array.isArray(options)) {
throw new InternalError('Request options must be an object');
}
/*
* Beware of the order of setXxx methods: if there is an
* error object in the options, it's very probable that
* the user wants its status to be the request's final
* status.
*
* Likewise, we should initialize the request status last,
* as it should override any automated status if it has
* been specified.
*/
if (options.result) {
this.setResult(options.result, options);
}
if (options.error) {
if (options.error instanceof Error) {
this.setError(options.error);
}
else {
const error = new KuzzleError(options.error.message, options.error.status || 500);
for (const prop of Object.keys(options.error).filter(key => key !== 'message' && key !== 'status')) {
error[prop] = options.error[prop];
}
this.setError(error);
}
}
if (options.status) {
this.status = options.status;
}
}
Object.seal(this);
}
/**
* Request internal ID
*/
get internalId (): string {
return this[_internalId];
}
/**
* Deprecation warnings for the API action
*/
get deprecations(): Deprecation[] | void {
return this[_deprecations];
}
/**
* Request timestamp (in Epoch-micro)
*/
get timestamp(): number {
return this[_timestamp];
}
/**
* Request HTTP status
*/
get status(): number {
return this[_status];
}
set status(i: number) {
this[_status] = assert.assertInteger('status', i);
}
/**
* Request input
*/
get input (): RequestInput {
return this[_input];
}
/**
* Request context
*/
get context (): RequestContext {
return this[_context];
}
/**
* Request error
*/
get error (): KuzzleError | null {
return this[_error];
}
/**
* Request result
*/
get result (): any | null {
return this[_result];
}
/**
* Request response
*/
get response (): RequestResponse {
if (this[_response] === null) {
this[_response] = new RequestResponse(this);
}
return this[_response];
}
/**
* Adds an error to the request, and sets the request's status to the error one.
*/
setError (error: Error) {
if (! error || !(error instanceof Error)) {
throw new InternalError('Cannot set non-error object as a request\'s error');
}
this[_error] = error instanceof KuzzleError ? error : new InternalError(error);
this.status = this[_error].status;
}
/**
* Sets the request error to null and status to 200
*/
clearError () {
this[_error] = null;
this.status = 200;
}
/**
* Sets the request result and status
*
* @deprecated Use request.response.configure instead
*
* @param result Request result. Will be converted to JSON unless `raw` option is set to `true`
* @param options Additional options
* - `status` (number): HTTP status code (default: 200)
* - `headers` (JSONObject): additional response protocol headers (default: null)
* - `raw` (boolean): instead of a Kuzzle response, forward the result directly (default: false)
*/
setResult (
result: any,
options: {
/**
* HTTP status code
*/
status?: number
/**
* additional response protocol headers
*/
headers?: JSONObject | null;
/**
* Returns directly the result instead of wrapping it in a Kuzzle response
*/
raw?: boolean;
} = {}
) {
if (result instanceof Error) {
throw new InternalError('cannot set an error as a request\'s response');
}
this.status = options.status || 200;
if (options.headers) {
this.response.setHeaders(options.headers);
}
if (options.raw !== undefined) {
this.response.raw = options.raw;
}
this[_result] = result;
}
/**
* Add a deprecation for a used component, this can be action/controller/parameters...
*
* @param version version where the used component has been deprecated
* @param message message displayed in the warning
*/
addDeprecation (version: string, message: string) {
if (global.NODE_ENV !== 'development') {
return;
}
const deprecation = {
message,
version,
};
if (! this.deprecations) {
this[_deprecations] = [deprecation];
}
else {
this.deprecations.push(deprecation);
}
}
/**
* Serialize this object into a pair of POJOs that can be send
* across the network and then used to instantiate a new Request
* object
*/
serialize (): { data: JSONObject, options: JSONObject } {
const serialized = {
data: {
_id: this[_input].args._id,
action: this[_input].action,
body: this[_input].body,
collection: this[_input].args.collection,
controller: this[_input].controller,
index: this[_input].args.index,
jwt: this[_input].jwt,
requestId: this.id,
timestamp: this[_timestamp],
volatile: this[_input].volatile,
},
// @deprecated - duplicate of options.connection.misc.headers
headers: this[_input].headers,
options: {
error: this[_error],
result: this[_result],
status: this[_status],
},
};
Object.assign(serialized.data, this[_input].args);
Object.assign(serialized.options, this[_context].toJSON());
return serialized;
}
/**
* Returns the `lang` param of the request.
*
* It can only be 'elasticsearch' or 'koncorde'
*/
getLangParam (): 'elasticsearch' | 'koncorde' {
const lang = this.getString('lang', 'elasticsearch');
if (lang !== 'elasticsearch' && lang !== 'koncorde') {
throw kerror.get(
'api',
'assert',
'invalid_argument',
'lang',
'"elasticsearch" or "koncorde"');
}
return lang;
}
/**
* Gets a parameter from a request body and checks that it is a boolean.
* Contrary to other parameter types, an unset boolean does not trigger an
* error, instead it's considered as 'false'
*
* @param name parameter name
*/
getBodyBoolean (name: string): boolean {
const body = this.input.body;
if (body === null) {
return false;
}
return this._getBoolean(body, name, `body.${name}`);
}
/**
* Gets a parameter from a request body and checks that it is a number
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.body_required} If no default value provided and no
* request body set
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not a number
*/
getBodyNumber (name: string, def: number | null = null): number {
const body = this.input.body;
if (body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this._getNumber(body, name, `body.${name}`, def);
}
/**
* Gets a parameter from a request body and checks that it is a integer
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.body_required} If no default value provided and no
* request body set
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an integer
*/
getBodyInteger (name: string, def: number | null = null): number {
const body = this.input.body;
if (body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this._getInteger(body, name, `body.${name}`, def);
}
/**
* Gets a parameter from a request body and checks that it is a string
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.body_required} If no default value provided and no
* request body set
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not a string
*/
getBodyString (name: string, def: string | null = null): string {
const body = this.input.body;
if (body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this._getString(body, name, `body.${name}`, def);
}
/**
* Gets a parameter from a request body and checks that it is an array
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.body_required} If no default value provided and no
* request body set
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an array
*/
getBodyArray (name: string, def: [] | null = null) {
const body = this.input.body;
if (body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this._getArray(body, name, `body.${name}`, def);
}
/**
* Gets a parameter from a request body and checks that it is an object
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.body_required} If no default value provided and no
* request body set
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an object
*/
getBodyObject (name: string, def: JSONObject | null = null): JSONObject {
const body = this.input.body;
if (body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this._getObject(body, name, `body.${name}`, def);
}
/**
* Gets a parameter from a request arguments and checks that it is a boolean
* Contrary to other parameter types, an unset boolean does not trigger an
* error, instead it's considered as 'false'
*
* @param name parameter name
*/
getBoolean (name: string): boolean {
return this._getBoolean(this.input.args, name, name);
}
/**
* Gets a parameter from a request arguments and checks that it is a number
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not a number
*/
getNumber (name: string, def: number | null = null): number {
return this._getNumber(this.input.args, name, name, def);
}
/**
* Gets a parameter from a request arguments and checks that it is an integer
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an integer
*/
getInteger (name: string, def: number | null = null): number {
return this._getInteger(this.input.args, name, name, def);
}
/**
* Gets a parameter from a request arguments and checks that it is a string
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not a string
*/
getString (name: string, def: string | null = null) {
return this._getString(this.input.args, name, name, def);
}
/**
* Gets a parameter from a request arguments and checks that it is an array
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an array
*/
getArray (name: string, def: [] | null = null): any[] {
return this._getArray(this.input.args, name, name, def);
}
/**
* Gets a parameter from a request arguments and checks that it is an object
*
* @param name parameter name
* @param def default value to return if the parameter is not set
*
* @throws {api.assert.missing_argument} If parameter not found and no default
* value provided
* @throws {api.assert.invalid_type} If the fetched parameter is not an object
*/
getObject (name: string, def: JSONObject | null = null): JSONObject {
return this._getObject(this.input.args, name, name, def);
}
/**
* Returns the index specified in the request
*/
getIndex (): string {
const index = this.input.args.index;
if (! index) {
throw assertionError.get('missing_argument', 'index');
}
return index;
}
/**
* Returns the collection specified in the request
*/
getCollection (): string {
const collection = this.input.args.collection;
if (! collection) {
throw assertionError.get('missing_argument', 'collection');
}
return collection;
}
/**
* Returns the index and collection specified in the request
*/
getIndexAndCollection (): { index: string, collection: string } {
if (! this.input.args.index) {
throw assertionError.get('missing_argument', 'index');
}
if (! this.input.args.collection) {
throw assertionError.get('missing_argument', 'collection');
}
return {
collection: this.input.args.collection,
index: this.input.args.index,
};
}
/**
* Returns the provided request's body
*
* @param def default value to return if the body is not set
*
* @throws {api.assert.body_required} If the body is not set and if no default
* value is provided
*/
getBody (def: JSONObject | null = null): JSONObject {
if (this.input.body === null) {
if (def !== null) {
return def;
}
throw assertionError.get('body_required');
}
return this.input.body;
}
/**
* Returns the `_id` specified in the request.
*
* @param options Additional options
* - `ifMissing`: method behavior if the ID is missing (default: 'error')
* - `generator`: function used to generate an ID (default: 'uuid.v4')
*
*/
getId (
options: {
ifMissing?: 'error' | 'generate' | 'ignore',
generator?: () => string,
} = { generator: uuid.v4, ifMissing: 'error' }
): string {
const id = this.input.args._id;
if (! id) {
if (options.ifMissing === 'generate') {
return options.generator();
}
if (options.ifMissing === 'ignore') {
return null;
}
throw assertionError.get('missing_argument', '_id');
}
if (typeof id !== 'string') {
throw assertionError.get('invalid_type', '_id', 'string');
}
return id;
}
/**
* Returns the current user kuid
*/
getKuid (): string | null {
if (this.context && this.context.user && this.context.user._id) {
return this.context.user._id;
}
return null;
}
/**
* Returns the current user
*/
getUser (): User | null {
if (this.context && this.context.user) {
return this.context.user;
}
return null;
}
/**
* Returns the search body query according to the http method
*/
getSearchBody (): JSONObject {
if ( this.context.connection.protocol !== 'http'
|| this.context.connection.misc.verb !== 'GET'
) {
return this.getBody({});
}
const searchBody = this.getString('searchBody', '{}');
try {
return JSON.parse(searchBody);
}
catch (err) {
throw assertionError.get('invalid_argument', err.message);
}
}
/**
* Returns the search params.
*/
getSearchParams (): {
from: number,
query: JSONObject,
scrollTTL: string,
searchBody: JSONObject,
size: number,
} {
const from = this.getInteger('from', 0);
const size = this.getInteger('size', 10);
const scrollTTL = this.getScrollTTLParam();
const query = this.getBodyObject('query', {});
const searchBody = this.getSearchBody();
return { from, query, scrollTTL, searchBody, size };
}
/**
* Extract string scroll ttl param from the request or returns undefined
*/
getScrollTTLParam (): string {
const scrollTTLParam = this.input.args.scroll;
if (scrollTTLParam && typeof scrollTTLParam !== 'string') {
throw assertionError.get('invalid_type', 'scroll', 'string');
}
return scrollTTLParam;
}
/**
* Gets the refresh value.
*/
getRefresh (defaultValue: 'false' | 'wait_for' = 'false'): 'false' | 'wait_for' {
if (this.input.args.refresh === undefined) {
return defaultValue;
}
if ( this.input.args.refresh === false
|| this.input.args.refresh === 'false'
|| this.input.args.refresh === null
) {
return 'false';
}
return 'wait_for';
}
/**
* Returns true if the current user have `admin` profile
*/
userIsAdmin (): boolean {
const user = this.getUser();
if (! user) {
return false;
}
return user.profileIds.includes('admin');
}
/**
* Generic object getter: boolean value
*
* @param obj container object
* @param name parameter name
* @param errorName name to use in error messages
*/
private _getBoolean (obj: JSONObject, name: string, errorName: string): boolean {
let value = get(obj, name);
// In HTTP, booleans are flags: if it's in the querystring, it's set,
// whatever its value.
// If a user needs to unset the option, they need to remove it from the
// querystring.
if (this.context.connection.protocol === 'http') {
value = value !== undefined;
obj[name] = value;
}
else if (value === undefined || value === null) {
value = false;
}
else if (typeof value !== 'boolean') {
throw assertionError.get('invalid_type', errorName, 'boolean');
}
else {
value = Boolean(value);
}
return value;
}
/**
* Generic object getter: number value
*
* @param obj container object
* @param name parameter name
* @param errorName - name to use in error messages
* @param def default value
*/
private _getNumber (
obj: JSONObject,
name: string,
errorName: string,
def: number | null = null
): number {
let value = get(obj, name);
if (value === undefined || value === null) {
if (def !== null) {
return def;
}
throw assertionError.get('missing_argument', errorName);
}
value = Number.parseFloat(value);
if (Number.isNaN(value)) {
throw assertionError.get('invalid_type', errorName, 'number');
}
return value;
}
/**
* Generic object getter: integer value
*
* @param obj container object
* @param name parameter name
* @param errorName name to use in error messages
* @param def default value
*/
private _getInteger (
obj: JSONObject,
name: string,
errorName: string,
def: number | null = null
): number {
let value = get(obj, name);
if (value === undefined || value === null) {
if (def !== null) {
return def;
}
throw assertionError.get('missing_argument', errorName);
}
value = Number.parseFloat(value);
if (Number.isNaN(value) || !Number.isSafeInteger(value)) {
throw assertionError.get('invalid_type', errorName, 'integer');
}
return value;
}
/**
* Generic object getter: string value
*
* @param obj container object
* @param name parameter name
* @param errorName name to use in error messages
* @param def default value
*/
private _getString (
obj: JSONObject,
name: string,
errorName: string,
def: string | null = null
): string {
const value = get(obj, name);
if (value === undefined || value === null) {
if (def !== null) {
return def;
}
throw assertionError.get('missing_argument', errorName);
}
if (typeof value !== 'string') {
throw assertionError.get('invalid_type', errorName, 'string');
}
return value;
}
/**
* Generic object getter: array value
*
* @param obj container object
* @param name parameter name
* @param errorName name to use in error messages
* @param def default value
*/
private _getArray (
obj: JSONObject,
name: string,
errorName: string,
def: [] | null = null
): any[] {
const value = get(obj, name);
if (value === undefined || value === null) {
if (def !== null) {
return def;
}
throw assertionError.get('missing_argument', errorName);
}
if (!Array.isArray(value)) {
throw assertionError.get('invalid_type', errorName, 'array');
}
return value;
}
/**
* Generic object getter: object value
*
* @param obj container object
* @param name parameter name
* @param errorName name to use in error messages
* @param def default value
*/
private _getObject (
obj: JSONObject,
name: string,
errorName: string,
def: JSONObject | null = null
): JSONObject {
const value = get(obj, name);
if (value === undefined || value === null) {
if (def !== null) {
return def;
}
throw assertionError.get('missing_argument', errorName);
}
if (!isPlainObject(value)) {
throw assertionError.get('invalid_type', errorName, 'object');
}
return value;
}
}
export class Request extends KuzzleRequest {} | the_stack |
import { IEvent, BindingAspect, parseNode, Locals, PartialBinding, ITemplateData, ITemplateConfig } from "./template";
import { addIdentifierToElement, addEvent, addBinding } from "./helpers";
import { ValueTypes } from "../chef/javascript/components/value/value";
import { Expression, VariableReference } from "../chef/javascript/components/value/expression";
import { parseForNode } from "./constructs/for";
import { parseIfNode } from "./constructs/if";
import { parseStylingDeclarationsFromString } from "../chef/css/value";
import { TemplateLiteral } from "../chef/javascript/components/value/template-literal";
import { FunctionDeclaration } from "../chef/javascript/components/constructs/function";
import { HTMLComment, HTMLDocument, HTMLElement } from "../chef/html/html";
import { defaultRenderSettings } from "../chef/helpers";
import { assignToObjectMap } from "../helpers";
import { join } from "path";
import { ObjectLiteral } from "../chef/javascript/components/value/object";
export function parseHTMLElement(
element: HTMLElement,
templateData: ITemplateData,
templateConfig: ITemplateConfig,
locals: Array<VariableReference>, // TODO eventually remove
localData: Locals = [],
nullable = false,
multiple = false,
) {
assignToObjectMap(templateData.nodeData, element, "nullable", nullable);
assignToObjectMap(templateData.nodeData, element, "multiple", multiple);
// If imported element:
if (templateConfig.tagNameToComponentMap.has(element.tagName)) {
const component = templateConfig.tagNameToComponentMap.get(element.tagName)!;
if (!component) {
throw Error(`Cannot find imported component of name ${element.tagName}`)
}
// Assert that if component needs data then the "$data" attribute is present
if (component.needsData && !element.attributes?.has?.("$data")) {
// TODO filename and render the node
throw Error(`Component: "${component.className}" requires data and was not passed data through "$data" at and "${element.render(defaultRenderSettings, { inline: true })}"`);
}
if (component.hasSlots && element.children.length === 0) {
throw Error(`Component: "${component.className}" requires content and "${element.render(defaultRenderSettings, { inline: true })}" has no children`);
}
if (component.isPage) {
throw Error(`Component: "${component.className}" is a page and cannot be used within markup`);
}
// Modify the tag to match mentioned component tag (used by client side render)
element.tagName = component.tagName;
// Used for binding ssr function call to component render function
assignToObjectMap(templateData.nodeData, element, "component", component);
}
if (element.tagName === "svg") {
templateData.hasSVG = true;
}
// If element is slot
if (element.tagName === "slot") {
if (element.children.length > 0) {
throw Error("Slots elements cannot have children");
}
// Slot can only be single children
if (element.parent!.children.filter(child => !(child instanceof HTMLComment)).length > 1) {
throw Error("Slot element must be single child of element");
}
if (multiple) {
throw Error("Slot cannot be used under a #for element");
}
if (!(element.parent instanceof HTMLDocument)) {
addIdentifierToElement(element.parent!, templateData.nodeData);
}
// Future potential multiple slots but for now has not been implemented throughout
const slotFor = element.attributes?.get("for") ?? "content";
if (templateData.slots.has(slotFor)) {
throw Error(`Duplicate slot for "${slotFor}"`);
}
templateData.slots.set(slotFor, element);
assignToObjectMap(templateData.nodeData, element, "slotFor", slotFor);
return;
}
let childrenParsed = false;
// If element has attributes
if (element.attributes) {
// If relative anchor tag
if (
element.tagName === "a" &&
element.attributes.has("relative")
) {
element.attributes.delete("relative");
if (templateConfig.doClientSideRouting) {
const identifier = addIdentifierToElement(element, templateData.nodeData);
const event: IEvent = {
nodeIdentifier: identifier,
element: element,
// Router.bind is a method will which call Router.goTo using the href of the element
callback: VariableReference.fromChain("Router", "bind") as VariableReference,
eventName: "click",
required: false, // A
existsOnComponentClass: false
}
addEvent(templateData.events, element, event, templateData.nodeData);
}
// Rewrite href to be in terms staticSrc
// TODO for dynamic paths
if (element.attributes.has("href")) {
element.attributes.set(
"href",
join(templateConfig.staticSrc, element.attributes.get("href")!).replace(/\\/g, "/")
);
}
}
// TODO sort the attributes so #if comes later
for (const [name, value] of element.attributes) {
const subject = name.slice(1);
// If element is multiple then can be retrieved using root parent
if (
!multiple &&
"#$@".split("").some(prefix => name.startsWith(prefix)) &&
typeof templateData.nodeData.get(element)?.identifier === "undefined"
) {
addIdentifierToElement(element, templateData.nodeData);
}
// Dynamic attributes
if (name === "$style") {
const parts: Array<string | ValueTypes> = [];
for (const [key, [cssValue]] of parseStylingDeclarationsFromString(value!)) {
if (!cssValue || typeof cssValue === "string" || !("value" in cssValue)) {
throw Error(`Invalid CSS value around "${element.render(defaultRenderSettings, { inline: true })}"`);
}
const expression = Expression.fromString(cssValue.value);
parts.push(key + ":", expression, ";");
const binding: PartialBinding = {
aspect: BindingAspect.Style,
expression,
element: element,
styleKey: key
}
addBinding(binding, localData, locals, templateData.bindings);
}
// With CSR: elem.style = "color: red" does work okay!;
const styleTemplateLiteral = new TemplateLiteral(parts);
const dynamicAttributes = templateData.nodeData.get(element)?.dynamicAttributes;
if (dynamicAttributes) {
dynamicAttributes.set("style", styleTemplateLiteral);
} else {
assignToObjectMap(
templateData.nodeData,
element,
"dynamicAttributes",
new Map([["style", styleTemplateLiteral]])
);
}
element.attributes.delete(name);
} else if (name[0] === "$") {
let expression: ValueTypes;
if (!value) {
// Allows shorthand #src <=> #src="src"
expression = new VariableReference(subject);
} else {
expression = Expression.fromString(value);
}
let binding: PartialBinding;
if (templateData.nodeData.get(element)?.component && subject === "data") {
if (expression instanceof ObjectLiteral) {
templateData.nodeData.get(element)!.component!.createdUsingDestructured = true;
}
binding = {
aspect: BindingAspect.Data,
expression,
element,
}
} else {
binding = {
aspect: BindingAspect.Attribute,
attribute: subject,
expression,
element,
}
}
addBinding(binding, localData, locals, templateData.bindings);
const dynamicAttributes = templateData.nodeData.get(element)?.dynamicAttributes;
if (dynamicAttributes) {
dynamicAttributes.set(subject, expression);
} else {
assignToObjectMap(
templateData.nodeData,
element,
"dynamicAttributes",
new Map([[subject, expression]])
);
}
element.attributes.delete(name);
} else if (name[0] === "@") {
// Event binding
// TODO inline function & add to component.methods
if (!value) {
throw Error(`Expected handler for event "${name}"`);
}
const methodReference = Expression.fromString(value) as VariableReference;
if (methodReference instanceof FunctionDeclaration) {
throw Error("Not implemented - anonymous function in event listener");
}
if (!(methodReference instanceof VariableReference)) {
throw Error("Expected variable reference in event callback");
}
const internal = !locals.some(local => local.isEqual(methodReference, true));
const identifier = addIdentifierToElement(element, templateData.nodeData);
const event: IEvent = {
nodeIdentifier: identifier,
element: element,
callback: methodReference,
eventName: subject,
required: true,
existsOnComponentClass: internal
}
addEvent(templateData.events, element, event, templateData.nodeData);
element.attributes.delete(name);
} else if (name[0] === "#") {
switch (subject) {
case "for":
childrenParsed = true;
parseForNode(element, templateData, templateConfig, locals, localData, nullable, multiple);
break;
case "if":
childrenParsed = true;
parseIfNode(element, templateData, templateConfig, locals, localData, multiple);
break;
case "html":
if (element.children.length > 0) throw Error(`Element with #html cannot have any children`);
if (!value) throw Error(`Expected value for #html construct`);
const htmlValue = Expression.fromString(value);
assignToObjectMap(templateData.nodeData, element, "rawInnerHTML", htmlValue);
addBinding(
{ aspect: BindingAspect.InnerHTML, element, expression: htmlValue },
localData,
locals,
templateData.bindings
);
element.attributes.delete(name);
break;
default:
throw Error(`Unknown / unsupported construct "#${subject}"`);
}
}
}
}
if (childrenParsed) {
return;
}
for (const child of element.children) {
parseNode(child, templateData, templateConfig, locals, localData, nullable, multiple);
}
} | the_stack |
import React, {useContext} from 'react';
import * as API from '../../api';
import {Conversation, Message} from '../../types';
import {mapConversationsById, mapMessagesByConversationId} from './support';
import {notification} from '../common';
import logger from '../../logger';
const defaultFilterCallback = () => true;
type Unread = {
conversations: {
open: number;
assigned: number;
priority: number;
unread: number;
unassigned: number;
closed: number;
mentioned: number;
};
inboxes: {
[id: string]: number;
};
};
export const ConversationsContext = React.createContext<{
loading?: boolean;
unread: Unread;
getValidConversations: (
filter?: (conversation: Conversation) => boolean
) => Array<Conversation>;
getValidConversationsByIds: (
conversationIds: Array<string>,
filter?: (conversation: Conversation) => boolean
) => Array<Conversation>;
fetchConversations: (
query?: Record<string, any>
) => Promise<API.ConversationsListResponse>;
fetchConversationById: (id: string) => Promise<Conversation | null>;
updateConversationById: (
id: string,
updates: Record<any, any>
) => Promise<Conversation | null>;
updateConversationAssignee: (
id: string,
userId: string | null
) => Promise<Conversation | null>;
markConversationPriority: (id: string) => Promise<Conversation | null>;
removeConversationPriority: (id: string) => Promise<Conversation | null>;
closeConversation: (id: string) => Promise<Conversation | null>;
reopenConversation: (id: string) => Promise<Conversation | null>;
archiveConversationById: (id: string) => Promise<void>;
getConversationById: (id: string | null) => Conversation | null;
getMessagesByConversationId: (id: string | null) => Array<Message>;
onNewMessage: (message: Message) => void;
onNewConversation: (conversationId: string) => void;
onConversationUpdated: (
conversationId: string,
updates: Record<string, any>
) => void;
}>({
loading: false,
unread: {
conversations: {
open: 0,
assigned: 0,
priority: 0,
unread: 0,
unassigned: 0,
closed: 0,
mentioned: 0,
},
inboxes: {},
},
getValidConversations: () => [],
getValidConversationsByIds: () => [],
fetchConversations: () =>
Promise.resolve({
data: [],
next: null,
previous: null,
limit: null,
total: null,
}),
fetchConversationById: () => Promise.resolve(null),
updateConversationById: () => Promise.resolve(null),
updateConversationAssignee: () => Promise.resolve(null),
markConversationPriority: () => Promise.resolve(null),
removeConversationPriority: () => Promise.resolve(null),
closeConversation: () => Promise.resolve(null),
reopenConversation: () => Promise.resolve(null),
archiveConversationById: () => Promise.resolve(),
getConversationById: () => null,
getMessagesByConversationId: () => [],
onNewMessage: () => {},
onNewConversation: () => {},
onConversationUpdated: () => {},
});
export const useConversations = () => useContext(ConversationsContext);
type Props = React.PropsWithChildren<{}>;
type State = {
loading: boolean;
connecting: boolean;
conversationIds: Array<string>;
conversationsById: {[id: string]: Conversation};
messagesByConversationId: {[id: string]: Array<Message>};
unread: Unread;
pagination: API.PaginationOptions;
};
export class ConversationsProvider extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
loading: true,
connecting: false,
conversationIds: [],
conversationsById: {},
messagesByConversationId: {},
unread: {
conversations: {
open: 0,
assigned: 0,
priority: 0,
unread: 0,
unassigned: 0,
closed: 0,
mentioned: 0,
},
inboxes: {},
},
pagination: {
previous: null,
next: null,
limit: undefined,
total: undefined,
},
};
}
async componentDidMount() {
await this.fetchConversations({status: 'open'});
this.setState({loading: false});
}
// TODO: distinguish between partial updates (i.e. just updating some conversation fields)
// versus full update (i.e. complete refresh of conversation/customer/messages data)?
updateConversationState = (conversation: Conversation) => {
const {id, messages = []} = conversation;
const {
conversationIds = [],
conversationsById = {},
messagesByConversationId = {},
} = this.state;
const cachedConversation = conversationsById[id] || {};
const cachedMessages = messagesByConversationId[id] || [];
this.setState({
conversationIds: [...new Set([...conversationIds, id])],
conversationsById: {
...conversationsById,
[id]: {...cachedConversation, ...conversation},
},
messagesByConversationId: {
...messagesByConversationId,
[id]:
messages.length > cachedMessages.length ? messages : cachedMessages,
},
});
};
fetchConversations = async (
query: Record<string, any> = {status: 'open'}
) => {
try {
const result = await API.fetchConversations(query);
const {data: conversations = []} = result;
const {
conversationIds = [],
conversationsById = {},
messagesByConversationId = {},
} = this.state;
this.setState({
conversationIds: [
...new Set([...conversationIds, ...conversations.map((c) => c.id)]),
],
conversationsById: {
...conversationsById,
...mapConversationsById(conversations),
},
messagesByConversationId: {
...messagesByConversationId,
...mapMessagesByConversationId(conversations),
},
});
await this.updateUnreadNotifications();
return result;
} catch (err) {
logger.error('Failed to fetch conversations:', err);
throw err;
}
};
fetchConversationById = async (conversationId: string) => {
try {
const conversation = await API.fetchConversation(conversationId);
this.updateConversationState(conversation);
await this.updateUnreadNotifications();
return conversation;
} catch (err) {
logger.error('Failed to fetch conversation:', conversationId, err);
throw err;
}
};
updateConversationById = async (
conversationId: string,
updates: Record<any, any>
) => {
try {
const conversation = await API.updateConversation(conversationId, {
conversation: updates,
});
this.updateConversationState(conversation);
return conversation;
} catch (err) {
logger.error(
'Failed to update conversation:',
conversationId,
updates,
err
);
throw err;
}
};
updateConversationAssignee = async (
conversationId: string,
userId: string | null
) => this.updateConversationById(conversationId, {assignee_id: userId});
markConversationPriority = async (conversationId: string) =>
this.updateConversationById(conversationId, {priority: 'priority'});
removeConversationPriority = async (conversationId: string) =>
this.updateConversationById(conversationId, {priority: 'not_priority'});
closeConversation = async (conversationId: string) =>
this.updateConversationById(conversationId, {status: 'closed'});
reopenConversation = async (conversationId: string) =>
this.updateConversationById(conversationId, {status: 'open'});
archiveConversationById = async (conversationId: string) => {
try {
await API.archiveConversation(conversationId);
delete this.state.conversationsById[conversationId];
} catch (err) {
logger.error('Failed to archive conversation:', conversationId, err);
throw err;
}
};
getConversationById = (
conversationId: string | null
): Conversation | null => {
if (!conversationId) {
return null;
}
const conversation = this.state.conversationsById[conversationId];
if (!conversation) {
// TODO: figure out the best way to avoid this... probably needs to be
// handled on the server where we handle emitting events via channels)
logger.debug(
`[Warning] Missing conversation in cache for id: ${conversationId}`
);
return null;
}
const messages = this.getMessagesByConversationId(conversationId);
return {...conversation, messages};
};
getValidConversationsByIds = (
conversationIds: Array<string>,
filter: (conversation: Conversation) => boolean = defaultFilterCallback
) => {
return (
conversationIds
.map((id) => this.getConversationById(id))
.filter(
(conversation: Conversation | null): conversation is Conversation =>
!!conversation
)
.map((conversation: Conversation) => {
const messages = this.getMessagesByConversationId(conversation.id);
return {...conversation, messages};
})
// TODO: figure out why some conversations get created without messages
// .filter(({messages = []}) => messages && messages.length > 0)
.sort((a: Conversation, b: Conversation) => {
const x = a.last_activity_at || a.updated_at;
const y = b.last_activity_at || b.updated_at;
return +new Date(y) - +new Date(x);
})
.filter((conversation: Conversation) => filter(conversation))
);
};
getValidConversations = (
filter: (conversation: Conversation) => boolean = defaultFilterCallback
): Array<Conversation> => {
const {conversationIds = []} = this.state;
return this.getValidConversationsByIds(conversationIds, filter);
};
getMessagesByConversationId = (conversationId: string | null) => {
if (!conversationId) {
return [];
}
const messages = this.state.messagesByConversationId[conversationId];
if (!messages) {
// TODO: figure out the best way to avoid this... probably needs to be
// handled on the server where we handle emitting events via channels)
logger.debug(
`[Warning] Missing messages in cache for conversation: ${conversationId}`
);
return [];
}
return messages;
};
addMessagesByConversationId = (
conversationId: string,
messages: Array<Message>
) => {
return {
...this.state.messagesByConversationId,
[conversationId]: [
...this.getMessagesByConversationId(conversationId),
...messages,
],
};
};
handleNewMessage = (message: Message) => {
const {id: messageId, conversation_id: conversationId} = message;
const messages = this.getMessagesByConversationId(conversationId);
// This may happen for the first message of a new conversation
const isAlreadyCached = messages.some((msg) => msg.id === messageId);
if (!isAlreadyCached) {
this.setState({
messagesByConversationId: {
...this.state.messagesByConversationId,
[conversationId]: [...messages, message],
},
});
}
this.handleNewMessageNotification(message);
this.updateUnreadNotifications();
};
handleNewMessageNotification = (message: Message) => {
const {conversation_id: conversationId, customer_id: customerId} = message;
const conversation = this.getConversationById(conversationId);
const isClosed = conversation?.status === 'closed';
const pathname = window.location.pathname || '';
const isViewing =
pathname.includes('conversations') && pathname.includes(conversationId);
if (isViewing || !customerId || isClosed) {
return;
}
const inboxId = conversation?.inbox_id ?? null;
const url = inboxId
? `/inboxes/${inboxId}/conversations/${conversationId}`
: `/conversations/all/${conversationId}`;
notification.open({
key: conversationId,
message: 'New message',
description: <a href={url}>{message.body}</a>,
});
};
updateUnreadNotifications = async () => {
// TODO: don't invoke this as aggressively
const unread = await API.countUnreadConversations();
this.setState({unread});
};
handleNewConversation = async (conversationId: string) => {
const conversation = await this.fetchConversationById(conversationId);
this.setState({
conversationsById: {
...this.state.conversationsById,
[conversationId]: conversation,
},
});
this.updateUnreadNotifications();
};
handleConversationUpdated = async (
conversationId: string,
updates: Record<any, any>
) => {
const existing = this.getConversationById(conversationId);
if (existing) {
this.setState({
conversationsById: {
...this.state.conversationsById,
[conversationId]: {
...existing,
...updates,
},
},
});
} else {
const conversation = await this.fetchConversationById(conversationId);
this.setState({
conversationsById: {
...this.state.conversationsById,
[conversationId]: conversation,
},
});
}
this.updateUnreadNotifications();
};
render() {
const {loading, unread} = this.state;
return (
<ConversationsContext.Provider
value={{
loading,
unread,
getValidConversations: this.getValidConversations,
getValidConversationsByIds: this.getValidConversationsByIds,
fetchConversations: this.fetchConversations,
fetchConversationById: this.fetchConversationById,
updateConversationById: this.updateConversationById,
updateConversationAssignee: this.updateConversationAssignee,
markConversationPriority: this.markConversationPriority,
removeConversationPriority: this.removeConversationPriority,
closeConversation: this.closeConversation,
reopenConversation: this.reopenConversation,
archiveConversationById: this.archiveConversationById,
getConversationById: this.getConversationById,
getMessagesByConversationId: this.getMessagesByConversationId,
onNewMessage: this.handleNewMessage,
onNewConversation: this.handleNewConversation,
onConversationUpdated: this.handleConversationUpdated,
}}
>
{this.props.children}
</ConversationsContext.Provider>
);
}
} | the_stack |
import { inspect } from 'util'
import { toFileKey } from './utils/id-utils'
import { enumerablizeWithPrototypeGetters } from './utils/object-utils'
import { createLayerEntitySelector } from './utils/selector-utils'
import { LayerCollectionFacade } from './layer-collection-facade'
import type { CancelToken } from '@avocode/cancel-token'
import type {
ArtboardId,
ArtboardSelector,
ComponentId,
DesignLayerSelector,
IPage,
LayerId,
PageId,
PageSelector,
} from '@opendesign/octopus-reader'
import type { ArtboardFacade } from './artboard-facade'
import type { DesignFacade } from './design-facade'
import type { FontDescriptor, LayerFacade } from './layer-facade'
import type { BitmapAssetDescriptor } from './local/local-design'
export class PageFacade {
private _pageEntity: IPage
private _designFacade: DesignFacade
/** @internal */
constructor(pageEntity: IPage, params: { designFacade: DesignFacade }) {
this._pageEntity = pageEntity
this._designFacade = params.designFacade
enumerablizeWithPrototypeGetters(this)
}
/**
* The ID of the page.
*
* Beware that this value may not be safely usable for naming files in the file system and the {@link fileKey} value should be instead.
*
* @category Identification
*/
get id(): PageId {
return this._pageEntity.id
}
/**
* The key which can be used to name files in the file system. It SHOULD be unique within a design.
*
* IDs can include characters invalid for use in file names (such as `:`).
*
* @category Identification
*
* @example
* ```typescript
* // Safe:
* page.renderToFile(`./pages/${page.fileKey}.png`)
*
* // Unsafe:
* page.renderToFile(`./pages/${page.id}.png`)
* ```
*/
get fileKey(): string {
return toFileKey(this.id)
}
/**
* The name of the artboard.
* @category Identification
*/
get name(): string | null {
return this._pageEntity.name
}
/** @internal */
toString(): string {
const artboardInfo = this.toJSON()
return `Page ${inspect(artboardInfo)}`
}
/** @internal */
[inspect.custom](): string {
return this.toString()
}
/** @internal */
toJSON(): unknown {
return { ...this }
}
/** @internal */
setPageEntity(pageEntity: IPage): void {
this._pageEntity = pageEntity
}
/**
* Returns the design object associated with the page object.
* @category Reference
* @returns A design object.
*
* @example
* ```typescript
* const design = page.getDesign()
* ```
*/
getDesign(): DesignFacade {
return this._designFacade
}
/**
* Returns whether the page content and the content of all artboards the page contains are loaded in memory from the API, a local `.octopus` file or a local cache.
*
* @category Status
* @returns Whether the page content and contents of its artboards are loaded.
*
* @example
* ```typescript
* const loaded = page.isLoaded()
* ```
*/
isLoaded(): boolean {
const artboards = this.getArtboards()
return artboards.every((artboard) => {
return artboard.isLoaded()
})
}
/** @internal */
async load(options: { cancelToken?: CancelToken | null }): Promise<void> {
const artboards = this.getArtboards()
await Promise.all(
artboards.map((artboard) => {
return artboard.load(options)
})
)
}
/**
* Returns whether the page matches the provided selector.
*
* @category Page Lookup
* @param selector The selector against which to test the page.
* @returns Whether the page matches.
*
* @example
* ```typescript
* console.log(page.name) // A
* page.matches({ name: 'A' }) // true
* ```
*/
matches(selector: PageSelector): boolean {
return this._pageEntity.matches(selector)
}
/**
* Returns a list of artboard object the page contains. These can be used to work with artboard contents.
*
* @category Artboard Lookup
* @returns A list of artboard objects.
*
* @example
* ```typescript
* const artboards = page.getArtboards()
* ```
*/
getArtboards(): Array<ArtboardFacade> {
return this._designFacade.getPageArtboards(this.id)
}
/**
* Returns a single artboard object. This can be used to work with the artboard contents. Artboards from other pages are not returned.
*
* @category Artboard Lookup
* @param artboardId An artboard ID.
* @returns An artboard object.
*
* @example
* ```typescript
* const artboard = page.getArtboardById('<ARTBOARD_ID>')
* ```
*/
getArtboardById(artboardId: ArtboardId): ArtboardFacade | null {
const artboard = this._designFacade.getArtboardById(artboardId)
if (!artboard || artboard.pageId !== this.id) {
return null
}
return artboard
}
/**
* Returns (main/master) component artboard objects the page contains. These can be used to work with artboard contents.
*
* @category Artboard Lookup
* @returns A list of artboard objects.
*
* @example
* ```typescript
* const componentArtboards = page.getComponentArtboards()
* ```
*/
getComponentArtboards(): Array<ArtboardFacade> {
return this.getArtboards().filter((artboard) => {
return artboard.isComponent()
})
}
/**
* Returns an artboard object of a specific (main/master) component. These can be used to work with the artboard contents. Component artboards from other pages are not returned.
*
* @category Artboard Lookup
* @param componentId A component ID.
* @returns An artboard object.
*
* @example
* ```typescript
* const artboard = page.getArtboardByComponentId('<COMPONENT_ID>')
* ```
*/
getArtboardByComponentId(componentId: ComponentId): ArtboardFacade | null {
const artboard = this._designFacade.getArtboardByComponentId(componentId)
if (!artboard || artboard.pageId !== this.id) {
return null
}
return artboard
}
/**
* Looks up the first artboard object the page contains matching the provided criteria.
*
* @category Artboard Lookup
* @param selector An artboard selector. All specified fields must be matched by the result.
* @returns A matched artboard object.
*
* @example
* ```typescript
* const productArtboard = page.findArtboard({ name: /Product/i })
* const productArtboard = page.findArtboard((artboard) => /Product/i.test(artboard.name))
* const oneOfArtboards123 = page.findArtboard({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findArtboard(
selector: ArtboardSelector | ((artboard: ArtboardFacade) => boolean)
): ArtboardFacade | null {
if (typeof selector === 'object') {
const selectorKeys = Object.keys(selector)
if (
selectorKeys.length === 1 &&
selectorKeys[0] === 'id' &&
typeof selector['id'] === 'string'
) {
return this.getArtboardById(selector['id'])
}
}
const matchingArtboards = this._designFacade.findArtboards(selector)
return (
matchingArtboards.find((artboard) => {
return artboard.pageId === this.id
}) || null
)
}
/**
* Looks up all artboard objects the page contains matching the provided criteria.
*
* @category Artboard Lookup
* @param selector An artboard selector. All specified fields must be matched by the results.
* @returns A list of matched artboard objects.
*
* @example
* ```typescript
* const productArtboards = page.findArtboards({ name: /Product/i })
* const productArtboards = page.findArtboards((artboard) => /Product/i.test(artboard.name))
* const artboards123 = page.findArtboards({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findArtboards(
selector: ArtboardSelector | ((artboard: ArtboardFacade) => boolean)
): Array<ArtboardFacade> {
if (typeof selector === 'object') {
const selectorKeys = Object.keys(selector)
if (
selectorKeys.length === 1 &&
selectorKeys[0] === 'id' &&
typeof selector['id'] === 'string'
) {
const artboard = this.getArtboardById(selector['id'])
return artboard ? [artboard] : []
}
}
return this._designFacade.findArtboards(selector).filter((artboard) => {
return artboard.pageId === this.id
})
}
/**
* Returns a list of bitmap assets used by layers in all artboards the page contains (optionally down to a specific nesting level).
*
* This method internally triggers loading of all artboards the page contains. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search for bitmap asset usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.includePrerendered Whether to also include "pre-rendered" bitmap assets. These assets can be produced by the rendering engine (if configured; future functionality) but are available as assets for either performance reasons or due to the some required data (such as font files) potentially not being available. By default, pre-rendered assets are included.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A list of bitmap assets.
*
* @example All bitmap assets from all artboards on the page
* ```typescript
* const bitmapAssetDescs = await page.getBitmapAssets()
* ```
*
* @example Bitmap assets excluding pre-rendered bitmaps from all artboards on the page
* ```typescript
* const bitmapAssetDescs = await page.getBitmapAssets({
* includePrerendered: false,
* })
* ```
*/
async getBitmapAssets(
options: {
depth?: number
includePrerendered?: boolean
cancelToken?: CancelToken | null
} = {}
): Promise<
Array<
BitmapAssetDescriptor & {
artboardLayerIds: Record<ArtboardId, Array<LayerId>>
}
>
> {
const { cancelToken = null, ...bitmapOptions } = options
await this.load({ cancelToken })
return this._pageEntity.getBitmapAssets(bitmapOptions)
}
/**
* Returns a list of fonts used by layers in all artboards the page contains (optionally down to a specific nesting level).
*
* This method internally triggers loading of all artboards the page contains. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search for font usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A list of fonts.
*
* @example All fonts from all artboards on the page
* ```typescript
* const fontDescs = await page.getFonts()
* ```
*/
async getFonts(
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<
Array<
FontDescriptor & { artboardLayerIds: Record<ArtboardId, Array<LayerId>> }
>
> {
const { cancelToken = null, ...fontOptions } = options
await this.load({ cancelToken })
return this._pageEntity.getFonts(fontOptions)
}
/**
* Returns a collection of all layers from all artboards within the page (optionally down to a specific nesting level).
*
* The produced collection can be queried further for narrowing down the search.
*
* This method internally triggers loading of all artboards within the page. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param options Options
* @param options.depth The maximum nesting level of layers within the artboards to include in the collection. By default, all levels are included. `0` also means "no limit"; `1` means only root layers in the artboard should be included.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A collection of flattened layers.
*
* @example All layers from all artboards on the page
* ```typescript
* const layers = await page.getFlattenedLayers()
* ```
*
* @example Root layers from all artboards on the page
* ```typescript
* const rootLayers = await page.getFlattenedLayers({ depth: 1 })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layers = await page.getFlattenedLayers({ cancelToken: token })
* ```
*/
async getFlattenedLayers(
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<LayerCollectionFacade> {
const { cancelToken = null, ...layerOptions } = options
await this.load({ cancelToken })
const layerCollection = this._pageEntity.getFlattenedLayers(layerOptions)
return new LayerCollectionFacade(layerCollection, {
designFacade: this._designFacade,
})
}
/**
* Returns the first layer object which has the specified ID within the artboards on the page.
*
* Layer IDs are unique within individual artboards but different artboards can potentially have layer ID clashes. This is the reason the method is not prefixed with "get".
*
* This method internally triggers loading of all the artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param layerId A layer ID.
* @param options Options
* @param options.depth The maximum nesting level within artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A matched layer object.
*
* @example
* ```typescript
* const layer = await page.findLayerById('<ID>')
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await page.findLayerById('<ID>', { cancelToken: token })
* ```
*/
async findLayerById(
layerId: LayerId,
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<LayerFacade | null> {
const { cancelToken = null, ...layerOptions } = options
await this.load({ cancelToken })
const layerEntity = this._pageEntity.findLayerById(layerId, layerOptions)
const layerFacade =
layerEntity && layerEntity.artboardId
? this._designFacade.getArtboardLayerFacade(
layerEntity.artboardId,
layerEntity.id
)
: null
return layerFacade
}
/**
* Returns a collection of all layer objects which have the specified ID within the artboards on the page.
*
* Layer IDs are unique within individual artboards but different artboards can potentially have layer ID clashes.
*
* This method internally triggers loading of all the artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param layerId A layer ID.
* @param options Options
* @param options.depth The maximum nesting level within artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A collection of matched layer.
*
* @example
* ```typescript
* const layers = await page.findLayersById('<ID>')
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layers = await page.findLayersById('<ID>', { cancelToken: token })
* ```
*/
async findLayersById(
layerId: LayerId,
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<LayerCollectionFacade> {
const { cancelToken = null, ...layerOptions } = options
await this.load({ cancelToken })
const layerCollection = this._pageEntity.findLayersById(
layerId,
layerOptions
)
return new LayerCollectionFacade(layerCollection, {
designFacade: this._designFacade,
})
}
/**
* Returns the first layer object from any artboard within the page (optionally down to a specific nesting level) matching the specified criteria.
*
* This method internally triggers loading of all the artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param selector A design-wide layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A matched layer object.
*
* @example Layer by name from any artboard on the page
* ```typescript
* const layer = await page.findLayer({ name: 'Share icon' })
* ```
*
* @example Layer by function selector from any artboard on the page
* ```typescript
* const shareIconLayer = await page.findLayer((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Layer by name from a certain artboad subset within the page
* ```typescript
* const layer = await page.findLayer({
* name: 'Share icon',
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await page.findLayer(
* { name: 'Share icon' },
* { cancelToken: token }
* )
* ```
*/
async findLayer(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<LayerFacade | null> {
const { cancelToken = null, ...layerOptions } = options
await this.load({ cancelToken })
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerEntity = this._pageEntity.findLayer(entitySelector, layerOptions)
const layerFacade =
layerEntity && layerEntity.artboardId
? this._designFacade.getArtboardLayerFacade(
layerEntity.artboardId,
layerEntity.id
)
: null
return layerFacade
}
/**
* Returns a collection of all layer objects from all artboards within the page (optionally down to a specific nesting level) matching the specified criteria.
*
* This method internally triggers loading of all the artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param selector A design-wide layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A collection of matched layer.
*
* @example Layers by name from all artboards on the page
* ```typescript
* const layers = await page.findLayers({ name: 'Share icon' })
* ```
*
* @example Layers by function selector from all artboards on the page
* ```typescript
* const shareIconLayers = await page.findLayers((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Invisible layers from all a certain artboard subset within the page
* ```typescript
* const layers = await page.findLayers({
* visible: false,
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await page.findLayers(
* { type: 'shapeLayer' },
* { cancelToken: token }
* )
* ```
*/
async findLayers(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: {
depth?: number
cancelToken?: CancelToken | null
} = {}
): Promise<LayerCollectionFacade> {
const { cancelToken = null, ...layerOptions } = options
await this.load({ cancelToken })
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerCollection = this._pageEntity.findLayers(
entitySelector,
layerOptions
)
return new LayerCollectionFacade(layerCollection, {
designFacade: this._designFacade,
})
}
/**
* Renders all artboards from the page as a single PNG image file.
*
* All visible layers from the artboards are included.
*
* Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x, whole page area)
* ```typescript
* await page.renderPageToFile('./rendered/page.png')
* ```
*
* @example With custom scale and crop
* ```typescript
* await page.renderPageToFile('./rendered/page.png', {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* })
* ```
*/
async renderToFile(
filePath: string,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
await this._designFacade.renderPageToFile(this.id, filePath, options)
}
} | the_stack |
namespace eui {
let UIComponentClass = "eui.UIComponent";
/**
* The TileLayout class arranges layout elements in columns and rows
* of equally-sized cells.
* The TileLayout class uses a number of properties that control orientation,
* count, size, gap and justification of the columns and the rows
* as well as element alignment within the cells.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @includeExample extension/eui/layout/TileLayoutExample.ts
* @language en_US
*/
/**
* TileLayout 类在单元格大小相等的列和行中排列布局元素。
* TileLayout 类使用许多属性来控制列和行的方向、计数、大小、间隙和两端对齐以及单元格内的元素对齐。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @includeExample extension/eui/layout/TileLayoutExample.ts
* @language zh_CN
*/
export class TileLayout extends LayoutBase {
/**
* Constructor.
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 构造函数。
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public constructor() {
super();
}
/**
* @private
* 标记horizontalGap被显式指定过
*/
private explicitHorizontalGap:number = NaN;
/**
* @private
*/
private _horizontalGap:number = 6;
/**
* Horizontal space between columns, in pixels.
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 列之间的水平空间(以像素为单位)。
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get horizontalGap():number {
return this._horizontalGap;
}
public set horizontalGap(value:number) {
value = +value;
if (value === this._horizontalGap)
return;
this.explicitHorizontalGap = value;
this._horizontalGap = value;
this.invalidateTargetLayout();
}
/**
* @private
* 标记verticalGap被显式指定过
*/
private explicitVerticalGap:number = NaN;
/**
* @private
*/
private _verticalGap:number = 6;
/**
* Vertical space between rows, in pixels.
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 行之间的垂直空间(以像素为单位)。
*
* @default 6
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get verticalGap():number {
return this._verticalGap;
}
public set verticalGap(value:number) {
value = +value;
if (value === this._verticalGap)
return;
this.explicitVerticalGap = value;
this._verticalGap = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _columnCount:number = -1;
/**
* Contain the actual column count.
*
* @default -1
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 实际列计数。
*
* @default -1
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get columnCount():number {
return this._columnCount;
}
/**
* @private
*/
private _requestedColumnCount:number = 0;
/**
* Number of columns to be displayed.
* <p>Set to 0 to allow the TileLayout to determine
* the column count automatically.</p>
* <p>If the <code>orientation</code> property is set to <code>TileOrientation.ROWS</code>,
* then setting this property has no effect
* In this case, the <code>rowCount</code> is explicitly set, and the
* container width is explicitly set. </p>
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 要显示的列数。
* <p>设置为 0 会允许 TileLayout 自动确定列计数。</p>
* <p>如果将 <code>orientation</code> 属性设置为 <code>TileOrientation.ROWS</code>,
* 则设置此属性不会产生任何效果。这种情况下,会显式设置 code>rowCount</code>,并显式设置容器宽度。</p>
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get requestedColumnCount():number {
return this._requestedColumnCount;
}
public set requestedColumnCount(value:number) {
value = +value || 0;
if (this._requestedColumnCount === value)
return;
this._requestedColumnCount = value;
this._columnCount = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _rowCount:number = -1;
/**
* The row count.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 行计数。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get rowCount():number {
return this._rowCount;
}
/**
* @private
*/
private _requestedRowCount:number = 0;
/**
* Number of rows to be displayed.
* <p>Set to 0 to remove explicit override and allow the TileLayout to determine
* the row count automatically.</p>
* <p>If the <code>orientation</code> property is set to
* <code>TileOrientation.COLUMNS</code>, setting this property has no effect.
* in this case, <code>columnCount</code> is explicitly set, and the
* container height is explicitly set.</p>
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 要显示的行数。
* <code>设置为 -1 会删除显式覆盖并允许 TileLayout 自动确定行计数。</code>
* <code>如果将 <code>orientation</code> 属性设置为 <code>TileOrientation.COLUMNS</code>,
* 则设置此属性不会产生任何效果。这种情况下,会显式设置 <code>columnCount</code>,并显式设置容器高度。</code>
*
* @default 0
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get requestedRowCount():number {
return this._requestedRowCount;
}
public set requestedRowCount(value:number) {
value = +value || 0;
if (this._requestedRowCount == value)
return;
this._requestedRowCount = value;
this._rowCount = value;
this.invalidateTargetLayout();
}
/**
* @private
* 外部显式指定的列宽
*/
private explicitColumnWidth:number = NaN;
/**
* @private
*/
private _columnWidth:number = NaN;
/**
* Contain the actual column width, in pixels.
* <p>If not explicitly set, the column width is
* determined from the width of the widest element. </p>
*
* @default NaN
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 包含实际列宽(以像素为单位)。
* <p>若未显式设置,则从根据最宽的元素的宽度确定列宽度。</p>
*
* @default NaN
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get columnWidth():number {
return this._columnWidth;
}
public set columnWidth(value:number) {
value = +value;
if (value === this._columnWidth)
return;
this.explicitColumnWidth = value;
this._columnWidth = value;
this.invalidateTargetLayout();
}
/**
* @private
* 外部显式指定的行高
*/
private explicitRowHeight:number = NaN;
/**
* @private
*/
private _rowHeight:number = NaN;
/**
* The row height, in pixels.
* <p>If not explicitly set, the row height is
* determined from the maximum of elements' height.</p>
*
* @default NaN
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 行高(以像素为单位)。
* <p>如果未显式设置,则从元素的高度的最大值确定行高度。<p>
*
* @default NaN
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get rowHeight():number {
return this._rowHeight;
}
public set rowHeight(value:number) {
value = +value;
if (value === this._rowHeight)
return;
this.explicitRowHeight = value;
this._rowHeight = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _paddingLeft:number = 0;
/**
* @copy eui.LinearLayoutBase#paddingLeft
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get paddingLeft():number {
return this._paddingLeft;
}
public set paddingLeft(value:number) {
value = +value || 0;
if (this._paddingLeft == value)
return;
this._paddingLeft = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _paddingRight:number = 0;
/**
* @copy eui.LinearLayoutBase#paddingRight
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get paddingRight():number {
return this._paddingRight;
}
public set paddingRight(value:number) {
value = +value || 0;
if (this._paddingRight === value)
return;
this._paddingRight = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _paddingTop:number = 0;
/**
* @copy eui.LinearLayoutBase#paddingTop
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get paddingTop():number {
return this._paddingTop;
}
public set paddingTop(value:number) {
value = +value || 0;
if (this._paddingTop == value)
return;
this._paddingTop = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _paddingBottom:number = 0;
/**
* @copy eui.LinearLayoutBase#paddingBottom
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public get paddingBottom():number {
return this._paddingBottom;
}
public set paddingBottom(value:number) {
value = +value || 0;
if (this._paddingBottom === value)
return;
this._paddingBottom = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _horizontalAlign:string = JustifyAlign.JUSTIFY;
/**
* Specifies how to align the elements within the cells in the horizontal direction.
* Supported values are
* HorizontalAlign.LEFT、HorizontalAlign.CENTER、
* HorizontalAlign.RIGHT、JustifyAlign.JUSTIFY。
*
* @default <code>JustifyAlign.JUSTIFY</code>
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 指定如何在水平方向上对齐单元格内的元素。支持的值有
* HorizontalAlign.LEFT、HorizontalAlign.CENTER、
* HorizontalAlign.RIGHT、JustifyAlign.JUSTIFY。
*
* @default <code>JustifyAlign.JUSTIFY</code>
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get horizontalAlign():string {
return this._horizontalAlign;
}
public set horizontalAlign(value:string) {
if (this._horizontalAlign == value)
return;
this._horizontalAlign = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _verticalAlign:string = JustifyAlign.JUSTIFY;
/**
* 指定如何在垂直方向上对齐单元格内的元素。
* 支持的值有 VerticalAlign.TOP、VerticalAlign.MIDDLE、
* VerticalAlign.BOTTOM、JustifyAlign.JUSTIFY。
* 默认值:JustifyAlign.JUSTIFY。
*
* @default <code>eui.JustifyAlign.JUSTIFY</code>
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* Specifies how to align the elements within the cells in the vertical direction.
* Supported values are
* VerticalAlign.TOP、VerticalAlign.MIDDLE、
* VerticalAlign.BOTTOM、JustifyAlign.JUSTIFY。
*
* @default <code>eui.JustifyAlign.JUSTIFY</code>
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get verticalAlign():string {
return this._verticalAlign;
}
public set verticalAlign(value:string) {
if (this._verticalAlign == value)
return;
this._verticalAlign = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _columnAlign:string = ColumnAlign.LEFT;
/**
* Specifies how to justify the fully visible columns to the container width.
*
* <p>When set to <code>ColumnAlign.LEFT</code> it turns column justification off.
* There may be partially visible columns or whitespace between the last column and
* the right edge of the container. This is the default value.</p>
*
* <p>When set to <code>ColumnAlign.JUSTIFY_USING_GAP</code> the <code>horizontalGap</code>
* actual value increases so that
* the last fully visible column right edge aligns with the container's right edge.
* In case there is only a single fully visible column, the <code>horizontalGap</code> actual value
* increases so that it pushes any partially visible column beyond the right edge
* of the container.
* Note that explicitly setting the <code>horizontalGap</code> property does not turn off
* justification. It only determines the initial gap value.
* Justification may increases it.</p>
*
* <p>When set to <code>ColumnAlign.JUSTIFY_USING_WIDTH</code> the <code>columnWidth</code>
* actual value increases so that
* the last fully visible column right edge aligns with the container's right edge.
* Note that explicitly setting the <code>columnWidth</code> property does not turn off justification.
* It only determines the initial column width value.
* Justification may increases it.</p>
*
* @default ColumnAlign.LEFT
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 指定如何将完全可见列与容器宽度对齐。
*
* <p>设置为 <code>ColumnAlign.LEFT</code> 时,它会关闭列两端对齐。
* 在容器的最后一列和右边缘之间可能存在部分可见的列或空白。这是默认值。</p>
*
* <p>设置为 <code>ColumnAlign.JUSTIFY_USING_GAP</code> 时,<code>horizontalGap</code> 的实际值将增大,
* 这样最后一个完全可见列右边缘会与容器的右边缘对齐。仅存在一个完全可见列时,
* <code>horizontalGap</code> 的实际值将增大,这样它会将任何部分可见列推到容器的右边缘之外。
* 请注意显式设置 <code>horizontalGap</code> 属性不会关闭两端对齐。它仅确定初始间隙值。两端对齐可能会增大它。</p>
*
* <p>设置为 <code>ColumnAlign.JUSTIFY_USING_WIDTH</code> 时,<code>columnWidth</code> 的实际值将增大,
* 这样最后一个完全可见列右边缘会与容器的右边缘对齐。请注意显式设置 <code>columnWidth</code> 属性不会关闭两端对齐。
* 它仅确定初始列宽度值。两端对齐可能会增大它。</p>
*
* @default ColumnAlign.LEFT
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get columnAlign():string {
return this._columnAlign;
}
public set columnAlign(value:string) {
if (this._columnAlign == value)
return;
this._columnAlign = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _rowAlign:string = RowAlign.TOP;
/**
* Specifies how to justify the fully visible rows to the container height.
*
* <p>When set to <code>RowAlign.TOP</code> it turns column justification off.
* There might be partially visible rows or whitespace between the last row and
* the bottom edge of the container. This is the default value.</p>
*
* <p>When set to <code>RowAlign.JUSTIFY_USING_GAP</code> the <code>verticalGap</code>
* actual value increases so that
* the last fully visible row bottom edge aligns with the container's bottom edge.
* In case there is only a single fully visible row, the value of <code>verticalGap</code>
* increases so that it pushes any partially visible row beyond the bottom edge
* of the container. Note that explicitly setting the <code>verticalGap</code> does not turn off
* justification, but just determines the initial gap value.
* Justification can then increases it.</p>
*
* <p>When set to <code>RowAlign.JUSTIFY_USING_HEIGHT</code> the <code>rowHeight</code>
* actual value increases so that
* the last fully visible row bottom edge aligns with the container's bottom edge. Note that
* explicitly setting the <code>rowHeight</code> does not turn off justification, but
* determines the initial row height value.
* Justification can then increase it.</p>
*
* @default RowAlign.TOP
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 指定如何将完全可见行与容器高度对齐。
*
* <p>设置为 <code>RowAlign.TOP</code> 时,它会关闭列两端对齐。
* 在容器的最后一行和底边缘之间可能存在部分可见的行或空白。这是默认值。</p>
*
* <p>设置为 <code>RowAlign.JUSTIFY_USING_GAP</code> 时,<code>verticalGap</code> 的实际值会增大,
* 这样最后一个完全可见行底边缘会与容器的底边缘对齐。仅存在一个完全可见行时,<code>verticalGap</code> 的值会增大,
* 这样它会将任何部分可见行推到容器的底边缘之外。请注意,显式设置 <code>verticalGap</code>
* 不会关闭两端对齐,而只是确定初始间隙值。两端对齐接着可以增大它。</p>
*
* <p>设置为 <code>RowAlign.JUSTIFY_USING_HEIGHT</code> 时,<code>rowHeight</code> 的实际值会增大,
* 这样最后一个完全可见行底边缘会与容器的底边缘对齐。请注意,显式设置 <code>rowHeight</code>
* 不会关闭两端对齐,而只是确定初始行高度值。两端对齐接着可以增大它。</p>
*
* @default RowAlign.TOP
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get rowAlign():string {
return this._rowAlign;
}
public set rowAlign(value:string) {
if (this._rowAlign == value)
return;
this._rowAlign = value;
this.invalidateTargetLayout();
}
/**
* @private
*/
private _orientation:string = TileOrientation.ROWS;
/**
* Specifies whether elements are arranged row by row or
* column by column.
*
* @default TileOrientation.ROWS
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language en_US
*/
/**
* 指定是逐行还是逐列排列元素。
*
* @default TileOrientation.ROWS
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @language zh_CN
*/
public get orientation():string {
return this._orientation;
}
public set orientation(value:string) {
if (this._orientation == value)
return;
this._orientation = value;
this.invalidateTargetLayout();
}
/**
* @private
* 标记目标容器的尺寸和显示列表失效
*/
private invalidateTargetLayout():void {
let target = this.$target;
if (target) {
target.invalidateSize();
target.invalidateDisplayList();
}
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public measure():void {
let target = this.$target;
if (!target)
return;
let savedColumnCount = this._columnCount;
let savedRowCount = this._rowCount;
let savedColumnWidth = this._columnWidth;
let savedRowHeight = this._rowHeight;
let measuredWidth = 0;
let measuredHeight = 0;
let values = target.$UIComponent;
this.calculateRowAndColumn(values[sys.UIKeys.explicitWidth], values[sys.UIKeys.explicitHeight]);
let columnCount = this._requestedColumnCount > 0 ? this._requestedColumnCount : this._columnCount;
let rowCount = this._requestedRowCount > 0 ? this._requestedRowCount : this._rowCount;
let horizontalGap = isNaN(this._horizontalGap) ? 0 : this._horizontalGap;
let verticalGap = isNaN(this._verticalGap) ? 0 : this._verticalGap;
if (columnCount > 0) {
measuredWidth = columnCount * (this._columnWidth + horizontalGap) - horizontalGap;
}
if (rowCount > 0) {
measuredHeight = rowCount * (this._rowHeight + verticalGap) - verticalGap;
}
let hPadding = this._paddingLeft + this._paddingRight;
let vPadding = this._paddingTop + this._paddingBottom;
target.setMeasuredSize(measuredWidth + hPadding, measuredHeight + vPadding)
this._columnCount = savedColumnCount;
this._rowCount = savedRowCount;
this._columnWidth = savedColumnWidth;
this._rowHeight = savedRowHeight;
}
/**
* @private
* 计算行和列的尺寸及数量
*/
private calculateRowAndColumn(explicitWidth:number, explicitHeight:number):void {
let target = this.$target;
let horizontalGap = isNaN(this._horizontalGap) ? 0 : this._horizontalGap;
let verticalGap = isNaN(this._verticalGap) ? 0 : this._verticalGap;
this._rowCount = this._columnCount = -1;
let numElements = target.numElements;
let count = numElements;
for (let index = 0; index < count; index++) {
let layoutElement = <UIComponent> (target.getElementAt(index));
if (layoutElement && (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout)) {
numElements--;
continue;
}
}
if (numElements == 0) {
this._rowCount = this._columnCount = 0;
return;
}
if (isNaN(this.explicitColumnWidth) || isNaN(this.explicitRowHeight))
this.updateMaxElementSize();
if (isNaN(this.explicitColumnWidth)) {
this._columnWidth = this.maxElementWidth;
}
else {
this._columnWidth = this.explicitColumnWidth;
}
if (isNaN(this.explicitRowHeight)) {
this._rowHeight = this.maxElementHeight;
}
else {
this._rowHeight = this.explicitRowHeight;
}
let itemWidth = this._columnWidth + horizontalGap;
//防止出现除数为零的情况
if (itemWidth <= 0)
itemWidth = 1;
let itemHeight = this._rowHeight + verticalGap;
if (itemHeight <= 0)
itemHeight = 1;
let orientedByColumns = (this._orientation == TileOrientation.COLUMNS);
let widthHasSet = !isNaN(explicitWidth);
let heightHasSet = !isNaN(explicitHeight);
let paddingL = this._paddingLeft;
let paddingR = this._paddingRight;
let paddingT = this._paddingTop;
let paddingB = this._paddingBottom;
if (this._requestedColumnCount > 0 || this._requestedRowCount > 0) {
if (this._requestedRowCount > 0)
this._rowCount = Math.min(this._requestedRowCount, numElements);
if (this._requestedColumnCount > 0)
this._columnCount = Math.min(this._requestedColumnCount, numElements);
}
else if (!widthHasSet && !heightHasSet) {
let side = Math.sqrt(numElements * itemWidth * itemHeight);
if (orientedByColumns) {
this._rowCount = Math.max(1, Math.round(side / itemHeight));
}
else {
this._columnCount = Math.max(1, Math.round(side / itemWidth));
}
}
else if (widthHasSet && (!heightHasSet || !orientedByColumns)) {
let targetWidth = Math.max(0,
explicitWidth - paddingL - paddingR);
this._columnCount = Math.floor((targetWidth + horizontalGap) / itemWidth);
this._columnCount = Math.max(1, Math.min(this._columnCount, numElements));
}
else {
let targetHeight = Math.max(0,
explicitHeight - paddingT - paddingB);
this._rowCount = Math.floor((targetHeight + verticalGap) / itemHeight);
this._rowCount = Math.max(1, Math.min(this._rowCount, numElements));
}
if (this._rowCount == -1)
this._rowCount = Math.max(1, Math.ceil(numElements / this._columnCount));
if (this._columnCount == -1)
this._columnCount = Math.max(1, Math.ceil(numElements / this._rowCount));
if (this._requestedColumnCount > 0 && this._requestedRowCount > 0) {
if (this._orientation == TileOrientation.ROWS)
this._rowCount = Math.max(1, Math.ceil(numElements / this._requestedColumnCount));
else
this._columnCount = Math.max(1, Math.ceil(numElements / this._requestedRowCount));
}
}
/**
* @private
* 缓存的最大子对象宽度
*/
private maxElementWidth:number = 0;
/**
* @private
* 缓存的最大子对象高度
*/
private maxElementHeight:number = 0;
/**
* @private
* 更新最大子对象尺寸
*/
private updateMaxElementSize():void {
if (!this.$target)
return;
if (this.$useVirtualLayout) {
this.maxElementWidth = Math.max(this.maxElementWidth, this.$typicalWidth);
this.maxElementHeight = Math.max(this.maxElementHeight, this.$typicalHeight);
this.doUpdateMaxElementSize(this.startIndex, this.endIndex);
}
else {
this.doUpdateMaxElementSize(0, this.$target.numElements - 1);
}
}
/**
* @private
* 更新虚拟布局的最大子对象尺寸
*/
private doUpdateMaxElementSize(startIndex:number, endIndex:number):void {
let maxElementWidth = this.maxElementWidth;
let maxElementHeight = this.maxElementHeight;
let bounds = egret.$TempRectangle;
let target = this.$target;
if ((startIndex != -1) && (endIndex != -1)) {
for (let index = startIndex; index <= endIndex; index++) {
let elt = <UIComponent> target.getVirtualElementAt(index);
if (!egret.is(elt, UIComponentClass) || !elt.$includeInLayout) {
continue;
}
elt.getPreferredBounds(bounds);
maxElementWidth = Math.max(maxElementWidth, bounds.width);
maxElementHeight = Math.max(maxElementHeight, bounds.height);
}
}
this.maxElementWidth = maxElementWidth;
this.maxElementHeight = maxElementHeight;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public clearVirtualLayoutCache():void {
super.clearVirtualLayoutCache();
this.maxElementWidth = 0;
this.maxElementHeight = 0;
}
/**
* @private
* 当前视图中的第一个元素索引
*/
private startIndex:number = -1;
/**
* @private
* 当前视图中的最后一个元素的索引
*/
private endIndex:number = -1;
/**
* @private
* 视图的第一个和最后一个元素的索引值已经计算好的标志
*/
private indexInViewCalculated:boolean = false;
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public scrollPositionChanged():void {
if (this.$useVirtualLayout) {
let changed = this.getIndexInView();
if (changed) {
this.indexInViewCalculated = true;
this.$target.invalidateDisplayList();
}
}
}
/**
* @private
* 获取视图中第一个和最后一个元素的索引,返回是否发生改变
*/
private getIndexInView():boolean {
if (!this.$target || this.$target.numElements == 0) {
this.startIndex = this.endIndex = -1;
return false;
}
let target = this.$target;
let numElements = target.numElements;
if (!this.$useVirtualLayout) {
this.startIndex = 0;
this.endIndex = numElements - 1;
return false;
}
let values = target.$UIComponent;
if (values[sys.UIKeys.width] == 0 || values[sys.UIKeys.height] == 0) {
this.startIndex = this.endIndex = -1;
return false;
}
let oldStartIndex = this.startIndex;
let oldEndIndex = this.endIndex;
let paddingL = this._paddingLeft;
let paddingT = this._paddingTop;
let horizontalGap = isNaN(this._horizontalGap) ? 0 : this._horizontalGap;
let verticalGap = isNaN(this._verticalGap) ? 0 : this._verticalGap;
if (this._orientation == TileOrientation.COLUMNS) {
let itemWidth = this._columnWidth + horizontalGap;
if (itemWidth <= 0) {
this.startIndex = 0;
this.endIndex = numElements - 1;
return false;
}
let minVisibleX = target.scrollH;
let maxVisibleX = minVisibleX + values[sys.UIKeys.width];
let startColumn = Math.floor((minVisibleX - paddingL) / itemWidth);
if (startColumn < 0)
startColumn = 0;
let endColumn = Math.ceil((maxVisibleX - paddingL) / itemWidth);
if (endColumn < 0)
endColumn = 0;
this.startIndex = Math.min(numElements - 1, Math.max(0, startColumn * this._rowCount));
this.endIndex = Math.min(numElements - 1, Math.max(0, endColumn * this._rowCount - 1));
}
else {
let itemHeight = this._rowHeight + verticalGap;
if (itemHeight <= 0) {
this.startIndex = 0;
this.endIndex = numElements - 1;
return false;
}
let minVisibleY = target.scrollV;
let maxVisibleY = minVisibleY + values[sys.UIKeys.height];
let startRow = Math.floor((minVisibleY - paddingT) / itemHeight);
if (startRow < 0)
startRow = 0;
let endRow = Math.ceil((maxVisibleY - paddingT) / itemHeight);
if (endRow < 0)
endRow = 0;
this.startIndex = Math.min(numElements - 1, Math.max(0, startRow * this._columnCount));
this.endIndex = Math.min(numElements - 1, Math.max(0, endRow * this._columnCount - 1));
}
return this.startIndex != oldStartIndex || this.endIndex != oldEndIndex;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public updateDisplayList(width:number, height:number):void {
super.updateDisplayList(width, height);
if (!this.$target)
return;
let target = this.$target;
let paddingL = this._paddingLeft;
let paddingR = this._paddingRight;
let paddingT = this._paddingTop;
let paddingB = this._paddingBottom;
if (this.indexInViewCalculated) {
this.indexInViewCalculated = false;
}
else {
this.calculateRowAndColumn(width, height);
if (this._rowCount == 0 || this._columnCount == 0) {
target.setContentSize(paddingL + paddingR, paddingT + paddingB);
return;
}
this.adjustForJustify(width, height);
this.getIndexInView();
}
if (this.$useVirtualLayout) {
this.calculateRowAndColumn(width, height);
this.adjustForJustify(width, height);
}
if (this.startIndex == -1 || this.endIndex == -1) {
target.setContentSize(0, 0);
return;
}
let endIndex = this.endIndex;
target.setVirtualElementIndicesInView(this.startIndex, endIndex);
let elt:UIComponent;
let x:number;
let y:number;
let columnIndex:number;
let rowIndex:number;
let orientedByColumns = (this._orientation == TileOrientation.COLUMNS);
let index = this.startIndex;
let horizontalGap = isNaN(this._horizontalGap) ? 0 : this._horizontalGap;
let verticalGap = isNaN(this._verticalGap) ? 0 : this._verticalGap;
let rowCount = this._rowCount;
let columnCount = this._columnCount;
let columnWidth = this._columnWidth;
let rowHeight = this._rowHeight;
for (let i = this.startIndex; i <= endIndex; i++) {
if(this.$useVirtualLayout){
elt = <UIComponent> (this.target.getVirtualElementAt(i));
}else{
elt = <UIComponent> (this.target.getElementAt(i));
}
if (!egret.is(elt, UIComponentClass) || !elt.$includeInLayout) {
continue;
}
if (orientedByColumns) {
columnIndex = Math.ceil((index + 1) / rowCount) - 1;
rowIndex = Math.ceil((index + 1) % rowCount) - 1;
if (rowIndex == -1)
rowIndex = rowCount - 1;
}
else {
columnIndex = Math.ceil((index + 1) % columnCount) - 1;
if (columnIndex == -1)
columnIndex = columnCount - 1;
rowIndex = Math.ceil((index + 1) / columnCount) - 1;
}
switch (this._horizontalAlign) {
case egret.HorizontalAlign.RIGHT:
x = width - (columnIndex + 1) * (columnWidth + horizontalGap) + horizontalGap - paddingR;
break;
case egret.HorizontalAlign.LEFT:
x = columnIndex * (columnWidth + horizontalGap) + paddingL;
break;
default:
x = columnIndex * (columnWidth + horizontalGap) + paddingL;
}
switch (this._verticalAlign) {
case egret.VerticalAlign.TOP:
y = rowIndex * (rowHeight + verticalGap) + paddingT;
break;
case egret.VerticalAlign.BOTTOM:
y = height - (rowIndex + 1) * (rowHeight + verticalGap) + verticalGap - paddingB;
break;
default:
y = rowIndex * (rowHeight + verticalGap) + paddingT;
}
this.sizeAndPositionElement(elt, x, y, columnWidth, rowHeight);
index++;
}
let hPadding = paddingL + paddingR;
let vPadding = paddingT + paddingB;
let contentWidth = (columnWidth + horizontalGap) * columnCount - horizontalGap;
let contentHeight = (rowHeight + verticalGap) * rowCount - verticalGap;
target.setContentSize(contentWidth + hPadding, contentHeight + vPadding);
}
/**
* @private
* 为单个元素布局
*/
private sizeAndPositionElement(element:UIComponent, cellX:number, cellY:number,
cellWidth:number, cellHeight:number):void {
let elementWidth = NaN;
let elementHeight = NaN;
let values = element.$UIComponent;
if (this._horizontalAlign == JustifyAlign.JUSTIFY)
elementWidth = cellWidth;
else if (!isNaN(values[sys.UIKeys.percentWidth]))
elementWidth = cellWidth * values[sys.UIKeys.percentWidth] * 0.01;
if (this._verticalAlign == JustifyAlign.JUSTIFY)
elementHeight = cellHeight;
else if (!isNaN(values[sys.UIKeys.percentHeight]))
elementHeight = cellHeight * values[sys.UIKeys.percentHeight] * 0.01;
element.setLayoutBoundsSize(Math.round(elementWidth), Math.round(elementHeight));
let x = cellX;
let bounds = egret.$TempRectangle;
element.getLayoutBounds(bounds);
switch (this._horizontalAlign) {
case egret.HorizontalAlign.RIGHT:
x += cellWidth - bounds.width;
break;
case egret.HorizontalAlign.CENTER:
x = cellX + (cellWidth - bounds.width) / 2;
break;
}
let y = cellY;
switch (this._verticalAlign) {
case egret.VerticalAlign.BOTTOM:
y += cellHeight - bounds.height;
break;
case egret.VerticalAlign.MIDDLE:
y += (cellHeight - bounds.height) / 2;
break;
}
element.setLayoutBoundsPosition(Math.round(x), Math.round(y));
}
/**
* @private
* 为两端对齐调整间隔或格子尺寸
*/
private adjustForJustify(width:number, height:number):void {
let paddingL = this._paddingLeft;
let paddingR = this._paddingRight;
let paddingT = this._paddingTop;
let paddingB = this._paddingBottom;
let targetWidth = Math.max(0, width - paddingL - paddingR);
let targetHeight = Math.max(0, height - paddingT - paddingB);
if (!isNaN(this.explicitVerticalGap))
this._verticalGap = this.explicitVerticalGap;
if (!isNaN(this.explicitHorizontalGap))
this._horizontalGap = this.explicitHorizontalGap;
this._verticalGap = isNaN(this._verticalGap) ? 0 : this._verticalGap;
this._horizontalGap = isNaN(this._horizontalGap) ? 0 : this._horizontalGap;
let offsetY = targetHeight - this._rowHeight * this._rowCount;
let offsetX = targetWidth - this._columnWidth * this._columnCount;
let gapCount;
if (offsetY > 0) {
if (this._rowAlign == RowAlign.JUSTIFY_USING_GAP) {
gapCount = Math.max(1, this._rowCount - 1);
this._verticalGap = offsetY / gapCount;
}
else if (this._rowAlign == RowAlign.JUSTIFY_USING_HEIGHT) {
if (this._rowCount > 0) {
this._rowHeight += (offsetY - (this._rowCount - 1) * this._verticalGap) / this._rowCount;
}
}
}
if (offsetX > 0) {
if (this._columnAlign == ColumnAlign.JUSTIFY_USING_GAP) {
gapCount = Math.max(1, this._columnCount - 1);
this._horizontalGap = offsetX / gapCount;
}
else if (this._columnAlign == ColumnAlign.JUSTIFY_USING_WIDTH) {
if (this._columnCount > 0) {
this._columnWidth += (offsetX - (this._columnCount - 1) * this._horizontalGap) / this._columnCount;
}
}
}
}
}
} | the_stack |
import { ArgumentOutOfRangeException } from "../Exceptions/ArgumentException";
import { ComplexPropertyCollection } from "./ComplexPropertyCollection";
import { Contact } from "../Core/ServiceObjects/Items/Contact";
import { ContactGroupSchema } from "../Core/ServiceObjects/Schemas/ContactGroupSchema";
import { EmailAddress } from "./EmailAddress";
import { EmailAddressKey } from "../Enumerations/EmailAddressKey";
import { EwsLogging } from "../Core/EwsLogging";
import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter";
import { EwsUtilities } from "../Core/EwsUtilities";
import { GroupMember } from "./GroupMember";
import { GroupMemberPropertyDefinition } from "../PropertyDefinitions/GroupMemberPropertyDefinition";
import { ICustomUpdateSerializer } from "../Interfaces/ICustomXmlUpdateSerializer";
import { ItemId } from "./ItemId";
import { MailboxType } from "../Enumerations/MailboxType";
import { ServiceValidationException } from "../Exceptions/ServiceValidationException";
import { StringHelper } from "../ExtensionMethods";
import { Strings } from "../Strings";
import { XmlElementNames } from "../Core/XmlElementNames";
import { XmlNamespace } from "../Enumerations/XmlNamespace";
import { ServiceObject } from "../Core/ServiceObjects/ServiceObject";
import { PropertyDefinition } from "../PropertyDefinitions/PropertyDefinition";
/**
* Represents a collection of members of GroupMember type.
* @sealed
*/
export class GroupMemberCollection extends ComplexPropertyCollection<GroupMember> implements ICustomUpdateSerializer {
/**
* If the collection is cleared, then store PDL members collection is updated with "SetItemField". If the collection is not cleared, then store PDL members collection is updated with "AppendToItemField".
*
*/
private collectionIsCleared: boolean = false;
/**
* Initializes a new instance of the class.
*
*/
constructor() {
super();
}
/**
* Adds a member to the collection.
*
* @param {GroupMember} member The member to add.
*/
Add(member: GroupMember): void {
EwsUtilities.ValidateParam(member, "member");
EwsLogging.Assert(
member.Key == null,
"GroupMemberCollection.Add",
"member.Key is not null.");
EwsLogging.Assert(
!this.Contains(member),
"GroupMemberCollection.Add",
"The member is already in the collection");
this.InternalAdd(member);
}
/**
* Adds a member that is linked to a specific e-mail address of a contact.
*
* @param {Contact} contact The contact to link to.
* @param {EmailAddressKey} emailAddressKey The contact's e-mail address to link to.
*/
AddContactEmailAddress(contact: Contact, emailAddressKey: EmailAddressKey): void {
this.Add(new GroupMember(contact, emailAddressKey));
}
/**
* Adds a member linked to a Contact Group.
*
* @param {ItemId} contactGroupId The Id of the contact group.
*/
AddContactGroup(contactGroupId: ItemId): void {
this.Add(new GroupMember(contactGroupId));
}
/**
* Adds a member linked to an Active Directory contact.
*
* @param {string} smtpAddress The SMTP address of the Active Directory contact.
*/
AddDirectoryContact(smtpAddress: string): void;
/**
* Adds a member linked to an Active Directory contact.
*
* @param {string} address The address of the Active Directory contact.
* @param {string} routingType The routing type of the address.
*/
AddDirectoryContact(address: string, routingType: string): void;
AddDirectoryContact(address: string, routingType: string = EmailAddress.SmtpRoutingType): void {
this.Add(new GroupMember(address, routingType, MailboxType.Contact));
}
/**
* Adds a member linked to a mail-enabled Public Folder.
*
* @param {string} smtpAddress The SMTP address of the mail-enabled Public Folder.
*/
AddDirectoryPublicFolder(smtpAddress: string): void {
this.Add(new GroupMember(smtpAddress, EmailAddress.SmtpRoutingType, MailboxType.PublicFolder));
}
/**
* Adds a member linked to an Active Directory user.
*
* @param {string} smtpAddress The SMTP address of the member.
*/
AddDirectoryUser(smtpAddress: string): void;
/**
* Adds a member linked to an Active Directory user.
*
* @param {string} address The address of the member.
* @param {string} routingType The routing type of the address.
*/
AddDirectoryUser(address: string, routingType: string): void;
AddDirectoryUser(address: string, routingType: string = EmailAddress.SmtpRoutingType): void {
this.Add(new GroupMember(address, routingType, MailboxType.Mailbox));
}
/**
* Adds a one-off member.
*
* @param {string} displayName The display name of the member.
* @param {string} smtpAddress The SMTP address of the member.
*/
AddOneOff(displayName: string, smtpAddress: string): void;
/**
* Adds a one-off member.
*
* @param {string} displayName The display name of the member.
* @param {string} address The address of the member.
* @param {string} routingType The routing type of the address.
*/
AddOneOff(displayName: string, address: string, routingType: string): void;
AddOneOff(displayName: string, address: string, routingType: string = EmailAddress.SmtpRoutingType): void {
this.Add(new GroupMember(displayName, address, routingType));
}
/**
* Adds a member linked to a contact's first available e-mail address.
*
* @param {ItemId} contactId The Id of the contact.
*/
AddPersonalContact(contactId: ItemId): void;
/**
* Adds a member linked to a specific contact's e-mail address.
*
* @param {ItemId} contactId The Id of the contact.
* @param {string} addressToLink The contact's address to link to.
*/
AddPersonalContact(contactId: ItemId, addressToLink: string): void;
AddPersonalContact(contactId: ItemId, addressToLink: string = null): void {
this.Add(new GroupMember(contactId, addressToLink));
}
/**
* Adds a member linked to a Public Group.
*
* @param {string} smtpAddress The SMTP address of the Public Group.
*/
AddPublicGroup(smtpAddress: string): void {
this.Add(new GroupMember(smtpAddress, EmailAddress.SmtpRoutingType, MailboxType.PublicGroup));
}
/**
* Adds multiple members to the collection.
*
* @param {GroupMember[]} members The members to add.
*/
AddRange(members: GroupMember[] /*IEnumerable<T>*/): void {
EwsUtilities.ValidateParam(members, "members");
for (let member of members) {
this.Add(member);
}
}
/**
* Clears the collection.
*/
Clear(): void {
// mark the whole collection for deletion
this.InternalClear();
this.collectionIsCleared = true;
}
/**
* @internal Clears the change log.
*
*/
ClearChangeLog(): void {
super.ClearChangeLog();
this.collectionIsCleared = false;
}
/**
* @internal Creates a GroupMember object from an XML element name.
*
* @param {string} xmlElementName The XML element name from which to create the e-mail address.
* @return {GroupMember} An GroupMember object.
*/
CreateComplexProperty(xmlElementName: string): GroupMember {
return new GroupMember();
}
/**
* @internal Creates the default complex property.
*
* @return {GroupMember} An GroupMember object.
*/
CreateDefaultComplexProperty(): GroupMember {
return new GroupMember();
}
/**
* Finds the member with the specified key in the collection.
* Members that have not yet been saved do not have a key.
*
* @param {} key The key of the member to find.
* @return {} The member with the specified key.
*/
Find(key: string): GroupMember {
EwsUtilities.ValidateParam(key, "key");
for (let item of this.Items) {
if (item.Key == key) {
return item;
}
}
return null;
}
/**
* @internal Retrieves the XML element name corresponding to the provided GroupMember object.
*
* @param {GroupMember} member The GroupMember object from which to determine the XML element name.
* @return {string} The XML element name corresponding to the provided GroupMember object.
*/
GetCollectionItemXmlElementName(member: GroupMember): string {
return XmlElementNames.Member;
}
/**
* @internal Validates this instance.
*/
InternalValidate(): void {
super.InternalValidate();
for (let groupMember of this.ModifiedItems) {
if (StringHelper.IsNullOrEmpty(groupMember.Key)) {
throw new ServiceValidationException(Strings.ContactGroupMemberCannotBeUpdatedWithoutBeingLoadedFirst);
}
}
}
/**
* Removes a member from the collection.
*
* @param {GroupMember} member The member to remove.
* @return {boolean} True if the group member was successfully removed from the collection, false otherwise.
*/
Remove(member: GroupMember): boolean {
return this.InternalRemove(member);
}
/**
* Removes a member at the specified index.
*
* @param {number} index The index of the member to remove.
*/
RemoveAt(index: number): void {
if (index < 0 || index >= this.Count) {
throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange);
}
this.InternalRemoveAt(index);
}
/**
* Delete the whole members collection.
*
* @param {EwsServiceXmlWriter} writer Xml writer.
*/
private WriteDeleteMembersCollectionToXml(writer: EwsServiceXmlWriter): void {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DeleteItemField);
ContactGroupSchema.Members.WriteToXml(writer);
writer.WriteEndElement();
}
/**
* Generate XML to delete individual members.
*
* @param {EwsServiceXmlWriter} writer Xml writer.
* @param {GroupMember[]} members Members to delete.
*/
private WriteDeleteMembersToXml(writer: EwsServiceXmlWriter, members: GroupMember[] /* List<GroupMember>*/): void {
if (members.length != 0) {
let memberPropDef: GroupMemberPropertyDefinition = new GroupMemberPropertyDefinition();
for (let member of members) {
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DeleteItemField);
memberPropDef.Key = member.Key;
memberPropDef.WriteToXml(writer);
writer.WriteEndElement(); // DeleteItemField
}
}
}
/**
* Generate XML to Set or Append members. When members are set, the existing PDL member collection is cleared On append members are added to the PDL existing members collection.
*
* @param {EwsServiceXmlWriter} writer Xml writer.
* @param {GroupMember[]} members Members to set or append.
* @param {boolean} setMode True - set members, false - append members.
*/
private WriteSetOrAppendMembersToXml(writer: EwsServiceXmlWriter, members: GroupMember[] /*List<GroupMember>*/, setMode: boolean): void {
if (members.length != 0) {
writer.WriteStartElement(XmlNamespace.Types, setMode ? XmlElementNames.SetItemField : XmlElementNames.AppendToItemField);
ContactGroupSchema.Members.WriteToXml(writer);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.DistributionList);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Members);
for (let member of members) {
member.WriteToXml(writer, XmlElementNames.Member);
}
writer.WriteEndElement(); // Members
writer.WriteEndElement(); // Group
writer.WriteEndElement(); // setMode ? SetItemField : AppendItemField
}
}
//#region ICustomUpdateSerializer
/**
* @internal Writes the deletion update to XML.
* ICustomUpdateSerializer.WriteDeleteUpdateToXml
*
* @param {EwsServiceXmlWriter} writer The writer.
* @param {ServiceObject} ewsObject The ews object.
* @return {boolean} True if property generated serialization.
*/
WriteDeleteUpdateToXml(writer: EwsServiceXmlWriter, ewsObject: ServiceObject): boolean {
return false;
}
/**
* @internal Writes the update to XML.
* ICustomUpdateSerializer.WriteSetUpdateToXml
*
* @param {EwsServiceXmlWriter} writer The writer.
* @param {ServiceObject} ewsObject The ews object.
* @param {PropertyDefinition} propertyDefinition Property definition.
* @return {boolean} True if property generated serialization.
*/
WriteSetUpdateToXml(
writer: EwsServiceXmlWriter,
ewsObject: ServiceObject,
propertyDefinition: PropertyDefinition): boolean {
if (this.collectionIsCleared) {
if (this.AddedItems.length == 0) {
// Delete the whole members collection
this.WriteDeleteMembersCollectionToXml(writer);
}
else {
// The collection is cleared, so Set
this.WriteSetOrAppendMembersToXml(writer, this.AddedItems, true);
}
}
else {
// The collection is not cleared, i.e. dl.Members.Clear() is not called.
// Append AddedItems.
this.WriteSetOrAppendMembersToXml(writer, this.AddedItems, false);
// Since member replacement is not supported by server
// Delete old ModifiedItems, then recreate new instead.
this.WriteDeleteMembersToXml(writer, this.ModifiedItems);
this.WriteSetOrAppendMembersToXml(writer, this.ModifiedItems, false);
// Delete RemovedItems.
this.WriteDeleteMembersToXml(writer, this.RemovedItems);
}
return true;
}
//#endregion
} | the_stack |
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {ApiService} from '../../../core/services';
import {Dataset} from '../models/catalog-dataset';
import {ObjectSchemaMap} from '../models/catalog-objectschema';
import {Cluster} from '../../../admin/models/catalog-cluster';
import {User} from '../../../admin/models/catalog-user';
import {Category} from '../../../admin/models/catalog-category';
import {Type} from '../../../admin/models/catalog-type';
import {System} from '../../../admin/models/catalog-system';
import {DatasetWithAttributes} from '../models/catalog-dataset-attributes';
import {PagedData} from '../models/catalog-paged-data';
import {Page} from '../models/catalog-list-page';
import {StorageTypeAttribute} from '../models/catalog-dataset-storagetype-attribute';
import {Zone} from '../../../admin/models/catalog-zone';
@Injectable()
export class CatalogService {
private datasetPostAttributesURL: any;
private actionDetailsURL: string;
private actionDBDetailsURL: string;
private actionBackupDetailsURL: string;
private dataSetsURL: string;
private objectListURL: string;
private dataSetsPendingURL: string;
private dataSetsDeletedURL: string;
private dataSetURL: string;
private dataSetPendingURL: string;
private datasetsPrefixUrl: string;
private sampleDataURL: string;
private objectDetailsURL: string;
private clustersURL: string;
private zonesURL: string;
private usersURL: string;
private storageCategoriesURL: string;
private storageTypesURL: string;
private storageSystemsURL: string;
private accessControlURL: string;
private teradataAccessControlURL: string;
private storageTypeURLForCategory: string;
private storageTypeURLForCategoryName: string;
private storageSystemURLForTypeName: string;
private storageSystemsURLForType: string;
private containersURLForSystem: string;
private storageSystemURL: string;
private containersURL: string;
private objectsForContainerAndSystem: string;
private storageTypeAttributesForType: string;
private userNameURL: string;
private datasetPostURL: string;
private objectsPostURL: string;
public clustersByNameURL: string;
public deleteDatasetURL: string;
private deleteTypeURL: string;
private deleteSystemURL: string;
private enableTypeURL: string;
private enableSystemURL: string;
public serverWithPort: string;
private clusterPostURL: string;
private zonePostURL: string;
private insertUserURL: string;
private deleteClusterURL: string;
private deleteZoneURL: string;
private deleteUserURL: string;
private deleteCategoryURL: string;
private enableClusterURL: string;
private enableZoneURL: string;
private enableUserURL: string;
private enableCategoryURL: string;
private userPostURL: string;
private categoryPostURL: string;
private typePostURL: string;
private typeAttributePostURL: string;
private systemPostURL: string;
private schemaByObjectIdURL: string;
private systemAttributesByNameURL: string;
private typeAttributesByURL: string;
private typeAttributesAtSystemLevelByURL: string;
private dataSetDetails: any;
private objectDetails: any;
private clustersByIdURL: string;
private pagedObjectData = new PagedData<ObjectSchemaMap>();
private pagedData = new PagedData<Dataset>();
constructor(private api: ApiService) {
this.serverWithPort = api.serverWithPort;
const urlGenerator = (url) => {
return `${this.serverWithPort}${url}`;
};
this.dataSetsURL = urlGenerator('/dataSet/dataSetsBySystem/$typeName$/$systemName$');
this.objectListURL = urlGenerator('/objectschema/objects/$systemName$/$containerName$');
this.typeAttributesByURL = urlGenerator('/storageType/storageAttributeKey/$storageTypeId$');
this.typeAttributesAtSystemLevelByURL = urlGenerator('/storageType/storageAttributeKey/$storageTypeId$/$isSystemLevel$');
this.dataSetsPendingURL = this.serverWithPort + '/dataSet/dataSetsBySystemPending/$typeName$/$systemName$';
this.dataSetsDeletedURL = this.serverWithPort + '/dataSet/dataSetsBySystemDeleted/$typeName$/$systemName$';
this.dataSetURL = this.serverWithPort + '/dataSet/dataSet/$datasetId$';
this.dataSetPendingURL = this.serverWithPort + '/dataSet/dataSetPending/$datasetId$';
this.datasetsPrefixUrl = this.serverWithPort + '/dataSet/detailedDataSets/';
this.sampleDataURL = this.serverWithPort + '/dataSet/sampleData/$dataset$/$objectId$';
this.objectDetailsURL = this.serverWithPort + '/objectschema/schema/$objectId$';
this.clustersURL = this.serverWithPort + '/cluster/clusters';
this.zonesURL = this.serverWithPort + '/zone/zones';
this.usersURL = this.serverWithPort + '/user/users';
this.storageCategoriesURL = this.serverWithPort + '/storage/storages';
this.storageTypesURL = this.serverWithPort + '/storageType/storageTypes';
this.storageSystemsURL = this.serverWithPort + '/storageSystem/storageSystems';
this.accessControlURL = this.serverWithPort + '/ranger/policiesByLocation';
this.teradataAccessControlURL = this.serverWithPort + '/teradata/policy/$storageSystemId$/$databasename$';
this.storageTypeURLForCategory = this.serverWithPort + '/storageType/storageTypeByStorageId/$storageId$';
this.storageTypeURLForCategoryName = this.serverWithPort + '/storageType/storageTypeByStorageName/$storageName$';
this.storageSystemURLForTypeName = this.serverWithPort + '/storageSystem/storageSystemByTypeName/$storageTypeName$';
this.storageSystemsURLForType = this.serverWithPort + '/storageSystem/storageSystemByType/$storageTypeId$';
this.containersURLForSystem = this.serverWithPort + '/objectschema/containers/$storageSystemId$';
this.containersURL = this.serverWithPort + '/objectschema/containers/';
this.objectsForContainerAndSystem = this.serverWithPort + '/objectschema/objectnames/$containerName$/$storageSystemId$';
this.storageTypeAttributesForType = this.serverWithPort + '/storageType/storageAttributeKey/$storageTypeId$/$isStorageSystemLevel$';
this.userNameURL = this.serverWithPort + '/user/userByName/$username$';
this.datasetPostURL = this.serverWithPort + '/dataSet/dataSet';
this.objectsPostURL = this.serverWithPort + '/objectschema/schema';
this.clusterPostURL = this.serverWithPort + '/cluster/cluster';
this.zonePostURL = this.serverWithPort + '/zone/zone';
this.insertUserURL = this.serverWithPort + '/user/user';
this.userPostURL = this.serverWithPort + '/user/user';
this.categoryPostURL = this.serverWithPort + '/storage/storage';
this.typePostURL = this.serverWithPort + '/storageType/storageType';
this.typeAttributePostURL = this.serverWithPort + '/storageType/storageTypeAttribute';
this.systemPostURL = this.serverWithPort + '/storageSystem/storageSystem';
this.clustersByNameURL = this.serverWithPort + '/cluster/clusterByName/$clusterName$';
this.clustersByIdURL = this.serverWithPort + '/cluster/cluster/$clusterId$';
this.deleteDatasetURL = this.serverWithPort + '/dataSet/dataSet/$datasetId$';
this.deleteClusterURL = this.serverWithPort + '/cluster/dcluster/$clusterId$';
this.deleteZoneURL = this.serverWithPort + '/zone/dzone/$zoneId$';
this.deleteUserURL = this.serverWithPort + '/user/duser/$userId$';
this.deleteCategoryURL = this.serverWithPort + '/storage/dstorage/$categoryId$';
this.deleteTypeURL = this.serverWithPort + '/storageType/dstorageType/$typeId$';
this.deleteSystemURL = this.serverWithPort + '/storageSystem/dstorageSystem/$storageSystemId$';
this.enableClusterURL = this.serverWithPort + '/cluster/ecluster/$clusterId$';
this.enableZoneURL = this.serverWithPort + '/zone/ezone/$zoneId$';
this.enableCategoryURL = this.serverWithPort + '/storage/estorage/$categoryId$';
this.enableUserURL = this.serverWithPort + '/user/euser/$userId$';
this.enableTypeURL = this.serverWithPort + '/storageType/estorageType/$typeId$';
this.enableSystemURL = this.serverWithPort + '/storageSystem/estorageSystem/$storageSystemId$';
this.schemaByObjectIdURL = this.serverWithPort + '/objectschema/schema/$objectId$';
this.systemAttributesByNameURL = this.serverWithPort + '/storageSystem/storageSystemAttributesByName/$systemName$';
this.datasetPostAttributesURL = this.serverWithPort + '/dataSet/dataSetWithObjectAttributes';
this.storageSystemURL = this.serverWithPort + '/storageSystem/storageSystem/$storageSystemId$';
this.actionDBDetailsURL = `${ this.actionDetailsURL }/database/$DB$/$action$`;
this.actionBackupDetailsURL = `${ this.actionDetailsURL }/backup/$backup$/$action$`;
}
/**
* This function gets all the storage categories which are supported.
*/
getStorageCategories() {
return this.api.get<Array<any>>(this.storageCategoriesURL);
}
/**
* This function gets all the storage types which are supported.
*/
getStorageTypes() {
return this.api.get<Array<any>>(this.storageTypesURL);
}
getStorageTypesForCategory(storageCategoryId: string) {
return this.api.get<Array<any>>(this.storageTypeURLForCategory.replace('$storageId$', storageCategoryId));
}
getStorageTypeAttributes(storageTypeId: string, isStorageSystemLevel: string) {
return this.api.get<Array<any>>(this.storageTypeAttributesForType.replace('$storageTypeId$', storageTypeId).replace('$isStorageSystemLevel$', isStorageSystemLevel));
}
getStorageSystemsForType(storageTypeId: string) {
return this.api.get<Array<any>>(this.storageSystemsURLForType.replace('$storageTypeId$', storageTypeId));
}
getSystemAttributes(storageSystemName: string) {
return this.api.get<Array<any>>(this.systemAttributesByNameURL.replace('$systemName$', storageSystemName));
}
getUserByName(username: string) {
return this.api.get<Array<any>>(this.userNameURL.replace('$username$', username));
}
getContainersForSystem(storageSystemId: string) {
return this.api.get<Array<any>>(this.containersURLForSystem.replace('$storageSystemId$', storageSystemId));
}
getContainers() {
return this.api.get<Array<any>>(this.containersURL);
}
getObjectsForContainerAndSystem(containerName: string, storageSystemId: string) {
return this.api.get<Array<any>>(this.objectsForContainerAndSystem.replace('$storageSystemId$', storageSystemId).replace('$containerName$', containerName));
}
/**
* This function gets all the storage categories which are supported.
*/
getStorageSystems() {
return this.api.get<Array<any>>(this.storageSystemsURL);
}
getStorageSystem(storageSystemId: string) {
return this.api.get<any>(this.storageSystemURL.replace('$storageSystemId$', storageSystemId));
}
getAccessControl(location: string, type: string, clusterId: number) {
return this.api.get<Array<any>>(this.accessControlURL + '?location=' + location + '&type=' + type + '&cluster=' + clusterId);
}
getTeradataPolicy(storageSystemId: string, databasename: string) {
return this.api.get<Array<any>>(this.teradataAccessControlURL.replace('$storageSystemId$', storageSystemId).replace('$databasename$', databasename));
}
getPendingDataSetList(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<Array<any>> {
const pageNumber = page.pageNumber.toString();
const size = page.size.toString();
return this.api.get<Array<any>>(this.dataSetsPendingURL.replace('$systemName$', systemName)
.replace('$typeName$', typeName).concat('?datasetStr=').concat(datasetStr).concat('&page=').concat(pageNumber).concat('&size=').concat(size));
}
getPendingDataSetListPageable(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<PagedData<Dataset>> {
return Observable.create(observer => {
this.getPendingDataSetList(datasetStr, systemName, typeName, page)
.subscribe(data => {
this.dataSetDetails = data;
this.pagedData = this.getPagedData(page);
observer.next(this.pagedData);
observer.complete();
}, error => {
this.dataSetDetails = [];
});
});
}
getDeletedDataSetList(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<Array<any>> {
const pageNumber = page.pageNumber.toString();
const size = page.size.toString();
return this.api.get<Array<any>>(this.dataSetsDeletedURL.replace('$systemName$', systemName).replace('$typeName$', typeName).concat('?datasetStr=').concat(datasetStr).concat('&page=').concat(pageNumber).concat('&size=').concat(size));
}
getDeletedDataSetListPageable(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<PagedData<Dataset>> {
return Observable.create(observer => {
this.getDeletedDataSetList(datasetStr, systemName, typeName, page)
.subscribe(data => {
this.dataSetDetails = data;
this.pagedData = this.getPagedData(page);
observer.next(this.pagedData);
observer.complete();
}, error => {
this.dataSetDetails = [];
});
});
}
/**
* This function returns list of all datasets for storage system ID
*/
getDataSetList(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<Array<any>> {
const pageNumber = page.pageNumber.toString();
const size = page.size.toString();
return this.api.get<Array<any>>(this.dataSetsURL.replace('$systemName$', systemName).replace('$typeName$', typeName)
.concat('?datasetStr=').concat(datasetStr).concat('&page=').concat(pageNumber).concat('&size=').concat(size));
}
getDataSetListPageable(datasetStr: string, systemName: string, typeName: string, page: Page): Observable<PagedData<Dataset>> {
return Observable.create(observer => {
this.getDataSetList(datasetStr, systemName, typeName, page)
.subscribe(data => {
this.dataSetDetails = data;
this.pagedData = this.getPagedData(page);
observer.next(this.pagedData);
observer.complete();
});
});
// return Observable.of(this.pagedData);
}
private getPagedData(page: Page): PagedData<Dataset> {
const pagedData = new PagedData<Dataset>();
page.totalElements = this.dataSetDetails.totalElements;
page.totalPages = this.dataSetDetails.totalPages;
const numberOfElements = this.dataSetDetails.numberOfElements;
for (let i = 0; i < numberOfElements; i++) {
const jsonObj = this.dataSetDetails.content[i];
const employee = new Dataset(jsonObj.storageDataSetName, jsonObj.storageDataSetId, jsonObj.storageSystemName, jsonObj.attributesPresent, jsonObj.objectSchemaMapId, jsonObj.storageDataSetAliasName, jsonObj.storageDataSetDescription, jsonObj.createdUser, jsonObj.updatedUser, jsonObj.isGimelCompatible, jsonObj.zoneName, jsonObj.isAccessControlled, jsonObj.teradataPolicies, jsonObj.derivedPolicies, jsonObj.isReadCompatible);
pagedData.data.push(employee);
}
pagedData.page = page;
return pagedData;
}
getObjectList(systemName: string, containerName: string, page: Page): Observable<Array<any>> {
const pageNumber = page.pageNumber.toString();
const size = page.size.toString();
return this.api.get<Array<any>>(this.objectListURL.replace('$systemName$', systemName).replace('$containerName$', containerName).concat('?page=').concat(pageNumber).concat('&size=').concat(size));
}
private getPagedObjectData(page: Page): PagedData<ObjectSchemaMap> {
const pagedData = new PagedData<ObjectSchemaMap>();
page.totalElements = this.objectDetails.totalElements;
page.totalPages = this.objectDetails.totalPages;
const numberOfElements = this.objectDetails.numberOfElements;
for (let i = 0; i < numberOfElements; i++) {
const jsonObj = this.objectDetails.content[i];
const employee = new ObjectSchemaMap(jsonObj.objectId, jsonObj.objectName, jsonObj.containerName, jsonObj.storageSystemId, jsonObj.createdUser);
pagedData.data.push(employee);
}
pagedData.page = page;
return pagedData;
}
getObjectListPageable(systemName: string, containerName: string, page: Page): Observable<PagedData<ObjectSchemaMap>> {
return Observable.create(observer => {
this.getObjectList(systemName, containerName, page).subscribe(data => {
this.objectDetails = data;
this.pagedObjectData = this.getPagedObjectData(page);
observer.next(this.pagedObjectData);
observer.complete();
});
});
}
getTypeList(storageName: string) {
return this.api.get<Array<any>>(this.storageTypeURLForCategoryName.replace('$storageName$', storageName));
}
getSystemList(storageTypeName: string) {
return this.api.get<Array<any>>(this.storageSystemURLForTypeName.replace('$storageTypeName$', storageTypeName));
}
getSchemaDetails(objectId: string): Observable<any> {
return this.api.get<any>(this.schemaByObjectIdURL.replace('$objectId$', objectId));
}
/**
* This function invokes UDC get Dataset API and returns current Dataset Details
* @param datasetId
*/
getDatasetPendingDetails(datasetId: string): Observable<any> {
return this.api.get<any>(this.dataSetPendingURL.replace('$datasetId$', datasetId));
}
getDatasetsWithPrefix(prefix: string): Observable<any> {
return this.api.get<any>(this.datasetsPrefixUrl.concat('?prefixString=').concat(prefix));
}
getSampleData(dataset: string, objectSchemaMapId: string): Observable<any> {
return this.api.get<any>(this.sampleDataURL.replace('$dataset$', dataset).replace('$objectId$', objectSchemaMapId));
}
getObjectDetails(objectId: string): Observable<any> {
return this.api.get<any>(this.objectDetailsURL.replace('$objectId$', objectId));
}
getClusterList(): Observable<Array<any>> {
return this.api.get<Array<any>>(this.clustersURL);
}
getZonesList(): Observable<Array<any>> {
return this.api.get<Array<any>>(this.zonesURL);
}
getUsersList(): Observable<Array<any>> {
return this.api.get<Array<any>>(this.usersURL);
}
getClusterById(clusterId: number): Observable<any> {
return this.api.get<any>(this.clustersByIdURL.replace('$clusterId$', clusterId.toString()));
}
getTypeAttributes(storageTypeId: string): Observable<Array<any>> {
return this.api.get<Array<any>>(this.typeAttributesByURL.replace('$storageTypeId$', storageTypeId));
}
getTypeAttributesAtSystemLevel(storageTypeId: string, isSystemLevel: string): Observable<Array<any>> {
return this.api.get<Array<any>>(this.typeAttributesAtSystemLevelByURL.replace('$storageTypeId$', storageTypeId).replace('$isSystemLevel$', isSystemLevel));
}
insertCluster(cluster: Cluster) {
return this.api.post<any>(this.clusterPostURL, cluster);
}
insertZone(zone: Zone) {
return this.api.post<any>(this.zonePostURL, zone);
}
insertDataset(payload: Dataset) {
return this.api.post<any>(this.datasetPostURL, payload);
}
insertUser(user: User) {
return this.api.post<any>(this.insertUserURL, user);
}
insertCategory(category: Category) {
return this.api.post<any>(this.categoryPostURL, category);
}
insertType(type: Type) {
return this.api.post<any>(this.typePostURL, type);
}
insertTypeAttribute(typeAttribute: StorageTypeAttribute) {
return this.api.post<any>(this.typeAttributePostURL, typeAttribute);
}
insertSystem(system: System) {
return this.api.post<any>(this.systemPostURL, system);
}
insertObject(objectSchema: ObjectSchemaMap) {
return this.api.post<any>(this.objectsPostURL, objectSchema);
}
updateDataset(payload: Dataset) {
return this.api.put<any>(this.datasetPostURL, payload);
}
updateObject(payload: ObjectSchemaMap) {
return this.api.put<any>(this.objectsPostURL, payload);
}
updateDatasetWithAttributes(payload: DatasetWithAttributes) {
return this.api.put<any>(this.datasetPostAttributesURL, payload);
}
updateCluster(cluster: Cluster) {
return this.api.put<any>(this.clusterPostURL, cluster);
}
updateZone(zone: Zone) {
return this.api.put<any>(this.zonePostURL, zone);
}
updateUser(user: User) {
return this.api.put<any>(this.userPostURL, user);
}
updateCategory(category: Category) {
return this.api.put<any>(this.categoryPostURL, category);
}
updateType(type: Type) {
return this.api.put<any>(this.typePostURL, type);
}
updateSystem(system: System) {
return this.api.put<any>(this.systemPostURL, system);
}
deleteDataset(datasetId: string) {
return this.api.delete<any>(this.deleteDatasetURL.replace('$datasetId$', datasetId));
}
deleteCluster(clusterId: string) {
return this.api.delete<any>(this.deleteClusterURL.replace('$clusterId$', clusterId));
}
deleteZone(zoneId: string) {
return this.api.delete<any>(this.deleteZoneURL.replace('$zoneId$', zoneId));
}
deleteCategory(categoryId: string) {
return this.api.delete<any>(this.deleteCategoryURL.replace('$categoryId$', categoryId));
}
deleteUser(userId: string) {
return this.api.delete<any>(this.deleteUserURL.replace('$userId$', userId));
}
deleteType(typeId: string) {
return this.api.delete<any>(this.deleteTypeURL.replace('$typeId$', typeId));
}
deleteSystem(systemId: string) {
return this.api.delete<any>(this.deleteSystemURL.replace('$storageSystemId$', systemId));
}
enableCluster(clusterId: string) {
return this.api.putWithoutPayload<any>(this.enableClusterURL.replace('$clusterId$', clusterId));
}
enableZone(zoneId: string) {
return this.api.putWithoutPayload<any>(this.enableZoneURL.replace('$zoneId$', zoneId));
}
enableUser(userId: string) {
return this.api.putWithoutPayload<any>(this.enableUserURL.replace('$userId$', userId));
}
enableCategory(categoryId: string) {
return this.api.putWithoutPayload<any>(this.enableCategoryURL.replace('$categoryId$', categoryId));
}
enableType(typeId: string) {
return this.api.putWithoutPayload<any>(this.enableTypeURL.replace('$typeId$', typeId));
}
enableSystem(systemId: string) {
return this.api.putWithoutPayload<any>(this.enableSystemURL.replace('$storageSystemId$', systemId));
}
} | the_stack |
import { TupleArbitrary } from '../../../../src/arbitrary/_internals/TupleArbitrary';
import { NextValue } from '../../../../src/check/arbitrary/definition/NextValue';
import { FakeIntegerArbitrary, fakeNextArbitrary } from '../__test-helpers__/NextArbitraryHelpers';
import { fakeRandom } from '../__test-helpers__/RandomHelpers';
import { cloneMethod, hasCloneMethod } from '../../../../src/check/symbols';
import { Stream } from '../../../../src/stream/Stream';
import {
assertProduceValuesShrinkableWithoutContext,
assertProduceCorrectValues,
assertShrinkProducesSameValueWithoutInitialContext,
assertShrinkProducesStrictlySmallerValue,
assertProduceSameValueGivenSameSeed,
} from '../__test-helpers__/NextArbitraryAssertions';
import { buildNextShrinkTree, renderTree, walkTree } from '../__test-helpers__/ShrinkTree';
import { NextArbitrary } from '../../../../src/check/arbitrary/definition/NextArbitrary';
import { Random } from '../../../../src/random/generator/Random';
describe('TupleArbitrary', () => {
describe('generate', () => {
it('should merge results coming from underlyings and call them with the exact same inputs as the received ones', () => {
// Arrange
const expectedBiasFactor = 48;
const vA = Symbol();
const vB = Symbol();
const vC = Symbol();
const { instance: instanceA, generate: generateA } = fakeNextArbitrary<symbol>();
const { instance: instanceB, generate: generateB } = fakeNextArbitrary<symbol>();
const { instance: instanceC, generate: generateC } = fakeNextArbitrary<symbol>();
generateA.mockReturnValueOnce(new NextValue(vA, undefined));
generateB.mockReturnValueOnce(new NextValue(vB, undefined));
generateC.mockReturnValueOnce(new NextValue(vC, undefined));
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([instanceA, instanceB, instanceC]);
const g = arb.generate(mrng, expectedBiasFactor);
// Assert
expect(g.value).toEqual([vA, vB, vC]);
expect(generateA).toHaveBeenCalledWith(mrng, expectedBiasFactor);
expect(generateB).toHaveBeenCalledWith(mrng, expectedBiasFactor);
expect(generateC).toHaveBeenCalledWith(mrng, expectedBiasFactor);
});
it('should produce a cloneable instance if provided one cloneable underlying', () => {
// Arrange
const { instance: fakeArbitraryNotCloneableA, generate: generateA } = fakeNextArbitrary<string[]>();
const { instance: fakeArbitraryCloneableB, generate: generateB } = fakeNextArbitrary<string[]>();
generateA.mockReturnValue(new NextValue([], undefined));
generateB.mockReturnValue(new NextValue(Object.defineProperty([], cloneMethod, { value: jest.fn() }), undefined));
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([fakeArbitraryNotCloneableA, fakeArbitraryCloneableB]);
const g = arb.generate(mrng, undefined);
// Assert
expect(g.hasToBeCloned).toBe(true);
expect(hasCloneMethod(g.value)).toBe(true);
});
it('should not produce a cloneable instance if no cloneable underlyings', () => {
// Arrange
const { instance: fakeArbitraryNotCloneableA, generate: generateA } = fakeNextArbitrary<string[]>();
const { instance: fakeArbitraryNotCloneableB, generate: generateB } = fakeNextArbitrary<string[]>();
generateA.mockReturnValue(new NextValue([], undefined));
generateB.mockReturnValue(new NextValue([], undefined));
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([fakeArbitraryNotCloneableA, fakeArbitraryNotCloneableB]);
const g = arb.generate(mrng, undefined);
// Assert
expect(g.hasToBeCloned).toBe(false);
expect(hasCloneMethod(g.value)).toBe(false);
});
it('should not clone cloneable on generate', () => {
// Arrange
const { instance: fakeArbitraryNotCloneableA, generate: generateA } = fakeNextArbitrary<string[]>();
const { instance: fakeArbitraryCloneableB, generate: generateB } = fakeNextArbitrary<string[]>();
const cloneMethodImpl = jest.fn();
generateA.mockReturnValue(new NextValue([], undefined));
generateB.mockReturnValue(
new NextValue(Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }), undefined)
);
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([fakeArbitraryNotCloneableA, fakeArbitraryCloneableB]);
arb.generate(mrng, undefined);
// Assert
expect(cloneMethodImpl).not.toHaveBeenCalled();
});
});
describe('canShrinkWithoutContext', () => {
it.each`
canA | canB | canC
${false} | ${false} | ${false}
${false} | ${true} | ${true}
${true} | ${false} | ${true}
${true} | ${true} | ${false}
${true} | ${true} | ${true}
`(
'should merge results coming from underlyings for canShrinkWithoutContext if received array has the right size',
({ canA, canB, canC }) => {
// Arrange
const vA = Symbol();
const vB = Symbol();
const vC = Symbol();
const { instance: instanceA, canShrinkWithoutContext: canShrinkWithoutContextA } = fakeNextArbitrary<symbol>();
const { instance: instanceB, canShrinkWithoutContext: canShrinkWithoutContextB } = fakeNextArbitrary<symbol>();
const { instance: instanceC, canShrinkWithoutContext: canShrinkWithoutContextC } = fakeNextArbitrary<symbol>();
canShrinkWithoutContextA.mockReturnValueOnce(canA);
canShrinkWithoutContextB.mockReturnValueOnce(canB);
canShrinkWithoutContextC.mockReturnValueOnce(canC);
// Act
const arb = new TupleArbitrary([instanceA, instanceB, instanceC]);
const out = arb.canShrinkWithoutContext([vA, vB, vC]);
// Assert
expect(out).toBe(canA && canB && canC);
expect(canShrinkWithoutContextA).toHaveBeenCalledWith(vA);
if (canA) expect(canShrinkWithoutContextB).toHaveBeenCalledWith(vB);
else expect(canShrinkWithoutContextB).not.toHaveBeenCalled();
if (canA && canB) expect(canShrinkWithoutContextC).toHaveBeenCalledWith(vC);
else expect(canShrinkWithoutContextC).not.toHaveBeenCalled();
}
);
it('should not call underlyings on canShrinkWithoutContext if size is invalid', () => {
// Arrange
const { instance: instanceA, canShrinkWithoutContext: canShrinkWithoutContextA } = fakeNextArbitrary<symbol>();
const { instance: instanceB, canShrinkWithoutContext: canShrinkWithoutContextB } = fakeNextArbitrary<symbol>();
const { instance: instanceC, canShrinkWithoutContext: canShrinkWithoutContextC } = fakeNextArbitrary<symbol>();
// Act
const arb = new TupleArbitrary([instanceA, instanceB, instanceC]);
const out = arb.canShrinkWithoutContext([Symbol(), Symbol(), Symbol(), Symbol()]);
// Assert
expect(out).toBe(false);
expect(canShrinkWithoutContextA).not.toHaveBeenCalled();
expect(canShrinkWithoutContextB).not.toHaveBeenCalled();
expect(canShrinkWithoutContextC).not.toHaveBeenCalled();
});
});
describe('shrink', () => {
it('should call back arbitraries on shrink with the initially returned contextq', () => {
// Arrange
const expectedBiasFactor = 48;
const vA = Symbol();
const vB = Symbol();
const vC = Symbol();
const contextA = Symbol();
const contextB = Symbol();
const contextC = Symbol();
const { instance: instanceA, generate: generateA, shrink: shrinkA } = fakeNextArbitrary<symbol>();
const { instance: instanceB, generate: generateB, shrink: shrinkB } = fakeNextArbitrary<symbol>();
const { instance: instanceC, generate: generateC, shrink: shrinkC } = fakeNextArbitrary<symbol>();
generateA.mockReturnValueOnce(new NextValue(vA, contextA));
generateB.mockReturnValueOnce(new NextValue(vB, contextB));
generateC.mockReturnValueOnce(new NextValue(vC, contextC));
const shrinkA1 = Symbol();
const shrinkA2 = Symbol();
const shrinkB1 = Symbol();
const shrinkC1 = Symbol();
const shrinkC2 = Symbol();
const shrinkC3 = Symbol();
shrinkA.mockReturnValueOnce(
Stream.of(new NextValue(shrinkA1 as symbol, undefined), new NextValue(shrinkA2, undefined))
);
shrinkB.mockReturnValueOnce(Stream.of(new NextValue(shrinkB1 as symbol, undefined)));
shrinkC.mockReturnValueOnce(
Stream.of(
new NextValue(shrinkC1 as symbol, undefined),
new NextValue(shrinkC2, undefined),
new NextValue(shrinkC3, undefined)
)
);
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([instanceA, instanceB, instanceC]);
const g = arb.generate(mrng, expectedBiasFactor);
const shrinks = [...arb.shrink(g.value, g.context)];
// Assert
expect(shrinks).toHaveLength(2 /* A */ + 1 /* B */ + 3 /* C */);
expect(shrinks.map((v) => v.value)).toEqual([
[shrinkA1, vB, vC],
[shrinkA2, vB, vC],
[vA, shrinkB1, vC],
[vA, vB, shrinkC1],
[vA, vB, shrinkC2],
[vA, vB, shrinkC3],
]);
expect(shrinkA).toHaveBeenCalledWith(vA, contextA);
expect(shrinkB).toHaveBeenCalledWith(vB, contextB);
expect(shrinkC).toHaveBeenCalledWith(vC, contextC);
});
it('should clone cloneable on shrink', () => {
// Arrange
const {
instance: fakeArbitraryNotCloneableA,
generate: generateA,
shrink: shrinkA,
} = fakeNextArbitrary<string[]>();
const { instance: fakeArbitraryCloneableB, generate: generateB, shrink: shrinkB } = fakeNextArbitrary<string[]>();
const {
instance: fakeArbitraryNotCloneableC,
generate: generateC,
shrink: shrinkC,
} = fakeNextArbitrary<string[]>();
const cloneMethodImpl = jest
.fn()
.mockImplementation(() => Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }));
generateA.mockReturnValue(new NextValue([], undefined));
shrinkA.mockReturnValue(Stream.of(new NextValue([], undefined), new NextValue([], undefined)));
generateB.mockReturnValue(
new NextValue(Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }), undefined)
);
shrinkB.mockReturnValue(
Stream.of(
new NextValue(Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }), undefined),
new NextValue(Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }), undefined),
new NextValue(Object.defineProperty([], cloneMethod, { value: cloneMethodImpl }), undefined)
)
);
generateC.mockReturnValue(new NextValue([], undefined));
shrinkC.mockReturnValue(
Stream.of(
new NextValue([], undefined),
new NextValue([], undefined),
new NextValue([], undefined),
new NextValue([], undefined)
)
);
const { instance: mrng } = fakeRandom();
// Act
const arb = new TupleArbitrary([fakeArbitraryNotCloneableA, fakeArbitraryCloneableB, fakeArbitraryNotCloneableC]);
const g = arb.generate(mrng, undefined);
expect(cloneMethodImpl).not.toHaveBeenCalled();
const shrinkLazy = arb.shrink(g.value, g.context);
expect(cloneMethodImpl).not.toHaveBeenCalled();
const shrinks = [...shrinkLazy];
// Assert
expect(shrinks).toHaveLength(2 /* A */ + 3 /* B */ + 4 /* C */);
expect(cloneMethodImpl).toHaveBeenCalledTimes(shrinks.length);
});
});
});
describe('TupleArbitrary (integration)', () => {
const isCorrect = (value: number[]) => Array.isArray(value) && value.length === 3;
const isStrictlySmaller = (t1: number[], t2: number[]) => t1.findIndex((v, idx) => v < t2[idx]) !== -1;
const tupleBuilder = () =>
new TupleArbitrary([new FakeIntegerArbitrary(), new FakeIntegerArbitrary(), new FakeIntegerArbitrary()]);
it('should produce the same values given the same seed', () => {
assertProduceSameValueGivenSameSeed(tupleBuilder);
});
it('should only produce correct values', () => {
assertProduceCorrectValues(tupleBuilder, isCorrect);
});
it('should produce values seen as shrinkable without any context', () => {
assertProduceValuesShrinkableWithoutContext(tupleBuilder);
});
it('should be able to shrink to the same values without initial context (if underlyings do)', () => {
assertShrinkProducesSameValueWithoutInitialContext(tupleBuilder);
});
it('should preserve strictly smaller ordering in shrink (if underlyings do)', () => {
assertShrinkProducesStrictlySmallerValue(tupleBuilder, isStrictlySmaller);
});
it('should produce the right shrinking tree', () => {
// Arrange
const arb = new TupleArbitrary([new FirstArbitrary(), new SecondArbitrary()]);
const { instance: mrng } = fakeRandom();
// Act
const g = arb.generate(mrng, undefined);
const renderedTree = renderTree(buildNextShrinkTree(arb, g)).join('\n');
// Assert
expect(g.hasToBeCloned).toBe(false);
expect(g.value).toBe(g.value_);
expect(g.value).toEqual([expectedFirst, expectedSecond]);
expect(renderedTree).toMatchInlineSnapshot(`
"[4,97]
├> [2,97]
| ├> [0,97]
| | ├> [0,99]
| | └> [0,98]
| | └> [0,100]
| ├> [2,99]
| | └> [0,99]
| └> [2,98]
| ├> [0,98]
| | └> [0,100]
| └> [2,100]
| └> [0,100]
├> [3,97]
| ├> [0,97]
| | ├> [0,99]
| | └> [0,98]
| | └> [0,100]
| ├> [1,97]
| | ├> [1,99]
| | └> [1,98]
| | └> [1,100]
| ├> [3,99]
| | ├> [0,99]
| | └> [1,99]
| └> [3,98]
| ├> [0,98]
| | └> [0,100]
| ├> [1,98]
| | └> [1,100]
| └> [3,100]
| ├> [0,100]
| └> [1,100]
├> [4,99]
| ├> [2,99]
| | └> [0,99]
| └> [3,99]
| ├> [0,99]
| └> [1,99]
└> [4,98]
├> [2,98]
| ├> [0,98]
| | └> [0,100]
| └> [2,100]
| └> [0,100]
├> [3,98]
| ├> [0,98]
| | └> [0,100]
| ├> [1,98]
| | └> [1,100]
| └> [3,100]
| ├> [0,100]
| └> [1,100]
└> [4,100]
├> [2,100]
| └> [0,100]
└> [3,100]
├> [0,100]
└> [1,100]"
`);
});
it('should not re-use twice the same instance of cloneable', () => {
// Arrange
const alreadySeenCloneable = new Set<unknown>();
const arb = new TupleArbitrary([new FirstArbitrary(), new CloneableArbitrary(), new SecondArbitrary()]);
const { instance: mrng } = fakeRandom();
// Act
const g = arb.generate(mrng, undefined);
const treeA = buildNextShrinkTree(arb, g);
const treeB = buildNextShrinkTree(arb, g);
// Assert
walkTree(treeA, ([_first, cloneable, _second]) => {
expect(alreadySeenCloneable.has(cloneable)).toBe(false);
alreadySeenCloneable.add(cloneable);
});
walkTree(treeB, ([_first, cloneable, _second]) => {
expect(alreadySeenCloneable.has(cloneable)).toBe(false);
alreadySeenCloneable.add(cloneable);
});
});
});
// Helpers
const expectedFirst = 4;
const expectedSecond = 97;
class FirstArbitrary extends NextArbitrary<number> {
generate(_mrng: Random): NextValue<number> {
return new NextValue(expectedFirst, { step: 2 });
}
canShrinkWithoutContext(_value: unknown): _value is number {
throw new Error('No call expected in that scenario');
}
shrink(value: number, context?: unknown): Stream<NextValue<number>> {
if (typeof context !== 'object' || context === null || !('step' in context)) {
throw new Error('Invalid context for FirstArbitrary');
}
if (value <= 0) {
return Stream.nil();
}
const currentStep = (context as { step: number }).step;
const nextStep = currentStep + 1;
return Stream.of(
...(value - currentStep >= 0 ? [new NextValue(value - currentStep, { step: nextStep })] : []),
...(value - currentStep + 1 >= 0 ? [new NextValue(value - currentStep + 1, { step: nextStep })] : [])
);
}
}
class SecondArbitrary extends NextArbitrary<number> {
generate(_mrng: Random): NextValue<number> {
return new NextValue(expectedSecond, { step: 2 });
}
canShrinkWithoutContext(_value: unknown): _value is number {
throw new Error('No call expected in that scenario');
}
shrink(value: number, context?: unknown): Stream<NextValue<number>> {
if (typeof context !== 'object' || context === null || !('step' in context)) {
throw new Error('Invalid context for SecondArbitrary');
}
if (value >= 100) {
return Stream.nil();
}
const currentStep = (context as { step: number }).step;
const nextStep = currentStep + 1;
return Stream.of(
...(value + currentStep <= 100 ? [new NextValue(value + currentStep, { step: nextStep })] : []),
...(value + currentStep - 1 <= 100 ? [new NextValue(value + currentStep - 1, { step: nextStep })] : [])
);
}
}
class CloneableArbitrary extends NextArbitrary<number[]> {
private instance() {
return Object.defineProperty([], cloneMethod, { value: () => this.instance() });
}
generate(_mrng: Random): NextValue<number[]> {
return new NextValue(this.instance(), { shrunkOnce: false });
}
canShrinkWithoutContext(_value: unknown): _value is number[] {
throw new Error('No call expected in that scenario');
}
shrink(value: number[], context?: unknown): Stream<NextValue<number[]>> {
if (typeof context !== 'object' || context === null || !('shrunkOnce' in context)) {
throw new Error('Invalid context for CloneableArbitrary');
}
const safeContext = context as { shrunkOnce: boolean };
if (safeContext.shrunkOnce) {
return Stream.nil();
}
return Stream.of(new NextValue(this.instance(), { shrunkOnce: true }));
}
} | the_stack |
import * as tfc from '@tensorflow/tfjs-core';
import {scalar} from '@tensorflow/tfjs-core';
import * as tensorflow from '../data/compiled_api';
import {deregisterOp, registerOp} from '../operations/custom_op/register';
import {GraphNode} from '../operations/types';
import {GraphModel, loadGraphModel} from './graph_model';
const HOST = 'http://example.org';
const MODEL_URL = `${HOST}/model.json`;
const RELATIVE_MODEL_URL = '/path/model.pb';
let model: GraphModel;
const bias = tfc.tensor1d([1], 'int32');
const alpha = tfc.scalar(1, 'int32');
const weightsManifest: tfc.io.WeightsManifestEntry[] =
[{'name': 'Const', 'dtype': 'int32', 'shape': [1]}];
const SIMPLE_MODEL: tensorflow.IGraphDef = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: tensorflow.DataType.DT_INT32,
},
shape: {shape: {dim: [{size: -1}, {size: 1}]}}
}
},
{
name: 'Const',
op: 'Const',
attr: {
dtype: {type: tensorflow.DataType.DT_INT32},
value: {
tensor: {
dtype: tensorflow.DataType.DT_INT32,
tensorShape: {dim: [{size: 1}]},
}
},
index: {i: 0},
length: {i: 4}
}
},
{name: 'Add1', op: 'Add', input: ['Input', 'Const'], attr: {}},
{name: 'Add', op: 'Add', input: ['Add1', 'Const'], attr: {}}
],
versions: {producer: 1.0, minConsumer: 3}
};
const PRELU_MODEL: tensorflow.IGraphDef = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: tensorflow.DataType.DT_FLOAT,
},
shape: {shape: {dim: []}}
}
},
{
name: 'Const',
op: 'Const',
attr: {
dtype: {type: tensorflow.DataType.DT_INT32},
value: {
tensor: {
dtype: tensorflow.DataType.DT_INT32,
tensorShape: {dim: []},
}
},
index: {i: 0},
length: {i: 4}
}
},
{name: 'Relu', op: 'Relu', input: ['Input'], attr: {}},
{name: 'Neg', op: 'Neg', input: ['Input'], attr: {}},
{name: 'Relu2', op: 'Relu', input: ['Neg'], attr: {}},
{name: 'Mul', op: 'Mul', input: ['Const', 'Relu2'], attr: {}},
{name: 'Add', op: 'Add', input: ['Relu', 'Mul'], attr: {}}
],
versions: {producer: 1.0, minConsumer: 3}
};
const CONTROL_FLOW_MODEL: tensorflow.IGraphDef = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: tensorflow.DataType.DT_INT32,
},
shape: {shape: {dim: [{size: -1}, {size: 1}]}}
}
},
{name: 'Enter', op: 'Enter', attr: {}, input: ['Input']},
],
versions: {producer: 1.0, minConsumer: 3}
};
const DYNAMIC_SHAPE_MODEL: tensorflow.IGraphDef = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: tensorflow.DataType.DT_BOOL,
},
shape: {shape: {dim: [{size: -1}, {size: 1}]}}
}
},
{name: 'Where', op: 'Where', attr: {}, input: ['Input']}
],
versions: {producer: 1.0, minConsumer: 3}
};
const SIMPLE_HTTP_MODEL_LOADER = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: bias.dataSync()
};
}
};
const PRELU_HTTP_MODEL_LOADER = {
load: async () => {
return {
modelTopology: PRELU_MODEL,
weightSpecs: weightsManifest,
weightData: alpha.dataSync()
};
}
};
const CUSTOM_OP_MODEL: tensorflow.IGraphDef = {
node: [
{
name: 'Input',
op: 'Placeholder',
attr: {
dtype: {
type: tensorflow.DataType.DT_INT32,
},
shape: {shape: {dim: [{size: -1}, {size: 1}]}}
}
},
{
name: 'Const',
op: 'Const',
attr: {
dtype: {type: tensorflow.DataType.DT_INT32},
value: {
tensor: {
dtype: tensorflow.DataType.DT_INT32,
tensorShape: {dim: [{size: 1}]},
}
},
index: {i: 0},
length: {i: 4}
}
},
{name: 'Add1', op: 'Add', input: ['Input', 'Const'], attr: {}},
{name: 'CustomOp', op: 'CustomOp', input: ['Add1'], attr: {}}
],
versions: {producer: 1.0, minConsumer: 3}
};
const CUSTOM_HTTP_MODEL_LOADER = {
load: async () => {
return {
modelTopology: CUSTOM_OP_MODEL,
weightSpecs: weightsManifest,
weightData: bias.dataSync()
};
}
};
const CONTROL_FLOW_HTTP_MODEL_LOADER = {
load: async () => {
return {
modelTopology: CONTROL_FLOW_MODEL,
weightSpecs: weightsManifest,
weightData: bias.dataSync()
};
}
};
describe('loadGraphModel', () => {
it('Pass a custom io handler', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => {
return {
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
};
}
};
const model = await loadGraphModel(customLoader);
expect(model).toBeDefined();
const bias = model.weights['Const'][0];
expect(bias.dtype).toBe('int32');
expect(bias.dataSync()).toEqual(new Int32Array([5]));
});
it('Expect an error when moderUrl is null', async () => {
let errorMsg = 'no error';
try {
await loadGraphModel(null);
} catch (err) {
errorMsg = err.message;
}
expect(errorMsg).toMatch(/modelUrl in loadGraphModel\(\) cannot be null/);
});
});
describe('Model', () => {
beforeEach(() => {
model = new GraphModel(MODEL_URL);
});
describe('custom model', () => {
beforeEach(() => {
spyOn(tfc.io, 'getLoadHandlers').and.returnValue([
CUSTOM_HTTP_MODEL_LOADER
]);
registerOp('CustomOp', (nodeValue: GraphNode) => {
const x = nodeValue.inputs[0];
return [tfc.add(x, scalar(1, 'int32'))];
});
});
afterEach(() => deregisterOp('CustomOp'));
it('load', async () => {
const loaded = await model.load();
expect(loaded).toBe(true);
});
describe('predict', () => {
it('should generate the output for single tensor', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.predict(input);
expect((output as tfc.Tensor).dataSync()[0]).toEqual(3);
});
});
});
describe('simple model', () => {
beforeEach(() => {
spyOn(tfc.io, 'getLoadHandlers').and.returnValue([
SIMPLE_HTTP_MODEL_LOADER
]);
spyOn(tfc.io, 'browserHTTPRequest')
.and.returnValue(SIMPLE_HTTP_MODEL_LOADER);
});
it('load', async () => {
const loaded = await model.load();
expect(loaded).toBe(true);
});
describe('predict', () => {
it('should generate the output for single tensor', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.predict(input);
expect((output as tfc.Tensor).dataSync()[0]).toEqual(3);
});
it('should generate the output for tensor array', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.predict([input]);
expect((output as tfc.Tensor).dataSync()[0]).toEqual(3);
});
it('should generate the output for tensor map', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.predict({'Input': input});
expect((output as tfc.Tensor).dataSync()[0]).toEqual(3);
});
it('should throw error if input size mismatch', async () => {
await model.load();
const input = tfc.tensor1d([1], 'int32');
expect(() => model.predict([input, input])).toThrow();
});
it('should throw exception if inputs shapes do not match', () => {
const input = tfc.tensor2d([1, 1], [1, 2], 'int32');
expect(() => model.predict([input])).toThrow();
});
it('should throw exception if inputs dtype does not match graph', () => {
const input = tfc.tensor1d([1], 'float32');
expect(() => model.predict([input])).toThrow();
});
});
describe('execute', () => {
it('should generate the default output', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.execute({'Input': input});
expect((output as tfc.Tensor).dataSync()[0]).toEqual(3);
});
it('should generate the output array', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.execute({'Input': input}, ['Add', 'Const']);
expect(Array.isArray(output)).toBeTruthy();
expect((output as tfc.Tensor[])[0].dataSync()[0]).toEqual(3);
expect((output as tfc.Tensor[])[1].dataSync()[0]).toEqual(1);
});
it('should throw exception if inputs shapes do not match', () => {
const input = tfc.tensor2d([1, 1], [1, 2], 'int32');
expect(() => model.execute([input])).toThrow();
});
it('should throw exception if inputs dtype does not match graph', () => {
const input = tfc.tensor2d([1, 1], [2, 1], 'float32');
expect(() => model.predict([input])).toThrow();
});
it('should throw error if input size mismatch', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.execute([input, input])).toThrow();
});
it('should allow feed intermediate node', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const output = model.execute({'Add1': input}) as tfc.Tensor;
tfc.test_util.expectArraysClose(await output.data(), [2, 2]);
});
});
describe('dispose', () => {
it('should dispose the weights', async () => {
const numOfTensors = tfc.memory().numTensors;
model = new GraphModel(MODEL_URL);
await model.load();
model.dispose();
expect(tfc.memory().numTensors).toEqual(numOfTensors);
});
});
describe('getVersion', () => {
it('should return the version info from the tf model', async () => {
await model.load();
expect(model.modelVersion).toEqual('1.3');
});
});
describe('relative path', () => {
beforeEach(() => {
model = new GraphModel(RELATIVE_MODEL_URL);
});
it('load', async () => {
const loaded = await model.load();
expect(loaded).toBe(true);
});
});
it('should loadGraphModel', async () => {
const model = await loadGraphModel(MODEL_URL);
expect(model).not.toBeUndefined();
});
it('should loadGraphModel with request options', async () => {
const model = await loadGraphModel(
MODEL_URL, {requestInit: {credentials: 'include'}});
expect(tfc.io.browserHTTPRequest).toHaveBeenCalledWith(MODEL_URL, {
requestInit: {credentials: 'include'}
});
expect(model).not.toBeUndefined();
});
it('should call loadGraphModel for TfHub Module', async () => {
const url = `${HOST}/model/1`;
const model = await loadGraphModel(url, {fromTFHub: true});
expect(model).toBeDefined();
});
describe('InferenceModel interface', () => {
it('should expose inputs', async () => {
await model.load();
expect(model.inputs).toEqual([
{name: 'Input', shape: [-1, 1], dtype: 'int32'}
]);
});
it('should expose outputs', async () => {
await model.load();
expect(model.outputs).toEqual([
{name: 'Add', shape: undefined, dtype: undefined}
]);
});
});
});
describe('prelu op model', () => {
beforeEach(() => {
spyOn(tfc.io, 'getLoadHandlers').and.returnValue([
PRELU_HTTP_MODEL_LOADER
]);
spyOn(tfc.io, 'browserHTTPRequest')
.and.returnValue(PRELU_HTTP_MODEL_LOADER);
});
it('fusePrelu should call model rewrite method', async () => {
await model.load();
const originalResult = model.predict(tfc.scalar(1)) as tfc.Tensor;
model.fusePrelu();
expect(Object.keys(model.weights)).toContain('Const_neg');
expect(model.outputNodes[0]).toEqual('Add_Prelu');
const result = model.predict(tfc.scalar(1)) as tfc.Tensor;
tfc.test_util.expectArraysClose(
result.dataSync(), originalResult.dataSync());
});
});
describe('control flow model', () => {
beforeEach(() => {
spyOn(tfc.io, 'getLoadHandlers').and.returnValue([
CONTROL_FLOW_HTTP_MODEL_LOADER
]);
spyOn(tfc.io, 'browserHTTPRequest')
.and.returnValue(CONTROL_FLOW_HTTP_MODEL_LOADER);
});
it('should throw error if call predict directly', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.predict([input])).toThrow();
});
it('should throw error if call execute directly', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.predict([input])).toThrow();
});
it('should be success if call executeAsync', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const res = await model.executeAsync([input]);
expect(res).not.toBeNull();
});
it('should allow feed intermediate node with executeAsync', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const res = await model.executeAsync({Enter: input});
expect(res).not.toBeNull();
});
});
const DYNAMIC_HTTP_MODEL_LOADER = {
load: async () => {
return {
modelTopology: DYNAMIC_SHAPE_MODEL,
weightSpecs: weightsManifest,
weightData: bias.dataSync()
};
}
};
describe('dynamic shape model', () => {
beforeEach(() => {
spyOn(tfc.io, 'getLoadHandlers').and.returnValue([
DYNAMIC_HTTP_MODEL_LOADER
]);
spyOn(tfc.io, 'browserHTTPRequest')
.and.returnValue(DYNAMIC_HTTP_MODEL_LOADER);
});
it('should throw error if call predict directly', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.predict([input])).toThrow();
});
it('should throw error if call execute directly', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.execute([input])).toThrow();
});
it('should be success if call executeAsync', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'bool');
const res = await model.executeAsync([input]);
expect(res).not.toBeNull();
});
it('should allow feed intermediate node with executeAsync', async () => {
await model.load();
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
const res = await model.executeAsync({Where: input});
expect(res).not.toBeNull();
});
});
});
describe('Graph execution gives actionable errors', () => {
it('executeAsync warns when there are no dynamic ops', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
await model.executeAsync(input);
expect(console.warn).toHaveBeenCalledTimes(1);
expect(console.warn)
.toHaveBeenCalledWith(
'This model execution did not contain any nodes with control ' +
'flow or dynamic output shapes. You can use model.execute() ' +
'instead.');
});
it('executeAsync does not warn when there are dynamic ops', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: CONTROL_FLOW_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
await model.executeAsync(input);
expect(console.warn).toHaveBeenCalledTimes(0);
});
it('executeAsync warns when the subgraph has no dynamic ops', async () => {
const graphDef: tensorflow.IGraphDef = {
node: [
{name: 'input', op: 'Placeholder'},
{name: 'intermediate', op: 'Enter', input: ['input']},
{name: 'intermediate2', op: 'Sqrt', input: ['intermediate']},
{name: 'output', op: 'Square', input: ['intermediate2']},
],
versions: {producer: 1.0, minConsumer: 3}
};
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: graphDef,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
await model.executeAsync({'intermediate2': input});
expect(console.warn).toHaveBeenCalledTimes(1);
expect(console.warn)
.toHaveBeenCalledWith(
'This model execution did not contain any nodes with control ' +
'flow or dynamic output shapes. You can use model.execute() ' +
'instead.');
});
it('executeAsync works when the subgraph has no unknown ops', async () => {
const graphDef: tensorflow.IGraphDef = {
node: [
{name: 'input', op: 'Placeholder'},
{name: 'intermediate', op: 'Unknown', input: ['input']},
{name: 'intermediate2', op: 'Sqrt', input: ['intermediate']},
{name: 'output', op: 'Square', input: ['intermediate2']},
],
versions: {producer: 1.0, minConsumer: 3}
};
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: graphDef,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
await model.executeAsync({'intermediate2': input});
});
it('executeAsync throws when the subgraph has unknown ops', async () => {
const graphDef: tensorflow.IGraphDef = {
node: [
{name: 'input', op: 'Placeholder'},
{name: 'intermediate', op: 'Unknown', input: ['input']},
{name: 'intermediate2', op: 'Sqrt', input: ['intermediate']},
{name: 'output', op: 'Square', input: ['intermediate2']},
],
versions: {producer: 1.0, minConsumer: 3}
};
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: graphDef,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
try {
await model.executeAsync({'input': input});
throw new Error('Previous line should throw');
} catch (ex) {
expect((ex as Error).message)
.toBe(
'Unknown op \'Unknown\'. File an issue at ' +
'https://github.com/tensorflow/tfjs/issues so we can add it, ' +
'or register a custom execution with tf.registerOp()');
}
});
it('execute fails when there are dynamic ops', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: CONTROL_FLOW_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
expect(() => model.execute(input))
.toThrowError(/This execution contains the node 'Enter'/);
});
it('execute does not warn when there are no dynamic ops', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
model.execute(input);
expect(console.warn).toHaveBeenCalledTimes(0);
});
it('execute err when there are no dynamic ops', async () => {
const customLoader: tfc.io.IOHandler = {
load: async () => ({
modelTopology: SIMPLE_MODEL,
weightSpecs: weightsManifest,
weightData: new Int32Array([5]).buffer,
})
};
const model = await loadGraphModel(customLoader);
spyOn(console, 'warn');
const input = tfc.tensor2d([1, 1], [2, 1], 'int32');
model.execute(input);
expect(console.warn).toHaveBeenCalledTimes(0);
});
}); | the_stack |
import {
CompletionItem,
CompletionItemKind,
SnippetString,
MarkdownString,
TextDocument,
Position,
Range,
} from 'vscode'
import {
TagItem,
TagAttrItem,
autocompleteSpecialTagAttr,
autocompleteTagAttr,
autocompleteTagAttrValue,
autocompleteTagName,
} from '../common/src'
import * as path from 'path'
import { Config } from './lib/config'
import { getCustomOptions, getTextAtPosition, getRoot, getEOL, getLastChar } from './lib/helper'
import { LanguageConfig } from './lib/language'
import { getTagAtPosition } from './getTagAtPosition/'
import * as s from './res/snippets'
import { getClass } from './lib/StyleFile'
import { getCloseTag } from './lib/closeTag'
import { getProp } from './lib/ScriptFile'
export default abstract class AutoCompletion {
abstract id: 'wxml' | 'wxml-pug'
get isPug() {
return this.id === 'wxml-pug'
}
get attrQuote() {
return this.isPug ? this.config.pugQuoteStyle : this.config.wxmlQuoteStyle
}
constructor(public config: Config) {}
getCustomOptions(doc: TextDocument) {
return getCustomOptions(this.config, doc)
}
renderTag(tag: TagItem, sortText: string) {
let c = tag.component
let item = new CompletionItem(c.name, CompletionItemKind.Module)
let { attrQuote, isPug } = this
let allAttrs = c.attrs || []
let attrs = allAttrs
.filter(a => a.required || a.subAttrs)
.map((a, i) => (isPug ? '' : ' ') + `${a.name}=${attrQuote}${this.setDefault(i + 1, a.defaultValue)}${attrQuote}`)
let extraSpace = ''
// 如果自动补全中没有属性,并且此组件有额外属性,则触发自动属性补全
if (!attrs.length && allAttrs.length) {
item.command = autoSuggestCommand()
extraSpace = ' '
}
let len = attrs.length + 1
let snippet: string
if (isPug) {
snippet = `${c.name}(${attrs.join(' ')}\${${len}})\${0}`
} else {
if (this.config.selfCloseTags.includes(c.name)) {
snippet = `${c.name}${attrs.join('')}${extraSpace}\${${len}} />\${0}`
} else {
snippet = `${c.name}${attrs.join('')}${extraSpace}\${${len}}>\${${len + 1}}</${c.name}>\${0}`
}
}
item.insertText = new SnippetString(snippet)
item.documentation = new MarkdownString(tag.markdown)
item.sortText = sortText
return item
}
renderTagAttr(tagAttr: TagAttrItem, sortText: string, kind?: CompletionItemKind) {
let a = tagAttr.attr
let item = new CompletionItem(a.name, kind === undefined ? CompletionItemKind.Field : kind)
let defaultValue = a.defaultValue
if (!this.isDefaultValueValid(defaultValue)) {
defaultValue = a.enum && a.enum[0].value
}
let { attrQuote, isPug } = this
if (a.boolean) {
item.insertText = new SnippetString(isPug && defaultValue === 'false' ? `${a.name}=false` : a.name)
} else {
let value = a.addBrace ? '{{${1}}}' : this.setDefault(1, defaultValue)
// 是否有可选值,如果有可选值则触发命令的自动补全
let values = a.enum ? a.enum : a.subAttrs ? a.subAttrs.map(sa => ({ value: sa.equal })) : []
if (values.length) {
value = '${1}'
item.command = autoSuggestCommand()
}
item.insertText = new SnippetString(`${a.name}=${attrQuote}${value}${attrQuote}$0`)
}
item.documentation = new MarkdownString(tagAttr.markdown)
item.sortText = sortText
if (a.name === 'class') item.command = autoSuggestCommand()
return item
}
renderSnippet(doc: TextDocument, name: string, snippet: s.Snippet, sortText: string) {
let item = new CompletionItem(name + ' snippet', CompletionItemKind.Snippet)
let eol = getEOL(doc)
let body = Array.isArray(snippet.body) ? snippet.body.join(eol) : snippet.body
body = body.replace(/___/g, this.attrQuote)
if (!this.isPug && body.startsWith('<')) body = body.substr(1) // 去除触发符号
item.insertText = new SnippetString(body)
item.documentation = new MarkdownString(snippet.markdown || snippet.description)
item.sortText = sortText
return item
}
private setDefault(index: number, defaultValue: any) {
if (!this.isDefaultValueValid(defaultValue)) return '${' + index + '}'
if (typeof defaultValue === 'boolean' || defaultValue === 'true' || defaultValue === 'false') {
return `{{\${${index}|true,false|}}}`
} else {
return `\${${index}:${String(defaultValue).replace(/['"]/g, '')}}`
}
}
private isDefaultValueValid(defaultValue: any) {
return defaultValue !== undefined && defaultValue !== ''
}
/**
* 创建组件名称的自动补全
*/
async createComponentSnippetItems(lc: LanguageConfig, doc: TextDocument, pos: Position, prefix?: string) {
let res = await autocompleteTagName(lc, this.getCustomOptions(doc))
let filter = (key: string) => key && (!prefix || prefix.split('').every(c => key.includes(c)))
let filterComponent = (t: TagItem) => filter(t.component.name)
let items = [
...res.customs.filter(filterComponent).map(t => this.renderTag(t, 'a')), // 自定义的组件放在前面
...res.natives.filter(filterComponent).map(t => this.renderTag(t, 'c')),
]
// 添加 Snippet
let userSnippets = this.config.snippets
let allSnippets: s.Snippets = this.isPug
? { ...s.PugSnippets, ...userSnippets.pug }
: { ...s.WxmlSnippets, ...userSnippets.wxml }
items.push(
...Object.keys(allSnippets)
.filter(k => filter(k))
.map(k => {
let snippet = allSnippets[k]
if (!snippet.description) {
let ck = k.split(' ')[0] // 取出名称中的第一段即可
let found = res.natives.find(it => it.component.name === (ck || k))
if (found) snippet.markdown = found.markdown
}
return this.renderSnippet(doc, k, allSnippets[k], 'b')
})
)
if (prefix) {
items.forEach(it => {
it.range = new Range(new Position(pos.line, pos.character - prefix.length), pos)
})
}
return items
}
/**
* 创建组件属性的自动补全
*/
async createComponentAttributeSnippetItems(lc: LanguageConfig, doc: TextDocument, pos: Position) {
let tag = getTagAtPosition(doc, pos)
if (!tag) return []
if (tag.isOnTagName) {
return this.createComponentSnippetItems(lc, doc, pos, tag.name)
}
if (tag.isOnAttrValue && tag.attrName) {
let attrValue = tag.attrs[tag.attrName]
if (tag.attrName === 'class' || /^[\w\d-]+-class/.test(tag.attrName)) {
// `class` 或者 `xxx-class` 自动提示 class 名
let existsClass = (tag.attrs[tag.attrName] || '') as string
return this.autoCompleteClassNames(doc, existsClass ? existsClass.trim().split(/\s+/) : [])
} else if (typeof attrValue === 'string') {
if (tag.attrName.startsWith('bind') || tag.attrName.startsWith('catch')) {
// 函数自动补全
return this.autoCompleteMethods(doc, attrValue.replace(/"|'/, ''))
} else if (attrValue.trim() === '') {
let values = await autocompleteTagAttrValue(tag.name, tag.attrName, lc, this.getCustomOptions(doc))
if (!values.length) return []
let range = doc.getWordRangeAtPosition(pos, /['"]\s*['"]/)
if (range) {
range = new Range(
new Position(range.start.line, range.start.character + 1),
new Position(range.end.line, range.end.character - 1)
)
}
return values.map(v => {
let it = new CompletionItem(v.value, CompletionItemKind.Value)
it.documentation = new MarkdownString(v.markdown)
it.range = range
return it
})
}
// } else if ((tag.attrName.startsWith('bind') || tag.attrName.startsWith('catch')) && typeof attrValue === 'string') {
// return this.autoCompleteMethods(doc, attrValue.replace(/"|'/, ''))
}
return []
} else {
let res = await autocompleteTagAttr(tag.name, tag.attrs, lc, this.getCustomOptions(doc))
let triggers: CompletionItem[] = []
let { natives, basics } = res
let noBasics = lc.noBasicAttrsComponents || []
if (!noBasics.includes(tag.name)) {
triggers = [...Object.keys(lc.custom), ...lc.event.prefixes]
.filter(k => k.length > 1)
.map(k => {
// let str = k.substr(0, k.length - 1)
// let trigger = k[k.length - 1]
// let item = new CompletionItem(str, CompletionItemKind.Constant)
let item = new CompletionItem(k, CompletionItemKind.Constant)
item.sortText = 'z'
item.command = autoSuggestCommand()
// item.documentation = new MarkdownString(`输入此字段再输入 "**${trigger}**" 字符可以再次触发自动补全`)
return item
})
}
return [
...natives.map(a => this.renderTagAttr(a, 'a')),
...basics.map(a => this.renderTagAttr(a, 'b')), // 基本属性放最后
...triggers,
]
}
}
/**
* wxml:
* wx:
* bind:
* catch:
*
* vue:
* :
* @
* :xxx.sync
* @xxx.default, @xxx.user, @xxx.stop
*/
async createSpecialAttributeSnippetItems(lc: LanguageConfig, doc: TextDocument, pos: Position) {
let prefix = getTextAtPosition(doc, pos, /[:@\w\d\.-]/) as string
if (!prefix) return []
let tag = getTagAtPosition(doc, pos)
if (!tag) return []
let isEventPrefix = lc.event.prefixes.includes(prefix)
// 非 Event,也非其它自定义的属性
if (!isEventPrefix && !lc.custom.hasOwnProperty(prefix)) {
// modifiers
let modifiers: string[] = []
if (prefix.endsWith('.')) {
if (lc.event.prefixes.some(p => prefix.startsWith(p))) {
modifiers = lc.event.modifiers
} else {
let customPrefix = Object.keys(lc.custom).find(p => prefix.startsWith(p))
if (customPrefix) modifiers = lc.custom[customPrefix].modifiers
}
}
return modifiers.map(m => new CompletionItem(m, CompletionItemKind.Constant))
}
let res = await autocompleteSpecialTagAttr(prefix, tag.name, tag.attrs, lc, this.getCustomOptions(doc))
let kind = isEventPrefix ? CompletionItemKind.Event : CompletionItemKind.Field
return [
...res.customs.map(c => this.renderTagAttr(c, 'a', kind)),
...res.natives.map(c => this.renderTagAttr(c, 'b', kind)),
]
}
// 样式名自动补全
async autoCompleteClassNames(doc: TextDocument, existsClassNames: string[]) {
let items: CompletionItem[] = []
let stylefiles = getClass(doc, this.config)
let root = getRoot(doc)
stylefiles.forEach((stylefile, sfi) => {
stylefile.styles.forEach(sty => {
if (!existsClassNames.includes(sty.name)) {
existsClassNames.push(sty.name)
let i = new CompletionItem(sty.name)
i.kind = CompletionItemKind.Variable
i.detail = root ? path.relative(root, stylefile.file) : path.basename(stylefile.file)
i.sortText = 'style' + sfi
i.documentation = new MarkdownString(sty.doc)
items.push(i)
}
})
})
return items
}
/**
* 闭合标签自动完成
* @param doc
* @param pos
*/
async createCloseTagCompletionItem(doc: TextDocument, pos: Position): Promise<CompletionItem[]> {
const text = doc.getText(new Range(new Position(0, 0), pos))
if (text.length < 2 || text.substr(text.length - 2) !== '</') {
return []
}
const closeTag = getCloseTag(text)
if (closeTag) {
const completionItem = new CompletionItem(closeTag)
completionItem.kind = CompletionItemKind.Property
completionItem.insertText = closeTag
const nextPos = new Position(pos.line, pos.character + 1)
if (getLastChar(doc, nextPos) === '>') {
completionItem.range = new Range(pos, nextPos)
completionItem.label = closeTag.substr(0, closeTag.length - 1)
}
return [completionItem]
}
return []
}
/**
* 函数自动提示
* @param doc
* @param prefix 函数前缀,空则查找所有函数
*/
autoCompleteMethods(doc: TextDocument, prefix: string): CompletionItem[] {
/**
* 页面周期和组件 生命周期函数,
* 显示时置于最后
* 列表中顺序决定显示顺序
*/
const lowPriority = [
'onPullDownRefresh',
'onReachBottom',
'onPageScroll',
'onShow',
'onHide',
'onTabItemTap',
'onLoad',
'onReady',
'onResize',
'onUnload',
'onShareAppMessage',
'error',
'creaeted',
'attached',
'ready',
'moved',
'detached',
'observer',
]
const methods = getProp(doc.uri.fsPath, 'method', (prefix || '[\\w_$]') + '[\\w\\d_$]*')
const root = getRoot(doc)
return methods.map(l => {
const c = new CompletionItem(l.name, getMethodKind(l.detail))
const filePath = root ? path.relative(root, l.loc.uri.fsPath) : path.basename(l.loc.uri.fsPath)
// 低优先级排序滞后
const priotity = lowPriority.indexOf(l.name) + 1
c.detail = `${filePath}\n[${l.loc.range.start.line}行,${l.loc.range.start.character}列]`
c.documentation = new MarkdownString('```ts\n' + l.detail + '\n```')
/**
* 排序显示规则
* 1. 正常函数 如 `onTap`
* 2. 下划线函数 `_save`
* 3. 生命周期函数 `onShow`
*/
if (priotity > 0) {
c.detail += '(生命周期函数)'
c.kind = CompletionItemKind.Field
c.sortText = '}'.repeat(priotity)
} else {
c.sortText = l.name.replace('_', '{')
}
return c
})
}
}
/**
* 是否为属性式函数声明
* 如 属性式声明 `foo:()=>{}`
* @param text
*/
function getMethodKind(text: string) {
return /^\s*[\w_$][\w_$\d]*\s*:/.test(text) ? CompletionItemKind.Property : CompletionItemKind.Method
}
function autoSuggestCommand() {
return {
command: 'editor.action.triggerSuggest',
title: 'triggerSuggest',
}
} | the_stack |
import {
$enum,
EnumValueMapper,
EnumValueMapperWithNull,
EnumValueMapperWithUndefined,
EnumValueMapperWithNullAndUndefined
} from "../src";
enum RGB {
R = "r",
G = 1,
B = "b"
}
describe("mapValue (string/number mix)", () => {
describe("Without null/undefined", () => {
interface TestEntry {
isUnexpected?: boolean;
value: RGB;
result: string;
}
const TEST_ENTRIES: TestEntry[] = [
{
value: RGB.R,
result: "Red!"
},
{
value: RGB.G,
result: "Green!"
},
{
value: RGB.B,
result: "Blue!"
},
{
isUnexpected: true,
value: (null as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
value: (undefined as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
value: ("unexpected!" as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
// matches a standard property name on Object.prototype
value: ("toString" as any) as RGB,
result: "Unexpected!"
}
];
const mappers: EnumValueMapper<RGB, string>[] = [
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!"
},
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleUnexpected]: "Unexpected!"
},
{
[RGB.R]: $enum.unhandledEntry,
[RGB.G]: $enum.unhandledEntry,
[RGB.B]: $enum.unhandledEntry,
[$enum.handleUnexpected]: $enum.unhandledEntry
}
];
for (const mapper of mappers) {
for (const testEntry of TEST_ENTRIES) {
if (mapper[RGB.R] === $enum.unhandledEntry) {
test(`Unhandled entry throws error (${testEntry.value}`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unhandled value: ${testEntry.value}`);
});
} else if (
mapper.hasOwnProperty($enum.handleUnexpected) ||
!testEntry.isUnexpected
) {
test(`Correct value is returned (${testEntry.value})`, () => {
const result = $enum
.mapValue(testEntry.value)
.with(mapper);
expect(result).toBe(testEntry.result);
});
} else {
test(`Unhandled unexpected value throws error (${testEntry.value})`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unexpected value: ${testEntry.value}`);
});
}
}
}
});
describe("With null", () => {
interface TestEntry {
isUnexpected?: boolean;
value: RGB | null;
result: string;
}
const TEST_ENTRIES: TestEntry[] = [
{
value: RGB.R,
result: "Red!"
},
{
value: RGB.G,
result: "Green!"
},
{
value: RGB.B,
result: "Blue!"
},
{
value: null,
result: "Null!"
},
{
isUnexpected: true,
value: (undefined as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
value: ("unexpected!" as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
// matches a standard property name on Object.prototype
value: ("toString" as any) as RGB,
result: "Unexpected!"
}
];
const mappers: EnumValueMapperWithNull<RGB, string>[] = [
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleNull]: "Null!"
},
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleNull]: "Null!",
[$enum.handleUnexpected]: "Unexpected!"
},
{
[RGB.R]: $enum.unhandledEntry,
[RGB.G]: $enum.unhandledEntry,
[RGB.B]: $enum.unhandledEntry,
[$enum.handleNull]: $enum.unhandledEntry,
[$enum.handleUnexpected]: $enum.unhandledEntry
}
];
for (const mapper of mappers) {
for (const testEntry of TEST_ENTRIES) {
if (mapper[RGB.R] === $enum.unhandledEntry) {
test(`Unhandled entry throws error (${testEntry.value}`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unhandled value: ${testEntry.value}`);
});
} else if (
mapper.hasOwnProperty($enum.handleUnexpected) ||
!testEntry.isUnexpected
) {
test(`Correct value is returned (${testEntry.value})`, () => {
const result = $enum
.mapValue(testEntry.value)
.with(mapper);
expect(result).toBe(testEntry.result);
});
} else {
test(`Unhandled unexpected value throws error (${testEntry.value})`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unexpected value: ${testEntry.value}`);
});
}
}
}
});
describe("With undefined", () => {
interface TestEntry {
isUnexpected?: boolean;
value: RGB | undefined;
result: string;
}
const TEST_ENTRIES: TestEntry[] = [
{
value: RGB.R,
result: "Red!"
},
{
value: RGB.G,
result: "Green!"
},
{
value: RGB.B,
result: "Blue!"
},
{
value: undefined,
result: "Undefined!"
},
{
isUnexpected: true,
value: (null as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
value: ("unexpected!" as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
// matches a standard property name on Object.prototype
value: ("toString" as any) as RGB,
result: "Unexpected!"
}
];
const mappers: EnumValueMapperWithUndefined<RGB, string>[] = [
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleUndefined]: "Undefined!"
},
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleUndefined]: "Undefined!",
[$enum.handleUnexpected]: "Unexpected!"
},
{
[RGB.R]: $enum.unhandledEntry,
[RGB.G]: $enum.unhandledEntry,
[RGB.B]: $enum.unhandledEntry,
[$enum.handleUndefined]: $enum.unhandledEntry,
[$enum.handleUnexpected]: $enum.unhandledEntry
}
];
for (const mapper of mappers) {
for (const testEntry of TEST_ENTRIES) {
if (mapper[RGB.R] === $enum.unhandledEntry) {
test(`Unhandled entry throws error (${testEntry.value}`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unhandled value: ${testEntry.value}`);
});
} else if (
mapper.hasOwnProperty($enum.handleUnexpected) ||
!testEntry.isUnexpected
) {
test(`Correct value is returned (${testEntry.value})`, () => {
const result = $enum
.mapValue(testEntry.value)
.with(mapper);
expect(result).toBe(testEntry.result);
});
} else {
test(`Unhandled unexpected value throws error (${testEntry.value})`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unexpected value: ${testEntry.value}`);
});
}
}
}
});
describe("With null and undefined", () => {
interface TestEntry {
isUnexpected?: boolean;
value: RGB | null | undefined;
result: string;
}
const TEST_ENTRIES: TestEntry[] = [
{
value: RGB.R,
result: "Red!"
},
{
value: RGB.G,
result: "Green!"
},
{
value: RGB.B,
result: "Blue!"
},
{
value: null,
result: "Null!"
},
{
value: undefined,
result: "Undefined!"
},
{
isUnexpected: true,
value: ("unexpected!" as any) as RGB,
result: "Unexpected!"
},
{
isUnexpected: true,
// matches a standard property name on Object.prototype
value: ("toString" as any) as RGB,
result: "Unexpected!"
}
];
const mappers: EnumValueMapperWithNullAndUndefined<RGB, string>[] = [
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleNull]: "Null!",
[$enum.handleUndefined]: "Undefined!"
},
{
[RGB.R]: "Red!",
[RGB.G]: "Green!",
[RGB.B]: "Blue!",
[$enum.handleNull]: "Null!",
[$enum.handleUndefined]: "Undefined!",
[$enum.handleUnexpected]: "Unexpected!"
},
{
[RGB.R]: $enum.unhandledEntry,
[RGB.G]: $enum.unhandledEntry,
[RGB.B]: $enum.unhandledEntry,
[$enum.handleNull]: $enum.unhandledEntry,
[$enum.handleUndefined]: $enum.unhandledEntry,
[$enum.handleUnexpected]: $enum.unhandledEntry
}
];
for (const mapper of mappers) {
for (const testEntry of TEST_ENTRIES) {
if (mapper[RGB.R] === $enum.unhandledEntry) {
test(`Unhandled entry throws error (${testEntry.value}`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unhandled value: ${testEntry.value}`);
});
} else if (
mapper.hasOwnProperty($enum.handleUnexpected) ||
!testEntry.isUnexpected
) {
test(`Correct value is returned (${testEntry.value})`, () => {
const result = $enum
.mapValue(testEntry.value)
.with(mapper);
expect(result).toBe(testEntry.result);
});
} else {
test(`Unhandled unexpected value throws error (${testEntry.value})`, () => {
expect(() => {
$enum.mapValue(testEntry.value).with(mapper);
}).toThrowError(`Unexpected value: ${testEntry.value}`);
});
}
}
}
});
}); | the_stack |
import { CUSTOM_ELEMENTS_SCHEMA, SimpleChange } from '@angular/core';
import { AppsProcessService, setupTestBed } from '@alfresco/adf-core';
import { from, of } from 'rxjs';
import { FilterProcessRepresentationModel } from '../models/filter-process.model';
import { ProcessFilterService } from '../services/process-filter.service';
import { ProcessFiltersComponent } from './process-filters.component';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { fakeProcessFilters } from '../../mock/process/process-filters.mock';
import { ProcessTestingModule } from '../../testing/process.testing.module';
import { TranslateModule } from '@ngx-translate/core';
describe('ProcessFiltersComponent', () => {
let filterList: ProcessFiltersComponent;
let fixture: ComponentFixture<ProcessFiltersComponent>;
let processFilterService: ProcessFilterService;
let appsProcessService: AppsProcessService;
setupTestBed({
imports: [
TranslateModule.forRoot(),
ProcessTestingModule
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
beforeEach(() => {
fixture = TestBed.createComponent(ProcessFiltersComponent);
filterList = fixture.componentInstance;
processFilterService = TestBed.inject(ProcessFilterService);
appsProcessService = TestBed.inject(AppsProcessService);
});
afterEach(() => {
fixture.destroy();
});
it('should return the filter task list', async (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.success.subscribe((res) => {
expect(res).toBeDefined();
expect(filterList.filters).toBeDefined();
expect(filterList.filters.length).toEqual(3);
expect(filterList.filters[0].name).toEqual('FakeCompleted');
expect(filterList.filters[1].name).toEqual('FakeAll');
expect(filterList.filters[2].name).toEqual('Running');
done();
});
spyOn(filterList, 'getFiltersByAppId').and.callThrough();
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
expect(filterList.getFiltersByAppId).toHaveBeenCalled();
});
it('should select the Running process filter', async (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.success.subscribe(() => {
filterList.selectRunningFilter();
expect(filterList.currentFilter.name).toEqual('Running');
done();
});
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
});
it('should emit the selected filter based on the filterParam input', async (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = new FilterProcessRepresentationModel({ id: 10 });
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.filterSelected.subscribe((filter) => {
expect(filter.name).toEqual('FakeCompleted');
done();
});
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
});
it('should filterClicked emit when a filter is clicked from the UI', async () => {
filterList.filters = fakeProcessFilters;
spyOn(filterList.filterClicked, 'emit');
fixture.detectChanges();
await fixture.whenStable();
const filterButton = fixture.debugElement.nativeElement.querySelector(`[data-automation-id="${fakeProcessFilters[0].name}_filter"]`);
filterButton.click();
expect(filterList.filterClicked.emit).toHaveBeenCalledWith(fakeProcessFilters[0]);
});
it('should reset selection when filterParam is a filter that does not exist', async () => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const nonExistingFilterParam = { name: 'non-existing-filter' };
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.currentFilter = nonExistingFilterParam;
filterList.filterParam = new FilterProcessRepresentationModel(nonExistingFilterParam);
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
await fixture.whenStable();
expect(filterList.currentFilter).toBe(undefined);
});
it('should return the filter task list, filtered By Name', (done) => {
spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(from(Promise.resolve({ id: 1 })));
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
const change = new SimpleChange(null, 'test', true);
filterList.ngOnChanges({ 'appName': change });
filterList.success.subscribe((res) => {
const deployApp: any = appsProcessService.getDeployedApplicationsByName;
expect(deployApp.calls.count()).toEqual(1);
expect(res).toBeDefined();
done();
});
fixture.detectChanges();
});
it('should emit an error with a bad response', (done) => {
const mockErrorFilterPromise = Promise.reject({
error: 'wrong request'
});
spyOn(processFilterService, 'getProcessFilters').and.returnValue(from(mockErrorFilterPromise));
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appId': change });
filterList.error.subscribe((err) => {
expect(err).toBeDefined();
done();
});
fixture.detectChanges();
});
it('should emit an error with a bad response', (done) => {
const mockErrorFilterPromise = Promise.reject({
error: 'wrong request'
});
spyOn(appsProcessService, 'getDeployedApplicationsByName').and.returnValue(from(mockErrorFilterPromise));
const appId = 'fake-app';
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appName': change });
filterList.error.subscribe((err) => {
expect(err).toBeDefined();
done();
});
fixture.detectChanges();
});
it('should emit an event when a filter is selected', (done) => {
const currentFilter = new FilterProcessRepresentationModel({
id: 10,
name: 'FakeCompleted',
filter: { state: 'open', assignment: 'fake-involved' }
});
filterList.filterClicked.subscribe((filter) => {
expect(filter).toBeDefined();
expect(filter).toEqual(currentFilter);
expect(filterList.currentFilter).toEqual(currentFilter);
done();
});
filterList.selectFilter(currentFilter);
});
it('should reload filters by appId on binding changes', () => {
spyOn(filterList, 'getFiltersByAppId').and.stub();
const appId = '1';
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appId': change });
expect(filterList.getFiltersByAppId).toHaveBeenCalledWith(appId);
});
it('should reload filters by appId null on binding changes', () => {
spyOn(filterList, 'getFiltersByAppId').and.stub();
const appId = null;
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appId': change });
expect(filterList.getFiltersByAppId).toHaveBeenCalledWith(appId);
});
it('should reload filters by app name on binding changes', () => {
spyOn(filterList, 'getFiltersByAppName').and.stub();
const appName = 'fake-app-name';
const change = new SimpleChange(null, appName, true);
filterList.ngOnChanges({ 'appName': change });
expect(filterList.getFiltersByAppName).toHaveBeenCalledWith(appName);
});
it('should return the current filter after one is selected', () => {
const filter = new FilterProcessRepresentationModel({
name: 'FakeAll',
filter: { state: 'open', assignment: 'fake-assignee' }
});
expect(filterList.currentFilter).toBeUndefined();
filterList.selectFilter(filter);
expect(filterList.getCurrentFilter()).toBe(filter);
});
it('should select the filter passed as input by id', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = new FilterProcessRepresentationModel({ id: 20 });
const appId = 1;
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appId': change });
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(filterList.filters).toBeDefined();
expect(filterList.filters.length).toEqual(3);
expect(filterList.currentFilter).toBeDefined();
expect(filterList.currentFilter.name).toEqual('FakeAll');
done();
});
});
it('should select the filter passed as input by name', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.filterParam = new FilterProcessRepresentationModel({ name: 'FakeAll' });
const appId = 1;
const change = new SimpleChange(null, appId, true);
filterList.ngOnChanges({ 'appId': change });
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(filterList.filters).toBeDefined();
expect(filterList.filters.length).toEqual(3);
expect(filterList.currentFilter).toBeDefined();
expect(filterList.currentFilter.name).toEqual('FakeAll');
done();
});
});
it('should attach specific icon for each filter if hasIcon is true', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.showIcon = true;
const change = new SimpleChange(undefined, 1, true);
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(filterList.filters.length).toBe(3);
const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon'));
expect(filters.length).toBe(3);
expect(filters[0].nativeElement.innerText).toContain('dashboard');
expect(filters[1].nativeElement.innerText).toContain('shuffle');
expect(filters[2].nativeElement.innerText).toContain('check_circle');
done();
});
});
it('should not attach icons for each filter if hasIcon is false', (done) => {
spyOn(processFilterService, 'getProcessFilters').and.returnValue(of(fakeProcessFilters));
filterList.showIcon = false;
const change = new SimpleChange(undefined, 1, true);
filterList.ngOnChanges({ 'appId': change });
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
const filters: any = fixture.debugElement.queryAll(By.css('.adf-icon'));
expect(filters.length).toBe(0);
done();
});
});
}); | the_stack |
* @packageDocumentation
* @module help-extension
*/
import {
ILayoutRestorer,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import {
Dialog,
ICommandPalette,
MainAreaWidget,
showDialog,
WidgetTracker
} from '@jupyterlab/apputils';
import { PageConfig, URLExt } from '@jupyterlab/coreutils';
import { IMainMenu } from '@jupyterlab/mainmenu';
import { KernelMessage } from '@jupyterlab/services';
import { ITranslator } from '@jupyterlab/translation';
import {
CommandToolbarButton,
copyrightIcon,
IFrame,
jupyterIcon,
jupyterlabWordmarkIcon,
refreshIcon,
Toolbar
} from '@jupyterlab/ui-components';
import { ReadonlyJSONObject } from '@lumino/coreutils';
import { Menu } from '@lumino/widgets';
import * as React from 'react';
import { Licenses } from './licenses';
/**
* The command IDs used by the help plugin.
*/
namespace CommandIDs {
export const open = 'help:open';
export const about = 'help:about';
export const activate = 'help:activate';
export const close = 'help:close';
export const show = 'help:show';
export const hide = 'help:hide';
export const launchClassic = 'help:launch-classic-notebook';
export const jupyterForum = 'help:jupyter-forum';
export const licenses = 'help:licenses';
export const licenseReport = 'help:license-report';
export const refreshLicenses = 'help:licenses-refresh';
}
/**
* A flag denoting whether the application is loaded over HTTPS.
*/
const LAB_IS_SECURE = window.location.protocol === 'https:';
/**
* The class name added to the help widget.
*/
const HELP_CLASS = 'jp-Help';
/**
* Add a command to show an About dialog.
*/
const about: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/help-extension:about',
autoStart: true,
requires: [ITranslator],
optional: [ICommandPalette],
activate: (
app: JupyterFrontEnd,
translator: ITranslator,
palette: ICommandPalette | null
): void => {
const { commands } = app;
const trans = translator.load('jupyterlab');
const category = trans.__('Help');
commands.addCommand(CommandIDs.about, {
label: trans.__('About %1', app.name),
execute: () => {
// Create the header of the about dialog
const versionNumber = trans.__('Version %1', app.version);
const versionInfo = (
<span className="jp-About-version-info">
<span className="jp-About-version">{versionNumber}</span>
</span>
);
const title = (
<span className="jp-About-header">
<jupyterIcon.react margin="7px 9.5px" height="auto" width="58px" />
<div className="jp-About-header-info">
<jupyterlabWordmarkIcon.react height="auto" width="196px" />
{versionInfo}
</div>
</span>
);
// Create the body of the about dialog
const jupyterURL = 'https://jupyter.org/about.html';
const contributorsURL =
'https://github.com/jupyterlab/jupyterlab/graphs/contributors';
const externalLinks = (
<span className="jp-About-externalLinks">
<a
href={contributorsURL}
target="_blank"
rel="noopener noreferrer"
className="jp-Button-flat"
>
{trans.__('CONTRIBUTOR LIST')}
</a>
<a
href={jupyterURL}
target="_blank"
rel="noopener noreferrer"
className="jp-Button-flat"
>
{trans.__('ABOUT PROJECT JUPYTER')}
</a>
</span>
);
const copyright = (
<span className="jp-About-copyright">
{trans.__('© 2015-2021 Project Jupyter Contributors')}
</span>
);
const body = (
<div className="jp-About-body">
{externalLinks}
{copyright}
</div>
);
return showDialog({
title,
body,
buttons: [
Dialog.createButton({
label: trans.__('Dismiss'),
className: 'jp-About-button jp-mod-reject jp-mod-styled'
})
]
});
}
});
if (palette) {
palette.addItem({ command: CommandIDs.about, category });
}
}
};
/**
* A plugin to add a command to open the Classic Notebook interface.
*/
const launchClassic: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/help-extension:launch-classic',
autoStart: true,
requires: [ITranslator],
optional: [ICommandPalette],
activate: (
app: JupyterFrontEnd,
translator: ITranslator,
palette: ICommandPalette | null
): void => {
const { commands } = app;
const trans = translator.load('jupyterlab');
const category = trans.__('Help');
commands.addCommand(CommandIDs.launchClassic, {
label: trans.__('Launch Classic Notebook'),
execute: () => {
window.open(PageConfig.getBaseUrl() + 'tree');
}
});
if (palette) {
palette.addItem({ command: CommandIDs.launchClassic, category });
}
}
};
/**
* A plugin to add a command to open the Jupyter Forum.
*/
const jupyterForum: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/help-extension:jupyter-forum',
autoStart: true,
requires: [ITranslator],
optional: [ICommandPalette],
activate: (
app: JupyterFrontEnd,
translator: ITranslator,
palette: ICommandPalette | null
): void => {
const { commands } = app;
const trans = translator.load('jupyterlab');
const category = trans.__('Help');
commands.addCommand(CommandIDs.jupyterForum, {
label: trans.__('Jupyter Forum'),
execute: () => {
window.open('https://discourse.jupyter.org/c/jupyterlab');
}
});
if (palette) {
palette.addItem({ command: CommandIDs.jupyterForum, category });
}
}
};
/**
* A plugin to add a list of resources to the help menu.
*/
const resources: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/help-extension:resources',
autoStart: true,
requires: [IMainMenu, ITranslator],
optional: [ICommandPalette, ILayoutRestorer],
activate: (
app: JupyterFrontEnd,
mainMenu: IMainMenu,
translator: ITranslator,
palette: ICommandPalette | null,
restorer: ILayoutRestorer | null
): void => {
const trans = translator.load('jupyterlab');
let counter = 0;
const category = trans.__('Help');
const namespace = 'help-doc';
const { commands, shell, serviceManager } = app;
const tracker = new WidgetTracker<MainAreaWidget<IFrame>>({ namespace });
const resources = [
{
text: trans.__('JupyterLab Reference'),
url: 'https://jupyterlab.readthedocs.io/en/latest/'
},
{
text: trans.__('JupyterLab FAQ'),
url:
'https://jupyterlab.readthedocs.io/en/latest/getting_started/faq.html'
},
{
text: trans.__('Jupyter Reference'),
url: 'https://jupyter.org/documentation'
},
{
text: trans.__('Markdown Reference'),
url: 'https://commonmark.org/help/'
}
];
resources.sort((a: any, b: any) => {
return a.text.localeCompare(b.text);
});
// Handle state restoration.
if (restorer) {
void restorer.restore(tracker, {
command: CommandIDs.open,
args: widget => ({
url: widget.content.url,
text: widget.content.title.label
}),
name: widget => widget.content.url
});
}
/**
* Create a new HelpWidget widget.
*/
function newHelpWidget(url: string, text: string): MainAreaWidget<IFrame> {
// Allow scripts and forms so that things like
// readthedocs can use their search functionality.
// We *don't* allow same origin requests, which
// can prevent some content from being loaded onto the
// help pages.
const content = new IFrame({
sandbox: ['allow-scripts', 'allow-forms']
});
content.url = url;
content.addClass(HELP_CLASS);
content.title.label = text;
content.id = `${namespace}-${++counter}`;
const widget = new MainAreaWidget({ content });
widget.addClass('jp-Help');
return widget;
}
// Populate the Help menu.
const helpMenu = mainMenu.helpMenu;
const resourcesGroup = resources.map(args => ({
args,
command: CommandIDs.open
}));
helpMenu.addGroup(resourcesGroup, 10);
// Generate a cache of the kernel help links.
const kernelInfoCache = new Map<
string,
KernelMessage.IInfoReplyMsg['content']
>();
serviceManager.sessions.runningChanged.connect((m, sessions) => {
// If a new session has been added, it is at the back
// of the session list. If one has changed or stopped,
// it does not hurt to check it.
if (!sessions.length) {
return;
}
const sessionModel = sessions[sessions.length - 1];
if (
!sessionModel.kernel ||
kernelInfoCache.has(sessionModel.kernel.name)
) {
return;
}
const session = serviceManager.sessions.connectTo({
model: sessionModel,
kernelConnectionOptions: { handleComms: false }
});
void session.kernel?.info.then(kernelInfo => {
const name = session.kernel!.name;
// Check the cache second time so that, if two callbacks get scheduled,
// they don't try to add the same commands.
if (kernelInfoCache.has(name)) {
return;
}
// Set the Kernel Info cache.
kernelInfoCache.set(name, kernelInfo);
// Utility function to check if the current widget
// has registered itself with the help menu.
const usesKernel = () => {
let result = false;
const widget = app.shell.currentWidget;
if (!widget) {
return result;
}
helpMenu.kernelUsers.forEach(u => {
if (u.tracker.has(widget) && u.getKernel(widget)?.name === name) {
result = true;
}
});
return result;
};
// Add the kernel banner to the Help Menu.
const bannerCommand = `help-menu-${name}:banner`;
const spec = serviceManager.kernelspecs?.specs?.kernelspecs[name];
if (!spec) {
return;
}
const kernelName = spec.display_name;
let kernelIconUrl = spec.resources['logo-64x64'];
commands.addCommand(bannerCommand, {
label: trans.__('About the %1 Kernel', kernelName),
isVisible: usesKernel,
isEnabled: usesKernel,
execute: () => {
// Create the header of the about dialog
const headerLogo = <img src={kernelIconUrl} />;
const title = (
<span className="jp-About-header">
{headerLogo}
<div className="jp-About-header-info">{kernelName}</div>
</span>
);
const banner = <pre>{kernelInfo.banner}</pre>;
const body = <div className="jp-About-body">{banner}</div>;
return showDialog({
title,
body,
buttons: [
Dialog.createButton({
label: trans.__('Dismiss'),
className: 'jp-About-button jp-mod-reject jp-mod-styled'
})
]
});
}
});
helpMenu.addGroup([{ command: bannerCommand }], 20);
// Add the kernel info help_links to the Help menu.
const kernelGroup: Menu.IItemOptions[] = [];
(kernelInfo.help_links || []).forEach(link => {
const commandId = `help-menu-${name}:${link.text}`;
commands.addCommand(commandId, {
label: link.text,
isVisible: usesKernel,
isEnabled: usesKernel,
execute: () => {
return commands.execute(CommandIDs.open, link);
}
});
kernelGroup.push({ command: commandId });
});
helpMenu.addGroup(kernelGroup, 21);
// Dispose of the session object since we no longer need it.
session.dispose();
});
});
commands.addCommand(CommandIDs.open, {
label: args => args['text'] as string,
execute: args => {
const url = args['url'] as string;
const text = args['text'] as string;
const newBrowserTab = (args['newBrowserTab'] as boolean) || false;
// If help resource will generate a mixed content error, load externally.
if (
newBrowserTab ||
(LAB_IS_SECURE && URLExt.parse(url).protocol !== 'https:')
) {
window.open(url);
return;
}
const widget = newHelpWidget(url, text);
void tracker.add(widget);
shell.add(widget, 'main');
return widget;
}
});
if (palette) {
resources.forEach(args => {
palette.addItem({ args, command: CommandIDs.open, category });
});
palette.addItem({
args: { reload: true },
command: 'apputils:reset',
category
});
}
}
};
/**
* A plugin to add a licenses reporting tools.
*/
const licenses: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/help-extension:licenses',
autoStart: true,
requires: [ITranslator],
optional: [IMainMenu, ICommandPalette, ILayoutRestorer],
activate: (
app: JupyterFrontEnd,
translator: ITranslator,
menu: IMainMenu | null,
palette: ICommandPalette | null,
restorer: ILayoutRestorer | null
) => {
// bail if no license API is available from the server
if (!PageConfig.getOption('licensesUrl')) {
return;
}
const { commands, shell } = app;
const trans = translator.load('jupyterlab');
// translation strings
const category = trans.__('Help');
const downloadAsText = trans.__('Download All Licenses as');
const licensesText = trans.__('Licenses');
const refreshLicenses = trans.__('Refresh Licenses');
// an incrementer for license widget ids
let counter = 0;
const licensesUrl =
URLExt.join(
PageConfig.getBaseUrl(),
PageConfig.getOption('licensesUrl')
) + '/';
const licensesNamespace = 'help-licenses';
const licensesTracker = new WidgetTracker<MainAreaWidget<Licenses>>({
namespace: licensesNamespace
});
/**
* Return a full license report format based on a format name
*/
function formatOrDefault(format: string): Licenses.IReportFormat {
return (
Licenses.REPORT_FORMATS[format] ||
Licenses.REPORT_FORMATS[Licenses.DEFAULT_FORMAT]
);
}
/**
* Create a MainAreaWidget for a license viewer
*/
function createLicenseWidget(args: Licenses.ICreateArgs) {
const licensesModel = new Licenses.Model({
...args,
licensesUrl,
trans,
serverSettings: app.serviceManager.serverSettings
});
const content = new Licenses({ model: licensesModel });
content.id = `${licensesNamespace}-${++counter}`;
content.title.label = licensesText;
content.title.icon = copyrightIcon;
const main = new MainAreaWidget({
content,
reveal: licensesModel.licensesReady
});
main.toolbar.addItem(
'refresh-licenses',
new CommandToolbarButton({
id: CommandIDs.refreshLicenses,
args: { noLabel: 1 },
commands
})
);
main.toolbar.addItem('spacer', Toolbar.createSpacerItem());
for (const format of Object.keys(Licenses.REPORT_FORMATS)) {
const button = new CommandToolbarButton({
id: CommandIDs.licenseReport,
args: { format, noLabel: 1 },
commands
});
main.toolbar.addItem(`download-${format}`, button);
}
return main;
}
// register license-related commands
commands.addCommand(CommandIDs.licenses, {
label: licensesText,
execute: (args: any) => {
const licenseMain = createLicenseWidget(args as Licenses.ICreateArgs);
shell.add(licenseMain, 'main');
// add to tracker so it can be restored, and update when choices change
void licensesTracker.add(licenseMain);
licenseMain.content.model.trackerDataChanged.connect(() => {
void licensesTracker.save(licenseMain);
});
return licenseMain;
}
});
commands.addCommand(CommandIDs.refreshLicenses, {
label: args => (args.noLabel ? '' : refreshLicenses),
caption: refreshLicenses,
icon: refreshIcon,
execute: async () => {
return licensesTracker.currentWidget?.content.model.initLicenses();
}
});
commands.addCommand(CommandIDs.licenseReport, {
label: args => {
if (args.noLabel) {
return '';
}
const format = formatOrDefault(`${args.format}`);
return `${downloadAsText} ${format.title}`;
},
caption: args => {
const format = formatOrDefault(`${args.format}`);
return `${downloadAsText} ${format.title}`;
},
icon: args => {
const format = formatOrDefault(`${args.format}`);
return format.icon;
},
execute: async args => {
const format = formatOrDefault(`${args.format}`);
return await licensesTracker.currentWidget?.content.model.download({
format: format.id
});
}
});
// handle optional integrations
if (palette) {
palette.addItem({ command: CommandIDs.licenses, category });
}
if (menu) {
const helpMenu = menu.helpMenu;
helpMenu.addGroup([{ command: CommandIDs.licenses }], 0);
}
if (restorer) {
void restorer.restore(licensesTracker, {
command: CommandIDs.licenses,
name: widget => 'licenses',
args: widget => {
const {
currentBundleName,
currentPackageIndex,
packageFilter
} = widget.content.model;
const args: Licenses.ICreateArgs = {
currentBundleName,
currentPackageIndex,
packageFilter
};
return args as ReadonlyJSONObject;
}
});
}
}
};
const plugins: JupyterFrontEndPlugin<any>[] = [
about,
launchClassic,
jupyterForum,
resources,
licenses
];
export default plugins; | the_stack |
import { useState, useEffect, useCallback } from 'react';
import { createStyles, makeStyles, Theme } from '@material-ui/core';
import { Formik, Form, FormikHelpers } from 'formik';
import { useRouter } from 'next/router';
import Button from '@material-ui/core/Button';
import useAuth from '../hooks/use-auth';
import Overview from '../components/SignUp/Forms/Overview';
import BasicInfo from '../components/SignUp/Forms/BasicInfo';
import GitHubAccount from '../components/SignUp/Forms/GitHubAccount';
import RSSFeeds from '../components/SignUp/Forms/RSSFeeds';
import Review from '../components/SignUp/Forms/Review';
import DynamicImage from '../components/DynamicImage';
import { SignUpForm } from '../interfaces';
import formModels from '../components/SignUp/Schema/FormModel';
import formSchema from '../components/SignUp/Schema/FormSchema';
import { authServiceUrl } from '../config';
import PopUp from '../components/PopUp';
import Spinner from '../components/Spinner';
enum SIGN_UP_STEPS {
OVERVIEW,
BASIC_INFO,
GITHUB_ACCOUNT,
RSS_FEEDS,
REVIEW,
}
type TelescopeAccountStatus = {
error?: boolean;
created?: boolean;
};
const {
firstName,
lastName,
displayName,
githubUsername,
github,
githubOwnership,
blogUrl,
feeds,
allFeeds,
email,
blogOwnership,
} = formModels;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
padding: '0',
margin: '0',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
width: '100vw',
boxSizing: 'border-box',
position: 'relative',
fontSize: '1.1rem',
},
imageContainer: {
minHeight: '100vh',
width: '100vw',
position: 'absolute',
top: '0',
bottom: '0',
zIndex: -1,
[theme.breakpoints.down(600)]: {
display: 'none',
},
},
signUpContainer: {
margin: '1% 0 1% 0',
display: 'grid',
gridTemplateRows: '10% 90%',
gridGap: '2%',
justifyItems: 'center',
fontFamily: 'Spartan',
height: '510px',
width: '510px',
padding: '1%',
borderRadius: '5px',
boxShadow: '2px 4px 4px 1px rgba(0, 0, 0, 0.1)',
background: '#ECF5FE',
'@media (max-height: 500px) and (max-width: 1024px)': {
margin: '0 0 65px 0',
},
[theme.breakpoints.down(600)]: {
background: 'none',
boxShadow: 'none',
minHeight: '650px',
position: 'absolute',
top: '0px',
width: '100%',
margin: '0',
padding: '0',
gridTemplateRows: '8% 92%',
},
},
title: {
color: '#121D59',
fontSize: '22px',
},
infoContainer: {
width: '100%',
position: 'relative',
},
buttonsWrapper: {
margin: '30px auto',
width: '50%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
button: {
height: '4rem',
width: 'auto',
fontSize: '1.1em',
padding: '0.7em',
margin: '5px',
background: '#E0C05A',
'&:hover': {
color: 'black',
background: '#EBD898',
},
'& .MuiButton-root': {
minWidth: 'none',
},
},
buttonLogin: {
height: '4rem',
width: '40%',
fontSize: '1.1em',
padding: '0.7em',
margin: '5px',
background: '#FF0000',
color: '#FFF',
'&:hover': {
background: '#FF7070',
},
},
homeButton: {
zIndex: 3000,
width: '120px',
position: 'absolute',
top: '2vh',
right: '50px',
[theme.breakpoints.down(600)]: {
top: '590px',
right: 'calc(50% - 60px)',
margin: '25px 0px',
},
},
text: {
textAlign: 'center',
fontSize: '0.9em',
color: '#474747',
},
})
);
const SignUpPage = () => {
const classes = useStyles();
const [activeStep, setActiveStep] = useState(SIGN_UP_STEPS.OVERVIEW);
const currentSchema = formSchema[activeStep];
const { user, token, login, register } = useAuth();
const [loggedIn, setLoggedIn] = useState(!!user);
const [telescopeAccount, setTelescopeAccount] = useState<TelescopeAccountStatus>({});
const [loading, setLoading] = useState(false);
const router = useRouter();
const handleNext = useCallback(() => {
setActiveStep(activeStep + 1);
}, [activeStep]);
const handlePrevious = useCallback(() => {
if (activeStep > 1) setActiveStep(activeStep - 1);
}, [activeStep]);
useEffect(() => {
if (user) {
setLoggedIn(true);
handleNext();
}
}, [handleNext, user]);
const handleSubmit = async (values: SignUpForm, actions: FormikHelpers<SignUpForm>) => {
if (activeStep < 4) {
handleNext();
actions.setTouched({});
actions.setSubmitting(false);
return;
}
try {
const telescopeUser = {
firstName: values.firstName,
lastName: values.lastName,
email: values.email,
displayName: values.displayName,
github: values.github,
feeds: values.feeds,
};
setLoading(true);
const response = await fetch(`${authServiceUrl}/register`, {
method: 'POST',
headers: {
Authorization: `bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(telescopeUser),
});
if (!response.ok) {
setTelescopeAccount({ error: true });
throw new Error(response.statusText);
}
const result = await response.json();
register(result.token);
setTelescopeAccount({ created: true });
handleNext();
return;
} catch (err) {
console.error(err, 'Unable to Post');
}
};
const renderForm = () => {
switch (activeStep) {
case SIGN_UP_STEPS.OVERVIEW:
return <Overview />;
case SIGN_UP_STEPS.BASIC_INFO:
return <BasicInfo />;
case SIGN_UP_STEPS.GITHUB_ACCOUNT:
return <GitHubAccount />;
case SIGN_UP_STEPS.RSS_FEEDS:
return <RSSFeeds />;
case SIGN_UP_STEPS.REVIEW:
return <Review />;
default:
return null;
}
};
// In this case, 'loading' is being used not to let an already telescope user start a signup flow again.
if (user?.isRegistered && !loading)
return (
<>
<div className={classes.imageContainer}>
<DynamicImage />
</div>
<PopUp
messageTitle="Telescope"
message={`Hi ${user?.name} you already have a Telescope account.`}
agreeAction={() => router.push('/')}
agreeButtonText="Ok"
/>
</>
);
if (telescopeAccount.error)
return (
<>
<div className={classes.imageContainer}>
<DynamicImage />
</div>
<PopUp
messageTitle="Telescope"
message={`Hi ${user?.name} there was a problem creating your account. Please try again later or contact us on our Slack channel.`}
agreeAction={() => router.push('/')}
agreeButtonText="Ok"
/>
</>
);
if (telescopeAccount.created)
return (
<>
<div className={classes.imageContainer}>
<DynamicImage />
</div>
<PopUp
messageTitle="Welcome to Telescope"
message={`Hello ${user?.name} your Telescope account was created.`}
agreeAction={() => router.push('/')}
agreeButtonText="Ok"
/>
</>
);
return (
<>
<Button
className={classes.homeButton}
variant="contained"
onClick={() => {
router.push('/');
}}
>
BACK TO HOME
</Button>
<div className={classes.root}>
<div className={classes.imageContainer}>
<DynamicImage />
</div>
{!loading && !user?.isRegistered ? (
<div className={classes.signUpContainer}>
<h1 className={classes.title}>Telescope Account</h1>
<Formik
enableReinitialize
onSubmit={handleSubmit}
validationSchema={currentSchema}
initialValues={
{
[firstName.name]: user?.firstName,
[lastName.name]: user?.lastName,
[displayName.name]: user?.name,
[email.name]: user?.email,
[githubUsername.name]: '',
[githubOwnership.name]: false,
[github.name]: {
username: '',
avatarUrl: '',
},
[blogUrl.name]: 'https://',
[feeds.name]: [] as Array<string>,
[allFeeds.name]: [] as Array<string>,
[blogOwnership.name]: false,
} as SignUpForm
}
>
{({ isSubmitting }) => (
<>
<Form autoComplete="off" className={classes.infoContainer}>
{renderForm()}
{!loggedIn && (
<div className={classes.text}>
<h3>Click LOGIN to start creating your Telescope Account.</h3>
</div>
)}
<div className={classes.buttonsWrapper}>
{activeStep === 0 && (
<Button className={classes.buttonLogin} onClick={() => login('/signup')}>
Login
</Button>
)}
{activeStep > 1 && loggedIn && (
<Button className={classes.button} onClick={handlePrevious}>
Previous
</Button>
)}
{activeStep > 0 && loggedIn && (
<Button className={classes.button} type="submit" disabled={isSubmitting}>
{activeStep === 4 ? 'Confirm' : 'Next'}
</Button>
)}
</div>
</Form>
</>
)}
</Formik>
</div>
) : (
<Spinner />
)}
</div>
</>
);
};
export default SignUpPage; | the_stack |
import * as path from "path";
import * as fs from "fs";
import * as os from "os";
import * as nls from "vscode-nls";
import { ILogger } from "../log/LogHelper";
import { CommandExecutor } from "../../common/commandExecutor";
import { ChildProcess, ISpawnResult } from "../../common/node/childProcess";
import { PromiseUtil } from "../../common/node/promise";
import { IDebuggableMobileTarget } from "../mobileTarget";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
// See android versions usage at: http://developer.android.com/about/dashboards/index.html
export enum AndroidAPILevel {
Marshmallow = 23,
LOLLIPOP_MR1 = 22,
LOLLIPOP = 21 /* Supports adb reverse */,
KITKAT = 19,
JELLY_BEAN_MR2 = 18,
JELLY_BEAN_MR1 = 17,
JELLY_BEAN = 16,
ICE_CREAM_SANDWICH_MR1 = 15,
GINGERBREAD_MR1 = 10,
}
enum KeyEvents {
KEYCODE_BACK = 4,
KEYCODE_DPAD_UP = 19,
KEYCODE_DPAD_DOWN = 20,
KEYCODE_DPAD_CENTER = 23,
KEYCODE_MENU = 82,
}
export class AdbHelper {
private nodeModulesRoot: string;
private launchActivity: string;
private childProcess: ChildProcess = new ChildProcess();
private commandExecutor: CommandExecutor;
private adbExecutable: string = "";
private static readonly AndroidRemoteTargetPattern =
/^((?:\d{1,3}\.){3}\d{1,3}:\d{1,5}|.*_adb-tls-con{2}ect\._tcp.*)$/gm;
public static readonly AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/;
constructor(
projectRoot: string,
nodeModulesRoot: string,
logger?: ILogger,
launchActivity: string = "MainActivity",
) {
this.nodeModulesRoot = nodeModulesRoot;
this.adbExecutable = this.getAdbPath(projectRoot, logger);
this.commandExecutor = new CommandExecutor(this.nodeModulesRoot);
this.launchActivity = launchActivity;
}
/**
* Gets the list of Android connected devices and emulators.
*/
public async getConnectedTargets(): Promise<IDebuggableMobileTarget[]> {
const output = await this.childProcess.execToString(`${this.adbExecutable} devices`);
return this.parseConnectedTargets(output);
}
public async findOnlineTargetById(
targetId: string,
): Promise<IDebuggableMobileTarget | undefined> {
return (await this.getOnlineTargets()).find(target => target.id === targetId);
}
public async getAvdsNames(): Promise<string[]> {
const res = await this.childProcess.execToString("emulator -list-avds");
let emulatorsNames: string[] = [];
if (res) {
emulatorsNames = res.split(/\r?\n|\r/g);
const indexOfBlank = emulatorsNames.indexOf("");
if (indexOfBlank >= 0) {
emulatorsNames.splice(indexOfBlank, 1);
}
}
return emulatorsNames;
}
public isRemoteTarget(id: string): boolean {
return !!id.match(AdbHelper.AndroidRemoteTargetPattern);
}
public async getAvdNameById(emulatorId: string): Promise<string | null> {
try {
const output = await this.childProcess.execToString(
`${this.adbExecutable} -s ${emulatorId} emu avd name`,
);
// The command returns the name of avd by id of this running emulator.
// Return value example:
// "
// emuName
// OK
// "
return output ? output.split(/\r?\n|\r/g)[0] : null;
} catch {
// If the command returned an error, it means that we could not find the emulator with the passed id
return null;
}
}
public setLaunchActivity(launchActivity: string): void {
this.launchActivity = launchActivity;
}
/**
* Broadcasts an intent to reload the application in debug mode.
*/
public async switchDebugMode(
projectRoot: string,
packageName: string,
enable: boolean,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const enableDebugCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${String(enable)}`;
await new CommandExecutor(this.nodeModulesRoot, projectRoot).execute(enableDebugCommand);
// We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up
await PromiseUtil.delay(200); // We need a little delay after broadcast command
await this.stopApp(projectRoot, packageName, debugTarget, appIdSuffix);
return this.launchApp(projectRoot, packageName, debugTarget, appIdSuffix);
}
/**
* Sends an intent which launches the main activity of the application.
*/
public launchApp(
projectRoot: string,
packageName: string,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const launchAppCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am start -n ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}/${packageName}.${
this.launchActivity
}`;
return new CommandExecutor(projectRoot).execute(launchAppCommand);
}
public stopApp(
projectRoot: string,
packageName: string,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const stopAppCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am force-stop ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}`;
return new CommandExecutor(projectRoot).execute(stopAppCommand);
}
public async apiVersion(deviceId: string): Promise<AndroidAPILevel> {
const output = await this.executeQuery(deviceId, "shell getprop ro.build.version.sdk");
return parseInt(output, 10);
}
public reverseAdb(deviceId: string, port: number): Promise<void> {
return this.execute(deviceId, `reverse tcp:${port} tcp:${port}`);
}
public showDevMenu(deviceId?: string): Promise<void> {
const command = `${this.adbExecutable} ${
deviceId ? `-s ${deviceId}` : ""
} shell input keyevent ${KeyEvents.KEYCODE_MENU}`;
return this.commandExecutor.execute(command);
}
public reloadApp(deviceId?: string): Promise<void> {
const command = `${this.adbExecutable} ${
deviceId ? `-s ${deviceId}` : ""
} shell input text "RR"`;
return this.commandExecutor.execute(command);
}
public async getOnlineTargets(): Promise<IDebuggableMobileTarget[]> {
const devices = await this.getConnectedTargets();
return devices.filter(device => device.isOnline);
}
public startLogCat(adbParameters: string[]): ISpawnResult {
return this.childProcess.spawn(this.adbExecutable.replace(/"/g, ""), adbParameters);
}
public parseSdkLocation(fileContent: string, logger?: ILogger): string | null {
const matches = fileContent.match(/^sdk\.dir\s*=(.+)$/m);
if (!matches || !matches[1]) {
if (logger) {
logger.info(
localize(
"NoSdkDirFoundInLocalPropertiesFile",
"No sdk.dir value found in local.properties file. Using Android SDK location from PATH.",
),
);
}
return null;
}
let sdkLocation = matches[1].trim();
if (os.platform() === "win32") {
// For Windows we need to unescape files separators and drive letter separators
sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":");
}
if (logger) {
logger.info(
localize(
"UsindAndroidSDKLocationDefinedInLocalPropertiesFile",
"Using Android SDK location defined in android/local.properties file: {0}.",
sdkLocation,
),
);
}
return sdkLocation;
}
public getAdbPath(projectRoot: string, logger?: ILogger): string {
// Trying to read sdk location from local.properties file and if we succueded then
// we would run adb from inside it, otherwise we would rely to PATH
const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger);
return sdkLocation ? `"${path.join(sdkLocation, "platform-tools", "adb")}"` : "adb";
}
public executeShellCommand(deviceId: string, command: string): Promise<string> {
return this.executeQuery(deviceId, `shell "${command}"`);
}
public executeQuery(deviceId: string, command: string): Promise<string> {
return this.childProcess.execToString(this.generateCommandForTarget(deviceId, command));
}
private parseConnectedTargets(input: string): IDebuggableMobileTarget[] {
const result: IDebuggableMobileTarget[] = [];
const regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg");
let match = regex.exec(input);
while (match != null) {
result.push({
id: match[1],
isOnline: match[2] === "device",
isVirtualTarget: this.isVirtualTarget(match[1]),
});
match = regex.exec(input);
}
return result;
}
public isVirtualTarget(id: string): boolean {
return !!id.match(AdbHelper.AndroidSDKEmulatorPattern);
}
private execute(deviceId: string, command: string): Promise<void> {
return this.commandExecutor.execute(this.generateCommandForTarget(deviceId, command));
}
private generateCommandForTarget(deviceId: string, adbCommand: string): string {
return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`;
}
private getSdkLocationFromLocalPropertiesFile(
projectRoot: string,
logger?: ILogger,
): string | null {
const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties");
if (!fs.existsSync(localPropertiesFilePath)) {
if (logger) {
logger.info(
localize(
"LocalPropertiesFileDoesNotExist",
"local.properties file doesn't exist. Using Android SDK location from PATH.",
),
);
}
return null;
}
let fileContent: string;
try {
fileContent = fs.readFileSync(localPropertiesFilePath).toString();
} catch (e) {
if (logger) {
logger.error(
localize(
"CouldNotReadFrom",
"Couldn't read from {0}.",
localPropertiesFilePath,
),
e,
e.stack,
);
logger.info(
localize(
"UsingAndroidSDKLocationFromPATH",
"Using Android SDK location from PATH.",
),
);
}
return null;
}
return this.parseSdkLocation(fileContent, logger);
}
} | the_stack |
declare namespace Selectize {
// see https://github.com/brianreavis/selectize.js/blob/master/docs/usage.md
// option identifiers are parameterized by T; data is parameterized by U
interface IOptions<T, U> {
// General
// ------------------------------------------------------------------------------------------------------------
/**
* An array of the initial selected values. By default this is populated from the original input element.
*/
items?: T[] | undefined;
/**
* The placeholder of the control (displayed when nothing is selected / typed).
* Defaults to input element's placeholder, unless this one is specified.
*/
placeholder?: string | undefined;
/**
* The string to separate items by. This option is only used when Selectize is instantiated from a
* <input type="text"> element.
*
* Default: ','
*/
delimiter?: string | undefined;
/**
* Enable or disable international character support.
*
* Default: true
*/
diacritics?: boolean | undefined;
/**
* Allows the user to create a new items that aren't in the list of options.
* This option can be any of the following: "true", "false" (disabled), or a function that accepts two
* arguments: "input" and "callback". The callback should be invoked with the final data for the option.
*
* Default: false
*/
create?: any;
/**
* If true, when user exits the field (clicks outside of input or presses ESC) new option is created and
* selected (if `create`-option is enabled).
*
* Default: false
*/
createOnBlur?: boolean | undefined;
/**
* Specifies a RegExp or String containing a regular expression that the current search filter must match to
* be allowed to be created. May also be a predicate function that takes the filter text and returns whether
* it is allowed.
*
* Default: null
*/
createFilter?: any;
/**
* Toggles match highlighting within the dropdown menu.
*
* Default: true
*/
highlight?: boolean | undefined;
/**
* If false, items created by the user will not show up as available options once they are unselected.
*
* Default: true
*/
persist?: boolean | undefined;
/**
* Show the dropdown immediately when the control receives focus.
*
* Default: true
*/
openOnFocus?: boolean | undefined;
/**
* The max number of items to render at once in the dropdown list of options.
*
* Default: 1000
*/
maxOptions?: number | undefined;
/**
* The max number of items the user can select.
*
* Default: Infinity
*/
maxItems?: number | undefined;
/**
* If true, the items that are currently selected will not be shown in the dropdown list of available options.
*
* Default: false
*/
hideSelected?: boolean | undefined;
/**
* If true, the dropdown will be closed after a selection is made.
*
* Default: false
*/
closeAfterSelect?: boolean | undefined;
/**
* If true, Selectize will treat any options with a "" value like normal. This defaults to false to
* accomodate the common <select> practice of having the first empty option act as a placeholder.
*
* Default: false
*/
allowEmptyOption?: boolean | undefined;
/**
* The animation duration (in milliseconds) of the scroll animation triggered when going [up] and [down] in
* the options dropdown.
*
* Default: 60
*/
scrollDuration?: number | undefined;
/**
* The number of milliseconds to wait before requesting options from the server or null.
* If null, throttling is disabled.
*
* Default: 300
*/
loadThrottle?: number | undefined;
/**
* If true, the "load" function will be called upon control initialization (with an empty search).
* Alternatively it can be set to "focus" to call the "load" function when control receives focus.
*
* Default: false
*/
preload?: boolean | 'focus' | undefined;
/**
* The element the dropdown menu is appended to. This should be "body" or null.
* If null, the dropdown will be appended as a child of the selectize control.
*
* Default: null
*/
dropdownParent?: string | undefined;
/**
* Sets if the "Add..." option should be the default selection in the dropdown.
*
* Default: false
*/
addPrecedence?: boolean | undefined;
/**
* If true, the tab key will choose the currently selected item.
*
* Default: false
*/
selectOnTab?: boolean | undefined;
/**
* Plugins to use
*
* Default: null
*/
plugins?: string[] | IPluginOption[] | { [name: string]: any } | undefined;
// Data / Searching
// ------------------------------------------------------------------------------------------------------------
/**
* Options available to select; array of objects. If your element is <select> with <option>s specified this
* property gets populated accordingly. Setting this property is convenient if you have your data as an
* array and want to automatically generate the <option>s.
*
* Default: []
*/
options?: U[] | undefined;
/**
* The <option> attribute from which to read JSON data about the option.
*
* Default: "data-data"
*/
dataAttr?: string | undefined;
/**
* The name of the property to use as the "value" when an item is selected.
*
* Default: "value"
*/
valueField?: string | undefined;
/**
* Option groups that options will be bucketed into.
* If your element is a <select> with <optgroup>s this property gets populated automatically.
* Make sure each object in the array has a property named whatever "optgroupValueField" is set to.
*/
optgroups?: U[] | undefined;
/**
* The name of the option group property that serves as its unique identifier.
*
* Default: "value"
*/
optgroupValueField?: string | undefined;
/**
* The name of the property to render as an option / item label (not needed when custom rendering
* functions are defined).
*
* Default: "text"
*/
labelField?: string | undefined;
/**
* The name of the property to render as an option group label (not needed when custom rendering
* functions are defined).
*
* Default: "label"
*/
optgroupLabelField?: string | undefined;
/**
* The name of the property to group items by.
*
* Default: "optgroup"
*/
optgroupField?: string | undefined;
/**
* The name of the property to disabled option and optgroup.
*
* Default: 'disabled'
*/
disabledField?: string | undefined;
/**
* A single field or an array of fields to sort by. Each item in the array should be an object containing at
* least a "field" property. Optionally, "direction" can be set to "asc" or "desc". The order of the array
* defines the sort precedence.
*
* Unless present, a special "$score" field will be automatically added to the beginning of the sort list.
* This will make results sorted primarily by match quality (descending).
*
* Default: "$order"
*/
sortField?: string | { field: string, direction?: 'asc' | 'desc' | undefined }[] | undefined;
/**
* An array of property names to analyze when filtering options.
*
* Default: ["text"]
*/
searchField?: string | string[] | undefined;
/**
* When searching for multiple terms (separated by a space), this is the operator used. Can be "and" or "or".
*
* Default: "and"
*/
searchConjunction?: string | undefined;
/**
* If truthy, Selectize will make all optgroups be in the same order as they were added (by the `$order`
* property). Otherwise, it will order based on the score of the results in each.
*
* Default: false
*/
lockOptgroupOrder?: boolean | undefined;
/**
* An array of optgroup values that indicates the order they should be listed in in the dropdown.
* If not provided, groups will be ordered by the ranking of the options within them.
*
* Default: null
*/
optgroupOrder?: string[] | undefined;
/**
* Copy the original input classes to the Dropdown element.
*
* Default: true
*/
copyClassesToDropdown?: boolean | undefined;
// Callbacks
// ------------------------------------------------------------------------------------------------------------
/**
* Invoked when new options should be loaded from the server.
*/
load?(query: string, callback: Function): any;
/**
* Overrides the scoring function used to sort available options. The provided function should return a
* function that returns a number greater than or equal to zero to represent the "score" of an item
* (the function's first argument). If 0, the option is declared not a match.
*/
score?(search: ISearch): (item: any) => number;
/**
* Invoked once the control is completely initialized.
*/
onInitialize?(): any;
/**
* Invoked when the control gains focus.
*/
onFocus?(): any;
/**
* Invoked when the control loses focus.
*/
onBlur?(): any;
/**
* Invoked when the value of the control changes.
*
* If single select, value is of type T.
* If multi select, value is of type T[].
*/
onChange?(value: any): any;
/**
* Invoked when an item is selected.
*/
onItemAdd?(value: T, item: JQuery): any;
/**
* Invoked when an item is deselected.
*/
onItemRemove?(value: T): any;
/**
* Invoked when the control is manually cleared via the clear() method.
*/
onClear?(): any;
/**
* Invoked when the user attempts to delete the current selection.
*/
onDelete?(values: T[]): any;
/**
* Invoked when a new option is added to the available options list.
*/
onOptionAdd?(value: T, data: U): any;
/**
* Invoked when an option is removed from the available options.
*/
onOptionRemove?(value: T): any;
/**
* Invoked when the dropdown opens.
*/
onDropdownOpen?(dropdown: JQuery): any;
/**
* Invoked when the dropdown closes.
*/
onDropdownClose?(dropdown: JQuery): any;
/**
* Invoked when the user types while filtering options.
*/
onType?(srt: string): any;
/**
* Invoked when new options have been loaded and added to the control (via the "load" option or "load" API method).
*/
onLoad?(data: U[]): any;
// Rendering
// ------------------------------------------------------------------------------------------------------------
render?: ICustomRenderers<U> | undefined;
}
/**
* Custom rendering functions. Each function should accept two arguments: "data" and "escape" and return
* HTML (string) with a single root element. The "escape" argument is a function that takes a string and
* escapes all special HTML characters. This is very important to use to prevent XSS vulnerabilities.
*/
interface ICustomRenderers<U> {
// An option in the dropdown list of available options.
option?(data: U, escape: (input: string) => string): string;
// An item the user has selected.
item?(data: U, escape: (input: string) => string): string;
// The "create new" option at the bottom of the dropdown. The data contains one property: "input"
// (which is what the user has typed).
option_create?(data: U, escape: (input: string) => string): string;
// The header of an option group.
optgroup_header?(data: U, escape: (input: string) => string): string;
// The wrapper for an optgroup. The "html" property in the data will be the raw html of the optgroup's header
// and options.
optgroup?(data: U, escape: (input: string) => string): string;
}
// see https://github.com/brianreavis/selectize.js/blob/master/docs/api.md
interface IApi<T, U> {
/**
* An array of selected values.
*/
items: T[];
/**
* An object containing the entire pool of options. The object is keyed by each object's value.
*/
options: { [value: string]: U };
// Dropdown Options
// ------------------------------------------------------------------------------------------------------------
/**
* Adds an available option. If it already exists, nothing will happen.
* Note: this does not refresh the options list dropdown (use refreshOptions() for that).
*/
addOption(data: U): void;
/**
* Updates an option available for selection. If it is visible in the selected items or options dropdown,
* it will be re-rendered automatically.
*/
updateOption(value: T, data: U): void;
/**
* Removes the option identified by the given value.
*/
removeOption(value: T): void;
/**
* Removes all options from the control.
*/
clearOptions(): void;
/**
* Retrieves the jQuery element for the option identified by the given value.
*/
getOption(value: T): JQuery;
/**
* Retrieves the jQuery element for the previous or next option, relative to the currently highlighted option.
* The "direction" argument should be 1 for "next" or -1 for "previous".
*/
getAdjacentOption(value: T, direction: number): void;
/**
* Refreshes the list of available options shown in the autocomplete dropdown menu.
*/
refreshOptions(triggerDropdown: boolean): void;
// Selected Items
// ------------------------------------------------------------------------------------------------------------
/**
* Resets / clears all selected items from the control.
*/
clear(silent?: boolean): void;
/**
* Returns the jQuery element of the item matching the given value.
*/
getItem(value: T): JQuery;
/**
* "Selects" an item. Adds it to the list at the current caret position.
*/
addItem(value: T, silent?: boolean): void;
/**
* Removes the selected item matching the provided value.
*/
removeItem(value: T, silent?: boolean): void;
/**
* Invokes the "create" method provided in the selectize options that should provide the data for the
* new item, given the user input. Once this completes, it will be added to the item list.
*/
createItem(value: T, triggerDropdown?: boolean, callback?: (data?: any) => void): void;
/**
* Re-renders the selected item lists.
*/
refreshItems(): void;
// Optgroups
// ------------------------------------------------------------------------------------------------------------
/**
* Registers a new optgroup for options to be bucketed into.
* The "id" argument refers to a value of the property in option identified by the "optgroupField" setting.
*/
addOptionGroup(id: string, data: U): void;
// Events
// ------------------------------------------------------------------------------------------------------------
/**
* Adds an event listener.
*/
on(eventName: string, handler: Function): void;
/**
* Removes an event listener. If no handler is provided, all event listeners are removed.
*/
off(eventName: string, handler?: Function): void;
/**
* Triggers event listeners.
*/
trigger(eventName: string, ...args: any[]): void;
// Dropdown Actions
// ------------------------------------------------------------------------------------------------------------
/**
* Shows the autocomplete dropdown containing the available options.
*/
open(): void;
/**
* Closes the autocomplete dropdown menu.
*/
close(): void;
/**
* Calculates and applies the appropriate position of the dropdown.
*/
positionDropdown(): void;
// Other
// ------------------------------------------------------------------------------------------------------------
/**
* Destroys the control and unbinds event listeners so that it can be garbage collected.
*/
destroy(): void;
/**
* Loads options by invoking the the provided function. The function should accept one argument (callback)
* and invoke the callback with the results once they are available.
*/
load(callback: (results: any) => any): void;
/**
* Brings the control into focus.
*/
focus(): void;
/**
* Forces the control out of focus.
*/
blur(): void;
/**
* Disables user input on the control (note: the control can still receive focus).
*/
lock(): void;
/**
* Re-enables user input on the control.
*/
unlock(): void;
/**
* Disables user input on the control completely. While disabled, it cannot receive focus.
*/
disable(): void;
/**
* Enables the control so that it can respond to focus and user input.
*/
enable(): void;
/**
* Returns the value of the control. If multiple items can be selected (e.g. <select multiple>), this
* returns an array. If only one item can be selected, this returns a string.
*/
getValue(): any;
/**
* Resets the selected items to the given value(s).
*/
setValue(value: T, silent?: boolean): void;
setValue(value: T[], silent?: boolean): void;
/**
* Moves the caret to the specified position ("index" being the index in the list of selected items).
*/
setCaret(index: number): void;
/**
* Returns whether or not the user can select more items.
*/
isFull(): boolean;
/**
* Clears the render cache. Takes an optional template argument (e.g. "option", "item") to clear only that cache.
*/
clearCache(template?: string): void;
/**
* When the `settings.placeholder` value is changed, the new placeholder will be displayed.
*/
updatePlaceholder(): void;
}
interface ISearchToken {
regex: RegExp;
string: string;
}
interface ISearchResult {
id: string;
score: number;
}
interface ISearch {
/**
* Original search options.
*/
options: any;
/**
* The raw user input
*/
query: string;
/**
* An array containing parsed search tokens. A token is an object containing two properties: "string" and "regex".
*/
tokens: ISearchToken[];
/**
* The total number of results.
*/
total: number;
/**
* A list of matched results. Each result is an object containing two properties: "score" and "id".
*/
items: ISearchResult[];
}
// see https://github.com/selectize/selectize.js/blob/master/docs/plugins.md
interface IPluginOption {
name: string;
options: any;
}
}
interface JQuery {
selectize(options?: Selectize.IOptions<any, any>): JQuery;
}
interface HTMLElement {
selectize: Selectize.IApi<any, any>;
} | the_stack |
import { assert } from "chai";
import * as Plottable from "../../src";
describe("Formatters", () => {
describe("fixed()", () => {
it("shows correct amount of digits according to precision", () => {
const fixed3 = Plottable.Formatters.fixed();
assert.strictEqual(fixed3(1), "1.000", "shows three decimal places by defalut");
assert.strictEqual(fixed3(-1), "-1.000", "shows three decimal places for negative integer");
assert.strictEqual(fixed3(1.234), "1.234", "shows three decimal places for float");
assert.strictEqual(fixed3(-1.234), "-1.234", "shows three decimal placesfor for negative float");
assert.strictEqual(fixed3(1.2346111111), "1.235", "shows three decimal places for long float");
assert.strictEqual(fixed3(-1.2346111111), "-1.235", "shows three decimal places for long negatvie float");
assert.strictEqual(fixed3(123), "123.000", "shows three decimal places for integer");
assert.strictEqual(fixed3(Infinity), "Infinity", "formats non-numeric number correctly");
assert.strictEqual(fixed3(-Infinity), "-Infinity", "formats non-numeric number correctly");
assert.strictEqual(fixed3(NaN), "NaN", "formats non-numeric number correctly");
const fixed0 = Plottable.Formatters.fixed(0);
assert.strictEqual(fixed0(1), "1", "shows no decimal places for integer");
assert.strictEqual(fixed0(-1), "-1", "shows no decimal places for negative integer");
assert.strictEqual(fixed0(1.23), "1", "shows no decimal places for float");
assert.strictEqual(fixed0(-1.23), "-1", "shows no decimal places for negative float");
assert.strictEqual(fixed0(123.456), "123", "shows no decimal places for integer");
});
it.skip("throws exception for non-numeric values", () => {
const nonNumericValues = [null, undefined, "123", "abc", ""];
const fixed = Plottable.Formatters.fixed();
nonNumericValues.forEach((value) =>
(<any> assert).throws(() => fixed(<any> value), Error,
"error message TBD", `${value} is not a valid value for Formatter.fixed`),
);
});
it("throws exception for invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.fixed(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.fixed(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
});
describe("general()", () => {
it("shows correct amount of digits according to precision", () => {
const general3 = Plottable.Formatters.general();
assert.strictEqual(general3(1), "1", "does not pad 0 to three decimal places");
assert.strictEqual(general3(-1), "-1", "does not pad 0 to three decimal places");
assert.strictEqual(general3(1.234), "1.234", "shows up to three decimal places");
assert.strictEqual(general3(-1.234), "-1.234", "shows up to three decimal places");
assert.strictEqual(general3(1.2346), "1.235", "shows up to three decimal places");
assert.strictEqual(general3(-1.2346), "-1.235", "shows up to three decimal places");
const general2 = Plottable.Formatters.general(2);
assert.strictEqual(general2(1), "1", "does not pad 0 to two decimal places");
assert.strictEqual(general2(-1), "-1", "does not pad 0 to two decimal places");
assert.strictEqual(general2(1.2), "1.2", "does not pad 0 to two decimal places");
assert.strictEqual(general2(-1.2), "-1.2", "does not pad 0 to two decimal places");
assert.strictEqual(general2(1.23), "1.23", "shows up to two decimal places");
assert.strictEqual(general2(-1.23), "-1.23", "shows up to two decimal places");
assert.strictEqual(general2(1.235), "1.24", "shows up to two decimal places");
assert.strictEqual(general2(-1.235), "-1.24", "shows up to two decimal places");
const general0 = Plottable.Formatters.general(0);
assert.strictEqual(general0(1), "1", "shows no decimals");
assert.strictEqual(general0(1.535), "2", "shows no decimals");
});
it("stringifies non-numeric values", () => {
const general = Plottable.Formatters.general();
const nonNumericValues = [null, undefined, Infinity, -Infinity, NaN, "123", "abc"];
const stringifiedValues = ["null", "undefined", "Infinity", "-Infinity", "NaN", "123", "abc"];
nonNumericValues.forEach((value, i) =>
assert.strictEqual(general(value), stringifiedValues[i], `non-numeric input ${value} is stringified`),
);
});
it("throws an error on invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.general(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.general(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
});
describe("identity()", () => {
it("stringifies inputs", () => {
const identity = Plottable.Formatters.identity();
const values = [1, 0.999999, null, undefined, Infinity, -Infinity, NaN, "123", "abc", ""];
const stringifiedValues = ["1", "0.999999", "null", "undefined", "Infinity", "-Infinity", "NaN", "123", "abc", ""];
values.forEach((value, i) =>
assert.strictEqual(identity(value), stringifiedValues[i], `${value} is stringified`),
);
});
});
describe("currency()", () => {
it("formats values based on precision, symobl, and prefix correctly", () => {
const defaultFormatter = Plottable.Formatters.currency();
assert.strictEqual(defaultFormatter(1), "$1.00", "formatted correctly with default \"$\" prefix");
assert.strictEqual(defaultFormatter(-1), "-$1.00", "formatted negative integer correctly with default \"$\" prefix");
assert.strictEqual(defaultFormatter(1.999), "$2.00", "formatted correctly with default \"$\" prefix");
assert.strictEqual(defaultFormatter(-1.234), "-$1.23", "formatted negative float correctly with default \"$\" prefix");
const currencyFormatter0 = Plottable.Formatters.currency(0);
assert.strictEqual(currencyFormatter0(1.1234), "$1", "formatted with correct precision");
assert.strictEqual(currencyFormatter0(123), "$123", "formatted with correct precision");
const poundFormatter = Plottable.Formatters.currency(2, "£");
assert.strictEqual(poundFormatter(1.1234), "£1.12", "formatted with correct precision and \"£\" as prefix");
assert.strictEqual(poundFormatter(-100.987), "-£100.99", "formatted with correct precision and \"£\" as prefix");
const centsFormatter = Plottable.Formatters.currency(0, "c", false);
assert.strictEqual(centsFormatter(1), "1c", "formatted correctly with \"c\" as suffix");
assert.strictEqual(centsFormatter(-1), "-1c", "formatted correctly with \"c\" as suffix");
});
it("throws an error on invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.currency(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.currency(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
it.skip("throws exception for non-numeric values", () => {
const nonNumericValues: any[] = [null, undefined, "123", "abc", ""];
// "$0.00", "$NaN", "$123.00", "$NaN", "$0.00"
const defaultFormatter = Plottable.Formatters.currency();
nonNumericValues.forEach((value) =>
(<any> assert).throws(() => defaultFormatter(<any> value), Error,
"error message TBD", `${value} is not a valid value for Formatter.currency`),
);
});
});
describe("multiTime()", () => {
it("uses reasonable defaults", () => {
const timeFormatter = Plottable.Formatters.multiTime();
// year, month, day, hours, minutes, seconds, milliseconds
assert.strictEqual(timeFormatter(new Date(2000, 0, 1, 0, 0, 0, 0)), "2000", "only the year was displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 1, 0, 0, 0, 0)), "Mar", "only the month was displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 5, 0, 0, 0, 0)), "Mar 05", "month and date displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 2, 0, 0, 0, 0)), "Thu 02", "day and date displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 1, 20, 0, 0, 0)), "08 PM", "only hour was displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 1, 20, 34, 0, 0)), "08:34", "hour and minute was displayed");
assert.strictEqual(timeFormatter(new Date(2000, 2, 1, 20, 34, 53, 0)), ":53", "seconds was displayed");
assert.strictEqual(timeFormatter(new Date(2000, 0, 1, 0, 0, 0, 950)), ".950", "milliseconds was displayed");
});
it.skip("throws exception for non-Date values", () => {
const nonNumericValues = [null, undefined, NaN, "123", "abc", "", 0];
const timeFormatter = Plottable.Formatters.multiTime();
nonNumericValues.forEach((value) =>
(<any> assert).throws(() => timeFormatter(<any> value), Error,
"error message TBD", `${value} is not a valid value for Formatter.multiTime`),
);
});
});
describe("time()", () => {
it("defaults to local time", () => {
const formatter = Plottable.Formatters.time("%I %p");
assert.strictEqual(formatter(new Date(2000, 0, 1, 0, 0, 0, 0)), "12 AM");
});
it("formats to UTC accordingly", () => {
const formatter = Plottable.Formatters.time("%I %p", true);
assert.strictEqual(formatter(new Date(Date.UTC(2000, 0, 1, 0, 0, 0, 0))), "12 AM");
});
});
describe("percentage()", () => {
it("formats number to percetage with correct precision", () => {
const percentFormatter = Plottable.Formatters.percentage();
assert.strictEqual(percentFormatter(1), "100%",
"the value was multiplied by 100, a percent sign was appended, and no decimal places are shown by default");
assert.strictEqual(percentFormatter(0.07), "7%", "does not have trailing zeros and is not empty string");
assert.strictEqual(percentFormatter(-0.355), "-36%", "negative values are formatted correctly");
assert.strictEqual(percentFormatter(50), "5000%", "formats 2 digit integer correctly");
const twoPercentFormatter = Plottable.Formatters.percentage(2);
assert.strictEqual(twoPercentFormatter(0.0035), "0.35%", "works even if multiplying by 100 does not make it an integer");
assert.strictEqual(twoPercentFormatter(-0.123), "-12.30%", "add 0 padding to make precision");
});
it.skip("formats non-numeric number correctly", () => {
const percentFormatter = Plottable.Formatters.percentage();
assert.strictEqual(percentFormatter(NaN), "NaN", "stringifies non-numeric number");
assert.strictEqual(percentFormatter(Infinity), "Infinity", "stringifies non-numeric number");
assert.strictEqual(percentFormatter(-Infinity), "-Infinity", "stringifies non-numeric number");
});
it("throws an error on invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.percentage(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.percentage(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
it.skip("throws exception for non-numeric values", () => {
const nonNumericValues = [null, undefined, "123", "abc", ""];
const percentFormatter = Plottable.Formatters.percentage();
nonNumericValues.forEach((value) =>
(<any> assert).throws(() => percentFormatter(<any> value), Error,
"error message TBD", `${value} is not a valid value for Formatter.percentage`),
);
});
});
describe("siSuffix()", () => {
it("shortens long numbers", () => {
const lnFormatter = Plottable.Formatters.siSuffix();
assert.strictEqual(lnFormatter(1), "1.00", "shows 3 signifigicant figures by default");
assert.operator(lnFormatter(Math.pow(10, 12)).length, "<=", 5, "large number was formatted to a short string");
assert.operator(lnFormatter(Math.pow(10, -12)).length, "<=", 5, "small number was formatted to a short string");
assert.strictEqual(lnFormatter(Math.pow(10, 5) * 1.55555), "156k", "formatting respects precision");
assert.strictEqual(lnFormatter(-Math.pow(10, 6) * 23.456), "-23.5M", "formatting respects precision");
const lnFormatter2 = Plottable.Formatters.siSuffix(2);
assert.strictEqual(lnFormatter2(1), "1.0", "shows 2 signifigicant figures by default");
assert.strictEqual(lnFormatter2(Math.pow(10, 5) * 1.55555), "160k", "formatting respects precision");
assert.strictEqual(lnFormatter2(-Math.pow(10, 6) * 23.456), "-23M", "formatting respects precision");
});
it.skip("formats non-numeric number correctly", () => {
const lnFormatter = Plottable.Formatters.siSuffix();
assert.strictEqual(lnFormatter(NaN), "NaN", "stringifies non-numeric number");
assert.strictEqual(lnFormatter(Infinity), "Infinity", "stringifies non-numeric number");
assert.strictEqual(lnFormatter(-Infinity), "-Infinity", "stringifies non-numeric number");
});
it("throws an error on invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.siSuffix(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.siSuffix(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
it.skip("throws exception for non-numeric values", () => {
const nonNumericValues = [null, undefined, "123", "abc", ""];
const lnFormatter = Plottable.Formatters.siSuffix();
nonNumericValues.forEach((value) =>
(<any> assert).throws(() => lnFormatter(<any> value), Error,
"error message TBD", `${value} is not a valid value for Formatter.siSuffix`),
);
});
});
describe("shortScale()", () => {
it("shortens long numbers", () => {
const formatter = Plottable.Formatters.shortScale();
assert.strictEqual(formatter(1), "1.000", "small numbers format simply");
assert.strictEqual(formatter(-1), "-1.000", "negative small numbers format simply");
assert.strictEqual(formatter(2e3), "2.000K", "thousands numbers format using short scale magnitudes");
assert.strictEqual(formatter(2e6), "2.000M", "millions numbers format using short scale magnitudes");
assert.strictEqual(formatter(2e9), "2.000B", "billions numbers format using short scale magnitudes");
assert.strictEqual(formatter(2e12), "2.000T", "trillions magnitude numbers format using short scale magnitudes");
assert.strictEqual(formatter(2e15), "2.000Q", "quadrillions numbers format using short scale magnitudes");
assert.strictEqual(formatter(999.999), "999.999", "boundary cases are correct");
assert.strictEqual(formatter(999.99999), "1.000K", "rounding cases are correct");
assert.strictEqual(formatter(-999.99999), "-1.000K", "negative rounding cases are correct");
assert.strictEqual(formatter(1000000), "1.000M", "boundary cases are correct");
assert.strictEqual(formatter(999999000000000000), "999.999Q", "Largest positive short-scale representable number");
assert.strictEqual(formatter(999999400000000000), "999.999Q", "Largest positive short-scale representable number round-down");
assert.strictEqual(formatter(999999500000000000), "1.000e+18", "Largest positive short-scale non-representable number round-up");
assert.strictEqual(formatter(1e17), "100.000Q", "Last positive round short-scale representable number");
assert.strictEqual(formatter(1e18), "1.000e+18", "First positive round short-scale non-representable number");
assert.strictEqual(formatter(-999999000000000000), "-999.999Q", "Largest negative short-scale representable number");
assert.strictEqual(formatter(999999400000000000), "999.999Q", "Largest negative short-scale representable number round-down");
assert.strictEqual(formatter(999999500000000000), "1.000e+18", "Largest negative short-scale non-representable number round-up");
assert.strictEqual(formatter(-1e17), "-100.000Q", "Last negative round short-scale representable number");
assert.strictEqual(formatter(-1e18), "-1.000e+18", "First negative round short-scale non-representable number");
assert.strictEqual(formatter(0.001), "0.001", "Smallest positive short-scale representable number");
assert.strictEqual(formatter(0.0009), "9.000e-4", "Round up is not applied for very small positive numbers");
assert.strictEqual(formatter(-0.001), "-0.001", "Smallest negative short-scale representable number");
assert.strictEqual(formatter(-0.0009), "-9.000e-4", "Round up is not applied for very small negative numbers");
assert.strictEqual(formatter(0), "0.000", "0 gets formatted well");
assert.strictEqual(formatter(-0), "0.000", "-0 gets formatted well");
assert.strictEqual(formatter(Infinity), "Infinity", "Infinity edge case");
// this is actually failing because of d3 - see https://github.com/d3/d3-format/issues/42
// assert.strictEqual(formatter(-Infinity), "-Infinity", "-Infinity edge case");
assert.strictEqual(formatter(NaN), "NaN", "NaN edge case");
assert.strictEqual(formatter(1e37), "1.000e+37", "large magnitute number use scientific notation");
assert.strictEqual(formatter(1e-7), "1.000e-7", "small magnitude numbers use scientific notation");
});
it("respects the precision provided", () => {
const formatter = Plottable.Formatters.shortScale(1);
assert.strictEqual(formatter(1), "1.0", "Just one decimal digit is added");
assert.strictEqual(formatter(999), "999.0", "Conversion to K happens in the same place (lower)");
assert.strictEqual(formatter(1000), "1.0K", "Conversion to K happens in the same place (upper)");
assert.strictEqual(formatter(999900000000000000), "999.9Q", "Largest positive short-scale representable number");
assert.strictEqual(formatter(999940000000000000), "999.9Q", "Largest positive short-scale representable number round-down");
assert.strictEqual(formatter(999950000000000000), "1.0e+18", "Largest positive short-scale representable number round-up");
assert.strictEqual(formatter(-999900000000000000), "-999.9Q", "Largest negative short-scale representable number");
assert.strictEqual(formatter(-999940000000000000), "-999.9Q", "Largest negative short-scale representable number round-down");
assert.strictEqual(formatter(-999950000000000000), "-1.0e+18", "Largest negative short-scale representable number round-up");
assert.strictEqual(formatter(0.1), "0.1", "Smallest positive short-scale representable number");
assert.strictEqual(formatter(0.09), "9.0e-2", "Round up is not applied for very small positive numbers");
assert.strictEqual(formatter(-0.1), "-0.1", "Smallest negative short-scale representable number");
assert.strictEqual(formatter(-0.09), "-9.0e-2", "Round up is not applied for very small negative numbers");
assert.strictEqual(formatter(0), "0.0", "0 gets formatted well");
const formatter0 = Plottable.Formatters.shortScale(0);
assert.strictEqual(formatter0(1), "1", "Just one decimal digit is added");
assert.strictEqual(formatter0(999), "999", "Conversion to K happens in the same place (lower)");
assert.strictEqual(formatter0(1000), "1K", "Conversion to K happens in the same place (upper)");
assert.strictEqual(formatter0(999000000000000000), "999Q", "Largest positive short-scale representable number");
assert.strictEqual(formatter0(999400000000000000), "999Q", "Largest positive short-scale representable number round-down");
assert.strictEqual(formatter0(999500000000000000), "1e+18", "Largest positive short-scale representable number round-up");
assert.strictEqual(formatter0(-999000000000000000), "-999Q", "Largest negative short-scale representable number");
assert.strictEqual(formatter0(-999400000000000000), "-999Q", "Largest negative short-scale representable number round-down");
assert.strictEqual(formatter0(-999500000000000000), "-1e+18", "Largest negative short-scale representable number round-up");
assert.strictEqual(formatter0(0.9), "9e-1", "Round up is not applied for very small positive numbers");
assert.strictEqual(formatter0(0), "0", "0 gets formatted well");
});
it("throws an error on invalid precision", () => {
const nonIntegerValues = [null, 2.1, NaN, "5", "abc"];
nonIntegerValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.shortScale(<any> value), Error,
"Formatter precision must be an integer", `${value} is not a valid precision value`),
);
const outOfBoundValues = [-1, 21, -Infinity, Infinity];
outOfBoundValues.forEach((value) =>
(<any> assert).throws(() => Plottable.Formatters.shortScale(<any> value), Error,
"Formatter precision must be between 0 and 20", `${value} is not a valid precision value`),
);
});
});
}); | the_stack |
import * as path from 'path';
import * as http from 'http';
import * as findup from 'findup';
import * as express from 'express';
import * as resolveFrom from 'resolve-from';
import * as webpackDevMiddleware from 'webpack-dev-middleware';
import * as webpackHotMiddleware from 'webpack-hot-middleware';
import * as semver from 'semver';
import * as cors from 'cors';
import * as child_process from 'child_process';
import * as vm from 'vm';
import * as _l from 'lodash';
import * as MemoryFS from 'memory-fs';
import * as clc from 'cli-color';
import * as request from 'request-promise-native';
import * as bodyParser from 'body-parser';
import * as md5 from 'blueimp-md5';
import * as interpret from 'interpret';
import * as mime from 'mime-types';
import { Volume } from 'memfs'
import { ufs } from 'unionfs';
import * as fs from 'fs';
import * as util from 'util';
import {
try_to_load_user_config,
load_dev_config,
load_prod_config,
merge_configs,
override_merge_configs,
MaybeConfig,
} from './load_config';
type ProjectType = 'REACT' | 'REACT-SCRIPTS' | 'WEBPACK-REACT' | 'USES-REACT' | 'UNKNOWN';
type PartialProjectInfo = { project_type: ProjectType, root_path: (string | undefined) };
type ProjectInfo = { project_type: ProjectType, root_path: string };
type FileSearchResult = { path: string, found: true } | { found: false };
const hash_string = (str) => md5(str);
async function get_project_info(): Promise<ProjectInfo> {
const detected_project_info = await Promise.all(['package.json', 'bower.json'].map(async (filename) => {
try {
const search_result = await find_in_dir_or_ancestor(process.cwd(), filename);
if (search_result.found) {
const package_file = search_result.found ? JSON.parse(fs.readFileSync(search_result.path, 'utf8')) : {};
const root_path = search_result.found ? path.dirname(search_result.path) : undefined;
return { project_type: detect_framework(package_file), root_path };
} else {
return { project_type: <ProjectType>'UNKNOWN', root_path: undefined };
}
} catch (e) {
return { project_type: <ProjectType>'UNKNOWN', root_path: undefined }; // fail as fast as possible
}
}));
let info: PartialProjectInfo = detected_project_info.reduce((inferred: ProjectInfo, other: ProjectInfo) => (
inferred.project_type === 'UNKNOWN' ? other : inferred
), { project_type: 'UNKNOWN', root_path: undefined });
if (info === undefined) {
return { project_type: 'UNKNOWN', root_path: process.cwd() }
}
return {
project_type: info.project_type,
root_path: info.root_path || process.cwd()
};
}
export async function start_dev_server(port, config_file, override, specs_file): Promise<void> {
process.env.NODE_ENV = "development";
const project_info = await get_project_info();
process.chdir(project_info.root_path);
const compiler_data = await make_external_code_compiler({
host: `http://localhost:${port}`,
static_id: '__dev',
specs_file,
config_file,
override
}, make_dev_config);
if (compiler_data === undefined) {
throw new Error("Could not start server");
}
const { compiler, dependencies, config } = compiler_data;
const devMiddlewareOptions = {
logLevel: 'error',
noInfo: true,
publicPath: config.output.publicPath,
allowedHosts: [
'localhost',
'.pagedraw.io',
],
compress: true,
stats: 'errors-only',
};
let webpackResolve = (_): any => { };
let webpackReject = (_): any => { };
const webpackValid = new Promise((resolve, reject) => {
webpackResolve = resolve;
webpackReject = reject;
});
const router = express.Router();
const dev_middleware_instance = dependencies.devMiddleware(compiler, devMiddlewareOptions);
router.use(dev_middleware_instance);
router.use(dependencies.hotMiddleware(compiler));
dev_middleware_instance.waitUntilValid(stats => {
if (stats.toJson().errors.length > 0) {
webpackReject(stats);
} else {
webpackResolve(stats);
}
});
const app = express();
app.use(cors());
app.use(router);
app.use(bodyParser.json());
app.post('/exit_dev', (req, res) => {
process.env.NODE_ENV = "production";
const static_id = req.body.static_id;
const host = req.body.host;
const metaserver = req.body.metaserver;
if (typeof static_id !== 'string' || typeof host !== 'string' || typeof metaserver !== 'string') {
res.send(JSON.stringify({
status: 'internal-err'
}));
return;
}
make_prod_bundle(host, static_id, config_file, override, specs_file).then((data) => {
process.env.NODE_ENV = "development";
if ((<any>data).user_errors) {
res.send(JSON.stringify({
status: 'user-err'
}));
return;
}
if ((<any>data).internal_errors) {
res.send(JSON.stringify({
status: 'internal-err'
}));
return;
}
if (_l.isEmpty((<any>data).bundle)) {
console.error('Error: prod bundle cannot be empty');
res.send(JSON.stringify({
status: 'internal-err'
}));
return;
}
console.log("production bundle done. Starting upload...");
return upload_static_files(metaserver, static_id, (<any>data).static_files)
.then(() => upload_code(metaserver, static_id, (<any>data).bundle))
.then(hash => {
console.log("Upload successful.");
res.send(JSON.stringify({
status: 'ok', id: hash,
}));
}).catch((e) => {
res.send(JSON.stringify({
status: 'net-err'
}));
});
});
});
app.get('/are-you-alive', (req, res) => {
res.send('yes');
});
const server = http.createServer(app);
let serverResolve = (): any => { };
let serverReject = (_): any => { };
const serverListening = new Promise((resolve, reject) => {
serverResolve = resolve;
serverReject = reject;
});
server.listen(port, error => {
if (error) {
serverReject(error);
} else {
serverResolve();
}
});
try {
await Promise.all([webpackValid, serverListening]);
console.log(`server started on http://localhost:${port}`);
} catch (e) {
// e.toJson().errors.forEach(console.error);
}
};
// TODO: config location by project type
// TODO: show user what files are being chosen and what options are
// being applied
const make_config = (options, load_config) => {
const base_config = load_config();
let config;
if (options.config_file) {
const config_path = path.resolve(options.config_file);
const user_config_search_result: MaybeConfig = try_to_load_user_config(config_path);
if (!user_config_search_result.found) {
console.error(`ERROR: unable to load custom configuration at ${config_path}`);
return;
}
if (typeof user_config_search_result.config !== 'object') {
console.error(`ERROR: Webpack config loaded from ${config_path} is not an object.`)
console.error("Pagedraw does not yet support Webpack configurations as functions.");
return;
}
if (options.override) {
config = override_merge_configs(base_config, user_config_search_result.config)
} else {
config = merge_configs(base_config, user_config_search_result.config);
}
} else {
config = base_config;
}
return config;
};
const make_dev_config = (version, options, dependencies) =>
make_config(options, () => load_dev_config(version, dependencies, path.resolve(options.specs_file), options.host));
const make_prod_config = (version, options, dependencies) =>
make_config(options, () => load_prod_config(version, path.resolve(options.specs_file), options.host, options.static_id));
const make_external_code_compiler = async (options, make_config) => {
let webpack_path, webpack_deps, webpack_version;
try {
webpack_path = resolveFrom(process.cwd(), 'webpack');
} catch (e) {
webpack_path = require.resolve('webpack');
}
const package_search_result = await find_in_dir_or_ancestor(path.dirname(webpack_path), 'package.json');
if (!package_search_result.found) {
console.warn("Could not deduce Webpack version. Assuming Webpack 4.x.");
webpack_deps = require('pagedraw-cli-webpack4');
} else {
const package_json = JSON.parse(fs.readFileSync(package_search_result.path, 'utf8'));
webpack_version = semver.major(package_json.version);
switch (webpack_version) {
case 3:
webpack_deps = require('pagedraw-cli-webpack3');
break;
case 4:
webpack_deps = require('pagedraw-cli-webpack4');
break;
default:
console.warn(`Cannot recognize Webpack version ${package_json.version}. Falling back to Webpack 4.`);
webpack_deps = require('pagedraw-cli-webpack4');
}
}
const config = make_config(webpack_version, options, webpack_deps);
if (config === undefined) {
return;
}
const webpack = require(webpack_path);
const compiler = webpack(config);
return { compiler, dependencies: webpack_deps, config };
}
const upload_static_files = (metaserver, prefix, static_files) => {
return Promise.all(Object.keys(static_files).map((name) => {
const filetype = mime.lookup(name) || 'binary/octet-stream';
return request({
uri: `${metaserver}/sign/external_code`,
qs: {
filepath: path.join(prefix, name),
filetype,
},
}).then((res) => {
const data = JSON.parse(res);
return request({
uri: data.upload_url,
method: 'PUT',
body: static_files[name],
headers: {
'Content-Type': filetype,
},
});
}).catch((e) => {
console.log("Metaserver returned error:");
console.log(e);
});
}));
};
const upload_code = (metaserver, static_id, bundle) => {
const filename = `${static_id}/${static_id}`
return request({
uri: `${metaserver}/sign/external_code`,
qs: {
filepath: filename,
filetype: 'application/javascript'
},
}).then((res) => {
const data = JSON.parse(res);
return request({
uri: data.upload_url,
method: 'PUT',
body: bundle,
headers: {
'Content-Type': 'application/javascript',
},
});
}).then(() => filename);
}
type CompilationResult = {
user_errors: string[] | undefined,
webpack_errors: string[] | undefined,
};
const webpack_compile = (compiler): Promise<CompilationResult> => new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return resolve({ webpack_errors: [err.toString()] });
}
if (stats.hasErrors()) {
console.error('Compilation error:');
console.error(stats.toJson().errors.map(err => err.toString()));
return resolve({ user_errors: stats.toJson().errors.map(err => err.toString()) });
}
return resolve({});
});
});
export async function make_prod_bundle(host, static_id, config_file, override, specs_file) {
process.env.NODE_ENV = "production";
const project_info = await get_project_info();
const base_path = project_info.root_path;
process.chdir(base_path);
const compiler_data = await make_external_code_compiler({
host,
static_id,
specs_file,
config_file,
override
}, make_prod_config);
if (compiler_data === undefined) {
throw new Error("Could not start server");
}
const { compiler, dependencies, config } = compiler_data;
const output_filename = 'bundle.js';
const output = new MemoryFS();
compiler.outputFileSystem = output;
try {
const compiler_output = await webpack_compile(compiler);
if (compiler_output.webpack_errors) {
return { internal_errors: compiler_output.webpack_errors }
}
if (compiler_output.user_errors) {
return { user_errors: compiler_output.user_errors }
}
const bundle = output.readFileSync(path.resolve(output_filename), 'utf8');
const static_file_data = read_files_in_dir(output, process.cwd(), [output_filename]);
const static_files = _l.fromPairs(<any>static_file_data);
return { bundle, static_files };
} catch (e) {
console.error(e);
return { internal_errors: [e] }
}
};
// FIXME: This can be async and probably faster
const read_files_in_dir = (fs, root, skip) => {
const _read_files_in_dir = (fs, root, current, skip) => {
const filenames = fs.readdirSync(current);
const children = filenames.map((filename) => {
if (!skip.includes(filename)) {
const filepath = path.join(current, filename);
if (fs.statSync(filepath).isDirectory()) {
return _read_files_in_dir(fs, root, filepath, skip)
} else {
const relative_path = path.relative(root, filepath);
return [[relative_path, fs.readFileSync(filepath)]]
}
}
});
return _l.flatten(_l.compact(children));
};
return _read_files_in_dir(fs, root, root, skip);
};
const detect_framework = (package_file): ProjectType => {
const has_dependency = (package_file, property: string): boolean => (
(package_file.dependencies && package_file.dependencies[property])
|| (package_file.devDependencies && package_file.devDependencies[property])
);
const has_peer_dependency = (package_file, property: string): boolean => (
(package_file.peerDependencies && package_file.peerDependencies[property])
);
if (has_dependency(package_file, 'react-scripts')) {
return 'REACT-SCRIPTS';
}
if (has_dependency(package_file, 'react') && has_dependency(package_file, 'webpack')) {
return 'WEBPACK-REACT'
}
if (has_dependency(package_file, 'react')) {
return 'REACT';
}
if (has_peer_dependency(package_file, 'react')) {
return 'USES-REACT';
}
return 'UNKNOWN';
}
const find_in_dir_or_ancestor = (base_dir: string, filename: string): Promise<FileSearchResult> => new Promise((resolve, reject) => {
const immediate_path = path.resolve(base_dir, filename);
if (fs.existsSync(immediate_path)) {
return resolve({ path: immediate_path, found: true });
}
findup(base_dir, filename, (err, dir) => {
if (err) {
return resolve({ found: false });
}
return resolve({ path: path.join(dir, filename), found: true });
});
}); | the_stack |
import * as Common from '../../core/common/common.js';
import * as SDK from '../../core/sdk/sdk.js';
import type * as Protocol from '../../generated/protocol.js';
import * as TextUtils from '../text_utils/text_utils.js';
import * as Workspace from '../workspace/workspace.js';
import {ContentProviderBasedProject} from './ContentProviderBasedProject.js';
import type {DebuggerSourceMapping, DebuggerWorkspaceBinding, RawLocationRange} from './DebuggerWorkspaceBinding.js';
import {IgnoreListManager} from './IgnoreListManager.js';
import {NetworkProject} from './NetworkProject.js';
export class CompilerScriptMapping implements DebuggerSourceMapping {
readonly #debuggerModel: SDK.DebuggerModel.DebuggerModel;
readonly #sourceMapManager: SDK.SourceMapManager.SourceMapManager<SDK.Script.Script>;
readonly #workspace: Workspace.Workspace.WorkspaceImpl;
readonly #debuggerWorkspaceBinding: DebuggerWorkspaceBinding;
readonly #regularProject: ContentProviderBasedProject;
readonly #contentScriptsProject: ContentProviderBasedProject;
readonly #regularBindings: Map<string, Binding>;
readonly #contentScriptsBindings: Map<string, Binding>;
readonly #stubUISourceCodes: Map<SDK.Script.Script, Workspace.UISourceCode.UISourceCode>;
readonly #stubProject: ContentProviderBasedProject;
readonly #eventListeners: Common.EventTarget.EventDescriptor[];
constructor(
debuggerModel: SDK.DebuggerModel.DebuggerModel, workspace: Workspace.Workspace.WorkspaceImpl,
debuggerWorkspaceBinding: DebuggerWorkspaceBinding) {
this.#debuggerModel = debuggerModel;
this.#sourceMapManager = this.#debuggerModel.sourceMapManager();
this.#workspace = workspace;
this.#debuggerWorkspaceBinding = debuggerWorkspaceBinding;
const target = debuggerModel.target();
this.#regularProject = new ContentProviderBasedProject(
workspace, 'jsSourceMaps::' + target.id(), Workspace.Workspace.projectTypes.Network, '',
false /* isServiceProject */);
this.#contentScriptsProject = new ContentProviderBasedProject(
workspace, 'jsSourceMaps:extensions:' + target.id(), Workspace.Workspace.projectTypes.ContentScripts, '',
false /* isServiceProject */);
NetworkProject.setTargetForProject(this.#regularProject, target);
NetworkProject.setTargetForProject(this.#contentScriptsProject, target);
this.#regularBindings = new Map();
this.#contentScriptsBindings = new Map();
this.#stubUISourceCodes = new Map();
this.#stubProject = new ContentProviderBasedProject(
workspace, 'jsSourceMaps:stub:' + target.id(), Workspace.Workspace.projectTypes.Service, '',
true /* isServiceProject */);
this.#eventListeners = [
this.#sourceMapManager.addEventListener(
SDK.SourceMapManager.Events.SourceMapWillAttach, this.sourceMapWillAttach, this),
this.#sourceMapManager.addEventListener(
SDK.SourceMapManager.Events.SourceMapFailedToAttach, this.sourceMapFailedToAttach, this),
this.#sourceMapManager.addEventListener(
SDK.SourceMapManager.Events.SourceMapAttached, this.sourceMapAttached, this),
this.#sourceMapManager.addEventListener(
SDK.SourceMapManager.Events.SourceMapDetached, this.sourceMapDetached, this),
this.#workspace.addEventListener(
Workspace.Workspace.Events.UISourceCodeAdded,
event => {
this.onUiSourceCodeAdded(event);
},
this),
];
}
private onUiSourceCodeAdded(event: Common.EventTarget.EventTargetEvent<Workspace.UISourceCode.UISourceCode>): void {
const uiSourceCode = event.data;
if (uiSourceCode.contentType().isDocument()) {
for (const script of this.#debuggerModel.scriptsForSourceURL(uiSourceCode.url())) {
this.#debuggerWorkspaceBinding.updateLocations(script);
}
}
}
private addStubUISourceCode(script: SDK.Script.Script): void {
const stubUISourceCode = this.#stubProject.addContentProvider(
script.sourceURL + ':sourcemap',
TextUtils.StaticContentProvider.StaticContentProvider.fromString(
script.sourceURL, Common.ResourceType.resourceTypes.Script,
'\n\n\n\n\n// Please wait a bit.\n// Compiled script is not shown while source map is being loaded!'),
'text/javascript');
this.#stubUISourceCodes.set(script, stubUISourceCode);
}
private async removeStubUISourceCode(script: SDK.Script.Script): Promise<void> {
const uiSourceCode = this.#stubUISourceCodes.get(script);
this.#stubUISourceCodes.delete(script);
if (uiSourceCode) {
this.#stubProject.removeFile(uiSourceCode.url());
}
await this.#debuggerWorkspaceBinding.updateLocations(script);
}
static uiSourceCodeOrigin(uiSourceCode: Workspace.UISourceCode.UISourceCode): string[] {
const binding = uiSourceCodeToBinding.get(uiSourceCode);
if (binding) {
return binding.getReferringSourceMaps().map((sourceMap: SDK.SourceMap.SourceMap) => sourceMap.compiledURL());
}
return [];
}
getLocationRangesForSameSourceLocation(rawLocation: SDK.DebuggerModel.Location): RawLocationRange[] {
const debuggerModel = rawLocation.debuggerModel;
const script = rawLocation.script();
if (!script) {
return [];
}
const sourceMap = this.#sourceMapManager.sourceMapForClient(script);
if (!sourceMap) {
return [];
}
// Find the source location for the raw location.
const entry = sourceMap.findEntry(rawLocation.lineNumber, rawLocation.columnNumber);
if (!entry || !entry.sourceURL) {
return [];
}
// Map the source location back to raw location ranges.
const ranges = sourceMap.findReverseRanges(entry.sourceURL, entry.sourceLineNumber, entry.sourceColumnNumber);
return ranges.map(textRangeToLocationRange);
function textRangeToLocationRange(t: TextUtils.TextRange.TextRange): RawLocationRange {
return {
start: debuggerModel.createRawLocation(script as SDK.Script.Script, t.startLine, t.startColumn),
end: debuggerModel.createRawLocation(script as SDK.Script.Script, t.endLine, t.endColumn),
};
}
}
uiSourceCodeForURL(url: string, isContentScript: boolean): Workspace.UISourceCode.UISourceCode|null {
return isContentScript ? this.#contentScriptsProject.uiSourceCodeForURL(url) :
this.#regularProject.uiSourceCodeForURL(url);
}
rawLocationToUILocation(rawLocation: SDK.DebuggerModel.Location): Workspace.UISourceCode.UILocation|null {
const script = rawLocation.script();
if (!script) {
return null;
}
const lineNumber = rawLocation.lineNumber - script.lineOffset;
let columnNumber = rawLocation.columnNumber;
if (!lineNumber) {
columnNumber -= script.columnOffset;
}
const stubUISourceCode = this.#stubUISourceCodes.get(script);
if (stubUISourceCode) {
return new Workspace.UISourceCode.UILocation(stubUISourceCode, lineNumber, columnNumber);
}
const sourceMap = this.#sourceMapManager.sourceMapForClient(script);
if (!sourceMap) {
return null;
}
const entry = sourceMap.findEntry(lineNumber, columnNumber);
if (!entry || !entry.sourceURL) {
return null;
}
const uiSourceCode = script.isContentScript() ? this.#contentScriptsProject.uiSourceCodeForURL(entry.sourceURL) :
this.#regularProject.uiSourceCodeForURL(entry.sourceURL);
if (!uiSourceCode) {
return null;
}
return uiSourceCode.uiLocation((entry.sourceLineNumber as number), (entry.sourceColumnNumber as number));
}
uiLocationToRawLocations(uiSourceCode: Workspace.UISourceCode.UISourceCode, lineNumber: number, columnNumber: number):
SDK.DebuggerModel.Location[] {
const binding = uiSourceCodeToBinding.get(uiSourceCode);
if (!binding) {
return [];
}
const locations: SDK.DebuggerModel.Location[] = [];
for (const sourceMap of binding.getReferringSourceMaps()) {
const entry = sourceMap.sourceLineMapping(uiSourceCode.url(), lineNumber, columnNumber);
if (!entry) {
continue;
}
for (const script of this.#sourceMapManager.clientsForSourceMap(sourceMap)) {
locations.push(this.#debuggerModel.createRawLocation(
script, entry.lineNumber + script.lineOffset,
!entry.lineNumber ? entry.columnNumber + script.columnOffset : entry.columnNumber));
}
}
return locations;
}
private async sourceMapWillAttach(event: Common.EventTarget.EventTargetEvent<{client: SDK.Script.Script}>):
Promise<void> {
const script = event.data.client;
// Create stub UISourceCode for the time source mapping is being loaded.
this.addStubUISourceCode(script);
await this.#debuggerWorkspaceBinding.updateLocations(script);
}
private async sourceMapFailedToAttach(event: Common.EventTarget.EventTargetEvent<{client: SDK.Script.Script}>):
Promise<void> {
const script = event.data.client;
await this.removeStubUISourceCode(script);
}
private async sourceMapAttached(
event: Common.EventTarget.EventTargetEvent<{client: SDK.Script.Script, sourceMap: SDK.SourceMap.SourceMap}>):
Promise<void> {
const script = event.data.client;
const sourceMap = event.data.sourceMap;
await this.removeStubUISourceCode(script);
if (IgnoreListManager.instance().isIgnoreListedURL(script.sourceURL, script.isContentScript())) {
this.sourceMapAttachedForTest(sourceMap);
return;
}
await this.populateSourceMapSources(script, sourceMap);
this.sourceMapAttachedForTest(sourceMap);
}
private async sourceMapDetached(
event: Common.EventTarget.EventTargetEvent<{client: SDK.Script.Script, sourceMap: SDK.SourceMap.SourceMap}>):
Promise<void> {
const script = event.data.client;
const sourceMap = event.data.sourceMap;
const bindings = script.isContentScript() ? this.#contentScriptsBindings : this.#regularBindings;
for (const sourceURL of sourceMap.sourceURLs()) {
const binding = bindings.get(sourceURL);
if (binding) {
binding.removeSourceMap(sourceMap, script.frameId);
if (!binding.getUiSourceCode()) {
bindings.delete(sourceURL);
}
}
}
await this.#debuggerWorkspaceBinding.updateLocations(script);
}
sourceMapForScript(script: SDK.Script.Script): SDK.SourceMap.SourceMap|null {
return this.#sourceMapManager.sourceMapForClient(script);
}
scriptsForUISourceCode(uiSourceCode: Workspace.UISourceCode.UISourceCode): SDK.Script.Script[] {
const binding = uiSourceCodeToBinding.get(uiSourceCode);
if (!binding) {
return [];
}
const scripts: SDK.Script.Script[] = [];
for (const sourceMap of binding.getReferringSourceMaps()) {
this.#sourceMapManager.clientsForSourceMap(sourceMap).forEach(script => scripts.push(script));
}
return scripts;
}
private sourceMapAttachedForTest(_sourceMap: SDK.SourceMap.SourceMap|null): void {
}
private async populateSourceMapSources(script: SDK.Script.Script, sourceMap: SDK.SourceMap.SourceMap): Promise<void> {
const project = script.isContentScript() ? this.#contentScriptsProject : this.#regularProject;
const bindings = script.isContentScript() ? this.#contentScriptsBindings : this.#regularBindings;
for (const sourceURL of sourceMap.sourceURLs()) {
let binding = bindings.get(sourceURL);
if (!binding) {
binding = new Binding(project, sourceURL);
bindings.set(sourceURL, binding);
}
binding.addSourceMap(sourceMap, script.frameId);
}
await this.#debuggerWorkspaceBinding.updateLocations(script);
}
static uiLineHasMapping(uiSourceCode: Workspace.UISourceCode.UISourceCode, lineNumber: number): boolean {
const binding = uiSourceCodeToBinding.get(uiSourceCode);
if (!binding) {
return true;
}
for (const sourceMap of binding.getReferringSourceMaps()) {
if (sourceMap.sourceLineMapping(uiSourceCode.url(), lineNumber, 0)) {
return true;
}
}
return false;
}
dispose(): void {
Common.EventTarget.removeEventListeners(this.#eventListeners);
this.#regularProject.dispose();
this.#contentScriptsProject.dispose();
this.#stubProject.dispose();
}
}
const uiSourceCodeToBinding = new WeakMap<Workspace.UISourceCode.UISourceCode, Binding>();
class Binding {
readonly #project: ContentProviderBasedProject;
readonly #url: string;
referringSourceMaps: SDK.SourceMap.SourceMap[];
readonly #activeSourceMap?: SDK.SourceMap.SourceMap|null;
uiSourceCode: Workspace.UISourceCode.UISourceCode|null;
constructor(project: ContentProviderBasedProject, url: string) {
this.#project = project;
this.#url = url;
this.referringSourceMaps = [];
this.uiSourceCode = null;
}
private recreateUISourceCodeIfNeeded(frameId: Protocol.Page.FrameId): void {
const sourceMap = this.referringSourceMaps[this.referringSourceMaps.length - 1];
const newUISourceCode =
this.#project.createUISourceCode(this.#url, Common.ResourceType.resourceTypes.SourceMapScript);
uiSourceCodeToBinding.set(newUISourceCode, this);
const contentProvider =
sourceMap.sourceContentProvider(this.#url, Common.ResourceType.resourceTypes.SourceMapScript);
const mimeType = Common.ResourceType.ResourceType.mimeFromURL(this.#url) || 'text/javascript';
const embeddedContent = sourceMap.embeddedContentByURL(this.#url);
const metadata = typeof embeddedContent === 'string' ?
new Workspace.UISourceCode.UISourceCodeMetadata(null, embeddedContent.length) :
null;
if (this.uiSourceCode) {
NetworkProject.cloneInitialFrameAttribution(this.uiSourceCode, newUISourceCode);
this.#project.removeFile(this.uiSourceCode.url());
} else {
NetworkProject.setInitialFrameAttribution(newUISourceCode, frameId);
}
this.uiSourceCode = newUISourceCode;
this.#project.addUISourceCodeWithProvider(this.uiSourceCode, contentProvider, metadata, mimeType);
}
addSourceMap(sourceMap: SDK.SourceMap.SourceMap, frameId: Protocol.Page.FrameId): void {
if (this.uiSourceCode) {
NetworkProject.addFrameAttribution(this.uiSourceCode, frameId);
}
this.referringSourceMaps.push(sourceMap);
this.recreateUISourceCodeIfNeeded(frameId);
}
removeSourceMap(sourceMap: SDK.SourceMap.SourceMap, frameId: Protocol.Page.FrameId): void {
const uiSourceCode = (this.uiSourceCode as Workspace.UISourceCode.UISourceCode);
NetworkProject.removeFrameAttribution(uiSourceCode, frameId);
const lastIndex = this.referringSourceMaps.lastIndexOf(sourceMap);
if (lastIndex !== -1) {
this.referringSourceMaps.splice(lastIndex, 1);
}
if (!this.referringSourceMaps.length) {
this.#project.removeFile(uiSourceCode.url());
this.uiSourceCode = null;
} else {
this.recreateUISourceCodeIfNeeded(frameId);
}
}
getReferringSourceMaps(): Array<SDK.SourceMap.SourceMap> {
return this.referringSourceMaps;
}
getUiSourceCode(): Workspace.UISourceCode.UISourceCode|null {
return this.uiSourceCode;
}
} | the_stack |
import Adapt, { callInstanceMethod, FinalDomElement, Group, handle } from "@adpt/core";
import { dockerMocha, mochaTmpdir } from "@adpt/testutils";
import execa from "execa";
import fs from "fs-extra";
import path from "path";
import should from "should";
import { createActionPlugin } from "../../src/action/action_plugin";
import { MockDeploy, smallDockerImage } from "../testlib";
import { waitForNoThrow } from "@adpt/utils";
import fetch from "node-fetch";
import {
BuildKitImage,
BuildKitImageProps,
computeContainerName,
DockerContainer,
File,
RegistryDockerImage,
RegistryDockerImageProps,
} from "../../src/docker";
import { buildKitBuild, buildKitFilesImage } from "../../src/docker/bk-cli";
import { BuildKitBuildOptions, BuildKitGlobalOptions, BuildKitOutputRegistry, ImageStorage } from "../../src/docker/bk-types";
import {
busyboxImage,
dockerInspect,
} from "../../src/docker/cli";
import { ImageRef } from "../../src/docker/image-ref";
import { buildKitHost } from "../run_buildkit";
import { registryHost } from "../run_registry";
import { checkRegistryImage, deleteAllContainers, deleteAllImages, deployIDFilter } from "./common";
async function checkDockerRun(image: string) {
const { stdout } = await execa("docker", [ "run", "--rm", image ]);
return stdout;
}
describe("buildKitFilesImage", function () {
let regHost: string;
let bkHost: string;
this.timeout(60 * 1000);
this.slow(2 * 1000);
mochaTmpdir.all(`adapt-cloud-buildKitFilesImage`);
before(async () => {
regHost = await registryHost();
bkHost = await buildKitHost();
});
const storage = (): ImageStorage => ({
type: "registry",
insecure: true,
registry: regHost,
});
async function doBuildFiles(files: File[], opts: BuildKitGlobalOptions) {
const image = await buildKitFilesImage(files, {
...opts,
storage: storage(),
buildKitHost: bkHost,
});
const { nameTag } = image;
if (!nameTag) throw new Error(`No nameTag present for files image`);
return image;
}
async function buildAndRun(dockerfile: string) {
await fs.writeFile("Dockerfile", dockerfile);
const image = await buildKitBuild("Dockerfile", ".", {
...storage(),
imageName: "adapt-test-buildkitfiles",
uniqueTag: true,
}, {
buildKitHost: bkHost,
});
const { nameTag } = image;
if (!nameTag) throw new Error(`No nameTag present for test image`);
return checkDockerRun(nameTag);
}
it("Should build an image", async () => {
const image = await doBuildFiles([{
path: "foo",
contents: "foo contents\n",
}, {
path: "/foo1",
contents: "foo1 contents\n",
}, {
path: "/dir/foo2",
contents: "foo2 contents\n",
}, {
path: "dir1/foo3",
contents: "foo3 contents\n",
}], {});
const output = await buildAndRun(`
FROM ${image.nameTag} as files
FROM ${busyboxImage}
COPY --from=files /foo myfoo
COPY --from=files foo1 myfoo1
COPY --from=files dir/foo2 myfoo2
COPY --from=files dir1/foo3 myfoo3
CMD cat myfoo myfoo1 myfoo2 myfoo3
`);
should(output).equal(
`foo contents
foo1 contents
foo2 contents
foo3 contents`);
});
});
describe("BuildKitImage", function () {
let mockDeploy: MockDeploy;
let pluginDir: string;
let regHost: string;
let reg2Host: string;
let bkHost: string;
this.timeout(80 * 1000);
this.slow(4 * 1000);
mochaTmpdir.all(`adapt-cloud-buildkitimage`);
const reg2Fixture = dockerMocha.all({
Image: "registry:2",
HostConfig: {
PublishAllPorts: true,
},
}, {
namePrefix: "bkimage-registry",
proxyPorts: true,
});
before(async () => {
pluginDir = path.join(process.cwd(), "plugins");
regHost = await registryHost();
bkHost = await buildKitHost();
await fs.ensureDir("ctx");
const localPorts = await reg2Fixture.ports(true);
const host = localPorts["5000/tcp"];
if (!host) throw new Error(`Unable to get host/port for registry`);
reg2Host = host;
await waitForNoThrow(60, 1, async () => {
const resp = await fetch(`http://${host}/v2/`);
if (!resp.ok) throw new Error(`Registry ping returned status ${resp.status}: ${resp.statusText}`);
});
});
beforeEach(async () => {
await fs.remove(pluginDir);
mockDeploy = new MockDeploy({
pluginCreates: [createActionPlugin],
tmpDir: pluginDir,
uniqueDeployID: true
});
await mockDeploy.init();
});
afterEach(async function () {
this.timeout(20 * 1000);
const filter = deployIDFilter(mockDeploy.deployID);
await deleteAllContainers(filter);
await deleteAllImages(filter);
});
const storage = () => ({
type: "registry" as const,
insecure: true,
registry: regHost,
});
async function buildAndRun(props: BuildKitImageProps, expected: string) {
const orig = <BuildKitImage {...props} />;
const { dom } = await mockDeploy.deploy(orig);
if (dom == null) throw should(dom).not.be.Null();
const image: ImageRef = dom.instance.image();
should(image).not.be.Undefined();
const { registryRef, registryDigest, id, nameTag } = image;
should(id).match(/^sha256:[a-f0-9]{64}$/);
should(registryDigest).match(RegExp(`^${regHost}/bki-test@sha256:[a-f0-9]{64}$`));
if (nameTag) should(nameTag).startWith(`${regHost}/bki-test:`);
const ref = nameTag || registryRef;
if (!ref) throw new Error(`Both nameTag and registryRef are null`);
const output = await checkDockerRun(ref);
should(output).equal(expected);
return image;
}
it("Should build a registry image with an imageTag", async () => {
await fs.writeFile("Dockerfile", `
FROM ${busyboxImage}
CMD echo SUCCESS1
`);
const props: BuildKitImageProps = {
dockerfileName: "Dockerfile",
options: {
buildKitHost: bkHost,
},
output: {
...storage(),
imageName: "bki-test",
imageTag: "simple",
},
};
const image = await buildAndRun(props, "SUCCESS1");
should(image.nameTag).equal(`${regHost}/bki-test:simple`);
});
it("Should build a registry image without an imageTag", async () => {
await fs.writeFile("Dockerfile", `
FROM ${busyboxImage}
CMD echo SUCCESS2
`);
const props: BuildKitImageProps = {
dockerfileName: "Dockerfile",
options: {
buildKitHost: bkHost,
},
output: {
...storage(),
imageName: "bki-test",
},
};
const image = await buildAndRun(props, "SUCCESS2");
should(image.registryRef).match(RegExp(`^${regHost}/bki-test@sha256:[a-f0-9]{64}$`));
should(image.nameTag).equal(undefined);
});
it("Should build a registry image with a unique tag", async () => {
await fs.writeFile("Dockerfile", `
FROM ${busyboxImage}
CMD echo SUCCESS3
`);
const props: BuildKitImageProps = {
dockerfileName: "Dockerfile",
options: {
buildKitHost: bkHost,
},
output: {
...storage(),
imageName: "bki-test",
uniqueTag: true,
},
};
const image = await buildAndRun(props, "SUCCESS3");
should(image.nameTag).match(RegExp(`^${regHost}/bki-test:[a-z]{8}$`));
// ID and tag should not change on a rebuild
const image2 = await buildAndRun(props, "SUCCESS3");
should(image2.nameTag).match(RegExp(`^${regHost}/bki-test:[a-z]{8}$`));
should(image2.nameTag).equal(image.nameTag);
should(image2.id).equal(image.id);
});
it("Should build using alternate file name", async () => {
await fs.writeFile("notadockerfile", `
FROM ${busyboxImage}
CMD echo SUCCESS1
`);
const props: BuildKitImageProps = {
dockerfileName: "notadockerfile",
options: {
buildKitHost: bkHost,
},
output: {
...storage(),
imageName: "bki-test",
imageTag: "simple",
},
};
const image = await buildAndRun(props, "SUCCESS1");
should(image.nameTag).equal(`${regHost}/bki-test:simple`);
});
it("Should build a registry image with files", async () => {
const props: BuildKitImageProps = {
dockerfile: `
FROM ${busyboxImage}
COPY --from=files somefile .
CMD cat somefile
`,
files: [{
path: "somefile",
contents: "SUCCESS4",
}],
options: {
buildKitHost: bkHost,
},
output: {
...storage(),
imageName: "bki-test",
uniqueTag: true,
},
};
await buildAndRun(props, "SUCCESS4");
});
interface BasicDom {
buildOpts?: BuildKitBuildOptions;
dockerfile?: string;
output?: BuildKitOutputRegistry;
registryPrefix: string;
newPathTag?: string;
}
const defaultBasicDom = () => {
const output: BuildKitOutputRegistry = {
...storage(),
imageName: "bki-test",
imageTag: "basicdom",
};
return {
dockerfile: `
FROM ${smallDockerImage}
CMD sleep 10000
`,
output,
};
};
const defaultBuildOpts = () => ({
buildKitHost: bkHost,
});
async function deployBasicTest(options: BasicDom) {
const [ iReg, iSrc ] = [ handle(), handle() ];
const opts = { ...defaultBasicDom(), ...options };
const buildOpts = { ...defaultBuildOpts(), ...(opts.buildOpts || {})};
const imageOpts: Partial<RegistryDockerImageProps> = {};
if (opts.newPathTag) imageOpts.newPathTag = opts.newPathTag;
const orig =
<Group>
<BuildKitImage
handle={iSrc}
contextDir="ctx"
dockerfile={opts.dockerfile}
options={buildOpts}
output={opts.output}
/>
<RegistryDockerImage
handle={iReg}
imageSrc={iSrc}
registryPrefix={opts.registryPrefix}
{...imageOpts}
/>
<DockerContainer autoRemove={true} image={iReg} stopSignal="SIGKILL" />
</Group>;
return mockDeploy.deploy(orig);
}
async function checkBasicTest(dom: FinalDomElement | null, options: BasicDom) {
const opts = { ...defaultBasicDom(), ...options };
if (dom == null) throw should(dom).not.be.Null();
should(dom.props.children).be.an.Array().with.length(3);
const iSrc = dom.props.children[0].props.handle;
const iReg = dom.props.children[1].props.handle;
const srcImageEl: FinalDomElement = dom.props.children[0];
should(srcImageEl.componentType).equal(BuildKitImage);
const srcImageInfo = callInstanceMethod<ImageRef | undefined>(iSrc, undefined, "latestImage");
if (srcImageInfo == null) throw should(srcImageInfo).be.ok();
// Info on the running container
const ctrEl: FinalDomElement = dom.props.children[2];
should(ctrEl.componentType).equal(DockerContainer);
const contName = computeContainerName(ctrEl.props.key, ctrEl.id, mockDeploy.deployID);
should(contName).startWith("dockercontainer-");
const infos = await dockerInspect([contName], { type: "container" });
should(infos).be.Array().of.length(1);
const ctrInfo = infos[0];
if (ctrInfo == null) throw should(ctrInfo).be.ok();
// Check image name
const regImageInfo = callInstanceMethod<ImageRef | undefined>(iReg, undefined, "latestImage");
if (regImageInfo == null) throw should(regImageInfo).be.ok();
should(regImageInfo.nameTag).equal(ctrInfo.Config.Image);
let pathTag = opts.newPathTag || srcImageInfo.pathTag;
if (!pathTag) throw should(pathTag).be.ok();
if (!pathTag.includes(":")) pathTag += ":latest";
should(regImageInfo.nameTag).equal(`${options.registryPrefix}/${pathTag}`);
should(regImageInfo.id).equal(ctrInfo.Image);
should(regImageInfo.digest).equal(srcImageInfo.digest);
// Stop the container so we can delete its image
await execa("docker", ["rm", "-f", contName]);
if (!regImageInfo.nameTag) throw should(regImageInfo.nameTag).be.ok();
await checkRegistryImage(regImageInfo.nameTag);
//Delete
await mockDeploy.deploy(null);
const finalInfos = await dockerInspect([contName], { type: "container" });
should(finalInfos).be.Array().of.length(0);
}
it("Should push a built image to second registry with same pathTag", async () => {
const output: BuildKitOutputRegistry = {
...storage(),
imageName: "bki-test",
imageTag: "sametag",
};
const opts = {
output,
registryPrefix: reg2Host,
};
const { dom } = await deployBasicTest(opts);
await checkBasicTest(dom, opts);
});
it("Should push a built image to second registry with new pathTag", async () => {
const output: BuildKitOutputRegistry = {
...storage(),
imageName: "bki-test",
imageTag: "firsttag",
};
const opts = {
output,
newPathTag: "new/repo/image:secondtag",
registryPrefix: reg2Host,
};
const { dom } = await deployBasicTest(opts);
await checkBasicTest(dom, opts);
});
}); | the_stack |
import {Class, AnyTiming, Creatable, InitType} from "@swim/util";
import type {MemberAnimatorInit} from "@swim/component";
import {AnyLength, Length, AnyTransform, Transform} from "@swim/math";
import {
FontStyle,
FontVariant,
FontWeight,
FontStretch,
FontFamily,
AnyFont,
Font,
AnyColor,
Color,
} from "@swim/style";
import {AnyView, ViewCreator, View} from "@swim/view";
import {AttributeAnimator} from "../animator/AttributeAnimator";
import {StyleAnimator} from "../animator/StyleAnimator";
import type {
AlignmentBaseline,
CssCursor,
FillRule,
StrokeLinecap,
StrokeLinejoin,
SvgPointerEvents,
TextAnchor,
TouchAction,
} from "../css/types";
import type {ViewNodeType} from "../node/NodeView";
import {
AnyElementView,
ElementViewInit,
ElementViewFactory,
ElementViewClass,
ElementViewConstructor,
ElementView,
} from "../element/ElementView";
import type {SvgViewObserver} from "./SvgViewObserver";
/** @public */
export interface ViewSvg extends SVGElement {
view?: SvgView;
}
/** @public */
export type AnySvgView<V extends SvgView = SvgView> = AnyElementView<V> | keyof SvgViewTagMap;
/** @public */
export interface SvgViewInit extends ElementViewInit {
attributes?: SvgViewAttributesInit;
style?: SvgViewStyleInit;
}
/** @public */
export interface SvgViewAttributesInit {
alignmentBaseline?: MemberAnimatorInit<SvgView, "alignmentBaseline">;
clipPath?: MemberAnimatorInit<SvgView, "clipPath">;
cursor?: MemberAnimatorInit<SvgView, "cursor">;
cx?: MemberAnimatorInit<SvgView, "cx">;
cy?: MemberAnimatorInit<SvgView, "cy">;
d?: MemberAnimatorInit<SvgView, "d">;
dx?: MemberAnimatorInit<SvgView, "dx">;
dy?: MemberAnimatorInit<SvgView, "dy">;
edgeMode?: MemberAnimatorInit<SvgView, "edgeMode">;
fill?: MemberAnimatorInit<SvgView, "fill">;
fillRule?: MemberAnimatorInit<SvgView, "fillRule">;
floodColor?: MemberAnimatorInit<SvgView, "floodColor">;
floodOpacity?: MemberAnimatorInit<SvgView, "floodOpacity">;
height?: MemberAnimatorInit<SvgView, "height">;
in?: MemberAnimatorInit<SvgView, "in">;
in2?: MemberAnimatorInit<SvgView, "in2">;
lengthAdjust?: MemberAnimatorInit<SvgView, "lengthAdjust">;
mode?: MemberAnimatorInit<SvgView, "mode">;
opacity?: MemberAnimatorInit<SvgView, "opacity">;
pointerEvents?: MemberAnimatorInit<SvgView, "pointerEvents">;
points?: MemberAnimatorInit<SvgView, "points">;
preserveAspectRatio?: MemberAnimatorInit<SvgView, "preserveAspectRatio">;
r?: MemberAnimatorInit<SvgView, "r">;
result?: MemberAnimatorInit<SvgView, "result">;
stdDeviation?: MemberAnimatorInit<SvgView, "stdDeviation">;
stroke?: MemberAnimatorInit<SvgView, "stroke">;
strokeDasharray?: MemberAnimatorInit<SvgView, "strokeDasharray">;
strokeDashoffset?: MemberAnimatorInit<SvgView, "strokeDashoffset">;
strokeLinecap?: MemberAnimatorInit<SvgView, "strokeLinecap">;
strokeLinejoin?: MemberAnimatorInit<SvgView, "strokeLinejoin">;
strokeMiterlimit?: MemberAnimatorInit<SvgView, "strokeMiterlimit">;
strokeWidth?: MemberAnimatorInit<SvgView, "strokeWidth">;
textAnchor?: MemberAnimatorInit<SvgView, "textAnchor">;
textLength?: MemberAnimatorInit<SvgView, "textLength">;
transform?: MemberAnimatorInit<SvgView, "transform">;
type?: MemberAnimatorInit<SvgView, "type">;
values?: MemberAnimatorInit<SvgView, "values">;
viewBox?: MemberAnimatorInit<SvgView, "viewBox">;
width?: MemberAnimatorInit<SvgView, "width">;
x?: MemberAnimatorInit<SvgView, "x">;
x1?: MemberAnimatorInit<SvgView, "x1">;
x2?: MemberAnimatorInit<SvgView, "x2">;
y?: MemberAnimatorInit<SvgView, "y">;
y1?: MemberAnimatorInit<SvgView, "y1">;
y2?: MemberAnimatorInit<SvgView, "y2">;
}
/** @public */
export interface SvgViewStyleInit {
cssTransform?: MemberAnimatorInit<SvgView, "cssTransform">;
filter?: MemberAnimatorInit<SvgView, "filter">;
fontFamily?: MemberAnimatorInit<SvgView, "fontFamily">;
fontSize?: MemberAnimatorInit<SvgView, "fontSize">;
fontStretch?: MemberAnimatorInit<SvgView, "fontStretch">;
fontStyle?: MemberAnimatorInit<SvgView, "fontStyle">;
fontVariant?: MemberAnimatorInit<SvgView, "fontVariant">;
fontWeight?: MemberAnimatorInit<SvgView, "fontWeight">;
lineHeight?: MemberAnimatorInit<SvgView, "lineHeight">;
touchAction?: MemberAnimatorInit<SvgView, "touchAction">;
}
/** @public */
export interface SvgViewTagMap {
a: SvgView;
animate: SvgView;
animateMotion: SvgView;
animateTransform: SvgView;
audio: SvgView;
canvas: SvgView;
circle: SvgView;
clipPath: SvgView;
defs: SvgView;
desc: SvgView;
discard: SvgView;
ellipse: SvgView;
feBlend: SvgView;
feColorMatrix: SvgView;
feComponentTransfer: SvgView;
feComposite: SvgView;
feConvolveMatrix: SvgView;
feDiffuseLighting: SvgView;
feDisplacementMap: SvgView;
feDistantLight: SvgView;
feDropShadow: SvgView;
feFlood: SvgView;
feFuncA: SvgView;
feFuncB: SvgView;
feFuncG: SvgView;
feFuncR: SvgView;
feGaussianBlur: SvgView;
feImage: SvgView;
feMerge: SvgView;
feMergeNode: SvgView;
feMorphology: SvgView;
feOffset: SvgView;
fePointLight: SvgView;
feSpecularLighting: SvgView;
feSpotLight: SvgView;
feTile: SvgView;
feTurbulence: SvgView;
filter: SvgView;
foreignObject: SvgView;
g: SvgView;
iframe: SvgView;
image: SvgView;
line: SvgView;
linearGradient: SvgView;
marker: SvgView;
mask: SvgView;
metadata: SvgView;
mpath: SvgView;
path: SvgView;
pattern: SvgView;
polygon: SvgView;
polyline: SvgView;
radialGradient: SvgView;
rect: SvgView;
script: SvgView;
set: SvgView;
stop: SvgView;
style: SvgView;
svg: SvgView;
switch: SvgView;
symbol: SvgView;
text: SvgView;
textPath: SvgView;
title: SvgView;
tspan: SvgView;
unknown: SvgView;
use: SvgView;
video: SvgView;
view: SvgView;
}
/** @public */
export interface SvgViewFactory<V extends SvgView = SvgView, U = AnySvgView<V>> extends ElementViewFactory<V, U> {
}
/** @public */
export interface SvgViewClass<V extends SvgView = SvgView, U = AnySvgView<V>> extends ElementViewClass<V, U>, SvgViewFactory<V, U> {
readonly tag: string;
readonly namespace: string;
}
/** @public */
export interface SvgViewConstructor<V extends SvgView = SvgView, U = AnySvgView<V>> extends ElementViewConstructor<V, U>, SvgViewClass<V, U> {
readonly tag: string;
readonly namespace: string;
}
/** @public */
export class SvgView extends ElementView {
constructor(node: SVGElement) {
super(node);
}
override readonly observerType?: Class<SvgViewObserver>;
override readonly node!: SVGElement;
override setChild<V extends View>(key: string, newChild: V): View | null;
override setChild<F extends ViewCreator<F>>(key: string, factory: F): View | null;
override setChild(key: string, newChild: AnyView | Node | keyof SvgViewTagMap | null): View | null;
override setChild(key: string, newChild: AnyView | Node | keyof SvgViewTagMap | null): View | null {
if (typeof newChild === "string") {
newChild = SvgView.fromTag(newChild);
}
return super.setChild(key, newChild);
}
override appendChild<V extends View>(child: V, key?: string): V;
override appendChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override appendChild<K extends keyof SvgViewTagMap>(tag: K, key?: string): SvgViewTagMap[K];
override appendChild(child: AnyView | Node | keyof SvgViewTagMap, key?: string): View;
override appendChild(child: AnyView | Node | keyof SvgViewTagMap, key?: string): View {
if (typeof child === "string") {
child = SvgView.fromTag(child);
}
return super.appendChild(child, key);
}
override prependChild<V extends View>(child: V, key?: string): V;
override prependChild<F extends ViewCreator<F>>(factory: F, key?: string): InstanceType<F>;
override prependChild<K extends keyof SvgViewTagMap>(tag: K, key?: string): SvgViewTagMap[K];
override prependChild(child: AnyView | Node | keyof SvgViewTagMap, key?: string): View;
override prependChild(child: AnyView | Node | keyof SvgViewTagMap, key?: string): View {
if (typeof child === "string") {
child = SvgView.fromTag(child);
}
return super.prependChild(child, key);
}
override insertChild<V extends View>(child: V, target: View | Node | null, key?: string): V;
override insertChild<F extends ViewCreator<F>>(factory: F, target: View | Node | null, key?: string): InstanceType<F>;
override insertChild<K extends keyof SvgViewTagMap>(tag: K, target: View | Node | null, key?: string): SvgViewTagMap[K];
override insertChild(child: AnyView | Node | keyof SvgViewTagMap, target: View | Node | null, key?: string): View;
override insertChild(child: AnyView | Node | keyof SvgViewTagMap, target: View | Node | null, key?: string): View {
if (typeof child === "string") {
child = SvgView.fromTag(child);
}
return super.insertChild(child, target, key);
}
override replaceChild<V extends View>(newChild: View, oldChild: V): V;
override replaceChild<V extends View>(newChild: AnyView | Node | keyof SvgViewTagMap, oldChild: V): V;
override replaceChild(newChild: AnyView | Node | keyof SvgViewTagMap, oldChild: View): View {
if (typeof newChild === "string") {
newChild = SvgView.fromTag(newChild);
}
return super.replaceChild(newChild, oldChild);
}
@AttributeAnimator({attributeName: "alignment-baseline", type: String})
readonly alignmentBaseline!: AttributeAnimator<this, AlignmentBaseline>;
@AttributeAnimator({attributeName: "clip-path", type: String})
readonly clipPath!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "cursor", type: String})
readonly cursor!: AttributeAnimator<this, CssCursor | undefined>;
@AttributeAnimator({attributeName: "cx", type: Number})
readonly cx!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "cy", type: Number})
readonly cy!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "d", type: String})
readonly d!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "dx", type: Length, value: null})
readonly dx!: AttributeAnimator<this, Length | null, AnyLength | null>;
@AttributeAnimator({attributeName: "dy", type: Length, value: null})
readonly dy!: AttributeAnimator<this, Length | null, AnyLength | null>;
@AttributeAnimator({attributeName: "edgeMode", type: String})
readonly edgeMode!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "fill", type: Color, value: null})
readonly fill!: AttributeAnimator<this, Color | null, AnyColor | null>;
@AttributeAnimator({attributeName: "fill-rule", type: String})
readonly fillRule!: AttributeAnimator<this, FillRule | undefined>;
@AttributeAnimator({attributeName: "flood-color", type: Color, value: null})
readonly floodColor!: AttributeAnimator<this, Color | null, AnyColor | null>;
@AttributeAnimator({attributeName: "flood-opacity", type: Number})
readonly floodOpacity!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "height", type: Length, value: null})
readonly height!: AttributeAnimator<this, Length | null, AnyLength | null>;
@AttributeAnimator({attributeName: "in", type: String})
readonly in!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "in2", type: String})
readonly in2!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "lengthAdjust", type: String})
readonly lengthAdjust!: AttributeAnimator<this, "spacing" | "spacingAndGlyphs" | undefined>;
@AttributeAnimator({attributeName: "mode", type: String})
readonly mode!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "opacity", type: Number})
readonly opacity!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "pointer-events", type: String})
readonly pointerEvents!: AttributeAnimator<this, SvgPointerEvents | undefined>;
@AttributeAnimator({attributeName: "points", type: String})
readonly points!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "preserveAspectRatio", type: Boolean})
readonly preserveAspectRatio!: AttributeAnimator<this, boolean | undefined>;
@AttributeAnimator({attributeName: "r", type: Number})
readonly r!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "result", type: String})
readonly result!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "stdDeviation", type: Number})
readonly stdDeviation!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "stroke", type: Color, value: null})
readonly stroke!: AttributeAnimator<this, Color | null, AnyColor | null>;
@AttributeAnimator({attributeName: "stroke-dasharray", type: String})
readonly strokeDasharray!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "stroke-dashoffset", type: Number})
readonly strokeDashoffset!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "stroke-linecap", type: String})
readonly strokeLinecap!: AttributeAnimator<this, StrokeLinecap | undefined>;
@AttributeAnimator({attributeName: "stroke-linejoin", type: String})
readonly strokeLinejoin!: AttributeAnimator<this, StrokeLinejoin | undefined>;
@AttributeAnimator({attributeName: "stroke-miterlimit", type: Number})
readonly strokeMiterlimit!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "stroke-width", type: Number})
readonly strokeWidth!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "text-anchor", type: String})
readonly textAnchor!: AttributeAnimator<this, TextAnchor | undefined>;
@AttributeAnimator({attributeName: "textLength", type: Length, value: null})
readonly textLength!: AttributeAnimator<this, Length | null, AnyLength | null>;
@AttributeAnimator({attributeName: "transform", type: Transform, value: null})
readonly transform!: AttributeAnimator<this, Transform | null, AnyTransform | null>;
@AttributeAnimator({attributeName: "type", type: String})
readonly type!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "values", type: String})
readonly values!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "viewBox", type: String})
readonly viewBox!: AttributeAnimator<this, string | undefined>;
@AttributeAnimator({attributeName: "width", type: Length, value: null})
readonly width!: AttributeAnimator<this, Length | null, AnyLength | null>;
@AttributeAnimator({attributeName: "x", type: Number})
readonly x!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "x1", type: Number})
readonly x1!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "x2", type: Number})
readonly x2!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "y", type: Number})
readonly y!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "y1", type: Number})
readonly y1!: AttributeAnimator<this, number | undefined>;
@AttributeAnimator({attributeName: "y2", type: Number})
readonly y2!: AttributeAnimator<this, number | undefined>;
@StyleAnimator({propertyNames: "transform", type: Transform, value: null})
readonly cssTransform!: StyleAnimator<this, Transform | null, AnyTransform | null>;
@StyleAnimator({propertyNames: "filter", type: String})
readonly filter!: StyleAnimator<this, string | undefined>;
font(): Font | null;
font(value: AnyFont | null, timing?: AnyTiming | boolean): this;
font(value?: AnyFont | null, timing?: AnyTiming | boolean): Font | null | this {
if (value === void 0) {
const style = this.fontStyle.value;
const variant = this.fontVariant.value;
const weight = this.fontWeight.value;
const stretch = this.fontStretch.value;
const size = this.fontSize.value;
const height = this.lineHeight.value;
const family = this.fontFamily.value;
if (family !== void 0) {
return Font.create(style, variant, weight, stretch, size, height, family);
} else {
return null;
}
} else {
if (value !== null) {
value = Font.fromAny(value);
if (value.style !== void 0) {
this.fontStyle.setState(value.style, timing);
}
if (value.variant !== void 0) {
this.fontVariant.setState(value.variant, timing);
}
if (value.weight !== void 0) {
this.fontWeight.setState(value.weight, timing);
}
if (value.stretch !== void 0) {
this.fontStretch.setState(value.stretch, timing);
}
if (value.size !== void 0) {
this.fontSize.setState(value.size, timing);
}
if (value.height !== void 0) {
this.lineHeight.setState(value.height, timing);
}
this.fontFamily.setState(value.family, timing);
} else {
this.fontStyle.setState(void 0, timing);
this.fontVariant.setState(void 0, timing);
this.fontWeight.setState(void 0, timing);
this.fontStretch.setState(void 0, timing);
this.fontSize.setState(null, timing);
this.lineHeight.setState(null, timing);
this.fontFamily.setState(void 0, timing);
}
return this;
}
}
@StyleAnimator({propertyNames: "font-family", type: FontFamily})
readonly fontFamily!: StyleAnimator<this, FontFamily | FontFamily[] | undefined, FontFamily | ReadonlyArray<FontFamily> | undefined>;
@StyleAnimator({propertyNames: "font-size", type: Length, value: null})
readonly fontSize!: StyleAnimator<this, Length | null, AnyLength | null>;
@StyleAnimator({propertyNames: "font-stretch", type: String})
readonly fontStretch!: StyleAnimator<this, FontStretch | undefined>;
@StyleAnimator({propertyNames: "font-style", type: String})
readonly fontStyle!: StyleAnimator<this, FontStyle | undefined>;
@StyleAnimator({propertyNames: "font-variant", type: String})
readonly fontVariant!: StyleAnimator<this, FontVariant | undefined>;
@StyleAnimator({propertyNames: "font-weight", type: String})
readonly fontWeight!: StyleAnimator<this, FontWeight | undefined>;
@StyleAnimator({propertyNames: "line-height", type: Length, value: null})
readonly lineHeight!: StyleAnimator<this, Length | null, AnyLength | null>;
@StyleAnimator({propertyNames: "touch-action", type: String})
readonly touchAction!: StyleAnimator<this, TouchAction | undefined>;
override get parentTransform(): Transform {
const transform = this.transform.value;
return transform !== null ? transform : Transform.identity();
}
override on<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGElement, event: SVGElementEventMap[K]) => unknown,
options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this;
override on(type: string, listener: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): this {
this.node.addEventListener(type, listener, options);
return this;
}
override off<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGElement, event: SVGElementEventMap[K]) => unknown,
options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this;
override off(type: string, listener: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): this {
this.node.removeEventListener(type, listener, options);
return this;
}
/** @internal */
protected initAttributes(init: SvgViewAttributesInit): void {
if (init.alignmentBaseline !== void 0) {
this.alignmentBaseline(init.alignmentBaseline);
}
if (init.clipPath !== void 0) {
this.clipPath(init.clipPath);
}
if (init.cursor !== void 0) {
this.cursor(init.cursor);
}
if (init.cx !== void 0) {
this.cx(init.cx);
}
if (init.cy !== void 0) {
this.cy(init.cy);
}
if (init.cy !== void 0) {
this.cy(init.cy);
}
if (init.d !== void 0) {
this.d(init.d);
}
if (init.dx !== void 0) {
this.dx(init.dx);
}
if (init.dy !== void 0) {
this.dy(init.dy);
}
if (init.edgeMode !== void 0) {
this.edgeMode(init.edgeMode);
}
if (init.fill !== void 0) {
this.fill(init.fill);
}
if (init.fillRule !== void 0) {
this.fillRule(init.fillRule);
}
if (init.floodColor !== void 0) {
this.floodColor(init.floodColor);
}
if (init.floodOpacity !== void 0) {
this.floodOpacity(init.floodOpacity);
}
if (init.height !== void 0) {
this.height(init.height);
}
if (init.in !== void 0) {
this.in(init.in);
}
if (init.in2 !== void 0) {
this.in2(init.in2);
}
if (init.lengthAdjust !== void 0) {
this.lengthAdjust(init.lengthAdjust);
}
if (init.mode !== void 0) {
this.mode(init.mode);
}
if (init.opacity !== void 0) {
this.opacity(init.opacity);
}
if (init.pointerEvents !== void 0) {
this.pointerEvents(init.pointerEvents);
}
if (init.points !== void 0) {
this.points(init.points);
}
if (init.preserveAspectRatio !== void 0) {
this.preserveAspectRatio(init.preserveAspectRatio);
}
if (init.r !== void 0) {
this.r(init.r);
}
if (init.result !== void 0) {
this.result(init.result);
}
if (init.stdDeviation !== void 0) {
this.stdDeviation(init.stdDeviation);
}
if (init.stroke !== void 0) {
this.stroke(init.stroke);
}
if (init.strokeDasharray !== void 0) {
this.strokeDasharray(init.strokeDasharray);
}
if (init.strokeDashoffset !== void 0) {
this.strokeDashoffset(init.strokeDashoffset);
}
if (init.strokeLinecap !== void 0) {
this.strokeLinecap(init.strokeLinecap);
}
if (init.strokeLinejoin !== void 0) {
this.strokeLinejoin(init.strokeLinejoin);
}
if (init.strokeMiterlimit !== void 0) {
this.strokeMiterlimit(init.strokeMiterlimit);
}
if (init.strokeWidth !== void 0) {
this.strokeWidth(init.strokeWidth);
}
if (init.textAnchor !== void 0) {
this.textAnchor(init.textAnchor);
}
if (init.textLength !== void 0) {
this.textLength(init.textLength);
}
if (init.transform !== void 0) {
this.transform(init.transform);
}
if (init.type !== void 0) {
this.type(init.type);
}
if (init.values !== void 0) {
this.values(init.values);
}
if (init.viewBox !== void 0) {
this.viewBox(init.viewBox);
}
if (init.width !== void 0) {
this.width(init.width);
}
if (init.x !== void 0) {
this.x(init.x);
}
if (init.x1 !== void 0) {
this.x1(init.x1);
}
if (init.x2 !== void 0) {
this.x2(init.x2);
}
if (init.y !== void 0) {
this.y(init.y);
}
if (init.y1 !== void 0) {
this.y1(init.y1);
}
if (init.y2 !== void 0) {
this.y2(init.y2);
}
}
/** @internal */
protected initStyle(init: SvgViewStyleInit): void {
if (init.cssTransform !== void 0) {
this.cssTransform(init.cssTransform);
}
if (init.filter !== void 0) {
this.filter(init.filter);
}
if (init.fontFamily !== void 0) {
this.fontFamily(init.fontFamily);
}
if (init.fontSize !== void 0) {
this.fontSize(init.fontSize);
}
if (init.fontStretch !== void 0) {
this.fontStretch(init.fontStretch);
}
if (init.fontStyle !== void 0) {
this.fontStyle(init.fontStyle);
}
if (init.fontVariant !== void 0) {
this.fontVariant(init.fontVariant);
}
if (init.fontWeight !== void 0) {
this.fontWeight(init.fontWeight);
}
if (init.lineHeight !== void 0) {
this.lineHeight(init.lineHeight);
}
if (init.touchAction !== void 0) {
this.touchAction(init.touchAction);
}
}
override init(init: SvgViewInit): void {
super.init(init);
if (init.attributes !== void 0) {
this.initAttributes(init.attributes);
}
if (init.style !== void 0) {
this.initStyle(init.style);
}
}
static override readonly tag: string = "svg";
static override readonly namespace: string = "http://www.w3.org/2000/svg";
static override create<S extends abstract new (...args: any) => InstanceType<S>>(this: S): InstanceType<S>;
static override create(): SvgView;
static override create(): SvgView {
return this.fromTag(this.tag);
}
static override fromTag<S extends abstract new (...args: any) => InstanceType<S>>(this: S, tag: string): InstanceType<S>;
static override fromTag(tag: string): SvgView;
static override fromTag(tag: string): SvgView {
const node = document.createElementNS(this.namespace, tag) as SVGElement;
return this.fromNode(node);
}
static override fromNode<S extends new (node: SVGElement) => InstanceType<S>>(this: S, node: ViewNodeType<InstanceType<S>>): InstanceType<S>;
static override fromNode(node: SVGElement): SvgView;
static override fromNode(node: SVGElement): SvgView {
let view = (node as ViewSvg).view;
if (view === void 0) {
view = new this(node);
this.mount(view);
} else if (!(view instanceof this)) {
throw new TypeError(view + " not an instance of " + this);
}
return view;
}
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnySvgView<InstanceType<S>>): InstanceType<S>;
static override fromAny(value: AnySvgView | string): SvgView;
static override fromAny(value: AnySvgView | string): SvgView {
if (value === void 0 || value === null) {
return value;
} else if (value instanceof View) {
if (value instanceof this) {
return value;
} else {
throw new TypeError(value + " not an instance of " + this);
}
} else if (value instanceof Node) {
return this.fromNode(value);
} else if (typeof value === "string") {
return this.fromTag(value);
} else if (Creatable.is(value)) {
return value.create();
} else {
return this.fromInit(value);
}
}
static forTag<S extends abstract new (...args: any) => InstanceType<S>>(this: S, tag: string): SvgViewFactory<InstanceType<S>>;
static forTag(tag: string): SvgViewFactory;
static forTag(tag: string): SvgViewFactory {
if (tag === this.tag) {
return this;
} else {
return new SvgViewTagFactory(this, tag);
}
}
}
/** @internal */
export class SvgViewTagFactory<V extends SvgView> implements SvgViewFactory<V> {
constructor(factory: SvgViewFactory<V>, tag: string) {
this.factory = factory;
this.tag = tag;
}
/** @internal */
readonly factory: SvgViewFactory<V>;
readonly tag: string;
get namespace(): string {
return SvgView.namespace;
}
create(): V {
return this.fromTag(this.tag);
}
fromTag(tag: string): V {
const node = document.createElementNS(this.namespace, tag) as SVGElement;
return this.fromNode(node as ViewNodeType<V>);
}
fromNode(node: ViewNodeType<V>): V {
return this.factory.fromNode(node);
}
fromInit(init: InitType<V>): V {
let type = init.type;
if (type === void 0) {
type = this;
}
const view = type.create() as V;
view.init(init);
return view;
}
fromAny(value: AnySvgView<V>): V {
return this.factory.fromAny(value);
}
} | the_stack |
import * as path from "path";
import * as semver from "semver";
import { ChildProcess } from "../../common/node/childProcess";
import { CommandExecutor } from "../../common/commandExecutor";
import { MobilePlatformDeps, TargetType } from "../generalPlatform";
import { IIOSRunOptions, PlatformType } from "../launchArgs";
import { PlistBuddy } from "./plistBuddy";
import { IOSDebugModeManager } from "./iOSDebugModeManager";
import { OutputVerifier, PatternToFailure } from "../../common/outputVerifier";
import { TelemetryHelper } from "../../common/telemetryHelper";
import { InternalErrorCode } from "../../common/error/internalErrorCode";
import * as nls from "vscode-nls";
import { AppLauncher } from "../appLauncher";
import { GeneralMobilePlatform } from "../generalMobilePlatform";
import { IDebuggableIOSTarget, IOSTarget, IOSTargetManager } from "./iOSTargetManager";
import { ErrorHelper } from "../../common/error/errorHelper";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
export class IOSPlatform extends GeneralMobilePlatform {
public static DEFAULT_IOS_PROJECT_RELATIVE_PATH = "ios";
private plistBuddy = new PlistBuddy();
private iosProjectRoot: string;
private iosDebugModeManager: IOSDebugModeManager;
private defaultConfiguration: string = "Debug";
private configurationArgumentName: string = "--configuration";
protected target?: IOSTarget;
// We should add the common iOS build/run errors we find to this list
private static RUN_IOS_FAILURE_PATTERNS: PatternToFailure[] = [
{
pattern: "No devices are booted",
errorCode: InternalErrorCode.IOSSimulatorNotLaunchable,
},
{
pattern: "FBSOpenApplicationErrorDomain",
errorCode: InternalErrorCode.IOSSimulatorNotLaunchable,
},
{
pattern: "ios-deploy",
errorCode: InternalErrorCode.IOSDeployNotFound,
},
];
private static readonly RUN_IOS_SUCCESS_PATTERNS = ["BUILD SUCCEEDED"];
constructor(protected runOptions: IIOSRunOptions, platformDeps: MobilePlatformDeps = {}) {
super(runOptions, platformDeps);
this.targetManager = new IOSTargetManager();
this.runOptions.configuration = this.getConfiguration();
if (this.runOptions.iosRelativeProjectPath) {
// Deprecated option
this.logger.warning(
localize(
"iosRelativeProjectPathOptionIsDeprecatedUseRunArgumentsInstead",
"'iosRelativeProjectPath' option is deprecated. Please use 'runArguments' instead.",
),
);
}
const iosProjectFolderPath = IOSPlatform.getOptFromRunArgs(
this.runArguments,
"--project-path",
false,
);
this.iosProjectRoot = path.join(
this.projectPath,
iosProjectFolderPath ||
this.runOptions.iosRelativeProjectPath ||
IOSPlatform.DEFAULT_IOS_PROJECT_RELATIVE_PATH,
);
const schemeFromArgs = IOSPlatform.getOptFromRunArgs(this.runArguments, "--scheme", false);
this.iosDebugModeManager = new IOSDebugModeManager(
this.iosProjectRoot,
this.projectPath,
schemeFromArgs ? schemeFromArgs : this.runOptions.scheme,
);
}
public async getTarget(): Promise<IOSTarget> {
if (!this.target) {
const targetFromRunArgs = await this.getTargetFromRunArgs();
if (targetFromRunArgs) {
this.target = targetFromRunArgs;
} else {
const targets = (await this.targetManager.getTargetList()) as IDebuggableIOSTarget[];
const targetsBySpecifiedType = targets.filter(target => {
switch (this.runOptions.target) {
case TargetType.Simulator:
return target.isVirtualTarget;
case TargetType.Device:
return !target.isVirtualTarget;
case undefined:
case "":
return true;
default:
return (
target.id === this.runOptions.target ||
target.name === this.runOptions.target
);
}
});
if (targetsBySpecifiedType.length) {
this.target = IOSTarget.fromInterface(targetsBySpecifiedType[0]);
} else if (targets.length) {
this.logger.warning(
localize(
"ThereIsNoTargetWithSpecifiedTargetType",
"There is no any target with specified target type '{0}'. Continue with any target.",
this.runOptions.target,
),
);
this.target = IOSTarget.fromInterface(targets[0]);
} else {
throw ErrorHelper.getInternalError(
InternalErrorCode.IOSThereIsNoAnyDebuggableTarget,
);
}
}
}
return this.target;
}
public async showDevMenu(appLauncher: AppLauncher): Promise<void> {
const worker = appLauncher.getAppWorker();
if (worker) {
worker.showDevMenuCommand();
}
}
public async reloadApp(appLauncher: AppLauncher): Promise<void> {
const worker = appLauncher.getAppWorker();
if (worker) {
worker.reloadAppCommand();
}
}
public async runApp(): Promise<void> {
let extProps = {
platform: {
value: PlatformType.iOS,
isPii: false,
},
};
extProps = TelemetryHelper.addPlatformPropertiesToTelemetryProperties(
this.runOptions,
this.runOptions.reactNativeVersions,
extProps,
);
await TelemetryHelper.generate("iOSPlatform.runApp", extProps, async () => {
// Compile, deploy, and launch the app on either a simulator or a device
const env = GeneralMobilePlatform.getEnvArgument(
process.env,
this.runOptions.env,
this.runOptions.envFile,
);
if (
!semver.valid(
this.runOptions.reactNativeVersions.reactNativeVersion,
) /*Custom RN implementations should support this flag*/ ||
semver.gte(
this.runOptions.reactNativeVersions.reactNativeVersion,
IOSPlatform.NO_PACKAGER_VERSION,
)
) {
this.runArguments.push("--no-packager");
}
// Since @react-native-community/cli@2.1.0 build output are hidden by default
// we are using `--verbose` to show it as it contains `BUILD SUCCESSFUL` and other patterns
if (semver.gte(this.runOptions.reactNativeVersions.reactNativeVersion, "0.60.0")) {
this.runArguments.push("--verbose");
}
const runIosSpawn = new CommandExecutor(
this.runOptions.nodeModulesRoot,
this.projectPath,
this.logger,
).spawnReactCommand("run-ios", this.runArguments, { env });
await new OutputVerifier(
() =>
this.generateSuccessPatterns(
this.runOptions.reactNativeVersions.reactNativeVersion,
),
() => Promise.resolve(IOSPlatform.RUN_IOS_FAILURE_PATTERNS),
PlatformType.iOS,
).process(runIosSpawn);
});
}
public async enableJSDebuggingMode(): Promise<void> {
// Configure the app for debugging
if (!(await this.getTarget()).isVirtualTarget) {
// Note that currently we cannot automatically switch the device into debug mode.
this.logger.info(
"Application is running on a device, please shake device and select 'Debug JS Remotely' to enable debugging.",
);
return;
}
// Wait until the configuration file exists, and check to see if debugging is enabled
const [debugModeEnabled, bundleId] = await Promise.all<boolean | string>([
this.iosDebugModeManager.getAppRemoteDebuggingSetting(
this.runOptions.configuration,
this.runOptions.productName,
),
this.getBundleId(),
]);
if (debugModeEnabled) {
return;
}
// Debugging must still be enabled
// We enable debugging by writing to a plist file that backs a NSUserDefaults object,
// but that file is written to by the app on occasion. To avoid races, we shut the app
// down before writing to the file.
const childProcess = new ChildProcess();
const output = await childProcess.execToString("xcrun simctl spawn booted launchctl list");
// Try to find an entry that looks like UIKitApplication:com.example.myApp[0x4f37]
const regex = new RegExp(`(\\S+${bundleId}\\S+)`);
const match = regex.exec(output);
// If we don't find a match, the app must not be running and so we do not need to close it
if (match) {
await childProcess.exec(`xcrun simctl spawn booted launchctl stop ${match[1]}`);
}
// Write to the settings file while the app is not running to avoid races
await this.iosDebugModeManager.setAppRemoteDebuggingSetting(
/*enable=*/ true,
this.runOptions.configuration,
this.runOptions.productName,
);
// Relaunch the app
return await this.runApp();
}
public async disableJSDebuggingMode(): Promise<void> {
if (!(await this.getTarget()).isVirtualTarget) {
return;
}
return this.iosDebugModeManager.setAppRemoteDebuggingSetting(
/*enable=*/ false,
this.runOptions.configuration,
this.runOptions.productName,
);
}
public prewarmBundleCache(): Promise<void> {
return this.packager.prewarmBundleCache(PlatformType.iOS);
}
public getRunArguments(): string[] {
let runArguments: string[] = [];
if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
runArguments = this.runOptions.runArguments;
if (this.runOptions.scheme) {
const schemeFromArgs = IOSPlatform.getOptFromRunArgs(
runArguments,
"--scheme",
false,
);
if (!schemeFromArgs) {
runArguments.push("--scheme", this.runOptions.scheme);
} else {
this.logger.warning(
localize(
"iosSchemeParameterAlreadySetInRunArguments",
"'--scheme' is set as 'runArguments' configuration parameter value, 'scheme' configuration parameter value will be omitted",
),
);
}
}
} else {
if (this.runOptions.target) {
runArguments.push(...this.handleTargetArg(this.runOptions.target));
}
if (this.runOptions.iosRelativeProjectPath) {
runArguments.push("--project-path", this.runOptions.iosRelativeProjectPath);
}
// provide any defined scheme
if (this.runOptions.scheme) {
runArguments.push("--scheme", this.runOptions.scheme);
}
}
return runArguments;
}
public async getTargetFromRunArgs(): Promise<IOSTarget | undefined> {
const targets = (await this.targetManager.getTargetList()) as IDebuggableIOSTarget[];
if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
const udid = GeneralMobilePlatform.getOptFromRunArgs(
this.runOptions.runArguments,
"--udid",
);
if (udid) {
const target = targets.find(target => target.id === udid);
if (target) {
return IOSTarget.fromInterface(target);
}
}
const device = GeneralMobilePlatform.getOptFromRunArgs(
this.runOptions.runArguments,
"--device",
);
if (device) {
const target = targets.find(
target =>
!target.isVirtualTarget && (target.id === device || target.name === device),
);
if (target) {
return IOSTarget.fromInterface(target);
}
}
const simulator = GeneralMobilePlatform.getOptFromRunArgs(
this.runOptions.runArguments,
"--simulator",
);
if (simulator) {
const target = targets.find(
target =>
target.isVirtualTarget &&
(target.id === simulator || target.name === simulator),
);
if (target) {
return IOSTarget.fromInterface(target);
}
}
}
return undefined;
}
private handleTargetArg(target: string): string[] {
if (target === TargetType.Device || target === TargetType.Simulator) {
return [`--${target}`];
} else {
return ["--udid", target];
}
}
private async generateSuccessPatterns(version: string): Promise<string[]> {
// Clone RUN_IOS_SUCCESS_PATTERNS to avoid its runtime mutation
let successPatterns = [...IOSPlatform.RUN_IOS_SUCCESS_PATTERNS];
if (!(await this.getTarget()).isVirtualTarget) {
if (semver.gte(version, "0.60.0")) {
successPatterns.push("success Installed the app on the device");
} else {
successPatterns.push("INSTALLATION SUCCEEDED");
}
return successPatterns;
} else {
const bundleId = await this.getBundleId();
if (semver.gte(version, "0.60.0")) {
successPatterns.push(
`Launching "${bundleId}"\nsuccess Successfully launched the app `,
);
} else {
successPatterns.push(`Launching ${bundleId}\n${bundleId}: `);
}
return successPatterns;
}
}
private getConfiguration(): string {
return (
IOSPlatform.getOptFromRunArgs(this.runArguments, this.configurationArgumentName) ||
this.defaultConfiguration
);
}
private getBundleId(): Promise<string> {
let scheme = this.runOptions.scheme;
if (!scheme) {
const schemeFromArgs = IOSPlatform.getOptFromRunArgs(
this.runArguments,
"--scheme",
false,
);
if (schemeFromArgs) {
scheme = schemeFromArgs;
}
}
return this.plistBuddy.getBundleId(
this.iosProjectRoot,
this.projectPath,
PlatformType.iOS,
true,
this.runOptions.configuration,
this.runOptions.productName,
scheme,
);
}
} | the_stack |
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** A date string, such as 2007-12-03, compliant with the `full-date` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */
Date: any;
/** A date-time string at UTC, such as 2007-12-03T10:15:30Z, compliant with the `date-time` format outlined in section 5.6 of the RFC 3339 profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */
DateTime: any;
/** A time string at UTC, such as 10:15:30Z, compliant with the `full-time` format outlined in section 5.6 of the RFC 3339profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar. */
Time: any;
};
export type AmbossSubscriptionType = {
__typename?: 'AmbossSubscriptionType';
end_date: Scalars['String'];
subscribed: Scalars['Boolean'];
upgradable: Scalars['Boolean'];
};
export type AmbossUserType = {
__typename?: 'AmbossUserType';
subscription?: Maybe<AmbossSubscriptionType>;
};
export type AuthResponse = {
__typename?: 'AuthResponse';
message: Scalars['String'];
status: Scalars['String'];
};
export type BalancesType = {
__typename?: 'BalancesType';
lightning: LightningBalanceType;
onchain: OnChainBalanceType;
};
export type BaseInfo = {
__typename?: 'BaseInfo';
apiTokenOriginalSatPrice: Scalars['Int'];
apiTokenSatPrice: Scalars['Int'];
lastBosUpdate: Scalars['String'];
};
export type BoltzInfoType = {
__typename?: 'BoltzInfoType';
feePercent: Scalars['Float'];
max: Scalars['Int'];
min: Scalars['Int'];
};
export type BoltzSwap = {
__typename?: 'BoltzSwap';
boltz?: Maybe<BoltzSwapStatus>;
id?: Maybe<Scalars['String']>;
};
export type BoltzSwapStatus = {
__typename?: 'BoltzSwapStatus';
status: Scalars['String'];
transaction?: Maybe<BoltzSwapTransaction>;
};
export type BoltzSwapTransaction = {
__typename?: 'BoltzSwapTransaction';
eta?: Maybe<Scalars['Int']>;
hex?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['String']>;
};
export type BosScore = {
__typename?: 'BosScore';
alias: Scalars['String'];
position: Scalars['Float'];
public_key: Scalars['String'];
score: Scalars['Float'];
updated: Scalars['String'];
};
export type BosScoreInfo = {
__typename?: 'BosScoreInfo';
count: Scalars['Float'];
first?: Maybe<BosScore>;
last?: Maybe<BosScore>;
};
export type ChannelRequest = {
__typename?: 'ChannelRequest';
callback?: Maybe<Scalars['String']>;
k1?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
uri?: Maybe<Scalars['String']>;
};
export type CreateBoltzReverseSwapType = {
__typename?: 'CreateBoltzReverseSwapType';
decodedInvoice?: Maybe<DecodeType>;
id: Scalars['String'];
invoice: Scalars['String'];
lockupAddress: Scalars['String'];
minerFeeInvoice?: Maybe<Scalars['String']>;
onchainAmount: Scalars['Int'];
preimage?: Maybe<Scalars['String']>;
preimageHash?: Maybe<Scalars['String']>;
privateKey?: Maybe<Scalars['String']>;
publicKey?: Maybe<Scalars['String']>;
receivingAddress: Scalars['String'];
redeemScript: Scalars['String'];
timeoutBlockHeight: Scalars['Int'];
};
export type CreateMacaroon = {
__typename?: 'CreateMacaroon';
base: Scalars['String'];
hex: Scalars['String'];
};
export type Forward = {
__typename?: 'Forward';
created_at: Scalars['String'];
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
incoming_channel: Scalars['String'];
mtokens: Scalars['String'];
outgoing_channel: Scalars['String'];
tokens: Scalars['Int'];
};
export type ForwardNodeType = {
__typename?: 'ForwardNodeType';
alias?: Maybe<Scalars['String']>;
capacity?: Maybe<Scalars['String']>;
channel_count?: Maybe<Scalars['Int']>;
channel_id?: Maybe<Scalars['String']>;
color?: Maybe<Scalars['String']>;
public_key?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['String']>;
};
export type GetRouteType = {
__typename?: 'GetRouteType';
confidence?: Maybe<Scalars['Int']>;
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
hops: Array<RouteHopType>;
messages?: Maybe<Array<Maybe<RouteMessageType>>>;
mtokens: Scalars['String'];
safe_fee: Scalars['Int'];
safe_tokens: Scalars['Int'];
timeout: Scalars['Int'];
tokens: Scalars['Int'];
};
export type InvoicePayment = {
__typename?: 'InvoicePayment';
in_channel: Scalars['String'];
messages?: Maybe<MessageType>;
};
export type InvoiceType = {
__typename?: 'InvoiceType';
chain_address?: Maybe<Scalars['String']>;
confirmed_at?: Maybe<Scalars['String']>;
created_at: Scalars['String'];
date: Scalars['String'];
description: Scalars['String'];
description_hash?: Maybe<Scalars['String']>;
expires_at: Scalars['String'];
id: Scalars['String'];
is_canceled?: Maybe<Scalars['Boolean']>;
is_confirmed: Scalars['Boolean'];
is_held?: Maybe<Scalars['Boolean']>;
is_private: Scalars['Boolean'];
is_push?: Maybe<Scalars['Boolean']>;
payments: Array<Maybe<InvoicePayment>>;
received: Scalars['Int'];
received_mtokens: Scalars['String'];
request?: Maybe<Scalars['String']>;
secret: Scalars['String'];
tokens: Scalars['String'];
type: Scalars['String'];
};
export type LightningAddress = {
__typename?: 'LightningAddress';
lightning_address: Scalars['String'];
pubkey: Scalars['String'];
};
export type LightningBalanceType = {
__typename?: 'LightningBalanceType';
active: Scalars['String'];
commit: Scalars['String'];
confirmed: Scalars['String'];
pending: Scalars['String'];
};
export type LightningNodeSocialInfo = {
__typename?: 'LightningNodeSocialInfo';
socials?: Maybe<NodeSocial>;
};
export type LnMarketsUserInfo = {
__typename?: 'LnMarketsUserInfo';
account_type?: Maybe<Scalars['String']>;
balance?: Maybe<Scalars['String']>;
last_ip?: Maybe<Scalars['String']>;
linkingpublickey?: Maybe<Scalars['String']>;
uid?: Maybe<Scalars['String']>;
username?: Maybe<Scalars['String']>;
};
export type LnUrlRequest = ChannelRequest | PayRequest | WithdrawRequest;
export type MessageType = {
__typename?: 'MessageType';
message?: Maybe<Scalars['String']>;
};
export type Mutation = {
__typename?: 'Mutation';
addPeer?: Maybe<Scalars['Boolean']>;
bosPay?: Maybe<Scalars['Boolean']>;
bosRebalance?: Maybe<BosRebalanceResultType>;
circularRebalance?: Maybe<Scalars['Boolean']>;
claimBoltzTransaction: Scalars['String'];
closeChannel?: Maybe<CloseChannelType>;
createAddress?: Maybe<Scalars['String']>;
createBaseInvoice?: Maybe<BaseInvoiceType>;
createBaseToken: Scalars['Boolean'];
createBaseTokenInvoice?: Maybe<BaseInvoiceType>;
createBoltzReverseSwap: CreateBoltzReverseSwapType;
createInvoice?: Maybe<NewInvoiceType>;
createMacaroon: CreateMacaroon;
createThunderPoints: Scalars['Boolean'];
deleteBaseToken: Scalars['Boolean'];
fetchLnUrl?: Maybe<LnUrlRequest>;
getAuthToken: Scalars['Boolean'];
getSessionToken: Scalars['String'];
keysend?: Maybe<PayType>;
lnMarketsDeposit: Scalars['Boolean'];
lnMarketsLogin: AuthResponse;
lnMarketsLogout: Scalars['Boolean'];
lnMarketsWithdraw: Scalars['Boolean'];
lnUrlAuth: AuthResponse;
lnUrlChannel: Scalars['String'];
lnUrlPay: PaySuccess;
lnUrlWithdraw: Scalars['String'];
loginAmboss?: Maybe<Scalars['Boolean']>;
logout: Scalars['Boolean'];
openChannel?: Maybe<OpenChannelType>;
pay?: Maybe<Scalars['Boolean']>;
payViaRoute?: Maybe<Scalars['Boolean']>;
removePeer?: Maybe<Scalars['Boolean']>;
sendMessage?: Maybe<Scalars['Int']>;
sendToAddress?: Maybe<SendToType>;
updateFees?: Maybe<Scalars['Boolean']>;
updateMultipleFees?: Maybe<Scalars['Boolean']>;
};
export type MutationAddPeerArgs = {
isTemporary?: Maybe<Scalars['Boolean']>;
publicKey?: Maybe<Scalars['String']>;
socket?: Maybe<Scalars['String']>;
url?: Maybe<Scalars['String']>;
};
export type MutationBosPayArgs = {
max_fee: Scalars['Int'];
max_paths: Scalars['Int'];
message?: Maybe<Scalars['String']>;
out?: Maybe<Array<Maybe<Scalars['String']>>>;
request: Scalars['String'];
};
export type MutationBosRebalanceArgs = {
avoid?: Maybe<Array<Maybe<Scalars['String']>>>;
in_through?: Maybe<Scalars['String']>;
max_fee?: Maybe<Scalars['Int']>;
max_fee_rate?: Maybe<Scalars['Int']>;
max_rebalance?: Maybe<Scalars['Int']>;
node?: Maybe<Scalars['String']>;
out_inbound?: Maybe<Scalars['Int']>;
out_through?: Maybe<Scalars['String']>;
timeout_minutes?: Maybe<Scalars['Int']>;
};
export type MutationCircularRebalanceArgs = {
route: Scalars['String'];
};
export type MutationClaimBoltzTransactionArgs = {
destination: Scalars['String'];
fee: Scalars['Int'];
preimage: Scalars['String'];
privateKey: Scalars['String'];
redeem: Scalars['String'];
transaction: Scalars['String'];
};
export type MutationCloseChannelArgs = {
forceClose?: Maybe<Scalars['Boolean']>;
id: Scalars['String'];
targetConfirmations?: Maybe<Scalars['Int']>;
tokensPerVByte?: Maybe<Scalars['Int']>;
};
export type MutationCreateAddressArgs = {
nested?: Maybe<Scalars['Boolean']>;
};
export type MutationCreateBaseInvoiceArgs = {
amount: Scalars['Int'];
};
export type MutationCreateBaseTokenArgs = {
id: Scalars['String'];
};
export type MutationCreateBoltzReverseSwapArgs = {
address?: Maybe<Scalars['String']>;
amount: Scalars['Int'];
};
export type MutationCreateInvoiceArgs = {
amount: Scalars['Int'];
description?: Maybe<Scalars['String']>;
includePrivate?: Maybe<Scalars['Boolean']>;
secondsUntil?: Maybe<Scalars['Int']>;
};
export type MutationCreateMacaroonArgs = {
permissions: PermissionsType;
};
export type MutationCreateThunderPointsArgs = {
alias: Scalars['String'];
id: Scalars['String'];
public_key: Scalars['String'];
uris: Array<Scalars['String']>;
};
export type MutationFetchLnUrlArgs = {
url: Scalars['String'];
};
export type MutationGetAuthTokenArgs = {
cookie?: Maybe<Scalars['String']>;
};
export type MutationGetSessionTokenArgs = {
id?: Maybe<Scalars['String']>;
password?: Maybe<Scalars['String']>;
};
export type MutationKeysendArgs = {
destination: Scalars['String'];
tokens: Scalars['Int'];
};
export type MutationLnMarketsDepositArgs = {
amount: Scalars['Int'];
};
export type MutationLnMarketsWithdrawArgs = {
amount: Scalars['Int'];
};
export type MutationLnUrlAuthArgs = {
url: Scalars['String'];
};
export type MutationLnUrlChannelArgs = {
callback: Scalars['String'];
k1: Scalars['String'];
uri: Scalars['String'];
};
export type MutationLnUrlPayArgs = {
amount: Scalars['Int'];
callback: Scalars['String'];
comment?: Maybe<Scalars['String']>;
};
export type MutationLnUrlWithdrawArgs = {
amount: Scalars['Int'];
callback: Scalars['String'];
description?: Maybe<Scalars['String']>;
k1: Scalars['String'];
};
export type MutationOpenChannelArgs = {
amount: Scalars['Int'];
isPrivate?: Maybe<Scalars['Boolean']>;
partnerPublicKey: Scalars['String'];
pushTokens?: Maybe<Scalars['Int']>;
tokensPerVByte?: Maybe<Scalars['Int']>;
};
export type MutationPayArgs = {
max_fee: Scalars['Int'];
max_paths: Scalars['Int'];
out?: Maybe<Array<Maybe<Scalars['String']>>>;
request: Scalars['String'];
};
export type MutationPayViaRouteArgs = {
id: Scalars['String'];
route: Scalars['String'];
};
export type MutationRemovePeerArgs = {
publicKey: Scalars['String'];
};
export type MutationSendMessageArgs = {
maxFee?: Maybe<Scalars['Int']>;
message: Scalars['String'];
messageType?: Maybe<Scalars['String']>;
publicKey: Scalars['String'];
tokens?: Maybe<Scalars['Int']>;
};
export type MutationSendToAddressArgs = {
address: Scalars['String'];
fee?: Maybe<Scalars['Int']>;
sendAll?: Maybe<Scalars['Boolean']>;
target?: Maybe<Scalars['Int']>;
tokens?: Maybe<Scalars['Int']>;
};
export type MutationUpdateFeesArgs = {
base_fee_tokens?: Maybe<Scalars['Float']>;
cltv_delta?: Maybe<Scalars['Int']>;
fee_rate?: Maybe<Scalars['Int']>;
max_htlc_mtokens?: Maybe<Scalars['String']>;
min_htlc_mtokens?: Maybe<Scalars['String']>;
transaction_id?: Maybe<Scalars['String']>;
transaction_vout?: Maybe<Scalars['Int']>;
};
export type MutationUpdateMultipleFeesArgs = {
channels: Array<ChannelDetailInput>;
};
export type Node = {
__typename?: 'Node';
node: NodeType;
};
export type NodeBosHistory = {
__typename?: 'NodeBosHistory';
info: BosScoreInfo;
scores: Array<BosScore>;
};
export type NodeSocial = {
__typename?: 'NodeSocial';
info?: Maybe<NodeSocialInfo>;
};
export type NodeSocialInfo = {
__typename?: 'NodeSocialInfo';
email?: Maybe<Scalars['String']>;
private?: Maybe<Scalars['Boolean']>;
telegram?: Maybe<Scalars['String']>;
twitter?: Maybe<Scalars['String']>;
twitter_verified?: Maybe<Scalars['Boolean']>;
website?: Maybe<Scalars['String']>;
};
export type OnChainBalanceType = {
__typename?: 'OnChainBalanceType';
closing: Scalars['String'];
confirmed: Scalars['String'];
pending: Scalars['String'];
};
export type PayRequest = {
__typename?: 'PayRequest';
callback?: Maybe<Scalars['String']>;
commentAllowed?: Maybe<Scalars['Int']>;
maxSendable?: Maybe<Scalars['String']>;
metadata?: Maybe<Scalars['String']>;
minSendable?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
};
export type PaySuccess = {
__typename?: 'PaySuccess';
ciphertext?: Maybe<Scalars['String']>;
description?: Maybe<Scalars['String']>;
iv?: Maybe<Scalars['String']>;
message?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
url?: Maybe<Scalars['String']>;
};
export type PaymentType = {
__typename?: 'PaymentType';
created_at: Scalars['String'];
date: Scalars['String'];
destination: Scalars['String'];
destination_node?: Maybe<Node>;
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
hops: Array<Node>;
id: Scalars['String'];
index?: Maybe<Scalars['Int']>;
is_confirmed: Scalars['Boolean'];
is_outgoing: Scalars['Boolean'];
mtokens: Scalars['String'];
request?: Maybe<Scalars['String']>;
safe_fee: Scalars['Int'];
safe_tokens?: Maybe<Scalars['Int']>;
secret: Scalars['String'];
tokens: Scalars['String'];
type: Scalars['String'];
};
export type ProbeRoute = {
__typename?: 'ProbeRoute';
route?: Maybe<ProbedRoute>;
};
export type Query = {
__typename?: 'Query';
adminCheck?: Maybe<Scalars['Boolean']>;
decodeRequest?: Maybe<DecodeType>;
getAccount?: Maybe<ServerAccountType>;
getAccountingReport: Scalars['String'];
getAmbossLoginToken: Scalars['String'];
getAmbossUser?: Maybe<AmbossUserType>;
getBackups?: Maybe<Scalars['String']>;
getBaseCanConnect: Scalars['Boolean'];
getBaseInfo: BaseInfo;
getBaseNodes: Array<Maybe<BaseNodesType>>;
getBasePoints: Array<Maybe<BasePointsType>>;
getBitcoinFees?: Maybe<BitcoinFeeType>;
getBitcoinPrice?: Maybe<Scalars['String']>;
getBoltzInfo: BoltzInfoType;
getBoltzSwapStatus: Array<Maybe<BoltzSwap>>;
getBosScores: Array<BosScore>;
getChainTransactions?: Maybe<Array<Maybe<GetTransactionsType>>>;
getChannel: SingleChannelType;
getChannelReport?: Maybe<ChannelReportType>;
getChannels: Array<Maybe<ChannelType>>;
getClosedChannels?: Maybe<Array<Maybe<ClosedChannelType>>>;
getFeeHealth?: Maybe<ChannelsFeeHealth>;
getForwardChannelsReport?: Maybe<Scalars['String']>;
getForwards: Array<Maybe<Forward>>;
getInvoiceStatusChange?: Maybe<Scalars['String']>;
getLatestVersion?: Maybe<Scalars['String']>;
getLightningAddressInfo: PayRequest;
getLightningAddresses: Array<LightningAddress>;
getLnMarketsStatus: Scalars['String'];
getLnMarketsUrl: Scalars['String'];
getLnMarketsUserInfo?: Maybe<LnMarketsUserInfo>;
getMessages?: Maybe<GetMessagesType>;
getNetworkInfo?: Maybe<NetworkInfoType>;
getNode: Node;
getNodeBalances: BalancesType;
getNodeBosHistory: NodeBosHistory;
getNodeInfo?: Maybe<NodeInfoType>;
getNodeSocialInfo: LightningNodeSocialInfo;
getPeers?: Maybe<Array<Maybe<PeerType>>>;
getPendingChannels?: Maybe<Array<Maybe<PendingChannelType>>>;
getResume: GetResumeType;
getRoutes?: Maybe<GetRouteType>;
getServerAccounts?: Maybe<Array<Maybe<ServerAccountType>>>;
getTimeHealth?: Maybe<ChannelsTimeHealth>;
getUtxos?: Maybe<Array<Maybe<GetUtxosType>>>;
getVolumeHealth?: Maybe<ChannelsHealth>;
getWalletInfo?: Maybe<WalletInfoType>;
recoverFunds?: Maybe<Scalars['Boolean']>;
signMessage?: Maybe<Scalars['String']>;
verifyBackups?: Maybe<Scalars['Boolean']>;
verifyMessage?: Maybe<Scalars['String']>;
};
export type QueryDecodeRequestArgs = {
request: Scalars['String'];
};
export type QueryGetAccountingReportArgs = {
category?: Maybe<Scalars['String']>;
currency?: Maybe<Scalars['String']>;
fiat?: Maybe<Scalars['String']>;
month?: Maybe<Scalars['String']>;
year?: Maybe<Scalars['String']>;
};
export type QueryGetBitcoinFeesArgs = {
logger?: Maybe<Scalars['Boolean']>;
};
export type QueryGetBitcoinPriceArgs = {
currency?: Maybe<Scalars['String']>;
logger?: Maybe<Scalars['Boolean']>;
};
export type QueryGetBoltzSwapStatusArgs = {
ids: Array<Maybe<Scalars['String']>>;
};
export type QueryGetChannelArgs = {
id: Scalars['String'];
pubkey?: Maybe<Scalars['String']>;
};
export type QueryGetChannelsArgs = {
active?: Maybe<Scalars['Boolean']>;
};
export type QueryGetClosedChannelsArgs = {
type?: Maybe<Scalars['String']>;
};
export type QueryGetForwardChannelsReportArgs = {
order?: Maybe<Scalars['String']>;
time?: Maybe<Scalars['String']>;
type?: Maybe<Scalars['String']>;
};
export type QueryGetForwardsArgs = {
days: Scalars['Int'];
};
export type QueryGetInvoiceStatusChangeArgs = {
id: Scalars['String'];
};
export type QueryGetLightningAddressInfoArgs = {
address: Scalars['String'];
};
export type QueryGetMessagesArgs = {
initialize?: Maybe<Scalars['Boolean']>;
lastMessage?: Maybe<Scalars['String']>;
token?: Maybe<Scalars['String']>;
};
export type QueryGetNodeArgs = {
publicKey: Scalars['String'];
withoutChannels?: Maybe<Scalars['Boolean']>;
};
export type QueryGetNodeBosHistoryArgs = {
pubkey: Scalars['String'];
};
export type QueryGetNodeSocialInfoArgs = {
pubkey: Scalars['String'];
};
export type QueryGetResumeArgs = {
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
};
export type QueryGetRoutesArgs = {
incoming: Scalars['String'];
maxFee?: Maybe<Scalars['Int']>;
outgoing: Scalars['String'];
tokens: Scalars['Int'];
};
export type QueryRecoverFundsArgs = {
backup: Scalars['String'];
};
export type QuerySignMessageArgs = {
message: Scalars['String'];
};
export type QueryVerifyBackupsArgs = {
backup: Scalars['String'];
};
export type QueryVerifyMessageArgs = {
message: Scalars['String'];
signature: Scalars['String'];
};
export type RouteHopType = {
__typename?: 'RouteHopType';
channel: Scalars['String'];
channel_capacity: Scalars['Int'];
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
forward: Scalars['Int'];
forward_mtokens: Scalars['String'];
public_key: Scalars['String'];
timeout: Scalars['Int'];
};
export type RouteMessageType = {
__typename?: 'RouteMessageType';
type: Scalars['String'];
value: Scalars['String'];
};
export type RouteType = {
__typename?: 'RouteType';
base_fee_mtokens?: Maybe<Scalars['String']>;
channel?: Maybe<Scalars['String']>;
cltv_delta?: Maybe<Scalars['Int']>;
fee_rate?: Maybe<Scalars['Int']>;
public_key: Scalars['String'];
};
export type Transaction = InvoiceType | PaymentType;
export type WithdrawRequest = {
__typename?: 'WithdrawRequest';
callback?: Maybe<Scalars['String']>;
defaultDescription?: Maybe<Scalars['String']>;
k1?: Maybe<Scalars['String']>;
maxWithdrawable?: Maybe<Scalars['String']>;
minWithdrawable?: Maybe<Scalars['String']>;
tag?: Maybe<Scalars['String']>;
};
export type BaseInvoiceType = {
__typename?: 'baseInvoiceType';
id: Scalars['String'];
request: Scalars['String'];
};
export type BaseNodesType = {
__typename?: 'baseNodesType';
_id?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
public_key: Scalars['String'];
socket: Scalars['String'];
};
export type BasePointsType = {
__typename?: 'basePointsType';
alias: Scalars['String'];
amount: Scalars['Int'];
};
export type BitcoinFeeType = {
__typename?: 'bitcoinFeeType';
fast?: Maybe<Scalars['Int']>;
halfHour?: Maybe<Scalars['Int']>;
hour?: Maybe<Scalars['Int']>;
minimum?: Maybe<Scalars['Int']>;
};
export type BosDecreaseType = {
__typename?: 'bosDecreaseType';
decreased_inbound_on?: Maybe<Scalars['String']>;
liquidity_inbound?: Maybe<Scalars['String']>;
liquidity_inbound_opening?: Maybe<Scalars['String']>;
liquidity_inbound_pending?: Maybe<Scalars['String']>;
liquidity_outbound?: Maybe<Scalars['String']>;
liquidity_outbound_opening?: Maybe<Scalars['String']>;
liquidity_outbound_pending?: Maybe<Scalars['String']>;
};
export type BosIncreaseType = {
__typename?: 'bosIncreaseType';
increased_inbound_on?: Maybe<Scalars['String']>;
liquidity_inbound?: Maybe<Scalars['String']>;
liquidity_inbound_opening?: Maybe<Scalars['String']>;
liquidity_inbound_pending?: Maybe<Scalars['String']>;
liquidity_outbound?: Maybe<Scalars['String']>;
liquidity_outbound_opening?: Maybe<Scalars['String']>;
liquidity_outbound_pending?: Maybe<Scalars['String']>;
};
export type BosRebalanceResultType = {
__typename?: 'bosRebalanceResultType';
decrease?: Maybe<BosDecreaseType>;
increase?: Maybe<BosIncreaseType>;
result?: Maybe<BosResultType>;
};
export type BosResultType = {
__typename?: 'bosResultType';
rebalance_fees_spent?: Maybe<Scalars['String']>;
rebalanced?: Maybe<Scalars['String']>;
};
export type ChannelDetailInput = {
alias?: Maybe<Scalars['String']>;
base_fee_tokens?: Maybe<Scalars['Float']>;
cltv_delta?: Maybe<Scalars['Int']>;
fee_rate?: Maybe<Scalars['Int']>;
id?: Maybe<Scalars['String']>;
max_htlc_mtokens?: Maybe<Scalars['String']>;
min_htlc_mtokens?: Maybe<Scalars['String']>;
transaction_id?: Maybe<Scalars['String']>;
transaction_vout?: Maybe<Scalars['Int']>;
};
export type ChannelFeeHealth = {
__typename?: 'channelFeeHealth';
id?: Maybe<Scalars['String']>;
mySide?: Maybe<FeeHealth>;
partner?: Maybe<Node>;
partnerSide?: Maybe<FeeHealth>;
};
export type ChannelHealth = {
__typename?: 'channelHealth';
averageVolumeNormalized?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['String']>;
partner?: Maybe<Node>;
score?: Maybe<Scalars['Int']>;
volumeNormalized?: Maybe<Scalars['String']>;
};
export type ChannelReportType = {
__typename?: 'channelReportType';
commit?: Maybe<Scalars['Int']>;
incomingPendingHtlc?: Maybe<Scalars['Int']>;
local?: Maybe<Scalars['Int']>;
maxIn?: Maybe<Scalars['Int']>;
maxOut?: Maybe<Scalars['Int']>;
outgoingPendingHtlc?: Maybe<Scalars['Int']>;
remote?: Maybe<Scalars['Int']>;
totalPendingHtlc?: Maybe<Scalars['Int']>;
};
export type ChannelTimeHealth = {
__typename?: 'channelTimeHealth';
id?: Maybe<Scalars['String']>;
monitoredDowntime?: Maybe<Scalars['Int']>;
monitoredTime?: Maybe<Scalars['Int']>;
monitoredUptime?: Maybe<Scalars['Int']>;
partner?: Maybe<Node>;
score?: Maybe<Scalars['Int']>;
significant?: Maybe<Scalars['Boolean']>;
};
export type ChannelType = {
__typename?: 'channelType';
bosScore?: Maybe<BosScore>;
capacity: Scalars['Int'];
channel_age: Scalars['Int'];
commit_transaction_fee: Scalars['Int'];
commit_transaction_weight: Scalars['Int'];
id: Scalars['String'];
is_active: Scalars['Boolean'];
is_closing: Scalars['Boolean'];
is_opening: Scalars['Boolean'];
is_partner_initiated: Scalars['Boolean'];
is_private: Scalars['Boolean'];
is_static_remote_key?: Maybe<Scalars['Boolean']>;
local_balance: Scalars['Int'];
local_reserve: Scalars['Int'];
partner_fee_info?: Maybe<SingleChannelType>;
partner_node_info: Node;
partner_public_key: Scalars['String'];
pending_payments: Array<Maybe<PendingPaymentType>>;
pending_resume: PendingResumeType;
received: Scalars['Int'];
remote_balance: Scalars['Int'];
remote_reserve: Scalars['Int'];
sent: Scalars['Int'];
time_offline?: Maybe<Scalars['Int']>;
time_online?: Maybe<Scalars['Int']>;
transaction_id: Scalars['String'];
transaction_vout: Scalars['Int'];
unsettled_balance: Scalars['Int'];
};
export type ChannelsFeeHealth = {
__typename?: 'channelsFeeHealth';
channels?: Maybe<Array<Maybe<ChannelFeeHealth>>>;
score?: Maybe<Scalars['Int']>;
};
export type ChannelsHealth = {
__typename?: 'channelsHealth';
channels?: Maybe<Array<Maybe<ChannelHealth>>>;
score?: Maybe<Scalars['Int']>;
};
export type ChannelsTimeHealth = {
__typename?: 'channelsTimeHealth';
channels?: Maybe<Array<Maybe<ChannelTimeHealth>>>;
score?: Maybe<Scalars['Int']>;
};
export type CloseChannelType = {
__typename?: 'closeChannelType';
transactionId?: Maybe<Scalars['String']>;
transactionOutputIndex?: Maybe<Scalars['String']>;
};
export type ClosedChannelType = {
__typename?: 'closedChannelType';
capacity: Scalars['Int'];
channel_age: Scalars['Int'];
close_confirm_height?: Maybe<Scalars['Int']>;
close_transaction_id?: Maybe<Scalars['String']>;
final_local_balance: Scalars['Int'];
final_time_locked_balance: Scalars['Int'];
id?: Maybe<Scalars['String']>;
is_breach_close: Scalars['Boolean'];
is_cooperative_close: Scalars['Boolean'];
is_funding_cancel: Scalars['Boolean'];
is_local_force_close: Scalars['Boolean'];
is_remote_force_close: Scalars['Boolean'];
partner_node_info: Node;
partner_public_key: Scalars['String'];
transaction_id: Scalars['String'];
transaction_vout: Scalars['Int'];
};
export type DecodeType = {
__typename?: 'decodeType';
chain_address?: Maybe<Scalars['String']>;
cltv_delta?: Maybe<Scalars['Int']>;
description: Scalars['String'];
description_hash?: Maybe<Scalars['String']>;
destination: Scalars['String'];
destination_node: Node;
expires_at: Scalars['String'];
id: Scalars['String'];
mtokens: Scalars['String'];
payment?: Maybe<Scalars['String']>;
probe_route?: Maybe<ProbeRoute>;
routes: Array<Maybe<Array<Maybe<RouteType>>>>;
safe_tokens: Scalars['Int'];
tokens: Scalars['Int'];
};
export type FeeHealth = {
__typename?: 'feeHealth';
base?: Maybe<Scalars['String']>;
baseOver?: Maybe<Scalars['Boolean']>;
baseScore?: Maybe<Scalars['Int']>;
rate?: Maybe<Scalars['Int']>;
rateOver?: Maybe<Scalars['Boolean']>;
rateScore?: Maybe<Scalars['Int']>;
score?: Maybe<Scalars['Int']>;
};
export type GetMessagesType = {
__typename?: 'getMessagesType';
messages: Array<Maybe<MessagesType>>;
token?: Maybe<Scalars['String']>;
};
export type GetResumeType = {
__typename?: 'getResumeType';
offset?: Maybe<Scalars['Int']>;
resume: Array<Maybe<Transaction>>;
};
export type GetTransactionsType = {
__typename?: 'getTransactionsType';
block_id?: Maybe<Scalars['String']>;
confirmation_count?: Maybe<Scalars['Int']>;
confirmation_height?: Maybe<Scalars['Int']>;
created_at: Scalars['String'];
fee?: Maybe<Scalars['Int']>;
id: Scalars['String'];
output_addresses: Array<Maybe<Scalars['String']>>;
tokens: Scalars['Int'];
};
export type GetUtxosType = {
__typename?: 'getUtxosType';
address: Scalars['String'];
address_format: Scalars['String'];
confirmation_count: Scalars['Int'];
output_script: Scalars['String'];
tokens: Scalars['Int'];
transaction_id: Scalars['String'];
transaction_vout: Scalars['Int'];
};
export type HopsType = {
__typename?: 'hopsType';
channel?: Maybe<Scalars['String']>;
channel_capacity?: Maybe<Scalars['Int']>;
fee_mtokens?: Maybe<Scalars['String']>;
forward_mtokens?: Maybe<Scalars['String']>;
timeout?: Maybe<Scalars['Int']>;
};
export type MessagesType = {
__typename?: 'messagesType';
alias?: Maybe<Scalars['String']>;
contentType?: Maybe<Scalars['String']>;
date: Scalars['String'];
id: Scalars['String'];
message?: Maybe<Scalars['String']>;
sender?: Maybe<Scalars['String']>;
tokens?: Maybe<Scalars['Int']>;
verified: Scalars['Boolean'];
};
export type NetworkInfoType = {
__typename?: 'networkInfoType';
averageChannelSize?: Maybe<Scalars['String']>;
channelCount?: Maybe<Scalars['Int']>;
maxChannelSize?: Maybe<Scalars['Int']>;
medianChannelSize?: Maybe<Scalars['Int']>;
minChannelSize?: Maybe<Scalars['Int']>;
nodeCount?: Maybe<Scalars['Int']>;
notRecentlyUpdatedPolicyCount?: Maybe<Scalars['Int']>;
totalCapacity?: Maybe<Scalars['String']>;
};
export type NewInvoiceType = {
__typename?: 'newInvoiceType';
chain_address?: Maybe<Scalars['String']>;
created_at: Scalars['DateTime'];
description: Scalars['String'];
id: Scalars['String'];
request: Scalars['String'];
secret: Scalars['String'];
tokens?: Maybe<Scalars['Int']>;
};
export type NodeInfoType = {
__typename?: 'nodeInfoType';
active_channels_count: Scalars['Int'];
alias: Scalars['String'];
chains: Array<Scalars['String']>;
closed_channels_count: Scalars['Int'];
color: Scalars['String'];
current_block_hash: Scalars['String'];
current_block_height: Scalars['Int'];
is_synced_to_chain: Scalars['Boolean'];
is_synced_to_graph: Scalars['Boolean'];
latest_block_at: Scalars['String'];
peers_count: Scalars['Int'];
pending_channels_count: Scalars['Int'];
public_key: Scalars['String'];
uris: Array<Scalars['String']>;
version: Scalars['String'];
};
export type NodePolicyType = {
__typename?: 'nodePolicyType';
base_fee_mtokens?: Maybe<Scalars['String']>;
cltv_delta?: Maybe<Scalars['Int']>;
fee_rate?: Maybe<Scalars['Int']>;
is_disabled?: Maybe<Scalars['Boolean']>;
max_htlc_mtokens?: Maybe<Scalars['String']>;
min_htlc_mtokens?: Maybe<Scalars['String']>;
node?: Maybe<Node>;
public_key: Scalars['String'];
updated_at?: Maybe<Scalars['String']>;
};
export type NodeType = {
__typename?: 'nodeType';
alias: Scalars['String'];
capacity?: Maybe<Scalars['String']>;
channel_count?: Maybe<Scalars['Int']>;
color?: Maybe<Scalars['String']>;
public_key?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['String']>;
};
export type OpenChannelType = {
__typename?: 'openChannelType';
transactionId?: Maybe<Scalars['String']>;
transactionOutputIndex?: Maybe<Scalars['String']>;
};
export type PayType = {
__typename?: 'payType';
fee?: Maybe<Scalars['Int']>;
fee_mtokens?: Maybe<Scalars['String']>;
hops?: Maybe<Array<Maybe<HopsType>>>;
id?: Maybe<Scalars['String']>;
is_confirmed?: Maybe<Scalars['Boolean']>;
is_outgoing?: Maybe<Scalars['Boolean']>;
mtokens?: Maybe<Scalars['String']>;
safe_fee?: Maybe<Scalars['Int']>;
safe_tokens?: Maybe<Scalars['Int']>;
secret?: Maybe<Scalars['String']>;
tokens?: Maybe<Scalars['Int']>;
};
export type PeerType = {
__typename?: 'peerType';
bytes_received: Scalars['Int'];
bytes_sent: Scalars['Int'];
is_inbound: Scalars['Boolean'];
is_sync_peer?: Maybe<Scalars['Boolean']>;
partner_node_info: Node;
ping_time: Scalars['Int'];
public_key: Scalars['String'];
socket: Scalars['String'];
tokens_received: Scalars['Int'];
tokens_sent: Scalars['Int'];
};
export type PendingChannelType = {
__typename?: 'pendingChannelType';
close_transaction_id?: Maybe<Scalars['String']>;
is_active: Scalars['Boolean'];
is_closing: Scalars['Boolean'];
is_opening: Scalars['Boolean'];
is_timelocked: Scalars['Boolean'];
local_balance: Scalars['Int'];
local_reserve: Scalars['Int'];
partner_node_info: Node;
partner_public_key: Scalars['String'];
received: Scalars['Int'];
remote_balance: Scalars['Int'];
remote_reserve: Scalars['Int'];
sent: Scalars['Int'];
timelock_blocks?: Maybe<Scalars['Int']>;
timelock_expiration?: Maybe<Scalars['Int']>;
transaction_fee?: Maybe<Scalars['Int']>;
transaction_id: Scalars['String'];
transaction_vout: Scalars['Int'];
};
export type PendingPaymentType = {
__typename?: 'pendingPaymentType';
id: Scalars['String'];
is_outgoing: Scalars['Boolean'];
timeout: Scalars['Int'];
tokens: Scalars['Int'];
};
export type PendingResumeType = {
__typename?: 'pendingResumeType';
incoming_amount: Scalars['Int'];
incoming_tokens: Scalars['Int'];
outgoing_amount: Scalars['Int'];
outgoing_tokens: Scalars['Int'];
total_amount: Scalars['Int'];
total_tokens: Scalars['Int'];
};
export type PermissionsType = {
is_ok_to_adjust_peers?: Maybe<Scalars['Boolean']>;
is_ok_to_create_chain_addresses?: Maybe<Scalars['Boolean']>;
is_ok_to_create_invoices?: Maybe<Scalars['Boolean']>;
is_ok_to_create_macaroons?: Maybe<Scalars['Boolean']>;
is_ok_to_derive_keys?: Maybe<Scalars['Boolean']>;
is_ok_to_get_chain_transactions?: Maybe<Scalars['Boolean']>;
is_ok_to_get_invoices?: Maybe<Scalars['Boolean']>;
is_ok_to_get_payments?: Maybe<Scalars['Boolean']>;
is_ok_to_get_peers?: Maybe<Scalars['Boolean']>;
is_ok_to_get_wallet_info?: Maybe<Scalars['Boolean']>;
is_ok_to_pay?: Maybe<Scalars['Boolean']>;
is_ok_to_send_to_chain_addresses?: Maybe<Scalars['Boolean']>;
is_ok_to_sign_bytes?: Maybe<Scalars['Boolean']>;
is_ok_to_sign_messages?: Maybe<Scalars['Boolean']>;
is_ok_to_stop_daemon?: Maybe<Scalars['Boolean']>;
is_ok_to_verify_bytes_signatures?: Maybe<Scalars['Boolean']>;
is_ok_to_verify_messages?: Maybe<Scalars['Boolean']>;
};
export type PolicyType = {
__typename?: 'policyType';
base_fee_mtokens?: Maybe<Scalars['String']>;
cltv_delta?: Maybe<Scalars['Int']>;
fee_rate?: Maybe<Scalars['Int']>;
is_disabled?: Maybe<Scalars['Boolean']>;
max_htlc_mtokens?: Maybe<Scalars['String']>;
min_htlc_mtokens?: Maybe<Scalars['String']>;
public_key: Scalars['String'];
updated_at?: Maybe<Scalars['String']>;
};
export type ProbedRoute = {
__typename?: 'probedRoute';
confidence: Scalars['Int'];
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
hops: Array<ProbedRouteHop>;
mtokens: Scalars['String'];
safe_fee: Scalars['Int'];
safe_tokens: Scalars['Int'];
timeout: Scalars['Int'];
tokens: Scalars['Int'];
};
export type ProbedRouteHop = {
__typename?: 'probedRouteHop';
channel: Scalars['String'];
channel_capacity: Scalars['Int'];
fee: Scalars['Int'];
fee_mtokens: Scalars['String'];
forward: Scalars['Int'];
forward_mtokens: Scalars['String'];
node: Node;
public_key: Scalars['String'];
timeout: Scalars['Int'];
};
export type SendToType = {
__typename?: 'sendToType';
confirmationCount: Scalars['String'];
id: Scalars['String'];
isConfirmed: Scalars['Boolean'];
isOutgoing: Scalars['Boolean'];
tokens?: Maybe<Scalars['Int']>;
};
export type ServerAccountType = {
__typename?: 'serverAccountType';
id: Scalars['String'];
loggedIn: Scalars['Boolean'];
name: Scalars['String'];
type: Scalars['String'];
};
export type SingleChannelType = {
__typename?: 'singleChannelType';
capacity: Scalars['Int'];
id: Scalars['String'];
node_policies?: Maybe<NodePolicyType>;
partner_node_policies?: Maybe<NodePolicyType>;
policies: Array<PolicyType>;
transaction_id: Scalars['String'];
transaction_vout: Scalars['Int'];
updated_at?: Maybe<Scalars['String']>;
};
export type WalletInfoType = {
__typename?: 'walletInfoType';
build_tags: Array<Scalars['String']>;
commit_hash: Scalars['String'];
is_autopilotrpc_enabled: Scalars['Boolean'];
is_chainrpc_enabled: Scalars['Boolean'];
is_invoicesrpc_enabled: Scalars['Boolean'];
is_signrpc_enabled: Scalars['Boolean'];
is_walletrpc_enabled: Scalars['Boolean'];
is_watchtowerrpc_enabled: Scalars['Boolean'];
is_wtclientrpc_enabled: Scalars['Boolean'];
}; | the_stack |
import useRaf from '@rooks/use-raf'
import useInterval from '@use-it/interval'
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import Button from '../../docs/fixtures/Button'
import Code from '../../docs/fixtures/Code'
import Container from '../../docs/fixtures/Container'
import Expandable from '../../docs/fixtures/Expandable'
import Kbd from '../../docs/fixtures/Kbd'
import SheetContent from '../../docs/fixtures/SheetContent'
import { BottomSheet, BottomSheetRef } from '../../src'
// Just to test we can stop re-renders with this pattern when necessary
const MemoBottomSheet = memo(BottomSheet)
function One() {
const [open, setOpen] = useState(false)
const [renders, setRenders] = useState(1)
const style = useMemo(() => ({ ['--rsbs-bg' as any]: '#EFF6FF' }), [])
const onDismiss = useCallback(() => setOpen(false), [])
const children = useMemo(
() => (
<SheetContent>
<p>
Using <Code>onDismiss</Code> lets users close the sheet by swiping it
down, tapping on the backdrop or by hitting <Kbd>esc</Kbd> on their
keyboard.
</p>
<Button
onClick={onDismiss}
className="w-full focus-visible:ring-offset-rsbs-bg"
>
Dismiss
</Button>
</SheetContent>
),
[onDismiss]
)
useRaf(() => {
setRenders(renders + 1)
}, open)
useEffect(() => {
if (open) {
return () => {
setRenders(1)
}
}
}, [open])
return (
<>
<Button onClick={() => setOpen(true)}>{renders}</Button>
<MemoBottomSheet
style={style}
open={open}
header={false}
onDismiss={onDismiss}
>
{children}
</MemoBottomSheet>
</>
)
}
function Two() {
const [open, setOpen] = useState(false)
const [header, setHeader] = useState(false)
function onDismiss() {
setOpen(false)
}
return (
<>
<Button onClick={() => setOpen(true)}>2</Button>
<BottomSheet
style={{ ['--rsbs-bg' as any]: '#EFF6FF' }}
open={open}
header={header}
onDismiss={onDismiss}
footer={
<Button
onClick={onDismiss}
className="w-full focus-visible:ring-offset-rsbs-bg"
>
Dismiss
</Button>
}
defaultSnap={({ headerHeight, footerHeight, minHeight }) =>
//headerHeight + footerHeight
minHeight
}
snapPoints={({ minHeight, headerHeight, footerHeight }) => [
headerHeight + footerHeight,
minHeight,
]}
>
<SheetContent>
<Button
onClick={() => setHeader((header) => !header)}
className="w-full focus-visible:ring-offset-rsbs-bg"
>
header: {header ? 'true' : 'false'}
</Button>
</SheetContent>
</BottomSheet>
</>
)
}
function Three() {
const [open, setOpen] = useState(false)
function onDismiss() {
setOpen(false)
}
return (
<>
<Button onClick={() => setOpen(true)}>3</Button>
<BottomSheet
style={{ ['--rsbs-bg' as any]: '#EFF6FF' }}
open={open}
onDismiss={onDismiss}
header={
<Button
onClick={onDismiss}
className="w-full focus-visible:ring-offset-rsbs-bg"
>
Dismiss
</Button>
}
snapPoints={({ minHeight, headerHeight }) => [headerHeight, minHeight]}
>
<SheetContent>
<p>
Using <Code>onDismiss</Code> lets users close the sheet by swiping
it down, tapping on the backdrop or by hitting <Kbd>esc</Kbd> on
their keyboard.
</p>
</SheetContent>
</BottomSheet>
</>
)
}
function Four() {
const [open, setOpen] = useState(false)
function onDismiss() {
setOpen(false)
}
return (
<>
<Button onClick={() => setOpen(true)}>4</Button>
<BottomSheet
open={open}
onDismiss={onDismiss}
header={
<input
className="mt-1 block w-full rounded-md bg-gray-100 border-transparent focus:border-gray-300 focus:bg-white focus:ring-0"
type="text"
placeholder="Text input field in a sticky header"
/>
}
footer={
<input
className="mt-1 block w-full rounded-md bg-gray-100 border-transparent focus:border-gray-300 focus:bg-white focus:ring-0"
type="text"
placeholder="Text input field in a sticky header"
/>
}
>
<SheetContent>
<input
className="mt-1 block w-full rounded-md bg-gray-100 border-transparent focus:border-gray-300 focus:bg-white focus:ring-0"
type="text"
placeholder="Text input field in a sticky header"
/>
<Expandable>
<div className="bg-gray-200 block rounded-md h-10 w-full my-10" />
<p>Testing focus management and keyboard behavior on open.</p>
<div className="bg-gray-200 block rounded-md h-10 w-full my-10" />
</Expandable>
<input
className="mt-1 block w-full rounded-md bg-gray-100 border-transparent focus:border-gray-300 focus:bg-white focus:ring-0"
type="text"
placeholder="Text input field in a sticky header"
/>
</SheetContent>
</BottomSheet>
</>
)
}
function Five() {
const [open, setOpen] = useState(false)
function onDismiss() {
setOpen(false)
}
return (
<>
<Button onClick={() => setOpen(true)}>5</Button>
<BottomSheet
style={{ ['--rsbs-bg' as any]: '#EFF6FF' }}
open={open}
footer={<strong>Sticky footer</strong>}
onDismiss={onDismiss}
defaultSnap={({ lastSnap }) => lastSnap}
snapPoints={({ minHeight, headerHeight, footerHeight }) => [
headerHeight,
headerHeight + footerHeight,
minHeight,
]}
>
<SheetContent>
<p>
Using <Code>onDismiss</Code> lets users close the sheet by swiping
it down, tapping on the backdrop or by hitting <Kbd>esc</Kbd> on
their keyboard.
</p>
</SheetContent>
</BottomSheet>
</>
)
}
function Six() {
const [open, setOpen] = useState(false)
const [half, setHalf] = useState(false)
const [maxHeight, setMaxHeight] = useState(() =>
typeof window !== 'undefined'
? half
? window.innerHeight / 2
: window.innerHeight
: 0
)
useEffect(() => {
setMaxHeight(half ? window.innerHeight / 2 : window.innerHeight)
}, [half])
const style = { ['--rsbs-bg' as any]: '#EFF6FF' }
if (half) {
// setting it to undefined removes it, so we don't have to hardcode the default rounding we want in this component
style['--rsbs-overlay-rounded' as any] = undefined
}
return (
<>
<Button onClick={() => setOpen(true)}>6</Button>
<BottomSheet
style={style}
open={open}
maxHeight={maxHeight}
onDismiss={() => setOpen(false)}
snapPoints={({ minHeight, maxHeight }) => [minHeight, maxHeight]}
>
<SheetContent>
<Button onClick={() => setHalf((half) => !half)}>
{half ? 'maxHeight 100%' : 'maxHeight 50%'}
</Button>
</SheetContent>
</BottomSheet>
</>
)
}
function Seven() {
const [open, setOpen] = useState(false)
const [shift, setShift] = useState(false)
useInterval(() => {
if (open) {
setShift((shift) => !shift)
}
}, 1000)
return (
<>
<Button onClick={() => setOpen(true)}>7</Button>
<BottomSheet
open={open}
maxHeight={
typeof window !== 'undefined'
? shift
? window.innerHeight / 2
: window.innerHeight
: 0
}
onDismiss={() => setOpen(false)}
snapPoints={({ maxHeight }) => [maxHeight]}
>
<SheetContent>maxHeight {shift ? 'shifted' : 'normal'}</SheetContent>
</BottomSheet>
</>
)
}
function Eight() {
const [open, setOpen] = useState(false)
const [defaultSnap, setDefaultSnap] = useState(200)
const reopenRef = useRef(false)
return (
<>
<Button onClick={() => setOpen(true)}>8</Button>
<BottomSheet
open={open}
onDismiss={() => setOpen(false)}
defaultSnap={defaultSnap}
snapPoints={({ minHeight, maxHeight }) => [minHeight, maxHeight]}
onSpringEnd={(event) => {
if (reopenRef.current && event.type === 'CLOSE') {
reopenRef.current = false
setOpen(true)
}
}}
// @TODO investigate missing opacity fade out on close if onDismiss isn't used
/*
footer={
<Button
className="w-full focus-visible:ring-offset-rsbs-bg"
>
Dismiss
</Button>
}
//*/
>
<SheetContent>
<Button
onClick={() => {
reopenRef.current = true
setDefaultSnap((defaultSnap) => (defaultSnap === 200 ? 800 : 200))
setOpen(false)
}}
>
defaultSnap: {defaultSnap}
</Button>
</SheetContent>
</BottomSheet>
</>
)
}
function Nine() {
const [open, setOpen] = useState(false)
const [expandHeader, setExpandHeader] = useState(false)
const [expandContent, setExpandContent] = useState(false)
const [expandFooter, setExpandFooter] = useState(false)
return (
<>
<Button onClick={() => setOpen(true)}>9</Button>
<BottomSheet
open={open}
onDismiss={() => setOpen(false)}
header={
<div>
<Button onClick={() => setExpandHeader(true)}>Expand</Button>
<br />
{expandHeader && (
<Button onClick={() => setExpandHeader(false)}>No!</Button>
)}
</div>
}
footer={
<>
<Button onClick={() => setExpandFooter(true)}>Expand</Button>
<br />
{expandFooter && (
<Button onClick={() => setExpandFooter(false)}>No!</Button>
)}
</>
}
>
<SheetContent>
<Button onClick={() => setExpandContent(true)}>Expand</Button>
{expandContent && (
<Button onClick={() => setExpandContent(false)}>No!</Button>
)}
</SheetContent>
</BottomSheet>
</>
)
}
function Ten() {
const [open, setOpen] = useState(false)
return (
<>
<Button onClick={() => setOpen(true)}>10</Button>
<BottomSheet
open={open}
onDismiss={() => setOpen(false)}
defaultSnap={({ snapPoints }) => Math.max(...snapPoints)}
snapPoints={({ minHeight, maxHeight }) =>
[maxHeight, maxHeight * 0.7, maxHeight * 0.3].map((v) =>
Math.min(v, minHeight)
)
}
>
<SheetContent>
<Expandable>
<div className="bg-gray-200 block rounded-md h-screen w-full my-10" />
</Expandable>
</SheetContent>
</BottomSheet>
</>
)
}
function Eleven() {
const [open, setOpen] = useState(false)
const [height, setHeight] = useState(undefined)
const sheetRef = useRef<BottomSheetRef>()
return (
<>
<Button onClick={() => setOpen(true)}>11</Button>
<BottomSheet
ref={sheetRef}
open={open}
onDismiss={() => setOpen(false)}
snapPoints={({ minHeight, maxHeight }) => [
height ? minHeight : maxHeight,
200,
]}
onSpringStart={(event) => {
if (event.type === 'SNAP' && event.source === 'custom') {
setTimeout(() => setHeight('80vh'), 100)
}
}}
onSpringEnd={(event) => {
if (event.type === 'SNAP' && event.source === 'custom') {
setHeight(undefined)
}
}}
footer={
<Button
onClick={() =>
sheetRef.current.snapTo(
({ height, snapPoints }) => {
const minSnap = Math.min(...snapPoints)
return height > minSnap ? minSnap : Math.max(...snapPoints)
},
{ velocity: 0, source: 'reset' }
)
}
>
Reset
</Button>
}
>
<SheetContent style={{ height }}>
<Button
onClick={() =>
sheetRef.current.snapTo(({ height, snapPoints }) => {
const minSnap = Math.min(...snapPoints)
return height > minSnap ? minSnap : Math.max(...snapPoints)
})
}
>
snapTo
</Button>
<div className="bg-gray-200 block rounded-md h-screen w-full my-10" />
</SheetContent>
</BottomSheet>
</>
)
}
function Twelve() {
const [open, setOpen] = useState(false)
const sheetRef = useRef<BottomSheetRef>()
const [height, setHeight] = useState(0)
return (
<>
<Button onClick={() => setOpen(true)}>12</Button>
<BottomSheet
ref={sheetRef}
open={open}
onDismiss={() => setOpen(false)}
defaultSnap={({ snapPoints }) => Math.max(...snapPoints)}
snapPoints={({ minHeight, maxHeight }) =>
[maxHeight, maxHeight * 0.7, maxHeight * 0.3].map((v) =>
Math.min(v, minHeight)
)
}
onSpringStart={(event) => {
console.log('onSpringStart', event, sheetRef.current.height)
setHeight(sheetRef.current.height)
requestAnimationFrame(() => setHeight(sheetRef.current.height))
if (event.type === 'OPEN') {
setTimeout(() => setHeight(sheetRef.current.height), 100)
}
}}
onSpringCancel={(event) => {
console.log('onSpringCancel', event, sheetRef.current.height)
setHeight(sheetRef.current.height)
}}
onSpringEnd={(event) => {
console.log('onSpringEnd', event, sheetRef.current.height)
setHeight(sheetRef.current.height)
}}
footer={<div className="w-full text-center">Height: {height}</div>}
>
<SheetContent>
<Expandable>
<div className="bg-gray-200 block rounded-md h-screen w-full my-10" />
</Expandable>
</SheetContent>
</BottomSheet>
</>
)
}
export default function ExperimentsFixturePage() {
return (
<Container
className={[
{ 'bg-white': false },
'bg-gray-200 grid-cols-3 place-items-center',
]}
>
<One />
<Two />
<Three />
<Four />
<Five />
<Six />
<Seven />
<Eight />
<Nine />
<Ten />
<Eleven />
<Twelve />
</Container>
)
} | the_stack |
import NeovimStore from './store';
import * as A from './actions';
import Cursor from './cursor';
import Input from './input';
import log from '../log';
export default class NeovimScreen {
ctx: CanvasRenderingContext2D;
cursor: Cursor;
input: Input;
constructor(private readonly store: NeovimStore, public canvas: HTMLCanvasElement) {
this.ctx = this.canvas.getContext('2d', { alpha: false });
this.store.on('put', this.drawText.bind(this));
this.store.on('clear-all', this.clearAll.bind(this));
this.store.on('clear-eol', this.clearEol.bind(this));
// Note: 'update-bg' clears all texts in screen.
this.store.on('update-bg', this.clearAll.bind(this));
this.store.on('screen-scrolled', this.scroll.bind(this));
this.store.on('line-height-changed', () => this.changeFontSize(this.store.font_attr.specified_px));
this.changeFontSize(this.store.font_attr.specified_px);
canvas.addEventListener('click', this.focus.bind(this));
canvas.addEventListener('mousedown', this.mouseDown.bind(this));
canvas.addEventListener('mouseup', this.mouseUp.bind(this));
canvas.addEventListener('mousemove', this.mouseMove.bind(this));
canvas.addEventListener('wheel', this.wheel.bind(this));
this.cursor = new Cursor(this.store, this.ctx);
this.input = new Input(this.store);
}
wheel(e: WheelEvent) {
this.store.dispatcher.dispatch(A.wheelScroll(e));
}
mouseDown(e: MouseEvent) {
this.store.dispatcher.dispatch(A.dragStart(e));
}
mouseUp(e: MouseEvent) {
this.store.dispatcher.dispatch(A.dragEnd(e));
}
mouseMove(e: MouseEvent) {
if (e.buttons !== 0) {
this.store.dispatcher.dispatch(A.dragUpdate(e));
}
}
resizeWithPixels(width_px: number, height_px: number) {
const res = window.devicePixelRatio || 1;
const h = height_px * res;
const w = width_px * res;
this.resizeImpl(
Math.floor(h / this.store.font_attr.draw_height),
Math.floor(w / this.store.font_attr.draw_width),
w,
h,
);
}
resize(lines: number, cols: number) {
this.resizeImpl(lines, cols, this.store.font_attr.draw_width * cols, this.store.font_attr.draw_height * lines);
}
changeFontSize(specified_px: number) {
const res = window.devicePixelRatio || 1;
const drawn_px = specified_px * res;
this.ctx.font = drawn_px + 'px ' + this.store.font_attr.face;
const font_width = this.ctx.measureText('m').width;
const font_height = Math.ceil(drawn_px * this.store.line_height);
this.store.dispatcher.dispatch(A.updateFontPx(specified_px));
this.store.dispatcher.dispatch(A.updateFontSize(font_width, font_height, font_width / res, font_height / res));
const { width, height } = this.store.size;
this.resizeWithPixels(width, height);
}
changeLineHeight(new_value: number) {
this.store.dispatcher.dispatch(A.updateLineHeight(new_value));
}
// Note:
// cols_delta > 0 -> screen up
// cols_delta < 0 -> screen down
scroll(cols_delta: number) {
if (cols_delta > 0) {
this.scrollUp(cols_delta);
} else if (cols_delta < 0) {
this.scrollDown(-cols_delta);
}
}
focus() {
this.input.focus();
}
clearAll() {
this.ctx.fillStyle = this.store.bg_color;
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
clearEol() {
const { line, col } = this.store.cursor;
const font_width = this.store.font_attr.draw_width;
const clear_length = this.store.size.cols * font_width - col * font_width;
log.debug(`Clear until EOL: ${line}:${col} length=${clear_length}`);
this.drawBlock(line, col, 1, clear_length, this.store.bg_color);
}
// Origin is at left-above.
//
// O-------------> x
// |
// |
// |
// |
// V
// y
//
convertPositionToLocation(line: number, col: number) {
const { width, height } = this.store.font_attr;
return {
x: col * width,
y: line * height,
};
}
convertLocationToPosition(x: number, y: number) {
const { width, height } = this.store.font_attr;
return {
line: Math.floor(y * height),
col: Math.floor(x * width),
};
}
checkShouldResize() {
const p = this.canvas.parentElement;
const cw = p.clientWidth;
const ch = p.clientHeight;
const w = this.canvas.width;
const h = this.canvas.height;
const res = window.devicePixelRatio || 1;
if (cw * res !== w || ch * res !== h) {
this.resizeWithPixels(cw, ch);
}
}
// Note:
// About 'chars' parameter includes characters to render as array of strings
// which should be rendered at the each cursor position.
// So we renders the strings with forwarding the start position incrementally.
// When chars[idx][0] is empty string, it means that 'no character to render,
// go ahead'.
private drawChars(x: number, y: number, chars: string[][], width: number) {
let includes_half_only = true;
for (const c of chars) {
if (!c[0]) {
includes_half_only = false;
break;
}
}
if (includes_half_only) {
// Note:
// If the text includes only half characters, we can render it at once.
const text = chars.map(c => c[0] || '').join('');
this.ctx.fillText(text, x, y);
return;
}
for (const char of chars) {
if (!char[0] || char[0] === ' ') {
x += width;
continue;
}
this.ctx.fillText(char.join(''), x, y);
x += width;
}
}
private drawText(chars: string[][]) {
const { line, col } = this.store.cursor;
const {
fg,
bg,
sp,
draw_width,
draw_height,
face,
specified_px,
bold,
italic,
underline,
undercurl,
} = this.store.font_attr;
// Draw background
this.drawBlock(line, col, 1, chars.length, bg);
const res = window.devicePixelRatio || 1;
const font_size = specified_px * res;
let attrs = '';
if (bold) {
attrs += 'bold ';
}
if (italic) {
attrs += 'italic ';
}
this.ctx.font = attrs + font_size + 'px ' + face;
this.ctx.textBaseline = 'top';
this.ctx.fillStyle = fg;
const margin = Math.ceil((font_size * (this.store.line_height - 1.0)) / 2);
const y = Math.floor(line * draw_height);
const x = col * draw_width;
this.drawChars(x, y + margin, chars, draw_width);
if (undercurl) {
this.ctx.strokeStyle = sp || this.store.sp_color || fg; // Note: Fallback for Neovim 0.1.4 or earlier.
this.ctx.lineWidth = 1 * res;
this.ctx.setLineDash([draw_width / 3, draw_width / 3]);
this.ctx.beginPath();
const curl_y = y + draw_height - margin;
this.ctx.moveTo(x, curl_y);
this.ctx.lineTo(x + draw_width * chars.length, curl_y);
this.ctx.stroke();
} else if (underline) {
this.ctx.strokeStyle = fg;
this.ctx.lineWidth = 1 * res;
this.ctx.setLineDash([]);
this.ctx.beginPath();
const underline_y = y + draw_height - margin;
this.ctx.moveTo(x, underline_y);
this.ctx.lineTo(x + draw_width * chars.length, underline_y);
this.ctx.stroke();
}
log.debug(`drawText(): (${x}, ${y})`, chars.length, this.store.cursor);
}
private drawBlock(line: number, col: number, height: number, width: number, color: string) {
const { draw_width, draw_height } = this.store.font_attr;
this.ctx.fillStyle = color;
// Note:
// Height doesn't need to be truncated (floor, ceil) but width needs.
// The reason is desribed in Note2 of changeFontSize().
this.ctx.fillRect(
Math.floor(col * draw_width),
line * draw_height,
Math.ceil(width * draw_width),
height * draw_height,
);
}
private slideVertical(top: number, height: number, dst_top: number) {
const { left, right } = this.store.scroll_region;
const { draw_width, draw_height } = this.store.font_attr;
const x = left * draw_width;
const sy = top * draw_height;
const w = (right - left + 1) * draw_width;
const h = height * draw_height;
const dy = dst_top * draw_height;
this.ctx.drawImage(this.canvas, x, sy, w, h, x, dy, w, h);
}
private scrollUp(cols_up: number) {
const { top, bottom, left, right } = this.store.scroll_region;
this.slideVertical(top + cols_up, bottom - (top + cols_up) + 1, top);
this.drawBlock(bottom - cols_up + 1, left, cols_up, right - left + 1, this.store.bg_color);
log.debug('Scroll up: ' + cols_up, this.store.scroll_region);
}
private scrollDown(cols_down: number) {
const { top, bottom, left, right } = this.store.scroll_region;
this.slideVertical(top, bottom - (top + cols_down) + 1, top + cols_down);
this.drawBlock(top, left, cols_down, right - left + 1, this.store.bg_color);
log.debug('Scroll down: ' + cols_down, this.store.scroll_region);
}
private resizeImpl(lines: number, cols: number, width: number, height: number) {
const res = window.devicePixelRatio || 1;
if (width !== this.canvas.width) {
this.canvas.width = width;
this.canvas.style.width = width / res + 'px';
}
if (height !== this.canvas.height) {
this.canvas.height = height;
this.canvas.style.height = height / res + 'px';
}
this.store.dispatcher.dispatch(A.updateScreenSize(width, height));
this.store.dispatcher.dispatch(A.updateScreenBounds(lines, cols));
}
} | the_stack |
import {hi, lo, toHex, toHexWord} from "z80-base";
import {Hal, Z80} from "z80-emulator";
import {CassettePlayer} from "./CassettePlayer.js";
import {Keyboard} from "./Keyboard.js";
import {model1Level1Rom} from "./Model1Level1Rom.js";
import {model1Level2Rom} from "./Model1Level2Rom.js";
import {model3Rom} from "./Model3Rom.js";
import {model4Rom} from "./Model4Rom.js";
import {Trs80Screen} from "./Trs80Screen.js";
import {BasicLevel, CGChip, Config, ModelType} from "./Config.js";
import {
BASIC_HEADER_BYTE,
BasicProgram,
CmdProgram,
decodeBasicProgram,
ElementType, isFloppy,
SystemProgram,
TRS80_SCREEN_BEGIN,
TRS80_SCREEN_END,
Trs80File
} from "trs80-base";
import {FloppyDisk} from "trs80-base";
import {FLOPPY_DRIVE_COUNT, FloppyDiskController} from "./FloppyDiskController.js";
import {Machine} from "./Machine.js";
import {EventScheduler} from "./EventScheduler.js";
import {SoundPlayer} from "./SoundPlayer.js";
import {SignalDispatcher,SimpleEventDispatcher} from "strongly-typed-events";
// IRQs
const M1_TIMER_IRQ_MASK = 0x80;
const M3_CASSETTE_RISE_IRQ_MASK = 0x01;
const M3_CASSETTE_FALL_IRQ_MASK = 0x02;
const M3_TIMER_IRQ_MASK = 0x04;
const M3_IO_BUS_IRQ_MASK = 0x08;
const M3_UART_SED_IRQ_MASK = 0x10;
const M3_UART_RECEIVE_IRQ_MASK = 0x20;
const M3_UART_ERROR_IRQ_MASK = 0x40;
const CASSETTE_IRQ_MASKS = M3_CASSETTE_RISE_IRQ_MASK | M3_CASSETTE_FALL_IRQ_MASK;
// NMIs
const RESET_NMI_MASK = 0x20;
const DISK_MOTOR_OFF_NMI_MASK = 0x40;
const DISK_INTRQ_NMI_MASK = 0x80;
// Timer.
const M1_TIMER_HZ = 40;
const M3_TIMER_HZ = 30;
const M4_TIMER_HZ = 60;
const ROM_SIZE = 14*1024;
const RAM_START = 16*1024;
// CPU clock speeds.
const M1_CLOCK_HZ = 1_774_080;
const M3_CLOCK_HZ = 2_027_520;
const M4_CLOCK_HZ = 4_055_040;
const INITIAL_CLICKS_PER_TICK = 2000;
/**
* Converts the two-bit cassette port to an audio value. These values are from "More TRS-80 Assembly
* Language Programming", page 222, with the last value taken from "The B00K" volume 2 (page 5-2).
*/
const CASSETTE_BITS_TO_AUDIO_VALUE = [0, 1, -1, -1];
const CASSETTE_THRESHOLD = 5000/32768.0;
// State of the cassette hardware. We don't support writing.
enum CassetteState {
CLOSE, READ, FAIL,
}
// Value of wave in audio: negative, neutral (around zero), or positive.
enum CassetteValue {
NEGATIVE, NEUTRAL, POSITIVE,
}
/**
* Whether the memory address maps to a screen location.
*/
function isScreenAddress(address: number): boolean {
return address >= TRS80_SCREEN_BEGIN && address < TRS80_SCREEN_END;
}
/**
* See the FONT.md file for an explanation of this, but basically bit 6 is the NOR of bits 5 and 7.
*/
function computeVideoBit6(value: number): number {
const bit5 = (value >> 5) & 1;
const bit7 = (value >> 7) & 1;
const bit6 = (bit5 | bit7) ^ 1;
return (value & 0xBF) | (bit6 << 6);
}
const WARN_ONCE_SET = new Set<string>();
/**
* Send this warning message to the console once. This is to avoid a program repeatedly doing something
* that results in a warning (such as reading from an unmapped memory address) and crashing the browser.
*/
function warnOnce(message: string): void {
if (!WARN_ONCE_SET.has(message)) {
WARN_ONCE_SET.add(message);
console.warn(message + " (further warnings suppressed)");
}
}
/**
* setTimeout() returns a different type on the browser and in node, so auto-detect the type.
*/
type TimeoutHandle = ReturnType<typeof setTimeout>;
/**
* HAL for the TRS-80 Model III.
*/
export class Trs80 implements Hal, Machine {
private config: Config;
private timerHz = M3_TIMER_HZ;
public clockHz = M3_CLOCK_HZ;
public tStateCount = 0;
private readonly screen: Trs80Screen;
private readonly fdc = new FloppyDiskController(this);
private readonly cassettePlayer: CassettePlayer;
private memory = new Uint8Array(0);
private readonly keyboard: Keyboard;
private modeImage = 0x80;
// Which IRQs should be handled.
private irqMask = 0;
// Which IRQs have been requested by the hardware.
private irqLatch = 0;
// Which NMIs should be handled.
private nmiMask = 0;
// Which NMIs have been requested by the hardware.
private nmiLatch = 0;
// Whether we've seen this NMI and handled it.
private nmiSeen = false;
private previousTimerClock = 0;
public readonly z80 = new Z80(this);
private clocksPerTick = INITIAL_CLICKS_PER_TICK;
private startTime = Date.now();
private tickHandle: TimeoutHandle | undefined;
public started = false;
// Internal state of the cassette controller.
// Whether the motor is running.
private cassetteMotorOn = false;
// State machine.
private cassetteState = CassetteState.CLOSE;
// Internal register state.
private cassetteValue = CassetteValue.NEUTRAL;
private cassetteLastNonZeroValue = CassetteValue.NEUTRAL;
private cassetteFlipFlop = false;
// When we turned on the motor (started reading the file) and how many samples
// we've read since then.
private cassetteMotorOnClock = 0;
private cassetteSamplesRead = 0;
private cassetteRiseInterruptCount = 0;
private cassetteFallInterruptCount = 0;
private orchestraLeftValue = 0;
public readonly soundPlayer: SoundPlayer;
public readonly eventScheduler = new EventScheduler();
public readonly onPreStep = new SignalDispatcher();
public readonly onPostStep = new SignalDispatcher();
constructor(config: Config, screen: Trs80Screen, keyboard: Keyboard, cassette: CassettePlayer, soundPlayer: SoundPlayer) {
this.screen = screen;
this.keyboard = keyboard;
this.cassettePlayer = cassette;
this.soundPlayer = soundPlayer;
this.config = config;
this.screen.setConfig(this.config);
this.updateFromConfig();
this.loadRom();
this.tStateCount = 0;
this.fdc.onActiveDrive.subscribe(activeDrive => this.soundPlayer.setFloppyMotorOn(activeDrive !== undefined));
this.fdc.onTrackMove.subscribe(moveCount => this.soundPlayer.trackMoved(moveCount));
}
/**
* Get the current emulator's configuration.
*/
public getConfig(): Config {
return this.config;
}
/**
* Sets a new configuration and reboots into it if necessary.
*/
public setConfig(config: Config): void {
const needsReboot = config.needsReboot(this.config);
this.config = config;
this.screen.setConfig(this.config);
if (needsReboot) {
this.updateFromConfig();
this.reset();
}
}
/**
* Update our settings based on the config. Wipes memory.
*/
private updateFromConfig(): void {
this.memory = new Uint8Array(RAM_START + this.config.getRamSize());
this.memory.fill(0);
this.loadRom();
switch (this.config.modelType) {
case ModelType.MODEL1:
this.timerHz = M1_TIMER_HZ;
this.clockHz = M1_CLOCK_HZ;
break;
case ModelType.MODEL3:
default:
this.timerHz = M3_TIMER_HZ;
this.clockHz = M3_CLOCK_HZ;
break;
case ModelType.MODEL4:
this.timerHz = M4_TIMER_HZ; // TODO depends on mode.
this.clockHz = M4_CLOCK_HZ;
break;
}
}
/**
* Load the config-specific ROM into memory.
*/
private loadRom(): void {
let rom: string;
switch (this.config.modelType) {
case ModelType.MODEL1:
switch (this.config.basicLevel) {
case BasicLevel.LEVEL1:
rom = model1Level1Rom;
break;
case BasicLevel.LEVEL2:
default:
rom = model1Level2Rom;
break;
}
break;
case ModelType.MODEL3:
default:
rom = model3Rom;
break;
case ModelType.MODEL4:
rom = model4Rom;
break;
}
for (let i = 0; i < rom.length; i++) {
this.memory[i] = rom.charCodeAt(i);
}
}
/**
* Get the max number of drives in this machine. This isn't the number of drives actually
* hooked up, it's the max that this machine could handle.
*/
public getMaxDrives(): number {
return FLOPPY_DRIVE_COUNT;
}
/**
* Event dispatcher for floppy drive activity, indicating which drive (0-based) has its motor on, if any.
*/
get onMotorOn(): SimpleEventDispatcher<number | undefined> {
return this.fdc.onActiveDrive;
}
/**
* Reset the state of the Z80 and hardware.
*/
public reset(): void {
this.setIrqMask(0);
this.setNmiMask(0);
this.resetCassette();
this.keyboard.clearKeyboard();
this.setTimerInterrupt(false);
this.z80.reset();
}
/**
* Jump the Z80 emulator to the specified address.
*/
public jumpTo(address: number): void {
this.z80.regs.pc = address;
}
/**
* Set the stack pointer to the specified address.
*/
private setStackPointer(address: number): void {
this.z80.regs.sp = address;
}
/**
* Start the executable at the given address. This sets up some
* state and jumps to the address.
*/
private startExecutable(address: number): void {
// Disable the cursor.
this.writeMemory(0x4022, 0);
// Disable interrupts.
this.z80.regs.iff1 = 0;
this.z80.regs.iff2 = 0;
this.jumpTo(address);
}
/**
* Start the CPU and intercept browser keys.
*/
public start(): void {
if (!this.started) {
this.keyboard.interceptKeys = true;
this.scheduleNextTick();
this.started = true;
}
}
/**
* Stop the CPU and no longer intercept browser keys.
*
* @return whether it was started.
*/
public stop(): boolean {
if (this.started) {
this.keyboard.interceptKeys = false;
this.cancelTickTimeout();
this.started = false;
return true;
} else {
return false;
}
}
/**
* Set the mask for IRQ (regular) interrupts.
*/
public setIrqMask(irqMask: number): void {
this.irqMask = irqMask;
}
/**
* Set the mask for non-maskable interrupts. (Yes.)
*/
public setNmiMask(nmiMask: number): void {
// Reset is always allowed:
this.nmiMask = nmiMask | RESET_NMI_MASK;
this.updateNmiSeen();
}
private interruptLatchRead(): number {
if (this.config.modelType === ModelType.MODEL1) {
const irqLatch = this.irqLatch;
this.setTimerInterrupt(false);
// TODO irq = this.irqLatch !== 0;
return irqLatch;
} else {
return ~this.irqLatch & 0xFF;
}
}
/**
* Take one Z80 step and update the state of the hardware.
*/
public step(): void {
this.onPreStep.dispatch();
this.z80.step();
// Handle non-maskable interrupts.
if ((this.nmiLatch & this.nmiMask) !== 0 && !this.nmiSeen) {
this.z80.nonMaskableInterrupt();
this.nmiSeen = true;
// Simulate the reset button being released.
this.resetButtonInterrupt(false);
}
// Handle interrupts.
if ((this.irqLatch & this.irqMask) !== 0) {
this.z80.maskableInterrupt();
}
// Set off a timer interrupt.
if (this.tStateCount > this.previousTimerClock + this.clockHz / this.timerHz) {
this.handleTimer();
this.previousTimerClock = this.tStateCount;
}
// Update cassette state.
this.updateCassette();
// Dispatch scheduled events.
this.eventScheduler.dispatch(this.tStateCount);
this.onPostStep.dispatch();
}
public contendMemory(address: number): void {
// Ignore.
}
public contendPort(address: number): void {
// Ignore.
}
public readMemory(address: number): number {
if (address < ROM_SIZE || address >= RAM_START || isScreenAddress(address)) {
return address < this.memory.length ? this.memory[address] : 0xFF;
} else if (address === 0x37E8) {
// Printer. 0x30 = Printer selected, ready, with paper, not busy.
return 0x30;
} else if (Keyboard.isInRange(address)) {
// Keyboard.
return this.keyboard.readKeyboard(address, this.tStateCount);
} else {
// Unmapped memory.
warnOnce("Reading from unmapped memory at 0x" + toHex(address, 4));
return 0;
}
}
public readPort(address: number): number {
const port = address & 0xFF;
let value = 0xFF; // Default value for missing ports.
switch (port) {
case 0x00:
// Joystick.
value = 0xFF;
break;
case 0xE0:
if (this.config.modelType !== ModelType.MODEL1) {
// IRQ latch read.
value = this.interruptLatchRead();
}
break;
case 0xE4:
if (this.config.modelType !== ModelType.MODEL1) {
// NMI latch read.
value = ~this.nmiLatch & 0xFF;
}
break;
case 0xEC:
case 0xED:
case 0xEE:
case 0xEF:
if (this.config.modelType !== ModelType.MODEL1) {
// Acknowledge timer.
this.setTimerInterrupt(false);
value = 0xFF;
}
break;
case 0xF0:
value = this.fdc.readStatus();
break;
case 0xF1:
value = this.fdc.readTrack();
break;
case 0xF2:
value = this.fdc.readSector();
break;
case 0xF3:
value = this.fdc.readData();
break;
case 0xF8:
// Printer status. Printer selected, ready, with paper, not busy.
value = 0x30;
break;
case 0xFF:
// Cassette and various flags.
if (this.config.modelType === ModelType.MODEL1) {
value = 0x3F;
if (!this.screen.isExpandedCharacters()) {
value |= 0x40;
}
} else {
value = this.modeImage & 0x7E;
}
value |= this.getCassetteByte();
break;
default:
// Not sure what a good default value is, but other emulators use 0xFF.
warnOnce("Reading from unknown port 0x" + toHex(lo(address), 2));
value = 0xFF;
break;
}
// console.log("Reading 0x" + toHex(value, 2) + " from port 0x" + toHex(lo(address), 2));
return value;
}
public writePort(address: number, value: number): void {
const port = address & 0xFF;
switch (port) {
case 0xB5: // ORCHESTRA-85
case 0x75: // ORCHESTRA-90
{
// ORCHESTRA hardware. The values are -128 to 127, so flip the MSB to convert to 0 to 255.
const leftValue = ((this.orchestraLeftValue ^ 0x80) - 128) / 128;
const rightValue = ((value ^ 0x80) - 128) / 128;
this.soundPlayer.setAudioValue(leftValue, rightValue, this.tStateCount, this.clockHz);
break;
}
case 0xB9: // ORCHESTRA-85
case 0x79: // ORCHESTRA-90
// ORCHESTRA hardware.
// Keep this for later right value.
this.orchestraLeftValue = value;
break;
case 0xE0:
if (this.config.modelType !== ModelType.MODEL1) {
// Set interrupt mask.
this.setIrqMask(value);
}
break;
case 0xE4:
case 0xE5:
case 0xE6:
case 0xE7:
if (this.config.modelType !== ModelType.MODEL1) {
// Set NMI state.
this.setNmiMask(value);
}
break;
case 0xEC:
case 0xED:
case 0xEE:
case 0xEF:
if (this.config.modelType !== ModelType.MODEL1) {
// Various controls.
this.modeImage = value;
this.setCassetteMotor((value & 0x02) !== 0);
this.screen.setExpandedCharacters((value & 0x04) !== 0);
this.screen.setAlternateCharacters((value & 0x08) === 0);
}
break;
case 0xF0:
this.fdc.writeCommand(value);
break;
case 0xF1:
this.fdc.writeTrack(value);
break;
case 0xF2:
this.fdc.writeSector(value);
break;
case 0xF3:
this.fdc.writeData(value);
break;
case 0xF4:
case 0xF5:
case 0xF6:
case 0xF7:
this.fdc.writeSelect(value);
break;
case 0xF8:
case 0xF9:
case 0xFA:
case 0xFB:
// Printer write.
console.log("Writing \"" + String.fromCodePoint(value) + "\" to printer");
break;
case 0xFC:
case 0xFD:
case 0xFE:
case 0xFF:
if (this.config.modelType === ModelType.MODEL1) {
this.setCassetteMotor((value & 0x04) !== 0);
this.screen.setExpandedCharacters((value & 0x08) !== 0);
}
if ((value & 0x20) !== 0) {
// Model III Micro Labs graphics card.
console.log("Sending 0x" + toHex(value, 2) + " to Micro Labs graphics card");
} else {
// Do cassette emulation.
this.putCassetteByte(value & 0x03);
}
break;
default:
warnOnce("Writing 0x" + toHex(value, 2) + " to unknown port 0x" + toHex(port, 2));
return;
}
// console.log("Wrote 0x" + toHex(value, 2) + " to port 0x" + toHex(port, 2));
}
public writeMemory(address: number, value: number): void {
if (address < ROM_SIZE) {
warnOnce("Warning: Writing to ROM location 0x" + toHex(address, 4));
} else {
if (address >= TRS80_SCREEN_BEGIN && address < TRS80_SCREEN_END) {
if (this.config.cgChip === CGChip.ORIGINAL) {
// No bit 6 in video memory, need to compute it.
value = computeVideoBit6(value);
}
this.screen.writeChar(address, value);
} else if (address < RAM_START) {
warnOnce("Writing to unmapped memory at 0x" + toHex(address, 4));
}
this.memory[address] = value;
}
}
/**
* Write a block of data to memory.
*
* @return the address just past the block.
*/
public writeMemoryBlock(address: number, values: Uint8Array, startIndex: number = 0, length?: number): number {
length = length ?? values.length;
for (let i = 0; i < length; i++) {
this.writeMemory(address++, values[startIndex + i]);
}
return address;
}
/**
* Reset cassette edge interrupts.
*/
public cassetteClearInterrupt(): void {
this.irqLatch &= ~CASSETTE_IRQ_MASKS;
}
/**
* Check whether the software has enabled these interrupts.
*/
public cassetteInterruptsEnabled(): boolean {
return (this.irqMask & CASSETTE_IRQ_MASKS) !== 0;
}
/**
* Get an opaque string that represents the state of the screen.
*
* Might want to also call flashNode() in the trs80-emulator-web project.
*/
public getScreenshot(): string {
const buf: number[] = [];
// First byte is screen mode, where 0 means normal (64 columns) and 1 means wide (32 columns).
buf.push(this.screen.isExpandedCharacters() ? 1 : 0);
// Run-length encode bytes with (value,count) pairs, with a max count of 255. Bytes
// in the range 33 to 127 inclusive have an implicit count of 1.
for (let address = TRS80_SCREEN_BEGIN; address < TRS80_SCREEN_END; address++) {
const value = this.memory[address];
if (value > 32 && value < 128) {
// Bytes in this range don't store a count.
buf.push(value);
} else if (buf.length < 2 || buf[buf.length - 1] === 255 || buf[buf.length - 2] !== value) {
// New entry.
buf.push(value);
buf.push(1);
} else {
// Increment existing count.
buf[buf.length - 1] += 1;
}
}
// Convert to a binary string.
let s = buf.map(n => String.fromCharCode(n)).join("");
// Base-64 encode and prefix with version number.
return "0:" + btoa(s);
}
// Reset whether we've seen this NMI interrupt if the mask and latch no longer overlap.
private updateNmiSeen(): void {
if ((this.nmiLatch & this.nmiMask) === 0) {
this.nmiSeen = false;
}
}
/**
* Run a certain number of CPU instructions and schedule another tick.
*/
private tick(): void {
for (let i = 0; i < this.clocksPerTick && this.started; i++) {
this.step();
}
// We might have stopped in the step() routine (e.g., with scheduled event).
if (this.started) {
this.scheduleNextTick();
}
}
/**
* Figure out how many CPU cycles we should optimally run and how long
* to wait until scheduling it, then schedule it to be run later.
*/
private scheduleNextTick(): void {
let delay: number;
if (this.cassetteMotorOn || this.keyboard.keyQueue.length > 4) {
// Go fast if we're accessing the cassette or pasting.
this.clocksPerTick = 100_000;
delay = 0;
} else {
// Delay to match original clock speed.
const now = Date.now();
const actualElapsed = now - this.startTime;
const expectedElapsed = this.tStateCount * 1000 / this.clockHz;
let behind = expectedElapsed - actualElapsed;
if (behind < -100 || behind > 100) {
// We're too far behind or ahead. Catch up artificially.
this.startTime = now - expectedElapsed;
behind = 0;
}
delay = Math.round(Math.max(0, behind));
if (delay === 0) {
// Delay too short, do more each tick.
this.clocksPerTick = Math.min(this.clocksPerTick + 100, 10000);
} else if (delay > 1) {
// Delay too long, do less each tick.
this.clocksPerTick = Math.max(this.clocksPerTick - 100, 100);
}
}
// console.log(this.clocksPerTick, delay);
this.cancelTickTimeout();
this.tickHandle = setTimeout(() => {
this.tickHandle = undefined;
this.tick();
}, delay);
}
/**
* Stop the tick timeout, if it's running.
*/
private cancelTickTimeout(): void {
if (this.tickHandle !== undefined) {
clearTimeout(this.tickHandle);
this.tickHandle = undefined;
}
}
// Set or reset the timer interrupt.
private setTimerInterrupt(state: boolean): void {
if (this.config.modelType === ModelType.MODEL1) {
if (state) {
this.irqLatch |= M1_TIMER_IRQ_MASK;
} else {
this.irqLatch &= ~M1_TIMER_IRQ_MASK;
}
} else {
if (state) {
this.irqLatch |= M3_TIMER_IRQ_MASK;
} else {
this.irqLatch &= ~M3_TIMER_IRQ_MASK;
}
}
}
// What to do when the hardware timer goes off.
private handleTimer(): void {
this.setTimerInterrupt(true);
}
// Set the state of the reset button interrupt.
private resetButtonInterrupt(state: boolean): void {
if (state) {
this.nmiLatch |= RESET_NMI_MASK;
} else {
this.nmiLatch &= ~RESET_NMI_MASK;
}
this.updateNmiSeen();
}
// Set the state of the disk motor off interrupt.
public diskMotorOffInterrupt(state: boolean): void {
if (state) {
this.nmiLatch |= DISK_MOTOR_OFF_NMI_MASK;
} else {
this.nmiLatch &= ~DISK_MOTOR_OFF_NMI_MASK;
}
this.updateNmiSeen();
}
// Set the state of the disk interrupt.
public diskIntrqInterrupt(state: boolean): void {
if (state) {
this.nmiLatch |= DISK_INTRQ_NMI_MASK;
} else {
this.nmiLatch &= ~DISK_INTRQ_NMI_MASK;
}
this.updateNmiSeen();
}
// Set the state of the disk interrupt.
public diskDrqInterrupt(state: boolean): void {
// No effect.
}
// Reset the controller to a known state.
private resetCassette() {
this.setCassetteState(CassetteState.CLOSE);
}
// Get a byte from the I/O port.
private getCassetteByte(): number {
// If the motor's running, and we're reading a byte, then get into read mode.
if (this.cassetteMotorOn) {
this.setCassetteState(CassetteState.READ);
}
// Clear any interrupt that may have triggered this read.
this.cassetteClearInterrupt();
// Cassette owns bits 0 and 7.
let b = 0;
if (this.cassetteFlipFlop) {
b |= 0x80;
}
if (this.config.modelType !== ModelType.MODEL1 && this.cassetteLastNonZeroValue === CassetteValue.POSITIVE) {
b |= 0x01;
}
return b;
}
// Write to the cassette port. We don't support writing tapes, but this is used
// for 500-baud reading to trigger the next analysis of the tape.
private putCassetteByte(b: number) {
if (this.cassetteMotorOn) {
if (this.cassetteState === CassetteState.READ) {
this.updateCassette();
this.cassetteFlipFlop = false;
}
} else {
const audioValue = CASSETTE_BITS_TO_AUDIO_VALUE[b];
this.soundPlayer.setAudioValue(audioValue, audioValue, this.tStateCount, this.clockHz);
}
}
// Kick off the reading process when doing 1500-baud reads.
private kickOffCassette() {
if (this.cassetteMotorOn &&
this.cassetteState === CassetteState.CLOSE &&
this.cassetteInterruptsEnabled()) {
// Kick off the process.
this.cassetteRiseInterrupt();
this.cassetteFallInterrupt();
}
}
// Turn the motor on or off.
private setCassetteMotor(cassetteMotorOn: boolean) {
if (cassetteMotorOn !== this.cassetteMotorOn) {
if (cassetteMotorOn) {
this.cassetteFlipFlop = false;
this.cassetteLastNonZeroValue = CassetteValue.NEUTRAL;
// Waits a second before kicking off the cassette.
// TODO this should be in CPU cycles, not browser cycles.
if (this.config.modelType !== ModelType.MODEL1) {
setTimeout(() => this.kickOffCassette(), 1000);
}
} else {
this.setCassetteState(CassetteState.CLOSE);
}
this.cassetteMotorOn = cassetteMotorOn;
if (cassetteMotorOn) {
this.cassettePlayer.onMotorStart();
} else {
this.cassettePlayer.onMotorStop();
}
}
}
// Read some of the cassette to see if we should be triggering a rise/fall interrupt.
private updateCassette() {
if (this.cassetteMotorOn && this.setCassetteState(CassetteState.READ) >= 0) {
// See how many samples we should have read by now.
const samplesToRead = Math.round((this.tStateCount - this.cassetteMotorOnClock) *
this.cassettePlayer.samplesPerSecond / this.clockHz);
// Catch up.
while (this.cassetteSamplesRead < samplesToRead) {
const sample = this.cassettePlayer.readSample();
this.cassetteSamplesRead++;
// Convert to state, where neutral is some noisy in-between state.
let cassetteValue = CassetteValue.NEUTRAL;
if (sample > CASSETTE_THRESHOLD) {
cassetteValue = CassetteValue.POSITIVE;
} else if (sample < -CASSETTE_THRESHOLD) {
cassetteValue = CassetteValue.NEGATIVE;
}
// See if we've changed value.
if (cassetteValue !== this.cassetteValue) {
if (cassetteValue === CassetteValue.POSITIVE) {
// Positive edge.
this.cassetteFlipFlop = true;
this.cassetteRiseInterrupt();
} else if (cassetteValue === CassetteValue.NEGATIVE) {
// Negative edge.
this.cassetteFlipFlop = true;
this.cassetteFallInterrupt();
}
this.cassetteValue = cassetteValue;
if (cassetteValue !== CassetteValue.NEUTRAL) {
this.cassetteLastNonZeroValue = cassetteValue;
}
}
}
}
}
// Returns 0 if the state was changed, 1 if it wasn't, and -1 on error.
private setCassetteState(newState: CassetteState): number {
const oldCassetteState = this.cassetteState;
// See if we're changing anything.
if (oldCassetteState === newState) {
return 1;
}
// Once in error, everything will fail until we close.
if (oldCassetteState === CassetteState.FAIL && newState !== CassetteState.CLOSE) {
return -1;
}
// Change things based on new state.
switch (newState) {
case CassetteState.READ:
this.openCassetteFile();
break;
}
// Update state.
this.cassetteState = newState;
return 0;
}
// Open file, get metadata, and get read to read the tape.
private openCassetteFile(): void {
// TODO open/rewind cassette?
// Reset the clock.
this.cassetteMotorOnClock = this.tStateCount;
this.cassetteSamplesRead = 0;
}
// Saw a positive edge on cassette.
private cassetteRiseInterrupt(): void {
this.cassetteRiseInterruptCount++;
this.irqLatch = (this.irqLatch & ~M3_CASSETTE_RISE_IRQ_MASK) |
(this.irqMask & M3_CASSETTE_RISE_IRQ_MASK);
}
// Saw a negative edge on cassette.
private cassetteFallInterrupt(): void {
this.cassetteFallInterruptCount++;
this.irqLatch = (this.irqLatch & ~M3_CASSETTE_FALL_IRQ_MASK) |
(this.irqMask & M3_CASSETTE_FALL_IRQ_MASK);
}
/**
* Clear screen and home cursor.
*/
private cls(): void {
for (let address = TRS80_SCREEN_BEGIN; address < TRS80_SCREEN_END; address++) {
this.writeMemory(address, 32);
}
this.positionCursor(0, 0);
}
/**
* Move the cursor (where the ROM's write routine will write to next) to the
* given location.
*
* @param col 0-based text column.
* @param row 0-based text row.
*/
private positionCursor(col: number, row: number): void {
const address = TRS80_SCREEN_BEGIN + row*64 + col;
// This works on Model III, not sure if it works on Model I or in wide mode.
this.writeMemory(0x4020, lo(address));
this.writeMemory(0x4021, hi(address));
}
/**
* Run a TRS-80 program. The exact behavior depends on the type of program.
*/
public runTrs80File(trs80File: Trs80File): void {
this.ejectAllFloppyDisks();
if (isFloppy(trs80File)) {
this.runFloppyDisk(trs80File);
} else {
switch (trs80File.className) {
case "CmdProgram":
this.runCmdProgram(trs80File);
break;
case "Cassette":
// Run the first file. Assume there's always at least one.
this.runTrs80File(trs80File.files[0].file);
break;
case "SystemProgram":
this.runSystemProgram(trs80File);
break;
case "BasicProgram":
this.runBasicProgram(trs80File);
break;
default:
console.error("Don't know how to run", trs80File);
break;
}
}
}
/**
* Load a CMD program into memory and run it.
*/
public runCmdProgram(cmdProgram: CmdProgram): void {
this.reset();
this.eventScheduler.add(undefined, this.tStateCount + this.clockHz*0.1, () => {
this.cls();
for (const chunk of cmdProgram.chunks) {
if (chunk.className === "CmdLoadBlockChunk") {
this.writeMemoryBlock(chunk.address, chunk.loadData);
} else if (chunk.className === "CmdTransferAddressChunk") {
this.startExecutable(chunk.address);
// Don't load any more after this. I assume on a real machine the jump
// happens immediately and CMD parsing ends.
break;
}
}
});
}
/**
* Load a system program into memory and run it.
*/
public runSystemProgram(systemProgram: SystemProgram): void {
this.reset();
this.eventScheduler.add(undefined, this.tStateCount + this.clockHz*0.1, () => {
this.cls();
for (const chunk of systemProgram.chunks) {
this.writeMemoryBlock(chunk.loadAddress, chunk.data);
}
// Do what the SYSTEM command does.
this.setStackPointer(0x4288);
// Handle programs that don't define an entry point address.
let entryPointAddress = systemProgram.entryPointAddress;
if (entryPointAddress === 0) {
const guessAddress = systemProgram.guessEntryAddress();
if (guessAddress !== undefined) {
entryPointAddress = guessAddress;
}
}
this.startExecutable(entryPointAddress);
});
}
/**
* Load a Basic program into memory and run it.
*/
public runBasicProgram(basicProgram: BasicProgram): void {
this.reset();
// Wait for Cass?
this.eventScheduler.add(undefined, this.tStateCount + this.clockHz*0.1, () => {
this.keyboard.simulateKeyboardText("\n0\n");
// Wait for Ready prompt.
this.eventScheduler.add(undefined, this.tStateCount + this.clockHz*0.2, () => {
this.loadBasicProgram(basicProgram);
this.keyboard.simulateKeyboardText("RUN\n");
});
});
}
/**
* Get the address of the first line of the Basic program, or a string explaining the error.
*/
private getBasicAddress(): number | string {
const addr = this.readMemory(0x40A4) + (this.readMemory(0x40A5) << 8);
if (addr < 0x4200) {
return `Basic load address is uninitialized (0x${toHexWord(addr)})`;
}
return addr;
}
/**
* Load a Basic program into memory, replacing the one that's there. Does not run it.
*/
public loadBasicProgram(basicProgram: BasicProgram): void {
// Find address to load to.
const addrOrError = this.getBasicAddress();
if (typeof(addrOrError) === "string") {
console.error(addrOrError);
return;
}
let addr = addrOrError as number;
// Terminate current line (if any) and set up the new one.
let lineStart: number | undefined;
const newLine = () => {
if (lineStart !== undefined) {
// End-of-line marker.
this.writeMemory(addr++, 0);
// Update previous line's next-line pointer.
this.writeMemory(lineStart, lo(addr));
this.writeMemory(lineStart + 1, hi(addr));
}
// Remember address of next-line pointer.
lineStart = addr;
// Next-line pointer.
this.writeMemory(addr++, 0);
this.writeMemory(addr++, 0);
};
// Write elements to memory.
for (const e of basicProgram.elements) {
if (e.offset !== undefined) {
if (e.elementType === ElementType.LINE_NUMBER) {
newLine();
}
// Write element.
addr = this.writeMemoryBlock(addr, basicProgram.binary, e.offset, e.length);
}
}
newLine();
// End of Basic program pointer.
this.writeMemory(0x40F9, lo(addr));
this.writeMemory(0x40FA, hi(addr));
// Start of array variables pointer.
this.writeMemory(0x40FB, lo(addr));
this.writeMemory(0x40FC, hi(addr));
// Start of free memory pointer.
this.writeMemory(0x40FD, lo(addr));
this.writeMemory(0x40FE, hi(addr));
}
/**
* Remove floppy disks from all drives.
*/
public ejectAllFloppyDisks(): void {
for (let i = 0; i < FLOPPY_DRIVE_COUNT; i++) {
this.loadFloppyDisk(undefined, i);
}
}
/**
* Load the floppy disk into the specified drive.
* @param floppyDisk the floppy, or undefined to unmount.
* @param driveNumber the drive number, 0-based.
*/
public loadFloppyDisk(floppyDisk: FloppyDisk | undefined, driveNumber: number): void {
this.fdc.loadFloppyDisk(floppyDisk, driveNumber);
}
/**
* Load a floppy and reboot into it.
*/
private runFloppyDisk(floppyDisk: FloppyDisk): void {
// Mount floppy.
this.loadFloppyDisk(floppyDisk, 0);
// Reboot.
this.reset();
}
/**
* Pulls the Basic program currently in memory, or returns a string with an error.
*/
public getBasicProgramFromMemory(): BasicProgram | string {
const addrOrError = this.getBasicAddress();
if (typeof(addrOrError) === "string") {
return addrOrError;
}
let addr = addrOrError as number;
// Walk through the program lines to find the end.
const beginAddr = addr;
while (true) {
// Find end address.
const nextLine = this.readMemory(addr) + (this.readMemory(addr + 1) << 8);
if (nextLine === 0) {
break;
}
if (nextLine < addr) {
// Error, went backward.
return `Next address 0x${toHexWord(nextLine)} is less than current address 0x${toHexWord(addr)}`;
}
addr = nextLine;
}
const endAddr = addr + 2;
// Put together the binary of just the program.
const binary = new Uint8Array(endAddr - beginAddr + 1);
binary[0] = BASIC_HEADER_BYTE;
binary.set(this.memory.subarray(beginAddr, endAddr), 1);
// Decode the program.
const basic = decodeBasicProgram(binary);
if (basic === undefined) {
return "Basic couldn't be decoded";
}
return basic;
}
} | the_stack |
import { Chart } from '../chart';
import { AnimationOptions, Animation, Browser, createElement } from '@syncfusion/ej2-base';
import {
textElement, getValueXByPoint, stopTimer, findCrosshairDirection,
getValueYByPoint, ChartLocation, withInBounds, removeElement
} from '../../common/utils/helper';
import { PathOption, Rect, Size, TextOption, measureText, SvgRenderer, CanvasRenderer } from '@syncfusion/ej2-svg-base';
import { Axis } from '../axis/axis';
import { CrosshairSettingsModel } from '../chart-model';
/**
* `Crosshair` module is used to render the crosshair for chart.
*/
export class Crosshair {
//Internal variables
private elementID: string;
private elementSize: Size;
private svgRenderer: SvgRenderer;
private crosshairInterval: number;
private arrowLocation: ChartLocation = new ChartLocation(0, 0);
private isTop: boolean; private isBottom: boolean; private isLeft: boolean; private isRight: boolean;
private valueX: number;
private valueY: number;
private rx: number = 2;
private ry: number = 2;
//Module declarations
private chart: Chart;
/**
* Constructor for crosshair module.
*
* @private
*/
constructor(chart: Chart) {
this.chart = chart;
this.elementID = this.chart.element.id;
this.svgRenderer = new SvgRenderer(this.chart.element.id);
this.addEventListener();
}
/**
* @hidden
*/
private addEventListener(): void {
if (this.chart.isDestroyed) { return; }
const cancelEvent: string = Browser.isPointer ? 'pointerleave' : 'mouseleave';
this.chart.on(Browser.touchMoveEvent, this.mouseMoveHandler, this);
this.chart.on(Browser.touchEndEvent, this.mouseUpHandler, this);
this.chart.on(cancelEvent, this.mouseLeaveHandler, this);
this.chart.on('tapHold', this.longPress, this);
}
private mouseUpHandler(): void {
if (this.chart.startMove) {
this.removeCrosshair(2000);
}
}
private mouseLeaveHandler(): void {
this.removeCrosshair(1000);
}
private mouseMoveHandler(event: PointerEvent | TouchEvent): void {
const chart: Chart = this.chart;
chart.mouseX = chart.mouseX / chart.scaleX;
chart.mouseY = chart.mouseY / chart.scaleY;
if (event.type === 'touchmove' && (Browser.isIos || Browser.isIos7) && chart.startMove && event.preventDefault) {
event.preventDefault();
}
// Tooltip for chart series.
if (!chart.disableTrackTooltip) {
if (withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {
if (chart.startMove || !chart.isTouch) {
this.crosshair();
}
} else {
this.removeCrosshair(1000);
}
}
}
/**
* Handles the long press on chart.
*
* @returns {boolean} false
* @private
*/
private longPress(): boolean {
const chart: Chart = this.chart;
if (withInBounds(chart.mouseX, chart.mouseY, chart.chartAxisLayoutPanel.seriesClipRect)) {
this.crosshair();
}
return false;
}
/**
* Renders the crosshair.
*
* @returns {void}
*/
public crosshair(): void {
const chart: Chart = this.chart; let horizontalCross: string = ''; let verticalCross: string = '';
let options: PathOption; let axisTooltipGroup: Element = document.getElementById( this.elementID + '_crosshair_axis');
const crosshair: CrosshairSettingsModel = chart.crosshair;
let tooltipdiv: Element = document.getElementById(this.elementID + '_tooltip');
const chartRect: Rect = chart.chartAxisLayoutPanel.seriesClipRect;
const crossGroup: HTMLElement = chart.enableCanvas ? document.getElementById(this.elementID + '_Secondary_Element') :
document.getElementById(this.elementID + '_UserInteraction');
let crosshairsvg: Element;
let cross: HTMLElement = document.getElementById(this.elementID + '_Crosshair');
if (chart.enableCanvas) {
if (!cross) {
cross = createElement('div', {
id: this.elementID + '_Crosshair', styles: 'position: absolute; pointer-events: none'
});
crossGroup.appendChild(cross);
}
}
this.stopAnimation();
if (chart.tooltip.enable && !withInBounds(chart.tooltipModule.valueX, chart.tooltipModule.valueY, chartRect)) {
return null;
}
if (chart.stockChart && chart.stockChart.onPanning) {
this.removeCrosshair(1000);
return null;
}
this.valueX = chart.tooltip.enable ? chart.tooltipModule.valueX : chart.mouseX;
this.valueY = chart.tooltip.enable ? chart.tooltipModule.valueY : chart.mouseY;
if (!chart.enableCanvas) {
crossGroup.setAttribute('opacity', '1');
}
if (crosshair.lineType === 'Both' || crosshair.lineType === 'Horizontal') {
horizontalCross += 'M ' + chartRect.x + ' ' + this.valueY +
' L ' + (chartRect.x + chartRect.width) + ' ' + this.valueY;
}
if (crosshair.lineType === 'Both' || crosshair.lineType === 'Vertical') {
verticalCross += 'M ' + this.valueX + ' ' + chartRect.y +
' L ' + this.valueX + ' ' + (chartRect.y + chartRect.height);
}
if (chart.enableCanvas) {
if (!axisTooltipGroup) {
axisTooltipGroup = this.svgRenderer.createGroup({ 'id': this.elementID + '_crosshair_axis' });
}
const elementID: string = chart.tooltip.enable ? chart.element.id + '_tooltip_svg' : chart.element.id + '_svg';
crosshairsvg = this.svgRenderer.createSvg({
id: elementID,
width: chart.availableSize.width,
height: chart.availableSize.height
});
if (chart.tooltip.enable) {
tooltipdiv = !tooltipdiv ? chart.tooltipModule.createElement() : tooltipdiv;
tooltipdiv.appendChild(crosshairsvg);
crossGroup.appendChild(tooltipdiv);
}
options = new PathOption(
this.elementID + '_HorizontalLine', 'none', crosshair.line.width,
crosshair.horizontalLineColor || crosshair.line.color || chart.themeStyle.crosshairLine, crosshair.opacity, crosshair.dashArray, horizontalCross
);
this.drawCrosshairLine(options, cross, chartRect.x, this.valueY, chartRect.width, 0, horizontalCross);
/**
* due to not working for vertical line side I added new option
* options.d = verticalCross; options.id = this.elementID + '_VerticalLine';
*/
options = new PathOption(
this.elementID + '_VerticalLine', 'none', crosshair.line.width,
crosshair.verticalLineColor || crosshair.line.color || chart.themeStyle.crosshairLine, crosshair.opacity, crosshair.dashArray, verticalCross
);
this.drawCrosshairLine(options, cross, this.valueX, chartRect.y, 0, chartRect.height, verticalCross);
this.renderAxisTooltip(chart, chartRect, <Element>axisTooltipGroup);
crosshairsvg.appendChild(axisTooltipGroup);
if (!chart.tooltip.enable) {
cross.appendChild(crosshairsvg);
}
} else {
if (crossGroup.childNodes.length === 0) {
axisTooltipGroup = chart.renderer.createGroup({ 'id': this.elementID + '_crosshair_axis' });
options = new PathOption(
this.elementID + '_HorizontalLine', 'none', crosshair.line.width,
crosshair.horizontalLineColor || crosshair.line.color || chart.themeStyle.crosshairLine, crosshair.opacity, crosshair.dashArray, horizontalCross
);
this.renderCrosshairLine(options, crossGroup);
options = new PathOption(
this.elementID + '_VerticalLine', 'none', crosshair.line.width,
crosshair.verticalLineColor || crosshair.line.color || chart.themeStyle.crosshairLine, crosshair.opacity, crosshair.dashArray, verticalCross
);
this.renderCrosshairLine(options, crossGroup);
crossGroup.appendChild(axisTooltipGroup);
this.renderAxisTooltip(chart, chartRect, <Element>crossGroup.lastChild);
} else {
document.getElementById(this.elementID + '_HorizontalLine').setAttribute('d', horizontalCross);
document.getElementById(this.elementID + '_VerticalLine').setAttribute('d', verticalCross);
this.renderAxisTooltip(chart, chartRect, <Element>crossGroup.lastChild);
}
}
}
private renderCrosshairLine(options: PathOption, crossGroup: HTMLElement): void {
const htmlObject: HTMLElement = this.chart.renderer.drawPath(options) as HTMLElement;
crossGroup.appendChild(htmlObject);
}
private drawCrosshairLine(options: PathOption, crossGroup: HTMLElement, left: number,
top: number, width: number, height: number, direction: string): void {
if (!document.getElementById(options.id) && direction) {
const line: HTMLElement = createElement('div', {
id: options.id
});
crossGroup.appendChild(line);
}
if (document.getElementById(options.id)) {
const style: string = 'top:' + top.toString() + 'px;' +
'left:' + left.toString() + 'px;' +
'width:' + width + 'px;' +
'height:' + height + 'px;' +
'fill:' + options.stroke + ';' +
'border: 0.5px solid ' + options.stroke + ';' +
'opacity: ' + options.opacity + ' ; ' +
'position: absolute';
const crosshairline: HTMLElement = document.getElementById(options.id);
const crosshairtooltip: HTMLElement = document.getElementById(this.elementID + '_crosshair_axis');
crosshairline.style.cssText = style;
crossGroup.style.opacity = '1';
if (crosshairtooltip) {
crosshairtooltip.style.opacity = '1';
}
}
}
private renderAxisTooltip(chart: Chart, chartRect: Rect, axisGroup: Element): void {
let axis: Axis; let text: string;
let rect: Rect;
let pathElement: Element;
let textElem: Element;
let options: TextOption;
const padding: number = 5;
let direction: string;
let axisRect: Rect;
for (let k: number = 0, length: number = chart.axisCollections.length; k < length; k++) {
axis = chart.axisCollections[k];
axisRect = !axis.placeNextToAxisLine ? axis.rect : axis.updatedRect;
if (axis.crosshairTooltip.enable) {
if ((this.valueX <= (axisRect.x + axisRect.width) && axisRect.x <= this.valueX) ||
(this.valueY <= (axisRect.y + axisRect.height) && axisRect.y <= this.valueY)) {
pathElement = document.getElementById(this.elementID + '_axis_tooltip_' + k);
textElem = document.getElementById(this.elementID + '_axis_tooltip_text_' + k);
text = this.getAxisText(axis);
if (!text) {
continue;
}
rect = this.tooltipLocation(text, axis, chartRect, axisRect);
if (pathElement === null) {
if (chart.enableCanvas) {
pathElement = this.svgRenderer.drawPath(
{
'id': this.elementID + '_axis_tooltip_' + k,
'fill': axis.crosshairTooltip.fill || chart.themeStyle.crosshairFill
});
} else {
pathElement = chart.renderer.drawPath(
{
'id': this.elementID + '_axis_tooltip_' + k,
'fill': axis.crosshairTooltip.fill || chart.themeStyle.crosshairFill},
null);
}
axisGroup.appendChild(pathElement);
options = new TextOption(this.elementID + '_axis_tooltip_text_' + k, 0, 0, 'start', text);
const render: SvgRenderer | CanvasRenderer = chart.enableCanvas ? this.svgRenderer : chart.renderer;
textElem = textElement(
render, options, axis.crosshairTooltip.textStyle,
axis.crosshairTooltip.textStyle.color || chart.themeStyle.crosshairLabel, axisGroup, null, null, null,
null, null, null, null, null, chart.enableCanvas
);
}
direction = findCrosshairDirection(
this.rx, this.ry, rect, this.arrowLocation, 9,
this.isTop, this.isBottom, this.isLeft, this.valueX, this.valueY
);
pathElement.setAttribute('d', direction);
textElem.textContent = text;
textElem.setAttribute('x', (rect.x + padding + (chart.enableRtl ? this.elementSize.width : 0)).toString());
textElem.setAttribute('y', (rect.y + padding + 3 * this.elementSize.height / 4).toString());
if (this.chart.theme === 'Fluent' || this.chart.theme === "FluentDark") {
const shadowId: string = this.chart.element.id + '_shadow';
pathElement.setAttribute('filter', Browser.isIE ? '' : 'url(#' + shadowId + ')');
let shadow: string = '<filter id="' + shadowId + '" height="130%"><feGaussianBlur in="SourceAlpha" stdDeviation="3"/>';
shadow += '<feOffset dx="3" dy="3" result="offsetblur"/><feComponentTransfer><feFuncA type="linear" slope="0.5"/>';
shadow += '</feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
const defElement: Element = this.chart.renderer.createDefs();
defElement.setAttribute('id', this.chart.element.id + 'SVG_tooltip_definition');
axisGroup.appendChild(defElement);
defElement.innerHTML = shadow;
pathElement.setAttribute('stroke', '#cccccc');
pathElement.setAttribute('stroke-width', '0.5');
}
} else {
removeElement(this.elementID + '_axis_tooltip_' + k);
removeElement(this.elementID + '_axis_tooltip_text_' + k);
}
}
}
}
private getAxisText(axis: Axis): string {
let value: number;
this.isBottom = false; this.isTop = false; this.isLeft = false; this.isRight = false;
const labelValue: number = (axis.valueType === 'Category' && axis.labelPlacement === 'BetweenTicks')
? 0.5 : 0;
const isOpposed: boolean = axis.isAxisOpposedPosition;
if (axis.orientation === 'Horizontal') {
value = getValueXByPoint(Math.abs(this.valueX - axis.rect.x), axis.rect.width, axis) + labelValue;
this.isBottom = !isOpposed; this.isTop = isOpposed;
} else {
value = getValueYByPoint(Math.abs(this.valueY - axis.rect.y), axis.rect.height, axis) + labelValue;
this.isRight = isOpposed; this.isLeft = !isOpposed;
}
if (axis.valueType === 'DateTime') {
return axis.format(new Date(value));
} else if (axis.valueType === 'Category') {
return axis.labels[Math.floor(<number>value)];
} else if (axis.valueType === 'DateTimeCategory') {
return this.chart.dateTimeCategoryModule.getIndexedAxisLabel(axis.labels[Math.floor(<number>value)], axis.format);
} else if (axis.valueType === 'Logarithmic') {
return value = axis.format(Math.pow(axis.logBase, value));
} else {
const customLabelFormat: boolean = axis.labelFormat && axis.labelFormat.match('{value}') !== null;
return customLabelFormat ? axis.labelFormat.replace('{value}', axis.format(value)) : axis.format(value);
}
}
private tooltipLocation(text: string, axis: Axis, bounds: Rect, axisRect: Rect): Rect {
const padding: number = 5; const arrowPadding: number = 9;
let tooltipRect: Rect;
const boundsX: number = bounds.x;
const boundsY: number = bounds.y;
const islabelInside: boolean = axis.labelPosition === 'Inside';
let scrollBarHeight: number = axis.scrollbarSettings.enable || (axis.zoomingScrollBar && axis.zoomingScrollBar.svgObject)
? axis.scrollBarHeight : 0;
this.elementSize = measureText(text, axis.crosshairTooltip.textStyle);
const isOpposed: boolean = axis.isAxisOpposedPosition;
if (axis.orientation === 'Horizontal') {
const yLocation: number = islabelInside ? axisRect.y - this.elementSize.height - (padding * 2 + arrowPadding) :
axisRect.y + scrollBarHeight;
const height: number = islabelInside ? axisRect.y - this.elementSize.height - arrowPadding : axisRect.y + arrowPadding;
this.arrowLocation = new ChartLocation(this.valueX, yLocation);
tooltipRect = new Rect(
(this.valueX - (this.elementSize.width / 2) - padding), height + (!islabelInside ? scrollBarHeight : 0),
this.elementSize.width + padding * 2, this.elementSize.height + padding * 2
);
if (isOpposed) {
tooltipRect.y = islabelInside ? axisRect.y : axisRect.y -
(this.elementSize.height + padding * 2 + arrowPadding) - scrollBarHeight;
}
if (tooltipRect.x < boundsX) {
tooltipRect.x = boundsX;
}
if (tooltipRect.x + tooltipRect.width > boundsX + bounds.width) {
tooltipRect.x -= ((tooltipRect.x + tooltipRect.width) - (boundsX + bounds.width));
}
if (this.arrowLocation.x + arrowPadding / 2 > tooltipRect.x + tooltipRect.width - this.rx) {
this.arrowLocation.x = tooltipRect.x + tooltipRect.width - this.rx - arrowPadding;
}
if (this.arrowLocation.x - arrowPadding < tooltipRect.x + this.rx) {
this.arrowLocation.x = tooltipRect.x + this.rx + arrowPadding;
}
} else {
scrollBarHeight = scrollBarHeight * (isOpposed ? 1 : -1);
this.arrowLocation = new ChartLocation(axisRect.x, this.valueY);
const width: number = islabelInside ? axisRect.x - scrollBarHeight :
axisRect.x - (this.elementSize.width) - (padding * 2 + arrowPadding);
tooltipRect = new Rect(
width + scrollBarHeight, this.valueY - (this.elementSize.height / 2) - padding,
this.elementSize.width + (padding * 2), this.elementSize.height + padding * 2
);
if (isOpposed) {
tooltipRect.x = islabelInside ? axisRect.x - this.elementSize.width - arrowPadding :
axisRect.x + arrowPadding + scrollBarHeight;
if ((tooltipRect.x + tooltipRect.width) > this.chart.availableSize.width) {
this.arrowLocation.x -= ((tooltipRect.x + tooltipRect.width) - this.chart.availableSize.width);
tooltipRect.x -= ((tooltipRect.x + tooltipRect.width) - this.chart.availableSize.width);
}
} else {
if (tooltipRect.x < 0) {
this.arrowLocation.x -= tooltipRect.x;
tooltipRect.x = 0;
}
}
if (tooltipRect.y < boundsY) {
tooltipRect.y = boundsY;
}
if (tooltipRect.y + tooltipRect.height >= boundsY + bounds.height) {
tooltipRect.y -= ((tooltipRect.y + tooltipRect.height) - (boundsY + bounds.height));
}
if (this.arrowLocation.y + arrowPadding / 2 > tooltipRect.y + tooltipRect.height - this.ry) {
this.arrowLocation.y = tooltipRect.y + tooltipRect.height - this.ry - arrowPadding / 2;
}
if (this.arrowLocation.y - arrowPadding / 2 < tooltipRect.y + this.ry) {
this.arrowLocation.y = tooltipRect.y + this.ry + arrowPadding / 2;
}
}
return tooltipRect;
}
private stopAnimation(): void {
stopTimer(this.crosshairInterval);
}
private progressAnimation(): void {
stopTimer(this.crosshairInterval);
}
/**
* Removes the crosshair on mouse leave.
*
* @returns {void}
* @private
*/
public removeCrosshair(duration: number): void {
const chart: Chart = this.chart;
const crosshair: HTMLElement = chart.enableCanvas ? document.getElementById(this.elementID + '_Crosshair') :
document.getElementById(this.elementID + '_UserInteraction');
const crosshairtooltip: HTMLElement = chart.enableCanvas ? document.getElementById(this.elementID + '_crosshair_axis') : null;
this.stopAnimation();
if (crosshair && crosshair.getAttribute('opacity') !== '0') {
this.crosshairInterval = +setTimeout(
(): void => {
new Animation({}).animate(crosshair, {
duration: 200,
progress: (args: AnimationOptions): void => {
// crosshair.removeAttribute('e-animate');
crosshair.style.animation = '';
if (!chart.enableCanvas) {
crosshair.setAttribute('opacity', (1 - (args.timeStamp / args.duration)).toString());
} else {
crosshair.style.opacity = (1 - (args.timeStamp / args.duration)).toString();
crosshairtooltip.style.opacity = (1 - (args.timeStamp / args.duration)).toString();
}
},
end: (): void => {
if (chart.enableCanvas) {
crosshair.style.opacity = '0';
crosshairtooltip.style.opacity = '0';
} else {
crosshair.setAttribute('opacity', '0');
}
chart.startMove = false;
if (chart.tooltipModule) {
chart.tooltipModule.valueX = null;
chart.tooltipModule.valueY = null;
}
}
});
},
duration);
}
}
/**
* Get module name.
*
* @returns {string} module name
*/
protected getModuleName(): string {
/**
* Returns the module name
*/
return 'Crosshair';
}
/**
* To destroy the crosshair.
*
* @returns {void}
* @private
*/
public destroy(): void {
/**
* Destroy method performed here
*/
}
} | the_stack |
import * as React from "react";
import { mount, configure } from "enzyme";
import * as Adapter from 'enzyme-adapter-react-16';
import { ListItemAttachments } from "../../../src/controls/listItemAttachments/ListItemAttachments";
import { assert} from "chai";
configure({ adapter: new Adapter() });
describe("<ListItemAttachments />",()=>{
test("should render item attachment", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let mockSPService = {
getListItemAttachments: (listId, itemId)=>Promise.resolve([{
FileName : "Test file.docx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.docx"
},{
FileName : "Test file.xlsx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.xlsx"
}])
}
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
listId="test-list-id"
itemId={1}
/>);
//@ts-ignore
listItemAttachments.instance()._spservice = mockSPService;
await listItemAttachments.instance().componentDidMount();
listItemAttachments.update();
let attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
let testWordCard = attachmentCards[0];
let testExcelCard = attachmentCards[1];
assert.equal(testWordCard.querySelector("img").src,"https://static2.sharepointonline.com/files/fabric/assets/item-types/96/docx.png");
assert.equal(testWordCard.textContent,"Test file.docx");
assert.equal(testExcelCard.querySelector("img").src,"https://static2.sharepointonline.com/files/fabric/assets/item-types/96/xlsx.png");
assert.equal(testExcelCard.textContent,"Test file.xlsx");
});
test("should render placeholder if item has no attachments", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let mockSPService = {
getListItemAttachments: (listId, itemId)=>Promise.resolve([])
}
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
listId="test-list-id"
itemId={1}
/>);
//@ts-ignore
listItemAttachments.instance()._spservice = mockSPService;
await listItemAttachments.instance().componentDidMount();
listItemAttachments.update();
let placeholder = listItemAttachments.getDOMNode().querySelector('[aria-label="ListItemAttachmentslPlaceHolderButtonLabel"]');
assert.isOk(placeholder)
});
test("should render placeholder if no item provided", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let mockSPService = {
getListItemAttachments: (listId, itemId)=>Promise.resolve([{
FileName : "Test file.docx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.docx"
},{
FileName : "Test file.xlsx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.xlsx"
}
])
}
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
listId="test-list-id"
/>);
//@ts-ignore
listItemAttachments.instance()._spservice = mockSPService;
await listItemAttachments.instance().componentDidMount();
listItemAttachments.update();
let placeholder = listItemAttachments.getDOMNode().querySelector('[aria-label="ListItemAttachmentslPlaceHolderButtonLabel"]');
assert.isOk(placeholder)
});
test("should add and load attachments", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let asserted = false;
let listItemAttachmentsRef = React.createRef<ListItemAttachments>();
let mockFile = new File([], "Test file.txt");
let mockSPService = {
getListItemAttachments: (listId, itemId)=>Promise.resolve([{
FileName : "Test file.xlsx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.xlsx"
},{
FileName : "Test file.txt",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.txt"
}]),
addAttachment: (listId: string, itemId: number, fileName: string, file: File, webUrl?: string)=>{
assert.equal(listId,"test-list-id");
assert.equal(itemId, 1);
assert.equal(file, mockFile);
asserted = true;
}
}
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
ref={listItemAttachmentsRef}
listId="test-list-id"
/>);
//@ts-ignore
listItemAttachments.instance()._spservice = mockSPService;
await listItemAttachments.instance().componentDidMount();
let placeholder = listItemAttachments.getDOMNode().querySelector('[aria-label="ListItemAttachmentslPlaceHolderButtonLabel"]');
listItemAttachments.instance().setState({
filesToUpload:[mockFile]
});
listItemAttachments.update();
assert.isOk(placeholder)
await listItemAttachmentsRef.current.uploadAttachments(1);
listItemAttachments.update();
let attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
let testWordCard = attachmentCards[0];
let testTxtCard = attachmentCards[1];
assert.equal(testWordCard.querySelector("img").src,"https://static2.sharepointonline.com/files/fabric/assets/item-types/96/xlsx.png");
assert.equal(testWordCard.textContent,"Test file.xlsx");
assert.equal(testTxtCard.querySelector("img").src,"https://static2.sharepointonline.com/files/fabric/assets/item-types/96/txt.png");
assert.equal(testTxtCard.textContent,"Test file.txt");
assert.isTrue(asserted);
});
test("should delete without itemId provided", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let mockFile = new File([], "Test file.txt");
let mockFileToDelete = new File([], "Test file to delete.txt");
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
listId="test-list-id"
/>);
await listItemAttachments.instance().componentDidMount();
//@ts-ignore
await listItemAttachments.instance()._onAttachmentUpload(mockFile);
//@ts-ignore
await listItemAttachments.instance()._onAttachmentUpload(mockFileToDelete);
listItemAttachments.update();
let attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
let mockFileCard = attachmentCards[0];
let mockFileCardToDelete = attachmentCards[1];
assert.equal(mockFileCard.textContent,"Test file.txt");
assert.equal(mockFileCardToDelete.textContent,"Test file to delete.txt");
listItemAttachments.instance().setState({
file: {
FileName: mockFileToDelete.name
}
});
//@ts-ignore
await listItemAttachments.instance().onConfirmedDeleteAttachment();
listItemAttachments.update();
attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
mockFileCard = attachmentCards[0];
assert.equal(mockFileCard.textContent,"Test file.txt");
assert.isNotOk(attachmentCards[1]);
});
test("should delete with itemId provided", async ()=>{
let mockContext = {
pageContext:{
web:{
absoluteUrl: "https://test.sharepoint.com/sites/test-site"
}
}
};
let asserted = false;
let mockSPService = {
getListItemAttachments: (listId, itemId)=>Promise.resolve([]),
deleteAttachment: (fileName: string, listId: string, itemId: number)=>{
assert.equal(fileName, "Test file.txt");
assert.equal(listId, "test-list-id");
assert.equal(itemId, 1);
asserted = true;
return Promise.resolve();
}
}
jest.spyOn(mockSPService, "getListItemAttachments").mockReturnValueOnce(Promise.resolve([{
FileName : "Test file.xlsx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.xlsx"
},{
FileName : "Test file.txt",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.txt"
}]));
jest.spyOn(mockSPService, "getListItemAttachments").mockReturnValueOnce(Promise.resolve([{
FileName : "Test file.xlsx",
ServerRelativeUrl: "/sites/test-site/Shared Documents/TestFile.xlsx"
}]));
let listItemAttachments = mount(<ListItemAttachments
context={mockContext as any}
listId="test-list-id"
itemId={1}
/>);
//@ts-ignore
listItemAttachments.instance()._spservice = mockSPService;
await listItemAttachments.instance().componentDidMount();
listItemAttachments.update();
let attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
let mockFileCard = attachmentCards[0];
let mockFileCardToDelete = attachmentCards[1];
assert.equal(mockFileCard.textContent,"Test file.xlsx");
assert.equal(mockFileCardToDelete.textContent,"Test file.txt");
listItemAttachments.instance().setState({
file: {
FileName: "Test file.txt"
}
});
//@ts-ignore
await listItemAttachments.instance().onConfirmedDeleteAttachment();
//@ts-ignore
await listItemAttachments.instance().loadAttachments();
listItemAttachments.update();
attachmentCards = listItemAttachments.getDOMNode().querySelectorAll('.ms-DocumentCard');
mockFileCard = attachmentCards[0];
assert.equal(mockFileCard.textContent,"Test file.xlsx");
assert.isNotOk(attachmentCards[1]);
})
}); | the_stack |
import {FormulaTransform as VgFormulaTransform, SignalRef} from 'vega';
import {isNumber, isString} from 'vega-util';
import {AncestorParse} from '.';
import {isMinMaxOp} from '../../aggregate';
import {getMainRangeChannel, SingleDefChannel} from '../../channel';
import {
isFieldDef,
isFieldOrDatumDefForTimeFormat,
isScaleFieldDef,
isTypedFieldDef,
TypedFieldDef
} from '../../channeldef';
import {isGenerator, Parse} from '../../data';
import {DateTime, isDateTime} from '../../datetime';
import * as log from '../../log';
import {forEachLeaf} from '../../logical';
import {isPathMark} from '../../mark';
import {
isFieldEqualPredicate,
isFieldGTEPredicate,
isFieldGTPredicate,
isFieldLTEPredicate,
isFieldLTPredicate,
isFieldOneOfPredicate,
isFieldPredicate,
isFieldRangePredicate
} from '../../predicate';
import {isSortField} from '../../sort';
import {FilterTransform} from '../../transform';
import {accessPathDepth, accessPathWithDatum, Dict, duplicate, hash, keys, removePathFromField} from '../../util';
import {signalRefOrValue} from '../common';
import {isFacetModel, isUnitModel, Model} from '../model';
import {Split} from '../split';
import {DataFlowNode} from './dataflow';
/**
* Remove quotes from a string.
*/
function unquote(pattern: string) {
if ((pattern.startsWith("'") && pattern.endsWith("'")) || (pattern.startsWith('"') && pattern.endsWith('"'))) {
return pattern.slice(1, -1);
}
return pattern;
}
/**
* @param field The field.
* @param parse What to parse the field as.
*/
function parseExpression(field: string, parse: string): string {
const f = accessPathWithDatum(field);
if (parse === 'number') {
return `toNumber(${f})`;
} else if (parse === 'boolean') {
return `toBoolean(${f})`;
} else if (parse === 'string') {
return `toString(${f})`;
} else if (parse === 'date') {
return `toDate(${f})`;
} else if (parse === 'flatten') {
return f;
} else if (parse.startsWith('date:')) {
const specifier = unquote(parse.slice(5, parse.length));
return `timeParse(${f},'${specifier}')`;
} else if (parse.startsWith('utc:')) {
const specifier = unquote(parse.slice(4, parse.length));
return `utcParse(${f},'${specifier}')`;
} else {
log.warn(log.message.unrecognizedParse(parse));
return null;
}
}
export function getImplicitFromFilterTransform(transform: FilterTransform) {
const implicit: Dict<string> = {};
forEachLeaf(transform.filter, filter => {
if (isFieldPredicate(filter)) {
// Automatically add a parse node for filters with filter objects
let val: string | number | boolean | DateTime | SignalRef = null;
// For EqualFilter, just use the equal property.
// For RangeFilter and OneOfFilter, all array members should have
// the same type, so we only use the first one.
if (isFieldEqualPredicate(filter)) {
val = signalRefOrValue(filter.equal);
} else if (isFieldLTEPredicate(filter)) {
val = signalRefOrValue(filter.lte);
} else if (isFieldLTPredicate(filter)) {
val = signalRefOrValue(filter.lt);
} else if (isFieldGTPredicate(filter)) {
val = signalRefOrValue(filter.gt);
} else if (isFieldGTEPredicate(filter)) {
val = signalRefOrValue(filter.gte);
} else if (isFieldRangePredicate(filter)) {
val = filter.range[0];
} else if (isFieldOneOfPredicate(filter)) {
val = (filter.oneOf ?? filter['in'])[0];
} // else -- for filter expression, we can't infer anything
if (val) {
if (isDateTime(val)) {
implicit[filter.field] = 'date';
} else if (isNumber(val)) {
implicit[filter.field] = 'number';
} else if (isString(val)) {
implicit[filter.field] = 'string';
}
}
if (filter.timeUnit) {
implicit[filter.field] = 'date';
}
}
});
return implicit;
}
/**
* Creates a parse node for implicit parsing from a model and updates ancestorParse.
*/
export function getImplicitFromEncoding(model: Model) {
const implicit: Dict<string> = {};
function add(fieldDef: TypedFieldDef<string>) {
if (isFieldOrDatumDefForTimeFormat(fieldDef)) {
implicit[fieldDef.field] = 'date';
} else if (
fieldDef.type === 'quantitative' &&
isMinMaxOp(fieldDef.aggregate) // we need to parse numbers to support correct min and max
) {
implicit[fieldDef.field] = 'number';
} else if (accessPathDepth(fieldDef.field) > 1) {
// For non-date/non-number (strings and booleans), derive a flattened field for a referenced nested field.
// (Parsing numbers / dates already flattens numeric and temporal fields.)
if (!(fieldDef.field in implicit)) {
implicit[fieldDef.field] = 'flatten';
}
} else if (isScaleFieldDef(fieldDef) && isSortField(fieldDef.sort) && accessPathDepth(fieldDef.sort.field) > 1) {
// Flatten fields that we sort by but that are not otherwise flattened.
if (!(fieldDef.sort.field in implicit)) {
implicit[fieldDef.sort.field] = 'flatten';
}
}
}
if (isUnitModel(model) || isFacetModel(model)) {
// Parse encoded fields
model.forEachFieldDef((fieldDef, channel) => {
if (isTypedFieldDef(fieldDef)) {
add(fieldDef);
} else {
const mainChannel = getMainRangeChannel(channel);
const mainFieldDef = model.fieldDef(mainChannel as SingleDefChannel) as TypedFieldDef<string>;
add({
...fieldDef,
type: mainFieldDef.type
});
}
});
}
// Parse quantitative dimension fields of path marks as numbers so that we sort them correctly.
if (isUnitModel(model)) {
const {mark, markDef, encoding} = model;
if (
isPathMark(mark) &&
// No need to sort by dimension if we have a connected scatterplot (order channel is present)
!model.encoding.order
) {
const dimensionChannel = markDef.orient === 'horizontal' ? 'y' : 'x';
const dimensionChannelDef = encoding[dimensionChannel];
if (
isFieldDef(dimensionChannelDef) &&
dimensionChannelDef.type === 'quantitative' &&
!(dimensionChannelDef.field in implicit)
) {
implicit[dimensionChannelDef.field] = 'number';
}
}
}
return implicit;
}
/**
* Creates a parse node for implicit parsing from a model and updates ancestorParse.
*/
export function getImplicitFromSelection(model: Model) {
const implicit: Dict<string> = {};
if (isUnitModel(model) && model.component.selection) {
for (const name of keys(model.component.selection)) {
const selCmpt = model.component.selection[name];
for (const proj of selCmpt.project.items) {
if (!proj.channel && accessPathDepth(proj.field) > 1) {
implicit[proj.field] = 'flatten';
}
}
}
}
return implicit;
}
export class ParseNode extends DataFlowNode {
private _parse: Parse;
public clone() {
return new ParseNode(null, duplicate(this._parse));
}
constructor(parent: DataFlowNode, parse: Parse) {
super(parent);
this._parse = parse;
}
public hash() {
return `Parse ${hash(this._parse)}`;
}
/**
* Creates a parse node from a data.format.parse and updates ancestorParse.
*/
public static makeExplicit(parent: DataFlowNode, model: Model, ancestorParse: AncestorParse) {
// Custom parse
let explicit = {};
const data = model.data;
if (!isGenerator(data) && data?.format?.parse) {
explicit = data.format.parse;
}
return this.makeWithAncestors(parent, explicit, {}, ancestorParse);
}
/**
* Creates a parse node from "explicit" parse and "implicit" parse and updates ancestorParse.
*/
public static makeWithAncestors(
parent: DataFlowNode,
explicit: Parse,
implicit: Parse,
ancestorParse: AncestorParse
) {
// We should not parse what has already been parsed in a parent (explicitly or implicitly) or what has been derived (maked as "derived"). We also don't need to flatten a field that has already been parsed.
for (const field of keys(implicit)) {
const parsedAs = ancestorParse.getWithExplicit(field);
if (parsedAs.value !== undefined) {
// We always ignore derived fields even if they are implicitly defined because we expect users to create the right types.
if (
parsedAs.explicit ||
parsedAs.value === implicit[field] ||
parsedAs.value === 'derived' ||
implicit[field] === 'flatten'
) {
delete implicit[field];
} else {
log.warn(log.message.differentParse(field, implicit[field], parsedAs.value));
}
}
}
for (const field of keys(explicit)) {
const parsedAs = ancestorParse.get(field);
if (parsedAs !== undefined) {
// Don't parse a field again if it has been parsed with the same type already.
if (parsedAs === explicit[field]) {
delete explicit[field];
} else {
log.warn(log.message.differentParse(field, explicit[field], parsedAs));
}
}
}
const parse = new Split(explicit, implicit);
// add the format parse from this model so that children don't parse the same field again
ancestorParse.copyAll(parse);
// copy only non-null parses
const p: Dict<string> = {};
for (const key of keys(parse.combine())) {
const val = parse.get(key);
if (val !== null) {
p[key] = val;
}
}
if (keys(p).length === 0 || ancestorParse.parseNothing) {
return null;
}
return new ParseNode(parent, p);
}
public get parse() {
return this._parse;
}
public merge(other: ParseNode) {
this._parse = {...this._parse, ...other.parse};
other.remove();
}
/**
* Assemble an object for Vega's format.parse property.
*/
public assembleFormatParse() {
const formatParse: Dict<string> = {};
for (const field of keys(this._parse)) {
const p = this._parse[field];
if (accessPathDepth(field) === 1) {
formatParse[field] = p;
}
}
return formatParse;
}
// format parse depends and produces all fields in its parse
public producedFields() {
return new Set(keys(this._parse));
}
public dependentFields() {
return new Set(keys(this._parse));
}
public assembleTransforms(onlyNested = false): VgFormulaTransform[] {
return keys(this._parse)
.filter(field => (onlyNested ? accessPathDepth(field) > 1 : true))
.map(field => {
const expr = parseExpression(field, this._parse[field]);
if (!expr) {
return null;
}
const formula: VgFormulaTransform = {
type: 'formula',
expr,
as: removePathFromField(field) // Vega output is always flattened
};
return formula;
})
.filter(t => t !== null);
}
} | the_stack |
import { Convert } from "pvtsutils";
import { Browser } from "../src/helper";
import { browser, testCrypto } from "./utils";
context("AES", () => {
testCrypto(crypto, [
//#region AES-CBC
{
name: "AES-128-CBC",
actions: {
generateKey: [
{
algorithm: { name: "AES-CBC", length: 128 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
],
encrypt: [
{
algorithm: {
name: "AES-CBC",
iv: Convert.FromUtf8String("1234567890abcdef"),
} as AesCbcParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("d5df3ea1598defe7446420802baef28e"),
key: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: { name: "AES-CBC" },
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "wrong key size",
error: true,
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("12345678"),
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk" as KeyFormat,
data: {
kty: "oct",
alg: "A128CBC",
k: "MTIzNDU2Nzg5MGFiY2RlZg",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
],
wrapKey: [
{
key: {
format: "raw",
algorithm: "AES-CBC",
data: Convert.FromBase64Url("AQIDBAUGBwgJAAECAwQFBg"),
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
wKey: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
algorithm: {
name: "AES-CBC",
iv: Convert.FromUtf8String("1234567890abcdef"),
} as AesCbcParams,
wrappedKey: Convert.FromHex("c630c4bf95977db13f386cc950b18e98521d54c4fda0ba15b2884d2695638bd9"),
},
],
},
},
{
name: "AES-192-CBC",
actions: {
generateKey: [
{
algorithm: { name: "AES-CBC", length: 192 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
],
encrypt: [
{
algorithm: {
name: "AES-CBC",
iv: Convert.FromUtf8String("1234567890abcdef"),
} as AesCbcParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("67d0b3022149829bf009ad4aff19963a"),
key: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: { name: "AES-CBC" },
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A192CBC",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-256-CBC",
actions: {
generateKey: [
{
algorithm: { name: "AES-CBC", length: 256 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-CBC",
iv: Convert.FromUtf8String("1234567890abcdef"),
} as AesCbcParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("d827c1c6aee9f0f552c62f30ddee83af"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567809abcdef"),
algorithm: { name: "AES-CBC" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567890abcdef"),
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A256CBC",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWY",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CBC",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
//#endregion
//#region AES-CTR
{
// skip: browser.name === Browser.Edge,
name: "AES-128-CTR",
actions: {
generateKey: [
{
algorithm: { name: "AES-CTR", length: 128 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
encrypt: [
{
algorithm: {
name: "AES-CTR",
counter: Convert.FromUtf8String("1234567890abcdef"),
length: 128,
} as AesCtrParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("e1d561c49ce4eb2f448f8a00"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: { name: "AES-CTR" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A128CTR",
k: "MTIzNDU2Nzg5MGFiY2RlZg",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-192-CTR",
skip: browser.name === Browser.Chrome // Chrome doesn't implement this alg
|| browser.name === Browser.Edge,
actions: {
generateKey: [
{
algorithm: { name: "AES-CTR", length: 192 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-CTR",
counter: Convert.FromUtf8String("1234567890abcdef"),
length: 128,
} as AesCtrParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("55a00e2851f00aba53bbd02c"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: { name: "AES-CTR" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A192CTR",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-256-CTR",
skip: browser.name === Browser.Edge,
actions: {
generateKey: [
{
algorithm: { name: "AES-CTR", length: 256 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-CTR",
counter: Convert.FromUtf8String("1234567890abcdef"),
length: 128,
} as AesCtrParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("8208d011a20162c8af7a9ce5"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567809abcdef"),
algorithm: { name: "AES-CTR" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567890abcdef"),
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A256CTR",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWY",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-CTR",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
//#endregion
//#region AES-GCM
{
name: "AES-128-GCM",
actions: {
generateKey: [
{
algorithm: { name: "AES-GCM", length: 128 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
encrypt: [
{
algorithm: {
name: "AES-GCM",
iv: Convert.FromUtf8String("1234567890ab"),
} as AesGcmParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("68d645649ddf8152a253304d698185072f28cdcf7644ac6064bcb240"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: { name: "AES-GCM" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A128GCM",
k: "MTIzNDU2Nzg5MGFiY2RlZg",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-192-GCM",
actions: {
generateKey: [
{
algorithm: { name: "AES-GCM", length: 192 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-GCM",
iv: Convert.FromUtf8String("1234567890ab"),
} as AesGcmParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("d8eab579ed2418f41ca9c4567226f54cb391d3ca2cb6819dace35691"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: { name: "AES-GCM" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A192GCM",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-256-GCM",
actions: {
generateKey: [
{
algorithm: { name: "AES-GCM", length: 256 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-GCM",
iv: Convert.FromUtf8String("1234567890ab"),
} as AesGcmParams,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("f961f2aadbe689ffce86fcaf2619ab647950afcf19e55b71b857c79d"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567809abcdef"),
algorithm: { name: "AES-GCM" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567890abcdef"),
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A256GCM",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWY",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-GCM",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
//#endregion
//#region AES-KW
{
name: "AES-128-KW",
skip: typeof module !== "undefined", // skip for nodejs
actions: {
generateKey: [
{
algorithm: { name: "AES-KW", length: 128 } as AesKeyGenParams,
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"] as KeyUsage[],
},
],
wrapKey: [
{
skip: browser.name === Browser.Firefox, // Firefox: Operation is not supported on unwrapKey
key: {
format: "raw",
algorithm: "AES-KW",
data: Convert.FromHex("000102030405060708090A0B0C0D0E0F"),
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
wKey: {
format: "raw" as KeyFormat,
data: Convert.FromHex("00112233445566778899AABBCCDDEEFF"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
algorithm: {
name: "AES-KW",
},
wrappedKey: Convert.FromHex("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5"),
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A128KW",
k: "MTIzNDU2Nzg5MGFiY2RlZg",
ext: true,
key_ops: ["wrapKey", "unwrapKey"],
},
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-192-KW",
skip: typeof module !== "undefined" // skip for nodejs
|| browser.name === Browser.Chrome, // Chrome doesn't support AES-192-KW
actions: {
generateKey: [
{
algorithm: { name: "AES-KW", length: 192 } as AesKeyGenParams,
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"] as KeyUsage[],
},
],
wrapKey: [
{
skip: browser.name === Browser.Firefox, // Firefox: Operation is not supported on unwrapKey
key: {
format: "raw",
algorithm: "AES-KW",
data: Convert.FromHex("000102030405060708090A0B0C0D0E0F1011121314151617"),
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
wKey: {
format: "raw" as KeyFormat,
data: Convert.FromHex("00112233445566778899AABBCCDDEEFF0001020304050607"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
algorithm: {
name: "AES-KW",
},
wrappedKey: Convert.FromHex("031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2"),
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A192KW",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4",
ext: true,
key_ops: ["wrapKey", "unwrapKey"],
},
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-256-KW",
skip: typeof module !== "undefined", // skip for nodejs
actions: {
generateKey: [
{
algorithm: { name: "AES-KW", length: 256 } as AesKeyGenParams,
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
],
wrapKey: [
{
skip: browser.name === Browser.Firefox, // Firefox: Operation is not supported on unwrapKey
key: {
format: "raw",
algorithm: "AES-KW",
data: Convert.FromHex("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"),
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
wKey: {
format: "raw" as KeyFormat,
data: Convert.FromHex("00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
algorithm: {
name: "AES-KW",
},
wrappedKey: Convert.FromHex("28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21"),
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567890abcdef"),
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A256KW",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWY",
ext: true,
key_ops: ["wrapKey", "unwrapKey"],
},
algorithm: "AES-KW",
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
],
},
},
//#endregion
//#region AES-ECB
{
name: "AES-128-ECB",
actions: {
generateKey: [
{
algorithm: { name: "AES-ECB", length: 128 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
],
encrypt: [
{
algorithm: {
name: "AES-ECB",
} as Algorithm,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("c6ec2f91a9f48e10062ae41e86cb299f"),
key: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: { name: "AES-ECB" },
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk" as KeyFormat,
data: {
kty: "oct",
alg: "A128ECB",
k: "MTIzNDU2Nzg5MGFiY2RlZg",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
],
wrapKey: [
{
key: {
format: "raw",
algorithm: "AES-ECB",
data: Convert.FromBase64Url("AQIDBAUGBwgJAAECAwQFBg"),
extractable: true,
keyUsages: ["wrapKey", "unwrapKey"],
},
wKey: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef"),
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
algorithm: {
name: "AES-ECB",
} as Algorithm,
wrappedKey: Convert.FromHex("039ec14b350bd92efd02dac2c01cdee6ea9953cfbdc067f20f5f47bb4459da79"),
},
],
},
},
{
name: "AES-192-ECB",
actions: {
generateKey: [
{
algorithm: { name: "AES-ECB", length: 192 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
],
encrypt: [
{
algorithm: {
name: "AES-ECB",
} as Algorithm,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("8c9f297827ad6aaa9e7501e79fb45ca5"),
key: {
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: { name: "AES-ECB" },
extractable: true,
keyUsages: ["encrypt", "decrypt"] as KeyUsage[],
},
},
],
import: [
{
name: "raw",
format: "raw" as KeyFormat,
data: Convert.FromUtf8String("1234567890abcdef12345678"),
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] as KeyUsage[],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A192ECB",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
{
name: "AES-256-ECB",
actions: {
generateKey: [
{
algorithm: { name: "AES-ECB", length: 256 } as AesKeyGenParams,
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
],
encrypt: [
{
algorithm: {
name: "AES-ECB",
} as Algorithm,
data: Convert.FromUtf8String("test message"),
encData: Convert.FromHex("84ccef71a364b112eb2b3b8b99587a95"),
key: {
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567809abcdef"),
algorithm: { name: "AES-ECB" },
extractable: true,
keyUsages: ["encrypt", "decrypt"],
},
},
],
import: [
{
name: "raw",
format: "raw",
data: Convert.FromUtf8String("1234567890abcdef1234567890abcdef"),
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
{
name: "jwk",
format: "jwk",
data: {
kty: "oct",
alg: "A256ECB",
k: "MTIzNDU2Nzg5MGFiY2RlZjEyMzQ1Njc4OTBhYmNkZWY",
ext: true,
key_ops: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
algorithm: "AES-ECB",
extractable: true,
keyUsages: ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
},
],
},
},
//#endregion
]);
}); | the_stack |
import {
getProjectFileFromTree,
isProjectContentFile,
ProjectContentsTree,
ProjectContentTreeRoot,
walkContentsTreeAsync,
zipContentsTree,
zipContentsTreeAsync,
} from '../../components/assets'
import { EditorDispatch } from '../../components/editor/action-types'
import {
deleteFile,
selectFromFileAndPosition,
markVSCodeBridgeReady,
updateFromCodeEditor,
sendCodeEditorInitialisation,
updateConfigFromVSCode,
sendLinterRequestMessage,
hideVSCodeLoadingScreen,
setIndexedDBFailed,
} from '../../components/editor/actions/action-creators'
import {
getSavedCodeFromTextFile,
getUnsavedCodeFromTextFile,
isDirectory,
} from '../model/project-file-utils'
import {
initializeFS,
writeFileAsUTF8,
ensureDirectoryExists,
watch,
stopWatchingAll,
stopPollingMailbox,
readFileAsUTF8,
clearBothMailboxes,
initMailbox,
openFileMessage,
sendMessage,
UtopiaInbox,
FromVSCodeMessage,
deletePath,
DecorationRange,
updateDecorationsMessage,
appendToPath,
stat,
BoundsInFile,
selectedElementChanged,
parseFromVSCodeMessage,
FSUser,
decorationRange,
DecorationRangeType,
boundsInFile,
getUtopiaVSCodeConfig,
setFollowSelectionConfig,
UpdateDecorationsMessage,
SelectedElementChanged,
} from 'utopia-vscode-common'
import { isTextFile, ProjectFile, ElementPath, TextFile } from '../shared/project-file-types'
import { isBrowserEnvironment } from '../shared/utils'
import {
EditorState,
getHighlightBoundsForElementPath,
getOpenTextFileKey,
} from '../../components/editor/store/editor-state'
import { ProjectFileChange } from '../../components/editor/store/vscode-changes'
const Scheme = 'utopia'
const RootDir = `/${Scheme}`
const UtopiaFSUser: FSUser = 'UTOPIA'
function toFSPath(projectPath: string): string {
const fsPath = appendToPath(RootDir, projectPath)
return fsPath
}
function fromFSPath(fsPath: string): string {
const prefix = RootDir
const prefixIndex = fsPath.indexOf(prefix)
if (prefixIndex === 0) {
const projectPath = fsPath.slice(prefix.length)
return projectPath
} else {
throw new Error(`Invalid FS path: ${fsPath}`)
}
}
async function writeProjectFile(projectPath: string, file: ProjectFile): Promise<void> {
switch (file.type) {
case 'DIRECTORY': {
return ensureDirectoryExists(toFSPath(projectPath))
}
case 'TEXT_FILE': {
const savedContent = getSavedCodeFromTextFile(file)
const unsavedContent = getUnsavedCodeFromTextFile(file)
const filePath = toFSPath(projectPath)
return writeFileAsUTF8(filePath, savedContent, unsavedContent)
}
case 'ASSET_FILE':
return Promise.resolve()
case 'IMAGE_FILE':
return Promise.resolve()
}
}
async function textFileDiffers(projectPath: string, file: TextFile): Promise<boolean> {
const savedContent = getSavedCodeFromTextFile(file)
const unsavedContent = getUnsavedCodeFromTextFile(file)
const filePath = toFSPath(projectPath)
const alreadyExistingFile = await readFileAsUTF8(filePath).catch((_) => null)
return (
alreadyExistingFile == null ||
alreadyExistingFile.content !== savedContent ||
alreadyExistingFile.unsavedContent !== unsavedContent
)
}
async function writeProjectContents(projectContents: ProjectContentTreeRoot): Promise<void> {
await walkContentsTreeAsync(projectContents, async (fullPath, file) => {
// Avoid pushing a file to the file system if the content hasn't changed.
if ((isTextFile(file) && (await textFileDiffers(fullPath, file))) || isDirectory(file)) {
return writeProjectFile(fullPath, file)
} else {
return Promise.resolve()
}
})
}
function watchForChanges(dispatch: EditorDispatch): void {
function onCreated(fsPath: string): void {
stat(fsPath).then((fsStat) => {
if (fsStat.type === 'FILE' && fsStat.sourceOfLastChange !== UtopiaFSUser) {
readFileAsUTF8(fsPath).then((fileContent) => {
const path = fromFSPath(fsPath)
const updateAction = updateFromCodeEditor(
path,
fileContent.content,
fileContent.unsavedContent,
)
const requestLintAction = sendLinterRequestMessage(
path,
fileContent.unsavedContent ?? fileContent.content,
)
dispatch([updateAction, requestLintAction], 'everyone')
})
}
})
}
function onModified(fsPath: string, modifiedBySelf: boolean): void {
if (!modifiedBySelf) {
onCreated(fsPath)
}
}
function onDeleted(fsPath: string): void {
const projectPath = fromFSPath(fsPath)
const action = deleteFile(projectPath)
dispatch([action], 'everyone')
}
function onIndexedDBFailure(): void {
dispatch([setIndexedDBFailed(true)], 'everyone')
}
watch(toFSPath('/'), true, onCreated, onModified, onDeleted, onIndexedDBFailure)
}
let currentInit: Promise<void> = Promise.resolve()
export async function initVSCodeBridge(
projectID: string,
projectContents: ProjectContentTreeRoot,
dispatch: EditorDispatch,
openFilePath: string | null,
): Promise<void> {
let loadingScreenHidden = false
async function innerInit(): Promise<void> {
dispatch([markVSCodeBridgeReady(false)], 'everyone')
if (isBrowserEnvironment) {
stopWatchingAll()
stopPollingMailbox()
await initializeFS(projectID, UtopiaFSUser)
await clearBothMailboxes()
await writeProjectContents(projectContents)
await initMailbox(UtopiaInbox, parseFromVSCodeMessage, (message: FromVSCodeMessage) => {
switch (message.type) {
case 'SEND_INITIAL_DATA':
dispatch([sendCodeEditorInitialisation()], 'everyone')
break
case 'EDITOR_CURSOR_POSITION_CHANGED':
dispatch(
[selectFromFileAndPosition(message.filePath, message.line, message.column)],
'everyone',
)
break
case 'UTOPIA_VSCODE_CONFIG_VALUES':
dispatch([updateConfigFromVSCode(message.config)], 'everyone')
break
case 'FILE_OPENED':
if (!loadingScreenHidden) {
loadingScreenHidden = true
dispatch([hideVSCodeLoadingScreen()], 'everyone')
}
break
default:
const _exhaustiveCheck: never = message
throw new Error(`Unhandled message type${JSON.stringify(message)}`)
}
})
await sendGetUtopiaVSCodeConfigMessage()
watchForChanges(dispatch)
if (openFilePath != null) {
await sendOpenFileMessage(openFilePath)
} else {
loadingScreenHidden = true
dispatch([hideVSCodeLoadingScreen()], 'everyone')
}
}
dispatch([markVSCodeBridgeReady(true)], 'everyone')
}
// Prevent multiple initialisations from driving over each other.
currentInit = currentInit.then(innerInit)
}
export async function sendOpenFileMessage(filePath: string): Promise<void> {
return sendMessage(openFileMessage(filePath))
}
export async function sendUpdateDecorationsMessage(
decorations: Array<DecorationRange>,
): Promise<void> {
return sendMessage(updateDecorationsMessage(decorations))
}
export async function sendSelectedElementChangedMessage(
boundsForFile: BoundsInFile,
): Promise<void> {
return sendMessage(selectedElementChanged(boundsForFile))
}
export async function sendSetFollowSelectionEnabledMessage(enabled: boolean): Promise<void> {
return sendMessage(setFollowSelectionConfig(enabled))
}
export async function sendGetUtopiaVSCodeConfigMessage(): Promise<void> {
return sendMessage(getUtopiaVSCodeConfig())
}
export async function applyProjectChanges(changes: Array<ProjectFileChange>): Promise<void> {
for (const change of changes) {
switch (change.type) {
case 'DELETE_PATH':
// eslint-disable-next-line no-await-in-loop
await deletePath(toFSPath(change.fullPath), change.recursive)
break
case 'WRITE_PROJECT_FILE':
// eslint-disable-next-line no-await-in-loop
await writeProjectFile(change.fullPath, change.projectFile)
break
case 'ENSURE_DIRECTORY_EXISTS':
// eslint-disable-next-line no-await-in-loop
await ensureDirectoryExists(toFSPath(change.fullPath))
break
default:
const _exhaustiveCheck: never = change
throw new Error(`Unhandled message type: ${JSON.stringify(change)}`)
}
}
}
export function getCodeEditorDecorations(editorState: EditorState): UpdateDecorationsMessage {
let decorations: Array<DecorationRange> = []
function addRange(rangeType: DecorationRangeType, path: ElementPath): void {
const highlightBounds = getHighlightBoundsForElementPath(path, editorState)
if (highlightBounds != null) {
decorations.push(
decorationRange(
rangeType,
highlightBounds.filePath,
highlightBounds.startLine,
highlightBounds.startCol,
highlightBounds.endLine,
highlightBounds.endCol,
),
)
}
}
editorState.selectedViews.forEach((selectedView) => {
addRange('selection', selectedView)
})
editorState.highlightedViews.forEach((highlightedView) => {
addRange('highlight', highlightedView)
})
return updateDecorationsMessage(decorations)
}
export async function sendCodeEditorDecorations(editorState: EditorState): Promise<void> {
const decorationsMessage = getCodeEditorDecorations(editorState)
await sendMessage(decorationsMessage)
}
export function getSelectedElementChangedMessage(
newEditorState: EditorState,
): SelectedElementChanged | null {
const selectedView = newEditorState.selectedViews[0]
if (selectedView == null) {
return null
}
const highlightBounds = getHighlightBoundsForElementPath(selectedView, newEditorState)
if (highlightBounds == null) {
return null
} else {
return selectedElementChanged(
boundsInFile(
highlightBounds.filePath,
highlightBounds.startLine,
highlightBounds.startCol,
highlightBounds.endLine,
highlightBounds.endCol,
),
)
}
}
export async function sendSelectedElement(newEditorState: EditorState): Promise<void> {
const selectedElementChangedMessage = getSelectedElementChangedMessage(newEditorState)
if (selectedElementChangedMessage == null) {
return Promise.resolve()
} else {
await sendMessage(selectedElementChangedMessage)
}
} | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { GistsAPIClientInterface } from './gists-api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, GistsAPIClient } from './gists-api-client.service';
import { DefaultHttpOptions, HttpOptions } from '../../types';
import * as models from '../../models';
import * as guards from '../../guards';
@Injectable()
export class GuardedGistsAPIClient extends GistsAPIClient implements GistsAPIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* List the authenticated user's gists or if called anonymously, this will
* return all public gists.
*
* Response generated for [ 200 ] HTTP response code.
*/
getGists(
args?: GistsAPIClientInterface['getGistsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gists>;
getGists(
args?: GistsAPIClientInterface['getGistsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gists>>;
getGists(
args?: GistsAPIClientInterface['getGistsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gists>>;
getGists(
args: GistsAPIClientInterface['getGistsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gists | HttpResponse<models.Gists> | HttpEvent<models.Gists>> {
return super.getGists(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGists(res) || console.error(`TypeGuard for response 'models.Gists' caught inconsistency.`, res)));
}
/**
* Create a gist.
* Response generated for [ 201 ] HTTP response code.
*/
postGists(
args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gist>;
postGists(
args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gist>>;
postGists(
args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gist>>;
postGists(
args: Exclude<GistsAPIClientInterface['postGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gist | HttpResponse<models.Gist> | HttpEvent<models.Gist>> {
return super.postGists(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGist(res) || console.error(`TypeGuard for response 'models.Gist' caught inconsistency.`, res)));
}
/**
* List all public gists.
* Response generated for [ 200 ] HTTP response code.
*/
getGistsPublic(
args?: GistsAPIClientInterface['getGistsPublicParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gists>;
getGistsPublic(
args?: GistsAPIClientInterface['getGistsPublicParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gists>>;
getGistsPublic(
args?: GistsAPIClientInterface['getGistsPublicParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gists>>;
getGistsPublic(
args: GistsAPIClientInterface['getGistsPublicParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gists | HttpResponse<models.Gists> | HttpEvent<models.Gists>> {
return super.getGistsPublic(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGists(res) || console.error(`TypeGuard for response 'models.Gists' caught inconsistency.`, res)));
}
/**
* List the authenticated user's starred gists.
* Response generated for [ 200 ] HTTP response code.
*/
getGistsStarred(
args?: GistsAPIClientInterface['getGistsStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gists>;
getGistsStarred(
args?: GistsAPIClientInterface['getGistsStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gists>>;
getGistsStarred(
args?: GistsAPIClientInterface['getGistsStarredParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gists>>;
getGistsStarred(
args: GistsAPIClientInterface['getGistsStarredParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gists | HttpResponse<models.Gists> | HttpEvent<models.Gists>> {
return super.getGistsStarred(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGists(res) || console.error(`TypeGuard for response 'models.Gists' caught inconsistency.`, res)));
}
/**
* Delete a gist.
* Response generated for [ 204 ] HTTP response code.
*/
deleteGistsId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteGistsId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteGistsId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteGistsId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteGistsId(args, requestHttpOptions, observe);
}
/**
* Get a single gist.
* Response generated for [ 200 ] HTTP response code.
*/
getGistsId(
args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gist>;
getGistsId(
args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gist>>;
getGistsId(
args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gist>>;
getGistsId(
args: Exclude<GistsAPIClientInterface['getGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gist | HttpResponse<models.Gist> | HttpEvent<models.Gist>> {
return super.getGistsId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGist(res) || console.error(`TypeGuard for response 'models.Gist' caught inconsistency.`, res)));
}
/**
* Edit a gist.
* Response generated for [ 200 ] HTTP response code.
*/
patchGistsId(
args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gist>;
patchGistsId(
args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gist>>;
patchGistsId(
args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gist>>;
patchGistsId(
args: Exclude<GistsAPIClientInterface['patchGistsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gist | HttpResponse<models.Gist> | HttpEvent<models.Gist>> {
return super.patchGistsId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGist(res) || console.error(`TypeGuard for response 'models.Gist' caught inconsistency.`, res)));
}
/**
* List comments on a gist.
* Response generated for [ 200 ] HTTP response code.
*/
getGistsIdComments(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Comments>;
getGistsIdComments(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Comments>>;
getGistsIdComments(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Comments>>;
getGistsIdComments(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Comments | HttpResponse<models.Comments> | HttpEvent<models.Comments>> {
return super.getGistsIdComments(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isComments(res) || console.error(`TypeGuard for response 'models.Comments' caught inconsistency.`, res)));
}
/**
* Create a commen
* Response generated for [ 201 ] HTTP response code.
*/
postGistsIdComments(
args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Comment>;
postGistsIdComments(
args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Comment>>;
postGistsIdComments(
args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Comment>>;
postGistsIdComments(
args: Exclude<GistsAPIClientInterface['postGistsIdCommentsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Comment | HttpResponse<models.Comment> | HttpEvent<models.Comment>> {
return super.postGistsIdComments(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isComment(res) || console.error(`TypeGuard for response 'models.Comment' caught inconsistency.`, res)));
}
/**
* Delete a comment.
* Response generated for [ 204 ] HTTP response code.
*/
deleteGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['deleteGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteGistsIdCommentsCommentId(args, requestHttpOptions, observe);
}
/**
* Get a single comment.
* Response generated for [ 200 ] HTTP response code.
*/
getGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Comment>;
getGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Comment>>;
getGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Comment>>;
getGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['getGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Comment | HttpResponse<models.Comment> | HttpEvent<models.Comment>> {
return super.getGistsIdCommentsCommentId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isComment(res) || console.error(`TypeGuard for response 'models.Comment' caught inconsistency.`, res)));
}
/**
* Edit a comment.
* Response generated for [ 200 ] HTTP response code.
*/
patchGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Comment>;
patchGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Comment>>;
patchGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Comment>>;
patchGistsIdCommentsCommentId(
args: Exclude<GistsAPIClientInterface['patchGistsIdCommentsCommentIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Comment | HttpResponse<models.Comment> | HttpEvent<models.Comment>> {
return super.patchGistsIdCommentsCommentId(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isComment(res) || console.error(`TypeGuard for response 'models.Comment' caught inconsistency.`, res)));
}
/**
* Fork a gist.
* Response generated for [ 204 ] HTTP response code.
*/
postGistsIdForks(
args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
postGistsIdForks(
args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
postGistsIdForks(
args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
postGistsIdForks(
args: Exclude<GistsAPIClientInterface['postGistsIdForksParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.postGistsIdForks(args, requestHttpOptions, observe);
}
/**
* Unstar a gist.
* Response generated for [ 204 ] HTTP response code.
*/
deleteGistsIdStar(
args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteGistsIdStar(
args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteGistsIdStar(
args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteGistsIdStar(
args: Exclude<GistsAPIClientInterface['deleteGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteGistsIdStar(args, requestHttpOptions, observe);
}
/**
* Check if a gist is starred.
* Response generated for [ 204 ] HTTP response code.
*/
getGistsIdStar(
args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getGistsIdStar(
args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getGistsIdStar(
args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getGistsIdStar(
args: Exclude<GistsAPIClientInterface['getGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getGistsIdStar(args, requestHttpOptions, observe);
}
/**
* Star a gist.
* Response generated for [ 204 ] HTTP response code.
*/
putGistsIdStar(
args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
putGistsIdStar(
args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
putGistsIdStar(
args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
putGistsIdStar(
args: Exclude<GistsAPIClientInterface['putGistsIdStarParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.putGistsIdStar(args, requestHttpOptions, observe);
}
} | the_stack |
import * as fileType from 'file-type'
import * as fs from 'fs-extra'
import { inject, injectable, LazyServiceIdentifer } from 'inversify'
import * as jsonwebtoken from 'jsonwebtoken'
import * as Git from 'nodegit'
import * as os from 'os'
import * as path from 'path'
import * as agent from 'superagent'
import * as URL from 'url'
import * as uuid from 'uuid/v4'
import { App } from '../app'
import { Cache, ICache, ICacheFactory } from '../cache'
import { Config } from '../config'
import { sanitize } from '../utility/rdnn'
import * as type from './type'
export const github = Symbol('GitHub')
export type IGitHubFactory = (url: string) => GitHub
@injectable()
export class GitHub implements type.ICodeRepository, type.IPackageRepository, type.ILogRepository {
/**
* Folder to use as scratch space for cloning repos
*
* @var {string}
*/
public tmpFolder = path.resolve(os.tmpdir(), 'houston')
/**
* The human readable name of the service.
*
* @var {String}
*/
public serviceName = 'GitHub'
/**
* The host for the repo. This is almost always "github.com" but can change if
* you have an enterprise instance.
*
* @var {string}
*/
public host = 'github.com'
/**
* The GitHub username or organization.
*
* @var {string}
*/
public username: string
/**
* The GitHub user's repository name
*
* @var {string}
*/
public repository: string
/**
* The http username
*
* @var {string|null}
*/
public authUsername?: string
/**
* The http password authentication string.
* NOTE: When the `authUsername` is 'installation', this will be an
* installation id. Not an accurate http password.
*
* @var {string|null}
*/
public authPassword?: string
/**
* The reference to branch or tag.
*
* @var {string}
*/
public reference = 'refs/heads/master'
/**
* The application configuration
*
* @var {Config}
*/
protected config: Config
/**
* A cache store for GitHub authentication tokens
*
* @var {Cache}
*/
protected cache: ICache
/**
* Tries to get the file mime type by reading the first chunk of a file.
* Required by GitHub API
*
* Code taken from examples of:
* https://github.com/sindresorhus/file-type
* https://github.com/sindresorhus/read-chunk/blob/master/index.js
*
* @async
* @param {String} p Full file path
* @return {String} The file mime type
*/
protected static async getFileType (p: string): Promise<string> {
const buffer = await new Promise((resolve, reject) => {
fs.open(p, 'r', (openErr, fd) => {
if (openErr != null) {
return reject(openErr)
}
fs.read(fd, Buffer.alloc(4100), 0, 4100, 0, (readErr, bytesRead, buff) => {
fs.close(fd)
if (readErr != null) {
return reject(readErr)
}
if (bytesRead < 4100) {
return resolve(buff.slice(0, bytesRead))
} else {
return resolve(buff)
}
})
})
})
return fileType(buffer).mime
}
/**
* Creates a new GitHub Repository
*
* @param {App} app - The application IOC instance
*/
constructor (@inject(new LazyServiceIdentifer(() => App)) app: App) {
this.config = app.get(Config)
this.cache = app.get<ICacheFactory>(Cache)('lib/service/github')
}
/**
* Returns the default RDNN value for this repository
*
* @return {string}
*/
public get rdnn () {
return sanitize(`com.github.${this.username}.${this.repository}`)
}
/**
* Returns the Git URL for the repository
*
* @return {string}
*/
public get url (): string {
let auth = null
if (this.authUsername !== 'installation') {
if (this.authUsername != null || this.authPassword != null) {
auth = `${this.authUsername}:${this.authPassword}`
}
}
return URL.format({
auth,
host: this.host,
pathname: `/${this.username}/${this.repository}.git`,
protocol: 'https'
})
}
/**
* Sets the Git URL for the repository
* NOTE: Auth code is case sensitive, so we can't lowercase the whole url
*
* @return {string}
*/
public set url (p: string) {
if (p.indexOf('github') === -1) {
throw new Error('Given URL is not a GitHub repository')
}
// NOTE: This is A+ 10/10 string logic. Will not break ever.
const httpPath = (p.startsWith('git@') ? p.replace('git@', 'https://') : p)
.replace('://github.com:', '://github.com/')
.replace(/\.git$/, '')
const url = new URL.URL(httpPath)
const [host, username, repository] = url.pathname.split('/')
this.host = url.host
this.username = username
this.repository = repository
this.authUsername = (url.username !== '') ? url.username : null
this.authPassword = (url.password !== '') ? url.password : null
// GitHub never sends auth codes as the username due to http security
// Headers. This probably means it was parsed weird so we should fix it.
if (this.authUsername != null && this.authPassword == null) {
this.authPassword = this.authUsername
this.authUsername = 'x-access-token'
}
}
/**
* Clones the repository to a folder
*
* @async
* @param {string} p - The path to clone to
* @param {string} [reference] - The branch to clone
* @return {void}
*/
public async clone (p: string, reference = this.reference): Promise<void> {
const repo = await Git.Clone(this.url, p)
const ref = await repo.getReference(reference)
const commit = await ref.peel(Git.Object.TYPE.COMMIT)
const branch = await repo.createBranch('houston', commit, true)
await repo.checkoutBranch(branch, {})
await this.recursiveClone(p)
await fs.remove(path.resolve(p, '.git'))
}
/**
* Returns a list of references this repository has
* TODO: Try to figure out a more optimized way
*
* @async
* @return {string[]}
*/
public async references (): Promise<string[]> {
const p = path.resolve(this.tmpFolder, uuid())
const repo = await Git.Clone(this.url, p)
const branches = await repo.getReferenceNames(Git.Reference.TYPE.LISTALL)
await fs.remove(p)
return branches
}
/**
* Uploads an asset to a GitHub release.
*
* @async
* @param {IPackage} pkg Package to upload
* @param {IStage} stage
* @param {string} [reference]
* @return {IPackage}
*/
public async uploadPackage (pkg: type.IPackage, stage: type.IStage, reference?: string) {
if (pkg.githubId != null) {
return pkg
}
return pkg
const auth = await this.getAuthorization()
const url = `${this.username}/${this.repository}/releases/tags/${reference}`
const { body } = await agent
.get(`https://api.github.com/repos/${url}`)
.set('accept', 'application/vnd.github.v3+json')
.set('user-agent', 'elementary-houston')
.set('authorization', auth)
if (body.upload_url == null) {
throw new Error('No Upload URL for GitHub release')
}
// TODO: Should we remove existing assets that would conflict?
const mime = await GitHub.getFileType(pkg.path)
const stat = await fs.stat(pkg.path)
const file = await fs.createReadStream(pkg.path)
const res = await new Promise((resolve, reject) => {
let data = ''
const req = agent
.post(body.upload_url.replace('{?name,label}', ''))
.set('content-type', mime)
.set('content-length', stat.size)
.set('user-agent', 'elementary-houston')
.set('authorization', auth)
.query({ name: pkg.name })
.query((pkg.description != null) ? { label: pkg.description } : {})
.parse((response, fn) => {
response.on('data', (chunk) => { data += chunk })
response.on('end', fn)
})
.on('error', reject)
.on('end', (err, response) => {
if (err != null) {
return reject(err)
}
try {
return resolve(JSON.parse(data))
} catch (err) {
return reject(err)
}
})
file
.pipe(req)
.on('error', reject)
.on('close', () => resolve(data))
})
return { ...pkg }
}
/**
* Uploads a log to GitHub as an issue with the 'AppCenter' label
*
* @async
* @param {ILog} log
* @param {IStage} stage
* @param {string} [reference]
* @return {ILog}
*/
public async uploadLog (log: type.ILog, stage: type.IStage, reference?: string): Promise<type.ILog> {
if (log.githubId != null) {
return
}
const auth = await this.getAuthorization()
const hasLabel = await agent
.get(`https://api.github.com/repos/${this.username}/${this.repository}/labels/AppCenter`)
.set('user-agent', 'elementary-houston')
.set('authorization', auth)
.then(() => true)
.catch(() => false)
if (!hasLabel) {
await agent
.post(`https://api.github.com/repos/${this.username}/${this.repository}/labels`)
.set('user-agent', 'elementary-houston')
.set('authorization', auth)
.send({
color: '4c158a',
description: 'Issues related to releasing on AppCenter',
name: 'AppCenter'
})
}
const { body } = await agent
.post(`https://api.github.com/repos/${this.username}/${this.repository}/issues`)
.set('user-agent', 'elementary-houston')
.set('authorization', auth)
.send({
body: log.body,
labels: ['AppCenter'],
title: log.title
})
return { ...log, githubId: body.id }
}
/**
* Returns the http Authorization header value
* NOTE: This should be private, but is public for easier testing.
*
* @async
* @return {string}
*/
public async getAuthorization (): Promise<string> {
if (this.authUsername !== 'installation') {
return `Bearer ${this.authPassword}`
} else {
const cachedToken = await this.cache.get(this.authPassword)
if (cachedToken == null) {
const token = await this.generateToken(Number(this.authPassword))
await this.cache.set(this.authPassword, token)
return `token ${token}`
} else {
return `token ${cachedToken}`
}
}
}
/**
* Generates a json web token used for making app requests to GitHub.
*
* @async
* @return {string}
*/
protected async generateJwt (): Promise<string> {
const keyPath = this.config.get('service.github.key')
const key = await fs.readFile(keyPath, 'utf-8')
const payload = {
iat: Math.floor(Date.now() / 1000),
iss: this.config.get('service.github.app')
}
const options = {
algorithm: 'RS256',
expiresIn: '1m'
}
return new Promise<string>((resolve, reject) => {
jsonwebtoken.sign(payload, key, options, (err, token) => {
if (err != null) {
return reject(err)
} else {
return resolve(token)
}
})
})
}
/**
* Uses a json web token to generate an API usable authentication token for
* GitHub.
*
* @async
* @param {number} installation The GitHub app installation number
* @return {string}
*/
protected async generateToken (installation: number): Promise<string> {
const jwt = await this.generateJwt()
return agent
.post(`https://api.github.com/app/installations/${installation}/access_tokens`)
.set('accept', 'application/vnd.github.machine-man-preview+json')
.set('user-agent', 'elementary-houston')
.set('authorization', `Bearer ${jwt}`)
.then((res) => res.body.token)
}
/**
* Clones all of the Git submodules for a given repo path
*
* @async
* @param {String} clonePath - Path of the repository
* @return {void}
*/
protected async recursiveClone (clonePath) {
const repo = await Git.Repository.open(clonePath)
await Git.Submodule.foreach(repo, async (submodule) => {
await submodule.update(1, new Git.SubmoduleUpdateOptions())
await this.recursiveClone(path.join(clonePath, submodule.path()))
})
}
} | the_stack |
import TransBtn from './TransBtn';
import PropTypes from '../_util/vue-types';
import KeyCode from '../_util/KeyCode';
import classNames from '../_util/classNames';
import pickAttrs from '../_util/pickAttrs';
import { isValidElement } from '../_util/props-util';
import createRef from '../_util/createRef';
import type { PropType } from 'vue';
import { computed, defineComponent, nextTick, reactive, watch } from 'vue';
import List from '../vc-virtual-list/List';
import type {
OptionsType as SelectOptionsType,
OptionData,
RenderNode,
OnActiveValue,
} from './interface';
import type { RawValueType, FlattenOptionsType } from './interface/generator';
import useMemo from '../_util/hooks/useMemo';
export interface RefOptionListProps {
onKeydown: (e?: KeyboardEvent) => void;
onKeyup: (e?: KeyboardEvent) => void;
scrollTo?: (index: number) => void;
}
import type { EventHandler } from '../_util/EventInterface';
export interface OptionListProps<OptionType extends object> {
prefixCls: string;
id: string;
options: OptionType[];
flattenOptions: FlattenOptionsType<OptionType>;
height: number;
itemHeight: number;
values: Set<RawValueType>;
multiple: boolean;
open: boolean;
defaultActiveFirstOption?: boolean;
notFoundContent?: any;
menuItemSelectedIcon?: RenderNode;
childrenAsData: boolean;
searchValue: string;
virtual: boolean;
onSelect: (value: RawValueType, option: { selected: boolean }) => void;
onToggleOpen: (open?: boolean) => void;
/** Tell Select that some value is now active to make accessibility work */
onActiveValue: OnActiveValue;
onScroll: EventHandler;
/** Tell Select that mouse enter the popup to force re-render */
onMouseenter?: EventHandler;
}
const OptionListProps = {
prefixCls: PropTypes.string,
id: PropTypes.string,
options: PropTypes.array,
flattenOptions: PropTypes.array,
height: PropTypes.number,
itemHeight: PropTypes.number,
values: PropTypes.any,
multiple: PropTypes.looseBool,
open: PropTypes.looseBool,
defaultActiveFirstOption: PropTypes.looseBool,
notFoundContent: PropTypes.any,
menuItemSelectedIcon: PropTypes.any,
childrenAsData: PropTypes.looseBool,
searchValue: PropTypes.string,
virtual: PropTypes.looseBool,
onSelect: PropTypes.func,
onToggleOpen: { type: Function as PropType<(open?: boolean) => void> },
/** Tell Select that some value is now active to make accessibility work */
onActiveValue: PropTypes.func,
onScroll: PropTypes.func,
/** Tell Select that mouse enter the popup to force re-render */
onMouseenter: PropTypes.func,
};
/**
* Using virtual list of option display.
* Will fallback to dom if use customize render.
*/
const OptionList = defineComponent<OptionListProps<SelectOptionsType[number]>, { state?: any }>({
name: 'OptionList',
inheritAttrs: false,
slots: ['option'],
setup(props) {
const itemPrefixCls = computed(() => `${props.prefixCls}-item`);
const memoFlattenOptions = useMemo(
() => props.flattenOptions,
[() => props.open, () => props.flattenOptions],
next => next[0],
);
// =========================== List ===========================
const listRef = createRef();
const onListMouseDown: EventHandler = event => {
event.preventDefault();
};
const scrollIntoView = (index: number) => {
if (listRef.current) {
listRef.current.scrollTo({ index });
}
};
// ========================== Active ==========================
const getEnabledActiveIndex = (index: number, offset = 1) => {
const len = memoFlattenOptions.value.length;
for (let i = 0; i < len; i += 1) {
const current = (index + i * offset + len) % len;
const { group, data } = memoFlattenOptions.value[current];
if (!group && !(data as OptionData).disabled) {
return current;
}
}
return -1;
};
const state = reactive({
activeIndex: getEnabledActiveIndex(0),
});
const setActive = (index: number, fromKeyboard = false) => {
state.activeIndex = index;
const info = { source: fromKeyboard ? ('keyboard' as const) : ('mouse' as const) };
// Trigger active event
const flattenItem = memoFlattenOptions.value[index];
if (!flattenItem) {
props.onActiveValue(null, -1, info);
return;
}
props.onActiveValue(flattenItem.data.value, index, info);
};
// Auto active first item when list length or searchValue changed
watch(
[() => memoFlattenOptions.value.length, () => props.searchValue],
() => {
setActive(props.defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1);
},
{ immediate: true },
);
// Auto scroll to item position in single mode
watch(
() => props.open,
() => {
if (!props.multiple && props.open && props.values.size === 1) {
const value = Array.from(props.values)[0];
const index = memoFlattenOptions.value.findIndex(({ data }) => data.value === value);
setActive(index);
nextTick(() => {
scrollIntoView(index);
});
}
// Force trigger scrollbar visible when open
if (props.open) {
nextTick(() => {
listRef.current?.scrollTo(undefined);
});
}
},
{ immediate: true, flush: 'post' },
);
// ========================== Values ==========================
const onSelectValue = (value?: RawValueType) => {
if (value !== undefined) {
props.onSelect(value, { selected: !props.values.has(value) });
}
// Single mode should always close by select
if (!props.multiple) {
props.onToggleOpen(false);
}
};
function renderItem(index: number) {
const item = memoFlattenOptions.value[index];
if (!item) return null;
const itemData = (item.data || {}) as OptionData;
const { value, label, children } = itemData;
const attrs = pickAttrs(itemData, true);
const mergedLabel = props.childrenAsData ? children : label;
return item ? (
<div
aria-label={typeof mergedLabel === 'string' ? mergedLabel : undefined}
{...attrs}
key={index}
role="option"
id={`${props.id}_list_${index}`}
aria-selected={props.values.has(value)}
>
{value}
</div>
) : null;
}
return {
memoFlattenOptions,
renderItem,
listRef,
state,
onListMouseDown,
itemPrefixCls,
setActive,
onSelectValue,
onKeydown: (event: KeyboardEvent) => {
const { which } = event;
switch (which) {
// >>> Arrow keys
case KeyCode.UP:
case KeyCode.DOWN: {
let offset = 0;
if (which === KeyCode.UP) {
offset = -1;
} else if (which === KeyCode.DOWN) {
offset = 1;
}
if (offset !== 0) {
const nextActiveIndex = getEnabledActiveIndex(state.activeIndex + offset, offset);
scrollIntoView(nextActiveIndex);
setActive(nextActiveIndex, true);
}
break;
}
// >>> Select
case KeyCode.ENTER: {
// value
const item = memoFlattenOptions.value[state.activeIndex];
if (item && !item.data.disabled) {
onSelectValue(item.data.value);
} else {
onSelectValue(undefined);
}
if (props.open) {
event.preventDefault();
}
break;
}
// >>> Close
case KeyCode.ESC: {
props.onToggleOpen(false);
if (props.open) {
event.stopPropagation();
}
}
}
},
onKeyup: () => {},
scrollTo: (index: number) => {
scrollIntoView(index);
},
};
},
render() {
const {
renderItem,
listRef,
onListMouseDown,
itemPrefixCls,
setActive,
onSelectValue,
memoFlattenOptions,
$slots,
} = this as any;
const {
id,
childrenAsData,
values,
height,
itemHeight,
menuItemSelectedIcon,
notFoundContent,
virtual,
onScroll,
onMouseenter,
} = this.$props;
const renderOption = $slots.option;
const { activeIndex } = this.state;
// ========================== Render ==========================
if (memoFlattenOptions.length === 0) {
return (
<div
role="listbox"
id={`${id}_list`}
class={`${itemPrefixCls}-empty`}
onMousedown={onListMouseDown}
>
{notFoundContent}
</div>
);
}
return (
<>
<div role="listbox" id={`${id}_list`} style={{ height: 0, width: 0, overflow: 'hidden' }}>
{renderItem(activeIndex - 1)}
{renderItem(activeIndex)}
{renderItem(activeIndex + 1)}
</div>
<List
itemKey="key"
ref={listRef}
data={memoFlattenOptions}
height={height}
itemHeight={itemHeight}
fullHeight={false}
onMousedown={onListMouseDown}
onScroll={onScroll}
virtual={virtual}
onMouseenter={onMouseenter}
children={({ group, groupOption, data }, itemIndex) => {
const { label, key } = data;
// Group
if (group) {
return (
<div class={classNames(itemPrefixCls, `${itemPrefixCls}-group`)}>
{renderOption ? renderOption(data) : label !== undefined ? label : key}
</div>
);
}
const {
disabled,
value,
title,
children,
style,
class: cls,
className,
...otherProps
} = data;
// Option
const selected = values.has(value);
const optionPrefixCls = `${itemPrefixCls}-option`;
const optionClassName = classNames(itemPrefixCls, optionPrefixCls, cls, className, {
[`${optionPrefixCls}-grouped`]: groupOption,
[`${optionPrefixCls}-active`]: activeIndex === itemIndex && !disabled,
[`${optionPrefixCls}-disabled`]: disabled,
[`${optionPrefixCls}-selected`]: selected,
});
const mergedLabel = childrenAsData ? children : label;
const iconVisible =
!menuItemSelectedIcon || typeof menuItemSelectedIcon === 'function' || selected;
const content = mergedLabel || value;
// https://github.com/ant-design/ant-design/issues/26717
let optionTitle =
typeof content === 'string' || typeof content === 'number'
? content.toString()
: undefined;
if (title !== undefined) {
optionTitle = title;
}
return (
<div
{...otherProps}
aria-selected={selected}
class={optionClassName}
title={optionTitle}
onMousemove={e => {
if (otherProps.onMousemove) {
otherProps.onMousemove(e);
}
if (activeIndex === itemIndex || disabled) {
return;
}
setActive(itemIndex);
}}
onClick={e => {
if (!disabled) {
onSelectValue(value);
}
if (otherProps.onClick) {
otherProps.onClick(e);
}
}}
style={style}
>
<div class={`${optionPrefixCls}-content`}>
{renderOption ? renderOption(data) : content}
</div>
{isValidElement(menuItemSelectedIcon) || selected}
{iconVisible && (
<TransBtn
class={`${itemPrefixCls}-option-state`}
customizeIcon={menuItemSelectedIcon}
customizeIconProps={{ isSelected: selected }}
>
{selected ? '✓' : null}
</TransBtn>
)}
</div>
);
}}
></List>
</>
);
},
});
OptionList.props = OptionListProps;
export default OptionList; | the_stack |
import * as ethers from 'ethers'
import * as fs from 'fs'
import {
genRandomSalt,
stringifyBigInts,
} from 'maci-crypto'
import {
maciContractAbi,
} from 'maci-contracts'
import {
genBatchUstProofAndPublicSignals,
verifyBatchUstProof,
genQvtProofAndPublicSignals,
verifyQvtProof,
getSignalByNameViaSym,
} from 'maci-circuits'
import {
PubKey,
PrivKey,
Keypair,
StateLeaf,
} from 'maci-domainobjs'
import {
genPerVOSpentVoiceCreditsCommitment,
genTallyResultCommitment,
genSpentVoiceCreditsCommitment,
} from 'maci-core'
import {
promptPwd,
validateEthAddress,
contractExists,
genMaciStateFromContract,
} from './utils'
import {
DEFAULT_ETH_PROVIDER,
} from './defaults'
const configureSubparser = (subparsers: any) => {
const parser = subparsers.addParser(
'genProofs',
{ addHelp: true },
)
parser.addArgument(
['-e', '--eth-provider'],
{
action: 'store',
type: 'string',
help: `A connection string to an Ethereum provider. Default: ${DEFAULT_ETH_PROVIDER}`,
}
)
const maciPrivkeyGroup = parser.addMutuallyExclusiveGroup({ required: true })
maciPrivkeyGroup.addArgument(
['-dsk', '--prompt-for-maci-privkey'],
{
action: 'storeTrue',
help: 'Whether to prompt for your serialized MACI private key',
}
)
maciPrivkeyGroup.addArgument(
['-sk', '--privkey'],
{
action: 'store',
type: 'string',
help: 'Your serialized MACI private key',
}
)
parser.addArgument(
['-x', '--contract'],
{
required: true,
type: 'string',
help: 'The MACI contract address',
}
)
parser.addArgument(
['-o', '--output'],
{
required: true,
type: 'string',
help: 'The output file',
}
)
parser.addArgument(
['-t', '--tally-file'],
{
required: true,
type: 'string',
help: 'A filepath in which to save the final vote tally and salt.',
}
)
parser.addArgument(
['-z', '--final-zeroth-leaf'],
{
required: false,
type: 'string',
help: 'The serialized zeroth state leaf to update the state tree after processing the final message batch.',
}
)
// TODO: support resumable proof generation
//parser.addArgument(
//['-r', '--resume'],
//{
//action: 'storeTrue',
//help: 'Resume proof generation from the last proof in the specified output file',
//}
//)
}
const genProofs = async (args: any) => {
// Zeroth leaf
const serialized = args.final_zeroth_leaf
let zerothLeaf: StateLeaf
if (serialized) {
try {
zerothLeaf = StateLeaf.unserialize(serialized)
} catch {
console.error('Error: invalid zeroth state leaf')
return
}
} else {
zerothLeaf = StateLeaf.genRandomLeaf()
}
// MACI contract
if (!validateEthAddress(args.contract)) {
console.error('Error: invalid MACI contract address')
return
}
// Ethereum provider
const ethProvider = args.eth_provider ? args.eth_provider : DEFAULT_ETH_PROVIDER
const provider = new ethers.providers.JsonRpcProvider(ethProvider)
const maciAddress = args.contract
if (! (await contractExists(provider, maciAddress))) {
console.error('Error: there is no contract deployed at the specified address')
return
}
// The coordinator's MACI private key
// They may either enter it as a command-line option or via the
// standard input
let coordinatorPrivkey
if (args.prompt_for_maci_privkey) {
coordinatorPrivkey = await promptPwd('Coordinator\'s MACI private key')
} else {
coordinatorPrivkey = args.privkey
}
if (!PrivKey.isValidSerializedPrivKey(coordinatorPrivkey)) {
console.error('Error: invalid MACI private key')
return
}
const unserialisedPrivkey = PrivKey.unserialize(coordinatorPrivkey)
const coordinatorKeypair = new Keypair(unserialisedPrivkey)
const maciContract = new ethers.Contract(
maciAddress,
maciContractAbi,
provider,
)
// Build an off-chain representation of the MACI contract using data in the contract storage
let maciState
try {
maciState = await genMaciStateFromContract(
provider,
maciAddress,
coordinatorKeypair,
StateLeaf.genBlankLeaf(BigInt(0)),
false,
)
} catch (e) {
console.error(e)
return
}
const numMessages = maciState.messages.length
if (numMessages === 0) {
console.error('No messages to process.')
return
}
const messageBatchSize = Number(await maciContract.messageBatchSize())
const outputFile = args.output
const processProofs: any[] = []
const tallyProofs: any[] = []
//if (fs.existsSync(outputFile)) {
//proofs = JSON.parse(fs.readFileSync(outputFile).toString())
//}
const currentMessageBatchIndex = numMessages % messageBatchSize === 0 ?
(numMessages / messageBatchSize - 1) * messageBatchSize
:
Math.floor(numMessages / messageBatchSize) * messageBatchSize
console.log('Generating proofs of message processing...')
let proofNum = 1
for (let i = currentMessageBatchIndex; i >= 0; i -= messageBatchSize) {
console.log(`\nProgress: ${proofNum} / ${1 + currentMessageBatchIndex / messageBatchSize}; batch index: ${i}`)
proofNum ++
const randomStateLeaf = i > 0 ?
StateLeaf.genRandomLeaf()
:
zerothLeaf
const circuitInputs = maciState.genBatchUpdateStateTreeCircuitInputs(
i,
messageBatchSize,
randomStateLeaf,
)
// Process the batch of messages
maciState.batchProcessMessage(
i,
messageBatchSize,
randomStateLeaf,
)
const stateRootAfter = maciState.genStateRoot()
let result
let configType
let circuitName
if (maciState.stateTreeDepth === 12) {
configType = 'prod-large'
circuitName = 'batchUstLarge'
} else if (maciState.stateTreeDepth === 9) {
configType = 'prod-medium'
circuitName = 'batchUstMedium'
} else if (maciState.stateTreeDepth === 8) {
configType = 'prod-small'
circuitName = 'batchUstSmall'
} else if (maciState.stateTreeDepth === 32) {
configType = 'prod-32'
circuitName = 'batchUst32'
} else {
configType = 'test'
circuitName = 'batchUst'
}
try {
result = await genBatchUstProofAndPublicSignals(circuitInputs, configType)
} catch (e) {
console.error('Error: unable to compute batch update state tree witness data')
console.error(e)
return
}
const { witness, proof, publicSignals } = result
// Get the circuit-generated root
//const circuitNewStateRoot = getSignalByName(circuit, witness, 'main.root')
const circuitNewStateRoot = getSignalByNameViaSym(circuitName, witness, 'main.root')
if (!circuitNewStateRoot.toString() === stateRootAfter.toString()) {
console.error('Error: circuit-computed root mismatch')
return
}
const ecdhPubKeys: string[] = []
for (const p of circuitInputs['ecdh_public_key']) {
const pubKey = new PubKey(p.map((x) => BigInt(x)))
ecdhPubKeys.push(pubKey.serialize())
}
const isValid = await verifyBatchUstProof(proof, publicSignals, configType)
if (!isValid) {
console.error('Error: could not generate a valid proof or the verifying key is incorrect')
return
}
processProofs.push(stringifyBigInts({
stateRootAfter,
circuitInputs,
publicSignals,
proof,
ecdhPubKeys,
randomStateLeaf: randomStateLeaf.serialize(),
}))
if (outputFile) {
saveOutput(outputFile, processProofs, tallyProofs)
}
}
// Tally votes
const tallyBatchSize = Number(await maciContract.tallyBatchSize())
const numStateLeaves = 1 + maciState.users.length
let currentResultsSalt = BigInt(0)
let currentTvcSalt = BigInt(0)
let currentPvcSalt = BigInt(0)
let cumulativeTally
let newResultsCommitment
let newSpentVoiceCredits
let newSpentVoiceCreditsCommitment
let newResultsSalt
let newSpentVoiceCreditsSalt
let newPerVOSpentVoiceCreditsSalt
let newPerVOSpentVoiceCreditsCommitment
let totalPerVOSpentVoiceCredits
console.log('\nGenerating proofs of vote tallying...')
for (let i = 0; i < numStateLeaves; i += tallyBatchSize) {
const startIndex = i
console.log(`\nProgress: ${1 + i / tallyBatchSize} / ${1 + Math.floor(numStateLeaves / tallyBatchSize)}; batch index: ${i}`)
cumulativeTally = maciState.computeCumulativeVoteTally(startIndex)
const tally = maciState.computeBatchVoteTally(startIndex, tallyBatchSize)
let totalVotes = BigInt(0)
for (let i = 0; i < tally.length; i++) {
cumulativeTally[i] = BigInt(cumulativeTally[i]) + BigInt(tally[i])
totalVotes += cumulativeTally[i]
}
newResultsSalt = genRandomSalt()
newSpentVoiceCreditsSalt = genRandomSalt()
newPerVOSpentVoiceCreditsSalt = genRandomSalt()
// Generate circuit inputs
const circuitInputs
= maciState.genQuadVoteTallyCircuitInputs(
startIndex,
tallyBatchSize,
currentResultsSalt,
newResultsSalt,
currentTvcSalt,
newSpentVoiceCreditsSalt,
currentPvcSalt,
newPerVOSpentVoiceCreditsSalt,
)
currentResultsSalt = BigInt(newResultsSalt)
currentTvcSalt = BigInt(newSpentVoiceCreditsSalt)
currentPvcSalt = BigInt(newPerVOSpentVoiceCreditsSalt)
let configType
let circuitName
if (maciState.stateTreeDepth === 12) {
configType = 'prod-large'
circuitName = 'qvtLarge'
} else if (maciState.stateTreeDepth === 9) {
configType = 'prod-medium'
circuitName = 'qvtMedium'
} else if (maciState.stateTreeDepth === 8) {
configType = 'prod-small'
circuitName = 'qvtSmall'
} else if (maciState.stateTreeDepth === 32) {
configType = 'prod-32'
circuitName = 'qvt32'
} else {
configType = 'test'
circuitName = 'qvt'
}
let result
try {
result = await genQvtProofAndPublicSignals(circuitInputs, configType)
} catch (e) {
console.error('Error: unable to compute quadratic vote tally witness data')
console.error(e)
return
}
const { witness, proof, publicSignals } = result
// The vote tally commmitment
const expectedNewResultsCommitmentOutput =
getSignalByNameViaSym(circuitName, witness, 'main.newResultsCommitment')
newResultsCommitment = genTallyResultCommitment(
cumulativeTally,
newResultsSalt,
maciState.voteOptionTreeDepth,
)
if (expectedNewResultsCommitmentOutput.toString() !== newResultsCommitment.toString()) {
console.error('Error: result commitment mismatch')
return
}
// The commitment to the total spent voice credits
const expectedSpentVoiceCreditsCommitmentOutput =
getSignalByNameViaSym(circuitName, witness, 'main.newSpentVoiceCreditsCommitment')
const currentSpentVoiceCredits = maciState.computeCumulativeSpentVoiceCredits(startIndex)
newSpentVoiceCredits =
currentSpentVoiceCredits +
maciState.computeBatchSpentVoiceCredits(startIndex, tallyBatchSize)
newSpentVoiceCreditsCommitment = genSpentVoiceCreditsCommitment(
newSpentVoiceCredits,
currentTvcSalt,
)
if (expectedSpentVoiceCreditsCommitmentOutput.toString() !== newSpentVoiceCreditsCommitment.toString()) {
console.error('Error: total spent voice credits commitment mismatch')
return
}
// The commitment to the spent voice credits per vote option
const expectedPerVOSpentVoiceCreditsCommitmentOutput =
getSignalByNameViaSym(circuitName, witness, 'main.newPerVOSpentVoiceCreditsCommitment')
const currentPerVOSpentVoiceCredits
= maciState.computeCumulativePerVOSpentVoiceCredits(startIndex)
const perVOSpentVoiceCredits = maciState.computeBatchPerVOSpentVoiceCredits(
startIndex,
tallyBatchSize,
)
totalPerVOSpentVoiceCredits = []
for (let i = 0; i < currentPerVOSpentVoiceCredits.length; i ++) {
totalPerVOSpentVoiceCredits[i] = currentPerVOSpentVoiceCredits[i] + perVOSpentVoiceCredits[i]
}
newPerVOSpentVoiceCreditsCommitment = genPerVOSpentVoiceCreditsCommitment(
totalPerVOSpentVoiceCredits,
newPerVOSpentVoiceCreditsSalt,
maciState.voteOptionTreeDepth,
)
if (
expectedPerVOSpentVoiceCreditsCommitmentOutput.toString() !==
newPerVOSpentVoiceCreditsCommitment.toString()
) {
console.error('Error: total spent voice credits per vote option commitment mismatch')
return
}
const isValid = verifyQvtProof(proof, publicSignals, configType)
if (!isValid) {
console.error('Error: could not generate a valid proof or the verifying key is incorrect')
return
}
tallyProofs.push(stringifyBigInts({
circuitInputs,
publicSignals,
proof,
newResultsCommitment,
newSpentVoiceCreditsCommitment,
newPerVOSpentVoiceCreditsCommitment,
totalVotes,
}))
if (outputFile) {
saveOutput(outputFile, processProofs, tallyProofs)
}
}
const tallyFileData = {
provider: ethProvider,
maci: maciContract.address,
results: {
commitment: '0x' + BigInt(newResultsCommitment.toString()).toString(16),
tally: cumulativeTally.map((x) => x.toString()),
salt: '0x' + currentResultsSalt.toString(16),
},
totalVoiceCredits: {
spent: newSpentVoiceCredits.toString(),
commitment: '0x' + newSpentVoiceCreditsCommitment.toString(16),
salt: '0x' + newSpentVoiceCreditsSalt.toString(16),
},
totalVoiceCreditsPerVoteOption: {
commitment: '0x' + newPerVOSpentVoiceCreditsCommitment.toString(16),
tally: totalPerVOSpentVoiceCredits.map((x) => x.toString()),
salt: '0x' + newPerVOSpentVoiceCreditsSalt.toString(16),
},
}
if (args.tally_file) {
fs.writeFileSync(args.tally_file, JSON.stringify(tallyFileData, null, 4))
}
console.log('OK')
return {
proofs: { processProofs, tallyProofs },
tally: tallyFileData,
}
}
const saveOutput = (outputFile: string, processProofs: any, tallyProofs: any) => {
fs.writeFileSync(
outputFile,
JSON.stringify({ processProofs, tallyProofs }, null, 2),
)
}
export {
genProofs,
configureSubparser,
} | the_stack |
namespace $ {
export enum $mol_time_moment_weekdays {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}
export type $mol_time_moment_config = number | Date | string | {
year? : number
month? : number
day? : number
hour? : number
minute? : number
second? : number
offset? : $mol_time_duration_config
}
function numb( str: string, max: number ) {
const numb = Number( str )
if( numb < max ) return numb
$mol_fail( new Error( `Wrong time component ${ str }` ) )
}
export class $mol_time_moment extends $mol_time_base {
constructor( config : $mol_time_moment_config = new Date ) {
super()
if( typeof config === 'number' ) config = new Date( config )
if( typeof config === 'string' ) {
const parsed = /^(?:(\d\d?\d?\d?)(?:-?(\d\d?)(?:-?(\d\d?))?)?)?(?:[T ](?:(\d\d?)(?::?(\d\d?)(?::?(\d\d?(?:\.\d+)?))?)?)?(Z|[\+\-]\d\d?(?::?(?:\d\d?)?)?)?)?$/.exec( config )
if( !parsed ) throw new Error( `Can not parse time moment (${ config })` )
if( parsed[1] ) this.year = numb( parsed[1], 9999 )
if( parsed[2] ) this.month = numb( parsed[2], 13 ) - 1
if( parsed[3] ) this.day = numb( parsed[3], 32 ) - 1
if( parsed[4] ) this.hour = numb( parsed[4], 60 )
if( parsed[5] ) this.minute = numb( parsed[5], 60 )
if( parsed[6] ) this.second = numb( parsed[6], 60 )
if( parsed[7] ) this.offset = new $mol_time_duration( parsed[7] )
return
}
if( config instanceof Date ) {
this.year = config.getFullYear()
this.month = config.getMonth()
this.day = config.getDate() - 1
this.hour = config.getHours()
this.minute = config.getMinutes()
this.second = config.getSeconds() + config.getMilliseconds() / 1000
const offset = - config.getTimezoneOffset()
this.offset = new $mol_time_duration({
hour : ( offset < 0 ) ? Math.ceil( offset / 60 ) : Math.floor( offset / 60 ) ,
minute : offset % 60
})
return
}
this.year = config.year
this.month = config.month
this.day = config.day
this.hour = config.hour
this.minute = config.minute
this.second = config.second
this.offset = config.offset == null ? config.offset as undefined : new $mol_time_duration( config.offset )
}
readonly year : number | undefined
readonly month : number | undefined
readonly day : number | undefined
readonly hour : number | undefined
readonly minute : number | undefined
readonly second : number | undefined
readonly offset : $mol_time_duration | undefined
get weekday() {
return ( this.native.getDay() + 6 ) % 7
}
_native : Date | undefined
get native() {
if( this._native ) return this._native
const utc = this.toOffset( 'Z' )
return this._native = new Date( Date.UTC(
utc.year ?? 0 ,
utc.month ?? 0 ,
( utc.day ?? 0 ) + 1 ,
utc.hour ?? 0 ,
utc.minute ?? 0 ,
utc.second != undefined ? Math.floor( utc.second ) : 0 ,
utc.second != undefined ? Math.floor( ( utc.second - Math.floor( utc.second ) ) * 1000 ) : 0 ,
) )
}
_normal : $mol_time_moment | undefined
get normal() {
if( this._normal ) return this._normal
const moment = new $mol_time_moment( this.native )
return this._normal = new $mol_time_moment({
year : this.year === undefined ? undefined : moment.year ,
month : this.month === undefined ? undefined : moment.month ,
day : this.day === undefined ? undefined : moment.day ,
hour : this.hour === undefined ? undefined : moment.hour ,
minute : this.minute === undefined ? undefined : moment.minute ,
second : this.second === undefined ? undefined : moment.second ,
offset : this.offset === undefined ? undefined : moment.offset ,
})
}
merge( config : $mol_time_moment_config ) {
const moment = new $mol_time_moment( config )
return new $mol_time_moment({
year : moment.year === undefined ? this.year : moment.year ,
month : moment.month === undefined ? this.month : moment.month ,
day : moment.day === undefined ? this.day : moment.day ,
hour : moment.hour === undefined ? this.hour : moment.hour ,
minute : moment.minute === undefined ? this.minute : moment.minute ,
second : moment.second === undefined ? this.second : moment.second ,
offset : moment.offset === undefined ? this.offset : moment.offset ,
})
}
shift( config : $mol_time_duration_config ) {
const duration = new $mol_time_duration( config )
const moment = new $mol_time_moment().merge({
year: this.year,
month: this.month,
day: this.day,
hour: this.hour ?? 0,
minute: this.minute ?? 0,
second: this.second ?? 0,
offset: this.offset ?? 0
})
const second = moment.second! + ( duration.second ?? 0 )
const native = new Date(
moment.year! + ( duration.year ?? 0 ) ,
moment.month! + ( duration.month ?? 0 ) ,
moment.day! + 1 + ( duration.day ?? 0 ) ,
moment.hour! + ( duration.hour ?? 0 ) ,
moment.minute! + ( duration.minute ?? 0 ) ,
Math.floor( second ) ,
( second - Math.floor( second ) ) * 1000
)
if( isNaN( native.valueOf() ) ) throw new Error( 'Wrong time' )
return new $mol_time_moment({
year : this.year === undefined ? undefined : native.getFullYear(),
month : this.month === undefined ? undefined : native.getMonth(),
day : this.day === undefined ? undefined : native.getDate() - 1,
hour : this.hour === undefined ? undefined : native.getHours(),
minute : this.minute === undefined ? undefined : native.getMinutes(),
second : this.second === undefined ? undefined : native.getSeconds() + native.getMilliseconds() / 1000,
offset : this.offset,
})
}
mask( config : $mol_time_moment_config ) {
const mask = new $mol_time_moment( config )
return new $mol_time_moment({
year : mask.year === undefined ? undefined : this.year ,
month : mask.month === undefined ? undefined : this.month ,
day : mask.day === undefined ? undefined : this.day ,
hour : mask.hour === undefined ? undefined : this.hour ,
minute : mask.minute === undefined ? undefined : this.minute ,
second : mask.second === undefined ? undefined : this.second ,
offset : mask.offset === undefined ? undefined : this.offset ,
})
}
toOffset( config : $mol_time_duration_config ) {
const duration = new $mol_time_duration( config )
const offset = this.offset || new $mol_time_moment().offset!
let with_time = new $mol_time_moment( 'T00:00:00' ).merge( this )
const moment = with_time.shift( duration.summ( offset.mult( -1 ) ) )
return moment.merge({ offset : duration })
}
valueOf() { return this.native.getTime() }
toJSON() { return this.toString() }
toString( pattern = 'YYYY-MM-DDThh:mm:ss.sssZ' ) {
return super.toString( pattern )
}
[ Symbol.toPrimitive ]( mode: 'default' | 'number' | 'string' ) {
return mode === 'number' ? this.valueOf() : this.toString()
}
/// Mnemonics:
/// * single letter for numbers: M - month number, D - day of month.
/// * uppercase letters for dates, lowercase for times: M - month number , m - minutes number
/// * repeated letters for define register count: YYYY - full year, YY - shot year, MM - padded month number
/// * words for word representation: Month - month name, WeekDay - day of week name
/// * shortcuts: WD - short day of week, Mon - short month name.
static patterns = {
'YYYY' : ( moment : $mol_time_moment )=> {
if( moment.year == null ) return ''
return String( moment.year )
} ,
'AD' : ( moment : $mol_time_moment )=> {
if( moment.year == null ) return ''
return String( Math.floor( moment.year / 100 ) + 1 )
} ,
'YY' : ( moment : $mol_time_moment )=> {
if( moment.year == null ) return ''
return String( moment.year % 100 )
} ,
'Month' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) return ''
return pattern.format( moment.native )
} )( new Intl.DateTimeFormat( undefined , { month : 'long' } ) ) ,
'DD Month' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) {
if( moment.day == null ) {
return ''
} else {
return $mol_time_moment.patterns[ 'DD' ]( moment )
}
} else {
if( moment.day == null ) {
return $mol_time_moment.patterns[ 'Month' ]( moment )
} else {
return pattern.format( moment.native )
}
}
} )(
new Intl.DateTimeFormat( undefined , { day : '2-digit' , month : 'long' } )
) ,
'D Month' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) {
if( moment.day == null ) {
return ''
} else {
return $mol_time_moment.patterns[ 'D' ]( moment )
}
} else {
if( moment.day == null ) {
return $mol_time_moment.patterns[ 'Month' ]( moment )
} else {
return pattern.format( moment.native )
}
}
} )(
new Intl.DateTimeFormat( undefined , { day : 'numeric' , month : 'long' } )
) ,
'Mon' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) return ''
return pattern.format( moment.native )
} )( new Intl.DateTimeFormat( undefined , { month : 'short' } ) ) ,
'DD Mon' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) {
if( moment.day == null ) {
return ''
} else {
return $mol_time_moment.patterns[ 'DD' ]( moment )
}
} else {
if( moment.day == null ) {
return $mol_time_moment.patterns[ 'Mon' ]( moment )
} else {
return pattern.format( moment.native )
}
}
} )(
new Intl.DateTimeFormat( undefined , { day : '2-digit' , month : 'short' } )
) ,
'D Mon' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.month == null ) {
if( moment.day == null ) {
return ''
} else {
return $mol_time_moment.patterns[ 'D' ]( moment )
}
} else {
if( moment.day == null ) {
return $mol_time_moment.patterns[ 'Mon' ]( moment )
} else {
return pattern.format( moment.native )
}
}
} )(
new Intl.DateTimeFormat( undefined , { day : 'numeric' , month : 'short' } )
) ,
'-MM' : ( moment : $mol_time_moment )=> {
if( moment.month == null ) return ''
return '-' + $mol_time_moment.patterns[ 'MM' ]( moment )
} ,
'MM' : ( moment : $mol_time_moment )=> {
if( moment.month == null ) return ''
return String( 100 + moment.month + 1 ).slice(1)
} ,
'M' : ( moment : $mol_time_moment )=> {
if( moment.month == null ) return ''
return String( moment.month + 1 )
} ,
'WeekDay' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.day == null ) return ''
if( moment.month == null ) return ''
if( moment.year == null ) return ''
return pattern.format( moment.native )
} )( new Intl.DateTimeFormat( undefined , { weekday : 'long' } ) ) ,
'WD' : ( pattern => ( moment : $mol_time_moment )=> {
if( moment.day == null ) return ''
if( moment.month == null ) return ''
if( moment.year == null ) return ''
return pattern.format( moment.native )
} )( new Intl.DateTimeFormat( undefined , { weekday : 'short' } ) ) ,
'-DD' : ( moment : $mol_time_moment )=> {
if( moment.day == null ) return ''
return '-' + $mol_time_moment.patterns[ 'DD' ]( moment )
} ,
'DD' : ( moment : $mol_time_moment )=> {
if( moment.day == null ) return ''
return String( 100 + moment.day + 1 ).slice(1)
} ,
'D' : ( moment : $mol_time_moment )=> {
if( moment.day == null ) return ''
return String( moment.day + 1 )
} ,
'Thh' : ( moment : $mol_time_moment )=> {
if( moment.hour == null ) return ''
return 'T' + $mol_time_moment.patterns[ 'hh' ]( moment )
} ,
'hh' : ( moment : $mol_time_moment )=> {
if( moment.hour == null ) return ''
return String( 100 + moment.hour ).slice(1)
} ,
'h' : ( moment : $mol_time_moment )=> {
if( moment.hour == null ) return ''
return String( moment.hour )
} ,
':mm' : ( moment : $mol_time_moment )=> {
if( moment.minute == null ) return ''
return ':' + $mol_time_moment.patterns[ 'mm' ]( moment )
} ,
'mm' : ( moment : $mol_time_moment )=> {
if( moment.minute == null ) return ''
return String( 100 + moment.minute ).slice(1)
} ,
'm' : ( moment : $mol_time_moment )=> {
if( moment.minute == null ) return ''
return String( moment.minute )
},
':ss' : ( moment : $mol_time_moment )=> {
if( moment.second == null ) return ''
return ':' + $mol_time_moment.patterns[ 'ss' ]( moment )
},
'ss' : ( moment : $mol_time_moment )=> {
if( moment.second == null ) return ''
return String( 100 + moment.second | 0 ).slice(1)
},
's' : ( moment : $mol_time_moment )=> {
if( moment.second == null ) return ''
return String( moment.second | 0 )
} ,
'.sss' : ( moment : $mol_time_moment )=> {
if( moment.second == null ) return ''
if( moment.second === ( moment.second | 0 ) ) return ''
return '.' + $mol_time_moment.patterns[ 'sss' ]( moment )
},
'sss' : ( moment : $mol_time_moment )=> {
if( moment.second == null ) return ''
const millisecond = Math.floor( ( moment.second - Math.floor( moment.second ) ) * 1000 )
return String( 1000 + millisecond ).slice(1)
},
'Z' : ( moment : $mol_time_moment )=> {
const offset = moment.offset
if( !offset ) return ''
let hour = offset.hour
let sign = '+'
if( hour < 0 ) {
sign = '-'
hour = -hour
}
return sign + String( 100 + hour ).slice(1) + ':' + String( 100 + offset.minute ).slice(1)
}
}
}
} | the_stack |
import * as core from '@spyglassmc/core'
import { sequence } from '@spyglassmc/core'
import * as json from '@spyglassmc/json'
import { localeQuote, localize } from '@spyglassmc/locales'
import * as mcf from '@spyglassmc/mcfunction'
import * as nbt from '@spyglassmc/nbt'
import { ReleaseVersion } from '../../dependency/index.js'
import { ColorArgumentValues, EntityAnchorArgumentValues, ItemSlotArgumentValues, OperationArgumentValues, ScoreboardSlotArgumentValues, SwizzleArgumentValues } from '../common/index.js'
import type { BlockNode, CoordinateNode, EntityNode, EntitySelectorAdvancementsArgumentCriteriaNode, EntitySelectorAdvancementsArgumentNode, EntitySelectorInvertableArgumentValueNode, EntitySelectorScoresArgumentNode, EntitySelectorVariable, FloatRangeNode, IntRangeNode, ItemNode, MessageNode, ParticleNode, ScoreHolderNode, UuidNode, VectorNode } from '../node/index.js'
import { BlockStatesNode, CoordinateSystem, EntitySelectorArgumentsNode, EntitySelectorAtVariable, EntitySelectorAtVariables, EntitySelectorNode, ObjectiveCriteriaNode, TimeNode } from '../node/index.js'
import type { ArgumentTreeNode } from '../tree/argument.js'
const IntegerPattern = /^-?\d+$/
/**
* A combination of:
* - https://github.com/Mojang/brigadier/blob/cf754c4ef654160dca946889c11941634c5db3d5/src/main/java/com/mojang/brigadier/StringReader.java#L137
* - https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#valueOf(java.lang.String)
*
* i.e. Only `[0-9\.\-]` is allowed in the number, and its format must follow The Java™ Language Specification.
*
* i.e.
* ```
* [NegativeSign] Digits [`.`] [Digits] |
* [NegativeSign] `.` Digits
* ```
*/
const FloatPattern = /^-?(?:\d+\.?\d*|\.\d+)$/
const DoubleMax = Number.MAX_VALUE
const DoubleMin = -DoubleMax
const FloatMax = (2 - (2 ** -23)) * (2 ** 127)
const FloatMin = -FloatMax
const IntegerMax = 2 ** 31 - 1
const IntegerMin = -(2 ** 31)
const LongMax = 9223372036854775807n
const LongMin = -9223372036854775808n
const FakeNameMaxLength = 40
const ObjectiveMaxLength = 16
const PlayerNameMaxLength = 16
function shouldValidateLength(ctx: core.ParserContext) {
const release = ctx.project['loadedVersion'] as ReleaseVersion | undefined
return !release || ReleaseVersion.cmp(release, '1.18') < 0
}
/**
* @returns The parser for the specified argument tree node. All argument parsers used in the `mcfunction` package
* fail on empty input.
*/
export const argument: mcf.ArgumentParserGetter = (rawTreeNode): core.Parser | undefined => {
const treeNode = rawTreeNode as ArgumentTreeNode
const wrap = <T extends core.AstNode>(parser: core.Parser<T>): core.Parser => core.failOnEmpty<T>(core.stopBefore(parser, '\r', '\n'))
switch (treeNode.parser) {
case 'brigadier:bool':
return wrap(core.boolean)
case 'brigadier:double':
return wrap(double(treeNode.properties?.min, treeNode.properties?.max))
case 'brigadier:float':
return wrap(float(treeNode.properties?.min, treeNode.properties?.max))
case 'brigadier:integer':
return wrap(integer(treeNode.properties?.min, treeNode.properties?.max))
case 'brigadier:long':
return wrap(long(treeNode.properties?.min, treeNode.properties?.max))
case 'brigadier:string':
switch (treeNode.properties.type) {
case 'word':
return wrap(unquotedString)
case 'phrase':
return wrap(core.brigadierString)
case 'greedy':
default:
return wrap(greedyString)
}
case 'minecraft:angle':
return wrap(core.validate(
coordinate(),
res => res.notation !== '^',
localize('mcfunction.parser.vector.local-disallowed')
))
case 'minecraft:block_pos':
return wrap(vector({ dimension: 3, integersOnly: true }))
case 'minecraft:block_predicate':
return wrap(blockPredicate)
case 'minecraft:block_state':
return wrap(blockState)
case 'minecraft:color':
return wrap(core.map(
core.literal(...ColorArgumentValues),
res => ({
...res,
color: core.Color.NamedColors.has(res.value)
? core.Color.fromCompositeInt(core.Color.NamedColors.get(res.value)!)
: undefined,
})
))
case 'minecraft:column_pos':
return wrap(vector({ dimension: 2, integersOnly: true }))
case 'minecraft:component':
return wrap(component)
case 'minecraft:dimension':
return wrap(core.resourceLocation({
category: 'dimension',
}))
case 'minecraft:entity':
return wrap(entity(treeNode.properties.amount, treeNode.properties.type))
case 'minecraft:entity_anchor':
return wrap(core.literal(...EntityAnchorArgumentValues))
case 'minecraft:entity_summon':
return wrap(core.resourceLocation({
category: 'entity_type',
}))
case 'minecraft:float_range':
return wrap(range('float'))
case 'minecraft:function':
return wrap(core.resourceLocation({
category: 'function',
allowTag: true,
}))
case 'minecraft:game_profile':
return wrap(entity('multiple', 'players'))
case 'minecraft:int_range':
return wrap(range('integer'))
case 'minecraft:item_enchantment':
return wrap(core.resourceLocation({
category: 'enchantment',
}))
case 'minecraft:item_predicate':
return wrap(itemPredicate)
case 'minecraft:item_slot':
return wrap(core.literal(...ItemSlotArgumentValues))
case 'minecraft:item_stack':
return wrap(itemStack)
case 'minecraft:message':
return wrap(message)
case 'minecraft:mob_effect':
return wrap(core.resourceLocation({
category: 'mob_effect',
}))
case 'minecraft:nbt_compound_tag':
return wrap(nbt.parser.compound)
case 'minecraft:nbt_path':
return wrap(nbt.parser.path)
case 'minecraft:nbt_tag':
return wrap(nbt.parser.entry)
case 'minecraft:objective':
return wrap(objective(core.SymbolUsageType.is(treeNode.properties?.usageType)
? treeNode.properties?.usageType
: undefined
))
case 'minecraft:objective_criteria':
return wrap(objectiveCriteria)
case 'minecraft:operation':
return wrap(core.literal({
pool: OperationArgumentValues,
colorTokenType: 'operator',
}))
case 'minecraft:particle':
return wrap(particle)
case 'minecraft:resource':
case 'minecraft:resource_or_tag':
return wrap(core.resourceLocation({
category: core.ResourceLocation.shorten(treeNode.properties.registry) as core.RegistryCategory | core.WorldgenFileCategory,
allowTag: treeNode.parser === 'minecraft:resource_or_tag',
}))
case 'minecraft:resource_location':
return wrap(core.resourceLocation(treeNode.properties ?? {
pool: [],
allowUnknown: true,
}))
case 'minecraft:rotation':
return wrap(vector({ dimension: 2, noLocal: true }))
case 'minecraft:score_holder':
return wrap(scoreHolder(treeNode.properties.amount))
case 'minecraft:scoreboard_slot':
// `BELOWNAME` and `sidebar.team.r--.+++e----__d` are also legal slots.
// But I do not want to spend time supporting them.
return wrap(core.literal(...ScoreboardSlotArgumentValues))
case 'minecraft:swizzle':
return wrap(core.literal(...SwizzleArgumentValues))
case 'minecraft:team':
return wrap(team(core.SymbolUsageType.is(treeNode.properties?.usageType)
? treeNode.properties?.usageType
: undefined
))
case 'minecraft:time':
return wrap(time)
case 'minecraft:uuid':
return wrap(uuid)
case 'minecraft:vec2':
return wrap(vector({ dimension: 2, noLocal: true }))
case 'minecraft:vec3':
return wrap(vector({ dimension: 3 }))
case 'spyglassmc:tag':
return wrap(tag())
default:
// Unknown parser.
return undefined
}
}
function block(isPredicate: boolean): core.InfallibleParser<BlockNode> {
return core.map<core.SequenceUtil<core.ResourceLocationNode | BlockStatesNode | nbt.NbtCompoundNode>, BlockNode>(
core.sequence([
core.resourceLocation({ category: 'block', allowTag: isPredicate }),
core.optional(core.map<core.RecordNode<core.StringNode, core.StringNode>, BlockStatesNode>(
core.failOnEmpty(core.record<core.StringNode, core.StringNode>({
start: '[',
pair: {
key: core.string({
...core.BrigadierStringOptions,
colorTokenType: 'property',
}),
sep: '=',
value: core.brigadierString,
end: ',',
trailingEnd: true,
},
end: ']',
})),
res => ({
...res,
type: 'mcfunction:block/states',
})
)),
core.optional(core.failOnEmpty(nbt.parser.compound)),
]),
res => {
const ans: BlockNode = {
type: 'mcfunction:block',
range: res.range,
children: res.children,
id: res.children.find(core.ResourceLocationNode.is)!,
states: res.children.find(BlockStatesNode.is),
nbt: res.children.find(nbt.NbtCompoundNode.is),
}
return ans
}
)
}
const blockState: core.InfallibleParser<BlockNode> = block(false)
export const blockPredicate: core.InfallibleParser<BlockNode> = block(true)
export const component = json.parser.json()
function double(min = DoubleMin, max = DoubleMax): core.InfallibleParser<core.FloatNode> {
return core.float({
pattern: FloatPattern,
min,
max,
})
}
function float(min = FloatMin, max = FloatMax): core.InfallibleParser<core.FloatNode> {
return core.float({
pattern: FloatPattern,
min,
max,
})
}
function integer(min = IntegerMin, max = IntegerMax): core.InfallibleParser<core.IntegerNode> {
return core.integer({
pattern: IntegerPattern,
min,
max,
})
}
function long(min?: number, max?: number): core.InfallibleParser<core.LongNode> {
return core.long({
pattern: IntegerPattern,
min: BigInt(min ?? LongMin),
max: BigInt(max ?? LongMax),
})
}
function coordinate(integerOnly = false): core.InfallibleParser<CoordinateNode> {
return (src, ctx): CoordinateNode => {
const ans: CoordinateNode = {
type: 'mcfunction:coordinate',
notation: '',
range: core.Range.create(src),
value: 0,
}
if (src.trySkip('^')) {
ans.notation = '^'
} else if (src.trySkip('~')) {
ans.notation = '~'
}
if ((src.canReadInLine() && src.peek() !== ' ') || ans.notation === '') {
const result = (integerOnly && ans.notation === '' ? integer : double)()(src, ctx)
ans.value = Number(result.value)
}
ans.range.end = src.cursor
return ans
}
}
function entity(amount: 'multiple' | 'single', type: 'entities' | 'players'): core.Parser<EntityNode> {
return core.map<core.StringNode | EntitySelectorNode | UuidNode, EntityNode>(
core.select([
{
predicate: src => EntitySelectorAtVariable.is(src.peek(2)),
parser: selector(),
},
{
parser: core.any([
validateLength<core.StringNode>(
core.brigadierString,
PlayerNameMaxLength,
'mcfunction.parser.entity-selector.player-name.too-long'
),
uuid,
]),
},
]),
(res, _src, ctx) => {
const ans: EntityNode = {
type: 'mcfunction:entity',
range: res.range,
children: [res],
}
if (core.StringNode.is(res)) {
ans.playerName = res
} else if (EntitySelectorNode.is(res)) {
ans.selector = res
} else {
ans.uuid = res
}
if (amount === 'single' && ans.selector && !ans.selector.single) {
ctx.err.report(localize('mcfunction.parser.entity-selector.multiple-disallowed'), ans)
}
if (type === 'players' && (ans.uuid || (ans.selector && !ans.selector.playersOnly && !ans.selector.currentEntity))) {
ctx.err.report(localize('mcfunction.parser.entity-selector.entities-disallowed'), ans)
}
return ans
}
)
}
const greedyString: core.InfallibleParser<core.StringNode> = core.string({
unquotable: { blockList: new Set(['\n', '\r']) },
})
function item(isPredicate: false): core.InfallibleParser<ItemNode>
function item(isPredicate: true): core.InfallibleParser<ItemNode>
function item(isPredicate: boolean): core.InfallibleParser<ItemNode> {
return core.map<core.SequenceUtil<core.ResourceLocationNode | nbt.NbtCompoundNode>, ItemNode>(
core.sequence([
core.resourceLocation({ category: 'item', allowTag: isPredicate }),
core.optional(core.failOnEmpty(nbt.parser.compound)),
]),
res => {
const ans: ItemNode = {
type: 'mcfunction:item',
range: res.range,
children: res.children,
id: res.children.find(core.ResourceLocationNode.is)!,
nbt: res.children.find(nbt.NbtCompoundNode.is),
}
return ans
}
)
}
const itemStack: core.InfallibleParser<ItemNode> = item(false)
const itemPredicate: core.InfallibleParser<ItemNode> = item(true)
const message: core.InfallibleParser<MessageNode> = (src, ctx) => {
const ans: MessageNode = {
type: 'mcfunction:message',
range: core.Range.create(src),
children: [],
}
while (src.canReadInLine()) {
if (EntitySelectorAtVariable.is(src.peek(2))) {
ans.children.push(selector()(src, ctx) as EntitySelectorNode)
} else {
ans.children.push(core.stopBefore(greedyString, ...EntitySelectorAtVariables)(src, ctx))
}
}
return ans
}
export const particle: core.InfallibleParser<ParticleNode> = (() => {
type CN = Exclude<ParticleNode['children'], undefined>[number]
const sep = core.map(mcf.sep, () => [])
const vec = vector({ dimension: 3 })
const color = core.map<VectorNode, VectorNode>(vec, res => ({
...res,
color: res.children.length === 3
? {
value: core.Color.fromDecRGB(res.children[0].value, res.children[1].value, res.children[2].value),
format: [core.ColorFormat.DecRGB],
}
: undefined,
}))
const map: Record<ParticleNode.SpecialType, core.InfallibleParser<CN | core.SequenceUtil<CN>>> = {
block: blockState,
block_marker: blockState,
dust: sequence([color, float()], sep),
dust_color_transition: sequence([color, float(), color], sep),
falling_dust: blockState,
item: itemStack,
sculk_charge: float(),
vibration: sequence([vec, vec, integer()], sep),
}
return core.map(
sequence([
core.resourceLocation({ category: 'particle_type' }),
{
get: res => {
return map[core.ResourceLocationNode.toString(res.children[0] as core.ResourceLocationNode, 'short') as ParticleNode.SpecialType] as typeof map[keyof typeof map] | undefined
},
},
], sep),
res => {
const ans: ParticleNode = {
type: 'mcfunction:particle',
range: res.range,
children: res.children,
id: res.children.find(core.ResourceLocationNode.is)!,
}
return ans
}
)
})()
function range(type: 'float', min?: number, max?: number, cycleable?: boolean): core.Parser<FloatRangeNode>
function range(type: 'integer', min?: number, max?: number, cycleable?: boolean): core.Parser<IntRangeNode>
function range(type: 'float' | 'integer', min?: number, max?: number, cycleable?: boolean): core.Parser<FloatRangeNode | IntRangeNode> {
const number: core.Parser<core.FloatNode | core.IntegerNode> = type === 'float' ? float(min, max) : integer(min, max)
const low = core.failOnEmpty(core.stopBefore(number, '..'))
const sep = core.failOnEmpty(core.literal({ pool: ['..'], colorTokenType: 'keyword' }))
const high = core.failOnEmpty(number)
return core.map<core.SequenceUtil<core.FloatNode | core.IntegerNode | core.LiteralNode>, FloatRangeNode | IntRangeNode>(
core.any([
/* exactly */ core.sequence([low]),
/* atLeast */ core.sequence([low, sep]),
/* atMost */ core.sequence([sep, high]),
/* between */ core.sequence([low, sep, high]),
]),
(res, _src, ctx) => {
const valueNodes = type === 'float'
? res.children.filter(core.FloatNode.is)
: res.children.filter(core.IntegerNode.is)
const sepNode = res.children.find(core.LiteralNode.is)
const ans: FloatRangeNode | IntRangeNode = {
type: type === 'float' ? 'mcfunction:float_range' : 'mcfunction:int_range',
range: res.range,
children: res.children as any,
value: sepNode
? valueNodes.length === 2
? [valueNodes[0].value, valueNodes[1].value]
: core.Range.endsBefore(valueNodes[0].range, sepNode.range.start)
? [valueNodes[0].value, undefined]
: [undefined, valueNodes[0].value]
: [valueNodes[0].value, valueNodes[0].value],
}
if (!cycleable && ans.value[0] !== undefined && ans.value[1] !== undefined && ans.value[0] > ans.value[1]) {
ctx.err.report(localize('mcfunction.parser.range.min>max', ans.value[0], ans.value[1]), res)
}
return ans
}
)
}
/**
* Failure when not beginning with `@[parse]`
*/
function selector(): core.Parser<EntitySelectorNode> {
let chunkLimited: boolean | undefined
let currentEntity: boolean | undefined
let dimensionLimited: boolean | undefined
let playersOnly: boolean | undefined
let predicates: string[] | undefined
let single: boolean | undefined
let typeLimited: boolean | undefined
return core.map<core.SequenceUtil<core.LiteralNode | EntitySelectorArgumentsNode>, EntitySelectorNode>(
core.sequence([
core.failOnEmpty(core.literal({ pool: EntitySelectorAtVariables, colorTokenType: 'keyword' })),
{
get: res => {
const variable = core.LiteralNode.is(res.children?.[0]) ? res.children[0].value : undefined
currentEntity = variable ? variable === '@s' : undefined
playersOnly = variable ? variable === '@p' || variable === '@a' || variable === '@r' : undefined
predicates = variable === '@e' ? ['Entity::isAlive'] : undefined
single = variable ? variable === '@p' || variable === '@r' || variable === '@s' : undefined
typeLimited = playersOnly
function invertable<T extends core.AstNode>(parser: core.Parser<T>): core.Parser<EntitySelectorInvertableArgumentValueNode<T>> {
return core.map<core.SequenceUtil<core.LiteralNode | T>, EntitySelectorInvertableArgumentValueNode<T>>(
core.sequence([
core.optional(core.failOnEmpty(core.literal({ pool: ['!'], colorTokenType: 'keyword' }))),
src => { src.skipSpace(); return undefined },
parser,
]),
res => {
const ans: EntitySelectorInvertableArgumentValueNode<T> = {
type: 'mcfunction:entity_selector/arguments/value/invertable',
range: res.range,
children: res.children,
inverted: !!res.children.find(n => core.LiteralNode.is(n) && n.value === '!'),
value: res.children.find(n => !core.LiteralNode.is(n) || n.value !== '!') as T,
}
return ans
}
)
}
return core.optional(core.map<core.RecordNode<core.StringNode, core.AstNode>, EntitySelectorArgumentsNode>(
core.failOnEmpty(core.record({
start: '[',
pair: {
key: core.string({
...core.BrigadierStringOptions,
value: {
parser: core.literal({ pool: [...EntitySelectorNode.ArgumentKeys], colorTokenType: 'property' }),
type: 'literal',
},
}),
sep: '=',
value: {
get: (record, key) => {
const hasKey = (key: string): boolean => !!record.children.find(p => p.key?.value === key)
const hasNonInvertedKey = (key: string): boolean => !!record.children.find(p => p.key?.value === key && !(p.value as EntitySelectorInvertableArgumentValueNode<core.AstNode>)?.inverted)
switch (key?.value) {
case 'advancements':
return core.map<core.RecordNode<core.ResourceLocationNode, core.BooleanNode | EntitySelectorAdvancementsArgumentCriteriaNode>, EntitySelectorAdvancementsArgumentNode>(
core.record<core.ResourceLocationNode, core.BooleanNode | EntitySelectorAdvancementsArgumentCriteriaNode>({
start: '{',
pair: {
key: core.resourceLocation({ category: 'advancement' }),
sep: '=',
value: core.select([
{
predicate: src => src.peek() === '{',
parser: core.map<core.RecordNode<core.StringNode, core.BooleanNode>, EntitySelectorAdvancementsArgumentCriteriaNode>(
core.record<core.StringNode, core.BooleanNode>({
start: '{',
pair: {
key: unquotedString,
sep: '=',
value: core.boolean,
end: ',',
trailingEnd: true,
},
end: '}',
}),
res => {
const ans: EntitySelectorAdvancementsArgumentCriteriaNode = {
...res,
type: 'mcfunction:entity_selector/arguments/advancements/criteria',
}
return ans
}
),
},
{
parser: core.boolean,
},
]),
end: ',',
trailingEnd: true,
},
end: '}',
}),
(res, _, ctx) => {
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
const ans: EntitySelectorAdvancementsArgumentNode = {
...res,
type: 'mcfunction:entity_selector/arguments/advancements',
}
return ans
}
)
case 'distance':
return core.map<FloatRangeNode>(
range('float', 0),
(res, _, ctx) => {
dimensionLimited = true
// x, y, z, dx, dy, dz take precedence over distance, so we use ??= instead of = to ensure it won't override the result.
chunkLimited ??= !playersOnly && res.value[1] !== undefined
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'gamemode':
return core.map<EntitySelectorInvertableArgumentValueNode<core.StringNode>>(
invertable(core.string({
unquotable: core.BrigadierUnquotableOption,
value: {
type: 'literal',
parser: core.literal('adventure', 'creative', 'spectator', 'survival'),
},
})),
(res, _, ctx) => {
playersOnly = true
if (res.inverted ? hasNonInvertedKey(key.value) : hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'limit':
return core.map<core.IntegerNode>(
integer(0),
(res, _, ctx) => {
single = res.value <= 1
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
if (currentEntity) {
ctx.err.report(localize('mcfunction.parser.entity-selector.arguments.not-applicable', localeQuote(key.value)), key)
}
return res
}
)
case 'level':
return core.map<IntRangeNode>(
range('integer', 0),
(res, _, ctx) => {
playersOnly = true
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'name':
return core.map<EntitySelectorInvertableArgumentValueNode<core.StringNode>>(
invertable(core.brigadierString),
(res, _, ctx) => {
if (res.inverted ? hasNonInvertedKey(key.value) : hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'nbt':
return invertable(nbt.parser.compound)
case 'predicate':
return invertable(core.resourceLocation({ category: 'predicate' }))
case 'scores':
return core.map<core.RecordNode<core.SymbolNode, IntRangeNode>, EntitySelectorScoresArgumentNode>(
core.record<core.SymbolNode, IntRangeNode>({
start: '{',
pair: {
key: objective('reference', ['[', '=', ',', ']', '{', '}']),
sep: '=',
value: range('integer'),
end: ',',
trailingEnd: true,
},
end: '}',
}),
(res, _, ctx) => {
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
const ans: EntitySelectorScoresArgumentNode = {
...res,
type: 'mcfunction:entity_selector/arguments/scores',
}
return ans
}
)
case 'sort':
return core.map<core.StringNode>(
core.string({
unquotable: core.BrigadierUnquotableOption,
value: {
type: 'literal',
parser: core.literal('arbitrary', 'furthest', 'nearest', 'random'),
},
}),
(res, _, ctx) => {
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
if (currentEntity) {
ctx.err.report(localize('mcfunction.parser.entity-selector.arguments.not-applicable', localeQuote(key.value)), key)
}
return res
}
)
case 'tag':
return invertable(tag(['[', '=', ',', ']', '{', '}']))
case 'team':
return core.map<EntitySelectorInvertableArgumentValueNode<core.SymbolNode>>(
invertable(team('reference', ['[', '=', ',', ']', '{', '}'])),
(res, _, ctx) => {
if (res.inverted ? hasNonInvertedKey(key.value) : hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'type':
return core.map<EntitySelectorInvertableArgumentValueNode<core.ResourceLocationNode>>(
invertable(core.resourceLocation({ category: 'entity_type', allowTag: true })),
(res, _, ctx) => {
if (typeLimited) {
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
} else {
ctx.err.report(localize('mcfunction.parser.entity-selector.arguments.not-applicable', localeQuote(key.value)), key)
}
} else if (!res.inverted && !res.value.isTag) {
typeLimited = true
if (core.ResourceLocationNode.toString(res.value, 'short') === 'player') {
playersOnly = true
}
}
return res
}
)
case 'x':
case 'y':
case 'z':
return core.map<core.FloatNode>(
double(),
(res, _, ctx) => {
dimensionLimited = true
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'dx':
case 'dy':
case 'dz':
return core.map<core.FloatNode>(
double(),
(res, _, ctx) => {
dimensionLimited = true
chunkLimited = !playersOnly
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case 'x_rotation':
case 'y_rotation':
return core.map<FloatRangeNode>(
range('float', undefined, undefined, true),
(res, _, ctx) => {
if (hasKey(key.value)) {
ctx.err.report(localize('duplicate-key', localeQuote(key.value)), key)
}
return res
}
)
case undefined:
// The key is empty. Let's just fail the value as well.
return (): core.Result<never> => core.Failure
default:
// The key is unknown.
return (_src, ctx): core.Result<never> => {
ctx.err.report(localize('mcfunction.parser.entity-selector.arguments.unknown', localeQuote(key!.value)), key!)
return core.Failure
}
}
},
},
end: ',',
trailingEnd: true,
},
end: ']',
})),
res => {
const ans: EntitySelectorArgumentsNode = {
...res,
type: 'mcfunction:entity_selector/arguments',
}
return ans
}
))
},
},
]),
res => {
const ans: EntitySelectorNode = {
type: 'mcfunction:entity_selector',
range: res.range,
children: res.children as EntitySelectorNode['children'],
variable: res.children.find(core.LiteralNode.is)!.value.slice(1) as EntitySelectorVariable,
arguments: res.children.find(EntitySelectorArgumentsNode.is),
chunkLimited,
currentEntity,
dimensionLimited,
playersOnly,
predicates,
single,
typeLimited,
}
ans.hover = getEntitySelectorHover(ans)
return ans
}
)
}
// This is more like a proof-of-concept.
// Might not make into the actual release.
function getEntitySelectorHover(node: EntitySelectorNode) {
const grades = new Map<number, string>([
[0, '🤢'], // Bad
[1, '😅'], // Normal
[2, 'Good'], // Good
[3, 'Great'], // Great
[4, '😌👌'], // Excellent
])
let ans: string
if (node.currentEntity) {
ans = `**Performance**: ${grades.get(4)}
- \`currentEntity\`: \`${node.currentEntity}\``
} else {
const amountOfTrue = [node.chunkLimited, node.dimensionLimited, node.playersOnly, node.typeLimited].filter(v => v).length
ans = `**Performance**: ${grades.get(amountOfTrue)}
- \`chunkLimited\`: \`${!!node.chunkLimited}\`
- \`dimensionLimited\`: \`${!!node.dimensionLimited}\`
- \`playersOnly\`: \`${!!node.playersOnly}\`
- \`typeLimited\`: \`${!!node.chunkLimited}\``
}
if (node.predicates?.length) {
ans += `
------
**Predicates**:
${node.predicates.map(p => `- \`${p}\``).join('\n')}`
}
return ans
}
export const scoreHolderFakeName: core.Parser<core.SymbolNode> = validateLength<core.SymbolNode>(
symbol('score_holder'),
FakeNameMaxLength,
'mcfunction.parser.score_holder.fake-name.too-long',
)
function scoreHolder(amount: 'multiple' | 'single'): core.Parser<ScoreHolderNode> {
return core.map<core.SymbolNode | EntitySelectorNode, ScoreHolderNode>(
core.select([
{
predicate: src => EntitySelectorAtVariable.is(src.peek(2)),
parser: selector(),
},
{
parser: scoreHolderFakeName,
},
]),
(res, _src, ctx) => {
const ans: ScoreHolderNode = {
type: 'mcfunction:score_holder',
range: res.range,
children: [res],
}
if (core.SymbolNode.is(res)) {
ans.fakeName = res
} else {
ans.selector = res
}
if (amount === 'single' && ans.selector && !ans.selector.single) {
ctx.err.report(localize('mcfunction.parser.entity-selector.multiple-disallowed'), ans)
}
return ans
}
)
}
function symbol(options: core.AllCategory | core.SymbolOptions, terminators: string[] = []): core.InfallibleParser<core.SymbolNode> {
return core.stopBefore(core.symbol(options as never), core.Whitespaces, terminators)
}
function objective(usageType?: core.SymbolUsageType, terminators: string[] = []): core.InfallibleParser<core.SymbolNode> {
return validateLength(
unquotableSymbol({ category: 'objective', usageType }, terminators),
ObjectiveMaxLength,
'mcfunction.parser.objective.too-long'
)
}
const objectiveCriteria: core.InfallibleParser<ObjectiveCriteriaNode> = core.map(
core.any([
core.sequence([
core.stopBefore(core.resourceLocation({ category: 'stat_type', namespacePathSep: '.' }), ':'),
core.failOnEmpty(core.literal(':')),
{
get: res => {
if (core.ResourceLocationNode.is(res.children[0])) {
const category = ObjectiveCriteriaNode.ComplexCategories.get(core.ResourceLocationNode.toString(res.children[0], 'short'))
if (category) {
return core.resourceLocation({ category, namespacePathSep: '.' })
}
}
return core.resourceLocation({ pool: [], allowUnknown: true, namespacePathSep: '.' })
},
},
]),
core.literal(...ObjectiveCriteriaNode.SimpleValues),
]),
res => {
const ans: ObjectiveCriteriaNode = {
type: 'mcfunction:objective_criteria',
range: res.range,
}
if (core.LiteralNode.is(res)) {
ans.simpleValue = res.value
} else {
ans.children = res.children.filter(core.ResourceLocationNode.is) as typeof ans['children']
}
return ans
}
)
export function tag(terminators: string[] = []): core.InfallibleParser<core.SymbolNode> {
return unquotableSymbol('tag', terminators)
}
export function team(usageType?: core.SymbolUsageType, terminators: string[] = []): core.InfallibleParser<core.SymbolNode> {
return unquotableSymbol({ category: 'team', usageType }, terminators)
}
function unquotableSymbol(options: core.AllCategory | core.SymbolOptions, terminators: string[]): core.InfallibleParser<core.SymbolNode> {
return validateUnquotable(symbol(options, terminators))
}
const time: core.InfallibleParser<TimeNode> = core.map(
core.sequence([float(0, undefined), core.optional(core.failOnEmpty(core.literal(...TimeNode.Units)))]),
res => {
const valueNode = res.children.find(core.FloatNode.is)!
const unitNode = res.children.find(core.LiteralNode.is)
const ans: TimeNode = {
type: 'mcfunction:time',
range: res.range,
children: res.children,
value: valueNode.value,
unit: unitNode?.value,
}
return ans
}
)
const unquotedString: core.InfallibleParser<core.StringNode> = core.string({
unquotable: core.BrigadierUnquotableOption,
})
const UuidPattern = /^[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+-[0-9a-f]+$/i
const uuid: core.InfallibleParser<UuidNode> = (src, ctx): UuidNode => {
const ans: UuidNode = {
type: 'mcfunction:uuid',
range: core.Range.create(src),
bits: [0n, 0n],
}
const raw = src.readUntil(' ', '\r', '\n', '\r')
/**
* According to the implementation of Minecraft's UUID parser and Java's `UUID#fromString` method,
* only strings that don't have five parts and strings where any part exceed the maximum Long value are
* considered invalid.
*
* http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/default/src/share/classes/java/util/UUID.java
*/
let isLegal = false
if (raw.match(UuidPattern)) {
try {
const parts = raw.split('-').map(p => BigInt(`0x${p}`))
if (parts.every(p => p <= LongMax)) {
isLegal = true
ans.bits[0] = BigInt.asIntN(64, (parts[0] << 32n) | (parts[1] << 16n) | parts[2])
ans.bits[1] = BigInt.asIntN(64, (parts[3] << 48n) | parts[4])
}
} catch {
// Ignored.
}
}
ans.range.end = src.cursor
if (!isLegal) {
ctx.err.report(localize('mcfunction.parser.uuid.invalid'), ans)
}
return ans
}
function validateLength<T extends core.AstNode & { value: string }>(parser: core.InfallibleParser<T>, maxLength: number, localeKey: `${string}.too-long`): core.InfallibleParser<T> {
return (src, ctx) => {
if (!shouldValidateLength(ctx)) {
return parser(src, ctx)
}
return core.map<T, T>(
parser,
(res, _src, ctx) => {
if (res.value.length > maxLength) {
ctx.err.report(localize(localeKey, maxLength), res)
}
return res
}
)(src, ctx)
}
}
function validateUnquotable(parser: core.InfallibleParser<core.SymbolNode>): core.InfallibleParser<core.SymbolNode> {
return core.map(
parser,
(res, _src, ctx) => {
if (!res.value.match(core.BrigadierUnquotablePattern)) {
ctx.err.report(localize('parser.string.illegal-brigadier', localeQuote(res.value)), res)
}
return res
}
)
}
function vector(options: VectorNode.Options): core.InfallibleParser<VectorNode> {
return (src, ctx): VectorNode => {
const ans: VectorNode = {
type: 'mcfunction:vector',
range: core.Range.create(src),
children: [],
options,
system: CoordinateSystem.World,
}
if (src.peek() === '^') {
ans.system = CoordinateSystem.Local
}
for (let i = 0; i < options.dimension; i++) {
if (i > 0) {
mcf.sep(src, ctx)
}
const coord = options.integersOnly ? coordinate(options.integersOnly)(src, ctx) : coordinate(options.integersOnly)(src, ctx)
ans.children.push(coord as never)
if ((ans.system === CoordinateSystem.Local) !== (coord.notation === '^')) {
ctx.err.report(localize('mcfunction.parser.vector.mixed'), coord)
}
}
if (options.noLocal && ans.system === CoordinateSystem.Local) {
ctx.err.report(localize('mcfunction.parser.vector.local-disallowed'), ans)
}
ans.range.end = src.cursor
return ans
}
} | the_stack |
import { BarcodeGenerator } from "../../../src/barcode/barcode";
import { createElement } from "@syncfusion/ej2-base";
let barcode: BarcodeGenerator;
let ele: HTMLElement;
describe('Barcode Control ', () => {
describe('EAN8 bar testing for all lines check EAN8 barcode', () => {
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
displayText: { alignment: 'Right', position: 'Top' },
type: 'Ean8',
value: '11223344',
mode: 'SVG',
});
barcode.appendTo('#codabar1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "2.47", height: "116.50", x: 10, y: 24 },
1: { width: "2.47", height: "116.50", x: 15, y: 24 },
2: { width: "4.93", height: "103.00", x: 25, y: 24 },
3: { width: "2.47", height: "103.00", x: 35, y: 24 },
4: { width: "4.93", height: "103.00", x: 42, y: 24 },
5: { width: "2.47", height: "103.00", x: 52, y: 24 },
6: { width: "2.47", height: "103.00", x: 59, y: 24 },
7: { width: "4.93", height: "103.00", x: 67, y: 24 },
8: { width: "2.47", height: "103.00", x: 77, y: 24 },
9: { width: "4.93", height: "103.00", x: 84, y: 24 },
10: { width: "2.47", height: "116.50", x: 94, y: 24 },
11: { width: "2.47", height: "116.50", x: 99, y: 24 },
12: { width: "2.47", height: "103.00", x: 106, y: 24 },
13: { width: "2.47", height: "103.00", x: 118, y: 24 },
14: { width: "2.47", height: "103.00", x: 123, y: 24 },
15: { width: "2.47", height: "103.00", x: 136, y: 24 },
16: { width: "2.47", height: "103.00", x: 141, y: 24 },
17: { width: "7.40", height: "103.00", x: 146, y: 24 },
18: { width: "2.47", height: "103.00", x: 158, y: 24 },
19: { width: "7.40", height: "103.00", x: 163, y: 24 },
20: { width: "2.47", height: "116.50", x: 178, y: 24 },
21: { width: "2.47", height: "116.50", x: 183, y: 24 },
};
it('EAN8 bar testing for all lines check EAN8 barcode', (done: Function) => {
let barcode = document.getElementById('codabar1')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect(Math.round(Number(children.children[0].getAttribute('x'))) === 41
&& Math.round(Number(children.children[1].getAttribute('x'))) === 127 &&
(children.children[0] as HTMLElement).style.fontSize === '20px'
&& Math.round(Number(children.children[0].getAttribute('y'))) === 22
&& Math.round(Number(children.children[1].getAttribute('y'))) === 22).toBe(true);
for (var j = 0; j < children.children.length - 2; j++) {
expect(Math.round(Number(children.children[j + 2].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 2].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 2].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 2].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('EAN8 bar testing for all lines check EAN8 barcode invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean8',
value: '11223344223r343',
mode: 'SVG',
});
barcode.appendTo('#codabar1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('EAN8 bar testing for all lines check EAN8 barcode', (done: Function) => {
done();
});
});
describe('EAN8 bar testing for all lines check EAN8 barcode invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean8',
value: '1',
mode: 'SVG',
});
barcode.appendTo('#codabar1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('EAN8 bar testing for all lines check EAN8 barcode', (done: Function) => {
done();
});
});
describe('EAN8 bar testing for all lines check EAN8 barcode invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar1' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean8',
value: '1',
mode: 'SVG',
});
barcode.appendTo('#codabar1');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('EAN8 bar testing for all lines check EAN8 barcode', (done: Function) => {
done();
});
});
describe('EAN13 bar testing for all lines check EAN13 barcode', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar2' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean13',
margin: { left: 20 },
displayText: { alignment: 'Right', position: 'Top' },
value: '9735940564824',
mode: 'SVG',
});
barcode.appendTo('#codabar2');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "1.68", height: "116.50", x: 20, y: 24 },
1: { width: "1.68", height: "116.50", x: 23, y: 24 },
2: { width: "5.05", height: "103.00", x: 28, y: 24 },
3: { width: "3.37", height: "103.00", x: 35, y: 24 },
4: { width: "1.68", height: "103.00", x: 40, y: 24 },
5: { width: "1.68", height: "103.00", x: 49, y: 24 },
6: { width: "5.05", height: "103.00", x: 52, y: 24 },
7: { width: "1.68", height: "103.00", x: 60, y: 24 },
8: { width: "1.68", height: "103.00", x: 67, y: 24 },
9: { width: "3.37", height: "103.00", x: 70, y: 24 },
10: { width: "5.05", height: "103.00", x: 77, y: 24 },
11: { width: "1.68", height: "103.00", x: 84, y: 24 },
12: { width: "3.37", height: "103.00", x: 91, y: 24 },
13: { width: "1.68", height: "103.00", x: 96, y: 24 },
14: { width: "1.68", height: "116.50", x: 101, y: 24 },
15: { width: "1.68", height: "116.50", x: 106, y: 24 },
16: { width: "1.68", height: "103.00", x: 111, y: 24 },
17: { width: "5.05", height: "103.00", x: 116, y: 24 },
18: { width: "1.68", height: "103.00", x: 123, y: 24 },
19: { width: "1.68", height: "103.00", x: 126, y: 24 },
20: { width: "1.68", height: "103.00", x: 134, y: 24 },
21: { width: "5.05", height: "103.00", x: 138, y: 24 },
22: { width: "1.68", height: "103.00", x: 146, y: 24 },
23: { width: "1.68", height: "103.00", x: 151, y: 24 },
24: { width: "3.37", height: "103.00", x: 158, y: 24 },
25: { width: "3.37", height: "103.00", x: 163, y: 24 },
26: { width: "1.68", height: "103.00", x: 170, y: 24 },
27: { width: "5.05", height: "103.00", x: 173, y: 24 },
28: { width: "1.68", height: "116.50", x: 183, y: 24 },
29: { width: "1.68", height: "116.50", x: 187, y: 24 },
};
it('EAN13 bar testing for all lines check EAN13 barcode', (done: Function) => {
let barcode = document.getElementById('codabar2')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect(Math.round(Number(children.children[0].getAttribute('x'))) === 0 && Math.round(Number(children.children[2].getAttribute('y'))) === 22
&& Math.round(Number(children.children[1].getAttribute('y'))) === 22
&& Math.round(Number(children.children[0].getAttribute('y'))) === 22 && (children.children[0] as HTMLElement).style.fontSize === '20px').toBe(true);
for (var j = 0; j < children.children.length - 3; j++) {
expect(Math.round(Number(children.children[j + 3].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 3].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 3].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 3].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('EAN13 bar testing CR issue test case', () => {
beforeAll((): void => {
ele = createElement('div', { id: 'barcode' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean13',
margin: { left: 20 },
displayText: { alignment: 'Right', position: 'Top' },
value: '8020834736939',
mode: 'SVG',
});
barcode.appendTo('#barcode');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('EAN13 bar testing CR issue test case', (done: Function) => {
var barocodeDiv = document.getElementById("barcodecontent")
expect(barocodeDiv.childElementCount === 33).toBe(true);
done();
});
});
describe('EAN13 bar testing for all lines check EAN13 barcode invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar2' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'Ean13',
margin: { left: 20 },
value: '1',
mode: 'SVG',
});
barcode.appendTo('#codabar2');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('EAN13 bar testing for all lines check EAN13 barcode', (done: Function) => {
done();
});
});
describe('upcA bar testing for all lines check upcA barcode', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar3' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'UpcA',
margin: { left: 20 },
displayText: { position: 'Top', alignment: 'Right' },
value: '72527273070',
//value: '043100750246',
mode: 'SVG',
});
barcode.appendTo('#codabar3');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "1.43", height: "116.50", x: 31, y: 24 },
1: { width: "1.43", height: "116.50", x: 34, y: 24 },
2: { width: "4.29", height: "116.50", x: 37, y: 24 },
3: { width: "2.86", height: "116.50", x: 43, y: 24 },
4: { width: "1.43", height: "103.00", x: 49, y: 24 },
5: { width: "2.86", height: "103.00", x: 53, y: 24 },
6: { width: "2.86", height: "103.00", x: 57, y: 24 },
7: { width: "1.43", height: "103.00", x: 64, y: 24 },
8: { width: "1.43", height: "103.00", x: 69, y: 24 },
9: { width: "2.86", height: "103.00", x: 73, y: 24 },
10: { width: "4.29", height: "103.00", x: 77, y: 24 },
11: { width: "2.86", height: "103.00", x: 83, y: 24 },
12: { width: "1.43", height: "103.00", x: 89, y: 24 },
13: { width: "2.86", height: "103.00", x: 93, y: 24 },
14: { width: "1.43", height: "116.50", x: 97, y: 24 },
15: { width: "1.43", height: "116.50", x: 100, y: 24 },
16: { width: "1.43", height: "103.00", x: 103, y: 24 },
17: { width: "1.43", height: "103.00", x: 109, y: 24 },
18: { width: "1.43", height: "103.00", x: 113, y: 24 },
19: { width: "1.43", height: "103.00", x: 120, y: 24 },
20: { width: "4.29", height: "103.00", x: 123, y: 24 },
21: { width: "1.43", height: "103.00", x: 130, y: 24 },
22: { width: "1.43", height: "103.00", x: 133, y: 24 },
23: { width: "1.43", height: "103.00", x: 139, y: 24 },
24: { width: "4.29", height: "103.00", x: 143, y: 24 },
25: { width: "1.43", height: "103.00", x: 150, y: 24 },
26: { width: "1.43", height: "116.50", x: 153, y: 24 },
27: { width: "1.43", height: "116.50", x: 156, y: 24 },
28: { width: "1.43", height: "116.50", x: 163, y: 24 },
29: { width: "1.43", height: "116.50", x: 166, y: 24 },
};
it('upcA bar testing for all lines check upcA barcode', (done: Function) => {
let barcode = document.getElementById('codabar3')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect(Math.round(Number(children.children[1].getAttribute('y'))) === 22
&& Math.round(Number(children.children[0].getAttribute('y'))) === 22
&& Math.round(Number(children.children[0].getAttribute('x'))) === 16
&& (children.children[0] as HTMLElement).style.fontSize === '14.6px').toBe(true);
for (var j = 0; j < children.children.length - 4; j++) {
expect(Math.round(Number(children.children[j + 4].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 4].getAttribute('y'))) === output1[j].y
&& parseFloat((children.children[j + 4].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 4].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('upcA bar testing for all lines check upcA barcode invalid character', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar3' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'UpcA',
margin: { left: 20 },
value: '72527273070a3dd',
//value: '043100750246',
mode: 'SVG',
});
barcode.appendTo('#codabar3');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('upcA bar testing for all lines check upcA barcode', (done: Function) => {
done();
});
});
describe('upcA character rendering issue ', () => {
beforeAll((): void => {
ele = createElement('div', { id: 'codabar3' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '300px', height: '150px',
type: 'UpcA',
value: '024100106851',
displayText: {
},
});
barcode.appendTo('#codabar3');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('upcA character rendering issue', (done: Function) => {
var barcode = document.getElementById("codabar3");
var value = barcode.children[0].children[0].getAttribute("style")
expect(value==="font-size: 20px; font-family: monospace;").toBe(true);
done();
});
});
describe('upcE bar testing for all lines check upcE barcode', () => {
//let barcode: BarcodeGenerator;
//let ele: HTMLElement;
beforeAll((): void => {
ele = createElement('div', { id: 'codabar4' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'UpcE',
displayText: { alignment: 'Right', position: 'Top' },
value: '123456',
mode: 'SVG',
});
barcode.appendTo('#codabar4');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
var output1 = {
0: { width: "2.54", height: "116.50", x: 30, y: 24 },
1: { width: "2.54", height: "116.50", x: 35, y: 24 },
2: { width: "5.07", height: "103.00", x: 40, y: 24 },
3: { width: "5.07", height: "103.00", x: 51, y: 24 },
4: { width: "2.54", height: "103.00", x: 61, y: 24 },
5: { width: "5.07", height: "103.00", x: 68, y: 24 },
6: { width: "10.14", height: "103.00", x: 76, y: 24 },
7: { width: "2.54", height: "103.00", x: 89, y: 24 },
8: { width: "7.61", height: "103.00", x: 96, y: 24 },
9: { width: "2.54", height: "103.00", x: 106, y: 24 },
10: { width: "7.61", height: "103.00", x: 111, y: 24 },
11: { width: "2.54", height: "103.00", x: 124, y: 24 },
12: { width: "2.54", height: "103.00", x: 129, y: 24 },
13: { width: "10.14", height: "103.00", x: 134, y: 24 },
14: { width: "2.54", height: "116.50", x: 147, y: 24 },
15: { width: "2.54", height: "116.50", x: 152, y: 24 },
16: { width: "2.54", height: "116.50", x: 160, y: 24 },
};
it('upcE bar testing for all lines check upcE barcode', (done: Function) => {
let barcode = document.getElementById('codabar4')
let children: HTMLElement = barcode.children[0] as HTMLElement
expect(Math.round(Number(children.children[0].getAttribute('y'))) === 22
&& Math.round(Number(children.children[0].getAttribute('x'))) === 51).toBe(true);
for (var j = 0; j < children.children.length - 2; j++) {
expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j + 1].y
&& parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width
&& parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true);
}
done();
});
});
describe('upcE bar testing for all lines check upcE barcode disable checksum', () => {
beforeAll((): void => {
ele = createElement('div', { id: 'codabar4' });
document.body.appendChild(ele);
barcode = new BarcodeGenerator({
width: '200px', height: '150px',
type: 'UpcE',
enableCheckSum: false,
displayText: { alignment: 'Right', position: 'Top' },
value: '123456',
mode: 'SVG',
});
barcode.appendTo('#codabar4');
});
afterAll((): void => {
barcode.destroy();
ele.remove();
});
it('upcE bar testing for all lines check upcE barcode disable checksum', (done: Function) => {
done();
});
});
}); | the_stack |
import * as $protobuf from "protobufjs";
/** Namespace google. */
export namespace google {
/** Namespace protobuf. */
namespace protobuf {
/** Properties of an Any. */
interface IAny {
/** Any type_url */
type_url?: (string|null);
/** Any value */
value?: (Uint8Array|null);
}
/** Represents an Any. */
class Any implements IAny {
/**
* Constructs a new Any.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IAny);
/** Any type_url. */
public type_url: string;
/** Any value. */
public value: Uint8Array;
/**
* Creates a new Any instance using the specified properties.
* @param [properties] Properties to set
* @returns Any instance
*/
public static create(properties?: google.protobuf.IAny): google.protobuf.Any;
/**
* Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Any message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any;
/**
* Decodes an Any message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any;
/**
* Verifies an Any message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Any message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Any
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Any;
/**
* Creates a plain object from an Any message. Also converts values to other types if specified.
* @param message Any
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Any to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Duration. */
interface IDuration {
/** Duration seconds */
seconds?: (number|Long|null);
/** Duration nanos */
nanos?: (number|null);
}
/** Represents a Duration. */
class Duration implements IDuration {
/**
* Constructs a new Duration.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IDuration);
/** Duration seconds. */
public seconds: (number|Long);
/** Duration nanos. */
public nanos: number;
/**
* Creates a new Duration instance using the specified properties.
* @param [properties] Properties to set
* @returns Duration instance
*/
public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration;
/**
* Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages.
* @param message Duration message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Duration message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration;
/**
* Decodes a Duration message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Duration
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration;
/**
* Verifies a Duration message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Duration message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Duration
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Duration;
/**
* Creates a plain object from a Duration message. Also converts values to other types if specified.
* @param message Duration
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Duration to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Empty. */
interface IEmpty {
}
/** Represents an Empty. */
class Empty implements IEmpty {
/**
* Constructs a new Empty.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IEmpty);
/**
* Creates a new Empty instance using the specified properties.
* @param [properties] Properties to set
* @returns Empty instance
*/
public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty;
/**
* Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @param message Empty message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Empty message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty;
/**
* Decodes an Empty message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty;
/**
* Verifies an Empty message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Empty message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Empty
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Empty;
/**
* Creates a plain object from an Empty message. Also converts values to other types if specified.
* @param message Empty
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Empty to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Timestamp. */
interface ITimestamp {
/** Timestamp seconds */
seconds?: (number|Long|null);
/** Timestamp nanos */
nanos?: (number|null);
}
/** Represents a Timestamp. */
class Timestamp implements ITimestamp {
/**
* Constructs a new Timestamp.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.ITimestamp);
/** Timestamp seconds. */
public seconds: (number|Long);
/** Timestamp nanos. */
public nanos: number;
/**
* Creates a new Timestamp instance using the specified properties.
* @param [properties] Properties to set
* @returns Timestamp instance
*/
public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp;
/**
* Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @param message Timestamp message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @param message Timestamp message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Timestamp message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp;
/**
* Decodes a Timestamp message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp;
/**
* Verifies a Timestamp message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Timestamp message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Timestamp
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp;
/**
* Creates a plain object from a Timestamp message. Also converts values to other types if specified.
* @param message Timestamp
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Timestamp to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
}
/** Namespace ProtobufBroker. */
export namespace ProtobufBroker {
/** Properties of a BrokerSessionMessage. */
interface IBrokerSessionMessage {
/** BrokerSessionMessage session */
session?: (ProtobufBroker.BrokerSessionMessage.ISession|null);
/** BrokerSessionMessage anonymousTradingSession */
anonymousTradingSession?: (ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession|null);
/** BrokerSessionMessage marketId */
marketId?: (number|Long|null);
}
/** Represents a BrokerSessionMessage. */
class BrokerSessionMessage implements IBrokerSessionMessage {
/**
* Constructs a new BrokerSessionMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBrokerSessionMessage);
/** BrokerSessionMessage session. */
public session?: (ProtobufBroker.BrokerSessionMessage.ISession|null);
/** BrokerSessionMessage anonymousTradingSession. */
public anonymousTradingSession?: (ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession|null);
/** BrokerSessionMessage marketId. */
public marketId: (number|Long);
/** BrokerSessionMessage SessionConfig. */
public SessionConfig?: ("session"|"anonymousTradingSession");
/**
* Creates a new BrokerSessionMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns BrokerSessionMessage instance
*/
public static create(properties?: ProtobufBroker.IBrokerSessionMessage): ProtobufBroker.BrokerSessionMessage;
/**
* Encodes the specified BrokerSessionMessage message. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.verify|verify} messages.
* @param message BrokerSessionMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBrokerSessionMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BrokerSessionMessage message, length delimited. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.verify|verify} messages.
* @param message BrokerSessionMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBrokerSessionMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BrokerSessionMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BrokerSessionMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BrokerSessionMessage;
/**
* Decodes a BrokerSessionMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BrokerSessionMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BrokerSessionMessage;
/**
* Verifies a BrokerSessionMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BrokerSessionMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BrokerSessionMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BrokerSessionMessage;
/**
* Creates a plain object from a BrokerSessionMessage message. Also converts values to other types if specified.
* @param message BrokerSessionMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BrokerSessionMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BrokerSessionMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace BrokerSessionMessage {
/** Properties of a Session. */
interface ISession {
/** Session userId */
userId?: (string|null);
/** Session expires */
expires?: (number|Long|null);
/** Session token */
token?: (string|null);
/** Session mfaToken */
mfaToken?: (string|null);
}
/** Represents a Session. */
class Session implements ISession {
/**
* Constructs a new Session.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.BrokerSessionMessage.ISession);
/** Session userId. */
public userId: string;
/** Session expires. */
public expires: (number|Long);
/** Session token. */
public token: string;
/** Session mfaToken. */
public mfaToken: string;
/**
* Creates a new Session instance using the specified properties.
* @param [properties] Properties to set
* @returns Session instance
*/
public static create(properties?: ProtobufBroker.BrokerSessionMessage.ISession): ProtobufBroker.BrokerSessionMessage.Session;
/**
* Encodes the specified Session message. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.BrokerSessionMessage.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Session message, length delimited. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.BrokerSessionMessage.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Session message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BrokerSessionMessage.Session;
/**
* Decodes a Session message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BrokerSessionMessage.Session;
/**
* Verifies a Session message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Session message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Session
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BrokerSessionMessage.Session;
/**
* Creates a plain object from a Session message. Also converts values to other types if specified.
* @param message Session
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BrokerSessionMessage.Session, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Session to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnonymousTradingSession. */
interface IAnonymousTradingSession {
/** AnonymousTradingSession exchange */
exchange?: (string|null);
/** AnonymousTradingSession token */
token?: (string|null);
/** AnonymousTradingSession expiration */
expiration?: (number|Long|null);
}
/** Represents an AnonymousTradingSession. */
class AnonymousTradingSession implements IAnonymousTradingSession {
/**
* Constructs a new AnonymousTradingSession.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession);
/** AnonymousTradingSession exchange. */
public exchange: string;
/** AnonymousTradingSession token. */
public token: string;
/** AnonymousTradingSession expiration. */
public expiration: (number|Long);
/**
* Creates a new AnonymousTradingSession instance using the specified properties.
* @param [properties] Properties to set
* @returns AnonymousTradingSession instance
*/
public static create(properties?: ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession): ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession;
/**
* Encodes the specified AnonymousTradingSession message. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession.verify|verify} messages.
* @param message AnonymousTradingSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnonymousTradingSession message, length delimited. Does not implicitly {@link ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession.verify|verify} messages.
* @param message AnonymousTradingSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.BrokerSessionMessage.IAnonymousTradingSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnonymousTradingSession message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnonymousTradingSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession;
/**
* Decodes an AnonymousTradingSession message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnonymousTradingSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession;
/**
* Verifies an AnonymousTradingSession message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnonymousTradingSession message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnonymousTradingSession
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession;
/**
* Creates a plain object from an AnonymousTradingSession message. Also converts values to other types if specified.
* @param message AnonymousTradingSession
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BrokerSessionMessage.AnonymousTradingSession, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnonymousTradingSession to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a PlaceOrderRequest. */
interface IPlaceOrderRequest {
/** PlaceOrderRequest order */
order?: (ProtobufBroker.IPrivateOrder|null);
/** PlaceOrderRequest closingOrder */
closingOrder?: (ProtobufBroker.IPrivateOrder|null);
}
/** Represents a PlaceOrderRequest. */
class PlaceOrderRequest implements IPlaceOrderRequest {
/**
* Constructs a new PlaceOrderRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPlaceOrderRequest);
/** PlaceOrderRequest order. */
public order?: (ProtobufBroker.IPrivateOrder|null);
/** PlaceOrderRequest closingOrder. */
public closingOrder?: (ProtobufBroker.IPrivateOrder|null);
/**
* Creates a new PlaceOrderRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns PlaceOrderRequest instance
*/
public static create(properties?: ProtobufBroker.IPlaceOrderRequest): ProtobufBroker.PlaceOrderRequest;
/**
* Encodes the specified PlaceOrderRequest message. Does not implicitly {@link ProtobufBroker.PlaceOrderRequest.verify|verify} messages.
* @param message PlaceOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPlaceOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlaceOrderRequest message, length delimited. Does not implicitly {@link ProtobufBroker.PlaceOrderRequest.verify|verify} messages.
* @param message PlaceOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPlaceOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlaceOrderRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlaceOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PlaceOrderRequest;
/**
* Decodes a PlaceOrderRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlaceOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PlaceOrderRequest;
/**
* Verifies a PlaceOrderRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlaceOrderRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlaceOrderRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PlaceOrderRequest;
/**
* Creates a plain object from a PlaceOrderRequest message. Also converts values to other types if specified.
* @param message PlaceOrderRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PlaceOrderRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlaceOrderRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PlaceOrderResult. */
interface IPlaceOrderResult {
/** PlaceOrderResult order */
order?: (ProtobufBroker.IPrivateOrder|null);
/** PlaceOrderResult orderId */
orderId?: (string|null);
}
/** Represents a PlaceOrderResult. */
class PlaceOrderResult implements IPlaceOrderResult {
/**
* Constructs a new PlaceOrderResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPlaceOrderResult);
/** PlaceOrderResult order. */
public order?: (ProtobufBroker.IPrivateOrder|null);
/** PlaceOrderResult orderId. */
public orderId: string;
/**
* Creates a new PlaceOrderResult instance using the specified properties.
* @param [properties] Properties to set
* @returns PlaceOrderResult instance
*/
public static create(properties?: ProtobufBroker.IPlaceOrderResult): ProtobufBroker.PlaceOrderResult;
/**
* Encodes the specified PlaceOrderResult message. Does not implicitly {@link ProtobufBroker.PlaceOrderResult.verify|verify} messages.
* @param message PlaceOrderResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPlaceOrderResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PlaceOrderResult message, length delimited. Does not implicitly {@link ProtobufBroker.PlaceOrderResult.verify|verify} messages.
* @param message PlaceOrderResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPlaceOrderResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PlaceOrderResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PlaceOrderResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PlaceOrderResult;
/**
* Decodes a PlaceOrderResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PlaceOrderResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PlaceOrderResult;
/**
* Verifies a PlaceOrderResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PlaceOrderResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PlaceOrderResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PlaceOrderResult;
/**
* Creates a plain object from a PlaceOrderResult message. Also converts values to other types if specified.
* @param message PlaceOrderResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PlaceOrderResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PlaceOrderResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CancelOrderRequest. */
interface ICancelOrderRequest {
/** CancelOrderRequest orderId */
orderId?: (string|null);
}
/** Represents a CancelOrderRequest. */
class CancelOrderRequest implements ICancelOrderRequest {
/**
* Constructs a new CancelOrderRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ICancelOrderRequest);
/** CancelOrderRequest orderId. */
public orderId: string;
/**
* Creates a new CancelOrderRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns CancelOrderRequest instance
*/
public static create(properties?: ProtobufBroker.ICancelOrderRequest): ProtobufBroker.CancelOrderRequest;
/**
* Encodes the specified CancelOrderRequest message. Does not implicitly {@link ProtobufBroker.CancelOrderRequest.verify|verify} messages.
* @param message CancelOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ICancelOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CancelOrderRequest message, length delimited. Does not implicitly {@link ProtobufBroker.CancelOrderRequest.verify|verify} messages.
* @param message CancelOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ICancelOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CancelOrderRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CancelOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.CancelOrderRequest;
/**
* Decodes a CancelOrderRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CancelOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.CancelOrderRequest;
/**
* Verifies a CancelOrderRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CancelOrderRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CancelOrderRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.CancelOrderRequest;
/**
* Creates a plain object from a CancelOrderRequest message. Also converts values to other types if specified.
* @param message CancelOrderRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.CancelOrderRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CancelOrderRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a CancelOrderResult. */
interface ICancelOrderResult {
/** CancelOrderResult orderId */
orderId?: (string|null);
}
/** Represents a CancelOrderResult. */
class CancelOrderResult implements ICancelOrderResult {
/**
* Constructs a new CancelOrderResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ICancelOrderResult);
/** CancelOrderResult orderId. */
public orderId: string;
/**
* Creates a new CancelOrderResult instance using the specified properties.
* @param [properties] Properties to set
* @returns CancelOrderResult instance
*/
public static create(properties?: ProtobufBroker.ICancelOrderResult): ProtobufBroker.CancelOrderResult;
/**
* Encodes the specified CancelOrderResult message. Does not implicitly {@link ProtobufBroker.CancelOrderResult.verify|verify} messages.
* @param message CancelOrderResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ICancelOrderResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CancelOrderResult message, length delimited. Does not implicitly {@link ProtobufBroker.CancelOrderResult.verify|verify} messages.
* @param message CancelOrderResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ICancelOrderResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CancelOrderResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CancelOrderResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.CancelOrderResult;
/**
* Decodes a CancelOrderResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CancelOrderResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.CancelOrderResult;
/**
* Verifies a CancelOrderResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CancelOrderResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CancelOrderResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.CancelOrderResult;
/**
* Creates a plain object from a CancelOrderResult message. Also converts values to other types if specified.
* @param message CancelOrderResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.CancelOrderResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CancelOrderResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReplaceOrderRequest. */
interface IReplaceOrderRequest {
/** ReplaceOrderRequest orderId */
orderId?: (string|null);
/** ReplaceOrderRequest replacement */
replacement?: (ProtobufBroker.IPrivateOrder|null);
/** ReplaceOrderRequest replacementClosingOrder */
replacementClosingOrder?: (ProtobufBroker.IPrivateOrder|null);
}
/** Represents a ReplaceOrderRequest. */
class ReplaceOrderRequest implements IReplaceOrderRequest {
/**
* Constructs a new ReplaceOrderRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IReplaceOrderRequest);
/** ReplaceOrderRequest orderId. */
public orderId: string;
/** ReplaceOrderRequest replacement. */
public replacement?: (ProtobufBroker.IPrivateOrder|null);
/** ReplaceOrderRequest replacementClosingOrder. */
public replacementClosingOrder?: (ProtobufBroker.IPrivateOrder|null);
/**
* Creates a new ReplaceOrderRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ReplaceOrderRequest instance
*/
public static create(properties?: ProtobufBroker.IReplaceOrderRequest): ProtobufBroker.ReplaceOrderRequest;
/**
* Encodes the specified ReplaceOrderRequest message. Does not implicitly {@link ProtobufBroker.ReplaceOrderRequest.verify|verify} messages.
* @param message ReplaceOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IReplaceOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReplaceOrderRequest message, length delimited. Does not implicitly {@link ProtobufBroker.ReplaceOrderRequest.verify|verify} messages.
* @param message ReplaceOrderRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IReplaceOrderRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReplaceOrderRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReplaceOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.ReplaceOrderRequest;
/**
* Decodes a ReplaceOrderRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReplaceOrderRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.ReplaceOrderRequest;
/**
* Verifies a ReplaceOrderRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReplaceOrderRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReplaceOrderRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.ReplaceOrderRequest;
/**
* Creates a plain object from a ReplaceOrderRequest message. Also converts values to other types if specified.
* @param message ReplaceOrderRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.ReplaceOrderRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReplaceOrderRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClosePositionRequest. */
interface IClosePositionRequest {
/** ClosePositionRequest positionId */
positionId?: (string|null);
}
/** Represents a ClosePositionRequest. */
class ClosePositionRequest implements IClosePositionRequest {
/**
* Constructs a new ClosePositionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IClosePositionRequest);
/** ClosePositionRequest positionId. */
public positionId: string;
/**
* Creates a new ClosePositionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClosePositionRequest instance
*/
public static create(properties?: ProtobufBroker.IClosePositionRequest): ProtobufBroker.ClosePositionRequest;
/**
* Encodes the specified ClosePositionRequest message. Does not implicitly {@link ProtobufBroker.ClosePositionRequest.verify|verify} messages.
* @param message ClosePositionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IClosePositionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClosePositionRequest message, length delimited. Does not implicitly {@link ProtobufBroker.ClosePositionRequest.verify|verify} messages.
* @param message ClosePositionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IClosePositionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClosePositionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClosePositionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.ClosePositionRequest;
/**
* Decodes a ClosePositionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClosePositionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.ClosePositionRequest;
/**
* Verifies a ClosePositionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClosePositionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClosePositionRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.ClosePositionRequest;
/**
* Creates a plain object from a ClosePositionRequest message. Also converts values to other types if specified.
* @param message ClosePositionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.ClosePositionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClosePositionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SettlePositionRequest. */
interface ISettlePositionRequest {
/** SettlePositionRequest positionId */
positionId?: (string|null);
}
/** Represents a SettlePositionRequest. */
class SettlePositionRequest implements ISettlePositionRequest {
/**
* Constructs a new SettlePositionRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ISettlePositionRequest);
/** SettlePositionRequest positionId. */
public positionId: string;
/**
* Creates a new SettlePositionRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns SettlePositionRequest instance
*/
public static create(properties?: ProtobufBroker.ISettlePositionRequest): ProtobufBroker.SettlePositionRequest;
/**
* Encodes the specified SettlePositionRequest message. Does not implicitly {@link ProtobufBroker.SettlePositionRequest.verify|verify} messages.
* @param message SettlePositionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ISettlePositionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SettlePositionRequest message, length delimited. Does not implicitly {@link ProtobufBroker.SettlePositionRequest.verify|verify} messages.
* @param message SettlePositionRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ISettlePositionRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SettlePositionRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SettlePositionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.SettlePositionRequest;
/**
* Decodes a SettlePositionRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SettlePositionRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.SettlePositionRequest;
/**
* Verifies a SettlePositionRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SettlePositionRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SettlePositionRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.SettlePositionRequest;
/**
* Creates a plain object from a SettlePositionRequest message. Also converts values to other types if specified.
* @param message SettlePositionRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.SettlePositionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SettlePositionRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SyncRequest. */
interface ISyncRequest {
}
/** Represents a SyncRequest. */
class SyncRequest implements ISyncRequest {
/**
* Constructs a new SyncRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ISyncRequest);
/**
* Creates a new SyncRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns SyncRequest instance
*/
public static create(properties?: ProtobufBroker.ISyncRequest): ProtobufBroker.SyncRequest;
/**
* Encodes the specified SyncRequest message. Does not implicitly {@link ProtobufBroker.SyncRequest.verify|verify} messages.
* @param message SyncRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ISyncRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SyncRequest message, length delimited. Does not implicitly {@link ProtobufBroker.SyncRequest.verify|verify} messages.
* @param message SyncRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ISyncRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SyncRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SyncRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.SyncRequest;
/**
* Decodes a SyncRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SyncRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.SyncRequest;
/**
* Verifies a SyncRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SyncRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SyncRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.SyncRequest;
/**
* Creates a plain object from a SyncRequest message. Also converts values to other types if specified.
* @param message SyncRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.SyncRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SyncRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BrokerRequest. */
interface IBrokerRequest {
/** BrokerRequest id */
id?: (string|null);
/** BrokerRequest marketId */
marketId?: (number|Long|null);
/** BrokerRequest placeOrderRequest */
placeOrderRequest?: (ProtobufBroker.IPlaceOrderRequest|null);
/** BrokerRequest cancelOrderRequest */
cancelOrderRequest?: (ProtobufBroker.ICancelOrderRequest|null);
/** BrokerRequest replaceOrderRequest */
replaceOrderRequest?: (ProtobufBroker.IReplaceOrderRequest|null);
/** BrokerRequest syncRequest */
syncRequest?: (ProtobufBroker.ISyncRequest|null);
/** BrokerRequest closePositionRequest */
closePositionRequest?: (ProtobufBroker.IClosePositionRequest|null);
/** BrokerRequest settlePositionRequest */
settlePositionRequest?: (ProtobufBroker.ISettlePositionRequest|null);
}
/** Represents a BrokerRequest. */
class BrokerRequest implements IBrokerRequest {
/**
* Constructs a new BrokerRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBrokerRequest);
/** BrokerRequest id. */
public id: string;
/** BrokerRequest marketId. */
public marketId: (number|Long);
/** BrokerRequest placeOrderRequest. */
public placeOrderRequest?: (ProtobufBroker.IPlaceOrderRequest|null);
/** BrokerRequest cancelOrderRequest. */
public cancelOrderRequest?: (ProtobufBroker.ICancelOrderRequest|null);
/** BrokerRequest replaceOrderRequest. */
public replaceOrderRequest?: (ProtobufBroker.IReplaceOrderRequest|null);
/** BrokerRequest syncRequest. */
public syncRequest?: (ProtobufBroker.ISyncRequest|null);
/** BrokerRequest closePositionRequest. */
public closePositionRequest?: (ProtobufBroker.IClosePositionRequest|null);
/** BrokerRequest settlePositionRequest. */
public settlePositionRequest?: (ProtobufBroker.ISettlePositionRequest|null);
/** BrokerRequest Request. */
public Request?: ("placeOrderRequest"|"cancelOrderRequest"|"replaceOrderRequest"|"syncRequest"|"closePositionRequest"|"settlePositionRequest");
/**
* Creates a new BrokerRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns BrokerRequest instance
*/
public static create(properties?: ProtobufBroker.IBrokerRequest): ProtobufBroker.BrokerRequest;
/**
* Encodes the specified BrokerRequest message. Does not implicitly {@link ProtobufBroker.BrokerRequest.verify|verify} messages.
* @param message BrokerRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBrokerRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BrokerRequest message, length delimited. Does not implicitly {@link ProtobufBroker.BrokerRequest.verify|verify} messages.
* @param message BrokerRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBrokerRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BrokerRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BrokerRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BrokerRequest;
/**
* Decodes a BrokerRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BrokerRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BrokerRequest;
/**
* Verifies a BrokerRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BrokerRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BrokerRequest
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BrokerRequest;
/**
* Creates a plain object from a BrokerRequest message. Also converts values to other types if specified.
* @param message BrokerRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BrokerRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BrokerRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OrdersUpdate. */
interface IOrdersUpdate {
/** OrdersUpdate orders */
orders?: (ProtobufBroker.IPrivateOrder[]|null);
}
/** Represents an OrdersUpdate. */
class OrdersUpdate implements IOrdersUpdate {
/**
* Constructs a new OrdersUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IOrdersUpdate);
/** OrdersUpdate orders. */
public orders: ProtobufBroker.IPrivateOrder[];
/**
* Creates a new OrdersUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns OrdersUpdate instance
*/
public static create(properties?: ProtobufBroker.IOrdersUpdate): ProtobufBroker.OrdersUpdate;
/**
* Encodes the specified OrdersUpdate message. Does not implicitly {@link ProtobufBroker.OrdersUpdate.verify|verify} messages.
* @param message OrdersUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IOrdersUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrdersUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.OrdersUpdate.verify|verify} messages.
* @param message OrdersUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IOrdersUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrdersUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrdersUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.OrdersUpdate;
/**
* Decodes an OrdersUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrdersUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.OrdersUpdate;
/**
* Verifies an OrdersUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrdersUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrdersUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.OrdersUpdate;
/**
* Creates a plain object from an OrdersUpdate message. Also converts values to other types if specified.
* @param message OrdersUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.OrdersUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrdersUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TradesUpdate. */
interface ITradesUpdate {
/** TradesUpdate trades */
trades?: (ProtobufBroker.IPrivateTrade[]|null);
}
/** Represents a TradesUpdate. */
class TradesUpdate implements ITradesUpdate {
/**
* Constructs a new TradesUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ITradesUpdate);
/** TradesUpdate trades. */
public trades: ProtobufBroker.IPrivateTrade[];
/**
* Creates a new TradesUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns TradesUpdate instance
*/
public static create(properties?: ProtobufBroker.ITradesUpdate): ProtobufBroker.TradesUpdate;
/**
* Encodes the specified TradesUpdate message. Does not implicitly {@link ProtobufBroker.TradesUpdate.verify|verify} messages.
* @param message TradesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ITradesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TradesUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.TradesUpdate.verify|verify} messages.
* @param message TradesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ITradesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TradesUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TradesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.TradesUpdate;
/**
* Decodes a TradesUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TradesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.TradesUpdate;
/**
* Verifies a TradesUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TradesUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TradesUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.TradesUpdate;
/**
* Creates a plain object from a TradesUpdate message. Also converts values to other types if specified.
* @param message TradesUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.TradesUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TradesUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PositionsUpdate. */
interface IPositionsUpdate {
/** PositionsUpdate positions */
positions?: (ProtobufBroker.IPrivatePosition[]|null);
}
/** Represents a PositionsUpdate. */
class PositionsUpdate implements IPositionsUpdate {
/**
* Constructs a new PositionsUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPositionsUpdate);
/** PositionsUpdate positions. */
public positions: ProtobufBroker.IPrivatePosition[];
/**
* Creates a new PositionsUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PositionsUpdate instance
*/
public static create(properties?: ProtobufBroker.IPositionsUpdate): ProtobufBroker.PositionsUpdate;
/**
* Encodes the specified PositionsUpdate message. Does not implicitly {@link ProtobufBroker.PositionsUpdate.verify|verify} messages.
* @param message PositionsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPositionsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PositionsUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.PositionsUpdate.verify|verify} messages.
* @param message PositionsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPositionsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PositionsUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PositionsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PositionsUpdate;
/**
* Decodes a PositionsUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PositionsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PositionsUpdate;
/**
* Verifies a PositionsUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PositionsUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PositionsUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PositionsUpdate;
/**
* Creates a plain object from a PositionsUpdate message. Also converts values to other types if specified.
* @param message PositionsUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PositionsUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PositionsUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BalancesUpdate. */
interface IBalancesUpdate {
/** BalancesUpdate balances */
balances?: (ProtobufBroker.IBalances[]|null);
/** BalancesUpdate total */
total?: (ProtobufBroker.IBalances[]|null);
}
/** Represents a BalancesUpdate. */
class BalancesUpdate implements IBalancesUpdate {
/**
* Constructs a new BalancesUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBalancesUpdate);
/** BalancesUpdate balances. */
public balances: ProtobufBroker.IBalances[];
/** BalancesUpdate total. */
public total: ProtobufBroker.IBalances[];
/**
* Creates a new BalancesUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns BalancesUpdate instance
*/
public static create(properties?: ProtobufBroker.IBalancesUpdate): ProtobufBroker.BalancesUpdate;
/**
* Encodes the specified BalancesUpdate message. Does not implicitly {@link ProtobufBroker.BalancesUpdate.verify|verify} messages.
* @param message BalancesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBalancesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BalancesUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.BalancesUpdate.verify|verify} messages.
* @param message BalancesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBalancesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BalancesUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BalancesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BalancesUpdate;
/**
* Decodes a BalancesUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BalancesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BalancesUpdate;
/**
* Verifies a BalancesUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BalancesUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BalancesUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BalancesUpdate;
/**
* Creates a plain object from a BalancesUpdate message. Also converts values to other types if specified.
* @param message BalancesUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BalancesUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BalancesUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a LedgersUpdate. */
interface ILedgersUpdate {
/** LedgersUpdate ledgers */
ledgers?: (ProtobufBroker.IPrivateLedger[]|null);
}
/** Represents a LedgersUpdate. */
class LedgersUpdate implements ILedgersUpdate {
/**
* Constructs a new LedgersUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ILedgersUpdate);
/** LedgersUpdate ledgers. */
public ledgers: ProtobufBroker.IPrivateLedger[];
/**
* Creates a new LedgersUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns LedgersUpdate instance
*/
public static create(properties?: ProtobufBroker.ILedgersUpdate): ProtobufBroker.LedgersUpdate;
/**
* Encodes the specified LedgersUpdate message. Does not implicitly {@link ProtobufBroker.LedgersUpdate.verify|verify} messages.
* @param message LedgersUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ILedgersUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified LedgersUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.LedgersUpdate.verify|verify} messages.
* @param message LedgersUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ILedgersUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a LedgersUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns LedgersUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.LedgersUpdate;
/**
* Decodes a LedgersUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns LedgersUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.LedgersUpdate;
/**
* Verifies a LedgersUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a LedgersUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns LedgersUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.LedgersUpdate;
/**
* Creates a plain object from a LedgersUpdate message. Also converts values to other types if specified.
* @param message LedgersUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.LedgersUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this LedgersUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a RequestResolutionUpdate. */
interface IRequestResolutionUpdate {
/** RequestResolutionUpdate id */
id?: (string|null);
/** RequestResolutionUpdate error */
error?: (number|null);
/** RequestResolutionUpdate message */
message?: (string|null);
/** RequestResolutionUpdate errorV2 */
errorV2?: (ProtobufBroker.IError|null);
/** RequestResolutionUpdate placeOrderResult */
placeOrderResult?: (ProtobufBroker.IPlaceOrderResult|null);
/** RequestResolutionUpdate cancelOrderResult */
cancelOrderResult?: (ProtobufBroker.ICancelOrderResult|null);
}
/** Represents a RequestResolutionUpdate. */
class RequestResolutionUpdate implements IRequestResolutionUpdate {
/**
* Constructs a new RequestResolutionUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IRequestResolutionUpdate);
/** RequestResolutionUpdate id. */
public id: string;
/** RequestResolutionUpdate error. */
public error: number;
/** RequestResolutionUpdate message. */
public message: string;
/** RequestResolutionUpdate errorV2. */
public errorV2?: (ProtobufBroker.IError|null);
/** RequestResolutionUpdate placeOrderResult. */
public placeOrderResult?: (ProtobufBroker.IPlaceOrderResult|null);
/** RequestResolutionUpdate cancelOrderResult. */
public cancelOrderResult?: (ProtobufBroker.ICancelOrderResult|null);
/** RequestResolutionUpdate Result. */
public Result?: ("placeOrderResult"|"cancelOrderResult");
/**
* Creates a new RequestResolutionUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns RequestResolutionUpdate instance
*/
public static create(properties?: ProtobufBroker.IRequestResolutionUpdate): ProtobufBroker.RequestResolutionUpdate;
/**
* Encodes the specified RequestResolutionUpdate message. Does not implicitly {@link ProtobufBroker.RequestResolutionUpdate.verify|verify} messages.
* @param message RequestResolutionUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IRequestResolutionUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RequestResolutionUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.RequestResolutionUpdate.verify|verify} messages.
* @param message RequestResolutionUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IRequestResolutionUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RequestResolutionUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RequestResolutionUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.RequestResolutionUpdate;
/**
* Decodes a RequestResolutionUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RequestResolutionUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.RequestResolutionUpdate;
/**
* Verifies a RequestResolutionUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RequestResolutionUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RequestResolutionUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.RequestResolutionUpdate;
/**
* Creates a plain object from a RequestResolutionUpdate message. Also converts values to other types if specified.
* @param message RequestResolutionUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.RequestResolutionUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RequestResolutionUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnonymousSessionStatusUpdate. */
interface IAnonymousSessionStatusUpdate {
/** AnonymousSessionStatusUpdate expiration */
expiration?: (number|Long|null);
/** AnonymousSessionStatusUpdate token */
token?: (string|null);
}
/** Represents an AnonymousSessionStatusUpdate. */
class AnonymousSessionStatusUpdate implements IAnonymousSessionStatusUpdate {
/**
* Constructs a new AnonymousSessionStatusUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IAnonymousSessionStatusUpdate);
/** AnonymousSessionStatusUpdate expiration. */
public expiration: (number|Long);
/** AnonymousSessionStatusUpdate token. */
public token: string;
/**
* Creates a new AnonymousSessionStatusUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns AnonymousSessionStatusUpdate instance
*/
public static create(properties?: ProtobufBroker.IAnonymousSessionStatusUpdate): ProtobufBroker.AnonymousSessionStatusUpdate;
/**
* Encodes the specified AnonymousSessionStatusUpdate message. Does not implicitly {@link ProtobufBroker.AnonymousSessionStatusUpdate.verify|verify} messages.
* @param message AnonymousSessionStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IAnonymousSessionStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnonymousSessionStatusUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.AnonymousSessionStatusUpdate.verify|verify} messages.
* @param message AnonymousSessionStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IAnonymousSessionStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnonymousSessionStatusUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnonymousSessionStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.AnonymousSessionStatusUpdate;
/**
* Decodes an AnonymousSessionStatusUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnonymousSessionStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.AnonymousSessionStatusUpdate;
/**
* Verifies an AnonymousSessionStatusUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnonymousSessionStatusUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnonymousSessionStatusUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.AnonymousSessionStatusUpdate;
/**
* Creates a plain object from an AnonymousSessionStatusUpdate message. Also converts values to other types if specified.
* @param message AnonymousSessionStatusUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.AnonymousSessionStatusUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnonymousSessionStatusUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SessionStatusUpdate. */
interface ISessionStatusUpdate {
/** SessionStatusUpdate initialized */
initialized?: (boolean|null);
/** SessionStatusUpdate syncing */
syncing?: (boolean|null);
/** SessionStatusUpdate lastSyncTime */
lastSyncTime?: (number|Long|null);
/** SessionStatusUpdate syncError */
syncError?: (number|null);
}
/** Represents a SessionStatusUpdate. */
class SessionStatusUpdate implements ISessionStatusUpdate {
/**
* Constructs a new SessionStatusUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.ISessionStatusUpdate);
/** SessionStatusUpdate initialized. */
public initialized: boolean;
/** SessionStatusUpdate syncing. */
public syncing: boolean;
/** SessionStatusUpdate lastSyncTime. */
public lastSyncTime: (number|Long);
/** SessionStatusUpdate syncError. */
public syncError: number;
/**
* Creates a new SessionStatusUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns SessionStatusUpdate instance
*/
public static create(properties?: ProtobufBroker.ISessionStatusUpdate): ProtobufBroker.SessionStatusUpdate;
/**
* Encodes the specified SessionStatusUpdate message. Does not implicitly {@link ProtobufBroker.SessionStatusUpdate.verify|verify} messages.
* @param message SessionStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.ISessionStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SessionStatusUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.SessionStatusUpdate.verify|verify} messages.
* @param message SessionStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.ISessionStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SessionStatusUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SessionStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.SessionStatusUpdate;
/**
* Decodes a SessionStatusUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SessionStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.SessionStatusUpdate;
/**
* Verifies a SessionStatusUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SessionStatusUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SessionStatusUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.SessionStatusUpdate;
/**
* Creates a plain object from a SessionStatusUpdate message. Also converts values to other types if specified.
* @param message SessionStatusUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.SessionStatusUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SessionStatusUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PermissionsUpdate. */
interface IPermissionsUpdate {
/** PermissionsUpdate orderTypes */
orderTypes?: (ProtobufBroker.PrivateOrder.Type[]|null);
/** PermissionsUpdate fundingTypes */
fundingTypes?: (ProtobufBroker.FundingType[]|null);
/** PermissionsUpdate agreements */
agreements?: (ProtobufBroker.PermissionsUpdate.IAgreement[]|null);
/** PermissionsUpdate leverageLevels */
leverageLevels?: (ProtobufBroker.PermissionsUpdate.ILeverageLevels|null);
/** PermissionsUpdate supportsOrderExpiry */
supportsOrderExpiry?: (boolean|null);
}
/** Represents a PermissionsUpdate. */
class PermissionsUpdate implements IPermissionsUpdate {
/**
* Constructs a new PermissionsUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPermissionsUpdate);
/** PermissionsUpdate orderTypes. */
public orderTypes: ProtobufBroker.PrivateOrder.Type[];
/** PermissionsUpdate fundingTypes. */
public fundingTypes: ProtobufBroker.FundingType[];
/** PermissionsUpdate agreements. */
public agreements: ProtobufBroker.PermissionsUpdate.IAgreement[];
/** PermissionsUpdate leverageLevels. */
public leverageLevels?: (ProtobufBroker.PermissionsUpdate.ILeverageLevels|null);
/** PermissionsUpdate supportsOrderExpiry. */
public supportsOrderExpiry: boolean;
/**
* Creates a new PermissionsUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PermissionsUpdate instance
*/
public static create(properties?: ProtobufBroker.IPermissionsUpdate): ProtobufBroker.PermissionsUpdate;
/**
* Encodes the specified PermissionsUpdate message. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.verify|verify} messages.
* @param message PermissionsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPermissionsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PermissionsUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.verify|verify} messages.
* @param message PermissionsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPermissionsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PermissionsUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PermissionsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PermissionsUpdate;
/**
* Decodes a PermissionsUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PermissionsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PermissionsUpdate;
/**
* Verifies a PermissionsUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PermissionsUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PermissionsUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PermissionsUpdate;
/**
* Creates a plain object from a PermissionsUpdate message. Also converts values to other types if specified.
* @param message PermissionsUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PermissionsUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PermissionsUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PermissionsUpdate {
/** Properties of an Agreement. */
interface IAgreement {
/** Agreement key */
key?: (string|null);
/** Agreement body */
body?: (string|null);
}
/** Represents an Agreement. */
class Agreement implements IAgreement {
/**
* Constructs a new Agreement.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.PermissionsUpdate.IAgreement);
/** Agreement key. */
public key: string;
/** Agreement body. */
public body: string;
/**
* Creates a new Agreement instance using the specified properties.
* @param [properties] Properties to set
* @returns Agreement instance
*/
public static create(properties?: ProtobufBroker.PermissionsUpdate.IAgreement): ProtobufBroker.PermissionsUpdate.Agreement;
/**
* Encodes the specified Agreement message. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.Agreement.verify|verify} messages.
* @param message Agreement message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.PermissionsUpdate.IAgreement, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Agreement message, length delimited. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.Agreement.verify|verify} messages.
* @param message Agreement message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.PermissionsUpdate.IAgreement, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Agreement message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Agreement
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PermissionsUpdate.Agreement;
/**
* Decodes an Agreement message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Agreement
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PermissionsUpdate.Agreement;
/**
* Verifies an Agreement message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Agreement message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Agreement
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PermissionsUpdate.Agreement;
/**
* Creates a plain object from an Agreement message. Also converts values to other types if specified.
* @param message Agreement
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PermissionsUpdate.Agreement, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Agreement to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a LeverageLevels. */
interface ILeverageLevels {
/** LeverageLevels buy */
buy?: (string[]|null);
/** LeverageLevels sell */
sell?: (string[]|null);
}
/** Represents a LeverageLevels. */
class LeverageLevels implements ILeverageLevels {
/**
* Constructs a new LeverageLevels.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.PermissionsUpdate.ILeverageLevels);
/** LeverageLevels buy. */
public buy: string[];
/** LeverageLevels sell. */
public sell: string[];
/**
* Creates a new LeverageLevels instance using the specified properties.
* @param [properties] Properties to set
* @returns LeverageLevels instance
*/
public static create(properties?: ProtobufBroker.PermissionsUpdate.ILeverageLevels): ProtobufBroker.PermissionsUpdate.LeverageLevels;
/**
* Encodes the specified LeverageLevels message. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.LeverageLevels.verify|verify} messages.
* @param message LeverageLevels message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.PermissionsUpdate.ILeverageLevels, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified LeverageLevels message, length delimited. Does not implicitly {@link ProtobufBroker.PermissionsUpdate.LeverageLevels.verify|verify} messages.
* @param message LeverageLevels message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.PermissionsUpdate.ILeverageLevels, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a LeverageLevels message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns LeverageLevels
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PermissionsUpdate.LeverageLevels;
/**
* Decodes a LeverageLevels message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns LeverageLevels
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PermissionsUpdate.LeverageLevels;
/**
* Verifies a LeverageLevels message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a LeverageLevels message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns LeverageLevels
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PermissionsUpdate.LeverageLevels;
/**
* Creates a plain object from a LeverageLevels message. Also converts values to other types if specified.
* @param message LeverageLevels
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PermissionsUpdate.LeverageLevels, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this LeverageLevels to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a APIAccessorStatusUpdate. */
interface IAPIAccessorStatusUpdate {
/** APIAccessorStatusUpdate hasAccess */
hasAccess?: (boolean|null);
/** APIAccessorStatusUpdate status */
status?: (number|null);
/** APIAccessorStatusUpdate statusString */
statusString?: (string|null);
}
/** Represents a APIAccessorStatusUpdate. */
class APIAccessorStatusUpdate implements IAPIAccessorStatusUpdate {
/**
* Constructs a new APIAccessorStatusUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IAPIAccessorStatusUpdate);
/** APIAccessorStatusUpdate hasAccess. */
public hasAccess: boolean;
/** APIAccessorStatusUpdate status. */
public status: number;
/** APIAccessorStatusUpdate statusString. */
public statusString: string;
/**
* Creates a new APIAccessorStatusUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns APIAccessorStatusUpdate instance
*/
public static create(properties?: ProtobufBroker.IAPIAccessorStatusUpdate): ProtobufBroker.APIAccessorStatusUpdate;
/**
* Encodes the specified APIAccessorStatusUpdate message. Does not implicitly {@link ProtobufBroker.APIAccessorStatusUpdate.verify|verify} messages.
* @param message APIAccessorStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IAPIAccessorStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified APIAccessorStatusUpdate message, length delimited. Does not implicitly {@link ProtobufBroker.APIAccessorStatusUpdate.verify|verify} messages.
* @param message APIAccessorStatusUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IAPIAccessorStatusUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a APIAccessorStatusUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns APIAccessorStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.APIAccessorStatusUpdate;
/**
* Decodes a APIAccessorStatusUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns APIAccessorStatusUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.APIAccessorStatusUpdate;
/**
* Verifies a APIAccessorStatusUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a APIAccessorStatusUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns APIAccessorStatusUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.APIAccessorStatusUpdate;
/**
* Creates a plain object from a APIAccessorStatusUpdate message. Also converts values to other types if specified.
* @param message APIAccessorStatusUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.APIAccessorStatusUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this APIAccessorStatusUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BrokerUpdateMessage. */
interface IBrokerUpdateMessage {
/** BrokerUpdateMessage marketId */
marketId?: (number|Long|null);
/** BrokerUpdateMessage ordersUpdate */
ordersUpdate?: (ProtobufBroker.IOrdersUpdate|null);
/** BrokerUpdateMessage tradesUpdate */
tradesUpdate?: (ProtobufBroker.ITradesUpdate|null);
/** BrokerUpdateMessage balancesUpdate */
balancesUpdate?: (ProtobufBroker.IBalancesUpdate|null);
/** BrokerUpdateMessage positionsUpdate */
positionsUpdate?: (ProtobufBroker.IPositionsUpdate|null);
/** BrokerUpdateMessage ledgersUpdate */
ledgersUpdate?: (ProtobufBroker.ILedgersUpdate|null);
/** BrokerUpdateMessage requestResolutionUpdate */
requestResolutionUpdate?: (ProtobufBroker.IRequestResolutionUpdate|null);
/** BrokerUpdateMessage anonymousSessionStatusUpdate */
anonymousSessionStatusUpdate?: (ProtobufBroker.IAnonymousSessionStatusUpdate|null);
/** BrokerUpdateMessage permissionsUpdate */
permissionsUpdate?: (ProtobufBroker.IPermissionsUpdate|null);
/** BrokerUpdateMessage sessionStatusUpdate */
sessionStatusUpdate?: (ProtobufBroker.ISessionStatusUpdate|null);
/** BrokerUpdateMessage apiAccessorStatusUpdate */
apiAccessorStatusUpdate?: (ProtobufBroker.IAPIAccessorStatusUpdate|null);
/** BrokerUpdateMessage authenticationResult */
authenticationResult?: (ProtobufStream.IAuthenticationResult|null);
/** BrokerUpdateMessage subscriptionResult */
subscriptionResult?: (ProtobufStream.ISubscriptionResult|null);
/** BrokerUpdateMessage webAuthenticationResult */
webAuthenticationResult?: (ProtobufClient.IWebAuthenticationResult|null);
}
/** Represents a BrokerUpdateMessage. */
class BrokerUpdateMessage implements IBrokerUpdateMessage {
/**
* Constructs a new BrokerUpdateMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBrokerUpdateMessage);
/** BrokerUpdateMessage marketId. */
public marketId: (number|Long);
/** BrokerUpdateMessage ordersUpdate. */
public ordersUpdate?: (ProtobufBroker.IOrdersUpdate|null);
/** BrokerUpdateMessage tradesUpdate. */
public tradesUpdate?: (ProtobufBroker.ITradesUpdate|null);
/** BrokerUpdateMessage balancesUpdate. */
public balancesUpdate?: (ProtobufBroker.IBalancesUpdate|null);
/** BrokerUpdateMessage positionsUpdate. */
public positionsUpdate?: (ProtobufBroker.IPositionsUpdate|null);
/** BrokerUpdateMessage ledgersUpdate. */
public ledgersUpdate?: (ProtobufBroker.ILedgersUpdate|null);
/** BrokerUpdateMessage requestResolutionUpdate. */
public requestResolutionUpdate?: (ProtobufBroker.IRequestResolutionUpdate|null);
/** BrokerUpdateMessage anonymousSessionStatusUpdate. */
public anonymousSessionStatusUpdate?: (ProtobufBroker.IAnonymousSessionStatusUpdate|null);
/** BrokerUpdateMessage permissionsUpdate. */
public permissionsUpdate?: (ProtobufBroker.IPermissionsUpdate|null);
/** BrokerUpdateMessage sessionStatusUpdate. */
public sessionStatusUpdate?: (ProtobufBroker.ISessionStatusUpdate|null);
/** BrokerUpdateMessage apiAccessorStatusUpdate. */
public apiAccessorStatusUpdate?: (ProtobufBroker.IAPIAccessorStatusUpdate|null);
/** BrokerUpdateMessage authenticationResult. */
public authenticationResult?: (ProtobufStream.IAuthenticationResult|null);
/** BrokerUpdateMessage subscriptionResult. */
public subscriptionResult?: (ProtobufStream.ISubscriptionResult|null);
/** BrokerUpdateMessage webAuthenticationResult. */
public webAuthenticationResult?: (ProtobufClient.IWebAuthenticationResult|null);
/** BrokerUpdateMessage Update. */
public Update?: ("ordersUpdate"|"tradesUpdate"|"balancesUpdate"|"positionsUpdate"|"ledgersUpdate"|"requestResolutionUpdate"|"anonymousSessionStatusUpdate"|"permissionsUpdate"|"sessionStatusUpdate"|"apiAccessorStatusUpdate"|"authenticationResult"|"subscriptionResult"|"webAuthenticationResult");
/**
* Creates a new BrokerUpdateMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns BrokerUpdateMessage instance
*/
public static create(properties?: ProtobufBroker.IBrokerUpdateMessage): ProtobufBroker.BrokerUpdateMessage;
/**
* Encodes the specified BrokerUpdateMessage message. Does not implicitly {@link ProtobufBroker.BrokerUpdateMessage.verify|verify} messages.
* @param message BrokerUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBrokerUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BrokerUpdateMessage message, length delimited. Does not implicitly {@link ProtobufBroker.BrokerUpdateMessage.verify|verify} messages.
* @param message BrokerUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBrokerUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BrokerUpdateMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BrokerUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.BrokerUpdateMessage;
/**
* Decodes a BrokerUpdateMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BrokerUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.BrokerUpdateMessage;
/**
* Verifies a BrokerUpdateMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BrokerUpdateMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BrokerUpdateMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.BrokerUpdateMessage;
/**
* Creates a plain object from a BrokerUpdateMessage message. Also converts values to other types if specified.
* @param message BrokerUpdateMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.BrokerUpdateMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BrokerUpdateMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Error. */
interface IError {
/** Error kind */
kind?: (ProtobufBroker.Error.Kind|null);
/** Error code */
code?: (number|Long|null);
/** Error message */
message?: (string|null);
/** Error details */
details?: (google.protobuf.IAny[]|null);
}
/** Represents an Error. */
class Error implements IError {
/**
* Constructs a new Error.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IError);
/** Error kind. */
public kind: ProtobufBroker.Error.Kind;
/** Error code. */
public code: (number|Long);
/** Error message. */
public message: string;
/** Error details. */
public details: google.protobuf.IAny[];
/**
* Creates a new Error instance using the specified properties.
* @param [properties] Properties to set
* @returns Error instance
*/
public static create(properties?: ProtobufBroker.IError): ProtobufBroker.Error;
/**
* Encodes the specified Error message. Does not implicitly {@link ProtobufBroker.Error.verify|verify} messages.
* @param message Error message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Error message, length delimited. Does not implicitly {@link ProtobufBroker.Error.verify|verify} messages.
* @param message Error message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Error message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.Error;
/**
* Decodes an Error message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Error
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.Error;
/**
* Verifies an Error message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Error message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Error
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.Error;
/**
* Creates a plain object from an Error message. Also converts values to other types if specified.
* @param message Error
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.Error, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Error to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Error {
/** Kind enum. */
enum Kind {
KIND_UNKNOWN = 0,
KIND_INTERNAL = 1,
KIND_TRANSIENT = 2,
KIND_ABORTED = 3,
KIND_IO = 4,
KIND_PERMISSION_DENIED = 5,
KIND_INVALID_OPERATION = 6,
KIND_INVALID_ARGUMENT = 7,
KIND_INVALID_REQUEST = 8
}
}
/** FundingType enum. */
enum FundingType {
Spot = 0,
Margin = 1,
Staking = 2
}
/** Properties of a PrivateOrder. */
interface IPrivateOrder {
/** PrivateOrder id */
id?: (string|null);
/** PrivateOrder time */
time?: (number|Long|null);
/** PrivateOrder side */
side?: (number|null);
/** PrivateOrder type */
type?: (ProtobufBroker.PrivateOrder.Type|null);
/** PrivateOrder fundingType */
fundingType?: (ProtobufBroker.FundingType|null);
/** PrivateOrder priceParams */
priceParams?: (ProtobufBroker.PrivateOrder.IPriceParam[]|null);
/** PrivateOrder amountParamString */
amountParamString?: (string|null);
/** PrivateOrder amountFilledString */
amountFilledString?: (string|null);
/** PrivateOrder leverage */
leverage?: (string|null);
/** PrivateOrder currentStopString */
currentStopString?: (string|null);
/** PrivateOrder initialStopString */
initialStopString?: (string|null);
/** PrivateOrder startTime */
startTime?: (number|Long|null);
/** PrivateOrder expireTime */
expireTime?: (number|Long|null);
/** PrivateOrder rate */
rate?: (number|null);
/** PrivateOrder hasClosingOrder */
hasClosingOrder?: (boolean|null);
/** PrivateOrder closingOrderType */
closingOrderType?: (ProtobufBroker.PrivateOrder.Type|null);
/** PrivateOrder closingOrderPriceParams */
closingOrderPriceParams?: (ProtobufBroker.PrivateOrder.IPriceParam[]|null);
/** PrivateOrder feeCurrency */
feeCurrency?: (ProtobufBroker.PrivateOrder.CurrencyPairSide|null);
/** PrivateOrder postOnly */
postOnly?: (boolean|null);
/** PrivateOrder groupId */
groupId?: (string|null);
/** PrivateOrder fillOrKill */
fillOrKill?: (boolean|null);
/** PrivateOrder immediateOrCancel */
immediateOrCancel?: (boolean|null);
}
/** Represents a PrivateOrder. */
class PrivateOrder implements IPrivateOrder {
/**
* Constructs a new PrivateOrder.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPrivateOrder);
/** PrivateOrder id. */
public id: string;
/** PrivateOrder time. */
public time: (number|Long);
/** PrivateOrder side. */
public side: number;
/** PrivateOrder type. */
public type: ProtobufBroker.PrivateOrder.Type;
/** PrivateOrder fundingType. */
public fundingType: ProtobufBroker.FundingType;
/** PrivateOrder priceParams. */
public priceParams: ProtobufBroker.PrivateOrder.IPriceParam[];
/** PrivateOrder amountParamString. */
public amountParamString: string;
/** PrivateOrder amountFilledString. */
public amountFilledString: string;
/** PrivateOrder leverage. */
public leverage: string;
/** PrivateOrder currentStopString. */
public currentStopString: string;
/** PrivateOrder initialStopString. */
public initialStopString: string;
/** PrivateOrder startTime. */
public startTime: (number|Long);
/** PrivateOrder expireTime. */
public expireTime: (number|Long);
/** PrivateOrder rate. */
public rate: number;
/** PrivateOrder hasClosingOrder. */
public hasClosingOrder: boolean;
/** PrivateOrder closingOrderType. */
public closingOrderType: ProtobufBroker.PrivateOrder.Type;
/** PrivateOrder closingOrderPriceParams. */
public closingOrderPriceParams: ProtobufBroker.PrivateOrder.IPriceParam[];
/** PrivateOrder feeCurrency. */
public feeCurrency: ProtobufBroker.PrivateOrder.CurrencyPairSide;
/** PrivateOrder postOnly. */
public postOnly: boolean;
/** PrivateOrder groupId. */
public groupId: string;
/** PrivateOrder fillOrKill. */
public fillOrKill: boolean;
/** PrivateOrder immediateOrCancel. */
public immediateOrCancel: boolean;
/**
* Creates a new PrivateOrder instance using the specified properties.
* @param [properties] Properties to set
* @returns PrivateOrder instance
*/
public static create(properties?: ProtobufBroker.IPrivateOrder): ProtobufBroker.PrivateOrder;
/**
* Encodes the specified PrivateOrder message. Does not implicitly {@link ProtobufBroker.PrivateOrder.verify|verify} messages.
* @param message PrivateOrder message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPrivateOrder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PrivateOrder message, length delimited. Does not implicitly {@link ProtobufBroker.PrivateOrder.verify|verify} messages.
* @param message PrivateOrder message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPrivateOrder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PrivateOrder message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PrivateOrder
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PrivateOrder;
/**
* Decodes a PrivateOrder message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PrivateOrder
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PrivateOrder;
/**
* Verifies a PrivateOrder message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PrivateOrder message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PrivateOrder
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PrivateOrder;
/**
* Creates a plain object from a PrivateOrder message. Also converts values to other types if specified.
* @param message PrivateOrder
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PrivateOrder, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PrivateOrder to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PrivateOrder {
/** Type enum. */
enum Type {
Market = 0,
Limit = 1,
StopLoss = 2,
StopLossLimit = 3,
TakeProfit = 4,
TakeProfitLimit = 5,
StopLossTakeProfit = 6,
StopLossTakeProfitLimit = 7,
TrailingStopLoss = 8,
TrailingStopLossLimit = 9,
StopLossAndLimit = 10,
FillOrKill = 11,
SettlePosition = 12
}
/** PriceParamType enum. */
enum PriceParamType {
AbsoluteValue = 0,
OffsetValue = 1,
PrecentageOffsetValue = 2
}
/** Properties of a PriceParam. */
interface IPriceParam {
/** PriceParam valueString */
valueString?: (string|null);
/** PriceParam type */
type?: (ProtobufBroker.PrivateOrder.PriceParamType|null);
}
/** Represents a PriceParam. */
class PriceParam implements IPriceParam {
/**
* Constructs a new PriceParam.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.PrivateOrder.IPriceParam);
/** PriceParam valueString. */
public valueString: string;
/** PriceParam type. */
public type: ProtobufBroker.PrivateOrder.PriceParamType;
/**
* Creates a new PriceParam instance using the specified properties.
* @param [properties] Properties to set
* @returns PriceParam instance
*/
public static create(properties?: ProtobufBroker.PrivateOrder.IPriceParam): ProtobufBroker.PrivateOrder.PriceParam;
/**
* Encodes the specified PriceParam message. Does not implicitly {@link ProtobufBroker.PrivateOrder.PriceParam.verify|verify} messages.
* @param message PriceParam message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.PrivateOrder.IPriceParam, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PriceParam message, length delimited. Does not implicitly {@link ProtobufBroker.PrivateOrder.PriceParam.verify|verify} messages.
* @param message PriceParam message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.PrivateOrder.IPriceParam, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PriceParam message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PriceParam
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PrivateOrder.PriceParam;
/**
* Decodes a PriceParam message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PriceParam
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PrivateOrder.PriceParam;
/**
* Verifies a PriceParam message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PriceParam message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PriceParam
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PrivateOrder.PriceParam;
/**
* Creates a plain object from a PriceParam message. Also converts values to other types if specified.
* @param message PriceParam
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PrivateOrder.PriceParam, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PriceParam to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** CurrencyPairSide enum. */
enum CurrencyPairSide {
CURRENCY_PAIR_SIDE_UNKNOWN = 0,
CURRENCY_PAIR_SIDE_BASE = 1,
CURRENCY_PAIR_SIDE_QUOTE = 2
}
}
/** Properties of a PrivateTrade. */
interface IPrivateTrade {
/** PrivateTrade externalId */
externalId?: (string|null);
/** PrivateTrade orderId */
orderId?: (string|null);
/** PrivateTrade time */
time?: (number|Long|null);
/** PrivateTrade timeMillis */
timeMillis?: (number|Long|null);
/** PrivateTrade priceString */
priceString?: (string|null);
/** PrivateTrade amountString */
amountString?: (string|null);
/** PrivateTrade side */
side?: (number|null);
/** PrivateTrade id */
id?: (number|Long|null);
}
/** Represents a PrivateTrade. */
class PrivateTrade implements IPrivateTrade {
/**
* Constructs a new PrivateTrade.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPrivateTrade);
/** PrivateTrade externalId. */
public externalId: string;
/** PrivateTrade orderId. */
public orderId: string;
/** PrivateTrade time. */
public time: (number|Long);
/** PrivateTrade timeMillis. */
public timeMillis: (number|Long);
/** PrivateTrade priceString. */
public priceString: string;
/** PrivateTrade amountString. */
public amountString: string;
/** PrivateTrade side. */
public side: number;
/** PrivateTrade id. */
public id: (number|Long);
/**
* Creates a new PrivateTrade instance using the specified properties.
* @param [properties] Properties to set
* @returns PrivateTrade instance
*/
public static create(properties?: ProtobufBroker.IPrivateTrade): ProtobufBroker.PrivateTrade;
/**
* Encodes the specified PrivateTrade message. Does not implicitly {@link ProtobufBroker.PrivateTrade.verify|verify} messages.
* @param message PrivateTrade message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPrivateTrade, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PrivateTrade message, length delimited. Does not implicitly {@link ProtobufBroker.PrivateTrade.verify|verify} messages.
* @param message PrivateTrade message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPrivateTrade, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PrivateTrade message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PrivateTrade
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PrivateTrade;
/**
* Decodes a PrivateTrade message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PrivateTrade
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PrivateTrade;
/**
* Verifies a PrivateTrade message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PrivateTrade message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PrivateTrade
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PrivateTrade;
/**
* Creates a plain object from a PrivateTrade message. Also converts values to other types if specified.
* @param message PrivateTrade
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PrivateTrade, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PrivateTrade to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PrivatePosition. */
interface IPrivatePosition {
/** PrivatePosition id */
id?: (string|null);
/** PrivatePosition time */
time?: (number|Long|null);
/** PrivatePosition side */
side?: (number|null);
/** PrivatePosition avgPriceString */
avgPriceString?: (string|null);
/** PrivatePosition amountOpenString */
amountOpenString?: (string|null);
/** PrivatePosition amountClosedString */
amountClosedString?: (string|null);
/** PrivatePosition profitLoss */
profitLoss?: (string|null);
/** PrivatePosition orderIds */
orderIds?: (string[]|null);
/** PrivatePosition tradeIds */
tradeIds?: (string[]|null);
}
/** Represents a PrivatePosition. */
class PrivatePosition implements IPrivatePosition {
/**
* Constructs a new PrivatePosition.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPrivatePosition);
/** PrivatePosition id. */
public id: string;
/** PrivatePosition time. */
public time: (number|Long);
/** PrivatePosition side. */
public side: number;
/** PrivatePosition avgPriceString. */
public avgPriceString: string;
/** PrivatePosition amountOpenString. */
public amountOpenString: string;
/** PrivatePosition amountClosedString. */
public amountClosedString: string;
/** PrivatePosition profitLoss. */
public profitLoss: string;
/** PrivatePosition orderIds. */
public orderIds: string[];
/** PrivatePosition tradeIds. */
public tradeIds: string[];
/**
* Creates a new PrivatePosition instance using the specified properties.
* @param [properties] Properties to set
* @returns PrivatePosition instance
*/
public static create(properties?: ProtobufBroker.IPrivatePosition): ProtobufBroker.PrivatePosition;
/**
* Encodes the specified PrivatePosition message. Does not implicitly {@link ProtobufBroker.PrivatePosition.verify|verify} messages.
* @param message PrivatePosition message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPrivatePosition, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PrivatePosition message, length delimited. Does not implicitly {@link ProtobufBroker.PrivatePosition.verify|verify} messages.
* @param message PrivatePosition message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPrivatePosition, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PrivatePosition message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PrivatePosition
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PrivatePosition;
/**
* Decodes a PrivatePosition message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PrivatePosition
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PrivatePosition;
/**
* Verifies a PrivatePosition message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PrivatePosition message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PrivatePosition
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PrivatePosition;
/**
* Creates a plain object from a PrivatePosition message. Also converts values to other types if specified.
* @param message PrivatePosition
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PrivatePosition, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PrivatePosition to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Balance. */
interface IBalance {
/** Balance currency */
currency?: (string|null);
/** Balance amountString */
amountString?: (string|null);
}
/** Represents a Balance. */
class Balance implements IBalance {
/**
* Constructs a new Balance.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBalance);
/** Balance currency. */
public currency: string;
/** Balance amountString. */
public amountString: string;
/**
* Creates a new Balance instance using the specified properties.
* @param [properties] Properties to set
* @returns Balance instance
*/
public static create(properties?: ProtobufBroker.IBalance): ProtobufBroker.Balance;
/**
* Encodes the specified Balance message. Does not implicitly {@link ProtobufBroker.Balance.verify|verify} messages.
* @param message Balance message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBalance, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Balance message, length delimited. Does not implicitly {@link ProtobufBroker.Balance.verify|verify} messages.
* @param message Balance message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBalance, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Balance message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Balance
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.Balance;
/**
* Decodes a Balance message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Balance
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.Balance;
/**
* Verifies a Balance message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Balance message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Balance
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.Balance;
/**
* Creates a plain object from a Balance message. Also converts values to other types if specified.
* @param message Balance
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.Balance, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Balance to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Balances. */
interface IBalances {
/** Balances fundingType */
fundingType?: (ProtobufBroker.FundingType|null);
/** Balances balances */
balances?: (ProtobufBroker.IBalance[]|null);
}
/** Represents a Balances. */
class Balances implements IBalances {
/**
* Constructs a new Balances.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IBalances);
/** Balances fundingType. */
public fundingType: ProtobufBroker.FundingType;
/** Balances balances. */
public balances: ProtobufBroker.IBalance[];
/**
* Creates a new Balances instance using the specified properties.
* @param [properties] Properties to set
* @returns Balances instance
*/
public static create(properties?: ProtobufBroker.IBalances): ProtobufBroker.Balances;
/**
* Encodes the specified Balances message. Does not implicitly {@link ProtobufBroker.Balances.verify|verify} messages.
* @param message Balances message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IBalances, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Balances message, length delimited. Does not implicitly {@link ProtobufBroker.Balances.verify|verify} messages.
* @param message Balances message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IBalances, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Balances message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Balances
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.Balances;
/**
* Decodes a Balances message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Balances
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.Balances;
/**
* Verifies a Balances message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Balances message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Balances
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.Balances;
/**
* Creates a plain object from a Balances message. Also converts values to other types if specified.
* @param message Balances
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.Balances, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Balances to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PrivateLedger. */
interface IPrivateLedger {
/** PrivateLedger externalId */
externalId?: (string|null);
/** PrivateLedger time */
time?: (google.protobuf.ITimestamp|null);
/** PrivateLedger type */
type?: (ProtobufBroker.PrivateLedger.Type|null);
/** PrivateLedger symbol */
symbol?: (string|null);
/** PrivateLedger amountString */
amountString?: (string|null);
/** PrivateLedger feeAmountString */
feeAmountString?: (string|null);
/** PrivateLedger balanceString */
balanceString?: (string|null);
}
/** Represents a PrivateLedger. */
class PrivateLedger implements IPrivateLedger {
/**
* Constructs a new PrivateLedger.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufBroker.IPrivateLedger);
/** PrivateLedger externalId. */
public externalId: string;
/** PrivateLedger time. */
public time?: (google.protobuf.ITimestamp|null);
/** PrivateLedger type. */
public type: ProtobufBroker.PrivateLedger.Type;
/** PrivateLedger symbol. */
public symbol: string;
/** PrivateLedger amountString. */
public amountString: string;
/** PrivateLedger feeAmountString. */
public feeAmountString: string;
/** PrivateLedger balanceString. */
public balanceString: string;
/**
* Creates a new PrivateLedger instance using the specified properties.
* @param [properties] Properties to set
* @returns PrivateLedger instance
*/
public static create(properties?: ProtobufBroker.IPrivateLedger): ProtobufBroker.PrivateLedger;
/**
* Encodes the specified PrivateLedger message. Does not implicitly {@link ProtobufBroker.PrivateLedger.verify|verify} messages.
* @param message PrivateLedger message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufBroker.IPrivateLedger, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PrivateLedger message, length delimited. Does not implicitly {@link ProtobufBroker.PrivateLedger.verify|verify} messages.
* @param message PrivateLedger message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufBroker.IPrivateLedger, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PrivateLedger message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PrivateLedger
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufBroker.PrivateLedger;
/**
* Decodes a PrivateLedger message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PrivateLedger
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufBroker.PrivateLedger;
/**
* Verifies a PrivateLedger message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PrivateLedger message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PrivateLedger
*/
public static fromObject(object: { [k: string]: any }): ProtobufBroker.PrivateLedger;
/**
* Creates a plain object from a PrivateLedger message. Also converts values to other types if specified.
* @param message PrivateLedger
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufBroker.PrivateLedger, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PrivateLedger to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PrivateLedger {
/** Type enum. */
enum Type {
All = 0,
Deposit = 1,
Withdrawal = 2,
Trade = 3,
Margin = 4,
Spend = 5,
Receive = 6
}
}
}
/** Namespace ProtobufClient. */
export namespace ProtobufClient {
/** Properties of a ClientMessage. */
interface IClientMessage {
/** ClientMessage identification */
identification?: (ProtobufClient.IClientIdentificationMessage|null);
/** ClientMessage subscribe */
subscribe?: (ProtobufClient.IClientSubscribeMessage|null);
/** ClientMessage unsubscribe */
unsubscribe?: (ProtobufClient.IClientUnsubscribeMessage|null);
/** ClientMessage webAuthentication */
webAuthentication?: (ProtobufClient.IWebAuthenticationMessage|null);
/** ClientMessage apiAuthentication */
apiAuthentication?: (ProtobufClient.IAPIAuthenticationMessage|null);
/** ClientMessage clientSession */
clientSession?: (ProtobufClient.IClientSessionMessage|null);
}
/** Represents a ClientMessage. */
class ClientMessage implements IClientMessage {
/**
* Constructs a new ClientMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientMessage);
/** ClientMessage identification. */
public identification?: (ProtobufClient.IClientIdentificationMessage|null);
/** ClientMessage subscribe. */
public subscribe?: (ProtobufClient.IClientSubscribeMessage|null);
/** ClientMessage unsubscribe. */
public unsubscribe?: (ProtobufClient.IClientUnsubscribeMessage|null);
/** ClientMessage webAuthentication. */
public webAuthentication?: (ProtobufClient.IWebAuthenticationMessage|null);
/** ClientMessage apiAuthentication. */
public apiAuthentication?: (ProtobufClient.IAPIAuthenticationMessage|null);
/** ClientMessage clientSession. */
public clientSession?: (ProtobufClient.IClientSessionMessage|null);
/** ClientMessage body. */
public body?: ("identification"|"subscribe"|"unsubscribe"|"webAuthentication"|"apiAuthentication"|"clientSession");
/**
* Creates a new ClientMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientMessage instance
*/
public static create(properties?: ProtobufClient.IClientMessage): ProtobufClient.ClientMessage;
/**
* Encodes the specified ClientMessage message. Does not implicitly {@link ProtobufClient.ClientMessage.verify|verify} messages.
* @param message ClientMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientMessage message, length delimited. Does not implicitly {@link ProtobufClient.ClientMessage.verify|verify} messages.
* @param message ClientMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientMessage;
/**
* Decodes a ClientMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientMessage;
/**
* Verifies a ClientMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientMessage;
/**
* Creates a plain object from a ClientMessage message. Also converts values to other types if specified.
* @param message ClientMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientIdentificationMessage. */
interface IClientIdentificationMessage {
/** ClientIdentificationMessage useragent */
useragent?: (string|null);
/** ClientIdentificationMessage revision */
revision?: (string|null);
/** ClientIdentificationMessage integration */
integration?: (string|null);
/** ClientIdentificationMessage locale */
locale?: (string|null);
/** ClientIdentificationMessage subscriptions */
subscriptions?: (string[]|null);
/** ClientIdentificationMessage clientSubscriptions */
clientSubscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a ClientIdentificationMessage. */
class ClientIdentificationMessage implements IClientIdentificationMessage {
/**
* Constructs a new ClientIdentificationMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientIdentificationMessage);
/** ClientIdentificationMessage useragent. */
public useragent: string;
/** ClientIdentificationMessage revision. */
public revision: string;
/** ClientIdentificationMessage integration. */
public integration: string;
/** ClientIdentificationMessage locale. */
public locale: string;
/** ClientIdentificationMessage subscriptions. */
public subscriptions: string[];
/** ClientIdentificationMessage clientSubscriptions. */
public clientSubscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new ClientIdentificationMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientIdentificationMessage instance
*/
public static create(properties?: ProtobufClient.IClientIdentificationMessage): ProtobufClient.ClientIdentificationMessage;
/**
* Encodes the specified ClientIdentificationMessage message. Does not implicitly {@link ProtobufClient.ClientIdentificationMessage.verify|verify} messages.
* @param message ClientIdentificationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientIdentificationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientIdentificationMessage message, length delimited. Does not implicitly {@link ProtobufClient.ClientIdentificationMessage.verify|verify} messages.
* @param message ClientIdentificationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientIdentificationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientIdentificationMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientIdentificationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientIdentificationMessage;
/**
* Decodes a ClientIdentificationMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientIdentificationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientIdentificationMessage;
/**
* Verifies a ClientIdentificationMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientIdentificationMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientIdentificationMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientIdentificationMessage;
/**
* Creates a plain object from a ClientIdentificationMessage message. Also converts values to other types if specified.
* @param message ClientIdentificationMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientIdentificationMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientIdentificationMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WebAuthenticationMessage. */
interface IWebAuthenticationMessage {
/** WebAuthenticationMessage identification */
identification?: (ProtobufClient.IClientIdentificationMessage|null);
/** WebAuthenticationMessage token */
token?: (string|null);
/** WebAuthenticationMessage nonce */
nonce?: (string|null);
/** WebAuthenticationMessage accessList */
accessList?: (string[]|null);
}
/** Represents a WebAuthenticationMessage. */
class WebAuthenticationMessage implements IWebAuthenticationMessage {
/**
* Constructs a new WebAuthenticationMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IWebAuthenticationMessage);
/** WebAuthenticationMessage identification. */
public identification?: (ProtobufClient.IClientIdentificationMessage|null);
/** WebAuthenticationMessage token. */
public token: string;
/** WebAuthenticationMessage nonce. */
public nonce: string;
/** WebAuthenticationMessage accessList. */
public accessList: string[];
/**
* Creates a new WebAuthenticationMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns WebAuthenticationMessage instance
*/
public static create(properties?: ProtobufClient.IWebAuthenticationMessage): ProtobufClient.WebAuthenticationMessage;
/**
* Encodes the specified WebAuthenticationMessage message. Does not implicitly {@link ProtobufClient.WebAuthenticationMessage.verify|verify} messages.
* @param message WebAuthenticationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IWebAuthenticationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WebAuthenticationMessage message, length delimited. Does not implicitly {@link ProtobufClient.WebAuthenticationMessage.verify|verify} messages.
* @param message WebAuthenticationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IWebAuthenticationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WebAuthenticationMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WebAuthenticationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.WebAuthenticationMessage;
/**
* Decodes a WebAuthenticationMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WebAuthenticationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.WebAuthenticationMessage;
/**
* Verifies a WebAuthenticationMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WebAuthenticationMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WebAuthenticationMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.WebAuthenticationMessage;
/**
* Creates a plain object from a WebAuthenticationMessage message. Also converts values to other types if specified.
* @param message WebAuthenticationMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.WebAuthenticationMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WebAuthenticationMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a WebAuthenticationResult. */
interface IWebAuthenticationResult {
/** WebAuthenticationResult status */
status?: (ProtobufClient.WebAuthenticationResult.Status|null);
}
/** Represents a WebAuthenticationResult. */
class WebAuthenticationResult implements IWebAuthenticationResult {
/**
* Constructs a new WebAuthenticationResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IWebAuthenticationResult);
/** WebAuthenticationResult status. */
public status: ProtobufClient.WebAuthenticationResult.Status;
/**
* Creates a new WebAuthenticationResult instance using the specified properties.
* @param [properties] Properties to set
* @returns WebAuthenticationResult instance
*/
public static create(properties?: ProtobufClient.IWebAuthenticationResult): ProtobufClient.WebAuthenticationResult;
/**
* Encodes the specified WebAuthenticationResult message. Does not implicitly {@link ProtobufClient.WebAuthenticationResult.verify|verify} messages.
* @param message WebAuthenticationResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IWebAuthenticationResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified WebAuthenticationResult message, length delimited. Does not implicitly {@link ProtobufClient.WebAuthenticationResult.verify|verify} messages.
* @param message WebAuthenticationResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IWebAuthenticationResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a WebAuthenticationResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns WebAuthenticationResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.WebAuthenticationResult;
/**
* Decodes a WebAuthenticationResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns WebAuthenticationResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.WebAuthenticationResult;
/**
* Verifies a WebAuthenticationResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a WebAuthenticationResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns WebAuthenticationResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.WebAuthenticationResult;
/**
* Creates a plain object from a WebAuthenticationResult message. Also converts values to other types if specified.
* @param message WebAuthenticationResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.WebAuthenticationResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this WebAuthenticationResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace WebAuthenticationResult {
/** Status enum. */
enum Status {
UNKNOWN = 0,
AUTHENTICATED = 1,
INVALID_SESSION = 2,
MFA_REQUIRED = 3
}
}
/** Properties of a TradeSessionAuth. */
interface ITradeSessionAuth {
/** TradeSessionAuth apiKey */
apiKey?: (string|null);
/** TradeSessionAuth apiSecret */
apiSecret?: (string|null);
/** TradeSessionAuth customerId */
customerId?: (string|null);
/** TradeSessionAuth keyPassphrase */
keyPassphrase?: (string|null);
}
/** Represents a TradeSessionAuth. */
class TradeSessionAuth implements ITradeSessionAuth {
/**
* Constructs a new TradeSessionAuth.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ITradeSessionAuth);
/** TradeSessionAuth apiKey. */
public apiKey: string;
/** TradeSessionAuth apiSecret. */
public apiSecret: string;
/** TradeSessionAuth customerId. */
public customerId: string;
/** TradeSessionAuth keyPassphrase. */
public keyPassphrase: string;
/**
* Creates a new TradeSessionAuth instance using the specified properties.
* @param [properties] Properties to set
* @returns TradeSessionAuth instance
*/
public static create(properties?: ProtobufClient.ITradeSessionAuth): ProtobufClient.TradeSessionAuth;
/**
* Encodes the specified TradeSessionAuth message. Does not implicitly {@link ProtobufClient.TradeSessionAuth.verify|verify} messages.
* @param message TradeSessionAuth message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ITradeSessionAuth, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TradeSessionAuth message, length delimited. Does not implicitly {@link ProtobufClient.TradeSessionAuth.verify|verify} messages.
* @param message TradeSessionAuth message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ITradeSessionAuth, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TradeSessionAuth message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TradeSessionAuth
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.TradeSessionAuth;
/**
* Decodes a TradeSessionAuth message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TradeSessionAuth
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.TradeSessionAuth;
/**
* Verifies a TradeSessionAuth message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TradeSessionAuth message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TradeSessionAuth
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.TradeSessionAuth;
/**
* Creates a plain object from a TradeSessionAuth message. Also converts values to other types if specified.
* @param message TradeSessionAuth
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.TradeSessionAuth, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TradeSessionAuth to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TradeSubscription. */
interface ITradeSubscription {
/** TradeSubscription marketId */
marketId?: (string|null);
/** TradeSubscription auth */
auth?: (ProtobufClient.ITradeSessionAuth|null);
}
/** Represents a TradeSubscription. */
class TradeSubscription implements ITradeSubscription {
/**
* Constructs a new TradeSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ITradeSubscription);
/** TradeSubscription marketId. */
public marketId: string;
/** TradeSubscription auth. */
public auth?: (ProtobufClient.ITradeSessionAuth|null);
/**
* Creates a new TradeSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns TradeSubscription instance
*/
public static create(properties?: ProtobufClient.ITradeSubscription): ProtobufClient.TradeSubscription;
/**
* Encodes the specified TradeSubscription message. Does not implicitly {@link ProtobufClient.TradeSubscription.verify|verify} messages.
* @param message TradeSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ITradeSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TradeSubscription message, length delimited. Does not implicitly {@link ProtobufClient.TradeSubscription.verify|verify} messages.
* @param message TradeSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ITradeSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TradeSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TradeSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.TradeSubscription;
/**
* Decodes a TradeSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TradeSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.TradeSubscription;
/**
* Verifies a TradeSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TradeSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TradeSubscription
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.TradeSubscription;
/**
* Creates a plain object from a TradeSubscription message. Also converts values to other types if specified.
* @param message TradeSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.TradeSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TradeSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a StreamSubscription. */
interface IStreamSubscription {
/** StreamSubscription resource */
resource?: (string|null);
}
/** Represents a StreamSubscription. */
class StreamSubscription implements IStreamSubscription {
/**
* Constructs a new StreamSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IStreamSubscription);
/** StreamSubscription resource. */
public resource: string;
/**
* Creates a new StreamSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns StreamSubscription instance
*/
public static create(properties?: ProtobufClient.IStreamSubscription): ProtobufClient.StreamSubscription;
/**
* Encodes the specified StreamSubscription message. Does not implicitly {@link ProtobufClient.StreamSubscription.verify|verify} messages.
* @param message StreamSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IStreamSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StreamSubscription message, length delimited. Does not implicitly {@link ProtobufClient.StreamSubscription.verify|verify} messages.
* @param message StreamSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IStreamSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StreamSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StreamSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.StreamSubscription;
/**
* Decodes a StreamSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StreamSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.StreamSubscription;
/**
* Verifies a StreamSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a StreamSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StreamSubscription
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.StreamSubscription;
/**
* Creates a plain object from a StreamSubscription message. Also converts values to other types if specified.
* @param message StreamSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.StreamSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StreamSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a UserPushSubscription. */
interface IUserPushSubscription {
/** UserPushSubscription triggeredHandlers */
triggeredHandlers?: (ProtobufClient.UserPushSubscription.ITriggeredHandlers|null);
/** UserPushSubscription achievements */
achievements?: (ProtobufClient.UserPushSubscription.IAchievements|null);
}
/** Represents a UserPushSubscription. */
class UserPushSubscription implements IUserPushSubscription {
/**
* Constructs a new UserPushSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IUserPushSubscription);
/** UserPushSubscription triggeredHandlers. */
public triggeredHandlers?: (ProtobufClient.UserPushSubscription.ITriggeredHandlers|null);
/** UserPushSubscription achievements. */
public achievements?: (ProtobufClient.UserPushSubscription.IAchievements|null);
/** UserPushSubscription body. */
public body?: ("triggeredHandlers"|"achievements");
/**
* Creates a new UserPushSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns UserPushSubscription instance
*/
public static create(properties?: ProtobufClient.IUserPushSubscription): ProtobufClient.UserPushSubscription;
/**
* Encodes the specified UserPushSubscription message. Does not implicitly {@link ProtobufClient.UserPushSubscription.verify|verify} messages.
* @param message UserPushSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IUserPushSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UserPushSubscription message, length delimited. Does not implicitly {@link ProtobufClient.UserPushSubscription.verify|verify} messages.
* @param message UserPushSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IUserPushSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a UserPushSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UserPushSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.UserPushSubscription;
/**
* Decodes a UserPushSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UserPushSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.UserPushSubscription;
/**
* Verifies a UserPushSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a UserPushSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UserPushSubscription
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.UserPushSubscription;
/**
* Creates a plain object from a UserPushSubscription message. Also converts values to other types if specified.
* @param message UserPushSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.UserPushSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UserPushSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace UserPushSubscription {
/** Properties of a TriggeredHandlers. */
interface ITriggeredHandlers {
}
/** Represents a TriggeredHandlers. */
class TriggeredHandlers implements ITriggeredHandlers {
/**
* Constructs a new TriggeredHandlers.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.UserPushSubscription.ITriggeredHandlers);
/**
* Creates a new TriggeredHandlers instance using the specified properties.
* @param [properties] Properties to set
* @returns TriggeredHandlers instance
*/
public static create(properties?: ProtobufClient.UserPushSubscription.ITriggeredHandlers): ProtobufClient.UserPushSubscription.TriggeredHandlers;
/**
* Encodes the specified TriggeredHandlers message. Does not implicitly {@link ProtobufClient.UserPushSubscription.TriggeredHandlers.verify|verify} messages.
* @param message TriggeredHandlers message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.UserPushSubscription.ITriggeredHandlers, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TriggeredHandlers message, length delimited. Does not implicitly {@link ProtobufClient.UserPushSubscription.TriggeredHandlers.verify|verify} messages.
* @param message TriggeredHandlers message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.UserPushSubscription.ITriggeredHandlers, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TriggeredHandlers message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TriggeredHandlers
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.UserPushSubscription.TriggeredHandlers;
/**
* Decodes a TriggeredHandlers message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TriggeredHandlers
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.UserPushSubscription.TriggeredHandlers;
/**
* Verifies a TriggeredHandlers message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TriggeredHandlers message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TriggeredHandlers
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.UserPushSubscription.TriggeredHandlers;
/**
* Creates a plain object from a TriggeredHandlers message. Also converts values to other types if specified.
* @param message TriggeredHandlers
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.UserPushSubscription.TriggeredHandlers, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TriggeredHandlers to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Achievements. */
interface IAchievements {
}
/** Represents an Achievements. */
class Achievements implements IAchievements {
/**
* Constructs a new Achievements.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.UserPushSubscription.IAchievements);
/**
* Creates a new Achievements instance using the specified properties.
* @param [properties] Properties to set
* @returns Achievements instance
*/
public static create(properties?: ProtobufClient.UserPushSubscription.IAchievements): ProtobufClient.UserPushSubscription.Achievements;
/**
* Encodes the specified Achievements message. Does not implicitly {@link ProtobufClient.UserPushSubscription.Achievements.verify|verify} messages.
* @param message Achievements message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.UserPushSubscription.IAchievements, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Achievements message, length delimited. Does not implicitly {@link ProtobufClient.UserPushSubscription.Achievements.verify|verify} messages.
* @param message Achievements message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.UserPushSubscription.IAchievements, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Achievements message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Achievements
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.UserPushSubscription.Achievements;
/**
* Decodes an Achievements message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Achievements
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.UserPushSubscription.Achievements;
/**
* Verifies an Achievements message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Achievements message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Achievements
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.UserPushSubscription.Achievements;
/**
* Creates a plain object from an Achievements message. Also converts values to other types if specified.
* @param message Achievements
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.UserPushSubscription.Achievements, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Achievements to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a TriggerSubscription. */
interface ITriggerSubscription {
}
/** Represents a TriggerSubscription. */
class TriggerSubscription implements ITriggerSubscription {
/**
* Constructs a new TriggerSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ITriggerSubscription);
/**
* Creates a new TriggerSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns TriggerSubscription instance
*/
public static create(properties?: ProtobufClient.ITriggerSubscription): ProtobufClient.TriggerSubscription;
/**
* Encodes the specified TriggerSubscription message. Does not implicitly {@link ProtobufClient.TriggerSubscription.verify|verify} messages.
* @param message TriggerSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ITriggerSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TriggerSubscription message, length delimited. Does not implicitly {@link ProtobufClient.TriggerSubscription.verify|verify} messages.
* @param message TriggerSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ITriggerSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TriggerSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TriggerSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.TriggerSubscription;
/**
* Decodes a TriggerSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TriggerSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.TriggerSubscription;
/**
* Verifies a TriggerSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TriggerSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TriggerSubscription
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.TriggerSubscription;
/**
* Creates a plain object from a TriggerSubscription message. Also converts values to other types if specified.
* @param message TriggerSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.TriggerSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TriggerSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientSubscription. */
interface IClientSubscription {
/** ClientSubscription streamSubscription */
streamSubscription?: (ProtobufClient.IStreamSubscription|null);
/** ClientSubscription tradeSubscription */
tradeSubscription?: (ProtobufClient.ITradeSubscription|null);
/** ClientSubscription triggerSubscription */
triggerSubscription?: (ProtobufClient.ITriggerSubscription|null);
/** ClientSubscription userPushSubscription */
userPushSubscription?: (ProtobufClient.IUserPushSubscription|null);
}
/** Represents a ClientSubscription. */
class ClientSubscription implements IClientSubscription {
/**
* Constructs a new ClientSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientSubscription);
/** ClientSubscription streamSubscription. */
public streamSubscription?: (ProtobufClient.IStreamSubscription|null);
/** ClientSubscription tradeSubscription. */
public tradeSubscription?: (ProtobufClient.ITradeSubscription|null);
/** ClientSubscription triggerSubscription. */
public triggerSubscription?: (ProtobufClient.ITriggerSubscription|null);
/** ClientSubscription userPushSubscription. */
public userPushSubscription?: (ProtobufClient.IUserPushSubscription|null);
/** ClientSubscription body. */
public body?: ("streamSubscription"|"tradeSubscription"|"triggerSubscription"|"userPushSubscription");
/**
* Creates a new ClientSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientSubscription instance
*/
public static create(properties?: ProtobufClient.IClientSubscription): ProtobufClient.ClientSubscription;
/**
* Encodes the specified ClientSubscription message. Does not implicitly {@link ProtobufClient.ClientSubscription.verify|verify} messages.
* @param message ClientSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientSubscription message, length delimited. Does not implicitly {@link ProtobufClient.ClientSubscription.verify|verify} messages.
* @param message ClientSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSubscription;
/**
* Decodes a ClientSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSubscription;
/**
* Verifies a ClientSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientSubscription
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSubscription;
/**
* Creates a plain object from a ClientSubscription message. Also converts values to other types if specified.
* @param message ClientSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a APIAuthenticationMessage. */
interface IAPIAuthenticationMessage {
/** APIAuthenticationMessage token */
token?: (string|null);
/** APIAuthenticationMessage nonce */
nonce?: (string|null);
/** APIAuthenticationMessage apiKey */
apiKey?: (string|null);
/** APIAuthenticationMessage source */
source?: (ProtobufClient.APIAuthenticationMessage.Source|null);
/** APIAuthenticationMessage version */
version?: (string|null);
/** APIAuthenticationMessage subscriptions */
subscriptions?: (string[]|null);
/** APIAuthenticationMessage clientSubscriptions */
clientSubscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a APIAuthenticationMessage. */
class APIAuthenticationMessage implements IAPIAuthenticationMessage {
/**
* Constructs a new APIAuthenticationMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IAPIAuthenticationMessage);
/** APIAuthenticationMessage token. */
public token: string;
/** APIAuthenticationMessage nonce. */
public nonce: string;
/** APIAuthenticationMessage apiKey. */
public apiKey: string;
/** APIAuthenticationMessage source. */
public source: ProtobufClient.APIAuthenticationMessage.Source;
/** APIAuthenticationMessage version. */
public version: string;
/** APIAuthenticationMessage subscriptions. */
public subscriptions: string[];
/** APIAuthenticationMessage clientSubscriptions. */
public clientSubscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new APIAuthenticationMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns APIAuthenticationMessage instance
*/
public static create(properties?: ProtobufClient.IAPIAuthenticationMessage): ProtobufClient.APIAuthenticationMessage;
/**
* Encodes the specified APIAuthenticationMessage message. Does not implicitly {@link ProtobufClient.APIAuthenticationMessage.verify|verify} messages.
* @param message APIAuthenticationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IAPIAuthenticationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified APIAuthenticationMessage message, length delimited. Does not implicitly {@link ProtobufClient.APIAuthenticationMessage.verify|verify} messages.
* @param message APIAuthenticationMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IAPIAuthenticationMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a APIAuthenticationMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns APIAuthenticationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.APIAuthenticationMessage;
/**
* Decodes a APIAuthenticationMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns APIAuthenticationMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.APIAuthenticationMessage;
/**
* Verifies a APIAuthenticationMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a APIAuthenticationMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns APIAuthenticationMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.APIAuthenticationMessage;
/**
* Creates a plain object from a APIAuthenticationMessage message. Also converts values to other types if specified.
* @param message APIAuthenticationMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.APIAuthenticationMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this APIAuthenticationMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace APIAuthenticationMessage {
/** Source enum. */
enum Source {
UNKNOWN = 0,
GOLANG_SDK = 1,
JAVASCRIPT_SDK = 2,
NODE_SDK = 3,
RUST_SDK = 5,
CW_WEB = 4
}
}
/** Properties of a ClientSessionMessage. */
interface IClientSessionMessage {
/** ClientSessionMessage session */
session?: (ProtobufClient.ClientSessionMessage.ISession|null);
/** ClientSessionMessage anonymousTradingSession */
anonymousTradingSession?: (ProtobufClient.ClientSessionMessage.IAnonymousTradingSession|null);
/** ClientSessionMessage anonymousUserSession */
anonymousUserSession?: (ProtobufClient.ClientSessionMessage.IAnonymousUserSession|null);
/** ClientSessionMessage identification */
identification?: (ProtobufClient.IClientIdentificationMessage|null);
}
/** Represents a ClientSessionMessage. */
class ClientSessionMessage implements IClientSessionMessage {
/**
* Constructs a new ClientSessionMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientSessionMessage);
/** ClientSessionMessage session. */
public session?: (ProtobufClient.ClientSessionMessage.ISession|null);
/** ClientSessionMessage anonymousTradingSession. */
public anonymousTradingSession?: (ProtobufClient.ClientSessionMessage.IAnonymousTradingSession|null);
/** ClientSessionMessage anonymousUserSession. */
public anonymousUserSession?: (ProtobufClient.ClientSessionMessage.IAnonymousUserSession|null);
/** ClientSessionMessage identification. */
public identification?: (ProtobufClient.IClientIdentificationMessage|null);
/** ClientSessionMessage SessionConfig. */
public SessionConfig?: ("session"|"anonymousTradingSession"|"anonymousUserSession");
/**
* Creates a new ClientSessionMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientSessionMessage instance
*/
public static create(properties?: ProtobufClient.IClientSessionMessage): ProtobufClient.ClientSessionMessage;
/**
* Encodes the specified ClientSessionMessage message. Does not implicitly {@link ProtobufClient.ClientSessionMessage.verify|verify} messages.
* @param message ClientSessionMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientSessionMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientSessionMessage message, length delimited. Does not implicitly {@link ProtobufClient.ClientSessionMessage.verify|verify} messages.
* @param message ClientSessionMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientSessionMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientSessionMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientSessionMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSessionMessage;
/**
* Decodes a ClientSessionMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientSessionMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSessionMessage;
/**
* Verifies a ClientSessionMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientSessionMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientSessionMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSessionMessage;
/**
* Creates a plain object from a ClientSessionMessage message. Also converts values to other types if specified.
* @param message ClientSessionMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSessionMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientSessionMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ClientSessionMessage {
/** Properties of a Session. */
interface ISession {
/** Session userId */
userId?: (string|null);
/** Session expires */
expires?: (number|Long|null);
/** Session token */
token?: (string|null);
/** Session mfaToken */
mfaToken?: (string|null);
}
/** Represents a Session. */
class Session implements ISession {
/**
* Constructs a new Session.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ClientSessionMessage.ISession);
/** Session userId. */
public userId: string;
/** Session expires. */
public expires: (number|Long);
/** Session token. */
public token: string;
/** Session mfaToken. */
public mfaToken: string;
/**
* Creates a new Session instance using the specified properties.
* @param [properties] Properties to set
* @returns Session instance
*/
public static create(properties?: ProtobufClient.ClientSessionMessage.ISession): ProtobufClient.ClientSessionMessage.Session;
/**
* Encodes the specified Session message. Does not implicitly {@link ProtobufClient.ClientSessionMessage.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ClientSessionMessage.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Session message, length delimited. Does not implicitly {@link ProtobufClient.ClientSessionMessage.Session.verify|verify} messages.
* @param message Session message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ClientSessionMessage.ISession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Session message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSessionMessage.Session;
/**
* Decodes a Session message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Session
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSessionMessage.Session;
/**
* Verifies a Session message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Session message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Session
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSessionMessage.Session;
/**
* Creates a plain object from a Session message. Also converts values to other types if specified.
* @param message Session
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSessionMessage.Session, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Session to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnonymousTradingSession. */
interface IAnonymousTradingSession {
/** AnonymousTradingSession exchange */
exchange?: (string|null);
/** AnonymousTradingSession token */
token?: (string|null);
/** AnonymousTradingSession expiration */
expiration?: (number|Long|null);
}
/** Represents an AnonymousTradingSession. */
class AnonymousTradingSession implements IAnonymousTradingSession {
/**
* Constructs a new AnonymousTradingSession.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ClientSessionMessage.IAnonymousTradingSession);
/** AnonymousTradingSession exchange. */
public exchange: string;
/** AnonymousTradingSession token. */
public token: string;
/** AnonymousTradingSession expiration. */
public expiration: (number|Long);
/**
* Creates a new AnonymousTradingSession instance using the specified properties.
* @param [properties] Properties to set
* @returns AnonymousTradingSession instance
*/
public static create(properties?: ProtobufClient.ClientSessionMessage.IAnonymousTradingSession): ProtobufClient.ClientSessionMessage.AnonymousTradingSession;
/**
* Encodes the specified AnonymousTradingSession message. Does not implicitly {@link ProtobufClient.ClientSessionMessage.AnonymousTradingSession.verify|verify} messages.
* @param message AnonymousTradingSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ClientSessionMessage.IAnonymousTradingSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnonymousTradingSession message, length delimited. Does not implicitly {@link ProtobufClient.ClientSessionMessage.AnonymousTradingSession.verify|verify} messages.
* @param message AnonymousTradingSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ClientSessionMessage.IAnonymousTradingSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnonymousTradingSession message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnonymousTradingSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSessionMessage.AnonymousTradingSession;
/**
* Decodes an AnonymousTradingSession message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnonymousTradingSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSessionMessage.AnonymousTradingSession;
/**
* Verifies an AnonymousTradingSession message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnonymousTradingSession message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnonymousTradingSession
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSessionMessage.AnonymousTradingSession;
/**
* Creates a plain object from an AnonymousTradingSession message. Also converts values to other types if specified.
* @param message AnonymousTradingSession
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSessionMessage.AnonymousTradingSession, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnonymousTradingSession to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnonymousUserSession. */
interface IAnonymousUserSession {
/** AnonymousUserSession token */
token?: (string|null);
}
/** Represents an AnonymousUserSession. */
class AnonymousUserSession implements IAnonymousUserSession {
/**
* Constructs a new AnonymousUserSession.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.ClientSessionMessage.IAnonymousUserSession);
/** AnonymousUserSession token. */
public token: string;
/**
* Creates a new AnonymousUserSession instance using the specified properties.
* @param [properties] Properties to set
* @returns AnonymousUserSession instance
*/
public static create(properties?: ProtobufClient.ClientSessionMessage.IAnonymousUserSession): ProtobufClient.ClientSessionMessage.AnonymousUserSession;
/**
* Encodes the specified AnonymousUserSession message. Does not implicitly {@link ProtobufClient.ClientSessionMessage.AnonymousUserSession.verify|verify} messages.
* @param message AnonymousUserSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.ClientSessionMessage.IAnonymousUserSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnonymousUserSession message, length delimited. Does not implicitly {@link ProtobufClient.ClientSessionMessage.AnonymousUserSession.verify|verify} messages.
* @param message AnonymousUserSession message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.ClientSessionMessage.IAnonymousUserSession, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnonymousUserSession message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnonymousUserSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSessionMessage.AnonymousUserSession;
/**
* Decodes an AnonymousUserSession message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnonymousUserSession
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSessionMessage.AnonymousUserSession;
/**
* Verifies an AnonymousUserSession message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnonymousUserSession message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnonymousUserSession
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSessionMessage.AnonymousUserSession;
/**
* Creates a plain object from an AnonymousUserSession message. Also converts values to other types if specified.
* @param message AnonymousUserSession
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSessionMessage.AnonymousUserSession, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnonymousUserSession to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ClientSubscribeMessage. */
interface IClientSubscribeMessage {
/** ClientSubscribeMessage subscriptionKeys */
subscriptionKeys?: (string[]|null);
/** ClientSubscribeMessage subscriptions */
subscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a ClientSubscribeMessage. */
class ClientSubscribeMessage implements IClientSubscribeMessage {
/**
* Constructs a new ClientSubscribeMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientSubscribeMessage);
/** ClientSubscribeMessage subscriptionKeys. */
public subscriptionKeys: string[];
/** ClientSubscribeMessage subscriptions. */
public subscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new ClientSubscribeMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientSubscribeMessage instance
*/
public static create(properties?: ProtobufClient.IClientSubscribeMessage): ProtobufClient.ClientSubscribeMessage;
/**
* Encodes the specified ClientSubscribeMessage message. Does not implicitly {@link ProtobufClient.ClientSubscribeMessage.verify|verify} messages.
* @param message ClientSubscribeMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientSubscribeMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientSubscribeMessage message, length delimited. Does not implicitly {@link ProtobufClient.ClientSubscribeMessage.verify|verify} messages.
* @param message ClientSubscribeMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientSubscribeMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientSubscribeMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientSubscribeMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientSubscribeMessage;
/**
* Decodes a ClientSubscribeMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientSubscribeMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientSubscribeMessage;
/**
* Verifies a ClientSubscribeMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientSubscribeMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientSubscribeMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientSubscribeMessage;
/**
* Creates a plain object from a ClientSubscribeMessage message. Also converts values to other types if specified.
* @param message ClientSubscribeMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientSubscribeMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientSubscribeMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientUnsubscribeMessage. */
interface IClientUnsubscribeMessage {
/** ClientUnsubscribeMessage subscriptionKeys */
subscriptionKeys?: (string[]|null);
/** ClientUnsubscribeMessage subscriptions */
subscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a ClientUnsubscribeMessage. */
class ClientUnsubscribeMessage implements IClientUnsubscribeMessage {
/**
* Constructs a new ClientUnsubscribeMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufClient.IClientUnsubscribeMessage);
/** ClientUnsubscribeMessage subscriptionKeys. */
public subscriptionKeys: string[];
/** ClientUnsubscribeMessage subscriptions. */
public subscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new ClientUnsubscribeMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientUnsubscribeMessage instance
*/
public static create(properties?: ProtobufClient.IClientUnsubscribeMessage): ProtobufClient.ClientUnsubscribeMessage;
/**
* Encodes the specified ClientUnsubscribeMessage message. Does not implicitly {@link ProtobufClient.ClientUnsubscribeMessage.verify|verify} messages.
* @param message ClientUnsubscribeMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufClient.IClientUnsubscribeMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientUnsubscribeMessage message, length delimited. Does not implicitly {@link ProtobufClient.ClientUnsubscribeMessage.verify|verify} messages.
* @param message ClientUnsubscribeMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufClient.IClientUnsubscribeMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientUnsubscribeMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientUnsubscribeMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufClient.ClientUnsubscribeMessage;
/**
* Decodes a ClientUnsubscribeMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientUnsubscribeMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufClient.ClientUnsubscribeMessage;
/**
* Verifies a ClientUnsubscribeMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ClientUnsubscribeMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientUnsubscribeMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufClient.ClientUnsubscribeMessage;
/**
* Creates a plain object from a ClientUnsubscribeMessage message. Also converts values to other types if specified.
* @param message ClientUnsubscribeMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufClient.ClientUnsubscribeMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientUnsubscribeMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace ProtobufMarkets. */
export namespace ProtobufMarkets {
/** Properties of an AssetUpdateMessage. */
interface IAssetUpdateMessage {
/** AssetUpdateMessage asset */
asset?: (number|null);
/** AssetUpdateMessage usdVolumeUpdate */
usdVolumeUpdate?: (ProtobufMarkets.IAssetUSDVolumeUpdate|null);
}
/** Represents an AssetUpdateMessage. */
class AssetUpdateMessage implements IAssetUpdateMessage {
/**
* Constructs a new AssetUpdateMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IAssetUpdateMessage);
/** AssetUpdateMessage asset. */
public asset: number;
/** AssetUpdateMessage usdVolumeUpdate. */
public usdVolumeUpdate?: (ProtobufMarkets.IAssetUSDVolumeUpdate|null);
/** AssetUpdateMessage Update. */
public Update?: "usdVolumeUpdate";
/**
* Creates a new AssetUpdateMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns AssetUpdateMessage instance
*/
public static create(properties?: ProtobufMarkets.IAssetUpdateMessage): ProtobufMarkets.AssetUpdateMessage;
/**
* Encodes the specified AssetUpdateMessage message. Does not implicitly {@link ProtobufMarkets.AssetUpdateMessage.verify|verify} messages.
* @param message AssetUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IAssetUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AssetUpdateMessage message, length delimited. Does not implicitly {@link ProtobufMarkets.AssetUpdateMessage.verify|verify} messages.
* @param message AssetUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IAssetUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AssetUpdateMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AssetUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.AssetUpdateMessage;
/**
* Decodes an AssetUpdateMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AssetUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.AssetUpdateMessage;
/**
* Verifies an AssetUpdateMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AssetUpdateMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AssetUpdateMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.AssetUpdateMessage;
/**
* Creates a plain object from an AssetUpdateMessage message. Also converts values to other types if specified.
* @param message AssetUpdateMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.AssetUpdateMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AssetUpdateMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AssetUSDVolumeUpdate. */
interface IAssetUSDVolumeUpdate {
/** AssetUSDVolumeUpdate volume */
volume?: (string|null);
}
/** Represents an AssetUSDVolumeUpdate. */
class AssetUSDVolumeUpdate implements IAssetUSDVolumeUpdate {
/**
* Constructs a new AssetUSDVolumeUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IAssetUSDVolumeUpdate);
/** AssetUSDVolumeUpdate volume. */
public volume: string;
/**
* Creates a new AssetUSDVolumeUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns AssetUSDVolumeUpdate instance
*/
public static create(properties?: ProtobufMarkets.IAssetUSDVolumeUpdate): ProtobufMarkets.AssetUSDVolumeUpdate;
/**
* Encodes the specified AssetUSDVolumeUpdate message. Does not implicitly {@link ProtobufMarkets.AssetUSDVolumeUpdate.verify|verify} messages.
* @param message AssetUSDVolumeUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IAssetUSDVolumeUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AssetUSDVolumeUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.AssetUSDVolumeUpdate.verify|verify} messages.
* @param message AssetUSDVolumeUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IAssetUSDVolumeUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AssetUSDVolumeUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AssetUSDVolumeUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.AssetUSDVolumeUpdate;
/**
* Decodes an AssetUSDVolumeUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AssetUSDVolumeUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.AssetUSDVolumeUpdate;
/**
* Verifies an AssetUSDVolumeUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AssetUSDVolumeUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AssetUSDVolumeUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.AssetUSDVolumeUpdate;
/**
* Creates a plain object from an AssetUSDVolumeUpdate message. Also converts values to other types if specified.
* @param message AssetUSDVolumeUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.AssetUSDVolumeUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AssetUSDVolumeUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Index. */
interface IIndex {
/** Index id */
id?: (number|Long|null);
/** Index symbol */
symbol?: (string|null);
/** Index indexType */
indexType?: (string|null);
/** Index cwIndex */
cwIndex?: (boolean|null);
/** Index exchangeId */
exchangeId?: (number|Long|null);
/** Index instrumentId */
instrumentId?: (number|Long|null);
}
/** Represents an Index. */
class Index implements IIndex {
/**
* Constructs a new Index.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IIndex);
/** Index id. */
public id: (number|Long);
/** Index symbol. */
public symbol: string;
/** Index indexType. */
public indexType: string;
/** Index cwIndex. */
public cwIndex: boolean;
/** Index exchangeId. */
public exchangeId: (number|Long);
/** Index instrumentId. */
public instrumentId: (number|Long);
/**
* Creates a new Index instance using the specified properties.
* @param [properties] Properties to set
* @returns Index instance
*/
public static create(properties?: ProtobufMarkets.IIndex): ProtobufMarkets.Index;
/**
* Encodes the specified Index message. Does not implicitly {@link ProtobufMarkets.Index.verify|verify} messages.
* @param message Index message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IIndex, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Index message, length delimited. Does not implicitly {@link ProtobufMarkets.Index.verify|verify} messages.
* @param message Index message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IIndex, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Index message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Index
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Index;
/**
* Decodes an Index message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Index
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Index;
/**
* Verifies an Index message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Index message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Index
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Index;
/**
* Creates a plain object from an Index message. Also converts values to other types if specified.
* @param message Index
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Index, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Index to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an IndexUpdateMessage. */
interface IIndexUpdateMessage {
/** IndexUpdateMessage index */
index?: (ProtobufMarkets.IIndex|null);
/** IndexUpdateMessage tickerUpdate */
tickerUpdate?: (ProtobufMarkets.ITickerUpdate|null);
/** IndexUpdateMessage intervalsUpdate */
intervalsUpdate?: (ProtobufMarkets.IIntervalsUpdate|null);
/** IndexUpdateMessage summaryUpdate */
summaryUpdate?: (ProtobufMarkets.ISummaryUpdate|null);
/** IndexUpdateMessage sparklineUpdate */
sparklineUpdate?: (ProtobufMarkets.ISparklineUpdate|null);
}
/** Represents an IndexUpdateMessage. */
class IndexUpdateMessage implements IIndexUpdateMessage {
/**
* Constructs a new IndexUpdateMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IIndexUpdateMessage);
/** IndexUpdateMessage index. */
public index?: (ProtobufMarkets.IIndex|null);
/** IndexUpdateMessage tickerUpdate. */
public tickerUpdate?: (ProtobufMarkets.ITickerUpdate|null);
/** IndexUpdateMessage intervalsUpdate. */
public intervalsUpdate?: (ProtobufMarkets.IIntervalsUpdate|null);
/** IndexUpdateMessage summaryUpdate. */
public summaryUpdate?: (ProtobufMarkets.ISummaryUpdate|null);
/** IndexUpdateMessage sparklineUpdate. */
public sparklineUpdate?: (ProtobufMarkets.ISparklineUpdate|null);
/** IndexUpdateMessage Update. */
public Update?: ("tickerUpdate"|"intervalsUpdate"|"summaryUpdate"|"sparklineUpdate");
/**
* Creates a new IndexUpdateMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns IndexUpdateMessage instance
*/
public static create(properties?: ProtobufMarkets.IIndexUpdateMessage): ProtobufMarkets.IndexUpdateMessage;
/**
* Encodes the specified IndexUpdateMessage message. Does not implicitly {@link ProtobufMarkets.IndexUpdateMessage.verify|verify} messages.
* @param message IndexUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IIndexUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified IndexUpdateMessage message, length delimited. Does not implicitly {@link ProtobufMarkets.IndexUpdateMessage.verify|verify} messages.
* @param message IndexUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IIndexUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an IndexUpdateMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns IndexUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.IndexUpdateMessage;
/**
* Decodes an IndexUpdateMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns IndexUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.IndexUpdateMessage;
/**
* Verifies an IndexUpdateMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an IndexUpdateMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns IndexUpdateMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.IndexUpdateMessage;
/**
* Creates a plain object from an IndexUpdateMessage message. Also converts values to other types if specified.
* @param message IndexUpdateMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.IndexUpdateMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this IndexUpdateMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TickerUpdate. */
interface ITickerUpdate {
/** TickerUpdate tickers */
tickers?: (ProtobufMarkets.ITicker[]|null);
}
/** Represents a TickerUpdate. */
class TickerUpdate implements ITickerUpdate {
/**
* Constructs a new TickerUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ITickerUpdate);
/** TickerUpdate tickers. */
public tickers: ProtobufMarkets.ITicker[];
/**
* Creates a new TickerUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns TickerUpdate instance
*/
public static create(properties?: ProtobufMarkets.ITickerUpdate): ProtobufMarkets.TickerUpdate;
/**
* Encodes the specified TickerUpdate message. Does not implicitly {@link ProtobufMarkets.TickerUpdate.verify|verify} messages.
* @param message TickerUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ITickerUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TickerUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.TickerUpdate.verify|verify} messages.
* @param message TickerUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ITickerUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TickerUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TickerUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.TickerUpdate;
/**
* Decodes a TickerUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TickerUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.TickerUpdate;
/**
* Verifies a TickerUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TickerUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TickerUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.TickerUpdate;
/**
* Creates a plain object from a TickerUpdate message. Also converts values to other types if specified.
* @param message TickerUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.TickerUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TickerUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Ticker. */
interface ITicker {
/** Ticker value */
value?: (string|null);
/** Ticker timestamp */
timestamp?: (number|Long|null);
/** Ticker timestampNano */
timestampNano?: (number|Long|null);
}
/** Represents a Ticker. */
class Ticker implements ITicker {
/**
* Constructs a new Ticker.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ITicker);
/** Ticker value. */
public value: string;
/** Ticker timestamp. */
public timestamp: (number|Long);
/** Ticker timestampNano. */
public timestampNano: (number|Long);
/**
* Creates a new Ticker instance using the specified properties.
* @param [properties] Properties to set
* @returns Ticker instance
*/
public static create(properties?: ProtobufMarkets.ITicker): ProtobufMarkets.Ticker;
/**
* Encodes the specified Ticker message. Does not implicitly {@link ProtobufMarkets.Ticker.verify|verify} messages.
* @param message Ticker message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ITicker, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Ticker message, length delimited. Does not implicitly {@link ProtobufMarkets.Ticker.verify|verify} messages.
* @param message Ticker message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ITicker, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Ticker message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Ticker
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Ticker;
/**
* Decodes a Ticker message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Ticker
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Ticker;
/**
* Verifies a Ticker message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Ticker message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Ticker
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Ticker;
/**
* Creates a plain object from a Ticker message. Also converts values to other types if specified.
* @param message Ticker
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Ticker, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Ticker to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Market. */
interface IMarket {
/** Market exchangeId */
exchangeId?: (number|Long|null);
/** Market currencyPairId */
currencyPairId?: (number|Long|null);
/** Market marketId */
marketId?: (number|Long|null);
/** Market exchange */
exchange?: (string|null);
/** Market currencyPair */
currencyPair?: (string|null);
}
/** Represents a Market. */
class Market implements IMarket {
/**
* Constructs a new Market.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IMarket);
/** Market exchangeId. */
public exchangeId: (number|Long);
/** Market currencyPairId. */
public currencyPairId: (number|Long);
/** Market marketId. */
public marketId: (number|Long);
/** Market exchange. */
public exchange: string;
/** Market currencyPair. */
public currencyPair: string;
/**
* Creates a new Market instance using the specified properties.
* @param [properties] Properties to set
* @returns Market instance
*/
public static create(properties?: ProtobufMarkets.IMarket): ProtobufMarkets.Market;
/**
* Encodes the specified Market message. Does not implicitly {@link ProtobufMarkets.Market.verify|verify} messages.
* @param message Market message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IMarket, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Market message, length delimited. Does not implicitly {@link ProtobufMarkets.Market.verify|verify} messages.
* @param message Market message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IMarket, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Market message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Market
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Market;
/**
* Decodes a Market message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Market
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Market;
/**
* Verifies a Market message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Market message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Market
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Market;
/**
* Creates a plain object from a Market message. Also converts values to other types if specified.
* @param message Market
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Market, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Market to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Order. */
interface IOrder {
/** Order priceStr */
priceStr?: (string|null);
/** Order amountStr */
amountStr?: (string|null);
}
/** Represents an Order. */
class Order implements IOrder {
/**
* Constructs a new Order.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IOrder);
/** Order priceStr. */
public priceStr: string;
/** Order amountStr. */
public amountStr: string;
/**
* Creates a new Order instance using the specified properties.
* @param [properties] Properties to set
* @returns Order instance
*/
public static create(properties?: ProtobufMarkets.IOrder): ProtobufMarkets.Order;
/**
* Encodes the specified Order message. Does not implicitly {@link ProtobufMarkets.Order.verify|verify} messages.
* @param message Order message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IOrder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Order message, length delimited. Does not implicitly {@link ProtobufMarkets.Order.verify|verify} messages.
* @param message Order message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IOrder, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Order message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Order
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Order;
/**
* Decodes an Order message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Order
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Order;
/**
* Verifies an Order message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Order message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Order
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Order;
/**
* Creates a plain object from an Order message. Also converts values to other types if specified.
* @param message Order
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Order, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Order to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Trade. */
interface ITrade {
/** Trade externalId */
externalId?: (string|null);
/** Trade timestamp */
timestamp?: (number|Long|null);
/** Trade timestampNano */
timestampNano?: (number|Long|null);
/** Trade priceStr */
priceStr?: (string|null);
/** Trade amountStr */
amountStr?: (string|null);
/** Trade orderSide */
orderSide?: (ProtobufMarkets.Trade.OrderSide|null);
}
/** Represents a Trade. */
class Trade implements ITrade {
/**
* Constructs a new Trade.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ITrade);
/** Trade externalId. */
public externalId: string;
/** Trade timestamp. */
public timestamp: (number|Long);
/** Trade timestampNano. */
public timestampNano: (number|Long);
/** Trade priceStr. */
public priceStr: string;
/** Trade amountStr. */
public amountStr: string;
/** Trade orderSide. */
public orderSide: ProtobufMarkets.Trade.OrderSide;
/**
* Creates a new Trade instance using the specified properties.
* @param [properties] Properties to set
* @returns Trade instance
*/
public static create(properties?: ProtobufMarkets.ITrade): ProtobufMarkets.Trade;
/**
* Encodes the specified Trade message. Does not implicitly {@link ProtobufMarkets.Trade.verify|verify} messages.
* @param message Trade message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ITrade, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Trade message, length delimited. Does not implicitly {@link ProtobufMarkets.Trade.verify|verify} messages.
* @param message Trade message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ITrade, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Trade message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Trade
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Trade;
/**
* Decodes a Trade message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Trade
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Trade;
/**
* Verifies a Trade message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Trade message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Trade
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Trade;
/**
* Creates a plain object from a Trade message. Also converts values to other types if specified.
* @param message Trade
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Trade, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Trade to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Trade {
/** OrderSide enum. */
enum OrderSide {
UNKNOWN = 0,
BUYSIDE = 1,
SELLSIDE = 2
}
/** Side enum. */
enum Side {
BUY = 0,
SELL = 1
}
}
/** Properties of a MarketUpdateMessage. */
interface IMarketUpdateMessage {
/** MarketUpdateMessage market */
market?: (ProtobufMarkets.IMarket|null);
/** MarketUpdateMessage orderBookUpdate */
orderBookUpdate?: (ProtobufMarkets.IOrderBookUpdate|null);
/** MarketUpdateMessage orderBookDeltaUpdate */
orderBookDeltaUpdate?: (ProtobufMarkets.IOrderBookDeltaUpdate|null);
/** MarketUpdateMessage orderBookSpreadUpdate */
orderBookSpreadUpdate?: (ProtobufMarkets.IOrderBookSpreadUpdate|null);
/** MarketUpdateMessage orderBookLiquidityUpdate */
orderBookLiquidityUpdate?: (ProtobufMarkets.IOrderBookLiquidityUpdate|null);
/** MarketUpdateMessage tradesUpdate */
tradesUpdate?: (ProtobufMarkets.ITradesUpdate|null);
/** MarketUpdateMessage intervalsUpdate */
intervalsUpdate?: (ProtobufMarkets.IIntervalsUpdate|null);
/** MarketUpdateMessage summaryUpdate */
summaryUpdate?: (ProtobufMarkets.ISummaryUpdate|null);
/** MarketUpdateMessage sparklineUpdate */
sparklineUpdate?: (ProtobufMarkets.ISparklineUpdate|null);
}
/** Represents a MarketUpdateMessage. */
class MarketUpdateMessage implements IMarketUpdateMessage {
/**
* Constructs a new MarketUpdateMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IMarketUpdateMessage);
/** MarketUpdateMessage market. */
public market?: (ProtobufMarkets.IMarket|null);
/** MarketUpdateMessage orderBookUpdate. */
public orderBookUpdate?: (ProtobufMarkets.IOrderBookUpdate|null);
/** MarketUpdateMessage orderBookDeltaUpdate. */
public orderBookDeltaUpdate?: (ProtobufMarkets.IOrderBookDeltaUpdate|null);
/** MarketUpdateMessage orderBookSpreadUpdate. */
public orderBookSpreadUpdate?: (ProtobufMarkets.IOrderBookSpreadUpdate|null);
/** MarketUpdateMessage orderBookLiquidityUpdate. */
public orderBookLiquidityUpdate?: (ProtobufMarkets.IOrderBookLiquidityUpdate|null);
/** MarketUpdateMessage tradesUpdate. */
public tradesUpdate?: (ProtobufMarkets.ITradesUpdate|null);
/** MarketUpdateMessage intervalsUpdate. */
public intervalsUpdate?: (ProtobufMarkets.IIntervalsUpdate|null);
/** MarketUpdateMessage summaryUpdate. */
public summaryUpdate?: (ProtobufMarkets.ISummaryUpdate|null);
/** MarketUpdateMessage sparklineUpdate. */
public sparklineUpdate?: (ProtobufMarkets.ISparklineUpdate|null);
/** MarketUpdateMessage Update. */
public Update?: ("orderBookUpdate"|"orderBookDeltaUpdate"|"orderBookSpreadUpdate"|"orderBookLiquidityUpdate"|"tradesUpdate"|"intervalsUpdate"|"summaryUpdate"|"sparklineUpdate");
/**
* Creates a new MarketUpdateMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns MarketUpdateMessage instance
*/
public static create(properties?: ProtobufMarkets.IMarketUpdateMessage): ProtobufMarkets.MarketUpdateMessage;
/**
* Encodes the specified MarketUpdateMessage message. Does not implicitly {@link ProtobufMarkets.MarketUpdateMessage.verify|verify} messages.
* @param message MarketUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IMarketUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MarketUpdateMessage message, length delimited. Does not implicitly {@link ProtobufMarkets.MarketUpdateMessage.verify|verify} messages.
* @param message MarketUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IMarketUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MarketUpdateMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MarketUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.MarketUpdateMessage;
/**
* Decodes a MarketUpdateMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MarketUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.MarketUpdateMessage;
/**
* Verifies a MarketUpdateMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MarketUpdateMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MarketUpdateMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.MarketUpdateMessage;
/**
* Creates a plain object from a MarketUpdateMessage message. Also converts values to other types if specified.
* @param message MarketUpdateMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.MarketUpdateMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MarketUpdateMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OrderBookUpdate. */
interface IOrderBookUpdate {
/** OrderBookUpdate aggregationModulusStr */
aggregationModulusStr?: (string|null);
/** OrderBookUpdate seqNum */
seqNum?: (number|null);
/** OrderBookUpdate bids */
bids?: (ProtobufMarkets.IOrder[]|null);
/** OrderBookUpdate asks */
asks?: (ProtobufMarkets.IOrder[]|null);
}
/** Represents an OrderBookUpdate. */
class OrderBookUpdate implements IOrderBookUpdate {
/**
* Constructs a new OrderBookUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IOrderBookUpdate);
/** OrderBookUpdate aggregationModulusStr. */
public aggregationModulusStr: string;
/** OrderBookUpdate seqNum. */
public seqNum: number;
/** OrderBookUpdate bids. */
public bids: ProtobufMarkets.IOrder[];
/** OrderBookUpdate asks. */
public asks: ProtobufMarkets.IOrder[];
/**
* Creates a new OrderBookUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookUpdate instance
*/
public static create(properties?: ProtobufMarkets.IOrderBookUpdate): ProtobufMarkets.OrderBookUpdate;
/**
* Encodes the specified OrderBookUpdate message. Does not implicitly {@link ProtobufMarkets.OrderBookUpdate.verify|verify} messages.
* @param message OrderBookUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IOrderBookUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookUpdate.verify|verify} messages.
* @param message OrderBookUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IOrderBookUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookUpdate;
/**
* Decodes an OrderBookUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookUpdate;
/**
* Verifies an OrderBookUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookUpdate;
/**
* Creates a plain object from an OrderBookUpdate message. Also converts values to other types if specified.
* @param message OrderBookUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OrderBookDeltaUpdate. */
interface IOrderBookDeltaUpdate {
/** OrderBookDeltaUpdate aggregationModulusStr */
aggregationModulusStr?: (string|null);
/** OrderBookDeltaUpdate seqNum */
seqNum?: (number|null);
/** OrderBookDeltaUpdate bids */
bids?: (ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas|null);
/** OrderBookDeltaUpdate asks */
asks?: (ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas|null);
}
/** Represents an OrderBookDeltaUpdate. */
class OrderBookDeltaUpdate implements IOrderBookDeltaUpdate {
/**
* Constructs a new OrderBookDeltaUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IOrderBookDeltaUpdate);
/** OrderBookDeltaUpdate aggregationModulusStr. */
public aggregationModulusStr: string;
/** OrderBookDeltaUpdate seqNum. */
public seqNum: number;
/** OrderBookDeltaUpdate bids. */
public bids?: (ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas|null);
/** OrderBookDeltaUpdate asks. */
public asks?: (ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas|null);
/**
* Creates a new OrderBookDeltaUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookDeltaUpdate instance
*/
public static create(properties?: ProtobufMarkets.IOrderBookDeltaUpdate): ProtobufMarkets.OrderBookDeltaUpdate;
/**
* Encodes the specified OrderBookDeltaUpdate message. Does not implicitly {@link ProtobufMarkets.OrderBookDeltaUpdate.verify|verify} messages.
* @param message OrderBookDeltaUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IOrderBookDeltaUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookDeltaUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookDeltaUpdate.verify|verify} messages.
* @param message OrderBookDeltaUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IOrderBookDeltaUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookDeltaUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookDeltaUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookDeltaUpdate;
/**
* Decodes an OrderBookDeltaUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookDeltaUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookDeltaUpdate;
/**
* Verifies an OrderBookDeltaUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookDeltaUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookDeltaUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookDeltaUpdate;
/**
* Creates a plain object from an OrderBookDeltaUpdate message. Also converts values to other types if specified.
* @param message OrderBookDeltaUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookDeltaUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookDeltaUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace OrderBookDeltaUpdate {
/** Properties of an OrderDeltas. */
interface IOrderDeltas {
/** OrderDeltas set */
set?: (ProtobufMarkets.IOrder[]|null);
/** OrderDeltas delta */
delta?: (ProtobufMarkets.IOrder[]|null);
/** OrderDeltas removeStr */
removeStr?: (string[]|null);
}
/** Represents an OrderDeltas. */
class OrderDeltas implements IOrderDeltas {
/**
* Constructs a new OrderDeltas.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas);
/** OrderDeltas set. */
public set: ProtobufMarkets.IOrder[];
/** OrderDeltas delta. */
public delta: ProtobufMarkets.IOrder[];
/** OrderDeltas removeStr. */
public removeStr: string[];
/**
* Creates a new OrderDeltas instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderDeltas instance
*/
public static create(properties?: ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas): ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas;
/**
* Encodes the specified OrderDeltas message. Does not implicitly {@link ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas.verify|verify} messages.
* @param message OrderDeltas message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderDeltas message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas.verify|verify} messages.
* @param message OrderDeltas message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.OrderBookDeltaUpdate.IOrderDeltas, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderDeltas message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderDeltas
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas;
/**
* Decodes an OrderDeltas message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderDeltas
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas;
/**
* Verifies an OrderDeltas message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderDeltas message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderDeltas
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas;
/**
* Creates a plain object from an OrderDeltas message. Also converts values to other types if specified.
* @param message OrderDeltas
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookDeltaUpdate.OrderDeltas, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderDeltas to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an OrderBookSpreadUpdate. */
interface IOrderBookSpreadUpdate {
/** OrderBookSpreadUpdate timestamp */
timestamp?: (number|Long|null);
/** OrderBookSpreadUpdate bid */
bid?: (ProtobufMarkets.IOrder|null);
/** OrderBookSpreadUpdate ask */
ask?: (ProtobufMarkets.IOrder|null);
}
/** Represents an OrderBookSpreadUpdate. */
class OrderBookSpreadUpdate implements IOrderBookSpreadUpdate {
/**
* Constructs a new OrderBookSpreadUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IOrderBookSpreadUpdate);
/** OrderBookSpreadUpdate timestamp. */
public timestamp: (number|Long);
/** OrderBookSpreadUpdate bid. */
public bid?: (ProtobufMarkets.IOrder|null);
/** OrderBookSpreadUpdate ask. */
public ask?: (ProtobufMarkets.IOrder|null);
/**
* Creates a new OrderBookSpreadUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookSpreadUpdate instance
*/
public static create(properties?: ProtobufMarkets.IOrderBookSpreadUpdate): ProtobufMarkets.OrderBookSpreadUpdate;
/**
* Encodes the specified OrderBookSpreadUpdate message. Does not implicitly {@link ProtobufMarkets.OrderBookSpreadUpdate.verify|verify} messages.
* @param message OrderBookSpreadUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IOrderBookSpreadUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookSpreadUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookSpreadUpdate.verify|verify} messages.
* @param message OrderBookSpreadUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IOrderBookSpreadUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookSpreadUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookSpreadUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookSpreadUpdate;
/**
* Decodes an OrderBookSpreadUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookSpreadUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookSpreadUpdate;
/**
* Verifies an OrderBookSpreadUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookSpreadUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookSpreadUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookSpreadUpdate;
/**
* Creates a plain object from an OrderBookSpreadUpdate message. Also converts values to other types if specified.
* @param message OrderBookSpreadUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookSpreadUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookSpreadUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OrderBookLiquidityUpdate. */
interface IOrderBookLiquidityUpdate {
/** OrderBookLiquidityUpdate timestamp */
timestamp?: (number|Long|null);
/** OrderBookLiquidityUpdate bid */
bid?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide|null);
/** OrderBookLiquidityUpdate ask */
ask?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide|null);
}
/** Represents an OrderBookLiquidityUpdate. */
class OrderBookLiquidityUpdate implements IOrderBookLiquidityUpdate {
/**
* Constructs a new OrderBookLiquidityUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IOrderBookLiquidityUpdate);
/** OrderBookLiquidityUpdate timestamp. */
public timestamp: (number|Long);
/** OrderBookLiquidityUpdate bid. */
public bid?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide|null);
/** OrderBookLiquidityUpdate ask. */
public ask?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide|null);
/**
* Creates a new OrderBookLiquidityUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookLiquidityUpdate instance
*/
public static create(properties?: ProtobufMarkets.IOrderBookLiquidityUpdate): ProtobufMarkets.OrderBookLiquidityUpdate;
/**
* Encodes the specified OrderBookLiquidityUpdate message. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.verify|verify} messages.
* @param message OrderBookLiquidityUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IOrderBookLiquidityUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookLiquidityUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.verify|verify} messages.
* @param message OrderBookLiquidityUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IOrderBookLiquidityUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookLiquidityUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookLiquidityUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookLiquidityUpdate;
/**
* Decodes an OrderBookLiquidityUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookLiquidityUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookLiquidityUpdate;
/**
* Verifies an OrderBookLiquidityUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookLiquidityUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookLiquidityUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookLiquidityUpdate;
/**
* Creates a plain object from an OrderBookLiquidityUpdate message. Also converts values to other types if specified.
* @param message OrderBookLiquidityUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookLiquidityUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookLiquidityUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace OrderBookLiquidityUpdate {
/** Properties of an OrderBookLiquiditySums. */
interface IOrderBookLiquiditySums {
/** OrderBookLiquiditySums totalBase */
totalBase?: (string|null);
/** OrderBookLiquiditySums totalQuote */
totalQuote?: (string|null);
}
/** Represents an OrderBookLiquiditySums. */
class OrderBookLiquiditySums implements IOrderBookLiquiditySums {
/**
* Constructs a new OrderBookLiquiditySums.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums);
/** OrderBookLiquiditySums totalBase. */
public totalBase: string;
/** OrderBookLiquiditySums totalQuote. */
public totalQuote: string;
/**
* Creates a new OrderBookLiquiditySums instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookLiquiditySums instance
*/
public static create(properties?: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums;
/**
* Encodes the specified OrderBookLiquiditySums message. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums.verify|verify} messages.
* @param message OrderBookLiquiditySums message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookLiquiditySums message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums.verify|verify} messages.
* @param message OrderBookLiquiditySums message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookLiquiditySums message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookLiquiditySums
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums;
/**
* Decodes an OrderBookLiquiditySums message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookLiquiditySums
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums;
/**
* Verifies an OrderBookLiquiditySums message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookLiquiditySums message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookLiquiditySums
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums;
/**
* Creates a plain object from an OrderBookLiquiditySums message. Also converts values to other types if specified.
* @param message OrderBookLiquiditySums
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquiditySums, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookLiquiditySums to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OrderBookLiquidityUpdateSide. */
interface IOrderBookLiquidityUpdateSide {
/** OrderBookLiquidityUpdateSide bip25 */
bip25?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip50 */
bip50?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip75 */
bip75?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip100 */
bip100?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip150 */
bip150?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip200 */
bip200?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip250 */
bip250?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip300 */
bip300?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip400 */
bip400?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip500 */
bip500?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
}
/** Represents an OrderBookLiquidityUpdateSide. */
class OrderBookLiquidityUpdateSide implements IOrderBookLiquidityUpdateSide {
/**
* Constructs a new OrderBookLiquidityUpdateSide.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide);
/** OrderBookLiquidityUpdateSide bip25. */
public bip25?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip50. */
public bip50?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip75. */
public bip75?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip100. */
public bip100?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip150. */
public bip150?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip200. */
public bip200?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip250. */
public bip250?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip300. */
public bip300?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip400. */
public bip400?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/** OrderBookLiquidityUpdateSide bip500. */
public bip500?: (ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquiditySums|null);
/**
* Creates a new OrderBookLiquidityUpdateSide instance using the specified properties.
* @param [properties] Properties to set
* @returns OrderBookLiquidityUpdateSide instance
*/
public static create(properties?: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide;
/**
* Encodes the specified OrderBookLiquidityUpdateSide message. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide.verify|verify} messages.
* @param message OrderBookLiquidityUpdateSide message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OrderBookLiquidityUpdateSide message, length delimited. Does not implicitly {@link ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide.verify|verify} messages.
* @param message OrderBookLiquidityUpdateSide message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.OrderBookLiquidityUpdate.IOrderBookLiquidityUpdateSide, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OrderBookLiquidityUpdateSide message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OrderBookLiquidityUpdateSide
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide;
/**
* Decodes an OrderBookLiquidityUpdateSide message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OrderBookLiquidityUpdateSide
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide;
/**
* Verifies an OrderBookLiquidityUpdateSide message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OrderBookLiquidityUpdateSide message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OrderBookLiquidityUpdateSide
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide;
/**
* Creates a plain object from an OrderBookLiquidityUpdateSide message. Also converts values to other types if specified.
* @param message OrderBookLiquidityUpdateSide
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.OrderBookLiquidityUpdate.OrderBookLiquidityUpdateSide, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OrderBookLiquidityUpdateSide to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a TradesUpdate. */
interface ITradesUpdate {
/** TradesUpdate trades */
trades?: (ProtobufMarkets.ITrade[]|null);
}
/** Represents a TradesUpdate. */
class TradesUpdate implements ITradesUpdate {
/**
* Constructs a new TradesUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ITradesUpdate);
/** TradesUpdate trades. */
public trades: ProtobufMarkets.ITrade[];
/**
* Creates a new TradesUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns TradesUpdate instance
*/
public static create(properties?: ProtobufMarkets.ITradesUpdate): ProtobufMarkets.TradesUpdate;
/**
* Encodes the specified TradesUpdate message. Does not implicitly {@link ProtobufMarkets.TradesUpdate.verify|verify} messages.
* @param message TradesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ITradesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TradesUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.TradesUpdate.verify|verify} messages.
* @param message TradesUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ITradesUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TradesUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TradesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.TradesUpdate;
/**
* Decodes a TradesUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TradesUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.TradesUpdate;
/**
* Verifies a TradesUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TradesUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TradesUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.TradesUpdate;
/**
* Creates a plain object from a TradesUpdate message. Also converts values to other types if specified.
* @param message TradesUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.TradesUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TradesUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Interval. */
interface IInterval {
/** Interval closetime */
closetime?: (number|Long|null);
/** Interval ohlc */
ohlc?: (ProtobufMarkets.Interval.IOHLC|null);
/** Interval volumeBaseStr */
volumeBaseStr?: (string|null);
/** Interval volumeQuoteStr */
volumeQuoteStr?: (string|null);
/** Interval periodName */
periodName?: (string|null);
/** Interval period */
period?: (number|null);
}
/** Represents an Interval. */
class Interval implements IInterval {
/**
* Constructs a new Interval.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IInterval);
/** Interval closetime. */
public closetime: (number|Long);
/** Interval ohlc. */
public ohlc?: (ProtobufMarkets.Interval.IOHLC|null);
/** Interval volumeBaseStr. */
public volumeBaseStr: string;
/** Interval volumeQuoteStr. */
public volumeQuoteStr: string;
/** Interval periodName. */
public periodName: string;
/** Interval period. */
public period: number;
/**
* Creates a new Interval instance using the specified properties.
* @param [properties] Properties to set
* @returns Interval instance
*/
public static create(properties?: ProtobufMarkets.IInterval): ProtobufMarkets.Interval;
/**
* Encodes the specified Interval message. Does not implicitly {@link ProtobufMarkets.Interval.verify|verify} messages.
* @param message Interval message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IInterval, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Interval message, length delimited. Does not implicitly {@link ProtobufMarkets.Interval.verify|verify} messages.
* @param message Interval message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IInterval, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Interval message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Interval
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Interval;
/**
* Decodes an Interval message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Interval
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Interval;
/**
* Verifies an Interval message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Interval message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Interval
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Interval;
/**
* Creates a plain object from an Interval message. Also converts values to other types if specified.
* @param message Interval
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Interval, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Interval to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Interval {
/** Properties of a OHLC. */
interface IOHLC {
/** OHLC openStr */
openStr?: (string|null);
/** OHLC highStr */
highStr?: (string|null);
/** OHLC lowStr */
lowStr?: (string|null);
/** OHLC closeStr */
closeStr?: (string|null);
}
/** Represents a OHLC. */
class OHLC implements IOHLC {
/**
* Constructs a new OHLC.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.Interval.IOHLC);
/** OHLC openStr. */
public openStr: string;
/** OHLC highStr. */
public highStr: string;
/** OHLC lowStr. */
public lowStr: string;
/** OHLC closeStr. */
public closeStr: string;
/**
* Creates a new OHLC instance using the specified properties.
* @param [properties] Properties to set
* @returns OHLC instance
*/
public static create(properties?: ProtobufMarkets.Interval.IOHLC): ProtobufMarkets.Interval.OHLC;
/**
* Encodes the specified OHLC message. Does not implicitly {@link ProtobufMarkets.Interval.OHLC.verify|verify} messages.
* @param message OHLC message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.Interval.IOHLC, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OHLC message, length delimited. Does not implicitly {@link ProtobufMarkets.Interval.OHLC.verify|verify} messages.
* @param message OHLC message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.Interval.IOHLC, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a OHLC message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OHLC
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.Interval.OHLC;
/**
* Decodes a OHLC message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OHLC
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.Interval.OHLC;
/**
* Verifies a OHLC message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a OHLC message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OHLC
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.Interval.OHLC;
/**
* Creates a plain object from a OHLC message. Also converts values to other types if specified.
* @param message OHLC
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.Interval.OHLC, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OHLC to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an IntervalsUpdate. */
interface IIntervalsUpdate {
/** IntervalsUpdate intervals */
intervals?: (ProtobufMarkets.IInterval[]|null);
}
/** Represents an IntervalsUpdate. */
class IntervalsUpdate implements IIntervalsUpdate {
/**
* Constructs a new IntervalsUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IIntervalsUpdate);
/** IntervalsUpdate intervals. */
public intervals: ProtobufMarkets.IInterval[];
/**
* Creates a new IntervalsUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns IntervalsUpdate instance
*/
public static create(properties?: ProtobufMarkets.IIntervalsUpdate): ProtobufMarkets.IntervalsUpdate;
/**
* Encodes the specified IntervalsUpdate message. Does not implicitly {@link ProtobufMarkets.IntervalsUpdate.verify|verify} messages.
* @param message IntervalsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IIntervalsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified IntervalsUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.IntervalsUpdate.verify|verify} messages.
* @param message IntervalsUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IIntervalsUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an IntervalsUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns IntervalsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.IntervalsUpdate;
/**
* Decodes an IntervalsUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns IntervalsUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.IntervalsUpdate;
/**
* Verifies an IntervalsUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an IntervalsUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns IntervalsUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.IntervalsUpdate;
/**
* Creates a plain object from an IntervalsUpdate message. Also converts values to other types if specified.
* @param message IntervalsUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.IntervalsUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this IntervalsUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SummaryUpdate. */
interface ISummaryUpdate {
/** SummaryUpdate lastStr */
lastStr?: (string|null);
/** SummaryUpdate highStr */
highStr?: (string|null);
/** SummaryUpdate lowStr */
lowStr?: (string|null);
/** SummaryUpdate volumeBaseStr */
volumeBaseStr?: (string|null);
/** SummaryUpdate volumeQuoteStr */
volumeQuoteStr?: (string|null);
/** SummaryUpdate changeAbsoluteStr */
changeAbsoluteStr?: (string|null);
/** SummaryUpdate changePercentStr */
changePercentStr?: (string|null);
/** SummaryUpdate numTrades */
numTrades?: (number|null);
}
/** Represents a SummaryUpdate. */
class SummaryUpdate implements ISummaryUpdate {
/**
* Constructs a new SummaryUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ISummaryUpdate);
/** SummaryUpdate lastStr. */
public lastStr: string;
/** SummaryUpdate highStr. */
public highStr: string;
/** SummaryUpdate lowStr. */
public lowStr: string;
/** SummaryUpdate volumeBaseStr. */
public volumeBaseStr: string;
/** SummaryUpdate volumeQuoteStr. */
public volumeQuoteStr: string;
/** SummaryUpdate changeAbsoluteStr. */
public changeAbsoluteStr: string;
/** SummaryUpdate changePercentStr. */
public changePercentStr: string;
/** SummaryUpdate numTrades. */
public numTrades: number;
/**
* Creates a new SummaryUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns SummaryUpdate instance
*/
public static create(properties?: ProtobufMarkets.ISummaryUpdate): ProtobufMarkets.SummaryUpdate;
/**
* Encodes the specified SummaryUpdate message. Does not implicitly {@link ProtobufMarkets.SummaryUpdate.verify|verify} messages.
* @param message SummaryUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ISummaryUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SummaryUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.SummaryUpdate.verify|verify} messages.
* @param message SummaryUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ISummaryUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SummaryUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SummaryUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.SummaryUpdate;
/**
* Decodes a SummaryUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SummaryUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.SummaryUpdate;
/**
* Verifies a SummaryUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SummaryUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SummaryUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.SummaryUpdate;
/**
* Creates a plain object from a SummaryUpdate message. Also converts values to other types if specified.
* @param message SummaryUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.SummaryUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SummaryUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SparklineUpdate. */
interface ISparklineUpdate {
/** SparklineUpdate time */
time?: (number|Long|null);
/** SparklineUpdate priceStr */
priceStr?: (string|null);
}
/** Represents a SparklineUpdate. */
class SparklineUpdate implements ISparklineUpdate {
/**
* Constructs a new SparklineUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.ISparklineUpdate);
/** SparklineUpdate time. */
public time: (number|Long);
/** SparklineUpdate priceStr. */
public priceStr: string;
/**
* Creates a new SparklineUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns SparklineUpdate instance
*/
public static create(properties?: ProtobufMarkets.ISparklineUpdate): ProtobufMarkets.SparklineUpdate;
/**
* Encodes the specified SparklineUpdate message. Does not implicitly {@link ProtobufMarkets.SparklineUpdate.verify|verify} messages.
* @param message SparklineUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.ISparklineUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SparklineUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.SparklineUpdate.verify|verify} messages.
* @param message SparklineUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.ISparklineUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SparklineUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SparklineUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.SparklineUpdate;
/**
* Decodes a SparklineUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SparklineUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.SparklineUpdate;
/**
* Verifies a SparklineUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SparklineUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SparklineUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.SparklineUpdate;
/**
* Creates a plain object from a SparklineUpdate message. Also converts values to other types if specified.
* @param message SparklineUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.SparklineUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SparklineUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PairUpdateMessage. */
interface IPairUpdateMessage {
/** PairUpdateMessage pair */
pair?: (number|Long|null);
/** PairUpdateMessage vwapUpdate */
vwapUpdate?: (ProtobufMarkets.IPairVwapUpdate|null);
/** PairUpdateMessage performanceUpdate */
performanceUpdate?: (ProtobufMarkets.IPairPerformanceUpdate|null);
/** PairUpdateMessage trendlineUpdate */
trendlineUpdate?: (ProtobufMarkets.IPairTrendlineUpdate|null);
}
/** Represents a PairUpdateMessage. */
class PairUpdateMessage implements IPairUpdateMessage {
/**
* Constructs a new PairUpdateMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IPairUpdateMessage);
/** PairUpdateMessage pair. */
public pair: (number|Long);
/** PairUpdateMessage vwapUpdate. */
public vwapUpdate?: (ProtobufMarkets.IPairVwapUpdate|null);
/** PairUpdateMessage performanceUpdate. */
public performanceUpdate?: (ProtobufMarkets.IPairPerformanceUpdate|null);
/** PairUpdateMessage trendlineUpdate. */
public trendlineUpdate?: (ProtobufMarkets.IPairTrendlineUpdate|null);
/** PairUpdateMessage Update. */
public Update?: ("vwapUpdate"|"performanceUpdate"|"trendlineUpdate");
/**
* Creates a new PairUpdateMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns PairUpdateMessage instance
*/
public static create(properties?: ProtobufMarkets.IPairUpdateMessage): ProtobufMarkets.PairUpdateMessage;
/**
* Encodes the specified PairUpdateMessage message. Does not implicitly {@link ProtobufMarkets.PairUpdateMessage.verify|verify} messages.
* @param message PairUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IPairUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PairUpdateMessage message, length delimited. Does not implicitly {@link ProtobufMarkets.PairUpdateMessage.verify|verify} messages.
* @param message PairUpdateMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IPairUpdateMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PairUpdateMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PairUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.PairUpdateMessage;
/**
* Decodes a PairUpdateMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PairUpdateMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.PairUpdateMessage;
/**
* Verifies a PairUpdateMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PairUpdateMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PairUpdateMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.PairUpdateMessage;
/**
* Creates a plain object from a PairUpdateMessage message. Also converts values to other types if specified.
* @param message PairUpdateMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.PairUpdateMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PairUpdateMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PairVwapUpdate. */
interface IPairVwapUpdate {
/** PairVwapUpdate vwap */
vwap?: (number|null);
/** PairVwapUpdate timestamp */
timestamp?: (number|Long|null);
/** PairVwapUpdate timestampNano */
timestampNano?: (number|Long|null);
}
/** Represents a PairVwapUpdate. */
class PairVwapUpdate implements IPairVwapUpdate {
/**
* Constructs a new PairVwapUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IPairVwapUpdate);
/** PairVwapUpdate vwap. */
public vwap: number;
/** PairVwapUpdate timestamp. */
public timestamp: (number|Long);
/** PairVwapUpdate timestampNano. */
public timestampNano: (number|Long);
/**
* Creates a new PairVwapUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PairVwapUpdate instance
*/
public static create(properties?: ProtobufMarkets.IPairVwapUpdate): ProtobufMarkets.PairVwapUpdate;
/**
* Encodes the specified PairVwapUpdate message. Does not implicitly {@link ProtobufMarkets.PairVwapUpdate.verify|verify} messages.
* @param message PairVwapUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IPairVwapUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PairVwapUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.PairVwapUpdate.verify|verify} messages.
* @param message PairVwapUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IPairVwapUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PairVwapUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PairVwapUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.PairVwapUpdate;
/**
* Decodes a PairVwapUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PairVwapUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.PairVwapUpdate;
/**
* Verifies a PairVwapUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PairVwapUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PairVwapUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.PairVwapUpdate;
/**
* Creates a plain object from a PairVwapUpdate message. Also converts values to other types if specified.
* @param message PairVwapUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.PairVwapUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PairVwapUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PairPerformanceUpdate. */
interface IPairPerformanceUpdate {
/** PairPerformanceUpdate window */
window?: (string|null);
/** PairPerformanceUpdate performance */
performance?: (number|null);
}
/** Represents a PairPerformanceUpdate. */
class PairPerformanceUpdate implements IPairPerformanceUpdate {
/**
* Constructs a new PairPerformanceUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IPairPerformanceUpdate);
/** PairPerformanceUpdate window. */
public window: string;
/** PairPerformanceUpdate performance. */
public performance: number;
/**
* Creates a new PairPerformanceUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PairPerformanceUpdate instance
*/
public static create(properties?: ProtobufMarkets.IPairPerformanceUpdate): ProtobufMarkets.PairPerformanceUpdate;
/**
* Encodes the specified PairPerformanceUpdate message. Does not implicitly {@link ProtobufMarkets.PairPerformanceUpdate.verify|verify} messages.
* @param message PairPerformanceUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IPairPerformanceUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PairPerformanceUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.PairPerformanceUpdate.verify|verify} messages.
* @param message PairPerformanceUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IPairPerformanceUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PairPerformanceUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PairPerformanceUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.PairPerformanceUpdate;
/**
* Decodes a PairPerformanceUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PairPerformanceUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.PairPerformanceUpdate;
/**
* Verifies a PairPerformanceUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PairPerformanceUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PairPerformanceUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.PairPerformanceUpdate;
/**
* Creates a plain object from a PairPerformanceUpdate message. Also converts values to other types if specified.
* @param message PairPerformanceUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.PairPerformanceUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PairPerformanceUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PairTrendlineUpdate. */
interface IPairTrendlineUpdate {
/** PairTrendlineUpdate window */
window?: (string|null);
/** PairTrendlineUpdate time */
time?: (number|Long|null);
/** PairTrendlineUpdate price */
price?: (string|null);
/** PairTrendlineUpdate volume */
volume?: (string|null);
}
/** Represents a PairTrendlineUpdate. */
class PairTrendlineUpdate implements IPairTrendlineUpdate {
/**
* Constructs a new PairTrendlineUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufMarkets.IPairTrendlineUpdate);
/** PairTrendlineUpdate window. */
public window: string;
/** PairTrendlineUpdate time. */
public time: (number|Long);
/** PairTrendlineUpdate price. */
public price: string;
/** PairTrendlineUpdate volume. */
public volume: string;
/**
* Creates a new PairTrendlineUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns PairTrendlineUpdate instance
*/
public static create(properties?: ProtobufMarkets.IPairTrendlineUpdate): ProtobufMarkets.PairTrendlineUpdate;
/**
* Encodes the specified PairTrendlineUpdate message. Does not implicitly {@link ProtobufMarkets.PairTrendlineUpdate.verify|verify} messages.
* @param message PairTrendlineUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufMarkets.IPairTrendlineUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PairTrendlineUpdate message, length delimited. Does not implicitly {@link ProtobufMarkets.PairTrendlineUpdate.verify|verify} messages.
* @param message PairTrendlineUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufMarkets.IPairTrendlineUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PairTrendlineUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PairTrendlineUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufMarkets.PairTrendlineUpdate;
/**
* Decodes a PairTrendlineUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PairTrendlineUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufMarkets.PairTrendlineUpdate;
/**
* Verifies a PairTrendlineUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PairTrendlineUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PairTrendlineUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufMarkets.PairTrendlineUpdate;
/**
* Creates a plain object from a PairTrendlineUpdate message. Also converts values to other types if specified.
* @param message PairTrendlineUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufMarkets.PairTrendlineUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PairTrendlineUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace ProtobufStream. */
export namespace ProtobufStream {
/** Properties of a StreamMessage. */
interface IStreamMessage {
/** StreamMessage authenticationResult */
authenticationResult?: (ProtobufStream.IAuthenticationResult|null);
/** StreamMessage subscriptionResult */
subscriptionResult?: (ProtobufStream.ISubscriptionResult|null);
/** StreamMessage unsubscriptionResult */
unsubscriptionResult?: (ProtobufStream.IUnsubscriptionResult|null);
/** StreamMessage missedMessages */
missedMessages?: (ProtobufStream.IMissedMessages|null);
/** StreamMessage marketUpdate */
marketUpdate?: (ProtobufMarkets.IMarketUpdateMessage|null);
/** StreamMessage pairUpdate */
pairUpdate?: (ProtobufMarkets.IPairUpdateMessage|null);
/** StreamMessage assetUpdate */
assetUpdate?: (ProtobufMarkets.IAssetUpdateMessage|null);
/** StreamMessage indexUpdate */
indexUpdate?: (ProtobufMarkets.IIndexUpdateMessage|null);
/** StreamMessage bandwidthUpdate */
bandwidthUpdate?: (ProtobufStream.IBandwidthUpdate|null);
/** StreamMessage heartbeat */
heartbeat?: (ProtobufStream.IHeartbeat|null);
}
/** Represents a StreamMessage. */
class StreamMessage implements IStreamMessage {
/**
* Constructs a new StreamMessage.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IStreamMessage);
/** StreamMessage authenticationResult. */
public authenticationResult?: (ProtobufStream.IAuthenticationResult|null);
/** StreamMessage subscriptionResult. */
public subscriptionResult?: (ProtobufStream.ISubscriptionResult|null);
/** StreamMessage unsubscriptionResult. */
public unsubscriptionResult?: (ProtobufStream.IUnsubscriptionResult|null);
/** StreamMessage missedMessages. */
public missedMessages?: (ProtobufStream.IMissedMessages|null);
/** StreamMessage marketUpdate. */
public marketUpdate?: (ProtobufMarkets.IMarketUpdateMessage|null);
/** StreamMessage pairUpdate. */
public pairUpdate?: (ProtobufMarkets.IPairUpdateMessage|null);
/** StreamMessage assetUpdate. */
public assetUpdate?: (ProtobufMarkets.IAssetUpdateMessage|null);
/** StreamMessage indexUpdate. */
public indexUpdate?: (ProtobufMarkets.IIndexUpdateMessage|null);
/** StreamMessage bandwidthUpdate. */
public bandwidthUpdate?: (ProtobufStream.IBandwidthUpdate|null);
/** StreamMessage heartbeat. */
public heartbeat?: (ProtobufStream.IHeartbeat|null);
/** StreamMessage body. */
public body?: ("authenticationResult"|"subscriptionResult"|"unsubscriptionResult"|"missedMessages"|"marketUpdate"|"pairUpdate"|"assetUpdate"|"indexUpdate"|"bandwidthUpdate"|"heartbeat");
/**
* Creates a new StreamMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns StreamMessage instance
*/
public static create(properties?: ProtobufStream.IStreamMessage): ProtobufStream.StreamMessage;
/**
* Encodes the specified StreamMessage message. Does not implicitly {@link ProtobufStream.StreamMessage.verify|verify} messages.
* @param message StreamMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IStreamMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StreamMessage message, length delimited. Does not implicitly {@link ProtobufStream.StreamMessage.verify|verify} messages.
* @param message StreamMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IStreamMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StreamMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StreamMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.StreamMessage;
/**
* Decodes a StreamMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StreamMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.StreamMessage;
/**
* Verifies a StreamMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a StreamMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StreamMessage
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.StreamMessage;
/**
* Creates a plain object from a StreamMessage message. Also converts values to other types if specified.
* @param message StreamMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.StreamMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StreamMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AuthenticationResult. */
interface IAuthenticationResult {
/** AuthenticationResult status */
status?: (ProtobufStream.AuthenticationResult.Status|null);
}
/** Represents an AuthenticationResult. */
class AuthenticationResult implements IAuthenticationResult {
/**
* Constructs a new AuthenticationResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IAuthenticationResult);
/** AuthenticationResult status. */
public status: ProtobufStream.AuthenticationResult.Status;
/**
* Creates a new AuthenticationResult instance using the specified properties.
* @param [properties] Properties to set
* @returns AuthenticationResult instance
*/
public static create(properties?: ProtobufStream.IAuthenticationResult): ProtobufStream.AuthenticationResult;
/**
* Encodes the specified AuthenticationResult message. Does not implicitly {@link ProtobufStream.AuthenticationResult.verify|verify} messages.
* @param message AuthenticationResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IAuthenticationResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AuthenticationResult message, length delimited. Does not implicitly {@link ProtobufStream.AuthenticationResult.verify|verify} messages.
* @param message AuthenticationResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IAuthenticationResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AuthenticationResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AuthenticationResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.AuthenticationResult;
/**
* Decodes an AuthenticationResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AuthenticationResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.AuthenticationResult;
/**
* Verifies an AuthenticationResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AuthenticationResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AuthenticationResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.AuthenticationResult;
/**
* Creates a plain object from an AuthenticationResult message. Also converts values to other types if specified.
* @param message AuthenticationResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.AuthenticationResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AuthenticationResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace AuthenticationResult {
/** Status enum. */
enum Status {
UNKNOWN = 0,
AUTHENTICATED = 1,
BAD_NONCE = 2,
BAD_TOKEN = 3,
TOKEN_EXPIRED = 4,
READONLY_KEY = 5,
ACCESS_DENIED = 6,
INVALID_PUBLIC_KEY = 7
}
}
/** Properties of a SubscriptionResult. */
interface ISubscriptionResult {
/** SubscriptionResult subscribed */
subscribed?: (string[]|null);
/** SubscriptionResult failed */
failed?: (ProtobufStream.ISubscribeError[]|null);
/** SubscriptionResult status */
status?: (ProtobufStream.ISubscriptionStatus|null);
/** SubscriptionResult subscriptions */
subscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a SubscriptionResult. */
class SubscriptionResult implements ISubscriptionResult {
/**
* Constructs a new SubscriptionResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.ISubscriptionResult);
/** SubscriptionResult subscribed. */
public subscribed: string[];
/** SubscriptionResult failed. */
public failed: ProtobufStream.ISubscribeError[];
/** SubscriptionResult status. */
public status?: (ProtobufStream.ISubscriptionStatus|null);
/** SubscriptionResult subscriptions. */
public subscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new SubscriptionResult instance using the specified properties.
* @param [properties] Properties to set
* @returns SubscriptionResult instance
*/
public static create(properties?: ProtobufStream.ISubscriptionResult): ProtobufStream.SubscriptionResult;
/**
* Encodes the specified SubscriptionResult message. Does not implicitly {@link ProtobufStream.SubscriptionResult.verify|verify} messages.
* @param message SubscriptionResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.ISubscriptionResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SubscriptionResult message, length delimited. Does not implicitly {@link ProtobufStream.SubscriptionResult.verify|verify} messages.
* @param message SubscriptionResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.ISubscriptionResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SubscriptionResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SubscriptionResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.SubscriptionResult;
/**
* Decodes a SubscriptionResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SubscriptionResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.SubscriptionResult;
/**
* Verifies a SubscriptionResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SubscriptionResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SubscriptionResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.SubscriptionResult;
/**
* Creates a plain object from a SubscriptionResult message. Also converts values to other types if specified.
* @param message SubscriptionResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.SubscriptionResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SubscriptionResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an UnsubscriptionResult. */
interface IUnsubscriptionResult {
/** UnsubscriptionResult unsubscribed */
unsubscribed?: (string[]|null);
/** UnsubscriptionResult failed */
failed?: (ProtobufStream.IUnsubscribeError[]|null);
/** UnsubscriptionResult status */
status?: (ProtobufStream.ISubscriptionStatus|null);
/** UnsubscriptionResult subscriptions */
subscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents an UnsubscriptionResult. */
class UnsubscriptionResult implements IUnsubscriptionResult {
/**
* Constructs a new UnsubscriptionResult.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IUnsubscriptionResult);
/** UnsubscriptionResult unsubscribed. */
public unsubscribed: string[];
/** UnsubscriptionResult failed. */
public failed: ProtobufStream.IUnsubscribeError[];
/** UnsubscriptionResult status. */
public status?: (ProtobufStream.ISubscriptionStatus|null);
/** UnsubscriptionResult subscriptions. */
public subscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new UnsubscriptionResult instance using the specified properties.
* @param [properties] Properties to set
* @returns UnsubscriptionResult instance
*/
public static create(properties?: ProtobufStream.IUnsubscriptionResult): ProtobufStream.UnsubscriptionResult;
/**
* Encodes the specified UnsubscriptionResult message. Does not implicitly {@link ProtobufStream.UnsubscriptionResult.verify|verify} messages.
* @param message UnsubscriptionResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IUnsubscriptionResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UnsubscriptionResult message, length delimited. Does not implicitly {@link ProtobufStream.UnsubscriptionResult.verify|verify} messages.
* @param message UnsubscriptionResult message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IUnsubscriptionResult, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UnsubscriptionResult message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UnsubscriptionResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.UnsubscriptionResult;
/**
* Decodes an UnsubscriptionResult message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UnsubscriptionResult
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.UnsubscriptionResult;
/**
* Verifies an UnsubscriptionResult message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UnsubscriptionResult message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UnsubscriptionResult
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.UnsubscriptionResult;
/**
* Creates a plain object from an UnsubscriptionResult message. Also converts values to other types if specified.
* @param message UnsubscriptionResult
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.UnsubscriptionResult, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UnsubscriptionResult to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SubscribeError. */
interface ISubscribeError {
/** SubscribeError key */
key?: (string|null);
/** SubscribeError error */
error?: (string|null);
/** SubscribeError subscription */
subscription?: (ProtobufClient.IClientSubscription|null);
}
/** Represents a SubscribeError. */
class SubscribeError implements ISubscribeError {
/**
* Constructs a new SubscribeError.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.ISubscribeError);
/** SubscribeError key. */
public key: string;
/** SubscribeError error. */
public error: string;
/** SubscribeError subscription. */
public subscription?: (ProtobufClient.IClientSubscription|null);
/**
* Creates a new SubscribeError instance using the specified properties.
* @param [properties] Properties to set
* @returns SubscribeError instance
*/
public static create(properties?: ProtobufStream.ISubscribeError): ProtobufStream.SubscribeError;
/**
* Encodes the specified SubscribeError message. Does not implicitly {@link ProtobufStream.SubscribeError.verify|verify} messages.
* @param message SubscribeError message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.ISubscribeError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SubscribeError message, length delimited. Does not implicitly {@link ProtobufStream.SubscribeError.verify|verify} messages.
* @param message SubscribeError message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.ISubscribeError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SubscribeError message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SubscribeError
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.SubscribeError;
/**
* Decodes a SubscribeError message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SubscribeError
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.SubscribeError;
/**
* Verifies a SubscribeError message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SubscribeError message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SubscribeError
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.SubscribeError;
/**
* Creates a plain object from a SubscribeError message. Also converts values to other types if specified.
* @param message SubscribeError
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.SubscribeError, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SubscribeError to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an UnsubscribeError. */
interface IUnsubscribeError {
/** UnsubscribeError key */
key?: (string|null);
/** UnsubscribeError error */
error?: (string|null);
/** UnsubscribeError subscription */
subscription?: (ProtobufClient.IClientSubscription|null);
}
/** Represents an UnsubscribeError. */
class UnsubscribeError implements IUnsubscribeError {
/**
* Constructs a new UnsubscribeError.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IUnsubscribeError);
/** UnsubscribeError key. */
public key: string;
/** UnsubscribeError error. */
public error: string;
/** UnsubscribeError subscription. */
public subscription?: (ProtobufClient.IClientSubscription|null);
/**
* Creates a new UnsubscribeError instance using the specified properties.
* @param [properties] Properties to set
* @returns UnsubscribeError instance
*/
public static create(properties?: ProtobufStream.IUnsubscribeError): ProtobufStream.UnsubscribeError;
/**
* Encodes the specified UnsubscribeError message. Does not implicitly {@link ProtobufStream.UnsubscribeError.verify|verify} messages.
* @param message UnsubscribeError message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IUnsubscribeError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified UnsubscribeError message, length delimited. Does not implicitly {@link ProtobufStream.UnsubscribeError.verify|verify} messages.
* @param message UnsubscribeError message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IUnsubscribeError, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an UnsubscribeError message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns UnsubscribeError
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.UnsubscribeError;
/**
* Decodes an UnsubscribeError message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns UnsubscribeError
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.UnsubscribeError;
/**
* Verifies an UnsubscribeError message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an UnsubscribeError message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns UnsubscribeError
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.UnsubscribeError;
/**
* Creates a plain object from an UnsubscribeError message. Also converts values to other types if specified.
* @param message UnsubscribeError
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.UnsubscribeError, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this UnsubscribeError to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a SubscriptionStatus. */
interface ISubscriptionStatus {
/** SubscriptionStatus keys */
keys?: (string[]|null);
/** SubscriptionStatus subscriptions */
subscriptions?: (ProtobufClient.IClientSubscription[]|null);
}
/** Represents a SubscriptionStatus. */
class SubscriptionStatus implements ISubscriptionStatus {
/**
* Constructs a new SubscriptionStatus.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.ISubscriptionStatus);
/** SubscriptionStatus keys. */
public keys: string[];
/** SubscriptionStatus subscriptions. */
public subscriptions: ProtobufClient.IClientSubscription[];
/**
* Creates a new SubscriptionStatus instance using the specified properties.
* @param [properties] Properties to set
* @returns SubscriptionStatus instance
*/
public static create(properties?: ProtobufStream.ISubscriptionStatus): ProtobufStream.SubscriptionStatus;
/**
* Encodes the specified SubscriptionStatus message. Does not implicitly {@link ProtobufStream.SubscriptionStatus.verify|verify} messages.
* @param message SubscriptionStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.ISubscriptionStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified SubscriptionStatus message, length delimited. Does not implicitly {@link ProtobufStream.SubscriptionStatus.verify|verify} messages.
* @param message SubscriptionStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.ISubscriptionStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a SubscriptionStatus message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns SubscriptionStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.SubscriptionStatus;
/**
* Decodes a SubscriptionStatus message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns SubscriptionStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.SubscriptionStatus;
/**
* Verifies a SubscriptionStatus message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a SubscriptionStatus message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns SubscriptionStatus
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.SubscriptionStatus;
/**
* Creates a plain object from a SubscriptionStatus message. Also converts values to other types if specified.
* @param message SubscriptionStatus
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.SubscriptionStatus, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this SubscriptionStatus to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MissedMessages. */
interface IMissedMessages {
/** MissedMessages numMissedMessages */
numMissedMessages?: (number|Long|null);
}
/** Represents a MissedMessages. */
class MissedMessages implements IMissedMessages {
/**
* Constructs a new MissedMessages.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IMissedMessages);
/** MissedMessages numMissedMessages. */
public numMissedMessages: (number|Long);
/**
* Creates a new MissedMessages instance using the specified properties.
* @param [properties] Properties to set
* @returns MissedMessages instance
*/
public static create(properties?: ProtobufStream.IMissedMessages): ProtobufStream.MissedMessages;
/**
* Encodes the specified MissedMessages message. Does not implicitly {@link ProtobufStream.MissedMessages.verify|verify} messages.
* @param message MissedMessages message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IMissedMessages, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MissedMessages message, length delimited. Does not implicitly {@link ProtobufStream.MissedMessages.verify|verify} messages.
* @param message MissedMessages message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IMissedMessages, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MissedMessages message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MissedMessages
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.MissedMessages;
/**
* Decodes a MissedMessages message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MissedMessages
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.MissedMessages;
/**
* Verifies a MissedMessages message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MissedMessages message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MissedMessages
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.MissedMessages;
/**
* Creates a plain object from a MissedMessages message. Also converts values to other types if specified.
* @param message MissedMessages
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.MissedMessages, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MissedMessages to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BandwidthUpdate. */
interface IBandwidthUpdate {
/** BandwidthUpdate ok */
ok?: (boolean|null);
/** BandwidthUpdate bytesRemaining */
bytesRemaining?: (number|Long|null);
/** BandwidthUpdate bytesUsed */
bytesUsed?: (number|Long|null);
}
/** Represents a BandwidthUpdate. */
class BandwidthUpdate implements IBandwidthUpdate {
/**
* Constructs a new BandwidthUpdate.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IBandwidthUpdate);
/** BandwidthUpdate ok. */
public ok: boolean;
/** BandwidthUpdate bytesRemaining. */
public bytesRemaining: (number|Long);
/** BandwidthUpdate bytesUsed. */
public bytesUsed: (number|Long);
/**
* Creates a new BandwidthUpdate instance using the specified properties.
* @param [properties] Properties to set
* @returns BandwidthUpdate instance
*/
public static create(properties?: ProtobufStream.IBandwidthUpdate): ProtobufStream.BandwidthUpdate;
/**
* Encodes the specified BandwidthUpdate message. Does not implicitly {@link ProtobufStream.BandwidthUpdate.verify|verify} messages.
* @param message BandwidthUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IBandwidthUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BandwidthUpdate message, length delimited. Does not implicitly {@link ProtobufStream.BandwidthUpdate.verify|verify} messages.
* @param message BandwidthUpdate message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IBandwidthUpdate, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BandwidthUpdate message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BandwidthUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.BandwidthUpdate;
/**
* Decodes a BandwidthUpdate message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BandwidthUpdate
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.BandwidthUpdate;
/**
* Verifies a BandwidthUpdate message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a BandwidthUpdate message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BandwidthUpdate
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.BandwidthUpdate;
/**
* Creates a plain object from a BandwidthUpdate message. Also converts values to other types if specified.
* @param message BandwidthUpdate
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.BandwidthUpdate, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BandwidthUpdate to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Heartbeat. */
interface IHeartbeat {
/** Heartbeat time */
time?: (number|Long|null);
}
/** Represents a Heartbeat. */
class Heartbeat implements IHeartbeat {
/**
* Constructs a new Heartbeat.
* @param [properties] Properties to set
*/
constructor(properties?: ProtobufStream.IHeartbeat);
/** Heartbeat time. */
public time: (number|Long);
/**
* Creates a new Heartbeat instance using the specified properties.
* @param [properties] Properties to set
* @returns Heartbeat instance
*/
public static create(properties?: ProtobufStream.IHeartbeat): ProtobufStream.Heartbeat;
/**
* Encodes the specified Heartbeat message. Does not implicitly {@link ProtobufStream.Heartbeat.verify|verify} messages.
* @param message Heartbeat message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ProtobufStream.IHeartbeat, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Heartbeat message, length delimited. Does not implicitly {@link ProtobufStream.Heartbeat.verify|verify} messages.
* @param message Heartbeat message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ProtobufStream.IHeartbeat, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Heartbeat message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Heartbeat
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ProtobufStream.Heartbeat;
/**
* Decodes a Heartbeat message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Heartbeat
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ProtobufStream.Heartbeat;
/**
* Verifies a Heartbeat message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Heartbeat message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Heartbeat
*/
public static fromObject(object: { [k: string]: any }): ProtobufStream.Heartbeat;
/**
* Creates a plain object from a Heartbeat message. Also converts values to other types if specified.
* @param message Heartbeat
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ProtobufStream.Heartbeat, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Heartbeat to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
} | the_stack |
import { Template } from '@aws-cdk/assertions';
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';
import * as codepipeline from '../lib';
import * as validations from '../lib/private/validation';
import { FakeBuildAction } from './fake-build-action';
import { FakeSourceAction } from './fake-source-action';
/* eslint-disable quote-props */
describe('action', () => {
describe('artifact bounds validation', () => {
test('artifacts count exceed maximum', () => {
const result = boundsValidationResult(1, 0, 0);
expect(result.length).toEqual(1);
expect(result[0]).toMatch(/cannot have more than 0/);
});
test('artifacts count below minimum', () => {
const result = boundsValidationResult(1, 2, 2);
expect(result.length).toEqual(1);
expect(result[0]).toMatch(/must have at least 2/);
});
test('artifacts count within bounds', () => {
const result = boundsValidationResult(1, 0, 2);
expect(result.length).toEqual(0);
});
});
describe('action type validation', () => {
test('must be source and is source', () => {
const result = validations.validateSourceAction(true, codepipeline.ActionCategory.SOURCE, 'test action', 'test stage');
expect(result.length).toEqual(0);
});
test('must be source and is not source', () => {
const result = validations.validateSourceAction(true, codepipeline.ActionCategory.DEPLOY, 'test action', 'test stage');
expect(result.length).toEqual(1);
expect(result[0]).toMatch(/may only contain Source actions/);
});
test('cannot be source and is source', () => {
const result = validations.validateSourceAction(false, codepipeline.ActionCategory.SOURCE, 'test action', 'test stage');
expect(result.length).toEqual(1);
expect(result[0]).toMatch(/may only occur in first stage/);
});
test('cannot be source and is not source', () => {
const result = validations.validateSourceAction(false, codepipeline.ActionCategory.DEPLOY, 'test action', 'test stage');
expect(result.length).toEqual(0);
});
});
describe('action name validation', () => {
test('throws an exception when adding an Action with an empty name to the Pipeline', () => {
const stack = new cdk.Stack();
const action = new FakeSourceAction({
actionName: '',
output: new codepipeline.Artifact(),
});
const pipeline = new codepipeline.Pipeline(stack, 'Pipeline');
const stage = pipeline.addStage({ stageName: 'Source' });
expect(() => {
stage.addAction(action);
}).toThrow(/Action name must match regular expression:/);
});
});
describe('action Artifacts validation', () => {
test('validates that input Artifacts are within bounds', () => {
const stack = new cdk.Stack();
const sourceOutput = new codepipeline.Artifact();
const extraOutput1 = new codepipeline.Artifact('A1');
const extraOutput2 = new codepipeline.Artifact('A2');
const extraOutput3 = new codepipeline.Artifact('A3');
new codepipeline.Pipeline(stack, 'Pipeline', {
stages: [
{
stageName: 'Source',
actions: [
new FakeSourceAction({
actionName: 'Source',
output: sourceOutput,
extraOutputs: [
extraOutput1,
extraOutput2,
extraOutput3,
],
}),
],
},
{
stageName: 'Build',
actions: [
new FakeBuildAction({
actionName: 'Build',
input: sourceOutput,
extraInputs: [
extraOutput1,
extraOutput2,
extraOutput3,
],
}),
],
},
],
});
expect(() => {
Template.fromStack(stack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
});
}).toThrow(/Build\/Fake cannot have more than 3 input artifacts/);
});
test('validates that output Artifacts are within bounds', () => {
const stack = new cdk.Stack();
const sourceOutput = new codepipeline.Artifact();
const extraOutput1 = new codepipeline.Artifact('A1');
const extraOutput2 = new codepipeline.Artifact('A2');
const extraOutput3 = new codepipeline.Artifact('A3');
const extraOutput4 = new codepipeline.Artifact('A4');
new codepipeline.Pipeline(stack, 'Pipeline', {
stages: [
{
stageName: 'Source',
actions: [
new FakeSourceAction({
actionName: 'Source',
output: sourceOutput,
extraOutputs: [
extraOutput1,
extraOutput2,
extraOutput3,
extraOutput4,
],
}),
],
},
{
stageName: 'Build',
actions: [
new FakeBuildAction({
actionName: 'Build',
input: sourceOutput,
}),
],
},
],
});
expect(() => {
Template.fromStack(stack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
});
}).toThrow(/Source\/Fake cannot have more than 4 output artifacts/);
});
});
test('automatically assigns artifact names to the Actions', () => {
const stack = new cdk.Stack();
const pipeline = new codepipeline.Pipeline(stack, 'pipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new FakeSourceAction({
actionName: 'CodeCommit',
output: sourceOutput,
});
pipeline.addStage({
stageName: 'Source',
actions: [sourceAction],
});
pipeline.addStage({
stageName: 'Build',
actions: [
new FakeBuildAction({
actionName: 'CodeBuild',
input: sourceOutput,
output: new codepipeline.Artifact(),
}),
],
});
Template.fromStack(stack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
'Stages': [
{
'Name': 'Source',
'Actions': [
{
'Name': 'CodeCommit',
'OutputArtifacts': [
{
'Name': 'Artifact_Source_CodeCommit',
},
],
},
],
},
{
'Name': 'Build',
'Actions': [
{
'Name': 'CodeBuild',
'InputArtifacts': [
{
'Name': 'Artifact_Source_CodeCommit',
},
],
'OutputArtifacts': [
{
'Name': 'Artifact_Build_CodeBuild',
},
],
},
],
},
],
});
});
test('the same Action can be safely added to 2 different Stages', () => {
const stack = new cdk.Stack();
const sourceOutput = new codepipeline.Artifact();
const pipeline = new codepipeline.Pipeline(stack, 'Pipeline', {
stages: [
{
stageName: 'Source',
actions: [
new FakeSourceAction({
actionName: 'Source',
output: sourceOutput,
}),
],
},
],
});
const action = new FakeBuildAction({ actionName: 'FakeAction', input: sourceOutput });
const stage2: codepipeline.StageProps = {
stageName: 'Stage2',
actions: [action],
};
const stage3: codepipeline.StageProps = {
stageName: 'Stage3',
actions: [action],
};
pipeline.addStage(stage2);
expect(() => {
pipeline.addStage(stage3);
}).not.toThrow(/FakeAction/);
});
describe('input Artifacts', () => {
test('can be added multiple times to an Action safely', () => {
const artifact = new codepipeline.Artifact('SomeArtifact');
expect(() => {
new FakeBuildAction({
actionName: 'CodeBuild',
input: artifact,
extraInputs: [artifact],
});
}).not.toThrow();
});
test('can have duplicate names', () => {
const artifact1 = new codepipeline.Artifact('SomeArtifact');
const artifact2 = new codepipeline.Artifact('SomeArtifact');
expect(() => {
new FakeBuildAction({
actionName: 'CodeBuild',
input: artifact1,
extraInputs: [artifact2],
});
}).not.toThrow();
});
});
describe('output Artifacts', () => {
test('accept multiple Artifacts with the same name safely', () => {
expect(() => {
new FakeSourceAction({
actionName: 'CodeBuild',
output: new codepipeline.Artifact('Artifact1'),
extraOutputs: [
new codepipeline.Artifact('Artifact1'),
new codepipeline.Artifact('Artifact1'),
],
});
}).not.toThrow();
});
});
test('an Action with a non-AWS owner cannot have a Role passed for it', () => {
const stack = new cdk.Stack();
const sourceOutput = new codepipeline.Artifact();
const pipeline = new codepipeline.Pipeline(stack, 'Pipeline', {
stages: [
{
stageName: 'Source',
actions: [
new FakeSourceAction({
actionName: 'source',
output: sourceOutput,
}),
],
},
],
});
const buildStage = pipeline.addStage({ stageName: 'Build' });
// constructing it is fine
const buildAction = new FakeBuildAction({
actionName: 'build',
input: sourceOutput,
owner: 'ThirdParty',
role: new iam.Role(stack, 'Role', {
assumedBy: new iam.AnyPrincipal(),
}),
});
// an attempt to add it to the Pipeline is where things blow up
expect(() => {
buildStage.addAction(buildAction);
}).toThrow(/Role is not supported for actions with an owner different than 'AWS' - got 'ThirdParty' \(Action: 'build' in Stage: 'Build'\)/);
});
test('actions can be retrieved from stages they have been added to', () => {
const stack = new cdk.Stack();
const sourceOutput = new codepipeline.Artifact();
const pipeline = new codepipeline.Pipeline(stack, 'Pipeline', {
stages: [
{
stageName: 'Source',
actions: [
new FakeSourceAction({
actionName: 'source',
output: sourceOutput,
}),
],
},
],
});
const sourceStage = pipeline.stages[0];
const buildStage = pipeline.addStage({
stageName: 'Build',
actions: [
new FakeBuildAction({
actionName: 'build1',
input: sourceOutput,
runOrder: 11,
}),
new FakeBuildAction({
actionName: 'build2',
input: sourceOutput,
runOrder: 2,
}),
],
});
expect(sourceStage.actions.length).toEqual(1);
expect(sourceStage.actions[0].actionProperties.actionName).toEqual('source');
expect(buildStage.actions.length).toEqual(2);
expect(buildStage.actions[0].actionProperties.actionName).toEqual('build1');
expect(buildStage.actions[1].actionProperties.actionName).toEqual('build2');
});
});
function boundsValidationResult(numberOfArtifacts: number, min: number, max: number): string[] {
const artifacts: codepipeline.Artifact[] = [];
for (let i = 0; i < numberOfArtifacts; i++) {
artifacts.push(new codepipeline.Artifact(`TestArtifact${i}`));
}
return validations.validateArtifactBounds('output', artifacts, min, max, 'testCategory', 'testProvider');
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [codestar](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodestar.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Codestar extends PolicyStatement {
public servicePrefix = 'codestar';
/**
* Statement provider for service [codestar](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscodestar.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Adds a user to the team for an AWS CodeStar project.
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_AssociateTeamMember.html
*/
public toAssociateTeamMember() {
return this.to('AssociateTeamMember');
}
/**
* Creates a project with minimal structure, customer policies, and no resources.
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_CreateProject.html
*/
public toCreateProject() {
return this.to('CreateProject');
}
/**
* Creates a profile for a user that includes user preferences, display name, and email.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_CreateUserProfile.html
*/
public toCreateUserProfile() {
return this.to('CreateUserProfile');
}
/**
* Grants access to extended delete APIs.
*
* Access Level: Write
*/
public toDeleteExtendedAccess() {
return this.to('DeleteExtendedAccess');
}
/**
* Deletes a project, including project resources. Does not delete users associated with the project, but does delete the IAM roles that allowed access to the project.
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_DeleteProject.html
*/
public toDeleteProject() {
return this.to('DeleteProject');
}
/**
* Deletes a user profile in AWS CodeStar, including all personal preference data associated with that profile, such as display name and email address. It does not delete the history of that user, for example the history of commits made by that user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_DeleteUserProfile.html
*/
public toDeleteUserProfile() {
return this.to('DeleteUserProfile');
}
/**
* Describes a project and its resources.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_DescribeProject.html
*/
public toDescribeProject() {
return this.to('DescribeProject');
}
/**
* Describes a user in AWS CodeStar and the user attributes across all projects.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_DescribeUserProfile.html
*/
public toDescribeUserProfile() {
return this.to('DescribeUserProfile');
}
/**
* Removes a user from a project. Removing a user from a project also removes the IAM policies from that user that allowed access to the project and its resources.
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_DisassociateTeamMember.html
*/
public toDisassociateTeamMember() {
return this.to('DisassociateTeamMember');
}
/**
* Grants access to extended read APIs.
*
* Access Level: Read
*/
public toGetExtendedAccess() {
return this.to('GetExtendedAccess');
}
/**
* Lists all projects in CodeStar associated with your AWS account.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_ListProjects.html
*/
public toListProjects() {
return this.to('ListProjects');
}
/**
* Lists all resources associated with a project in CodeStar.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_ListResources.html
*/
public toListResources() {
return this.to('ListResources');
}
/**
* Lists the tags associated with a project in CodeStar.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_ListTagsForProject.html
*/
public toListTagsForProject() {
return this.to('ListTagsForProject');
}
/**
* Lists all team members associated with a project.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_ListTeamMembers.html
*/
public toListTeamMembers() {
return this.to('ListTeamMembers');
}
/**
* Lists user profiles in AWS CodeStar.
*
* Access Level: List
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_ListUserProfiles.html
*/
public toListUserProfiles() {
return this.to('ListUserProfiles');
}
/**
* Grants access to extended write APIs.
*
* Access Level: Write
*/
public toPutExtendedAccess() {
return this.to('PutExtendedAccess');
}
/**
* Adds tags to a project in CodeStar.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_TagProject.html
*/
public toTagProject() {
return this.to('TagProject');
}
/**
* Removes tags from a project in CodeStar.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_UntagProject.html
*/
public toUntagProject() {
return this.to('UntagProject');
}
/**
* Updates a project in CodeStar.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_UpdateProject.html
*/
public toUpdateProject() {
return this.to('UpdateProject');
}
/**
* Updates team member attributes within a CodeStar project.
*
* Access Level: Permissions management
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_UpdateTeamMember.html
*/
public toUpdateTeamMember() {
return this.to('UpdateTeamMember');
}
/**
* Updates a profile for a user that includes user preferences, display name, and email.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/codestar/latest/APIReference/API_UpdateUserProfile.html
*/
public toUpdateUserProfile() {
return this.to('UpdateUserProfile');
}
/**
* Verifies whether the AWS CodeStar service role exists in the customer's account.
*
* Access Level: List
*/
public toVerifyServiceRole() {
return this.to('VerifyServiceRole');
}
protected accessLevelList: AccessLevelList = {
"Permissions management": [
"AssociateTeamMember",
"CreateProject",
"DeleteProject",
"DisassociateTeamMember",
"UpdateTeamMember"
],
"Write": [
"CreateUserProfile",
"DeleteExtendedAccess",
"DeleteUserProfile",
"PutExtendedAccess",
"UpdateProject",
"UpdateUserProfile"
],
"Read": [
"DescribeProject",
"DescribeUserProfile",
"GetExtendedAccess"
],
"List": [
"ListProjects",
"ListResources",
"ListTagsForProject",
"ListTeamMembers",
"ListUserProfiles",
"VerifyServiceRole"
],
"Tagging": [
"TagProject",
"UntagProject"
]
};
/**
* Adds a resource of type project to the statement
*
* https://docs.aws.amazon.com/codestar/latest/userguide/working-with-projects.html
*
* @param projectId - Identifier for the projectId.
* @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(projectId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:codestar:${Region}:${Account}:project/${ProjectId}';
arn = arn.replace('${ProjectId}', projectId);
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 user to the statement
*
* @param userNameWithPath - Identifier for the userNameWithPath.
* @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:
* - .ifIamResourceTag()
*/
public onUser(userNameWithPath: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:iam:${Region}:${Account}:user/${UserNameWithPath}';
arn = arn.replace('${UserNameWithPath}', userNameWithPath);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Applies to resource types:
* - user
*
* @param tagKey The tag key to check
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifIamResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) {
return this.if(`iam:ResourceTag/${ tagKey }`, value, operator || 'StringLike');
}
} | the_stack |
import * as React from "react";
import { ComponentProps } from "widgets/BaseComponent";
import styled from "styled-components";
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";
import { Colors } from "constants/Colors";
export interface StyledImageProps {
defaultImageUrl: string;
enableRotation?: boolean;
imageUrl?: string;
backgroundColor?: string;
showHoverPointer?: boolean;
objectFit: string;
onClick?: (event: React.MouseEvent<HTMLElement>) => void;
}
export const StyledImage = styled.div<
StyledImageProps & {
imageError: boolean;
}
>`
position: relative;
display: flex;
flex-direction: "row";
background-size: ${(props) => props.objectFit ?? "contain"};
cursor: ${(props) =>
props.showHoverPointer && props.onClick ? "pointer" : "inherit"};
background: ${(props) => props.backgroundColor};
background-image: ${(props) =>
`url(${props.imageError ? props.defaultImageUrl : props.imageUrl})`};
background-position: center;
background-repeat: no-repeat;
height: 100%;
width: 100%;
`;
const Wrapper = styled.div`
height: 100%;
width: 100%;
.react-transform-element,
.react-transform-component {
height: 100%;
width: 100%;
}
`;
const ControlBtnWrapper = styled.div`
position: absolute;
top: 2px;
right: 2px;
padding: 5px 0px;
z-index: 1;
display: flex;
justify-content: center;
align-items: center;
background: white;
`;
const ControlBtn = styled.div`
height: 25px;
width: 45px;
color: white;
padding: 0px 10px;
display: inline-block;
&.separator {
border-right: 1px solid ${Colors.ALTO2};
}
& > div {
cursor: pointer;
height: 100%;
width: 100%;
padding: 4px;
transition: background 0.2s linear;
& > svg {
height: 16px;
width: 17px;
}
&: hover {
background: #ebebeb;
}
}
`;
enum ZoomingState {
MAX_ZOOMED_OUT = "MAX_ZOOMED_OUT",
MAX_ZOOMED_IN = "MAX_ZOOMED_IN",
}
class ImageComponent extends React.Component<
ImageComponentProps,
{
imageError: boolean;
showImageControl: boolean;
imageRotation: number;
zoomingState: ZoomingState;
}
> {
isPanning: boolean;
constructor(props: ImageComponentProps) {
super(props);
this.isPanning = false;
this.state = {
imageError: false,
showImageControl: false,
imageRotation: 0,
zoomingState: ZoomingState.MAX_ZOOMED_OUT,
};
}
render() {
const { maxZoomLevel } = this.props;
const { imageRotation } = this.state;
const zoomActive =
maxZoomLevel !== undefined && maxZoomLevel > 1 && !this.isPanning;
const isZoomingIn = this.state.zoomingState === ZoomingState.MAX_ZOOMED_OUT;
let cursor = "inherit";
if (zoomActive) {
cursor = isZoomingIn ? "zoom-in" : "zoom-out";
}
return (
<Wrapper
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
<TransformWrapper
defaultScale={1}
doubleClick={{
disabled: true,
}}
onPanning={() => {
this.isPanning = true;
}}
onPanningStart={() => {
this.props.disableDrag(true);
}}
onPanningStop={() => {
this.props.disableDrag(false);
}}
onZoomChange={(zoom: any) => {
if (zoomActive) {
//Check max zoom
if (
maxZoomLevel === zoom.scale &&
// Added for preventing infinite loops
this.state.zoomingState !== ZoomingState.MAX_ZOOMED_IN
) {
this.setState({
zoomingState: ZoomingState.MAX_ZOOMED_IN,
});
// Check min zoom
} else if (
zoom.scale === 1 &&
this.state.zoomingState !== ZoomingState.MAX_ZOOMED_OUT
) {
this.setState({
zoomingState: ZoomingState.MAX_ZOOMED_OUT,
});
}
}
}}
options={{
maxScale: maxZoomLevel,
disabled: !zoomActive,
transformEnabled: zoomActive,
}}
pan={{
disabled: !zoomActive,
}}
wheel={{
disabled: !zoomActive,
}}
>
{({ zoomIn, zoomOut }: any) => (
<>
{this.renderImageControl()}
<TransformComponent>
<StyledImage
className={this.props.isLoading ? "bp3-skeleton" : ""}
imageError={this.state.imageError}
{...this.props}
data-testid="styledImage"
onClick={(event: React.MouseEvent<HTMLElement>) => {
if (!this.isPanning) {
if (isZoomingIn) {
zoomIn(event);
} else {
zoomOut(event);
}
this.props.onClick && this.props.onClick(event);
}
this.isPanning = false;
}}
style={{
cursor,
transform: `rotate(${imageRotation}deg)`,
}}
>
{/* Used for running onImageError and onImageLoad Functions since Background Image doesn't have the functionality */}
<img
alt={this.props.widgetName}
onError={this.onImageError}
onLoad={this.onImageLoad}
src={this.props.imageUrl}
style={{
display: "none",
}}
/>
</StyledImage>
</TransformComponent>
</>
)}
</TransformWrapper>
</Wrapper>
);
}
renderImageControl = () => {
const {
defaultImageUrl,
enableDownload,
enableRotation,
imageUrl,
} = this.props;
const { showImageControl } = this.state;
const showDownloadBtn = enableDownload && (!!imageUrl || !!defaultImageUrl);
if (showImageControl && (enableRotation || showDownloadBtn)) {
return (
<ControlBtnWrapper>
{enableRotation && (
<>
<ControlBtn onClick={this.handleImageRotate(false)}>
<div>
<svg
fill="none"
height="12"
viewBox="0 0 12 12"
width="12"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2.28492 1.81862C3.27446 0.939565 4.57489 0.400391 6.00002 0.400391C9.08724 0.400391 11.6 2.91317 11.6 6.00039C11.6 9.08761 9.08724 11.6004 6.00002 11.6004C2.91281 11.6004 0.400024 9.08761 0.400024 6.00039H1.33336C1.33336 8.58317 3.41724 10.6671 6.00002 10.6671C8.58281 10.6671 10.6667 8.58317 10.6667 6.00039C10.6667 3.41761 8.58281 1.33372 6.00002 1.33372C4.82777 1.33372 3.76447 1.7682 2.94573 2.47943L4.13336 3.66706H1.33336V0.867057L2.28492 1.81862Z"
fill="#858282"
stroke="#858282"
strokeWidth="0.5"
/>
</svg>
</div>
</ControlBtn>
<ControlBtn
className="separator"
onClick={this.handleImageRotate(true)}
>
<div>
<svg
fill="none"
height="12"
viewBox="0 0 12 12"
width="12"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0.400024 6.00039C0.400024 2.91317 2.91281 0.400391 6.00002 0.400391C7.42515 0.400391 8.72559 0.939565 9.71513 1.81862L10.6667 0.867057V3.66706H7.86669L9.05432 2.47943C8.23558 1.7682 7.17228 1.33372 6.00002 1.33372C3.41724 1.33372 1.33336 3.41761 1.33336 6.00039C1.33336 8.58317 3.41724 10.6671 6.00002 10.6671C8.58281 10.6671 10.6667 8.58317 10.6667 6.00039H11.6C11.6 9.08761 9.08724 11.6004 6.00002 11.6004C2.91281 11.6004 0.400024 9.08761 0.400024 6.00039Z"
fill="#858282"
stroke="#858282"
strokeWidth="0.5"
/>
</svg>
</div>
</ControlBtn>
</>
)}
{showDownloadBtn && (
<ControlBtn onClick={this.handleImageDownload}>
<div>
<svg fill="none" height="20" viewBox="0 0 20 20" width="20">
<path
clipRule="evenodd"
d="M15.4547 16.4284H13.117H6.88326H4.54559C2.8243 16.4284 1.42871 14.8933 1.42871 12.9999C1.42871 11.3987 2.43157 10.0641 3.7804 9.68786C3.93001 6.28329 6.47884 3.57129 9.61053 3.57129C12.7072 3.57129 15.2349 6.22243 15.4352 9.57386C17.183 9.56015 18.5716 11.1167 18.5716 12.9999C18.5716 14.8933 17.176 16.4284 15.4547 16.4284ZM12.7266 11.4286L9.99929 14.8572L7.27202 11.4286L8.83045 11.4286L8.83045 8.00004L11.1681 8.00003V11.4286L12.7266 11.4286Z"
fill="#939090"
fillRule="evenodd"
/>
</svg>
</div>
</ControlBtn>
)}
</ControlBtnWrapper>
);
}
};
handleImageRotate = (rotateRight: boolean) => (e: any) => {
const { imageRotation } = this.state;
const nextRotation = rotateRight ? imageRotation + 90 : imageRotation - 90;
this.setState({ imageRotation: nextRotation % 360 });
if (!!e) {
e.preventDefault();
e.stopPropagation();
}
};
handleImageDownload = (e: any) => {
const { defaultImageUrl, imageUrl, widgetId } = this.props;
const fileName = `${widgetId}-download`;
const downloadUrl = imageUrl || defaultImageUrl;
const xhr = new XMLHttpRequest();
xhr.open("GET", downloadUrl, true);
xhr.responseType = "blob";
xhr.onload = function() {
const urlCreator = window.URL || window.webkitURL;
const imageUrlObj = urlCreator.createObjectURL(this.response);
const tag = document.createElement("a");
tag.href = imageUrlObj;
tag.download = fileName;
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
window.URL.revokeObjectURL(imageUrlObj);
};
// if download fails open image in new tab
xhr.onerror = function() {
const tag = document.createElement("a");
tag.href = downloadUrl;
tag.target = "_blank";
document.body.appendChild(tag);
tag.click();
document.body.removeChild(tag);
};
xhr.send();
if (!!e) {
e.preventDefault();
e.stopPropagation();
}
};
onMouseEnter = () => this.setState({ showImageControl: true });
onMouseLeave = () => this.setState({ showImageControl: false });
onImageError = () => {
this.setState({
imageError: true,
});
};
onImageLoad = () => {
this.setState({
imageError: false,
});
};
}
export interface ImageComponentProps extends ComponentProps {
imageUrl: string;
defaultImageUrl: string;
isLoading: boolean;
showHoverPointer?: boolean;
maxZoomLevel: number;
enableRotation?: boolean;
enableDownload?: boolean;
objectFit: string;
disableDrag: (disabled: boolean) => void;
onClick?: (event: React.MouseEvent<HTMLElement>) => void;
}
export default ImageComponent; | the_stack |
import { DisposableStore, Emitter, Event, IDisposable } from '@velcro/common';
import { execute } from '@velcro/runner';
import * as Monaco from 'monaco-editor';
import { createContext, useContext, useEffect, useState } from 'react';
import * as SvelteLanguage from './svelte.language';
const readUrl = (href: string) => fetch(href).then((res) => res.arrayBuffer());
export class EditorManager implements IDisposable {
editor: Monaco.editor.IStandaloneCodeEditor | null = null;
private readonly disposableStore = new DisposableStore();
private readonly initialPath: string | undefined;
private readonly viewState = new WeakMap<
Monaco.editor.ITextModel,
Monaco.editor.ICodeEditorViewState
>();
private readonly onWillFocusModelEmitter = new Emitter<Monaco.editor.ITextModel>();
private readonly onDidChangeEmitter = new Emitter<{ model: Monaco.editor.ITextModel }>();
constructor(options: { files?: Record<string, string>; initialPath?: string } = {}) {
this.disposableStore.add(this.onWillFocusModelEmitter);
this.disposableStore.add(this.onDidChangeEmitter);
Monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);
Monaco.languages.typescript.typescriptDefaults.setMaximumWorkerIdleTime(-1);
Monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
allowJs: true,
allowNonTsExtensions: true,
allowSyntheticDefaultImports: true,
baseUrl: '.',
checkJs: true,
esModuleInterop: true,
experimentalDecorators: true,
inlineSourceMap: true,
inlineSources: true,
isolatedModules: false,
jsx: Monaco.languages.typescript.JsxEmit.React,
lib: ['dom'],
module: Monaco.languages.typescript.ModuleKind.CommonJS,
moduleResolution: Monaco.languages.typescript.ModuleResolutionKind.NodeJs,
noEmit: false,
outDir: `dist`,
resolveJsonModule: true,
rootDir: '/',
sourceMap: true,
target: Monaco.languages.typescript.ScriptTarget.ES2015,
typeRoots: ['node_modules/@types'],
});
Monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: false,
});
Monaco.languages.register({
id: 'svelte',
extensions: ['.svelte'],
mimetypes: ['text/x-svelte'],
});
Monaco.languages.setLanguageConfiguration(
'svelte',
SvelteLanguage.conf as Monaco.languages.LanguageConfiguration
);
Monaco.languages.setMonarchTokensProvider(
'svelte',
SvelteLanguage.language as Monaco.languages.IMonarchLanguage
);
const createPrettierFormattingProvider = (): Monaco.languages.DocumentFormattingEditProvider => {
let prettierPromise:
| Promise<{
prettier: typeof import('prettier/standalone');
plugins: import('prettier').Plugin[];
}>
| undefined = undefined;
const loadPrettier = async () => {
if (!prettierPromise) {
prettierPromise = execute(
'module.exports = { prettier: require("prettier/standalone"), plugins: [require("prettier/parser-babel"), require("prettier/parser-html"), require("prettier/parser-postcss")] };',
{
readUrl,
cdn: 'jsdelivr',
dependencies: {
prettier: '^2.0.5',
'prettier-plugin-svelte': '^1.1.0',
},
nodeEnv: 'production',
packageMain: ['browser', 'main'],
sourceMap: false,
}
);
// The Svelte plugin depends on 'prettier' but we're in a browser and so we need
// to inject the 'standalone' version of prettier. This means to need to defer
// loading the svelte plugin until we've gotten a reference to prettier from
// the previous logic.
prettierPromise = prettierPromise.then(async ({ prettier, plugins }) => {
const prettierPluginSvelte = await execute<import('prettier').Plugin>(
'module.exports = require("prettier-plugin-svelte")',
{
readUrl,
cdn: 'jsdelivr',
dependencies: {
'prettier-plugin-svelte': '^1.1.0',
svelte: '^3.2.0',
},
injectModules: {
prettier,
},
nodeEnv: 'production',
packageMain: ['browser', 'main'],
sourceMap: false,
}
);
return {
prettier,
plugins: [...plugins, prettierPluginSvelte],
};
});
prettierPromise.catch((e) => {
console.error(e);
debugger;
});
}
return prettierPromise;
};
return {
async provideDocumentFormattingEdits(model, options, token) {
const { prettier, plugins } = await loadPrettier();
if (token.isCancellationRequested) {
return [];
}
const formatted = prettier.format(model.getValue(), {
filepath: model.uri.fsPath,
singleQuote: true,
tabWidth: 2,
plugins,
});
return [
{
range: model.getFullModelRange(),
text: formatted,
},
];
},
};
};
const codeFormattingEditProvider = createPrettierFormattingProvider();
Monaco.languages.registerDocumentFormattingEditProvider('css', codeFormattingEditProvider);
Monaco.languages.registerDocumentFormattingEditProvider('html', codeFormattingEditProvider);
Monaco.languages.registerDocumentFormattingEditProvider(
'javascript',
codeFormattingEditProvider
);
Monaco.languages.registerDocumentFormattingEditProvider('svelte', codeFormattingEditProvider);
Monaco.languages.registerDocumentFormattingEditProvider(
'typescript',
codeFormattingEditProvider
);
if (options.files) {
for (const pathname in options.files) {
const content = options.files[pathname];
this.createModel(pathname, content);
}
}
this.initialPath = options.initialPath;
}
get dispose() {
return this.disposableStore.dispose;
}
get onDidChange(): Event<{ model: Monaco.editor.ITextModel }> {
return this.onDidChangeEmitter.event;
}
get onWillFocusModel(): Event<Monaco.editor.ITextModel> {
return this.onWillFocusModelEmitter.event;
}
createModel(pathname: string, content = '') {
const language = this.inferLanguage(pathname);
let uri: Monaco.Uri;
try {
uri = Monaco.Uri.file(pathname);
} catch (err) {
throw new Error(`Invalid path '${pathname}': ${err && err.message}`);
}
if (Monaco.editor.getModel(uri)) {
throw new Error(`Cannot create file because it exists '${pathname}'`);
}
return Monaco.editor.createModel(content, language, uri);
}
focusHref(
href: string,
options: {
lineNumber?: number;
columnNumber?: number;
markers?: Monaco.editor.IMarkerData[];
} = {}
) {
const model = this.getModelByHref(href);
if (model) {
this.focusModel(model, options);
}
}
focusModel(
model: Monaco.editor.ITextModel,
options: {
lineNumber?: number;
columnNumber?: number;
markers?: Monaco.editor.IMarkerData[];
} = {}
) {
if (this.editor) {
this.editor.setModel(model);
if (options.lineNumber) {
this.editor.revealLineInCenter(options.lineNumber, Monaco.editor.ScrollType.Smooth);
this.editor.setPosition({
column: options.columnNumber || 0,
lineNumber: options.lineNumber,
});
}
if (options.markers) {
Monaco.editor.setModelMarkers(model, 'editorManager', options.markers);
}
this.editor.focus();
}
}
focusPath(
path: string,
options: {
lineNumber?: number;
columnNumber?: number;
markers?: Monaco.editor.IMarkerData[];
} = {}
) {
const model = this.getModelByPath(path);
if (model) {
this.focusModel(model, options);
}
}
getModelByHref(href: string) {
try {
const uri = Monaco.Uri.parse(href);
return Monaco.editor.getModel(uri);
} catch (_) {
return null;
}
}
getModelByPath(path: string) {
return Monaco.editor.getModel(Monaco.Uri.file(path));
}
mount(el: HTMLElement) {
if (this.editor) {
throw new Error('Invariant violation: Editor already mounted');
}
this.editor = Monaco.editor.create(el, {
model: null,
automaticLayout: true,
minimap: {
enabled: false,
},
showUnused: true,
scrollBeyondLastLine: false,
theme: 'vs',
wordWrap: 'bounded',
wrappingIndent: 'same',
});
this.editor.onDidDispose(() => {
this.editor = null;
});
this.editor.onDidChangeModel((e) => {
if (e.newModelUrl && this.editor) {
const model = Monaco.editor.getModel(e.newModelUrl)!;
const viewState = this.viewState.get(model);
if (viewState) {
this.editor.restoreViewState(viewState);
}
}
});
this.editor.onDidBlurEditorText(() => {
if (this.editor) {
const model = this.editor.getModel();
const viewState = this.editor.saveViewState();
if (model && viewState) {
this.viewState.set(model, viewState);
}
}
});
this.disposableStore.add(this.editor);
if (this.initialPath) {
this.focusPath(this.initialPath);
}
return this.editor;
}
inferLanguage(pathname: string) {
return pathname.match(/\.(?:tsx?|jsx?)$/) ? 'typescript' : undefined;
}
}
export const EditorManagerContext = createContext<EditorManager>(undefined as any);
export function useActiveModel() {
const workbench = useContext(EditorManagerContext);
const [activeModel, setActiveModel] = useState<Monaco.editor.ITextModel | null>(
workbench.editor ? workbench.editor.getModel() : null
);
useEffect(() => {
const disposable = new DisposableStore();
const trackEditor = (editor: Monaco.editor.ICodeEditor) => {
editor.onDidChangeModel((e) => {
const model = e.newModelUrl ? Monaco.editor.getModel(e.newModelUrl) : null;
setActiveModel(model);
});
disposable.add(
editor.onDidBlurEditorText(() => {
setActiveModel(null);
})
);
disposable.add(
editor.onDidFocusEditorText(() => {
setActiveModel(editor.getModel());
})
);
if (editor.hasTextFocus()) {
setActiveModel(editor.getModel());
}
};
disposable.add(Monaco.editor.onDidCreateEditor(trackEditor));
if (workbench.editor) {
trackEditor(workbench.editor);
}
return () => disposable.dispose();
}, [workbench.editor, activeModel]);
return activeModel;
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
arachneStarted?: boolean;
ozmaStarted?: boolean;
calStarted?: boolean;
}
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheWeepingCityOfMhach,
timelineFile: 'weeping_city.txt',
timelineTriggers: [
{
id: 'Weeping City Dark Spike',
regex: /Dark Spike/,
beforeSeconds: 4,
response: Responses.tankBuster(),
},
{
id: 'Weeping City Widow\'s Kiss',
regex: /The Widow's Kiss/,
beforeSeconds: 5,
// Probably kills the player if failed, so it gets an alert.
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stand on webs',
de: 'Auf den Spinnennetzen stehen',
fr: 'Placez-vous dans les toiles',
ja: 'アンキレーウェブに入る',
cn: '站在网上',
ko: '거미줄 위에 서기',
},
},
},
{
id: 'Weeping City Punishing Ray',
regex: /Punishing Ray/,
beforeSeconds: 10,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Get Puddles',
de: 'Flächen nehmen',
fr: 'Allez dans les zones au sol',
ja: '踏む',
cn: '踩圈',
ko: '바닥 징 밟기',
},
},
},
{
id: 'Weeping City Bloodied Nail',
regex: /Bloodied Nail/,
beforeSeconds: 4,
suppressSeconds: 10,
response: Responses.tankBuster(),
},
{
id: 'Weeping City Split End',
regex: /Split End/,
beforeSeconds: 4,
suppressSeconds: 10,
response: Responses.tankCleave(),
},
{
id: 'Weeping City Aura Burst',
regex: /Aura Burst/,
beforeSeconds: 4,
response: Responses.aoe(),
},
],
triggers: [
{
// 2 of the 4 encounters in Weeping City use the 0017 head marker.
// 2 of the 4 use the 003E head marker.
// Because of this, we restrict those triggers for each boss to activate
// only when that boss is in progress.
id: 'Weeping City HeadMarker Arachne',
type: 'GameLog',
netRegex: NetRegexes.message({ line: 'The Queen\'s Room will be sealed off.*?', capture: false }),
netRegexDe: NetRegexes.message({ line: 'Spinnenfalle will be sealed off.*?', capture: false }),
netRegexFr: NetRegexes.message({ line: 'Domaine de la Tisseuse will be sealed off.*?', capture: false }),
netRegexJa: NetRegexes.message({ line: '蜘蛛女の狩場 will be sealed off.*?', capture: false }),
netRegexCn: NetRegexes.message({ line: '女王蛛猎场 will be sealed off.*?', capture: false }),
netRegexKo: NetRegexes.message({ line: '거미 여왕의 사냥터 will be sealed off.*?', capture: false }),
run: (data) => data.arachneStarted = true,
},
{
id: 'Weeping City HeadMarker Ozma',
type: 'GameLog',
netRegex: NetRegexes.message({ line: 'The Gloriole will be sealed off.*?', capture: false }),
netRegexDe: NetRegexes.message({ line: 'Aureole will be sealed off.*?', capture: false }),
netRegexFr: NetRegexes.message({ line: 'Hauteurs de la pyramide will be sealed off.*?', capture: false }),
netRegexJa: NetRegexes.message({ line: 'ピラミッド上部層 will be sealed off.*?', capture: false }),
netRegexCn: NetRegexes.message({ line: '金字塔上层 will be sealed off.*?', capture: false }),
netRegexKo: NetRegexes.message({ line: '피라미드 상층부 will be sealed off.*?', capture: false }),
run: (data) => {
data.arachneStarted = false;
data.ozmaStarted = true;
},
},
{
id: 'Weeping City HeadMarker Calofisteri',
type: 'GameLog',
netRegex: NetRegexes.message({ line: 'The Tomb Of The Nullstone will be sealed off.*?', capture: false }),
netRegexDe: NetRegexes.message({ line: 'Kammer des Nullsteins will be sealed off.*?', capture: false }),
netRegexFr: NetRegexes.message({ line: 'Tombeau de la Clef de voûte will be sealed off.*?', capture: false }),
netRegexJa: NetRegexes.message({ line: '要の玄室 will be sealed off.*?', capture: false }),
netRegexCn: NetRegexes.message({ line: '契约石玄室 will be sealed off.*?', capture: false }),
netRegexKo: NetRegexes.message({ line: '쐐기 안치소 will be sealed off.*?', capture: false }),
run: (data) => {
data.ozmaStarted = false;
data.calStarted = true;
},
},
{
id: 'Weeping City Sticky Wicket',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003C', capture: false }),
suppressSeconds: 10,
response: Responses.spread(),
},
{
id: 'Weeping City Shadow Burst',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
condition: (data) => data.arachneStarted,
response: Responses.stackMarkerOn(),
},
{
id: 'Weeping City Frond Affeared',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '183A', source: 'Arachne Eve', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '183A', source: 'Arachne (?:der|die|das) Ahnin', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '183A', source: 'Arachné Mère', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '183A', source: 'アルケニー', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '183A', source: '阿剌克涅', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '183A', source: '아라크네', capture: false }),
response: Responses.lookAway(),
},
{
id: 'Weeping City Arachne Web',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0017' }),
condition: (data, matches) => data.arachneStarted && data.me === matches.target,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Drop Web Outside',
de: 'Spinnennetz draußen ablegen',
fr: 'Déposez les toiles à l\'extérieur',
ja: 'ウェブを外周に捨てる',
cn: '蛛网点名,放在场边',
ko: '거미줄 바깥쪽으로 빼기',
},
},
},
{
id: 'Weeping City Brand Of The Fallen',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0037' }),
condition: Conditions.targetIsYou(),
response: Responses.doritoStack(),
},
{
id: 'Weeping City Dark Eruption',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0019' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Puddles on YOU',
de: 'Pfützen auf DIR',
fr: 'Zones au sol sur VOUS',
ja: '自分に床範囲',
cn: '圈圈点名',
ko: '장판 바깥에 깔기',
},
},
},
{
id: 'Weeping City Beguiling Mist',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '17CE', source: 'Summoned Succubus' }),
netRegexDe: NetRegexes.startsUsing({ id: '17CE', source: 'Beschworen(?:e|er|es|en) Sukkubus' }),
netRegexFr: NetRegexes.startsUsing({ id: '17CE', source: 'Succube Adjuré' }),
netRegexJa: NetRegexes.startsUsing({ id: '17CE', source: 'サモン・サキュバス' }),
netRegexCn: NetRegexes.startsUsing({ id: '17CE', source: '被召唤出的梦魔' }),
netRegexKo: NetRegexes.startsUsing({ id: '17CE', source: '소환된 서큐버스' }),
condition: (data) => data.CanSilence(),
response: Responses.interrupt(),
},
{
id: 'Weeping City Mortal Ray',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '17D4', source: 'Summoned Haagenti' }),
netRegexDe: NetRegexes.startsUsing({ id: '17D4', source: 'Beschworen(?:e|er|es|en) Haagenti' }),
netRegexFr: NetRegexes.startsUsing({ id: '17D4', source: 'Haagenti Adjuré' }),
netRegexJa: NetRegexes.startsUsing({ id: '17D4', source: 'サモン・ハーゲンティ' }),
netRegexCn: NetRegexes.startsUsing({ id: '17D4', source: '被召唤出的哈加提' }),
netRegexKo: NetRegexes.startsUsing({ id: '17D4', source: '소환된 하겐티' }),
response: Responses.lookAwayFromSource(),
},
{
id: 'Weeping City Hell Wind',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '17CB', source: 'Forgall', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '17CB', source: 'Forgall', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '17CB', source: 'Forgall', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '17CB', source: 'フォルガル', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '17CB', source: '弗加尔', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '17CB', source: '포르갈', capture: false }),
// Hell Wind sets HP to single digits, so mitigations don't work. Don't notify non-healers.
condition: (data) => data.role === 'healer',
response: Responses.aoe(),
},
{
id: 'Weeping City Mega Death',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '17CA', source: 'Forgall', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '17CA', source: 'Forgall', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '17CA', source: 'Forgall', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '17CA', source: 'フォルガル', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '17CA', source: '弗加尔', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '17CA', source: '포르갈', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stand in one puddle',
de: 'In einer Fläche stehen',
fr: 'Placez-vous dans une zone au sol',
ja: '範囲に入る',
cn: '站在圈里',
ko: '장판으로',
},
},
},
{
id: 'Weeping City Meteor Impact',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0039' }),
condition: Conditions.targetIsYou(),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Drop meteor back or left',
de: 'Meteor hinten oder links ablegen',
fr: 'Déposez le météore derrière ou à gauche',
ja: 'メテオ、後ろや左に置く',
cn: '流星点名,放在背后或左边',
ko: '메테오 뒤/왼쪽으로 빼기',
},
},
},
{
// The ability used here is Ozma entering Pyramid form.
// Execration follows this up almost immediately.
id: 'Weeping City Execration',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '1826', source: 'Ozma', capture: false }),
netRegexDe: NetRegexes.ability({ id: '1826', source: 'Yadis', capture: false }),
netRegexFr: NetRegexes.ability({ id: '1826', source: 'Ozma', capture: false }),
netRegexJa: NetRegexes.ability({ id: '1826', source: 'オズマ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '1826', source: '奥兹玛', capture: false }),
netRegexKo: NetRegexes.ability({ id: '1826', source: '오즈마', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Get off rectangle platform',
de: 'Von der plattform runter gehen',
fr: 'Descendez de la plateforme rectangle',
ja: '通路で回避',
cn: '离开平台',
ko: '통로로 이동',
},
},
},
{
// The ability used here is Ozma entering Cube form.
// Flare Star and tank lasers follow shortly.
id: 'Weeping City Flare Star Ring',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '1803', source: 'Ozma', capture: false }),
netRegexDe: NetRegexes.ability({ id: '1803', source: 'Yadis', capture: false }),
netRegexFr: NetRegexes.ability({ id: '1803', source: 'Ozma', capture: false }),
netRegexJa: NetRegexes.ability({ id: '1803', source: 'オズマ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '1803', source: '奥兹玛', capture: false }),
netRegexKo: NetRegexes.ability({ id: '1803', source: '오즈마', capture: false }),
response: Responses.getIn(),
},
{
// The ability used here is Ozma entering Cube form. The actual laser ability, 1831,
// is literally named "attack". Ozma zaps the 3 highest-threat targets. (Not always tanks!)
// This continues until the next Sphere form, whether by time or by HP push.
id: 'Weeping City Tank Lasers',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '1803', source: 'Ozma', capture: false }),
netRegexDe: NetRegexes.ability({ id: '1803', source: 'Yadis', capture: false }),
netRegexFr: NetRegexes.ability({ id: '1803', source: 'Ozma', capture: false }),
netRegexJa: NetRegexes.ability({ id: '1803', source: 'オズマ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '1803', source: '奥兹玛', capture: false }),
netRegexKo: NetRegexes.ability({ id: '1803', source: '오즈마', capture: false }),
// Delaying here to avoid colliding with other Flare Star triggers.
delaySeconds: 4,
alertText: (data, _matches, output) => {
if (data.role === 'tank')
return output.tankLasers!();
return output.avoidTanks!();
},
outputStrings: {
tankLasers: {
en: 'Tank lasers--Avoid party',
de: 'Tank lasers--Weg von der Party',
fr: 'Tank lasers - Évitez le groupe',
ja: 'タンクレーザー - 外に',
cn: '坦克激光--远离人群',
ko: '탱커 레이저-- 피하기',
},
avoidTanks: {
en: 'Avoid tanks',
de: 'Weg von den Tanks',
fr: 'Évitez les tanks',
ja: 'タンクから離れる',
cn: '远离坦克',
ko: '탱커 피하기',
},
},
},
{
// The NPC name is Ozmasphere. These need to be popped just like any other Flare Star.
// Failing to pop an orb means it will explode, dealing damage with 1808 Aethernova.
id: 'Weeping City Flare Star Orbs',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcBaseId: '4889', capture: false }),
condition: (data) => data.role === 'tank' || data.role === 'healer',
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Get orbs',
de: 'Kugeln nehmen',
fr: 'Prenez les orbes',
ja: '玉を取る',
cn: '撞球',
ko: '구슬 먹기',
},
},
},
{
id: 'Weeping City Acceleration Bomb',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '430' }),
condition: Conditions.targetIsYou(),
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 3,
response: Responses.stopEverything(),
},
{
id: 'Weeping City Assimilation',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '1802', source: 'Ozmashade', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '1802', source: 'Yadis-Schatten', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '1802', source: 'Ombre D\'Ozma', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '1802', source: 'オズマの影', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '1802', source: '奥兹玛之影', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '1802', source: '오즈마의 그림자', capture: false }),
response: Responses.lookAway(),
},
{
// Each party gets a stack marker, so this is the best we can do.
id: 'Weeping City Meteor Stack',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E', capture: false }),
condition: (data) => data.ozmaStarted,
suppressSeconds: 5,
response: Responses.stackMarker(),
},
{
// Coif Change is always followed up shortly by Haircut.
// There's no castbar or indicator except that she grows a scythe on one side.
// It's not a very obvious visual cue unless the player knows to look for it.
id: 'Weeping City Coif Change Left',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '180A', source: 'Calofisteri', capture: false }),
netRegexDe: NetRegexes.ability({ id: '180A', source: 'Calofisteri', capture: false }),
netRegexFr: NetRegexes.ability({ id: '180A', source: 'Calofisteri', capture: false }),
netRegexJa: NetRegexes.ability({ id: '180A', source: 'カロフィステリ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '180A', source: '卡洛菲斯提莉', capture: false }),
netRegexKo: NetRegexes.ability({ id: '180A', source: '칼로피스테리', capture: false }),
response: Responses.goRight(),
},
{
id: 'Weeping City Coif Change Right',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '180E', source: 'Calofisteri', capture: false }),
netRegexDe: NetRegexes.ability({ id: '180E', source: 'Calofisteri', capture: false }),
netRegexFr: NetRegexes.ability({ id: '180E', source: 'Calofisteri', capture: false }),
netRegexJa: NetRegexes.ability({ id: '180E', source: 'カロフィステリ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '180E', source: '卡洛菲斯提莉', capture: false }),
netRegexKo: NetRegexes.ability({ id: '180E', source: '칼로피스테리', capture: false }),
response: Responses.goLeft(),
},
{
// 4899 is the base ID for bulb hair. 4900 is axe hair.
// Bulbs do a circle AoE surrounding them, while axes are a donut.
id: 'Weeping City Living Lock Axes',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: ['4899', '4900'], capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Close to axes, avoid bulbs',
de: 'Nahe den Äxten, vermeide Knospen',
fr: 'Soyez proche des haches, évitez les bulbes',
ja: '刃物の髪に近づき、丸い髪から離れる',
cn: '靠近斧状发,远离球状发',
ko: '도끼모양에 붙고, 둥근모양은 피하기',
},
},
},
{
id: 'Weeping City Living Lock Scythes',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '4898', capture: false }),
suppressSeconds: 5,
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Avoid scythe line AoEs',
de: 'Weiche den Sensen AOEs aus',
fr: 'Évitez les AoEs en lignes des faux',
ja: '十字AoE',
cn: '躲避镰刀直线AOE',
ko: '직선 장판 피하기',
},
},
},
{
// These adds are the purple circles waiting to grab people and Garrotte them.
id: 'Weeping City Entanglement',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '4904', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Avoid purple circles',
de: 'Vermeide die lilanen Flächen',
fr: 'Évitez les cercles violets',
ja: '紫の円範囲を避ける',
cn: '远离紫圈',
ko: '보라색 원 피하기',
},
},
},
{
// If by some chance someone actually did stand in the purple circles, break them out.
// The actual ability here is an Unknown ability, but it begins slightly before Garrotte.
id: 'Weeping City Garrotte',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '181D', source: 'Entanglement', capture: false }),
netRegexDe: NetRegexes.ability({ id: '181D', source: 'Verfilzung', capture: false }),
netRegexFr: NetRegexes.ability({ id: '181D', source: 'Emmêlement', capture: false }),
netRegexJa: NetRegexes.ability({ id: '181D', source: '魔髪の縛め', capture: false }),
netRegexCn: NetRegexes.ability({ id: '181D', source: '魔发束缚', capture: false }),
netRegexKo: NetRegexes.ability({ id: '181D', source: '머리카락 포박', capture: false }),
suppressSeconds: 5,
response: Responses.killExtraAdd(),
},
{
id: 'Weeping City Particle Beam',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0017' }),
condition: (data) => data.calStarted,
alertText: (data, matches, output) => {
if (data.me === matches.target)
return output.skyLaserOnYou!();
return output.avoidSkyLasers!();
},
outputStrings: {
skyLaserOnYou: {
en: '16x Sky Laser on YOU!',
de: '16x Himmelslaser auf DIR!',
fr: '16x Lasers du ciel sur VOUS',
ja: '自分に16連撃潜地式波動砲!',
cn: '16连追踪AOE点名',
ko: '16 하늘 레이저 대상자',
},
avoidSkyLasers: {
en: 'Avoid Sky Lasers',
de: 'Himmelslaser ausweichen',
fr: 'Évitez les lasers du ciel',
ja: '潜地式波動砲を避ける',
cn: '躲避追踪AOE',
ko: '하늘 레이저 피하기',
},
},
},
{
// The actual ability here is Mana Drain, which ends the intermission.
// Dancing Mad follows this up closely enough to make this the best time to notify.
id: 'Weeping City Dancing Mad',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '1819', source: 'Calofisteri', capture: false }),
netRegexDe: NetRegexes.ability({ id: '1819', source: 'Calofisteri', capture: false }),
netRegexFr: NetRegexes.ability({ id: '1819', source: 'Calofisteri', capture: false }),
netRegexJa: NetRegexes.ability({ id: '1819', source: 'カロフィステリ', capture: false }),
netRegexCn: NetRegexes.ability({ id: '1819', source: '卡洛菲斯提莉', capture: false }),
netRegexKo: NetRegexes.ability({ id: '1819', source: '칼로피스테리', capture: false }),
response: Responses.aoe(),
},
{
id: 'Weeping City Penetration',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '1822', source: 'Calofisteri', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '1822', source: 'Calofisteri', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '1822', source: 'Calofisteri', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '1822', source: 'カロフィステリ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '1822', source: '卡洛菲斯提莉', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '1822', source: '칼로피스테리', capture: false }),
response: Responses.lookAway(),
},
{
id: 'Weeping City Depth Charge',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '1820', source: 'Calofisteri', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '1820', source: 'Calofisteri', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '1820', source: 'Calofisteri', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '1820', source: 'カロフィステリ', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '1820', source: '卡洛菲斯提莉', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '1820', source: '칼로피스테리', capture: false }),
response: Responses.awayFromFront(),
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Arachne Eve': 'Arachne (?:der|die|das) Ahnin',
'Calofisteri': 'Calofisteri',
'Entanglement': 'Verfilzung',
'Forgall': 'Forgall',
'Living Lock': 'lebend(?:e|er|es|en) Locke',
'Ozma(?!shade)': 'Yadis',
'Ozmashade': 'Yadis-Schatten',
'Poison Mist': 'Giftnebel',
'Shriveled Talon': 'verschrumpelt(?:e|er|es|en) Harpyie',
'Singularity Fragment': 'Singularitätsfragment',
'Summoned Haagenti': 'beschworen(?:e|er|es|en) Haagenti',
'Summoned Succubus': 'beschworen(?:e|er|es|en) Sukkubus',
'The Gloriole': 'Aureole',
'The Queen\'s Room': 'Spinnenfalle',
'The Shrine Of The Goetic': 'Altar der Goëtie',
'The Tomb Of The Nullstone': 'Kammer des Nullsteins',
},
'replaceText': {
'Acceleration Bomb': 'Beschleunigungsbombe',
'Arachne Web': 'Arachne-Netz',
'Aura Burst': 'Auraknall',
'Black Hole': 'Schwarzes Loch',
'Bloodied Nail': 'Blutiger Nagel',
'Brand of the Fallen': 'Brandzeichen der Opferung',
'Coif Change': 'Typveränderung',
'Cube': 'Kubus',
'Dancing Mad': 'Wilder Tanz',
'Dark Eruption': 'Dunkle Eruption',
'Dark Spike': 'Dunkler Stachel',
'Depth Charge': 'Tiefenangriff',
'Evil Curl': 'Böse Locke',
'Evil Mist': 'Bösartiger Nebel',
'Evil Switch': 'Böse Strähne',
'Evil Tress': 'Böse Mähne',
'Execration': 'Exsekration',
'(?<! )Explosion': 'Explosion',
'Extension': 'Strähnchen',
'Feint Particle Beam': 'Schein-Partikelstrahl',
'Flare Star': 'Flare-Stern',
'Frond Affeared': 'Antlitz der Angst',
'Haircut': 'Haarschnitt',
'Hell Wind': 'Höllenwind',
'Holy': 'Sanctus',
'Implosion': 'Implosion',
'Mana Drain': 'Magische Anziehung',
'Mana Explosion': 'Mana-Explosion',
'Mega Death': 'Megatod',
'Megiddo Flame': 'Megiddoflamme',
'Meteor(?![\\w\\s])': 'Meteor',
'Meteor Headmarkers': 'Meteor Markierungen',
'Meteor Impact': 'Meteoreinschlag',
'Necropurge': 'Nekrobuße',
'Penetration': 'Durchdringen',
'Pitfall': 'Berstender Boden',
'Punishing Ray': 'Strafender Strahl',
'Pyramid': 'Pyramide',
'Shadow Burst': 'Schattenstoß',
'Silken Spray': 'Seidengespinst',
'Sphere': 'Kugel',
'Split End': 'Gespaltene Spitzen',
'Sticky Wicket': 'Klebfadenfetzen',
'Tank Lasers': 'Tank Laser',
'The Widow\'s Embrace': 'Eiserne Umgarnung',
'The Widow\'s Kiss': 'Seidige Umgarnung',
'Transfiguration': 'Transfiguration',
'Tremblor': 'Erdbeben',
},
},
{
'locale': 'fr',
'replaceSync': {
'Arachne Eve': 'Arachné mère',
'Calofisteri': 'Calofisteri',
'Entanglement': 'emmêlement',
'Forgall': 'Forgall',
'Living Lock': 'mèche animée',
'Ozma(?!shade)': 'Ozma',
'Ozmashade': 'ombre d\'Ozma',
'Poison Mist': 'Brume empoisonnée',
'Shriveled Talon': 'dépouille de Harpie féroce',
'Singularity Fragment': 'fragment de singularité',
'Summoned Haagenti': 'haagenti adjuré',
'Summoned Succubus': 'succube adjuré',
'The Gloriole': 'Hauteurs de la pyramide',
'The Queen\'s Room': 'Domaine de la Tisseuse',
'The Shrine Of The Goetic': 'Sanctuaire du Goétique',
'The Tomb Of The Nullstone': 'Tombeau de la Clef de voûte',
},
'replaceText': {
'\\?': ' ?',
'Acceleration Bomb': 'Bombe accélératrice',
'Arachne Web': 'Toile d\'Arachné',
'Aura Burst': 'Déflagration d\'aura',
'Black Hole': 'Trou noir',
'Bloodied Nail': 'Ongles sanglants',
'Brand of the Fallen': 'Marque des déchus',
'Coif Change': 'Recoiffage',
'Cube': 'Cube',
'Dancing Mad': 'Danse effrénée',
'Dark Eruption': 'Éruption ténébreuse',
'Dark Spike': 'Pointe ténébreuse',
'Depth Charge': 'Charge des profondeurs',
'Evil Curl': 'Boucle maléfique',
'Evil Mist': 'Brume maléfique',
'Evil Switch': 'Fouetté maléfique',
'Evil Tress': 'Tresse maléfique',
'Execration': 'Exécration',
'(?<! )Explosion': 'Explosion',
'Extension': 'Extension',
'Feint Particle Beam': 'Rayon pénétrant',
'Flare Star': 'Astre flamboyant',
'Frond Affeared': 'Fronde effrayante',
'Haircut': 'Coupe de cheveux',
'Hell Wind': 'Vent infernal',
'Holy': 'Miracle',
'Implosion': 'Implosion',
'Mana Drain': 'Inspiration de magie',
'Mana Explosion': 'Explosion de mana',
'Mega Death': 'Mégamort',
'Megiddo Flame': 'Flamme de Megiddo',
'Meteor(?![\\w\\s])': 'Météore',
'Meteor Headmarkers': 'Marqueurs de météores',
'Meteor Impact': 'Impact de météore',
'Necropurge': 'Nécropurge',
'Penetration': 'Pénétration',
'Pitfall': 'Embûche',
'Punishing Ray': 'Rayon punitif',
'Pyramid': 'Pyramide',
'Shadow Burst': 'Salve ténébreuse',
'Silken Spray': 'Aspersion de soie',
'Sphere': 'Sphère',
'Split End': 'Pointes fourchues',
'Sticky Wicket': 'Projectile collant',
'Tank Lasers': 'Tank lasers',
'The Widow\'s Embrace': 'Gravité arachnéenne',
'The Widow\'s Kiss': 'Attraction arachnéenne',
'Transfiguration': 'Transmutation',
'Tremblor': 'Tremblement de terre',
},
},
{
'locale': 'ja',
'replaceSync': {
'Arachne Eve': 'アルケニー',
'Calofisteri': 'カロフィステリ',
'Forgall': 'フォルガル',
'Entanglement': '魔髪の縛め',
'Living Lock': 'カロフィステリの魔髪',
'Ozma(?!shade)': 'オズマ',
'Ozmashade': 'オズマの影',
'Poison Mist': '毒霧',
'Shriveled Talon': '大鷲連合の遺骸',
'Singularity Fragment': '圧縮世界の断片',
'Summoned Haagenti': 'サモン・ハーゲンティ',
'Summoned Succubus': 'サモン・サキュバス',
'The Gloriole': 'ピラミッド上部層',
'The Queen\'s Room': '蜘蛛女の狩場',
'The Shrine Of The Goetic': '神託の祭壇',
'The Tomb Of The Nullstone': '要の玄室',
},
'replaceText': {
'Acceleration Bomb': '加速度爆弾',
'Arachne Web': 'アンキレーウェブ',
'Aura Burst': 'オーラバースト',
'Black Hole': 'ブラックホール',
'Bloodied Nail': 'ブラッディネイル',
'Brand of the Fallen': '生贄の烙印',
'Coif Change': '魔髪変化',
'Cube': '立方体状態',
'Dancing Mad': 'ダンシングマッド',
'Dark Eruption': 'ダークエラプション',
'Dark Spike': 'ダークスパイク',
'Depth Charge': 'デプスチャージ',
'Evil Curl': 'イビルカール',
'Evil Mist': 'イビルミスト',
'Evil Switch': 'イビルスウィッチ',
'Evil Tress': 'イビルトレス',
'Execration': 'エクセクレイション',
'(?<! )Explosion': '爆発',
'Extension': 'エクステンション',
'Feint Particle Beam': '潜地式波動砲',
'Flare Star': 'フレアスター',
'Frond Affeared': '恐怖のまなざし',
'Haircut': 'ヘアカット',
'Hell Wind': 'ヘルウィンド',
'Holy': 'ホーリー',
'Implosion': 'インプロージョン',
'Mana Drain': '魔力吸引',
'Mana Explosion': '魔力爆発',
'Mega Death': 'オーバーデス',
'Megiddo Flame': 'メギドフレイム',
'Meteor(?![\\w\\s])': 'メテオ',
'Meteor Headmarkers': 'メテオ マーキング',
'Meteor Impact': 'メテオインパクト',
'Necropurge': 'ネクロパージ',
'Penetration': 'ペネトレーション',
'Pitfall': '強襲',
'Punishing Ray': 'パニッシュレイ',
'Pyramid': '三角錐状態',
'Shadow Burst': 'シャドウバースト',
'Silken Spray': 'シルクスプレー',
'Sphere': '球体状態',
'Split End': 'スプリットエンド',
'Sticky Wicket': 'スティッキーウィケット',
'Tank Lasers': 'タンクレザー',
'The Widow\'s Embrace': '蜘蛛の大罠',
'The Widow\'s Kiss': '蜘蛛の罠',
'Transfiguration': '形態変化',
'Tremblor': '地震',
},
},
{
'locale': 'cn',
'replaceSync': {
'Arachne Eve': '阿剌克涅',
'Calofisteri': '卡洛菲斯提莉',
'Forgall': '弗加尔',
'Entanglement': '魔发束缚',
'Living Lock': '卡洛菲斯提莉的魔发',
'Ozma(?!shade)': '奥兹玛',
'Ozmashade': '奥兹玛之影',
'Poison Mist': '毒雾',
'Shriveled Talon': '猛禽联盟遗骸',
'Singularity Fragment': '压缩世界的断片',
'Summoned Haagenti': '被召唤出的哈加提',
'Summoned Succubus': '被召唤出的梦魔',
'The Gloriole': '金字塔上层',
'The Queen\'s Room': '女王蛛猎场',
'The Shrine Of The Goetic': '神谕祭坛',
'The Tomb Of The Nullstone': '契约石玄室',
},
'replaceText': {
'Acceleration Bomb': '加速度炸弹',
'Arachne Web': '阿剌克涅之网',
'Aura Burst': '灵气爆',
'Black Hole': '黑洞',
'Bloodied Nail': '血爪',
'Brand of the Fallen': '祭品烙印',
'Coif Change': '魔发变化',
'Cube': '立方体形态',
'Dancing Mad': '魔发狂舞',
'Dark Eruption': '暗炎喷发',
'Dark Spike': '暗之刺爪',
'Depth Charge': '蓄力冲击',
'Evil Curl': '罪恶发旋',
'Evil Mist': '恶魔毒雾',
'Evil Switch': '罪恶发钩',
'Evil Tress': '罪恶发团',
'Execration': '缩小射线',
'(?<! )Explosion': '爆炸',
'Extension': '接发',
'Feint Particle Beam': '潜地式波动炮',
'Flare Star': '耀星',
'Frond Affeared': '恐惧视线',
'Haircut': '魔发斩',
'Hell Wind': '地狱之风',
'Holy': '神圣',
'Implosion': '向心聚爆',
'Mana Drain': '魔力吸收',
'Mana Explosion': '魔力爆炸',
'Mega Death': '超即死',
'Megiddo Flame': '米吉多烈焰',
'Meteor(?![\\w\\s])': '陨石',
'Meteor Headmarkers': '陨石点名',
'Meteor Impact': '陨石冲击',
'Necropurge': '死灵潜质',
'Penetration': '透耳尖啸',
'Pitfall': '强袭',
'Punishing Ray': '惩戒之光',
'Pyramid': '三角锥形态',
'Shadow Burst': '暗影爆',
'Silken Spray': '喷吐蛛丝',
'Sphere': '球形态',
'Split End': '发梢分裂',
'Sticky Wicket': '粘液弹',
'Tank Lasers': '坦克激光',
'The Widow\'s Embrace': '大蜘蛛陷阱',
'The Widow\'s Kiss': '蜘蛛陷阱',
'Transfiguration': '形态变化',
'Tremblor': '地震',
},
},
{
'locale': 'ko',
'replaceSync': {
'Arachne Eve': '아라크네',
'Calofisteri': '칼로피스테리',
'Forgall': '포르갈',
'Entanglement': '머리카락 포박',
'Living Lock': '칼로피스테리의 머리카락',
'Ozma(?!shade)': '오즈마',
'Ozmashade': '오즈마의 그림자',
'Poison Mist': '독안개',
'Shriveled Talon': '참수리연합 주검',
'Singularity Fragment': '압축세계의 단편',
'Summoned Haagenti': '소환된 하겐티',
'Summoned Succubus': '소환된 서큐버스',
'The Gloriole': '피라미드 상층부',
'The Queen\'s Room': '거미 여왕의 사냥터',
'The Shrine Of The Goetic': '신탁의 제단',
'The Tomb Of The Nullstone': '쐐기 안치소',
},
'replaceText': {
'Acceleration Bomb': '가속도 폭탄',
'Arachne Web': '아라크네의 거미줄',
'Aura Burst': '오라 폭발',
'Black Hole': '블랙홀',
'Bloodied Nail': '핏빛 손톱',
'Brand of the Fallen': '산제물 낙인',
'Coif Change': '머리카락 변화',
'Cube': '입방체',
'Dancing Mad': '춤추는 광기',
'Dark Eruption': '황천의 불기둥',
'Dark Spike': '어둠의 내리치기',
'Depth Charge': '심연 돌격',
'Evil Curl': '악마의 곱슬머리',
'Evil Mist': '악마의 안개',
'Evil Switch': '악마의 머리채',
'Evil Tress': '악마의 땋은머리',
'Execration': '혐오의 저주',
'(?<! )Explosion': '폭발',
'Extension': '머리카락 연장',
'Feint Particle Beam': '위장형 파동포',
'Flare Star': '타오르는 별',
'Frond Affeared': '섬뜩한 시선',
'Haircut': '머리카락 참격',
'Hell Wind': '황천의 바람',
'Holy': '홀리',
'Implosion': '내파',
'Mana Drain': '마력 흡입',
'Mana Explosion': '마력 폭발',
'Mega Death': '범람하는 죽음',
'Megiddo Flame': '메기도 플레임',
'Meteor(?![\\w\\s])': '메테오',
'Meteor Headmarkers': '메테오 머리징',
'Meteor Impact': '운석 낙하',
'Necropurge': '사령 침잠',
'Penetration': '침투',
'Pitfall': '강습',
'Punishing Ray': '응징의 빛줄기',
'Pyramid': '삼각뿔',
'Shadow Burst': '그림자 폭발',
'Silken Spray': '거미줄 분사',
'Sphere': '구',
'Split End': '쪼개기',
'Sticky Wicket': '끈끈이 구멍',
'Tank Lasers': '탱 레이저',
'The Widow\'s Embrace': '큰거미의 포옹',
'The Widow\'s Kiss': '거미 덫',
'Transfiguration': '형태 변화',
'Tremblor': '지진',
},
},
],
};
export default triggerSet; | the_stack |
import { camelCase, isValid, mapObject, omit, toArr, toStr, transpose } from "./utils";
import type { TypeSingleValueCSSProperty, ICSSComputedTransformableProperties } from "./types";
/**
* Returns a closure Function, which adds a unit to numbers but simply returns strings with no edits assuming the value has a unit if it's a string
*
* @param unit - the default unit to give the CSS Value
* @returns
* if value already has a unit (we assume the value has a unit if it's a string), we return it;
* else return the value plus the default unit
*/
export const addCSSUnit = (unit: string = "") => {
return (value: string | number) => typeof value == "string" ? value : `${value}${unit}`;
}
/** Function doesn't add any units by default */
export const UnitLess = addCSSUnit();
/** Function adds "px" unit to numbers */
export const UnitPX = addCSSUnit("px");
/** Function adds "deg" unit to numbers */
export const UnitDEG = addCSSUnit("deg");
/**
* Returns a closure function, which adds units to numbers, strings or arrays of both
*
* @param unit - a unit function to use to add units to {@link TypeSingleValueCSSProperty | TypeSingleValueCSSProperty's }
* @returns
* if input is a string split it into an array at the comma's, and add units
* else if the input is a number add the default units
* otherwise if the input is an array of both add units according to {@link addCSSUnit}
*/
export const CSSValue = (unit: typeof UnitLess) => {
return (input: TypeSingleValueCSSProperty) => {
return isValid(input) ? toArr(input).map(val => {
if (typeof val != "number" && typeof val != "string")
return val;
// Basically if you can convert it to a number try to,
// otherwise just return whatever you can
let num = Number(val);
let value = Number.isNaN(num) ? (typeof val == "string" ? val.trim() : val) : num;
return unit(value); // Add the default units
}) : [];
};
}
/**
* Takes `TypeSingleValueCSSProperty` or an array of `TypeSingleValueCSSProperty` and adds units approriately
*
* @param arr - array of numbers, strings and/or an array of array of both e.g. ```[[25, "50px", "60%"], "25, 35, 60%", 50]```
* @param unit - a unit function to use to add units to {@link TypeSingleValueCSSProperty | TypeSingleValueCSSProperty's }
* @returns
* an array of an array of strings with units
* e.g.
* ```ts
* [
* [ '25px', '35px', ' 60%' ],
* [ '50px', '60px', '70px' ]
* ]
* ```
*/
export const CSSArrValue = (arr: TypeSingleValueCSSProperty | TypeSingleValueCSSProperty[], unit: typeof UnitLess) => {
// This is for the full varients of the transform function as well as the 3d varients
// zipping the `CSSValue` means if a user enters a string, it will treat each value (seperated by a comma) in that
// string as a seperate transition state
return toArr(arr).map(CSSValue(unit)) as TypeSingleValueCSSProperty[];
}
/** Parses CSSValues without adding any units */
export const UnitLessCSSValue = CSSValue(UnitLess);
/** Parses CSSValues and adds the "px" unit if required */
export const UnitPXCSSValue = CSSValue(UnitPX);
/** Parses CSSValues and adds the "deg" unit if required */
export const UnitDEGCSSValue = CSSValue(UnitDEG);
/**
* Removes dashes from CSS properties & maps the values to the camelCase keys
*/
export const ParseCSSProperties = (obj: object) => {
let keys = Object.keys(obj);
let key, value, result = {};
for (let i = 0, len = keys.length; i < len; i++) {
key = camelCase(keys[i]);
value = obj[keys[i]];
result[key] = value;
}
return result;
}
export interface ITransformFunctions {
[key: string]: (value: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>) => TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>;
}
/**
* Details how to compute each transform function
*/
export const TransformFunctions: ITransformFunctions = {
"translate": value => CSSArrValue(value, UnitPX),
"translate3d": value => CSSArrValue(value, UnitPX),
"translateX": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
"translateY": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
"translateZ": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
"rotate": value => CSSArrValue(value, UnitDEG),
"rotate3d": value => CSSArrValue(value, UnitLess),
"rotateX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
"rotateY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
"rotateZ": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
"scale": value => CSSArrValue(value, UnitLess),
"scale3d": value => CSSArrValue(value, UnitLess),
"scaleX": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
"scaleY": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
"scaleZ": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
"skew": value => CSSArrValue(value, UnitDEG),
"skewX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
"skewY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
"perspective": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
};
/**
* Store all the supported transform functions as an Array
*/
export const TransformFunctionNames = Object.keys(TransformFunctions);
/**
* Creates the transform property text
*/
export const createTransformProperty = (transformFnNames: string[], arr: any[]) => {
let result = "";
let len = transformFnNames.length;
for (let i = 0; i < len; i++) {
let name = transformFnNames[i];
let value = arr[i];
if (isValid(value))
result += `${name}(${Array.isArray(value) ? value.join(", ") : value}) `;
}
return result.trim();
}
/** Common CSS Property names with the units "px" as an acceptable value */
export const CSSPXDataType = ["margin", "padding", "size", "width", "height", "left", "right", "top", "bottom", "radius", "gap", "basis", "inset", "outline-offset", "perspective", "thickness", "position", "distance", "spacing"].map(camelCase).join("|");
/**
* Removes the need for the full transform statement in order to use translate, rotate, scale, skew, or perspective including their X, Y, Z, and 3d varients
* Also, adds the ability to use single string or number values for transform functions
*
* _**Note**: the `transform` animation option will override all transform function properties_
*
* _**Note**: the order of where/when you define transform function matters, for example, depending on the order you define `translate`, and `rotate`, you can create change the radius of the rotation_
*
* @param properties - the CSS properties to transform
*
* @example
* ```ts
* ParseTransformableCSSProperties({
* // It will automatically add the "px" units for you, or you can write a string with the units you want
* translate3d: [
* "25, 35, 60%",
* [50, "60px", 70],
* ["70", 50]
* ],
* translate: "25, 35, 60%",
* translateX: [50, "60px", "70"],
* translateY: ["50, 60", "60"], // Note: this will actually result in an error, make sure to pay attention to where you are putting strings and commas
* translateZ: 0,
* perspective: 0,
* opacity: "0, 5",
* scale: [
* [1, "2"],
* ["2", 1]
* ],
* rotate3d: [
* [1, 2, 5, "3deg"], // The last value in the array must be a string with units for rotate3d
* [2, "4", 6, "45turn"],
* ["2", "4", "6", "-1rad"]
* ],
*
* // Units are required for non transform CSS properties
* // String won't be split into array, they will be wrappeed in an Array
* // It will transform border-left to camelCase "borderLeft"
* "border-left": 50,
* "offset-rotate": "10, 20",
* margin: 5,
*
* // When writing in this formation you must specify the units
* padding: "5px 6px 7px"
* })
*
* //= {
* //= transform: [
* //= // `translateY(50, 60)` will actually result in an error
* //= 'translate(25px) translate3d(25px, 35px, 60%) translateX(50px) translateY(50, 60) translateZ(0px) rotate3d(1, 2, 5, 3deg) scale(1, 2) perspective(0px)',
* //= 'translate(35px) translate3d(50px, 60px, 70px) translateX(60px) translateY(60px) rotate3d(2, 4, 6, 45turn) scale(2, 1)',
* //= 'translate(60%) translate3d(70px, 50px) translateX(70px) rotate3d(2, 4, 6, -1rad)'
* //= ],
* //= opacity: [ '0', '5' ],
* //= borderLeft: ["50px"],
* //=
* //= // Notice the "deg"
* //= offsetRotate: ["10deg", "20deg"],
* //= margin: ["5px"],
* //= padding: ["5px 6px 7px"]
* //= }
* ```
*
* @returns
* an object with a properly formatted `transform` and `opactity`, as well as other unformatted CSS properties
* ```
*/
export const ParseTransformableCSSProperties = (properties: ICSSComputedTransformableProperties) => {
// Convert dash seperated strings to camelCase strings
let AllCSSProperties = ParseCSSProperties(properties) as ICSSComputedTransformableProperties;
let rest = omit(TransformFunctionNames, AllCSSProperties);
// Adds support for ordered transforms
let transformFunctionNames = Object.keys(AllCSSProperties)
.filter(key => TransformFunctionNames.includes(key));
let transformFunctionValues = transformFunctionNames
.map((key) => TransformFunctions[key](AllCSSProperties[key]));
// The transform string
let transform = transpose(...transformFunctionValues)
.filter(isValid)
.map(arr => createTransformProperty(transformFunctionNames, arr));
// Wrap non array CSS property values in an array
rest = mapObject(rest, (value, key) => {
let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue;
// If key doesn't have the word color in it, try to add the default "px" or "deg" to it
if (!/color/i.test(key)) {
let isAngle = /rotate/i.test(key);
let isLength = new RegExp(CSSPXDataType, "i").test(key);
// There is an intresting bug that occurs if you test a string againt the same instance of a Regular Expression
// where the answer will be different every test
// so, to avoid this bug, I create a new instance every time
if (isAngle || isLength) {
// If the key has rotate in it's name use "deg" as a default unit
if (isAngle) unit = UnitDEGCSSValue;
// If the key is for a common CSS Property name which has the units "px" as an acceptable value
// try to add "px" as the default unit
else if (isLength) unit = UnitPXCSSValue;
// Note: we first apply units, to make sure if it's a simple number, then units are added
// but otherwise, if it's "margin", "padding", "inset", etc.. with values like "55 60 70 5em"
// it can easily include the units required
return unit(value).map(str => {
// To support multi-value CSS properties like "margin", "padding", and "inset"
// split the value into an array using spaces as the seperator
// then apply the valid default units and join them back with spaces
// seperating them
let arr = str.trim().split(" ");
return unit(arr).join(" ");
});
}
}
return [].concat(value).map(toStr);
});
return Object.assign({},
isValid(transform) ? { transform } : null,
rest);
}
/**
* Similar to {@link ParseTransformableCSSProperties} except it transforms the CSS properties in each Keyframe
* @param keyframes - an array of keyframes with transformable CSS properties
* @returns
* an array of keyframes, with transformed CSS properties
*/
export const ParseTransformableCSSKeyframes = (keyframes: ICSSComputedTransformableProperties[]) => {
return keyframes.map(properties => {
let {
translate,
translate3d,
translateX,
translateY,
translateZ,
rotate,
rotate3d,
rotateX,
rotateY,
rotateZ,
scale,
scale3d,
scaleX,
scaleY,
scaleZ,
skew,
skewX,
skewY,
perspective,
easing,
iterations,
offset,
...rest
// Convert dash seperated strings to camelCase strings
} = ParseCSSProperties(properties) as ICSSComputedTransformableProperties;
translate = UnitPXCSSValue(translate as TypeSingleValueCSSProperty);
translate3d = UnitPXCSSValue(translate3d as TypeSingleValueCSSProperty);
translateX = UnitPXCSSValue(translateX)[0];
translateY = UnitPXCSSValue(translateY)[0];
translateZ = UnitPXCSSValue(translateZ)[0];
rotate = UnitDEGCSSValue(rotate as TypeSingleValueCSSProperty);
rotate3d = UnitLessCSSValue(rotate3d as TypeSingleValueCSSProperty);
rotateX = UnitDEGCSSValue(rotateX)[0];
rotateY = UnitDEGCSSValue(rotateY)[0];
rotateZ = UnitDEGCSSValue(rotateZ)[0];
scale = UnitLessCSSValue(scale as TypeSingleValueCSSProperty);
scale3d = UnitLessCSSValue(scale3d as TypeSingleValueCSSProperty);
scaleX = UnitLessCSSValue(scaleX)[0];
scaleY = UnitLessCSSValue(scaleY)[0];
scaleZ = UnitLessCSSValue(scaleZ)[0];
skew = UnitDEGCSSValue(skew as TypeSingleValueCSSProperty);
skewX = UnitDEGCSSValue(skewX)[0];
skewY = UnitDEGCSSValue(skewY)[0];
perspective = UnitPXCSSValue(perspective)[0];
return [
rest,
translate, translate3d, translateX, translateY, translateZ,
rotate, rotate3d, rotateX, rotateY, rotateZ,
scale, scale3d, scaleX, scaleY, scaleZ,
skew, skewX, skewY,
perspective
];
}).map(([rest, ...transformFunctions]) => {
let transform = createTransformProperty(TransformFunctionNames, transformFunctions);
rest = mapObject(rest as object, (value, key) => {
let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue;
// If key doesn't have the word color in it, try to add the default "px" or "deg" to it
if (!/color/i.test(key)) {
let isAngle = /rotate/i.test(key);
let isLength = new RegExp(CSSPXDataType, "i").test(key);
// There is an intresting bug that occurs if you test a string againt the same instance of a Regular Expression
// where the answer will be different every test
// so, to avoid this bug, I create a new instance every time
if (isAngle || isLength) {
// If the key has rotate in it's name use "deg" as a default unit
if (isAngle) unit = UnitDEGCSSValue;
// If the key is for a common CSS Property name which has the units "px" as an acceptable value
// try to add "px" as the default unit
else if (isLength) unit = UnitPXCSSValue;
// To support multi-value CSS properties like "margin", "padding", and "inset"
// with values like "55 60 70 5em", split the value into an array using spaces as the seperator
// then apply the valid default units and join them back with spaces
// seperating them
let arr = toStr(value).trim().split(" ");
return unit(arr).join(" ");
}
}
return toStr(value);
});
return Object.assign({},
isValid(transform) ? { transform } : null,
rest);
});
} | the_stack |
import type { Plugin } from "graphile-build";
import type { ConnectionFilterResolver } from "postgraphile-plugin-connection-filter/dist/PgConnectionArgFilterPlugin";
import type { BackwardRelationSpec } from "postgraphile-plugin-connection-filter/dist/PgConnectionArgFilterBackwardRelationsPlugin";
import type { PgEntity, PgIntrospectionResultsByKind } from "graphile-build-pg";
import type {
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
} from "graphql";
import { AggregateSpec } from "./interfaces";
const FilterRelationalAggregatesPlugin: Plugin = (builder) => {
// This hook adds 'aggregates' under a "backwards" relation, siblings of
// every, some, none.
// See https://github.com/graphile-contrib/postgraphile-plugin-connection-filter/blob/6223cdb1d2ac5723aecdf55f735a18f8e2b98683/src/PgConnectionArgFilterBackwardRelationsPlugin.ts#L374
builder.hook("GraphQLInputObjectType:fields", (fields, build, context) => {
const {
extend,
newWithHooks,
inflection,
pgSql: sql,
connectionFilterResolve,
connectionFilterRegisterResolver,
connectionFilterTypesByTypeName,
connectionFilterType,
graphql,
} = build;
const {
fieldWithHooks,
scope: { foreignTable, isPgConnectionFilterMany },
Self,
} = context;
if (!isPgConnectionFilterMany || !foreignTable) return fields;
connectionFilterTypesByTypeName[Self.name] = Self;
const foreignTableTypeName = inflection.tableType(foreignTable);
const foreignTableFilterTypeName = inflection.filterType(
foreignTableTypeName
);
const foreignTableAggregateFilterTypeName = inflection.filterType(
foreignTableTypeName + "Aggregates"
);
const FilterType: GraphQLInputObjectType = connectionFilterType(
newWithHooks,
foreignTableFilterTypeName,
foreignTable,
foreignTableTypeName
);
const filterFieldName = "filter";
const AggregateType: GraphQLInputObjectType | undefined = (() => {
if (
!(
foreignTableAggregateFilterTypeName in connectionFilterTypesByTypeName
)
) {
connectionFilterTypesByTypeName[
foreignTableAggregateFilterTypeName
] = newWithHooks(
graphql.GraphQLInputObjectType,
{
description: `A filter to be used against aggregates of \`${foreignTableTypeName}\` object types.`,
name: foreignTableAggregateFilterTypeName,
fields: {
[filterFieldName]: {
description: `A filter that must pass for the relevant \`${foreignTableTypeName}\` object to be included within the aggregate.`,
type: FilterType,
},
},
},
{
pgIntrospection: foreignTable,
isPgConnectionAggregateFilter: true,
},
true
);
}
return connectionFilterTypesByTypeName[
foreignTableAggregateFilterTypeName
];
})();
if (!AggregateType) {
return fields;
}
const resolve: ConnectionFilterResolver = ({
sourceAlias,
fieldValue,
queryBuilder,
parentFieldInfo,
}) => {
if (fieldValue == null) return null;
if (!parentFieldInfo || !parentFieldInfo.backwardRelationSpec) {
throw new Error("Did not receive backward relation spec");
}
const {
keyAttributes,
foreignKeyAttributes,
}: BackwardRelationSpec = parentFieldInfo.backwardRelationSpec;
const foreignTableAlias = sql.identifier(Symbol());
const sqlIdentifier = sql.identifier(
foreignTable.namespace.name,
foreignTable.name
);
const sqlKeysMatch = sql.query`(${sql.join(
foreignKeyAttributes.map((attr, i) => {
return sql.fragment`${foreignTableAlias}.${sql.identifier(
attr.name
)} = ${sourceAlias}.${sql.identifier(keyAttributes[i].name)}`;
}),
") and ("
)})`;
// Since we want `aggregates: {filter: {...}, sum: {...}}` at the same
// level, we extract the filter for the `where` clause whilst
// extracting all the other fields for the `select` clause.
const { [filterFieldName]: filter, ...rest } = fieldValue as any;
if (Object.keys(rest).length === 0) {
const fieldNames = Object.keys(AggregateType.getFields()).filter(
(n) => n !== filterFieldName
);
const lastFieldName = fieldNames.pop();
throw new Error(
`'aggregates' filter must specify at least one aggregate: ${
fieldNames.length > 0 ? `'${fieldNames.join("', '")}' or ` : ""
}'${lastFieldName}').`
);
}
const sqlFragment = filter
? connectionFilterResolve(
filter,
foreignTableAlias,
foreignTableFilterTypeName,
queryBuilder
)
: sql.fragment`true`;
const sqlAggregateConditions = connectionFilterResolve(
rest,
foreignTableAlias,
foreignTableAggregateFilterTypeName,
queryBuilder
);
//const sqlAggregateConditions = [sql.fragment`sum(saves) > 9`];
const sqlSelectWhereKeysMatch = sql.query`(select (${sqlAggregateConditions}) from (
select * from ${sqlIdentifier} as ${foreignTableAlias}
where ${sqlKeysMatch}
and (${sqlFragment})
) as ${foreignTableAlias}
)`;
return sqlSelectWhereKeysMatch;
};
const fieldName = "aggregates";
connectionFilterRegisterResolver(Self.name, fieldName, resolve);
return extend(fields, {
[fieldName]: fieldWithHooks(
fieldName,
{
description: `Aggregates across related \`${foreignTableTypeName}\` match the filter criteria.`,
type: AggregateType,
},
{
isPgConnectionFilterAggregatesField: true,
}
),
});
});
// This hook adds our various aggregates to the 'aggregates' input defined in `AggregateType` above
builder.hook("GraphQLInputObjectType:fields", (fields, build, context) => {
const {
extend,
graphql,
newWithHooks,
inflection,
connectionFilterResolve,
connectionFilterRegisterResolver,
} = build;
const {
fieldWithHooks,
scope: { isPgConnectionAggregateFilter },
Self,
} = context;
const pgIntrospection: PgEntity | undefined = context.scope.pgIntrospection;
const pgAggregateSpecs: AggregateSpec[] = build.pgAggregateSpecs;
if (
!isPgConnectionAggregateFilter ||
!pgIntrospection ||
pgIntrospection.kind !== "class"
) {
return fields;
}
const foreignTable = pgIntrospection;
const foreignTableTypeName = inflection.tableType(foreignTable);
return pgAggregateSpecs.reduce((memo, spec) => {
const filterTypeName = inflection.filterType(
foreignTableTypeName + inflection.upperCamelCase(spec.id) + "Aggregate"
);
const AggregateType = newWithHooks(
graphql.GraphQLInputObjectType,
{
name: filterTypeName,
},
{
isPgConnectionAggregateAggregateFilter: true,
pgConnectionAggregateFilterAggregateSpec: spec,
pgIntrospection,
},
true
);
if (!AggregateType) {
return memo;
}
const fieldName = inflection.camelCase(spec.id);
const resolve: ConnectionFilterResolver = ({
sourceAlias,
fieldValue,
queryBuilder,
//parentFieldInfo,
}) => {
if (fieldValue == null) return null;
const sqlFrag = connectionFilterResolve(
fieldValue,
sourceAlias,
filterTypeName,
queryBuilder
);
return sqlFrag;
};
connectionFilterRegisterResolver(Self.name, fieldName, resolve);
return extend(
memo,
{
[fieldName]: fieldWithHooks(fieldName, {
type: AggregateType,
description: `${spec.HumanLabel} aggregate over matching \`${foreignTableTypeName}\` objects.`,
}),
},
`Adding aggregate '${spec.id}' filter input for '${pgIntrospection.name}'. `
);
}, fields);
});
// This hook adds matching columns to the relevant aggregate types.
builder.hook("GraphQLInputObjectType:fields", (fields, build, context) => {
const {
extend,
inflection,
connectionFilterOperatorsType,
newWithHooks,
pgSql: sql,
connectionFilterResolve,
connectionFilterRegisterResolver,
pgGetComputedColumnDetails: getComputedColumnDetails,
} = build;
const pgIntrospectionResultsByKind: PgIntrospectionResultsByKind =
build.pgIntrospectionResultsByKind;
const {
scope: { isPgConnectionAggregateAggregateFilter },
Self,
} = context;
const spec: AggregateSpec | undefined =
context.scope.pgConnectionAggregateFilterAggregateSpec;
const pgIntrospection: PgEntity | undefined = context.scope.pgIntrospection;
if (
!isPgConnectionAggregateAggregateFilter ||
!spec ||
!pgIntrospection ||
pgIntrospection.kind !== "class"
) {
return fields;
}
const table = pgIntrospection;
return extend(fields, {
...table.attributes.reduce((memo, attr) => {
if (
(spec.shouldApplyToEntity && !spec.shouldApplyToEntity(attr)) ||
!spec.isSuitableType(attr.type)
) {
return memo;
}
const [pgType, pgTypeModifier] = spec.pgTypeAndModifierModifier
? spec.pgTypeAndModifierModifier(attr.type, attr.typeModifier)
: [attr.type, attr.typeModifier];
const fieldName = inflection.column(attr);
const OperatorsType:
| GraphQLInputObjectType
| undefined = connectionFilterOperatorsType(
newWithHooks,
pgType.id,
pgTypeModifier
);
if (!OperatorsType) {
return memo;
}
const resolve: ConnectionFilterResolver = ({
sourceAlias,
fieldName,
fieldValue,
queryBuilder,
}) => {
if (fieldValue == null) return null;
const sqlColumn = sql.query`${sourceAlias}.${sql.identifier(
attr.name
)}`;
const sqlAggregate = spec.sqlAggregateWrap(sqlColumn);
const frag = connectionFilterResolve(
fieldValue,
sqlAggregate,
OperatorsType.name,
queryBuilder,
pgType,
pgTypeModifier,
fieldName
);
return frag;
};
connectionFilterRegisterResolver(Self.name, fieldName, resolve);
return build.extend(memo, {
[fieldName]: {
type: OperatorsType,
},
});
}, {} as GraphQLInputFieldConfigMap),
...pgIntrospectionResultsByKind.procedure.reduce((memo, proc) => {
if (proc.returnsSet) {
return memo;
}
const type = pgIntrospectionResultsByKind.typeById[proc.returnTypeId];
if (
(spec.shouldApplyToEntity && !spec.shouldApplyToEntity(proc)) ||
!spec.isSuitableType(type)
) {
return memo;
}
const computedColumnDetails = getComputedColumnDetails(
build,
table,
proc
);
if (!computedColumnDetails) {
return memo;
}
const { pseudoColumnName } = computedColumnDetails;
const fieldName = inflection.computedColumn(
pseudoColumnName,
proc,
table
);
const OperatorsType:
| GraphQLInputObjectType
| undefined = connectionFilterOperatorsType(
newWithHooks,
type.id,
null
);
if (!OperatorsType) {
return memo;
}
const resolve: ConnectionFilterResolver = ({
sourceAlias,
fieldName,
fieldValue,
queryBuilder,
}) => {
if (fieldValue == null) return null;
const sqlComputedColumnCall = sql.query`${sql.identifier(
proc.namespaceName,
proc.name
)}(${sourceAlias})`;
const sqlAggregate = spec.sqlAggregateWrap(sqlComputedColumnCall);
const frag = connectionFilterResolve(
fieldValue,
sqlAggregate,
OperatorsType.name,
queryBuilder,
type,
null,
fieldName
);
return frag;
};
connectionFilterRegisterResolver(Self.name, fieldName, resolve);
return build.extend(memo, {
[fieldName]: {
type: OperatorsType,
},
});
}, {} as GraphQLInputFieldConfigMap),
});
});
};
export default FilterRelationalAggregatesPlugin; | the_stack |
* @packageDocumentation
* @module core/data
*/
import { SUPPORT_JIT, EDITOR, TEST } from 'internal:constants';
import * as js from '../utils/js';
import { CCClass } from './class';
import { errorID, warnID } from '../platform/debug';
import { legacyCC } from '../global-exports';
import { EditorExtendableObject, editorExtrasTag } from './editor-extras-tag';
// definitions for CCObject.Flags
const Destroyed = 1 << 0;
const RealDestroyed = 1 << 1;
const ToDestroy = 1 << 2;
const DontSave = 1 << 3;
const EditorOnly = 1 << 4;
const Dirty = 1 << 5;
const DontDestroy = 1 << 6;
const Destroying = 1 << 7;
const Deactivating = 1 << 8;
const LockedInEditor = 1 << 9;
const HideInHierarchy = 1 << 10;
const IsOnEnableCalled = 1 << 11;
const IsEditorOnEnableCalled = 1 << 12;
const IsPreloadStarted = 1 << 13;
const IsOnLoadCalled = 1 << 14;
const IsOnLoadStarted = 1 << 15;
const IsStartCalled = 1 << 16;
const IsRotationLocked = 1 << 17;
const IsScaleLocked = 1 << 18;
const IsAnchorLocked = 1 << 19;
const IsSizeLocked = 1 << 20;
const IsPositionLocked = 1 << 21;
// Distributed
const IsReplicated = 1 << 22;
export const IsClientLoad = 1 << 23;
// var Hide = HideInGame | HideInEditor;
// should not clone or serialize these flags
const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating
| IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled
| IsOnEnableCalled | IsEditorOnEnableCalled
| IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked
/* RegisteredInEditor */);
// all the hideFlags
const AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy;
const objectsToDestroy: any = [];
let deferredDestroyTimer = null;
function compileDestruct (obj, ctor) {
const shouldSkipId = obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component;
const idToSkip = shouldSkipId ? '_id' : null;
let key;
const propsToReset = {};
for (key in obj) {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(key)) {
if (key === idToSkip) {
continue;
}
switch (typeof obj[key]) {
case 'string':
propsToReset[key] = '';
break;
case 'object':
case 'function':
propsToReset[key] = null;
break;
default:
break;
}
}
}
// Overwrite propsToReset according to Class
if (CCClass._isCCClass(ctor)) {
const attrs = legacyCC.Class.Attr.getClassAttrs(ctor);
const propList = ctor.__props__;
for (let i = 0; i < propList.length; i++) {
key = propList[i];
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
const attrKey = `${key + legacyCC.Class.Attr.DELIMETER}default`;
if (attrKey in attrs) {
if (shouldSkipId && key === '_id') {
continue;
}
switch (typeof attrs[attrKey]) {
case 'string':
propsToReset[key] = '';
break;
case 'object':
case 'function':
propsToReset[key] = null;
break;
case 'undefined':
propsToReset[key] = undefined;
break;
default:
break;
}
}
}
}
if (SUPPORT_JIT) {
// compile code
let func = '';
for (key in propsToReset) {
let statement;
if (CCClass.IDENTIFIER_RE.test(key)) {
statement = `o.${key}=`;
} else {
statement = `o[${CCClass.escapeForJS(key)}]=`;
}
let val = propsToReset[key];
if (val === '') {
val = '""';
}
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
func += (`${statement + val};\n`);
}
// eslint-disable-next-line @typescript-eslint/no-implied-eval,no-new-func
return Function('o', func);
} else {
return (o) => {
for (const _key in propsToReset) {
o[_key] = propsToReset[_key];
}
};
}
}
/**
* @en
* The base class of most of all the objects in Fireball.
* @zh
* 大部分对象的基类。
* @private
*/
class CCObject implements EditorExtendableObject {
public static _deferredDestroy () {
const deleteCount = objectsToDestroy.length;
for (let i = 0; i < deleteCount; ++i) {
const obj = objectsToDestroy[i];
if (!(obj._objFlags & Destroyed)) {
obj._destroyImmediate();
}
}
// if we called b.destory() in a.onDestroy(), objectsToDestroy will be resized,
// but we only destroy the objects which called destory in this frame.
if (deleteCount === objectsToDestroy.length) {
objectsToDestroy.length = 0;
} else {
objectsToDestroy.splice(0, deleteCount);
}
if (EDITOR) {
deferredDestroyTimer = null;
}
}
public declare [editorExtrasTag]: unknown;
public _objFlags: number;
protected _name: string;
constructor (name = '') {
/**
* @default ""
* @private
*/
this._name = name;
/**
* @default 0
* @private
*/
this._objFlags = 0;
}
// MEMBER
/**
* @en The name of the object.
* @zh 该对象的名称。
* @default ""
* @example
* ```
* obj.name = "New Obj";
* ```
*/
get name () {
return this._name;
}
set name (value) {
this._name = value;
}
/**
* @en After inheriting CCObject objects, control whether you need to hide, lock, serialize, and other functions.
* @zh 在继承 CCObject 对象后,控制是否需要隐藏,锁定,序列化等功能。
*/
public set hideFlags (hideFlags: CCObject.Flags) {
const flags = hideFlags & CCObject.Flags.AllHideMasks;
this._objFlags = (this._objFlags & ~CCObject.Flags.AllHideMasks) | flags;
}
public get hideFlags () {
return this._objFlags & CCObject.Flags.AllHideMasks;
}
public set replicated (value: boolean) {
if (value) {
this._objFlags |= IsReplicated;
} else {
this._objFlags &= ~IsReplicated;
}
}
public get replicated () {
return !!(this._objFlags & IsReplicated);
}
/**
* @en
* Indicates whether the object is not yet destroyed. (It will not be available after being destroyed)<br>
* When an object's `destroy` is called, it is actually destroyed after the end of this frame.
* So `isValid` will return false from the next frame, while `isValid` in the current frame will still be true.
* If you want to determine whether the current frame has called `destroy`, use `isValid(obj, true)`,
* but this is often caused by a particular logical requirements, which is not normally required.
*
* @zh
* 表示该对象是否可用(被 destroy 后将不可用)。<br>
* 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。<br>
* 因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。<br>
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。
* @default true
* @readOnly
* @example
* ```ts
* import { Node, log } from 'cc';
* const node = new Node();
* log(node.isValid); // true
* node.destroy();
* log(node.isValid); // true, still valid in this frame
* // after a frame...
* log(node.isValid); // false, destroyed in the end of last frame
* ```
*/
get isValid (): boolean {
return !(this._objFlags & Destroyed);
}
/**
* @en
* Destroy this Object, and release all its own references to other objects.<br/>
* Actual object destruction will delayed until before rendering.
* From the next frame, this object is not usable any more.
* You can use `isValid(obj)` to check whether the object is destroyed before accessing it.
* @zh
* 销毁该对象,并释放所有它对其它对象的引用。<br/>
* 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。
* 您可以在访问对象之前使用 `isValid(obj)` 来检查对象是否已被销毁。
* @return whether it is the first time the destroy being called
* @example
* ```
* obj.destroy();
* ```
*/
public destroy (): boolean {
if (this._objFlags & Destroyed) {
warnID(5000);
return false;
}
if (this._objFlags & ToDestroy) {
return false;
}
this._objFlags |= ToDestroy;
objectsToDestroy.push(this);
if (EDITOR && deferredDestroyTimer === null && legacyCC.engine && !legacyCC.engine._isUpdating) {
// auto destroy immediate in edit mode
// @ts-expect-error no function
deferredDestroyTimer = setImmediate(CCObject._deferredDestroy);
}
return true;
}
/**
* Clear all references in the instance.
*
* NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject.
* You can override the _destruct method if you need, for example:
* _destruct: function () {
* for (var key in this) {
* if (this.hasOwnProperty(key)) {
* switch (typeof this[key]) {
* case 'string':
* this[key] = '';
* break;
* case 'object':
* case 'function':
* this[key] = null;
* break;
* }
* }
* }
*
*/
public _destruct () {
const ctor: any = this.constructor;
let destruct = ctor.__destruct__;
if (!destruct) {
destruct = compileDestruct(this, ctor);
js.value(ctor, '__destruct__', destruct, true);
}
destruct(this);
}
public _destroyImmediate () {
if (this._objFlags & Destroyed) {
errorID(5000);
return;
}
// engine internal callback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
if (this._onPreDestroy) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
this._onPreDestroy();
}
if (!EDITOR || legacyCC.GAME_VIEW) {
this._destruct();
}
this._objFlags |= Destroyed;
}
}
const prototype = CCObject.prototype;
if (EDITOR || TEST) {
js.get(prototype, 'isRealValid', function (this: CCObject) {
return !(this._objFlags & RealDestroyed);
});
/**
* @en After inheriting CCObject objects, control whether you need to hide, lock, serialize, and other functions.
* This method is only available for editors and is not recommended for developers
* @zh 在继承 CCObject 对象后,控制是否需要隐藏,锁定,序列化等功能(该方法仅提供给编辑器使用,不建议开发者使用)。
*/
js.getset(prototype, 'objFlags',
function (this: CCObject) {
return this._objFlags;
},
function (this: CCObject, objFlags: CCObject.Flags) {
this._objFlags = objFlags;
});
/*
* @en
* In fact, Object's "destroy" will not trigger the destruct operation in Firebal Editor.
* The destruct operation will be executed by Undo system later.
* @zh
* 事实上,对象的 “destroy” 不会在编辑器中触发析构操作,
* 析构操作将在 Undo 系统中**延后**执行。
* @method realDestroyInEditor
* @private
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prototype.realDestroyInEditor = function () {
if (!(this._objFlags & Destroyed)) {
warnID(5001);
return;
}
if (this._objFlags & RealDestroyed) {
warnID(5000);
return;
}
this._destruct();
this._objFlags |= RealDestroyed;
};
}
if (EDITOR) {
js.value(CCObject, '_clearDeferredDestroyTimer', () => {
if (deferredDestroyTimer !== null) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
clearImmediate(deferredDestroyTimer);
deferredDestroyTimer = null;
}
});
/*
* The customized serialization for this object. (Editor Only)
* @method _serialize
* @param {Boolean} exporting
* @return {object} the serialized json data object
* @private
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prototype._serialize = null;
}
/*
* Init this object from the custom serialized data.
* @method _deserialize
* @param {Object} data - the serialized json data
* @param {_Deserializer} ctx
* @private
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prototype._deserialize = null;
/*
* Called before the object being destroyed.
* @method _onPreDestroy
* @private
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
prototype._onPreDestroy = null;
CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0, [editorExtrasTag]: {} });
CCClass.Attr.setClassAttr(CCObject, editorExtrasTag, 'editorOnly', true);
CCClass.Attr.setClassAttr(CCObject, 'replicated', 'visible', false);
/**
* Bit mask that controls object states.
* @enum Object.Flags
* @private
*/
js.value(CCObject, 'Flags', {
Destroyed,
DontSave,
EditorOnly,
Dirty,
DontDestroy,
PersistentMask,
Destroying,
Deactivating,
LockedInEditor,
HideInHierarchy,
AllHideMasks,
IsPreloadStarted,
IsOnLoadStarted,
IsOnLoadCalled,
IsOnEnableCalled,
IsStartCalled,
IsEditorOnEnableCalled,
IsPositionLocked,
IsRotationLocked,
IsScaleLocked,
IsAnchorLocked,
IsSizeLocked,
});
declare namespace CCObject {
export enum Flags {
Destroyed,
// ToDestroy: ToDestroy,
/**
* @en The object will not be saved.
* @zh 该对象将不会被保存。
*/
DontSave,
/**
* @en The object will not be saved when building a player.
* @zh 构建项目时,该对象将不会被保存。
*/
EditorOnly,
Dirty,
/**
* @en Dont destroy automatically when loading a new scene.
* @zh 加载一个新场景时,不自动删除该对象。
* @private
*/
DontDestroy,
/**
* @en
* @zh
* @private
*/
PersistentMask,
// FLAGS FOR ENGINE
/**
* @en
* @zh
* @private
*/
Destroying,
/**
* @en The node is deactivating.
* @zh 节点正在反激活的过程中。
* @private
*/
Deactivating,
/**
* @en
* Hide in game and hierarchy.
* This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags().
* @zh
* 在游戏和层级中隐藏该对象。<br/>
* 该标记只读,它只能被用作 scene.addEntity()的一个参数。
*/
// HideInGame: HideInGame,
/**
* @en The lock node, when the node is locked, cannot be clicked in the scene.
* @zh 锁定节点,锁定后场景内不能点击。
* @private
*/
LockedInEditor,
/**
* @en Hide the object in editor.
* @zh 在编辑器中隐藏该对象。
*/
HideInHierarchy,
/**
* @en The object will not be saved and hide the object in editor,and lock node, when the node is locked,
* cannot be clicked in the scene,and The object will not be saved when building a player.
* @zh 该对象将不会被保存,构建项目时,该对象将不会被保存, 锁定节点,锁定后场景内不能点击, 在编辑器中隐藏该对象。
*/
AllHideMasks,
// FLAGS FOR EDITOR
/**
* @en
* Hide in game view, hierarchy, and scene view... etc.
* This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags().
* @zh
* 在游戏视图,层级,场景视图等等...中隐藏该对象。
* 该标记只读,它只能被用作 scene.addEntity()的一个参数。
*/
// Hide: Hide,
// FLAGS FOR COMPONENT
IsPreloadStarted,
IsOnLoadStarted,
IsOnLoadCalled,
IsOnEnableCalled,
IsStartCalled,
IsEditorOnEnableCalled,
IsPositionLocked,
IsRotationLocked,
IsScaleLocked,
IsAnchorLocked,
IsSizeLocked,
IsReplicated,
IsClientLoad,
}
// for @ccclass
let __props__: string[];
let __values__: string[];
}
/*
* @en
* Checks whether the object is non-nil and not yet destroyed.<br>
* When an object's `destroy` is called, it is actually destroyed after the end of this frame.
* So `isValid` will return false from the next frame, while `isValid` in the current frame will still be true.
* If you want to determine whether the current frame has called `destroy`, use `isValid(obj, true)`,
* but this is often caused by a particular logical requirements, which is not normally required.
*
* @zh
* 检查该对象是否不为 null 并且尚未销毁。<br>
* 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。<br>
* 因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。<br>
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。
*
* @method isValid
* @param value
* @param [strictMode=false] - If true, Object called destroy() in this frame will also treated as invalid.
* @return whether is valid
* @example
* ```
* import { Node, log } from 'cc';
* var node = new Node();
* log(isValid(node)); // true
* node.destroy();
* log(isValid(node)); // true, still valid in this frame
* // after a frame...
* log(isValid(node)); // false, destroyed in the end of last frame
* ```
*/
export function isValid (value: any, strictMode?: boolean) {
if (typeof value === 'object') {
return !!value && !(value._objFlags & (strictMode ? (Destroyed | ToDestroy) : Destroyed));
} else {
return typeof value !== 'undefined';
}
}
legacyCC.isValid = isValid;
if (EDITOR || TEST) {
js.value(CCObject, '_willDestroy', (obj) => !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0);
js.value(CCObject, '_cancelDestroy', (obj) => {
obj._objFlags &= ~ToDestroy;
js.array.fastRemove(objectsToDestroy, obj);
});
}
legacyCC.Object = CCObject;
export { CCObject }; | the_stack |
import Feature from 'ol/Feature';
import Draw from 'ol/interaction/Draw';
import Translate from 'ol/interaction/Translate';
import Text from 'ol/style/Text';
import Fill from 'ol/style/Fill';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Circle from 'ol/style/Circle';
import Point from 'ol/geom/Point';
import GeometryType from 'ol/geom/GeometryType';
import MultiPoint from 'ol/geom/MultiPoint';
import LineString from 'ol/geom/LineString';
import { click as clickCondition, pointerMove as pointerMoveCondition } from 'ol/events/condition';
import { FeatureCollection, GeometryObject, LineString as GeoJsonLineString, Point as GeoJsonPoint } from 'geojson';
import VectorSource from 'ol/source/Vector';
import { getLength } from 'ol/sphere';
import GeoJSON from 'ol/format/GeoJSON';
import Select from 'ol/interaction/Select';
import { UUID } from 'angular2-uuid';
import {
calculateLineDistance,
getPointByGeometry,
ImageryVisualizer,
IVisualizerEntity,
IVisualizersConfig,
MarkerSize,
VisualizerInteractions,
VisualizersConfig
} from '@ansyn/imagery';
import { Observable } from 'rxjs';
import { take, tap } from 'rxjs/operators';
import { Inject } from '@angular/core';
import { EntitiesVisualizer } from '../entities-visualizer';
import { OpenLayersProjectionService } from '../../projection/open-layers-projection.service';
import { OpenLayersMap } from '../../maps/open-layers-map/openlayers-map/openlayers-map';
import { geometry } from '@turf/helpers';
const MEASURE_TEXT_KEY = 'measureText';
const IS_TOTAL_MEASURE = 'isTotalMeasure';
export interface ILabelHandler {
select: Select;
translate: Translate;
}
@ImageryVisualizer({
supported: [OpenLayersMap],
deps: [OpenLayersProjectionService, VisualizersConfig],
isHideable: true
})
export class MeasureRulerVisualizer extends EntitiesVisualizer {
isTotalMeasureActive: boolean;
geoJsonFormat: GeoJSON;
interactionSource: VectorSource;
hoveredMeasureId: string;
protected editDistanceStyle = new Style({
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new Stroke({
color: 'yellow',
lineDash: [10, 10],
width: 2
}),
image: new Circle({
radius: 5,
stroke: new Stroke({
color: 'rgba(0, 0, 0, 0.7)'
}),
fill: new Fill({
color: 'rgba(255, 255, 255, 0.2)'
})
}),
zIndex: 3
});
protected hoverFeatureStyle = new Style({
stroke: new Stroke({
color: this.visualizerStyle.hover.stroke,
width: this.visualizerStyle.hover['stroke-width']
})
});
get drawInteractionHandler() {
return this.interactions.get(VisualizerInteractions.drawInteractionHandler);
}
constructor(protected projectionService: OpenLayersProjectionService,
@Inject(VisualizersConfig) config: IVisualizersConfig) {
super(config.MeasureDistanceVisualizer, {
initial: {
stroke: '#3399CC',
'stroke-width': 2,
fill: '#FFFFFF',
'marker-size': MarkerSize.small,
'marker-color': '#FFFFFF',
zIndex: 5
},
hover: {
stroke: '#ccb918',
'stroke-width': 2,
fill: '#61ff55',
'marker-size': MarkerSize.small,
'marker-color': '#ff521a',
zIndex: 5
}
});
this.isTotalMeasureActive = config.MeasureDistanceVisualizer.extra.isTotalMeasureActive;
this.geoJsonFormat = new GeoJSON();
}
enableRuler(activate: boolean) {
if (activate) {
this.createDrawInteraction();
} else {
this.removeDrawInteraction();
}
}
startDeleteSingleEntity(activate: boolean) {
if (activate) {
this.createHoverForDeleteInteraction();
this.createClickDeleteInteraction();
this.removeTranslateMeasuresLabelInteraction();
} else {
this.removeHoverForDeleteInteraction();
this.removeClickDeleteInteraction();
this.createTranslateMeasuresLabelInteraction();
}
}
createHoverForDeleteInteraction() {
this.removeHoverForDeleteInteraction();
const pointerMove = new Select({
condition: pointerMoveCondition,
style: this.hoverStyle.bind(this),
layers: [this.vector],
filter: this.filterLineStringFeature.bind(this)
});
pointerMove.on('select', this.onHoveredFeature.bind(this));
this.addInteraction(VisualizerInteractions.pointerMove, pointerMove);
}
onHoveredFeature($event) {
if ($event.selected.length > 0) {
this.hoveredMeasureId = $event.selected[0].getId();
} else {
this.hoveredMeasureId = null;
}
}
removeHoverForDeleteInteraction() {
this.removeInteraction(VisualizerInteractions.pointerMove);
}
createClickDeleteInteraction() {
this.removeClickDeleteInteraction();
const click = new Select({
condition: clickCondition,
style: () => new Style({}),
layers: [this.vector],
filter: this.filterLineStringFeature.bind(this)
});
click.on('select', this.onClickDeleteFeature.bind(this));
this.addInteraction(VisualizerInteractions.click, click);
}
onClickDeleteFeature($event) {
if ($event.selected.length > 0 && this.hoveredMeasureId === $event.selected[0].getId()) {
const feature = $event.selected[0];
const entity = this.getEntity(feature);
if (entity) {
this.afterEntityDeleted(entity);
this.hoveredMeasureId = null;
}
}
}
afterEntityDeleted(entity: IVisualizerEntity) {
this.removeEntity(entity.id);
}
removeClickDeleteInteraction() {
this.removeInteraction(VisualizerInteractions.click);
}
getSinglePointLengthTextStyle(text, isTotal = false): Text {
return new Text({
font: `${isTotal ? 24 : 14}px Calibri,sans-serif`,
fill: new Fill({
color: '#FFFFFF'
}),
stroke: new Stroke({
color: '#000',
width: 3
}),
offsetY: 30,
offsetX: isTotal ? -100 : 0,
text
});
}
onResetView(): Observable<boolean> {
return super.onResetView()
.pipe(tap(() => {
if (this.drawInteractionHandler) {
this.createDrawInteraction();
}
}));
}
createDrawInteraction(type = 'LineString') {
this.removeDrawInteraction();
this.interactionSource = new VectorSource({ wrapX: false });
const drawInteractionHandler = new Draw(<any>{
source: this.interactionSource,
type: type,
condition: (event) => event.originalEvent.which === 1,
style: this.drawFeatureStyle.bind(this)
});
drawInteractionHandler.on('drawend', this.onDrawEndEvent.bind(this));
this.addInteraction(VisualizerInteractions.drawInteractionHandler, drawInteractionHandler);
}
removeDrawInteraction() {
this.removeInteraction(VisualizerInteractions.drawInteractionHandler);
}
onDrawEndEvent(data) {
data.feature.setId(UUID.UUID());
this.projectionService.projectCollectionAccurately([data.feature], this.iMap.mapObject)
.subscribe((featureCollection: FeatureCollection<GeometryObject>) => {
const [featureJson] = featureCollection.features;
const measures = this.createMeasureLabelsFeatures(<GeoJsonLineString>featureJson.geometry, <string>featureJson.id);
const newEntity: IVisualizerEntity = {
id: <string>featureJson.id,
featureJson: {
...featureJson,
properties: {
...featureJson.properties,
measures: measures.map(measure => ({ id: measure.id, featureJson: measure }))
}
}
};
this.afterDrawEndEvent(newEntity);
});
}
afterDrawEndEvent(entity: IVisualizerEntity) {
this.addOrUpdateEntities([entity]).pipe(take(1)).subscribe();
}
featurePointsStyle(initial) {
const pointsStyle = new Style({
image: new Circle({
radius: 5,
stroke: new Stroke({
color: initial.stroke,
width: initial['stroke-width']
}),
fill: new Fill({ color: initial.fill })
}),
geometry: function (feature) {
// return the coordinates of the first ring of the polygon
const coordinates = (<LineString>feature.getGeometry()).getCoordinates();
return new MultiPoint(coordinates);
}
});
return pointsStyle;
}
featureStrokeStyle(initial) {
const stroke = new Style({
stroke: new Stroke({
color: initial.stroke,
width: initial['stroke-width']
})
});
return stroke;
}
// The feature after created
createStyle(feature: Feature) {
if (this.filterLineStringFeature(feature)) {
return this.measurementMainStyle();
}
const length = feature.get(MEASURE_TEXT_KEY);
const total = feature.get(IS_TOTAL_MEASURE);
const textStyle = this.getSinglePointLengthTextStyle(length, total);
return new Style({text: textStyle});
}
// Style in draw mode
drawFeatureStyle(feature: Feature) {
const styles = this.getMeasureTextStyle(feature);
styles.push(this.editDistanceStyle);
return styles;
}
measurementMainStyle() {
const { initial } = this.visualizerStyle;
const styles = [this.featureStrokeStyle(initial)];
styles.push(this.featurePointsStyle(initial));
return styles;
}
hoverStyle(feature) {
const styles = [this.hoverFeatureStyle];
// Points
const pointsStyle = new Style({
image: new Circle({
radius: 5,
stroke: new Stroke({
color: this.visualizerStyle.hover.stroke,
width: this.visualizerStyle.hover['stroke-width']
}),
fill: new Fill({ color: this.visualizerStyle.hover.fill })
}),
geometry: function (feature) {
// return the coordinates of the first ring of the polygon
const coordinates = (<LineString>feature.getGeometry()).getCoordinates();
return new MultiPoint(coordinates);
}
});
styles.push(pointsStyle);
return styles;
}
// points string styles
getMeasureTextStyle(feature: Feature, calculateCenterOfMass = false) {
const styles = [];
const geometry = <LineString>feature.getGeometry();
if (geometry.getType() === 'Point') {
return styles;
}
const view = (<any>this.iMap.mapObject).getView();
const projection = view.getProjection();
// text points
const length = geometry.getCoordinates().length;
if (length > 2) {
geometry.forEachSegment((start, end) => {
const lineString = new LineString([start, end]);
const centroid = getPointByGeometry(<any>{
type: lineString.getType(),
coordinates: lineString.getCoordinates()
});
const segmentLengthText = this.measureApproximateLength(lineString, projection);
const singlePointLengthTextStyle = this.getSinglePointLengthTextStyle(segmentLengthText);
styles.push(new Style({
geometry: new Point(<[number, number]>centroid.coordinates),
text: singlePointLengthTextStyle
}));
});
}
if (this.isTotalMeasureActive || length === 2) {
// all line string
const allLengthText = this.measureApproximateLength(geometry, projection);
let allLinePoint = new Point(geometry.getCoordinates()[0]);
if (calculateCenterOfMass) {
const featureId = <string>feature.getId();
const entityMap = this.idToEntity.get(featureId);
if (entityMap) {
const featureGeoJson = <any>this.geoJsonFormat.writeFeatureObject(entityMap.feature);
const endCoordinate = featureGeoJson.coordinates[featureGeoJson.coordinates.length - 1];
allLinePoint = new Point(endCoordinate);
}
}
styles.push(new Style({
geometry: allLinePoint,
text: this.getSinglePointLengthTextStyle(allLengthText, true)
}));
}
return styles;
}
createTranslateMeasuresLabelInteraction() {
this.removeTranslateMeasuresLabelInteraction();
const select = new Select({
condition: (event) => pointerMoveCondition(event) && !event.dragging,
layers: [this.vector],
style: (feature) => feature.styleCache,
filter: (feature) => !this.filterLineStringFeature(feature)
});
const translate = new Translate({
features: select.getFeatures()
});
this.addInteraction(VisualizerInteractions.selectMeasureLabelHandler, select);
this.addInteraction(VisualizerInteractions.translateInteractionHandler, translate);
translate.on('translateend', this.onLabelTranslateEndEvent.bind(this))
}
onLabelTranslateEndEvent(eventData) {
this.projectionService.projectCollectionAccurately([eventData.features.item(0)], this.iMap.mapObject)
.pipe(take(1))
.subscribe((featureCollection: FeatureCollection<GeometryObject>) => {
const feature = featureCollection.features[0];
const oldEntity = feature && this.getEntityById(<string>feature.id);
if (oldEntity) {
const newEntity = {
...oldEntity,
featureJson: { ...feature }
}
this.afterLabelTranslateEndEvent(newEntity);
}
})
}
afterLabelTranslateEndEvent(labelEntity: IVisualizerEntity) {
this.addOrUpdateEntities([labelEntity]);
}
removeTranslateMeasuresLabelInteraction() {
this.removeInteraction(VisualizerInteractions.selectMeasureLabelHandler);
this.removeInteraction(VisualizerInteractions.translateInteractionHandler);
}
/**
* Format length output.
* @param line The line.
* @param projection The Projection.
*/
measureApproximateLength(line, projection): string {
const length = getLength(line, { projection: projection });
let output;
if (length >= 1000) {
output = (Math.round(length / 1000 * 100) / 100) +
' ' + 'km';
} else {
output = (Math.round(length * 100) / 100) +
' ' + 'm';
}
return output;
};
measureAccurateLength(line: GeoJsonLineString): string {
const length = line.coordinates
.map((segment, index, arr) => arr[index + 1] && [this.createGeometryPoint(segment), this.createGeometryPoint(arr[index + 1])])
.filter(Boolean)
.reduce((length, segment) => {
return length + calculateLineDistance(segment[0], segment[1]);
}, 0);
if (length < 1) {
return `${ (length * 1000).toFixed(2) } m`;
}
return `${ length.toFixed(2) } km`;
}
onDispose(): void {
this.removeTranslateMeasuresLabelInteraction();
this.removeDrawInteraction();
this.removeHoverForDeleteInteraction();
this.removeClickDeleteInteraction();
super.onDispose();
}
private createMeasureLabelsFeatures(linestring: GeoJsonLineString, featureId: string) {
// @TODO: try to make this and getMeasureTextStyle one function
const features = [];
const length = linestring.coordinates.length;
if (length > 2) {
linestring.coordinates.forEach((point, index, coordinates) => {
if (coordinates[index + 1]) {
const pointA = this.createGeometryPoint(point);
const pointB = this.createGeometryPoint(coordinates[index + 1]);
const segment = this.createGeometryLineString(pointA, pointB);
const centroid = getPointByGeometry(segment);
const segmentLengthText = this.measureAccurateLength(segment);
const labelFeature = this.createLabelFeature(centroid.coordinates, segmentLengthText);
features.push(labelFeature);
}
});
}
if (this.isTotalMeasureActive || length === 2) {
// all line string
const allLengthText = this.measureAccurateLength(linestring);
const endCoordinate = linestring.coordinates[linestring.coordinates.length - 1];
const labelFeature = this.createLabelFeature(endCoordinate, allLengthText, true);
features.push(labelFeature);
}
features.forEach(feature => feature.setId(UUID.UUID()));
features.forEach(feature => feature.set('feature', featureId));
return features.map(feature => this.geoJsonFormat.writeFeatureObject(feature));
}
private filterLineStringFeature(feature) {
return feature.getGeometry().getType() === GeometryType.LINE_STRING;
}
private createGeometryPoint(coordinates: number[]): GeoJsonPoint {
return <GeoJsonPoint>geometry('Point', coordinates);
}
private createGeometryLineString(pointA: GeoJsonPoint, pointB: GeoJsonPoint): GeoJsonLineString {
return <GeoJsonLineString>geometry('LineString', [pointA.coordinates, pointB.coordinates]);
}
private createLabelFeature(coordinates, length, total = false) {
const labelFeature = new Feature(new Point(<[number, number]>coordinates));
labelFeature.set(MEASURE_TEXT_KEY, length);
labelFeature.set(IS_TOTAL_MEASURE, total);
return labelFeature;
}
} | the_stack |
import AnswerVerb from "./answer/answer";
import HangupVerb from "./hangup/hangup";
import UnmuteVerb from "./unmute/unmute";
import GatherVerb from "./gather/gather";
import MuteVerb, {MuteOptions} from "./mute/mute";
import PlayVerb, {PlayOptions} from "./play/play";
import RecordVerb, {RecordOptions, RecordResult} from "./record/record";
import {PlaybackControl} from "./playback/playback";
import {SayOptions} from "./say/types";
import {VoiceRequest} from "./types";
import {Plugin} from "@fonos/common";
import {assertPluginExist} from "./asserts";
import PubSub from "pubsub-js";
import {Verb} from "./verb";
import {startMediaTransfer, stopMediaTransfer} from "./utils";
import SGatherVerb, {SGatherOptions} from "./sgather/gather";
import {SGatherStream} from "./sgather/types";
import {DtmfOptions} from "./dtmf/types";
import DtmfVerb from "./dtmf/dtmf";
import DialVerb from "./dial/dial";
import {DialOptions} from "./dial/types";
import StreamStatus from "./dial/status_stream";
/**
* @classdesc Use the VoiceResponse object, to construct advance Interactive
* Voice Response (IVR) applications.
*
* @extends Verb
* @example
*
* import { VoiceServer } from "@fonos/voice";
*
* async function handler (request, response) {
* await response.answer();
* await response.play("sound:hello-world");
* }
*
* const voiceServer = new VoiceServer({base: '/voiceapp'})
* voiceServer.listen(handler, { port: 3000 })
*/
export default class {
request: VoiceRequest;
plugins: {};
/**
* Constructs a new VoiceResponse object.
*
* @param {VoiceRequest} request - Options to indicate the objects endpoint
* @see module:core:FonosService
*/
constructor(request: VoiceRequest) {
this.request = request;
this.plugins = {};
}
/**
* Adds a tts or asr plugin. Only one type of plugin can be attached.
*
* @param plugin
* @see GoogleTTS
* @see GoogleASR
*/
use(plugin: Plugin): void {
this.plugins[plugin.getType()] = plugin;
}
/**
* Plays an audio in the channel.
*
* @param {string} media - Sound name or uri with audio file
* @param {PlayOptions} options - Optional parameters to alter the command's normal
* behavior
* @param {string} options.offset - Milliseconds to skip before playing. Only applies to the first URI if multiple media URIs are specified
* @param {string} options.skip - Milliseconds to skip for forward/reverse operations
* @param {string} options.playbackId - Playback identifier to use in Playback operations
* @see Playback
* @example
*
* async function handler (request, response) {
* await response.answer();
* await response.play("https://soundsserver:9000/sounds/hello-world.wav");
* }
*/
async play(media: string, options: PlayOptions = {}): Promise<void> {
await new PlayVerb(this.request).run(media, options);
}
/**
* Converts a text into a sound and sends sound to media server. To use this verb, you must
* first setup a TTS plugin such as MaryTTS, GoogleTTS, or AWS PollyTTS
*
* @param {string} text - Converts a text into a sound and sends sound to media server
* @param {SayOptions} options - Optional parameters to alter the command's normal
* behavior
* @param {string} options.offset - Milliseconds to skip before playing
* @param {string} options.skip - Milliseconds to skip for forward/reverse operations
* @param {string} options.playbackId - Playback identifier to use in Playback operations
* @see Play
* @see Voice.use
* @example
*
* async function handler (request, response) {
* await response.answer();
* response.use(new GoogleTTS())
* await response.say("Hello workd"); // Plays the sound using GoogleTTS's default values
* }
*/
async say(text: string, options: SayOptions = {}): Promise<void> {
assertPluginExist(this, "tts");
const tts = this.plugins["tts"];
// It should return the filename and the generated file location
const result = await tts.synthetize(text, options);
const media = `sound:${this.request.selfEndpoint}/tts/${result.filename}`;
await new PlayVerb(this.request).run(media, options);
}
/**
* Waits for data entry from the user's keypad or from a speech provider.
*
* @param {GatherOptions} options - Options to select the maximum number of digits, final character, and timeout
* @param {number} options.numDigits - Milliseconds to skip before playing. Only applies to the first URI if multiple media URIs are specified
* @param {number} options.timeout - Milliseconds to wait before timeout. Defaults to 4000. Use zero for no timeout.
* @param {string} options.finishOnKey - Optional last character to wait for. Defaults to '#'. It will not be included in the returned digits
* @param {string} options.source - Where to listen as input source. This option accepts `dtmf` and `speech`. A speech provider must be configure
* when including the `speech` source. You might inclue both with `dtmf,speech`. Defaults to `dtmf`
* @note When including `speech` the default timeout is 10000 (10s).
* @see SpeechProvider
* @example
*
* async function handler (request, response) {
* await response.answer();
* const digits = await response.gather({numDigits: 3});
* console.log("digits: " + digits);
* }
*/
async gather(options: {source: "speech,dtmf"}): Promise<string> {
let asr = null;
if (options.source.includes("speech")) {
assertPluginExist(this, "asr");
asr = this.plugins["asr"];
}
return await new GatherVerb(this.request, asr).run(options);
}
/**
* Waits for data entry from the user's keypad or from a stream speech provider. This command is different from `gather`
* in that it returns a stream of results instead of a single result. You can think of it as active listening.
*
* @param {SGatherOptions} options - Options object for the SGather verb
* @param {string} options.source - Where to listen as input source. This option accepts `dtmf` and `speech`. A speech provider must be configure
* when including the `speech` source. You might inclue both with `dtmf,speech`. Defaults to `speech,dtmf`
* @return {SGatherStream} The SGatherStream fires events via the `on` method for `transcription`, `dtmf`, and `error`. And the stream can be close
* with the `close` function.
* @see StreamSpeechProvider
* @example
*
* async function handler (request, response) {
* await response.answer();
* const stream = await response.sgather({source: "dtmf,speech"});
*
* stream.on("transcript", (text, isFinal) => {
* console.log("transcript: %s", text);
* })
*
* stream.on("dtmf", digit => {
* console.log("digit: " + digit);
* if (digit === "#") stream.close();
* })
* }
*/
async sgather(
options: SGatherOptions = {source: "speech,dtmf"}
): Promise<SGatherStream> {
let asr = null;
if (options.source.includes("speech")) {
assertPluginExist(this, "asr");
asr = this.plugins["asr"];
}
return await new SGatherVerb(this.request, asr).run(options);
}
/**
* Sends dtmf tones to the current session.
*
* @param {DtmfOptions} options - Options object for the Dtmf verb
* @param {string} options.dtmf - A string of the dtmf tones
* @example
*
* async function handler (request, response) {
* await response.answer();
* await response.play("sound:hello-world");
* await response.dtmf({dtmf: "1234"});
* }
*/
async dtmf(options: DtmfOptions): Promise<void> {
return await new DtmfVerb(this.request).run(options);
}
/**
* Forwards the call to an Agent or the PSTN.
*
* @param {string} destination - Number or Agent to forward the call to
* @param {DialOptions} options - Options object for the Dial verb
* @param {timeout} options.timeout - Dial timeout
* @return {StatusStream} The StatusStream fires events via the `on` method for `progress`, `answer`, `noanswer`, and `busy`. And the stream can be close
* with the `close` function.
* @example
*
* async function handler (request, response) {
* await response.answer();
* await response.say("dialing number");
* const stream = await response.dial("17853178070");
* stream.on("progress", console.log)
* stream.on("answer", console.log)
* stream.on("busy", console.log)
* }
*/
async dial(
destination: string,
options?: DialOptions
): Promise<StreamStatus> {
return await new DialVerb(this.request).run(destination, options);
}
/**
* Returns a PlaybackControl control object.
*
* @param {string} playbackId - Playback identifier to use in Playback operations
* @see Play
* @example
*
* async function handler (request, response) {
* await response.answer();
* response.onDtmfReceived(async(digit) => {
* const control = response.playback("1234")
* digit === "3"
* ? await control.restart()
* : await control.forward()
* })
*
* await response.play("https://soundsserver:9000/sounds/hello-world.wav", {
* playbackId: "1234"
* });
* }
*/
playback(playbackId: string): PlaybackControl {
return new PlaybackControl(this.request, playbackId);
}
/**
* Listens event publication.
*
* @param {Function} handler - Event handler
* @example
*
* async function handler (request, response) {
* await response.answer();
* response.on("DtmfReceived", async(digit) => {
* const control = response.playback("1234")
* digit === "3"
* ? await control.restart()
* : await control.forward()
* })
*
* await response.play("https://soundsserver:9000/sounds/hello-world.wav", {
* playbackId: "1234"
* });
* }
*/
async on(topic: string, handler: Function) {
PubSub.subscribe(`${topic}.${this.request.sessionId}`, (type, data) => {
handler(data);
});
}
/**
* Mutes a channel.
*
* @param {MuteOptions} options - Indicate which direction of he communication to mute
* @param {string} options.direction - Possible values are 'in', 'out', and 'both'
* @see unmute
* @example
*
* async function handler (request, response) {
* await response.answer();
* await response.mute(); // Will mute both directions
* }
*/
async mute(options?: MuteOptions): Promise<void> {
await new MuteVerb(this.request).run(options);
}
/**
* Unmutes a channel.
*
* @param {MuteOptions} options - Indicate which direction of he communication to unmute
* @param {string} options.direction - Possible values are 'in', 'out', and 'both'
* @see mute
* @example
*
* async function handler (request, response) {
* ...
* await response.unmute({direction: "out"}); // Will unmute only the "out" direction
* }
*/
async unmute(options?: MuteOptions): Promise<void> {
await new UnmuteVerb(this.request).run(options);
}
/**
* Answer the communication channel. Before running any other verb you
* must run the anwer command.
*
* @example
*
* async function handler (request, response) {
* await response.answer();
* ...
* }
*/
async answer(): Promise<void> {
await new AnswerVerb(this.request).run();
}
/**
* Terminates the communication channel.
*
* @example
*
* async function handler (request, response) {
* ...
* await response.hangup();
* }
*/
async hangup(): Promise<void> {
await new HangupVerb(this.request).run();
}
/**
* Records the current channel and uploads the file to the storage subsystem.
*
* @param {RecordOptions} options - optional parameters to alter the command's normal
* behavior
* @param {number} options.maxDuration - Maximum duration of the recording, in seconds. Use `0` for no limit
* @param {number} options.maxSilence - Maximum duration of silence, in seconds. Use `0` for no limit
* @param {boolean} options.beep - Play beep when recording begins
* @param {string} options.finishOnKey - DTMF input to terminate recording
* @return {Promise<RecordResult>} Returns useful information such as the duration of the recording, etc.
* @example
*
* async function handler (request, response) {
* await response.answer();;
* const result = await response.record({finishOnKey: "#"});
* console.log("recording result: " + JSON.stringify(result)) // recording result: { duration: 30 ...}
* }
*/
async record(options: RecordOptions): Promise<RecordResult> {
return await new RecordVerb(this.request).run(options);
}
// Requests media from Media server
async openMediaPipe() {
const genericVerb = new Verb(this.request);
await startMediaTransfer(genericVerb, this.request.sessionId);
}
// Requests media stop from Media server
async closeMediaPipe() {
const genericVerb = new Verb(this.request);
await stopMediaTransfer(genericVerb, this.request.sessionId);
}
} | the_stack |
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai'
import * as sinon from 'sinon'
chai.use(sinonChai);
const expect = chai.expect
import { Game } from '../src/game'
import * as Parser from 'storyboard-lang'
import * as Actions from '../src/gameActions'
describe("initialization", function() {
describe("creating a nodeGraph", function() {
var node, game: Game;
beforeEach(function() {
const story = `
start: node
# node
`
game = new Game(story)
});
it("should create a valid nodeGraph with the passed options", function() {
expect(game.story.graph).to.exist;
expect(game.story!.graph!.start).to.equal("node");
expect(Object.keys(game.story!.graph!.nodes)).to.have.length(1);
});
it("shouldn't start the game", function() {
expect(game.state.graph.currentNodeId).to.be.undefined;
});
});
describe("creating a nodeBag", function() {
it("should create a valid nodeBag with the passed nodes", function() {
const story = `## node`
const game = new Game(story)
expect(game.story.bag).to.exist;
expect(Object.keys(game.story.bag.nodes)).to.have.length(1)
});
});
});
describe("playing the node graph", function() {
context("when starting the game", function() {
context.skip("when there is a quoted start node", () => {
it("should play the appropriate content via an output", function() {
const game = new Game(`
start: "node"
# node
text: "Hello World!"
`)
const callback = sinon.spy();
game.addOutput("text", callback);
game.start();
expect(callback).to.have.been.calledWith("Hello World!", sinon.match.any);
});
})
context("when there is an unquoted start node", () => {
it("should play the appropriate content via an output", function() {
const game = new Game(`
start: node
# node
text: "Hello World!"
`)
const callback = sinon.spy();
game.addOutput("text", callback);
game.start();
expect(callback).to.have.been.calledWith("Hello World!", sinon.match.any);
});
})
});
context("when a node has no passages", function() {
let game: Game, callback: any;
beforeEach(function() {
game = new Game(`
start: first
# first
-> second: [ continue is true ]
# second
text: "Goodbye World!"
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
});
context("when a predicate has not yet been met", function() {
it("should wait for the predicate to be met", function() {
expect(callback).not.to.have.been.called
})
})
context("when a predicate has been met", function() {
it("should go immediately on", function() {
game.receiveInput("continue", true)
expect(callback).to.have.been.calledWith("Goodbye World!", sinon.match.any);
});
})
})
context("when there are multiple passages", function() {
describe("waiting for completion", function() {
let first, second, game: Game, callback: any;
beforeEach(() => {
game = new Game(`
# node
text: First
text: Second
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
});
it("shouldn't play the second passage when the first isn't done", function() {
expect(callback).to.have.been.calledWith("First", "0")
expect(callback).not.to.have.been.calledWith("Second", sinon.match.any);
});
it("should play the second passage after the first is done", function() {
game.completePassage("0");
expect(callback).to.have.been.calledWith("Second", sinon.match.any);
})
})
describe("when a passage has no content", function() {
let first, second, game, callback: any;
beforeEach(function() {
game = new Game(`
# node
set foo to 5
text: Second
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.start()
})
it("should go on to the next passage", function() {
expect(callback).to.have.been.calledWith("Second", sinon.match.any)
})
context("when it's the last one in a node", function() {
let game, callback: any;
beforeEach(function() {
game = new Game(`
# first
set foo to 5
-> second
# second
text: Second
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.start()
})
it("should go on to the next node", function() {
expect(callback).to.have.been.calledWith("Second", sinon.match.any)
})
})
})
describe("when one of them should be skipped", function() {
describe("when there are passages after the skipped one", function() {
let game: Game, callback: any;
context("when the appropriate passage has no predicate", function() {
beforeEach(function() {
game = new Game(`
# node
[ foo is false ]
text: First
text: Second
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.receiveInput("foo", true)
})
it("should go on to the next passage", function() {
game.start();
expect(callback).not.to.have.been.calledWith("First", sinon.match.any)
expect(callback).to.have.been.calledWith("Second", sinon.match.any)
})
});
context("when the appropriate passage has a matching predicate", function() {
beforeEach(function() {
game = new Game(`
# node
[ foo is false ]
text: First
[ bar is true ]
text: Second
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.receiveInput("foo", true)
game.receiveInput("bar", true)
})
it("should go to the next passage", function() {
game.start();
expect(callback).not.to.have.been.calledWith("First", sinon.match.any)
expect(callback).to.have.been.calledWith("Second", sinon.match.any)
})
})
})
describe("when the skipped passage is the last one", function() {
it("should complete the node", function() {
const game = new Game(`
# node
[ foo exists ]
text: "Hi!"
`)
const callback = sinon.spy();
game.addOutput("text", callback);
game.start();
expect(callback).not.to.have.been.calledWith("Hi!", sinon.match.any);
expect(game.state.graph.nodeComplete).to.be.true;
})
})
})
});
context("when making a choice using a push-button variable", function() {
let game: Game, callback: any;
beforeEach(function() {
game = new Game(`
# start
-> buttonPressed: [button]
# buttonPressed
text: Goodbye World!
`)
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
game.receiveMomentaryInput("button")
});
it("should trigger the appropriate nodes", function() {
expect(callback).to.have.been.calledWith("Goodbye World!", sinon.match.any);
});
it("should not affect the actual variable", function() {
expect(game.state.button).to.not.exist
})
context("when a value is passed in", function() {
beforeEach(function() {
game = new Game(`
# start
-> buttonPressed: [button is "pushed!"]
# buttonPressed
text: Goodbye World!
`);
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
game.receiveMomentaryInput("button", "pushed!")
});
it("should trigger the appropriate nodes", function() {
expect(callback).to.have.been.calledWith("Goodbye World!", sinon.match.any);
});
it("should not affect the actual variable", function() {
expect(game.state.button).to.not.exist
})
})
});
context("when making a choice", function() {
let game: Game, callback: any;
beforeEach(function() {
game = new Game(`
# first
text: foobar
-> second: [ counter >= 10 ]
# second
text: Goodbye World!
`);
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
});
describe("waiting for the node to complete", function() {
context("when the output needs to finish first", function() {
it("shouldn't change nodes until the content finishes", function() {
game.receiveInput("counter", 11);
expect(callback).not.to.have.been.calledWith("Goodbye World!", sinon.match.any);
expect(game.state.graph.currentNodeId).to.equal("first");
});
});
context("when the output has finished", function() {
it("should play the appropriate new content", function() {
game.completePassage("0"); // TODO: This is ugly
game.receiveInput("counter", 11);
expect(callback).to.have.been.calledWith("Goodbye World!", sinon.match.any);
});
});
});
describe("when the predicate has multiple conditions", function() {
beforeEach(function() {
game = new Game(`
# node
text: This doesn't matter
-> nextNode: [ counter >= 10 and counter <= 15 ]
# nextNode
text: Hi
`);
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
game.completePassage("0"); // TODO
});
it("shouldn't transition when only one condition is met", function() {
game.receiveInput("counter", 9);
expect(callback).not.to.have.been.calledWith("Hi", sinon.match.any);
});
it("shouldn't transition when only the other condition is met", function() {
game.receiveInput("counter", 16);
expect(callback).not.to.have.been.calledWith("Hi", sinon.match.any);
});
it("should transition when both conditions are met", function() {
game.receiveInput("counter", 12);
expect(callback).to.have.been.calledWith("Hi", sinon.match.any);
});
});
});
context("when a choice is triggered by an in-passage variable set", function() {
let game: Game, callback: any;
beforeEach(function() {
game = new Game(`
# first
text: Hi!
set foo to 1
-> second: [ foo is 1 ]
# second
text: Goodbye World!
`);
callback = sinon.spy();
game.addOutput("text", callback);
game.start();
});
it("shouldn't change until the passage has ended", function() {
expect(callback).not.to.have.been.calledWith("Goodbye World!", sinon.match.any);
expect(game.state.graph.currentNodeId).to.equal("first");
})
it("should change after the passage has ended", function() {
game.completePassage("0"); // TODO
expect(callback).to.have.been.calledWith("Goodbye World!", sinon.match.any);
expect(game.state.graph.currentNodeId).to.equal("second");
});
})
});
describe("triggering events from the bag", function() {
context("when the game hasn't started yet", function() {
let node, game, output: any;
beforeEach(function() {
game = new Game(`
## node
[ foo <= 10 ]
text: What do you want?
text: Well let me tell you!
`);
output = sinon.spy();
game.addOutput("text", output);
game.receiveInput("foo", 7);
});
it("shouldn't do anything", function() {
expect(output).not.to.have.been.calledOnce;
});
})
describe("different ways to trigger an event", function() {
context("when the game starts without a start", function() {
let game, output: any;
beforeEach(function() {
game = new Game(`
## node
track: other
text: First
`);
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should play a valid event node", function() {
expect(output).to.have.been.calledWith("First", sinon.match.any, "other")
})
});
context("triggered by an input change", function() {
let game: Game, output: any;
beforeEach(function() {
game = new Game(`
## node
[ foo <= 10 ]
text: What do you want?
text: Well let me tell you!
`);
output = sinon.spy();
game.addOutput("text", output);
game.start();
game.receiveInput("foo", 7);
});
it("should trigger that node", function() {
expect(output).to.have.been.calledWith("What do you want?", sinon.match.any);
});
it("should not trigger the second passage yet", function() {
expect(output).not.to.have.been.calledWith("Well let me tell you!", sinon.match.any);
});
describe("when the first passage is done", function() {
it("should play the next passage", function() {
game.completePassage("0");
expect(output).to.have.been.calledWith("Well let me tell you!", sinon.match.any);
});
});
});
context("triggered by a push-button input", function() {
let game: Game, output: any;
beforeEach(function() {
game = new Game(`
## node
[ button ]
text: What do you want?
`);
output = sinon.spy();
game.addOutput("text", output);
game.start();
game.receiveMomentaryInput("button")
});
it("should trigger that node", function() {
expect(output).to.have.been.calledWith("What do you want?", sinon.match.any);
});
it("should not change the global state", function() {
expect(game.state.button).to.not.exist
});
})
context("triggered by a graph node being completed", function() {
let node, game: Game, output: any;
beforeEach(function() {
game = new Game(`
# graphNode
text: foobar
## bagNode
[ graph.nodeComplete ]
text: Hello
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should not trigger the node initially", function() {
expect(output).not.to.have.been.calledWith("Hello", sinon.match.any);
});
describe("when the graph node is complete", function() {
it("should play the bag node", function() {
game.completePassage("1"); // TODO, lol I don't know why this is 1 instead of 0
expect(output).to.have.been.calledWith("Hello", sinon.match.any);
});
});
});
context("triggered by reaching a specific graph node", function() {
let node, game: Game, output: any;
beforeEach(function() {
game = new Game(`
# firstGraphNode
text: foo
-> secondGraphNode
# secondGraphNode
text: bar
## bagNode
[ graph.currentNodeId is "secondGraphNode" ]
text: Hello
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should not trigger the node initially", function() {
expect(output).not.to.have.been.calledWith("Hello", sinon.match.any);
});
describe("when the target graph node has been completed", function() {
it("should trigger the bag node", function() {
game.completePassage("1"); // TODO
expect(output).to.have.been.calledWith("Hello", sinon.match.any);
});
});
});
});
describe("triggering the same node multiple times", function() {
context("when the node should only trigger once", function() {
let game: Game, output: any;
beforeEach(function() {
game = new Game(`
## node
[ foo <= 10 ]
text: Something
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
})
it("shouldn't play a second time while it's still playing the first time", function() {
game.receiveInput("foo", 7);
game.receiveInput("foo", 7);
expect(output).to.have.been.calledOnce;
})
it("shouldn't play even after the first time has completed", function() {
game.receiveInput("foo", 7);
game.completePassage("0");
game.receiveInput("foo", 7);
expect(output).to.have.been.calledOnce;
})
});
context("when the node should trigger multiple times", function() {
let game: Game, node, output: any;
beforeEach(function() {
game = new Game(`
## node
[ foo <= 10 ]
text: Something
allowRepeats
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
})
it("shouldn't play a second time while it's still playing the first time", function() {
game.receiveInput("foo", 7);
game.receiveInput("foo", 7);
expect(output).to.have.been.calledOnce;
})
it.skip("should allow playing a second time", function() {
game.receiveInput("foo", 7);
game.completePassage("0");
game.receiveInput("foo", 7);
expect(output).to.have.been.calledTwice;
})
});
});
context("when there are multiple valid nodes", function() {
context("when they both belong to the default track", function() {
let game, output: any;
beforeEach(function() {
game = new Game(`
## first
text: First
## second
text: Second
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should only play one of them at once", function() {
expect(output).to.have.been.calledOnce;
})
});
context("when they belong to the same track", function() {
let game: Game, output: any;
beforeEach(function() {
game = new Game(`
## first
track: primary
text: First
## second
track: primary
text: Second
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should only play one of them at once", function() {
expect(output).to.have.been.calledOnce;
})
});
context("when they belong to different tracks", function() {
let game, node1, node2, output: any;
beforeEach(function() {
game = new Game(`
## first
track: primary
text: Primary Track!
## second
track: secondary
text: Secondary Track!
`)
output = sinon.spy();
game.addOutput("text", output);
game.start();
});
it("should play both of them", function() {
expect(output).to.have.been.calledTwice;
expect(output).to.have.been.calledWith("Primary Track!", sinon.match.any);
expect(output).to.have.been.calledWith("Secondary Track!", sinon.match.any);
})
});
})
});
describe("receiving input", function() {
context("when the input variable is a keypath", function() {
context("when the keypath exists", function() {
let game: Game;
beforeEach(function() {
game = new Game({})
game.state.foo = {}
game.receiveInput("foo.bar", "baz")
})
it("should create the appropriate state", function() {
expect(game.state.foo.bar).to.equal("baz")
})
it("should not create the wrong variable", function() {
expect(game.state["foo.bar"]).to.not.exist
})
})
// TODO: This behavior should eventually match the previous test case
context("when the keypath doesn't exist", function() {
let game: Game;
beforeEach(function() {
game = new Game({})
game.receiveInput("foo.bar", "baz")
})
it("should create nested state", function() {
expect(game.state.foo.bar).to.equal("baz")
})
it("should not create the wrong variable", function() {
expect(game.state["foo.bar"]).to.not.exist
})
})
})
context("when the input data is an object", function() {
it("should set the object", function() {
let game = new Game({});
game.receiveInput("foo", {"bar": "baz"})
expect(game.state.foo.bar).to.equal("baz")
})
})
})
describe("observing variables", function() {
let game: Game, output: any;
context("when the thing being observed is just a variable", () => {
context("changing the variable via input", () => {
beforeEach(function() {
game = new Game(`
## node
text: Don't you watch!
`);
output = sinon.spy();
game.addObserver("pot", output);
game.start()
game.receiveInput("pot", "boiled");
});
it("should trigger when the value changes", () => {
expect(output).to.have.been.calledWith("boiled")
})
})
context("changing the variable within the story", () => {
beforeEach(function() {
game = new Game(`
## node
set pot to "boiled"
`);
output = sinon.spy();
game.addObserver("pot", output);
game.start()
});
it("should trigger when the value changes", () => {
expect(output).to.have.been.calledWith("boiled")
})
})
})
context("when the thing being observed is a nested property", () => {
context("changing the value via input", () => {
beforeEach(function() {
game = new Game(`
## node
text: Don't you watch!
`);
output = sinon.spy();
game.addObserver("pot.waterTemp", output);
game.start()
game.receiveInput("pot.waterTemp", "boiled");
});
it("should trigger when the value changes", () => {
expect(output).to.have.been.calledWith("boiled")
})
it("should trigger on subsequent changes", () => {
game.receiveInput("pot.waterTemp", "unboiled")
expect(output).to.have.been.calledWith("unboiled")
})
it("should trigger when undefined", () => {
game.receiveInput("pot.waterTemp", undefined)
expect(output).to.have.been.calledWith(undefined)
})
context("when there are multiple observers", () => {
let output2 = sinon.spy()
beforeEach(() => {
game.addObserver("pot.waterLevel", output)
game.addObserver("pot.waterLevel", output2)
})
it("should trigger both", () => {
game.receiveInput("pot.waterLevel", "3 quarts")
expect(output).to.have.been.calledWith("3 quarts")
expect(output2).to.have.been.calledWith("3 quarts")
})
context("when one is unobserved", () => {
it("should only call the right one", () => {
game.removeObserver("pot.waterLevel", output)
game.receiveInput("pot.waterLevel", "3 quarts")
expect(output).to.not.have.been.calledWith("3 quarts")
expect(output2).to.have.been.calledWith("3 quarts")
})
})
})
it("should not trigger after unobserving", () => {
game.removeObserver("pot.waterTemp", output)
game.receiveInput("pot.waterTemp", "unboiled")
expect(output).to.not.have.been.calledWith("unboiled")
})
})
context("changing the value within the story", () => {
beforeEach(function() {
game = new Game(`
## node
set pot.waterTemp to "boiled"
`);
output = sinon.spy();
game.addObserver("pot.waterTemp", output);
game.start()
});
it("should trigger when the value changes", () => {
expect(output).to.have.been.calledWith("boiled")
})
it("should trigger on subsequent changes", () => {
game = new Game(`
## node
set pot.waterTemp to "boiled"
set pot.waterTemp to "unboiled"
`);
output = sinon.spy();
game.addObserver("pot.waterTemp", output);
game.start()
expect(output).to.have.been.calledWith("boiled")
expect(output).to.have.been.calledWith("unboiled")
})
})
})
// TODO
context.skip("when the thing being observed is a system variable", () => {
beforeEach(function() {
game = new Game(`
## node
set pot.waterTemp to "boiled"
`);
output = sinon.spy();
game.addObserver("graph.currentNodeId", output);
game.start()
});
it("should trigger when the value changes", () => {
expect(output).to.have.been.calledWith("node")
})
})
})
// TODO: Find somewhere else for these to live?
describe("receiveDispatch", function() {
// TODO: Backfill this out
describe("MAKE_GRAPH_CHOICE",function() {
let choice1: Parser.Choice, choice2: Parser.Choice, game: Game;
beforeEach(function() {
choice1 = { nodeId: "3" }
choice2 = { nodeId: "4" }
game = new Game({
graph: {
nodes: {
2: {nodeId: "2"},
3: {nodeId: "3", "passages":[]},
4:{ nodeId: "4", "passages":[]}
}}})
game.state.graph.currentNodeId = "2";
game.receiveDispatch(Actions.MAKE_GRAPH_CHOICE, choice1);
game.receiveDispatch(Actions.MAKE_GRAPH_CHOICE, choice2);
});
it("should update the previousChoice with the most recent choice", function() {
expect(game.state.graph.previousChoice).to.eql(choice2);
});
it("should store the full choice history in reverse-chronological order", function() {
expect(game.state.graph.choiceHistory).to.eql([choice2, choice1]);
});
it("should store the previous nodeId", function() {
expect(game.state.graph.previousNodeId).to.equal("3");
});
it("should store the full node history in reverse-chronological order", function() {
expect(game.state.graph.nodeHistory).to.eql(["3", "2"]);
});
});
// TODO:
// COMPLETE_BAG_NODE now relies on more of the state graph than is being exposed in this tiny harness.
// I could hack it to work now, but I need to think more about the value and structure of these unit-level tests in general
describe.skip("COMPLETE_BAG_NODE", function() {
it("should remove the node from the list of active bag passages", function() {
const game = new Game({});
game.state.bag.activePassageIndexes["1"] = 0;
game.receiveDispatch(Actions.COMPLETE_BAG_NODE, "1");
expect(game.state.bag.activePassageIndexes["1"]).to.be.undefined;
});
it("should trigger a sweep of new bag nodes", function() {
// TODO: I'm not sure this is a valuable test!
const game = new Game({});
sinon.stub(game.story.bag, "checkNodes");
game.receiveDispatch(Actions.COMPLETE_BAG_NODE, "1");
expect(game.story.bag.checkNodes).to.have.been.calledWith(game.state);
});
context("when the node has never been visited before", function() {
it("should add it to the bag node history", function() {
const game = new Game({});
expect(game.state.bag.nodeHistory["1"]).to.be.undefined;
game.receiveDispatch(Actions.COMPLETE_BAG_NODE, "1");
expect(game.state.bag.nodeHistory["1"]).to.equal(1);
})
})
context("when the node has been visited before", function() {
it("should increment its node history", function() {
const game = new Game({});
game.receiveDispatch(Actions.COMPLETE_BAG_NODE, "1");
game.receiveDispatch(Actions.COMPLETE_BAG_NODE, "1");
expect(game.state.bag.nodeHistory["1"]).to.equal(2);
});
})
});
describe("OUTPUT", function() {
describe("selecting outputs", function() {
let textOutput1: any, textOutput2: any, audioOutput: any, game, passage;
beforeEach(function() {
textOutput1 = sinon.spy();
textOutput2 = sinon.spy();
audioOutput = sinon.spy();
game = new Game({});
game.addOutput("text", textOutput1);
game.addOutput("text", textOutput2);
game.addOutput("audio", audioOutput);
passage = {
"passageId": "5",
"content": "Hello World!",
"type": "text"
};
game.receiveDispatch(Actions.OUTPUT, passage)
});
it("should send output to all registered outputs of that type", function() {
expect(textOutput1).to.have.been.calledWith("Hello World!", sinon.match.any);
expect(textOutput2).to.have.been.calledWith("Hello World!", sinon.match.any);
});
it("should only send output to outputs of the same type", function() {
expect(audioOutput).not.to.have.been.calledWith("Hello World!", sinon.match.any);
});
});
it("should evaluate all embedded variables", function() {
const game = new Game({});
const output = sinon.spy()
const passage = {
"passageId": "5",
"content": "Hello {yourName}, it's {myName}!",
"type": "text"
};
game.state.yourName = "Stanley";
game.state.myName = "Ollie";
game.addOutput("text", output);
game.receiveDispatch(Actions.OUTPUT, passage);
expect(output).to.have.been.calledWith("Hello Stanley, it's Ollie!", sinon.match.any);
});
it("should allow nested keypaths in variables", function() {
const game = new Game({});
const output = sinon.spy()
const passage = {
"passageId": "5",
"content": "You're in node {graph.currentNodeId}!",
"type": "text"
};
game.state.graph.currentNodeId = "1";
game.addOutput("text", output);
game.receiveDispatch(Actions.OUTPUT, passage);
expect(output).to.have.been.calledWith("You're in node 1!", sinon.match.any);
});
});
}); | the_stack |
import type { IndentXml } from '@asap/shared/domain/xml';
import type {
FailedAssert,
ParseSchematronAssertions,
SchematronJSONToXMLProcessor,
SchematronProcessor,
SchematronResult,
SuccessfulReport,
} from '@asap/shared/use-cases/schematron';
import type { XSLTProcessor } from '../use-cases/assertion-views';
const getValidationReport = (
SaxonJS: any,
document: DocumentFragment,
): SchematronResult => {
const failedAsserts = SaxonJS.XPath.evaluate(
'//svrl:failed-assert',
document,
{
namespaceContext: { svrl: 'http://purl.oclc.org/dsdl/svrl' },
resultForm: 'array',
},
);
const successfulReports = SaxonJS.XPath.evaluate(
'//svrl:successful-report',
document,
{
namespaceContext: { svrl: 'http://purl.oclc.org/dsdl/svrl' },
resultForm: 'array',
},
);
return {
failedAsserts: Array.prototype.map.call(failedAsserts, (assert, index) => {
return Object.keys(assert.attributes).reduce(
(assertMap: Record<string, FailedAssert>, key: string) => {
const name = assert.attributes[key].name;
if (name) {
assertMap[name] = assert.attributes[key].value;
}
return assertMap;
},
{
diagnosticReferences: Array.prototype.map.call(
SaxonJS.XPath.evaluate('svrl:diagnostic-reference', assert, {
namespaceContext: { svrl: 'http://purl.oclc.org/dsdl/svrl' },
resultForm: 'array',
}),
(node: Node) => node.textContent,
) as any,
text: SaxonJS.XPath.evaluate('svrl:text', assert, {
namespaceContext: { svrl: 'http://purl.oclc.org/dsdl/svrl' },
}).textContent,
uniqueId: `${assert.getAttribute('id')}-${index}` as any,
},
);
}) as FailedAssert[],
successfulReports: Array.prototype.map.call(
successfulReports,
(report, index) => {
return Object.keys(report.attributes).reduce(
(assertMap: Record<string, FailedAssert>, key: string) => {
const name = report.attributes[key].name;
if (name) {
assertMap[name] = report.attributes[key].value;
}
return assertMap;
},
{
text: SaxonJS.XPath.evaluate('svrl:text', report, {
namespaceContext: { svrl: 'http://purl.oclc.org/dsdl/svrl' },
}).textContent,
uniqueId: `${report.getAttribute('id')}-${index}` as any,
},
);
},
) as SuccessfulReport[],
};
};
export const SaxonJsSchematronProcessorGateway =
(ctx: {
sefUrl: string;
SaxonJS: any;
baselinesBaseUrl: string;
registryBaseUrl: string;
}): SchematronProcessor =>
(sourceText: string) => {
return (
ctx.SaxonJS.transform(
{
stylesheetLocation: ctx.sefUrl,
destination: 'document',
sourceText: sourceText,
stylesheetParams: {
'baselines-base-path': ctx.baselinesBaseUrl,
'registry-base-path': ctx.registryBaseUrl,
'param-use-remote-resources': '1',
},
},
'async',
) as Promise<DocumentFragment>
).then((output: any) => {
return getValidationReport(
ctx.SaxonJS,
output.principalResult as DocumentFragment,
);
});
};
type XmlIndenterContext = {
SaxonJS: any;
};
export const XmlIndenter =
(ctx: XmlIndenterContext): IndentXml =>
(sourceText: string) => {
return (
ctx.SaxonJS.transform(
// This is an XSLT identity tranformation, manually-compiled to SEF
// format. Its output is indented XML.
{
stylesheetInternal: {
N: 'package',
version: '10',
packageVersion: '1',
saxonVersion: 'Saxon-JS 2.2',
target: 'JS',
targetVersion: '2',
name: 'TOP-LEVEL',
relocatable: 'true',
buildDateTime: '2021-07-01T13:24:49.504-05:00',
ns: 'xml=~ xsl=~',
C: [
{
N: 'co',
id: '0',
binds: '0',
C: [
{
N: 'mode',
onNo: 'TC',
flags: '',
patternSlots: '0',
prec: '',
C: [
{
N: 'templateRule',
rank: '0',
prec: '0',
seq: '0',
ns: 'xml=~ xsl=~',
minImp: '0',
flags: 's',
baseUri:
'file:///Users/dan/src/10x/fedramp-automation/resources/validations/ui/identity.xsl',
slots: '200',
line: '3',
module: 'identity.xsl',
match: 'node()|@*',
prio: '-0.5',
matches: 'N u[NT,NP,NC,NE]',
C: [
{
N: 'p.nodeTest',
role: 'match',
test: 'N u[NT,NP,NC,NE]',
sType: '1N u[NT,NP,NC,NE]',
},
{
N: 'copy',
sType: '1N u[1NT ,1NP ,1NC ,1NE ] ',
flags: 'cin',
role: 'action',
line: '4',
C: [
{
N: 'applyT',
sType: '* ',
line: '5',
mode: '#unnamed',
bSlot: '0',
C: [
{
N: 'docOrder',
sType:
'*N u[N u[N u[N u[NT,NP],NC],NE],NA]',
role: 'select',
line: '5',
C: [
{
N: 'union',
op: '|',
sType:
'*N u[N u[N u[N u[NT,NP],NC],NE],NA]',
ns: '= xml=~ fn=~ xsl=~ ',
C: [
{
N: 'axis',
name: 'child',
nodeTest: '*N u[NT,NP,NC,NE]',
},
{
N: 'axis',
name: 'attribute',
nodeTest: '*NA',
},
],
},
],
},
],
},
],
},
],
},
{
N: 'templateRule',
rank: '1',
prec: '0',
seq: '0',
ns: 'xml=~ xsl=~',
minImp: '0',
flags: 's',
baseUri:
'file:///Users/dan/src/10x/fedramp-automation/resources/validations/ui/identity.xsl',
slots: '200',
line: '3',
module: 'identity.xsl',
match: 'node()|@*',
prio: '-0.5',
matches: 'NA',
C: [
{
N: 'p.nodeTest',
role: 'match',
test: 'NA',
sType: '1NA',
},
{
N: 'copy',
sType: '1NA ',
flags: 'cin',
role: 'action',
line: '4',
C: [
{
N: 'applyT',
sType: '* ',
line: '5',
mode: '#unnamed',
bSlot: '0',
C: [
{
N: 'docOrder',
sType:
'*N u[N u[N u[N u[NT,NP],NC],NE],NA]',
role: 'select',
line: '5',
C: [
{
N: 'union',
op: '|',
sType:
'*N u[N u[N u[N u[NT,NP],NC],NE],NA]',
ns: '= xml=~ fn=~ xsl=~ ',
C: [
{
N: 'axis',
name: 'child',
nodeTest: '*N u[NT,NP,NC,NE]',
},
{
N: 'axis',
name: 'attribute',
nodeTest: '*NA',
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
{ N: 'overridden' },
{
N: 'output',
C: [
{
N: 'property',
name: 'Q{http://saxon.sf.net/}stylesheet-version',
value: '10',
},
{ N: 'property', name: 'omit-xml-declaration', value: 'yes' },
{ N: 'property', name: 'indent', value: 'yes' },
],
},
{ N: 'decimalFormat' },
],
Σ: 'da0fec95',
},
destination: 'serialized',
sourceText,
},
'async',
) as Promise<DocumentFragment>
)
.then((output: any) => {
return output.principalResult as string;
})
.catch(error => {
console.error(error);
throw new Error(`Error indenting xml: ${error}`);
});
};
export const SchematronParser =
(ctx: { SaxonJS: any }): ParseSchematronAssertions =>
(schematron: string) => {
const document = ctx.SaxonJS.getPlatform().parseXmlFromString(schematron);
const asserts = ctx.SaxonJS.XPath.evaluate('//sch:assert', document, {
namespaceContext: { sch: 'http://purl.oclc.org/dsdl/schematron' },
resultForm: 'array',
});
return asserts.map((assert: any) => ({
id: assert.getAttribute('id'),
message: assert.textContent,
role: assert.getAttribute('role'),
}));
};
// Wrapper over an XSLT transform that logs and re-rasies errors.
const transform = async (SaxonJS: any, options: any) => {
try {
return SaxonJS.transform(options, 'async') as Promise<DocumentFragment>;
} catch (error) {
console.error(error);
throw new Error(`Error transforming xml: ${error}`);
}
};
/**
* Given XSLT in SEF format and an input XML document, return a string of the
* transformed XML.
**/
export const SaxonJsProcessor =
(ctx: { SaxonJS: any }): XSLTProcessor =>
(stylesheetText: string, sourceText: string) => {
try {
return transform(ctx.SaxonJS, {
stylesheetText,
sourceText,
destination: 'serialized',
stylesheetParams: {},
}).then((output: any) => {
return output.principalResult as string;
});
} catch (error) {
console.error(error);
throw new Error(`Error transforming xml: ${error}`);
}
};
export const SaxonJsJsonSspToXmlProcessor =
(ctx: { sefUrl: string; SaxonJS: any }): SchematronJSONToXMLProcessor =>
(jsonString: string) => {
return ctx.SaxonJS.transform(
{
stylesheetLocation: ctx.sefUrl,
destination: 'serialized',
initialTemplate: 'from-json',
stylesheetParams: {
file: 'data:application/json;base64,' + btoa(jsonString),
},
},
'async',
).then((output: any) => {
return output.principalResult as string;
});
}; | the_stack |
import _ from 'lodash';
export class SeriesSizeItem {
public scrollIndex: number = -1;
public modelIndex: number;
public frozenIndex: number = -1;
public size: number;
public position: number;
public get endPosition(): number {
return this.position + this.size;
}
}
export class SeriesSizes {
private sizeOverridesByModelIndex: { [id: number]: number } = {};
public count: number = 0;
public defaultSize: number = 50;
public maxSize: number = 1000;
private hiddenAndFrozenModelIndexes: number[] = [];
private frozenModelIndexes: number[] = [];
private hiddenModelIndexes: number[] = [];
private scrollItems: SeriesSizeItem[] = [];
private positions: number[] = [];
private scrollIndexes: number[] = [];
private modelIndexes: number[] = [];
private frozenItems: SeriesSizeItem[] = [];
public get scrollCount(): number {
return this.count - (this.hiddenAndFrozenModelIndexes != null ? this.hiddenAndFrozenModelIndexes.length : 0);
}
public get frozenCount(): number {
return this.frozenModelIndexes != null ? this.frozenModelIndexes.length : 0;
}
public get frozenSize(): number {
return _.sumBy(this.frozenItems, x => x.size);
}
public get realCount(): number {
return this.frozenCount + this.scrollCount;
}
// public clear(): void {
// this.scrollItems = [];
// this.sizeOverridesByModelIndex = {};
// this.positions = [];
// this.scrollIndexes = [];
// this.frozenItems = [];
// this.hiddenAndFrozenModelIndexes = null;
// this.frozenModelIndexes = null;
// }
public putSizeOverride(modelIndex: number, size: number, sizeByUser = false): void {
if (this.maxSize && size > this.maxSize && !sizeByUser) {
size = this.maxSize;
}
let currentSize = this.sizeOverridesByModelIndex[modelIndex];
if (sizeByUser || !currentSize || size > currentSize) {
this.sizeOverridesByModelIndex[modelIndex] = size;
}
// if (!_.has(this.sizeOverridesByModelIndex, modelIndex))
// this.sizeOverridesByModelIndex[modelIndex] = size;
// if (size > this.sizeOverridesByModelIndex[modelIndex])
// this.sizeOverridesByModelIndex[modelIndex] = size;
}
public buildIndex(): void {
this.scrollItems = [];
this.scrollIndexes = _.filter(
_.map(_.range(this.count), x => this.modelToReal(x) - this.frozenCount),
// _.map(this.intKeys(_.keys(this.sizeOverridesByModelIndex)), (x) => this.modelToReal(x) - this.frozenCount),
x => x >= 0
);
this.scrollIndexes.sort();
let lastScrollIndex: number = -1;
let lastEndPosition: number = 0;
this.scrollIndexes.forEach(scrollIndex => {
let modelIndex: number = this.realToModel(scrollIndex + this.frozenCount);
let size: number = this.sizeOverridesByModelIndex[modelIndex];
let item = new SeriesSizeItem();
item.scrollIndex = scrollIndex;
item.modelIndex = modelIndex;
item.size = size;
item.position = lastEndPosition + (scrollIndex - lastScrollIndex - 1) * this.defaultSize;
this.scrollItems.push(item);
lastScrollIndex = scrollIndex;
lastEndPosition = item.endPosition;
});
this.positions = _.map(this.scrollItems, x => x.position);
this.frozenItems = [];
let lastpos: number = 0;
for (let i: number = 0; i < this.frozenCount; i++) {
let modelIndex: number = this.frozenModelIndexes[i];
let size: number = this.getSizeByModelIndex(modelIndex);
let item = new SeriesSizeItem();
item.frozenIndex = i;
item.modelIndex = modelIndex;
item.size = size;
item.position = lastpos;
this.frozenItems.push(item);
lastpos += size;
}
this.modelIndexes = _.range(0, this.count);
if (this.hiddenAndFrozenModelIndexes) {
this.modelIndexes = this.modelIndexes.filter(col => !this.hiddenAndFrozenModelIndexes.includes(col));
}
}
public getScrollIndexOnPosition(position: number): number {
let itemOrder: number = _.sortedIndex(this.positions, position);
if (this.positions[itemOrder] == position) return itemOrder;
if (itemOrder == 0) return Math.floor(position / this.defaultSize);
if (position <= this.scrollItems[itemOrder - 1].endPosition) return this.scrollItems[itemOrder - 1].scrollIndex;
return (
Math.floor((position - this.scrollItems[itemOrder - 1].position) / this.defaultSize) +
this.scrollItems[itemOrder - 1].scrollIndex
);
}
public getFrozenIndexOnPosition(position: number): number {
this.frozenItems.forEach(function (item) {
if (position >= item.position && position <= item.endPosition) return item.frozenIndex;
});
return -1;
}
// public getSizeSum(startScrollIndex: number, endScrollIndex: number): number {
// let order1: number = _.sortedIndexOf(this.scrollIndexes, startScrollIndex);
// let order2: number = _.sortedIndexOf(this.scrollIndexes, endScrollIndex);
// let count: number = endScrollIndex - startScrollIndex;
// if (order1 < 0)
// order1 = ~order1;
// if (order2 < 0)
// order2 = ~order2;
// let result: number = 0;
// for (let i: number = order1; i <= order2; i++) {
// if (i < 0)
// continue;
// if (i >= this.scrollItems.length)
// continue;
// let item = this.scrollItems[i];
// if (item.scrollIndex < startScrollIndex)
// continue;
// if (item.scrollIndex >= endScrollIndex)
// continue;
// result += item.size;
// count--;
// }
// result += count * this.defaultSize;
// return result;
// }
public getSizeByModelIndex(modelIndex: number): number {
if (_.has(this.sizeOverridesByModelIndex, modelIndex)) return this.sizeOverridesByModelIndex[modelIndex];
return this.defaultSize;
}
public getSizeByScrollIndex(scrollIndex: number): number {
return this.getSizeByRealIndex(scrollIndex + this.frozenCount);
}
public getSizeByRealIndex(realIndex: number): number {
let modelIndex: number = this.realToModel(realIndex);
return this.getSizeByModelIndex(modelIndex);
}
public removeSizeOverride(realIndex: number): void {
let modelIndex: number = this.realToModel(realIndex);
delete this.sizeOverridesByModelIndex[modelIndex];
}
public getScroll(sourceScrollIndex: number, targetScrollIndex: number): number {
if (sourceScrollIndex < targetScrollIndex) {
return -_.sum(
_.map(_.range(sourceScrollIndex, targetScrollIndex - sourceScrollIndex), x => this.getSizeByScrollIndex(x))
);
} else {
return _.sum(
_.map(_.range(targetScrollIndex, sourceScrollIndex - targetScrollIndex), x => this.getSizeByScrollIndex(x))
);
}
}
public modelIndexIsInScrollArea(modelIndex: number): boolean {
let realIndex = this.modelToReal(modelIndex);
return realIndex >= this.frozenCount;
}
public getTotalScrollSizeSum(): number {
let scrollSizeOverrides = _.map(
_.filter(this.intKeys(this.sizeOverridesByModelIndex), x => this.modelIndexIsInScrollArea(x)),
x => this.sizeOverridesByModelIndex[x]
);
return _.sum(scrollSizeOverrides) + (this.count - scrollSizeOverrides.length) * this.defaultSize;
}
public getVisibleScrollSizeSum(): number {
let scrollSizeOverrides = _.map(
_.filter(this.intKeys(this.sizeOverridesByModelIndex), x => !_.includes(this.hiddenAndFrozenModelIndexes, x)),
x => this.sizeOverridesByModelIndex[x]
);
return (
_.sum(scrollSizeOverrides) +
(this.count - this.hiddenModelIndexes.length - scrollSizeOverrides.length) * this.defaultSize
);
}
private intKeys(value): number[] {
return _.keys(value).map(x => _.parseInt(x));
}
public getPositionByRealIndex(realIndex: number): number {
if (realIndex < 0) return 0;
if (realIndex < this.frozenCount) return this.frozenItems[realIndex].position;
return this.getPositionByScrollIndex(realIndex - this.frozenCount);
}
public getPositionByScrollIndex(scrollIndex: number): number {
let order: number = _.sortedIndex(this.scrollIndexes, scrollIndex);
if (this.scrollIndexes[order] == scrollIndex) return this.scrollItems[order].position;
order--;
if (order < 0) return scrollIndex * this.defaultSize;
return (
this.scrollItems[order].endPosition + (scrollIndex - this.scrollItems[order].scrollIndex - 1) * this.defaultSize
);
}
public getVisibleScrollCount(firstVisibleIndex: number, viewportSize: number): number {
let res: number = 0;
let index: number = firstVisibleIndex;
let count: number = 0;
while (res < viewportSize && index <= this.scrollCount) {
res += this.getSizeByScrollIndex(index);
index++;
count++;
}
return count;
}
public getVisibleScrollCountReversed(lastVisibleIndex: number, viewportSize: number): number {
let res: number = 0;
let index: number = lastVisibleIndex;
let count: number = 0;
while (res < viewportSize && index >= 0) {
res += this.getSizeByScrollIndex(index);
index--;
count++;
}
return count;
}
public invalidateAfterScroll(
oldFirstVisible: number,
newFirstVisible: number,
invalidate: (_: number) => void,
viewportSize: number
): void {
if (newFirstVisible > oldFirstVisible) {
let oldVisibleCount: number = this.getVisibleScrollCount(oldFirstVisible, viewportSize);
let newVisibleCount: number = this.getVisibleScrollCount(newFirstVisible, viewportSize);
for (let i: number = oldFirstVisible + oldVisibleCount - 1; i <= newFirstVisible + newVisibleCount; i++) {
invalidate(i + this.frozenCount);
}
} else {
for (let i: number = newFirstVisible; i <= oldFirstVisible; i++) {
invalidate(i + this.frozenCount);
}
}
}
public isWholeInView(firstVisibleIndex: number, index: number, viewportSize: number): boolean {
let res: number = 0;
let testedIndex: number = firstVisibleIndex;
while (res < viewportSize && testedIndex < this.count) {
res += this.getSizeByScrollIndex(testedIndex);
if (testedIndex == index) return res <= viewportSize;
testedIndex++;
}
return false;
}
public scrollInView(firstVisibleIndex: number, scrollIndex: number, viewportSize: number): number {
if (this.isWholeInView(firstVisibleIndex, scrollIndex, viewportSize)) {
return firstVisibleIndex;
}
if (scrollIndex < firstVisibleIndex) {
return scrollIndex;
}
let testedIndex = firstVisibleIndex + 1;
while (testedIndex < this.scrollCount) {
if (this.isWholeInView(testedIndex, scrollIndex, viewportSize)) {
return testedIndex;
}
testedIndex++;
}
return this.scrollCount - 1;
// let res: number = 0;
// let testedIndex: number = scrollIndex;
// while (res < viewportSize && testedIndex >= 0) {
// let size: number = this.getSizeByScrollIndex(testedIndex);
// if (res + size > viewportSize) return testedIndex + 1;
// testedIndex--;
// res += size;
// }
// if (res >= viewportSize && testedIndex < scrollIndex) return testedIndex + 1;
// return firstVisibleIndex;
}
public resize(realIndex: number, newSize: number): void {
if (realIndex < 0) return;
let modelIndex: number = this.realToModel(realIndex);
if (modelIndex < 0) return;
this.sizeOverridesByModelIndex[modelIndex] = newSize;
this.buildIndex();
}
public setExtraordinaryIndexes(hidden: number[], frozen: number[]): void {
//this._hiddenAndFrozenModelIndexes = _.clone(hidden);
hidden = hidden.filter(x => x >= 0);
frozen = frozen.filter(x => x >= 0);
hidden.sort((a, b) => a - b);
frozen.sort((a, b) => a - b);
this.frozenModelIndexes = _.filter(frozen, x => !_.includes(hidden, x));
this.hiddenModelIndexes = _.filter(hidden, x => !_.includes(frozen, x));
this.hiddenAndFrozenModelIndexes = _.concat(hidden, this.frozenModelIndexes);
this.frozenModelIndexes.sort((a, b) => a - b);
if (this.hiddenAndFrozenModelIndexes.length == 0) this.hiddenAndFrozenModelIndexes = null;
if (this.frozenModelIndexes.length == 0) this.frozenModelIndexes = null;
this.buildIndex();
}
public realToModel(realIndex: number): number {
return this.modelIndexes[realIndex] ?? -1;
// console.log('realToModel', realIndex);
// if (this.hiddenAndFrozenModelIndexes == null && this.frozenModelIndexes == null) return realIndex;
// if (realIndex < 0) return -1;
// if (realIndex < this.frozenCount && this.frozenModelIndexes != null) return this.frozenModelIndexes[realIndex];
// if (this.hiddenAndFrozenModelIndexes == null) return realIndex;
// realIndex -= this.frozenCount;
// console.log('this.hiddenAndFrozenModelIndexes', this.hiddenAndFrozenModelIndexes);
// for (let hidItem of this.hiddenAndFrozenModelIndexes) {
// if (realIndex < hidItem) return realIndex;
// realIndex++;
// }
// console.log('realToModel RESP', realIndex);
// return realIndex;
}
public modelToReal(modelIndex: number): number {
return this.modelIndexes.indexOf(modelIndex);
// if (this.hiddenAndFrozenModelIndexes == null && this.frozenModelIndexes == null) return modelIndex;
// if (modelIndex < 0) return -1;
// let frozenIndex: number = this.frozenModelIndexes != null ? _.indexOf(this.frozenModelIndexes, modelIndex) : -1;
// if (frozenIndex >= 0) return frozenIndex;
// if (this.hiddenAndFrozenModelIndexes == null) return modelIndex;
// let hiddenIndex: number = _.sortedIndex(this.hiddenAndFrozenModelIndexes, modelIndex);
// if (this.hiddenAndFrozenModelIndexes[hiddenIndex] == modelIndex) return -1;
// if (hiddenIndex >= 0) return modelIndex - hiddenIndex + this.frozenCount;
// return modelIndex;
}
public getFrozenPosition(frozenIndex: number): number {
return this.frozenItems[frozenIndex].position;
}
public hasSizeOverride(modelIndex: number): boolean {
return _.has(this.sizeOverridesByModelIndex, modelIndex);
}
public isVisible(testedRealIndex: number, firstVisibleScrollIndex: number, viewportSize: number): boolean {
if (testedRealIndex < 0) return false;
if (testedRealIndex >= 0 && testedRealIndex < this.frozenCount) return true;
let scrollIndex: number = testedRealIndex - this.frozenCount;
let onPageIndex: number = scrollIndex - firstVisibleScrollIndex;
return onPageIndex >= 0 && onPageIndex < this.getVisibleScrollCount(firstVisibleScrollIndex, viewportSize);
}
} | the_stack |
import { useState } from 'react';
import { Story } from '../../../lib/@types/storybook-emotion-10-fixes';
import { asChromaticStory, asPlayground } from '../../../lib/story-intents';
import { ChoiceCard } from './ChoiceCard';
import ChoiceCardStories from './ChoiceCard.stories';
import { ChoiceCardGroup, ChoiceCardGroupProps } from './ChoiceCardGroup';
export default {
title: 'Source/src-choice-card/ChoiceCardGroup',
component: ChoiceCardGroup,
subcomponents: { ChoiceCard },
args: {
name: 'colours',
label: 'Choose an option',
supporting: 'These are your options',
multi: false,
hideLabel: false,
},
argTypes: {
// sorted by required,alpha
name: undefined,
columns: {
options: [undefined, 2, 3, 4, 5],
control: { type: 'select' },
},
error: {
options: [undefined, 'Please select a choice card to continue'],
control: { type: 'select' },
},
label: undefined,
hideLabel: undefined,
multi: undefined,
supporting: undefined,
},
};
const Template: Story<ChoiceCardGroupProps> = (args: ChoiceCardGroupProps) => (
<ChoiceCardGroup {...args}>
{args.children ?? (
<>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc1"
value="option-1"
label="Option 1"
key={1}
/>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc2"
value="option-2"
label="Option 2"
key={2}
/>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc3"
value="option-3"
label="Option 3"
key={3}
/>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc4"
value="option-4"
label="Option 4"
key={4}
/>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc5"
value="option-5"
label="Option 5"
key={5}
/>
<ChoiceCard
{...ChoiceCardStories.args}
id="abc6"
value="option-6"
label="Option 6"
key={6}
/>
</>
)}
</ChoiceCardGroup>
);
// *****************************************************************************
export const Playground = Template.bind({});
asPlayground(Playground);
// *****************************************************************************
export const DefaultDefaultTheme = Template.bind({});
DefaultDefaultTheme.args = {
label: undefined,
supporting: undefined,
};
asChromaticStory(DefaultDefaultTheme);
// *****************************************************************************
export const DefaultMobileDefaultTheme = Template.bind({});
DefaultMobileDefaultTheme.args = {
label: undefined,
supporting: undefined,
};
DefaultMobileDefaultTheme.parameters = {
viewport: { defaultViewport: 'mobileMedium' },
};
asChromaticStory(DefaultMobileDefaultTheme);
// *****************************************************************************
export const DefaultTabletDefaultTheme = Template.bind({});
DefaultTabletDefaultTheme.args = {
label: undefined,
supporting: undefined,
};
DefaultTabletDefaultTheme.parameters = {
viewport: { defaultViewport: 'tablet' },
};
asChromaticStory(DefaultTabletDefaultTheme);
// *****************************************************************************
export const DefaultIn2ColumnsDefaultTheme = Template.bind({});
DefaultIn2ColumnsDefaultTheme.args = {
label: undefined,
supporting: undefined,
columns: 2,
};
asChromaticStory(DefaultIn2ColumnsDefaultTheme);
// *****************************************************************************
export const DefaultIn3ColumnsDefaultTheme = Template.bind({});
DefaultIn3ColumnsDefaultTheme.args = {
label: undefined,
supporting: undefined,
columns: 3,
};
asChromaticStory(DefaultIn3ColumnsDefaultTheme);
// *****************************************************************************
export const DefaultIn4ColumnsDefaultTheme = Template.bind({});
DefaultIn4ColumnsDefaultTheme.args = {
label: undefined,
supporting: undefined,
columns: 4,
};
asChromaticStory(DefaultIn4ColumnsDefaultTheme);
// *****************************************************************************
export const DefaultIn5ColumnsDefaultTheme = Template.bind({});
DefaultIn5ColumnsDefaultTheme.args = {
label: undefined,
supporting: undefined,
columns: 5,
};
asChromaticStory(DefaultIn5ColumnsDefaultTheme);
// *****************************************************************************
export const WithLabelDefaultTheme = Template.bind({});
WithLabelDefaultTheme.args = { supporting: undefined };
asChromaticStory(WithLabelDefaultTheme);
// *****************************************************************************
export const WithSupportingDefaultTheme = Template.bind({});
asChromaticStory(WithSupportingDefaultTheme);
// *****************************************************************************
export const WithErrorDefaultTheme = Template.bind({});
WithErrorDefaultTheme.args = {
error: 'Please select a choice card to continue',
label: undefined,
supporting: undefined,
};
asChromaticStory(WithErrorDefaultTheme);
// *****************************************************************************
export const WithLabelAndErrorDefaultTheme = Template.bind({});
WithLabelAndErrorDefaultTheme.args = {
error: 'Please select a choice card to continue',
supporting: undefined,
};
asChromaticStory(WithLabelAndErrorDefaultTheme);
// *****************************************************************************
export const WithLabelAndSupportingAndErrorDefaultTheme = Template.bind({});
WithLabelAndSupportingAndErrorDefaultTheme.args = {
error: 'Please select a choice card to continue',
};
asChromaticStory(WithLabelAndSupportingAndErrorDefaultTheme);
// *****************************************************************************
export const WithWildlyVaryingLengthsDefaultTheme = Template.bind({});
WithWildlyVaryingLengthsDefaultTheme.args = {
children: [
<ChoiceCard
id="abc1"
value="option-1"
label="A very, very, very, very, very, very, very long piece of text indeed"
key={1}
/>,
<ChoiceCard
id="abc2"
value="option-2"
label="Something probable"
key={2}
/>,
<ChoiceCard id="abc3" value="option-3" label="Short" key={3} />,
],
};
asChromaticStory(WithWildlyVaryingLengthsDefaultTheme);
// *****************************************************************************
export const WithWildlyVaryingLengthsMobileDefaultTheme = Template.bind({});
WithWildlyVaryingLengthsMobileDefaultTheme.args =
WithWildlyVaryingLengthsDefaultTheme.args;
WithWildlyVaryingLengthsMobileDefaultTheme.parameters = {
viewport: { defaultViewport: 'mobile' },
};
asChromaticStory(WithWildlyVaryingLengthsMobileDefaultTheme);
// *****************************************************************************
export const WithWildlyVaryingLengthsTabletDefaultTheme = Template.bind({});
WithWildlyVaryingLengthsTabletDefaultTheme.args =
WithWildlyVaryingLengthsDefaultTheme.args;
WithWildlyVaryingLengthsTabletDefaultTheme.parameters = {
viewport: { defaultViewport: 'tablet' },
};
asChromaticStory(WithWildlyVaryingLengthsTabletDefaultTheme);
// *****************************************************************************
export const ControlledMultiSelectDefaultTheme: Story<ChoiceCardGroupProps> = (
args: ChoiceCardGroupProps,
) => {
const [state, setState] = useState({
opt1: true,
opt2: true,
});
return (
<>
<ChoiceCardGroup {...args}>
<ChoiceCard
id="abc1"
value="option-1"
label="Option 1"
checked={state.opt1}
onChange={() => setState({ ...state, opt1: !state.opt1 })}
/>
<ChoiceCard
id="abc2"
value="option-2"
label="Option 2"
checked={state.opt2}
onChange={() => setState({ ...state, opt2: !state.opt2 })}
/>
</ChoiceCardGroup>
<pre>
Option 1: {state.opt1 ? 'selected' : 'unselected'}
{'\n'}
Option 2: {state.opt2 ? 'selected' : 'unselected'}
</pre>
</>
);
};
ControlledMultiSelectDefaultTheme.args = {
multi: true,
};
asChromaticStory(ControlledMultiSelectDefaultTheme);
// *****************************************************************************
export const ControlledSingleSelectDefaultTheme: Story<ChoiceCardGroupProps> = (
args: ChoiceCardGroupProps,
) => {
const [selected, setSelected] = useState<string | null>('option-2');
return (
<>
<ChoiceCardGroup {...args}>
<ChoiceCard
id="abc1"
value="option-1"
label="Option 1"
checked={selected === 'option-1'}
onChange={() => setSelected('option-1')}
/>
<ChoiceCard
id="abc2"
value="option-2"
label="Option 2"
checked={selected === 'option-2'}
onChange={() => setSelected('option-2')}
/>
</ChoiceCardGroup>
<pre>
Option 1: {selected === 'option-1' ? 'selected' : 'unselected'}
{'\n'}
Option 2: {selected === 'option-2' ? 'selected' : 'unselected'}
</pre>
</>
);
};
ControlledSingleSelectDefaultTheme.args = {
multi: false,
};
asChromaticStory(ControlledSingleSelectDefaultTheme);
// *****************************************************************************
export const UnControlledMultiSelectDefaultTheme: Story<ChoiceCardGroupProps> =
(args: ChoiceCardGroupProps) => (
<ChoiceCardGroup {...args}>
<ChoiceCard
id="abc1"
value="option-1"
label="Option 1"
defaultChecked
/>
<ChoiceCard
id="abc2"
value="option-2"
label="Option 2"
defaultChecked
/>
</ChoiceCardGroup>
);
UnControlledMultiSelectDefaultTheme.args = {
multi: true,
};
UnControlledMultiSelectDefaultTheme.storyName = 'Un-controlled Multi Select';
asChromaticStory(UnControlledMultiSelectDefaultTheme);
// *****************************************************************************
export const UnControlledSingleSelectDefaultTheme: Story<ChoiceCardGroupProps> =
(args: ChoiceCardGroupProps) => (
<ChoiceCardGroup {...args}>
<ChoiceCard id="abc1" value="option-1" label="Option 1" />
<ChoiceCard
id="abc2"
value="option-2"
label="Option 2"
defaultChecked
/>
</ChoiceCardGroup>
);
UnControlledSingleSelectDefaultTheme.args = {
multi: false,
};
UnControlledSingleSelectDefaultTheme.storyName = 'Un-controlled Single Select';
asChromaticStory(UnControlledSingleSelectDefaultTheme); | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as AWS from 'aws-sdk';
import * as deploy_contracts from '../contracts';
import * as deploy_helpers from '../helpers';
import * as deploy_objects from '../objects';
import * as FS from 'fs';
import * as i18 from '../i18';
import * as Moment from 'moment';
interface DeployTargetS3Bucket extends deploy_contracts.TransformableDeployTarget {
acl?: string;
bucket: string;
credentials?: {
config?: any;
type?: string;
},
detectMime?: boolean;
dir?: string;
contentType?: string;
}
interface S3Context {
bucket: string;
connection: AWS.S3;
dir: string;
hasCancelled: boolean;
}
const KNOWN_CREDENTIAL_CLASSES = {
'cognito': AWS.CognitoIdentityCredentials,
'ec2': AWS.ECSCredentials,
'ec2meta': AWS.EC2MetadataCredentials,
'environment': AWS.EnvironmentCredentials,
'file': AWS.FileSystemCredentials,
'saml': AWS.SAMLCredentials,
'shared': AWS.SharedIniFileCredentials,
'temp': AWS.TemporaryCredentials,
'web': AWS.WebIdentityCredentials,
};
class S3BucketPlugin extends deploy_objects.DeployPluginWithContextBase<S3Context> {
public get canGetFileInfo(): boolean {
return true;
}
public get canPull(): boolean {
return true;
}
protected createContext(target: DeployTargetS3Bucket,
files: string[],
opts: deploy_contracts.DeployFileOptions): Promise<deploy_objects.DeployPluginContextWrapper<S3Context>> {
let me = this;
AWS.config.signatureVersion = "v4";
let bucketName = deploy_helpers.toStringSafe(target.bucket)
.trim();
let acl = deploy_helpers.toStringSafe(target.acl);
if (deploy_helpers.isEmptyString(acl)) {
acl = 'public-read';
}
let dir = deploy_helpers.toStringSafe(target.dir).trim();
while ((dir.length > 0) && (0 === dir.indexOf('/'))) {
dir = dir.substr(1).trim();
}
while ((dir.length > 0) && ((dir.length - 1) === dir.lastIndexOf('/'))) {
dir = dir.substr(0, dir.length - 1).trim();
}
dir += '/';
return new Promise<deploy_objects.DeployPluginContextWrapper<S3Context>>((resolve, reject) => {
let completed = (err?: any, wrapper?: deploy_objects.DeployPluginContextWrapper<S3Context>) => {
if (err) {
reject(err);
}
else {
resolve(wrapper);
}
};
// detect credential provider
let credentialClass = AWS.SharedIniFileCredentials;
let credentialConfig: any;
let credentialType: string;
if (target.credentials) {
credentialType = deploy_helpers.toStringSafe(target.credentials.type)
.toLowerCase().trim();
if (!deploy_helpers.isEmptyString(credentialType)) {
credentialClass = KNOWN_CREDENTIAL_CLASSES[credentialType];
}
credentialConfig = target.credentials.config;
}
if (!credentialClass) {
completed(new Error(i18.t('plugins.s3bucket.credentialTypeNotSupported', credentialType)));
return;
}
try {
AWS.config.credentials = new credentialClass(credentialConfig);
let s3bucket = new AWS.S3({
params: {
Bucket: bucketName,
ACL: acl,
}
});
let wrapper: deploy_objects.DeployPluginContextWrapper<S3Context> = {
context: {
bucket: bucketName,
connection: s3bucket,
dir: dir,
hasCancelled: false,
},
};
me.onCancelling(() => wrapper.context.hasCancelled = true, opts);
completed(null, wrapper);
}
catch (e) {
completed(e);
}
});
}
protected deployFileWithContext(ctx: S3Context,
file: string, target: DeployTargetS3Bucket, opts?: deploy_contracts.DeployFileOptions): void {
let me = this;
let completed = (err?: any) => {
if (opts.onCompleted) {
opts.onCompleted(me, {
canceled: ctx.hasCancelled,
error: err,
file: file,
target: target,
});
}
};
if (ctx.hasCancelled) {
completed(); // cancellation requested
}
else {
try {
let relativePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory);
if (false === relativePath) {
completed(new Error(i18.t('relativePaths.couldNotResolve', file)));
return;
}
// remove leading '/' chars
let bucketKey = relativePath;
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
bucketKey = ctx.dir + bucketKey;
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
let contentType = deploy_helpers.normalizeString(target.contentType);
if ('' === contentType) {
// no explicit content type
if (deploy_helpers.toBooleanSafe(target.detectMime, true)) { // detect?
contentType = deploy_helpers.detectMimeByFilename(file);
}
}
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(me, {
destination: bucketKey,
file: file,
target: target,
});
}
FS.readFile(file, (err, data) => {
if (err) {
completed(err);
return;
}
if (ctx.hasCancelled) {
completed();
return;
}
try {
let subCtx = {
file: file,
remoteFile: relativePath,
};
let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform,
subCtx);
tCtx.data = data;
let tResult = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Transform)(tCtx);
Promise.resolve(tResult).then((transformedJsonData) => {
ctx.connection.createBucket(() => {
if (ctx.hasCancelled) {
completed();
return;
}
let params: any = {
Key: bucketKey,
Body: transformedJsonData,
};
if (!deploy_helpers.isEmptyString(contentType)) {
params['ContentType'] = contentType;
}
ctx.connection.putObject(params, (err) => {
completed(err);
});
});
}).catch((e) => {
completed(e);
});
}
catch (e) {
completed(e);
}
});
}
catch (e) {
completed(e);
}
}
}
protected downloadFileWithContext(ctx: S3Context,
file: string, target: DeployTargetS3Bucket, opts?: deploy_contracts.DeployFileOptions): Promise<Buffer> {
let me = this;
return new Promise<Buffer>((resolve, reject) => {
let completed = (err: any, data?: Buffer) => {
if (opts.onCompleted) {
opts.onCompleted(me, {
canceled: ctx.hasCancelled,
error: err,
file: file,
target: target,
});
}
if (err) {
reject(err);
}
else {
resolve(data);
}
};
if (ctx.hasCancelled) {
completed(null); // cancellation requested
}
else {
try {
let relativePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory);
if (false === relativePath) {
completed(new Error(i18.t('relativePaths.couldNotResolve', file)));
return;
}
// remove leading '/' chars
let bucketKey = relativePath;
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
if (opts.onBeforeDeploy) {
opts.onBeforeDeploy(me, {
destination: bucketKey,
file: file,
target: target,
});
}
let params: any = {
Key: bucketKey,
};
ctx.connection.getObject(params, (err, data) => {
if (err) {
completed(err);
}
else {
try {
let subCtx = {
file: file,
remoteFile: relativePath,
};
let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Restore,
subCtx);
tCtx.data = <any>data.Body;
let tResult = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Restore)(tCtx);
Promise.resolve(tResult).then((untransformedJsonData) => {
completed(null, untransformedJsonData);
}).catch((e) => {
completed(e);
});
}
catch (e) {
completed(e);
}
}
});
}
catch (e) {
completed(e);
}
}
});
}
protected getFileInfoWithContext(ctx: S3Context,
file: string, target: DeployTargetS3Bucket, opts?: deploy_contracts.DeployFileOptions): Promise<deploy_contracts.FileInfo> {
let me = this;
return new Promise<deploy_contracts.FileInfo>((resolve, reject) => {
let completed = (err: any, data?: deploy_contracts.FileInfo) => {
if (err) {
reject(err);
}
else {
resolve(data);
}
};
try {
let relativePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory);
if (false === relativePath) {
completed(new Error(i18.t('relativePaths.couldNotResolve', file)));
return;
}
// remove leading '/' chars
let bucketKey = relativePath;
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
while (0 === bucketKey.indexOf('/')) {
bucketKey = bucketKey.substr(1);
}
let params: any = {
Key: bucketKey,
};
ctx.connection.getObject(params, (err, data) => {
let result: deploy_contracts.FileInfo = {
exists: false,
isRemote: true,
};
if (!err && data) {
result.exists = true;
result.size = data.ContentLength;
result.name = target.bucket;
result.path = bucketKey;
if (data.LastModified) {
try {
result.modifyTime = Moment(data.LastModified);
}
catch (e) {
//TODO: log
}
}
}
completed(null, result);
});
}
catch (e) {
completed(e);
}
});
}
public info(): deploy_contracts.DeployPluginInfo {
return {
description: i18.t('plugins.s3bucket.description'),
};
}
}
/**
* Creates a new Plugin.
*
* @param {deploy_contracts.DeployContext} ctx The deploy context.
*
* @returns {deploy_contracts.DeployPlugin} The new instance.
*/
export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin {
return new S3BucketPlugin(ctx);
} | the_stack |
import path from "path";
import fs from "fs";
import { Logger } from "@nestjs/common";
import { v5 as uuid } from "uuid";
import { JSDOM } from "jsdom";
import { SubmissionEntity } from "@/submission/submission.entity";
import { ProblemType } from "@/problem/problem.entity";
import { SubmissionStatus } from "@/submission/submission-status.enum";
import { SubmissionDetailEntity } from "@/submission/submission-detail.entity";
import { ConfigService } from "@/config/config.service";
import { FileEntity } from "@/file/file.entity";
import { SubmissionProgressType } from "@/submission/submission-progress.interface";
import {
SubmissionTestcaseResultTraditional,
SubmissionTestcaseStatusTraditional
} from "@/problem-type/types/traditional/submission-testcase-result.interface";
import {
SubmissionTestcaseResultInteraction,
SubmissionTestcaseStatusInteraction
} from "@/problem-type/types/interaction/submission-testcase-result.interface";
import {
SubmissionTestcaseResultSubmitAnswer,
SubmissionTestcaseStatusSubmitAnswer
} from "@/problem-type/types/submit-answer/submission-testcase-result.interface";
import { SubmissionContentTraditional } from "@/problem-type/types/traditional/submission-content.interface";
import { SubmissionResultOmittableString } from "@/submission/submission-testcase-result-omittable-string.interface";
import { getLanguageAndOptions, parseProblemType } from "./problem";
import { OldDatabaseJudgeStateEntity } from "./old-database.interface";
import { MigrationInterface } from "./migration.interface";
import { FileService } from "@/file/file.service";
enum OldSubmissionTestcaseResultType {
Accepted = 1,
WrongAnswer = 2,
PartiallyCorrect = 3,
MemoryLimitExceeded = 4,
TimeLimitExceeded = 5,
OutputLimitExceeded = 6,
FileError = 7, // The output file does not exist
RuntimeError = 8,
JudgementFailed = 9, // Special Judge or Interactor fails
InvalidInteraction = 10
}
interface OldSubmissionTestcaseFileContent {
content: string;
name: string;
}
interface OldSubmissionResult {
systemMessage?: string; // System Error
compile: {
/**
* 2: success, 3: fail
*/
status: number;
message?: string;
};
judge?: {
subtasks?: {
score?: number;
cases: {
status: number; // 2 OK, 4 skipped
result?: {
type: OldSubmissionTestcaseResultType;
time: number;
memory: number;
input?: OldSubmissionTestcaseFileContent;
output?: OldSubmissionTestcaseFileContent; // Output in test data
scoringRate: number; // e.g. 0.5
userOutput?: string;
userError?: string;
spjMessage?: string;
systemMessage?: string;
};
}[];
}[];
};
}
function convertSubmissionStatus(oldStatus: OldDatabaseJudgeStateEntity["status"]): SubmissionStatus {
switch (oldStatus) {
case "Accepted":
return SubmissionStatus.Accepted;
case "Compile Error":
return SubmissionStatus.CompilationError;
case "File Error":
return SubmissionStatus.FileError;
case "Judgement Failed":
return SubmissionStatus.JudgementFailed;
case "Memory Limit Exceeded":
return SubmissionStatus.MemoryLimitExceeded;
case "No Testdata":
return SubmissionStatus.ConfigurationError;
case "Output Limit Exceeded":
return SubmissionStatus.OutputLimitExceeded;
case "Partially Correct":
return SubmissionStatus.PartiallyCorrect;
case "Runtime Error":
return SubmissionStatus.RuntimeError;
case "System Error":
return SubmissionStatus.SystemError;
case "Time Limit Exceeded":
return SubmissionStatus.TimeLimitExceeded;
case "Unknown":
return SubmissionStatus.SystemError;
case "Waiting":
return SubmissionStatus.Pending;
case "Wrong Answer":
case "Invalid Interaction":
return SubmissionStatus.WrongAnswer;
default:
Logger.error(`Unknown submission status "${oldStatus}"`);
return SubmissionStatus.SystemError;
}
}
function convertTestcaseStatus(
oldStatus: OldSubmissionTestcaseResultType
): SubmissionTestcaseStatusTraditional | SubmissionTestcaseStatusInteraction | SubmissionTestcaseStatusSubmitAnswer {
switch (oldStatus) {
case OldSubmissionTestcaseResultType.Accepted:
return SubmissionTestcaseStatusTraditional.Accepted;
case OldSubmissionTestcaseResultType.FileError:
return SubmissionTestcaseStatusTraditional.FileError;
case OldSubmissionTestcaseResultType.JudgementFailed:
return SubmissionTestcaseStatusTraditional.JudgementFailed;
case OldSubmissionTestcaseResultType.MemoryLimitExceeded:
return SubmissionTestcaseStatusTraditional.MemoryLimitExceeded;
case OldSubmissionTestcaseResultType.OutputLimitExceeded:
return SubmissionTestcaseStatusTraditional.OutputLimitExceeded;
case OldSubmissionTestcaseResultType.PartiallyCorrect:
return SubmissionTestcaseStatusTraditional.PartiallyCorrect;
case OldSubmissionTestcaseResultType.RuntimeError:
return SubmissionTestcaseStatusTraditional.RuntimeError;
case OldSubmissionTestcaseResultType.TimeLimitExceeded:
return SubmissionTestcaseStatusTraditional.TimeLimitExceeded;
case OldSubmissionTestcaseResultType.InvalidInteraction:
case OldSubmissionTestcaseResultType.WrongAnswer:
return SubmissionTestcaseStatusTraditional.WrongAnswer;
default:
return SubmissionTestcaseStatusTraditional.SystemError;
}
}
function uuidFromSubmission(submissionId: number) {
const NAMESPACE = "c03eb380-e0a7-43f1-b276-9250f23663ee";
return uuid(`${submissionId}`, NAMESPACE);
}
const omittedRegex = /\n<(\d+) bytes? omitted>$/;
function parseOmittedString(data: string): SubmissionResultOmittableString {
data = data || "";
const result = data.match(omittedRegex);
if (!result) return data;
return {
data: data.replace(omittedRegex, ""),
omittedLength: Number(result[1])
};
}
function getOmittedStringLength(data: SubmissionResultOmittableString) {
return typeof data === "string" ? data.length : data.data.length + data.omittedLength;
}
const ansiColorStrings = {
"#000": 0,
"#A00": 1,
"#0A0": 2,
"#A50": 3,
"#00A": 4,
"#A0A": 5,
"#0AA": 6,
"#AAA": 7
};
function htmlToAnsi(html: string) {
const { window } = new JSDOM(html);
const { body } = window.document;
let result = "";
function printAnsi(code: number) {
result += `\x1B[${String(code)}m`;
}
let currentBold = false;
let currentColor = -1;
function dfs(node: ChildNode, bold = false, color = -1) {
if (node.nodeType === node.TEXT_NODE) {
// Change style
if (currentBold !== bold || currentColor !== color) {
// Cancel bold or color
if ((currentBold !== bold && !bold) || (currentColor !== color && color === -1)) {
// Reset ALL
printAnsi(0);
currentBold = false;
currentColor = -1;
}
// Bold
if (bold !== currentBold) {
printAnsi(1);
currentBold = bold;
}
// Color
if (color !== currentColor) {
printAnsi(30 + color);
currentColor = color;
}
}
result += node.nodeValue;
}
let nextBold = bold;
let nextColor = color;
if (node.nodeType === node.ELEMENT_NODE) {
const element = node as HTMLElement;
if (element.tagName === "B") {
nextBold = true;
} else if (element.tagName === "SPAN") {
const style = element.getAttribute("style");
const colorStringPrefix = "color:";
if (style.startsWith(colorStringPrefix)) {
const colorString = style.substr(colorStringPrefix.length);
if (colorString in ansiColorStrings) nextColor = ansiColorStrings[colorString];
}
}
}
if (node.childNodes.length) {
for (const childNode of node.childNodes) {
dfs(childNode, nextBold, nextColor);
}
}
}
dfs(body);
return result;
}
export const migrationSubmission: MigrationInterface = {
async migrate(entityManager, config, oldDatabase, queryTablePaged, app) {
const configService = app.get(ConfigService);
const fileService = app.get(FileService);
const problemInfoMap: Record<
number,
{
type: ProblemType;
timeLimit: number;
memoryLimit: number;
}
> = {};
for (const problem of await oldDatabase.query("SELECT `id`, `type`, `time_limit`, `memory_limit` FROM `problem`"))
problemInfoMap[problem.id] = {
type: parseProblemType(problem.type),
timeLimit: problem.time_limit,
memoryLimit: problem.memory_limit
};
await queryTablePaged<OldDatabaseJudgeStateEntity>(
"judge_state",
"id",
async oldSubmission => {
const problemInfo = problemInfoMap[oldSubmission.problem_id];
if (!problemInfo) {
Logger.error(
`Problem #${oldSubmission.problem_id} referenced by submission #${oldSubmission.id} doesn't exist`
);
return;
}
const isSubmitAnswer = problemInfo.type === ProblemType.SubmitAnswer;
const languageAndOptions =
!isSubmitAnswer && getLanguageAndOptions(oldSubmission.language, `submission ${oldSubmission.id}`, false);
if (!isSubmitAnswer && !languageAndOptions) {
Logger.error(`Unsupported language "${oldSubmission.language}", ignoring submission #${oldSubmission.id}`);
return;
}
const submission = new SubmissionEntity();
submission.id = oldSubmission.id;
submission.taskId = null;
submission.isPublic = !!oldSubmission.is_public;
submission.codeLanguage = languageAndOptions?.language;
submission.answerSize = isSubmitAnswer
? oldSubmission.code_length
: Buffer.byteLength(oldSubmission.code, "utf-8");
submission.score = Math.max(0, Math.min(oldSubmission.score, 100));
submission.status = convertSubmissionStatus(oldSubmission.status);
submission.submitTime = new Date(oldSubmission.submit_time * 1000);
submission.problemId = oldSubmission.problem_id;
submission.submitterId = oldSubmission.user_id;
const submissionDetail = new SubmissionDetailEntity();
submissionDetail.submissionId = submission.id;
if (isSubmitAnswer) {
submissionDetail.content = {};
try {
const answerFilePath = path.join(config.uploads, "answer", oldSubmission.code);
const stat = await fs.promises.stat(answerFilePath);
const fileUuid = uuidFromSubmission(oldSubmission.id);
// Find existing record in new database first to continue a failed migration
const fileEntity = (await entityManager.findOne(FileEntity, { uuid: fileUuid })) || new FileEntity();
if (!fileEntity.uuid) {
fileEntity.size = stat.size;
fileEntity.uploadTime = new Date();
fileEntity.uuid = uuidFromSubmission(oldSubmission.id);
if (!(await fileService.fileExistsInMinio(fileEntity.uuid)))
await fileService.uploadFile(fileEntity.uuid, answerFilePath);
await entityManager.save(fileEntity);
}
submissionDetail.fileUuid = fileEntity.uuid;
submission.answerSize = stat.size;
} catch (e) {
Logger.warn(`Failed to migrate submit answer submission #${oldSubmission.id}'s answer file, ${e}`);
submissionDetail.fileUuid = null;
}
} else {
submissionDetail.content = <SubmissionContentTraditional>{
language: languageAndOptions.language,
code: oldSubmission.code,
compileAndRunOptions: languageAndOptions.compileAndRunOptions,
skipSamples: true
};
}
submissionDetail.result =
submission.status === SubmissionStatus.Pending ? null : { progressType: SubmissionProgressType.Finished };
const { result } = submissionDetail;
if (result) {
try {
const oldResult: OldSubmissionResult = JSON.parse(oldSubmission.result);
if (oldResult.systemMessage) result.systemMessage = parseOmittedString(oldResult.systemMessage);
result.score = submission.score;
result.status = submission.status;
if (oldResult.compile) {
let oldCompileMessage = oldResult.compile.message || "";
// Replace confusing error message
const matchResult = /Your source code compiled to (\d+) bytes which is too big, too thick, too long for us\.\./.exec(
oldCompileMessage
);
if (matchResult) {
oldCompileMessage = `The source code compiled to ${matchResult[1]} bytes, exceeding the size limit.`;
}
const notConvertedRegex = /^A [a-zA-Z]+ encountered while compiling your code./;
const notConverted = notConvertedRegex.test(oldCompileMessage);
result.compile = {
compileTaskHash: null,
success: oldResult.compile.status === 2,
message: parseOmittedString(notConverted ? oldCompileMessage : htmlToAnsi(oldCompileMessage))
};
}
result.subtasks = [];
result.testcaseResult = {};
let i = 0;
for (const oldSubtask of oldResult.judge?.subtasks || []) {
result.subtasks.push({
score: oldSubtask.score || 0,
fullScore: Math.max(1, oldSubtask.score || 0),
testcases: []
});
for (const oldCase of oldSubtask.cases) {
const pseudoHash = `migrated_case_${++i}`;
const oldCaseResult = oldCase.result;
if (oldCase.status === 4) {
result.subtasks[result.subtasks.length - 1].testcases.push({});
continue;
}
result.subtasks[result.subtasks.length - 1].testcases.push({
testcaseHash: pseudoHash
});
if (problemInfo.type === ProblemType.Traditional) {
result.testcaseResult[pseudoHash] = <SubmissionTestcaseResultTraditional>{
testcaseInfo: {
timeLimit: problemInfo.timeLimit,
memoryLimit: problemInfo.memoryLimit,
inputFile: oldCaseResult.input?.name,
outputFile: oldCaseResult.output?.name
},
status: convertTestcaseStatus(oldCaseResult.type),
score: Math.round(oldCaseResult.scoringRate * 100),
time: oldCaseResult.time,
memory: oldCaseResult.memory,
input: parseOmittedString(oldCaseResult.input?.content || ""),
output: parseOmittedString(oldCaseResult.output?.content || ""),
userOutput: parseOmittedString(oldCaseResult.userOutput || ""),
userError: parseOmittedString(oldCaseResult.userError || ""),
checkerMessage: parseOmittedString(oldCaseResult.spjMessage),
systemMessage: parseOmittedString(oldCaseResult.systemMessage)
};
} else if (problemInfo.type === ProblemType.Interaction) {
result.testcaseResult[pseudoHash] = <SubmissionTestcaseResultInteraction>{
testcaseInfo: {
timeLimit: problemInfo.timeLimit,
memoryLimit: problemInfo.memoryLimit,
inputFile: oldCaseResult.input?.name
},
status: convertTestcaseStatus(oldCaseResult.type),
score: Math.round(oldCaseResult.scoringRate * 100),
time: oldCaseResult.time,
memory: oldCaseResult.memory,
input: parseOmittedString(oldCaseResult.input?.content || ""),
userError: parseOmittedString(oldCaseResult.userError || ""),
interactorMessage: parseOmittedString(oldCaseResult.spjMessage),
systemMessage: parseOmittedString(oldCaseResult.systemMessage)
};
} else if (problemInfo.type === ProblemType.SubmitAnswer) {
result.testcaseResult[pseudoHash] = <SubmissionTestcaseResultSubmitAnswer>{
testcaseInfo: {
inputFile: oldCaseResult.input?.name,
outputFile: oldCaseResult.output?.name
},
status: convertTestcaseStatus(oldCaseResult.type),
score: Math.round(oldCaseResult.scoringRate * 100),
input: parseOmittedString(oldCaseResult.input?.content || ""),
output: parseOmittedString(oldCaseResult.output?.content || ""),
userOutput: parseOmittedString(oldCaseResult.userOutput || ""),
userOutputLength: getOmittedStringLength(parseOmittedString(oldCaseResult.userOutput || "")),
checkerMessage: parseOmittedString(oldCaseResult.spjMessage),
systemMessage: parseOmittedString(oldCaseResult.systemMessage)
};
}
}
}
} catch (e) {
Logger.warn(`Failed to migrate result for submission #${oldSubmission.id}, ${e}`);
submissionDetail.result = null;
}
}
if (
!isSubmitAnswer &&
![
SubmissionStatus.CompilationError,
SubmissionStatus.ConfigurationError,
SubmissionStatus.Pending,
SubmissionStatus.SystemError
].includes(submission.status)
) {
submission.timeUsed = oldSubmission.total_time;
submission.memoryUsed = oldSubmission.max_memory;
}
await entityManager.save(submission);
submissionDetail.submissionId = submission.id;
await entityManager.save(submissionDetail);
},
10000
);
Logger.log("Calculating submission count of users and problems");
await Promise.all([
entityManager.query(
"UPDATE `user` SET `submissionCount` = (SELECT COUNT(*) FROM `submission` WHERE `submitterId` = `user`.`id`), `acceptedProblemCount` = (SELECT COUNT(DISTINCT `problemId`) FROM `submission` WHERE `submitterId` = `user`.`id` AND `status` = 'Accepted')"
),
entityManager.query(
"UPDATE `problem` SET `submissionCount` = (SELECT COUNT(*) FROM `submission` WHERE `problemId` = `problem`.`id`), `acceptedSubmissionCount` = (SELECT COUNT(*) FROM `submission` WHERE `problemId` = `problem`.`id` AND `status` = 'Accepted')"
)
]);
}
}; | the_stack |
import { assert } from 'chai'
import { Wallet, WalletFactory, XrplNetwork, XrpUtils } from 'xpring-common-js'
import XrpError from '../../src/XRP/shared/xrp-error'
import IssuedCurrencyClient from '../../src/XRP/issued-currency-client'
import XRPTestUtils from './helpers/xrp-test-utils'
import {
AccountRootFlag,
TransactionStatus,
XrpErrorType,
} from '../../src/XRP/shared'
import { TransactionResponse } from '../../src/XRP/shared/rippled-web-socket-schema'
import XrpClient from '../../src/XRP/xrp-client'
import IssuedCurrency from '../../src/XRP/shared/issued-currency'
// A timeout for these tests.
// eslint-disable-next-line @typescript-eslint/no-magic-numbers -- 1 minute in milliseconds
const timeoutMs = 60 * 1000
// An IssuedCurrencyClient that makes requests.
const rippledGrpcUrl = 'test.xrp.xpring.io:50051'
const rippledWebSocketUrl = 'wss://wss.test.xrp.xpring.io'
const issuedCurrencyClient = IssuedCurrencyClient.issuedCurrencyClientWithEndpoint(
rippledGrpcUrl,
rippledWebSocketUrl,
console.log,
XrplNetwork.Test,
)
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
describe('IssuedCurrencyClient Integration Tests', function (): void {
// Retry integration tests on failure.
this.retries(3)
// Some testnet wallets with invariant properties.
let walletMightHaveTrustLines: Wallet
let walletNeverAnyTrustLines: Wallet
let issuerWallet: Wallet
let issuerWalletAuthTrustLines: Wallet
before(async function () {
this.timeout(timeoutMs)
const walletPromise1 = XRPTestUtils.randomWalletFromFaucet().then(
(wallet) => {
walletMightHaveTrustLines = wallet
},
)
const walletPromise2 = XRPTestUtils.randomWalletFromFaucet().then(
(wallet) => {
walletNeverAnyTrustLines = wallet
},
)
const walletPromise3 = XRPTestUtils.randomWalletFromFaucet().then(
(wallet) => {
issuerWallet = wallet
},
)
const walletPromise4 = XRPTestUtils.randomWalletFromFaucet().then(
(wallet) => {
issuerWalletAuthTrustLines = wallet
},
)
await Promise.all([
walletPromise1,
walletPromise2,
walletPromise3,
walletPromise4,
])
})
after(function (done) {
issuedCurrencyClient.webSocketNetworkClient.close()
done()
})
it('getTrustLines - valid request', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a testnet wallet that has created at least one trustline
await issuedCurrencyClient.createTrustLine(
issuerWallet.getAddress(),
'FOO',
'100',
walletMightHaveTrustLines,
)
// WHEN getTrustLines is called for that address
const trustLines = await issuedCurrencyClient.getTrustLines(
walletMightHaveTrustLines.getAddress(),
)
// THEN there are trustlines in the response.
assert.exists(trustLines)
assert.isTrue(trustLines.length > 0)
})
// TODO: (amiecorso) implement an integration test that includes the peerAccount param when we have control over establishing
// specific trustlines. Can't otherwise verify correctness.
it('getTrustLines - account not found', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a valid address that doesn't actually exist on the ledger
const walletFactory = new WalletFactory(XrplNetwork.Test)
const address = (await walletFactory.generateRandomWallet())!.wallet.getAddress()
// WHEN getTrustLines is called for that address THEN an error is propagated.
issuedCurrencyClient.getTrustLines(address).catch((error) => {
assert.typeOf(error, 'Error')
assert.equal(error, XrpError.accountNotFound)
})
})
it('getTrustLines - account with no trust lines', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a valid, funded address that doesn't have any trustlines
// WHEN getTrustLines is called for that addres
const trustLines = await issuedCurrencyClient.getTrustLines(
walletNeverAnyTrustLines.getAddress(),
)
// THEN the result is an empty array.
assert.isArray(trustLines)
assert.isEmpty(trustLines)
})
it('requireAuthorizedTrustlines/allowUnauthorizedTrustlines - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN requireAuthorizedTrustlines is called
const result = await issuedCurrencyClient.requireAuthorizedTrustlines(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_REQUIRE_AUTH,
)
// GIVEN an existing testnet account with Require Authorization enabled
// WHEN allowUnauthorizedTrustlines is called
const result2 = await issuedCurrencyClient.allowUnauthorizedTrustlines(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was unset on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result2,
AccountRootFlag.LSF_REQUIRE_AUTH,
false,
)
})
it('enableRippling - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN enableRippling is called
const result = await issuedCurrencyClient.enableRippling(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_DEFAULT_RIPPLE,
)
})
it('disallowIncomingXrp/allowIncomingXrp - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN disallowIncomingXrp is called
const result = await issuedCurrencyClient.disallowIncomingXrp(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_DISALLOW_XRP,
)
// GIVEN an existing testnet account with Disallow XRP enabled
// WHEN allowIncomingXrp is called
const result2 = await issuedCurrencyClient.allowIncomingXrp(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the flag should not be set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result2,
AccountRootFlag.LSF_DISALLOW_XRP,
false,
)
})
// TODO: Once required IOU functionality exists in SDK, add integration tests that successfully establish an unauthorized trustline to this account.
it('requireDestinationTags/allowNoDestinationTag - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN requireDestinationTags is called
const result = await issuedCurrencyClient.requireDestinationTags(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_REQUIRE_DEST_TAG,
)
// GIVEN an existing testnet account with Require Destination Tags enabled
// WHEN allowNoDestinationTag is called
const result2 = await issuedCurrencyClient.allowNoDestinationTag(
walletNeverAnyTrustLines,
)
// THEN both transactions were successfully submitted and there should be no flag set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result2,
AccountRootFlag.LSF_REQUIRE_DEST_TAG,
false,
)
})
it('requireDestinationTags/allowNoDestinationTag - transaction without destination tags', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account with requireDestinationTags set
await issuedCurrencyClient.requireDestinationTags(walletNeverAnyTrustLines)
// WHEN a transaction is sent to the account without a destination tag
const xrpClient = new XrpClient(rippledGrpcUrl, XrplNetwork.Test)
const xrpAmount = '100'
const transactionResult = await xrpClient.sendXrp(
xrpAmount,
walletNeverAnyTrustLines.getAddress(),
walletMightHaveTrustLines,
)
// THEN the transaction fails.
assert.exists(transactionResult.hash)
assert.equal(transactionResult.status, TransactionStatus.ClaimedCostOnly)
// GIVEN an existing testnet account with requireDestinationTags unset
await issuedCurrencyClient.allowNoDestinationTag(walletNeverAnyTrustLines)
// WHEN a transaction is sent to the account without a destination tag
const transactionResult2 = await xrpClient.sendXrp(
xrpAmount,
walletNeverAnyTrustLines.getAddress(),
walletMightHaveTrustLines,
)
// THEN the transaction succeeds.
assert.exists(transactionResult2.hash)
assert.equal(transactionResult2.status, TransactionStatus.Succeeded)
})
// TODO: when SDK functionality is expanded, improve test specificity by creating trustlines/issued currencies first,
// which will also avoid the need for maintenance after a testnet reset.
// TODO: Implement an integration test for an account with balances/assets/obligations once functionality exists for first creating things.
it('getGatewayBalances - account not found', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a valid address that doesn't actually exist on the ledger
const walletFactory = new WalletFactory(XrplNetwork.Test)
const address = (await walletFactory.generateRandomWallet())!.wallet.getAddress()
// WHEN getGatewayBalances is called for that address THEN an error is propagated.
issuedCurrencyClient.getGatewayBalances(address).catch((error) => {
assert.typeOf(error, 'Error')
assert.equal(error, XrpError.accountNotFound)
})
})
it('getGatewayBalances - account with no issued currencies', async function (): Promise<void> {
// GIVEN a valid, funded address that has not issued any currencies
const address = walletNeverAnyTrustLines.getAddress()
// WHEN getGatewayBalances is called for that address
const gatewayBalances = await issuedCurrencyClient.getGatewayBalances(
address,
)
// THEN the result is as expected.
assert.equal(gatewayBalances.account, address)
assert.isUndefined(gatewayBalances.assets)
assert.isUndefined(gatewayBalances.balances)
assert.isUndefined(gatewayBalances.obligations)
})
it('getTransferFee/setTransferFee - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN setTransferFee is called
const expectedTransferFee = 1000000123
const result = await issuedCurrencyClient.setTransferFee(
expectedTransferFee,
walletMightHaveTrustLines,
)
const transactionHash = result.hash
const transactionStatus = result.status
const transferRate = await issuedCurrencyClient.getTransferFee(
walletMightHaveTrustLines.getAddress(),
)
// THEN the transaction was successfully submitted and the correct transfer rate was set on the account.
assert.exists(transactionHash)
assert.equal(transactionStatus, TransactionStatus.Succeeded)
assert.equal(transferRate, expectedTransferFee)
})
it('setTransferFee - bad transferRate values', async function (): Promise<void> {
this.timeout(timeoutMs)
const lowTransferFee = 12345
const highTransferFee = 3000001234
// GIVEN an existing testnet account
// WHEN setTransferFee is called on a too-low transfer fee
const result = await issuedCurrencyClient.setTransferFee(
lowTransferFee,
walletMightHaveTrustLines,
)
const transactionHash = result.hash
const transactionStatus = result.status
// THEN the transaction fails.
assert.exists(transactionHash)
assert.equal(transactionStatus, TransactionStatus.MalformedTransaction)
// GIVEN an existing testnet account
// WHEN setTransferFee is called on a too-high transfer fee
const result2 = await issuedCurrencyClient.setTransferFee(
highTransferFee,
walletMightHaveTrustLines,
)
const transactionHash2 = result2.hash
const transactionStatus2 = result2.status
// THEN the transaction fails.
assert.exists(transactionHash2)
assert.equal(transactionStatus2, TransactionStatus.MalformedTransaction)
})
it('enableGlobalFreeze/disableGlobalFreeze - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN enableGlobalFreeze is called
const result = await issuedCurrencyClient.enableGlobalFreeze(
walletMightHaveTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletMightHaveTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_GLOBAL_FREEZE,
)
// GIVEN an existing testnet account with Global Freeze enabled
// WHEN disableGlobalFreeze is called
const result2 = await issuedCurrencyClient.disableGlobalFreeze(
walletMightHaveTrustLines,
)
// THEN both transactions were successfully submitted and there should be no flag set on the account.
await XRPTestUtils.verifyFlagModification(
walletMightHaveTrustLines,
rippledGrpcUrl,
result2,
AccountRootFlag.LSF_GLOBAL_FREEZE,
false,
)
})
it('enableNoFreeze - rippled', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account
// WHEN enableNoFreeze is called
const result = await issuedCurrencyClient.enableNoFreeze(
walletNeverAnyTrustLines,
)
// THEN the transaction was successfully submitted and the correct flag was set on the account.
await XRPTestUtils.verifyFlagModification(
walletNeverAnyTrustLines,
rippledGrpcUrl,
result,
AccountRootFlag.LSF_NO_FREEZE,
)
})
it('createTrustLine - creating a trustline with XRP', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account and an issuer's wallet
// WHEN a trust line is created with the issuer with a value of 0
try {
await issuedCurrencyClient.createTrustLine(
issuerWallet.getAddress(),
'XRP',
'0',
walletMightHaveTrustLines,
)
} catch (error) {
// THEN an error is thrown.
assert.equal(error.errorType, XrpErrorType.InvalidInput)
}
})
it('createTrustLine - adding a trustline with 0 value', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account and an issuer's wallet
const freshWallet = await XRPTestUtils.randomWalletFromFaucet()
// WHEN a trust line is created with the issuer with a value of 0
await issuedCurrencyClient.createTrustLine(
issuerWallet.getAddress(),
'USD',
'0',
freshWallet,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
freshWallet.getAddress(),
)
// THEN no trustlines were created.
assert.isArray(trustLines)
assert.isEmpty(trustLines)
})
it('createTrustLine - adding a trustline with non-zero value', async function (): Promise<void> {
this.timeout(timeoutMs)
const freshWallet = await XRPTestUtils.randomWalletFromFaucet()
const trustLineLimit = '1'
const trustLineCurrency = 'USD'
// GIVEN an existing testnet account and an issuer's wallet
// WHEN a trustline is created with the issuer with a positive value
await issuedCurrencyClient.createTrustLine(
issuerWallet.getAddress(),
trustLineCurrency,
trustLineLimit,
freshWallet,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
freshWallet.getAddress(),
)
const [createdTrustLine] = trustLines
const classicAddress = XrpUtils.decodeXAddress(issuerWallet.getAddress())!
// THEN a trust line was created with the issuing account.
assert.equal(createdTrustLine.account, classicAddress.address)
assert.equal(createdTrustLine.limit, trustLineLimit)
assert.equal(createdTrustLine.currency, trustLineCurrency)
})
it('createTrustLine - adding a trustline with non-zero value and qualityIn + qualityOut', async function (): Promise<void> {
this.timeout(timeoutMs)
const trustLineLimit = '1'
const trustLineCurrency = 'USD'
const qualityInAmount = 20
const qualityOutAmount = 100
// GIVEN an existing testnet account and an issuer's wallet
const freshWallet = await XRPTestUtils.randomWalletFromFaucet()
// WHEN a trustline is created with the issuer with a positive value
await issuedCurrencyClient.createTrustLine(
issuerWallet.getAddress(),
trustLineCurrency,
trustLineLimit,
freshWallet,
qualityInAmount,
qualityOutAmount,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
freshWallet.getAddress(),
)
const [createdTrustLine] = trustLines
const classicAddress = XrpUtils.decodeXAddress(issuerWallet.getAddress())!
// THEN a trust line was created with the issuing account.
assert.equal(createdTrustLine.account, classicAddress.address)
assert.equal(createdTrustLine.limit, trustLineLimit)
assert.equal(createdTrustLine.currency, trustLineCurrency)
assert.equal(createdTrustLine.qualityIn, qualityInAmount)
assert.equal(createdTrustLine.qualityOut, qualityOutAmount)
})
it('authorizeTrustLine - valid account', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing testnet account requiring authorized trust lines
// and another account
const accountToTrust = await XRPTestUtils.randomWalletFromFaucet()
await issuedCurrencyClient.requireAuthorizedTrustlines(
issuerWalletAuthTrustLines,
)
const trustLineCurrency = 'USD'
// WHEN a trust line is authorized with another account
await issuedCurrencyClient.authorizeTrustLine(
accountToTrust.getAddress(),
'USD',
issuerWalletAuthTrustLines,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
issuerWalletAuthTrustLines.getAddress(),
)
const [createdTrustLine] = trustLines
const classicAddress = XrpUtils.decodeXAddress(accountToTrust.getAddress())!
// THEN an authorized trust line is created between the wallet and the other account.
assert.equal(createdTrustLine.account, classicAddress.address)
assert.equal(createdTrustLine.limit, '0')
assert.equal(createdTrustLine.currency, trustLineCurrency)
assert.isTrue(createdTrustLine.authorized)
})
it('freezeTrustLine', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing issuer account who has a trustline with a counter-party
const trustLineCurrency = 'NEW'
await issuedCurrencyClient.authorizeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
// WHEN the issuer freezes the trustline
await issuedCurrencyClient.freezeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
issuerWalletAuthTrustLines.getAddress(),
)
const frozenTrustLine = trustLines.find(
(trustLine) => trustLine.currency === trustLineCurrency,
)!
// THEN the trust line is frozen.
assert.equal(frozenTrustLine.freeze, true)
assert.equal(frozenTrustLine.limit, '0')
})
it('unfreezeTrustLine - unfreezes frozen account', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing issuer account who has a frozen trust line with a counter-party
const trustLineCurrency = 'FRZ'
await issuedCurrencyClient.authorizeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
await issuedCurrencyClient.freezeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
// WHEN the issuer unfreezes the trustline
await issuedCurrencyClient.unfreezeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
const trustLines = await issuedCurrencyClient.getTrustLines(
issuerWalletAuthTrustLines.getAddress(),
)
const unfrozenTrustLine = trustLines.find(
(trustLine) => trustLine.currency === trustLineCurrency,
)!
// THEN the trust line is not frozen.
assert.equal(unfrozenTrustLine.freeze, false)
assert.equal(unfrozenTrustLine.limit, '0')
})
it('disableRipplingForTrustLine/enableRipplingForTrustLine', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN an existing issuer account who has a trust line with a counter-party
const trustLineCurrency = 'NRP'
await issuedCurrencyClient.authorizeTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
issuerWalletAuthTrustLines,
)
const trustLineAmount = '1'
// WHEN the issuer sets no rippling on the trust line
await issuedCurrencyClient.disableRipplingForTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
trustLineAmount,
issuerWalletAuthTrustLines,
)
let trustLines = await issuedCurrencyClient.getTrustLines(
issuerWalletAuthTrustLines.getAddress(),
)
const noRippleTrustLine = trustLines.find(
(trustLine) => trustLine.currency === trustLineCurrency,
)!
// THEN the trust line has noRipple enabled.
assert.equal(noRippleTrustLine.noRipple, true)
assert.equal(noRippleTrustLine.limit, trustLineAmount)
// WHEN the issuer re-enables rippling on the trust line
await issuedCurrencyClient.enableRipplingForTrustLine(
walletMightHaveTrustLines.getAddress(),
trustLineCurrency,
trustLineAmount,
issuerWalletAuthTrustLines,
)
trustLines = await issuedCurrencyClient.getTrustLines(
issuerWalletAuthTrustLines.getAddress(),
)
const enabledRippleTrustLine = trustLines.find(
(trustLine) => trustLine.currency === trustLineCurrency,
)!
// THEN the trust line has noRipple enabled.
assert.equal(enabledRippleTrustLine.noRipple, false)
assert.equal(enabledRippleTrustLine.limit, trustLineAmount)
})
it('monitorAccountTransactions/stopMonitoringAccountTransactions - valid request', async function (): Promise<void> {
this.timeout(timeoutMs)
const xAddress = walletNeverAnyTrustLines.getAddress()
const classicAddress = XrpUtils.decodeXAddress(xAddress)
const address = classicAddress!.address
const xrpAmount = '100'
let messageReceived = false
const callback = (data: TransactionResponse) => {
if (messageReceived) {
assert.fail('Second message should not be received after unsubscribing')
}
messageReceived = true
assert.equal(data.engine_result, 'tesSUCCESS')
assert.equal(data.engine_result_code, 0)
assert.equal(
data.engine_result_message,
'The transaction was applied. Only final in a validated ledger.',
)
assert.equal(data.meta.TransactionResult, 'tesSUCCESS')
assert.equal(data.status, 'closed')
assert.equal(data.type, 'transaction')
assert.equal(data.validated, true)
assert.equal(data.transaction.Amount, xrpAmount)
assert.equal(data.transaction.Destination, address)
assert.equal(data.transaction.TransactionType, 'Payment')
}
const waitUntilMessageReceived = async () => {
while (!messageReceived) {
await sleep(5)
}
}
const xrpClient = new XrpClient(rippledGrpcUrl, XrplNetwork.Test)
// GIVEN a valid test address
// WHEN subscribeToAccount is called for that address
const response = await issuedCurrencyClient.monitorAccountTransactions(
xAddress,
callback,
)
// THEN the subscribe request is successfully submitted and received
assert.isTrue(response)
// WHEN a payment is sent to that address
await xrpClient.sendXrp(xrpAmount, xAddress, walletMightHaveTrustLines)
await waitUntilMessageReceived()
//THEN the payment is successfully received
assert(messageReceived)
// WHEN unsubscribe is called for that address
const unsubscribeResponse = await issuedCurrencyClient.stopMonitoringAccountTransactions(
xAddress,
)
// THEN the unsubscribe request is successfully submitted and received
assert.isTrue(unsubscribeResponse)
// WHEN a payment is sent to that address
await xrpClient.sendXrp(xrpAmount, xAddress, walletMightHaveTrustLines)
// THEN the payment is not received by the callback
// (If a payment is received, fail will be called in the callback)
})
it('monitorAccountTransactions - bad address', async function (): Promise<void> {
this.timeout(timeoutMs)
const address = 'badAddress'
// eslint-disable-next-line @typescript-eslint/no-empty-function
const callback = () => {}
// GIVEN a test address that is malformed.
// WHEN monitorAccountTransactions is called for that address THEN an error is thrown.
try {
await issuedCurrencyClient.monitorAccountTransactions(address, callback)
} catch (e) {
if (!(e instanceof XrpError)) {
assert.fail('wrong error')
}
}
})
it('stopMonitoringAccountTransactions - not-subscribed address', async function (): Promise<void> {
this.timeout(timeoutMs)
const xAddress = walletNeverAnyTrustLines.getAddress()
const classicAddress = XrpUtils.decodeXAddress(xAddress)
const address = classicAddress!.address
// GIVEN a test address that is not subscribed to.
// WHEN stopMonitoringAccountTransactions is called for that address THEN an error is thrown.
try {
await issuedCurrencyClient.stopMonitoringAccountTransactions(address)
assert.fail('Method call should fail')
} catch (e) {
if (!(e instanceof XrpError)) {
assert.fail('wrong error')
}
}
})
it('stopMonitoringAccountTransactions - bad address', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a test address that is malformed.
const address = 'badAddress'
// WHEN stopMonitoringAccountTransactions is called for that address THEN an error is thrown.
try {
await issuedCurrencyClient.stopMonitoringAccountTransactions(address)
assert.fail('Method call should fail')
} catch (e) {
if (!(e instanceof XrpError)) {
assert.fail('wrong error')
}
}
})
it('createOffer - success, taker gets issued currency taker pays xrp', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a funded issuer wallet
const issuerClassicAddress = XrpUtils.decodeXAddress(
issuerWallet.getAddress(),
)
if (!issuerClassicAddress) {
throw XrpError.xAddressRequired
}
const takerGetsIssuedCurrency: IssuedCurrency = {
issuer: issuerClassicAddress.address,
currency: 'FAK',
value: '100',
}
const takerPaysXrp = '50'
const offerSequenceNumber = 1
const rippleEpochStartTimeSeconds = 946684800
const currentTimeUnixEpochSeconds = Date.now() / 1000 // 1000 ms/sec
const currentTimeRippleEpochSeconds =
currentTimeUnixEpochSeconds - rippleEpochStartTimeSeconds
const expiration = currentTimeRippleEpochSeconds + 60 * 60 // roughly one hour in future
// WHEN the issuer creates an offer to exchange XRP for their issued currency
const transactionResult = await issuedCurrencyClient.createOffer(
issuerWallet,
takerGetsIssuedCurrency,
takerPaysXrp,
offerSequenceNumber,
expiration,
)
// THEN the offer is successfully created.
// TODO: confirm success using book_offers or account_offers API when implemented?
assert.equal(transactionResult.status, TransactionStatus.Succeeded)
assert.equal(transactionResult.validated, true)
assert.equal(transactionResult.final, true)
})
it('createOffer - success, taker gets xrp taker pays issued currency', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a wallet with XRP
const issuerClassicAddress = XrpUtils.decodeXAddress(
issuerWallet.getAddress(),
)
if (!issuerClassicAddress) {
throw XrpError.xAddressRequired
}
const takerPaysIssuedCurrency: IssuedCurrency = {
issuer: issuerClassicAddress.address,
currency: 'FAK',
value: '100',
}
const takerGetsXrp = '50'
const offerSequenceNumber = 1
const rippleEpochStartTimeSeconds = 946684800
const currentTimeUnixEpochSeconds = Date.now() / 1000 // 1000 ms/sec
const currentTimeRippleEpochSeconds =
currentTimeUnixEpochSeconds - rippleEpochStartTimeSeconds
const expiration = currentTimeRippleEpochSeconds + 60 * 60 // roughly one hour in future
// WHEN the wallet creates an offer to exchange (receive) their own issued currency for their XRP (deliver)
const transactionResult = await issuedCurrencyClient.createOffer(
issuerWallet,
takerGetsXrp,
takerPaysIssuedCurrency,
offerSequenceNumber,
expiration,
)
// THEN the offer is successfully created.
// TODO: confirm success using book_offers or account_offers API when implemented?
assert.equal(transactionResult.status, TransactionStatus.Succeeded)
assert.equal(transactionResult.validated, true)
assert.equal(transactionResult.final, true)
})
it('createOffer - flags, success', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a wallet with XRP
const issuerClassicAddress = XrpUtils.decodeXAddress(
issuerWallet.getAddress(),
)
if (!issuerClassicAddress) {
throw XrpError.xAddressRequired
}
const takerPaysIssuedCurrency: IssuedCurrency = {
issuer: issuerClassicAddress.address,
currency: 'FAK',
value: '100',
}
const takerGetsXrp = '50'
const offerSequenceNumber = 1
const rippleEpochStartTimeSeconds = 946684800
const currentTimeUnixEpochSeconds = Date.now() / 1000 // 1000 ms/sec
const currentTimeRippleEpochSeconds =
currentTimeUnixEpochSeconds - rippleEpochStartTimeSeconds
const expiration = currentTimeRippleEpochSeconds + 60 * 60 // roughly one hour in future
// WHEN the wallet creates an offer to exchange (receive) their own issued currency for their XRP (deliver)
const transactionResult = await issuedCurrencyClient.createOffer(
issuerWallet,
takerGetsXrp,
takerPaysIssuedCurrency,
offerSequenceNumber,
expiration,
true,
true,
false,
true,
)
console.log(transactionResult)
// THEN the offer is successfully created.
// TODO: confirm success using book_offers or account_offers API when implemented?
assert.equal(transactionResult.status, TransactionStatus.Succeeded)
assert.equal(transactionResult.validated, true)
assert.equal(transactionResult.final, true)
})
it('createOffer - tfImmediateOrCancel and tfFillOrKill, failure', async function (): Promise<void> {
this.timeout(timeoutMs)
// GIVEN a wallet with XRP
const issuerClassicAddress = XrpUtils.decodeXAddress(
issuerWallet.getAddress(),
)
if (!issuerClassicAddress) {
throw XrpError.xAddressRequired
}
const takerPaysIssuedCurrency: IssuedCurrency = {
issuer: issuerClassicAddress.address,
currency: 'FAK',
value: '100',
}
const takerGetsXrp = '50'
const offerSequenceNumber = 1
const rippleEpochStartTimeSeconds = 946684800
const currentTimeUnixEpochSeconds = Date.now() / 1000 // 1000 ms/sec
const currentTimeRippleEpochSeconds =
currentTimeUnixEpochSeconds - rippleEpochStartTimeSeconds
const expiration = currentTimeRippleEpochSeconds + 60 * 60 // roughly one hour in future
// WHEN the wallet creates an offer to exchange (receive) their own issued currency for their XRP (deliver),
// with mutually exclusive `immediateOrCancel` and `fillOrKill` flags both set,
const transactionResult = await issuedCurrencyClient.createOffer(
issuerWallet,
takerGetsXrp,
takerPaysIssuedCurrency,
offerSequenceNumber,
expiration,
false,
true,
true,
false,
)
// THEN the offer is not successfully created.
assert.equal(
transactionResult.status,
TransactionStatus.MalformedTransaction,
)
})
it('cancelOffer - success', async function (): Promise<void> {
this.timeout(timeoutMs)
const offerSequenceNumber = 1
const transactionResult = await issuedCurrencyClient.cancelOffer(
issuerWallet,
offerSequenceNumber,
)
// TODO: verify this better? An OfferCancel transaction is considered successful even if there was no offer to cancel.
// At least we know it's well-formed.
assert.equal(transactionResult.status, TransactionStatus.Succeeded)
assert.equal(transactionResult.validated, true)
assert.equal(transactionResult.final, true)
})
}) | the_stack |
import { DescriptorSet } from '../base/descriptor-set';
import { DescriptorSetLayout } from '../base/descriptor-set-layout';
import { PipelineLayout } from '../base/pipeline-layout';
import { Buffer } from '../base/buffer';
import { CommandBuffer } from '../base/command-buffer';
import { Device } from '../base/device';
import { Framebuffer } from '../base/framebuffer';
import { InputAssembler } from '../base/input-assembler';
import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
import { Queue } from '../base/queue';
import { RenderPass } from '../base/render-pass';
import { Sampler } from '../base/states/sampler';
import { Shader } from '../base/shader';
import { Texture } from '../base/texture';
import { WebGL2DescriptorSet } from './webgl2-descriptor-set';
import { WebGL2Buffer } from './webgl2-buffer';
import { WebGL2CommandBuffer } from './webgl2-command-buffer';
import { WebGL2Framebuffer } from './webgl2-framebuffer';
import { WebGL2InputAssembler } from './webgl2-input-assembler';
import { WebGL2DescriptorSetLayout } from './webgl2-descriptor-set-layout';
import { WebGL2PipelineLayout } from './webgl2-pipeline-layout';
import { WebGL2PipelineState } from './webgl2-pipeline-state';
import { WebGL2PrimaryCommandBuffer } from './webgl2-primary-command-buffer';
import { WebGL2Queue } from './webgl2-queue';
import { WebGL2RenderPass } from './webgl2-render-pass';
import { WebGL2Sampler } from './states/webgl2-sampler';
import { WebGL2Shader } from './webgl2-shader';
import { WebGL2Swapchain, getExtensions } from './webgl2-swapchain';
import { WebGL2Texture } from './webgl2-texture';
import {
CommandBufferType, DescriptorSetLayoutInfo, DescriptorSetInfo,
PipelineLayoutInfo, BufferViewInfo, CommandBufferInfo, BufferInfo, FramebufferInfo, InputAssemblerInfo,
QueueInfo, RenderPassInfo, SamplerInfo, ShaderInfo, TextureInfo, TextureViewInfo, DeviceInfo, GlobalBarrierInfo, TextureBarrierInfo,
QueueType, API, Feature, BufferTextureCopy, SwapchainInfo,
} from '../base/define';
import { WebGL2CmdFuncCopyTextureToBuffers, WebGL2CmdFuncCopyBuffersToTexture, WebGL2CmdFuncCopyTexImagesToTexture } from './webgl2-commands';
import { GlobalBarrier } from '../base/states/global-barrier';
import { TextureBarrier } from '../base/states/texture-barrier';
import { debug } from '../../platform/debug';
import { Swapchain } from '../base/swapchain';
import { WebGL2DeviceManager } from './webgl2-define';
export class WebGL2Device extends Device {
get gl () {
return this._swapchain!.gl;
}
get extensions () {
return this._swapchain!.extensions;
}
get stateCache () {
return this._swapchain!.stateCache;
}
get nullTex2D () {
return this._swapchain!.nullTex2D;
}
get nullTexCube () {
return this._swapchain!.nullTexCube;
}
private _swapchain: WebGL2Swapchain | null = null;
public initialize (info: DeviceInfo): boolean {
WebGL2DeviceManager.setInstance(this);
this._gfxAPI = API.WEBGL2;
this._bindingMappingInfo = info.bindingMappingInfo;
if (!this._bindingMappingInfo.bufferOffsets.length) this._bindingMappingInfo.bufferOffsets.push(0);
if (!this._bindingMappingInfo.samplerOffsets.length) this._bindingMappingInfo.samplerOffsets.push(0);
let gl: WebGL2RenderingContext | null = null;
try {
gl = document.createElement('canvas').getContext('webgl2');
} catch (err) {
console.error(err);
}
if (!gl) {
console.error('This device does not support WebGL.');
return false;
}
// create queue
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
this._caps.maxUniformBufferBindings = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS);
this._caps.maxUniformBlockSize = gl.getParameter(gl.MAX_UNIFORM_BLOCK_SIZE);
this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
this._caps.uboOffsetAlignment = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT);
const extensions = gl.getSupportedExtensions();
let extStr = '';
if (extensions) {
for (const ext of extensions) {
extStr += `${ext} `;
}
}
const exts = getExtensions(gl);
if (exts.WEBGL_debug_renderer_info) {
this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
} else {
this._renderer = gl.getParameter(gl.RENDERER);
this._vendor = gl.getParameter(gl.VENDOR);
}
const version: string = gl.getParameter(gl.VERSION);
this._features.fill(false);
this._features[Feature.TEXTURE_FLOAT] = true;
this._features[Feature.TEXTURE_HALF_FLOAT] = true;
this._features[Feature.FORMAT_R11G11B10F] = true;
this._features[Feature.FORMAT_SRGB] = true;
this._features[Feature.FORMAT_RGB8] = true;
this._features[Feature.ELEMENT_INDEX_UINT] = true;
this._features[Feature.INSTANCED_ARRAYS] = true;
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
this._features[Feature.BLEND_MINMAX] = true;
if (exts.EXT_color_buffer_float) {
this._features[Feature.COLOR_FLOAT] = true;
this._features[Feature.COLOR_HALF_FLOAT] = true;
}
if (exts.OES_texture_float_linear) {
this._features[Feature.TEXTURE_FLOAT_LINEAR] = true;
}
if (exts.OES_texture_half_float_linear) {
this._features[Feature.TEXTURE_HALF_FLOAT_LINEAR] = true;
}
let compressedFormat = '';
if (exts.WEBGL_compressed_texture_etc1) {
this._features[Feature.FORMAT_ETC1] = true;
compressedFormat += 'etc1 ';
}
if (exts.WEBGL_compressed_texture_etc) {
this._features[Feature.FORMAT_ETC2] = true;
compressedFormat += 'etc2 ';
}
if (exts.WEBGL_compressed_texture_s3tc) {
this._features[Feature.FORMAT_DXT] = true;
compressedFormat += 'dxt ';
}
if (exts.WEBGL_compressed_texture_pvrtc) {
this._features[Feature.FORMAT_PVRTC] = true;
compressedFormat += 'pvrtc ';
}
if (exts.WEBGL_compressed_texture_astc) {
this._features[Feature.FORMAT_ASTC] = true;
compressedFormat += 'astc ';
}
debug('WebGL2 device initialized.');
debug(`RENDERER: ${this._renderer}`);
debug(`VENDOR: ${this._vendor}`);
debug(`VERSION: ${version}`);
debug(`COMPRESSED_FORMAT: ${compressedFormat}`);
debug(`EXTENSIONS: ${extStr}`);
return true;
}
public destroy (): void {
if (this._queue) {
this._queue.destroy();
this._queue = null;
}
if (this._cmdBuff) {
this._cmdBuff.destroy();
this._cmdBuff = null;
}
const it = this._samplers.values();
let res = it.next();
while (!res.done) {
(res.value as WebGL2Sampler).destroy();
res = it.next();
}
this._swapchain = null;
}
public flushCommands (cmdBuffs: CommandBuffer[]) {}
public acquire (swapchains: Swapchain[]) {}
public present () {
const queue = (this._queue as WebGL2Queue);
this._numDrawCalls = queue.numDrawCalls;
this._numInstances = queue.numInstances;
this._numTris = queue.numTris;
queue.clear();
}
public createCommandBuffer (info: CommandBufferInfo): CommandBuffer {
// const Ctor = WebGLCommandBuffer; // opt to instant invocation
const Ctor = info.type === CommandBufferType.PRIMARY ? WebGL2PrimaryCommandBuffer : WebGL2CommandBuffer;
const cmdBuff = new Ctor();
cmdBuff.initialize(info);
return cmdBuff;
}
public createSwapchain (info: SwapchainInfo): Swapchain {
const swapchain = new WebGL2Swapchain();
this._swapchain = swapchain;
swapchain.initialize(info);
return swapchain;
}
public createBuffer (info: BufferInfo | BufferViewInfo): Buffer {
const buffer = new WebGL2Buffer();
buffer.initialize(info);
return buffer;
}
public createTexture (info: TextureInfo | TextureViewInfo): Texture {
const texture = new WebGL2Texture();
texture.initialize(info);
return texture;
}
public createDescriptorSet (info: DescriptorSetInfo): DescriptorSet {
const descriptorSet = new WebGL2DescriptorSet();
descriptorSet.initialize(info);
return descriptorSet;
}
public createShader (info: ShaderInfo): Shader {
const shader = new WebGL2Shader();
shader.initialize(info);
return shader;
}
public createInputAssembler (info: InputAssemblerInfo): InputAssembler {
const inputAssembler = new WebGL2InputAssembler();
inputAssembler.initialize(info);
return inputAssembler;
}
public createRenderPass (info: RenderPassInfo): RenderPass {
const renderPass = new WebGL2RenderPass();
renderPass.initialize(info);
return renderPass;
}
public createFramebuffer (info: FramebufferInfo): Framebuffer {
const framebuffer = new WebGL2Framebuffer();
framebuffer.initialize(info);
return framebuffer;
}
public createDescriptorSetLayout (info: DescriptorSetLayoutInfo): DescriptorSetLayout {
const descriptorSetLayout = new WebGL2DescriptorSetLayout();
descriptorSetLayout.initialize(info);
return descriptorSetLayout;
}
public createPipelineLayout (info: PipelineLayoutInfo): PipelineLayout {
const pipelineLayout = new WebGL2PipelineLayout();
pipelineLayout.initialize(info);
return pipelineLayout;
}
public createPipelineState (info: PipelineStateInfo): PipelineState {
const pipelineState = new WebGL2PipelineState();
pipelineState.initialize(info);
return pipelineState;
}
public createQueue (info: QueueInfo): Queue {
const queue = new WebGL2Queue();
queue.initialize(info);
return queue;
}
public getSampler (info: SamplerInfo): Sampler {
const hash = Sampler.computeHash(info);
if (!this._samplers.has(hash)) {
this._samplers.set(hash, new WebGL2Sampler(info, hash));
}
return this._samplers.get(hash)!;
}
public getGlobalBarrier (info: GlobalBarrierInfo) {
const hash = GlobalBarrier.computeHash(info);
if (!this._globalBarriers.has(hash)) {
this._globalBarriers.set(hash, new GlobalBarrier(info, hash));
}
return this._globalBarriers.get(hash)!;
}
public getTextureBarrier (info: TextureBarrierInfo) {
const hash = TextureBarrier.computeHash(info);
if (!this._textureBarriers.has(hash)) {
this._textureBarriers.set(hash, new TextureBarrier(info, hash));
}
return this._textureBarriers.get(hash)!;
}
public copyBuffersToTexture (buffers: ArrayBufferView[], texture: Texture, regions: BufferTextureCopy[]) {
WebGL2CmdFuncCopyBuffersToTexture(
this,
buffers,
(texture as WebGL2Texture).gpuTexture,
regions,
);
}
public copyTextureToBuffers (texture: Texture, buffers: ArrayBufferView[], regions: BufferTextureCopy[]) {
WebGL2CmdFuncCopyTextureToBuffers(
this,
(texture as WebGL2Texture).gpuTexture,
buffers,
regions,
);
}
public copyTexImagesToTexture (
texImages: TexImageSource[],
texture: Texture,
regions: BufferTextureCopy[],
) {
WebGL2CmdFuncCopyTexImagesToTexture(
this,
texImages,
(texture as WebGL2Texture).gpuTexture,
regions,
);
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/replicationPoliciesMappers";
import * as Parameters from "../models/parameters";
import { SiteRecoveryManagementClientContext } from "../siteRecoveryManagementClientContext";
/** Class representing a ReplicationPolicies. */
export class ReplicationPolicies {
private readonly client: SiteRecoveryManagementClientContext;
/**
* Create a ReplicationPolicies.
* @param {SiteRecoveryManagementClientContext} client Reference to the service client.
*/
constructor(client: SiteRecoveryManagementClientContext) {
this.client = client;
}
/**
* Lists the replication policies for a vault.
* @summary Gets the list of replication policies
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationPoliciesListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.ReplicationPoliciesListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.PolicyCollection>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyCollection>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyCollection>, callback?: msRest.ServiceCallback<Models.PolicyCollection>): Promise<Models.ReplicationPoliciesListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ReplicationPoliciesListResponse>;
}
/**
* Gets the details of a replication policy.
* @summary Gets the requested policy.
* @param policyName Replication policy name.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationPoliciesGetResponse>
*/
get(policyName: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationPoliciesGetResponse>;
/**
* @param policyName Replication policy name.
* @param callback The callback
*/
get(policyName: string, callback: msRest.ServiceCallback<Models.Policy>): void;
/**
* @param policyName Replication policy name.
* @param options The optional parameters
* @param callback The callback
*/
get(policyName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Policy>): void;
get(policyName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Policy>, callback?: msRest.ServiceCallback<Models.Policy>): Promise<Models.ReplicationPoliciesGetResponse> {
return this.client.sendOperationRequest(
{
policyName,
options
},
getOperationSpec,
callback) as Promise<Models.ReplicationPoliciesGetResponse>;
}
/**
* The operation to create a replication policy
* @summary Creates the policy.
* @param policyName Replication policy name
* @param input Create policy input
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationPoliciesCreateResponse>
*/
create(policyName: string, input: Models.CreatePolicyInput, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationPoliciesCreateResponse> {
return this.beginCreate(policyName,input,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ReplicationPoliciesCreateResponse>;
}
/**
* The operation to delete a replication policy.
* @summary Delete the policy.
* @param policyName Replication policy name.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(policyName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(policyName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* The operation to update a replication policy.
* @summary Updates the policy.
* @param policyName Policy Id.
* @param input Update Policy Input
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationPoliciesUpdateResponse>
*/
update(policyName: string, input: Models.UpdatePolicyInput, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationPoliciesUpdateResponse> {
return this.beginUpdate(policyName,input,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ReplicationPoliciesUpdateResponse>;
}
/**
* The operation to create a replication policy
* @summary Creates the policy.
* @param policyName Replication policy name
* @param input Create policy input
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(policyName: string, input: Models.CreatePolicyInput, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
policyName,
input,
options
},
beginCreateOperationSpec,
options);
}
/**
* The operation to delete a replication policy.
* @summary Delete the policy.
* @param policyName Replication policy name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(policyName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
policyName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* The operation to update a replication policy.
* @summary Updates the policy.
* @param policyName Policy Id.
* @param input Update Policy Input
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(policyName: string, input: Models.UpdatePolicyInput, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
policyName,
input,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Lists the replication policies for a vault.
* @summary Gets the list of replication policies
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationPoliciesListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationPoliciesListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyCollection>): 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.PolicyCollection>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyCollection>, callback?: msRest.ServiceCallback<Models.PolicyCollection>): Promise<Models.ReplicationPoliciesListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ReplicationPoliciesListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.policyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Policy
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.policyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "input",
mapper: {
...Mappers.CreatePolicyInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Policy
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.policyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationPolicies/{policyName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.policyName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "input",
mapper: {
...Mappers.UpdatePolicyInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Policy
},
202: {},
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.PolicyCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as cart from '../../helpers/cart';
import { visitHomePage } from '../../helpers/checkout-flow';
import * as alerts from '../../helpers/global-message';
import { clickHamburger } from '../../helpers/homepage';
import { viewportContext } from '../../helpers/viewport-context';
import { login } from '../../support/utils/login';
describe('Cart', () => {
viewportContext(['mobile', 'desktop'], () => {
context('Anonymous user', () => {
it('should add and remove products', () => {
cart.checkBasicCart();
});
});
context('Registered user', () => {
before(() => {
cy.window().then((win) => win.sessionStorage.clear());
cart.loginRegisteredUser();
visitHomePage();
});
it('should merge carts when user is authenticated', () => {
cart.registerCreateCartRoute();
cart.registerSaveCartRoute();
cart.addProductWhenLoggedIn(false);
clickHamburger();
cart.logOutAndNavigateToEmptyCart();
cart.addProductAsAnonymous();
cart.verifyMergedCartWhenLoggedIn();
cart.logOutAndEmptyCart();
});
it('should add product and manipulate cart quantity', () => {
cart.manipulateCartQuantity();
});
});
});
viewportContext(['desktop'], () => {
context('Anonymous user', () => {
it('should be unable to add out of stock products to cart', () => {
cart.outOfStock();
});
it('should keep cart on page refresh', () => {
cart.addProductAsAnonymous();
cy.reload();
cart.verifyCartNotEmpty();
});
});
context('Registered user', () => {
before(() => {
cy.window().then((win) => win.sessionStorage.clear());
cart.loginRegisteredUser();
visitHomePage();
});
it('should be loaded for authenticated user after "cart not found" error', () => {
cart.registerCreateCartRoute();
cart.registerSaveCartRoute();
cart.loginRegisteredUser();
cart.addProductWhenLoggedIn(false);
cy.window().then((window) => {
const storage = JSON.parse(
window.localStorage.getItem('spartacus⚿electronics-spa⚿cart')
);
const cartCode = storage.active;
storage.active = 'incorrect-code';
window.localStorage.setItem(
'spartacus⚿electronics-spa⚿cart',
JSON.stringify(storage)
);
cy.visit('/cart');
alerts.getErrorAlert().should('contain', 'Cart not found');
cy.get('.cart-details-wrapper .cx-total').contains(
`Cart #${cartCode}`
);
});
});
it('should be loaded after user login', () => {
cart.registerCartUser();
cart.loginCartUser();
cy.visit(`/product/${cart.products[0].code}`);
cart.clickAddToCart();
cart.checkAddedToCartDialog();
cart.closeAddedToCartDialog();
cy.selectUserMenuOption({
option: 'Sign Out',
});
cy.clearLocalStorage();
cy.intercept(
`${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/carts?fields*`
).as('carts');
cart.loginCartUser();
cy.wait('@carts');
cy.visit('/cart');
cart.checkProductInCart(cart.products[0]);
// cleanup
cart.removeCartItem(cart.products[0]);
cart.validateEmptyCart();
});
// will fail right now, as this is not implemented yet
it('should first try to load cart when adding first entry for logged user', () => {
cart.loginCartUser();
login(
cart.cartUser.registrationData.email,
cart.cartUser.registrationData.password,
false
).then((res) => {
expect(res.status).to.eq(200);
// remove cart
cy.request({
method: 'DELETE',
url: `${Cypress.env('API_URL')}/${Cypress.env(
'OCC_PREFIX'
)}/${Cypress.env('BASE_SITE')}/users/current/carts/current`,
headers: {
Authorization: `bearer ${res.body.access_token}`,
},
}).then((response) => {
expect(response.status).to.eq(200);
});
});
cy.visit(`/product/${cart.products[0].code}`);
cy.get('cx-breadcrumb h1').contains(cart.products[0].name);
login(
cart.cartUser.registrationData.email,
cart.cartUser.registrationData.password,
false
).then((res) => {
cy.request({
// create cart
method: 'POST',
url: `${Cypress.env('API_URL')}/${Cypress.env(
'OCC_PREFIX'
)}/${Cypress.env('BASE_SITE')}/users/current/carts`,
headers: {
Authorization: `bearer ${res.body.access_token}`,
},
}).then((response) => {
// add entry to cart
return cy.request({
method: 'POST',
url: `${Cypress.env('API_URL')}/${Cypress.env(
'OCC_PREFIX'
)}/${Cypress.env('BASE_SITE')}/users/current/carts/${
response.body.code
}/entries`,
headers: {
Authorization: `bearer ${res.body.access_token}`,
},
body: {
product: { code: cart.products[1].code, qty: 1 },
},
});
});
});
cart.clickAddToCart();
cart.checkAddedToCartDialog(2);
cy.visit('/cart');
cart.checkProductInCart(cart.products[0]);
cart.checkProductInCart(cart.products[1]);
cart.registerCartRefreshRoute();
cart.removeCartItem(cart.products[0]);
cy.wait('@refresh_cart');
cart.removeCartItem(cart.products[1]);
cart.validateEmptyCart();
});
it('should create new cart when adding first entry for authenticated user without a cart', () => {
cart.loginCartUser();
login(
cart.cartUser.registrationData.email,
cart.cartUser.registrationData.password,
false
).then((res) => {
expect(res.status).to.eq(200);
cy.log('Removing current Cart for the test case');
cy.request({
method: 'DELETE',
url: `${Cypress.env('API_URL')}/${Cypress.env(
'OCC_PREFIX'
)}/${Cypress.env('BASE_SITE')}/users/current/carts/current`,
headers: {
Authorization: `bearer ${res.body.access_token}`,
},
}).then((response) => {
expect(response.status).to.eq(200);
});
});
cy.visit(`/product/${cart.products[0].code}`);
cy.get('cx-breadcrumb h1').contains(cart.products[0].name);
cy.intercept({
method: 'GET',
pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/carts`,
}).as('cart');
cart.clickAddToCart();
cart.checkAddedToCartDialog();
cy.visit('/cart');
cart.checkProductInCart(cart.products[0]);
// cleanup
cy.intercept({
method: 'GET',
pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/current/carts/*`,
query: {
lang: 'en',
curr: 'USD',
fields: '*',
},
}).as('refresh_cart');
cart.removeCartItem(cart.products[0]);
cart.validateEmptyCart();
});
it('should use existing cart when adding new entries', () => {
cy.visit(`/product/${cart.products[0].code}`);
cy.get('cx-breadcrumb h1').contains(cart.products[0].name);
cart.clickAddToCart();
cart.checkAddedToCartDialog();
cy.visit(`/product/${cart.products[1].code}`);
cy.get('cx-breadcrumb h1').contains(cart.products[1].name);
cart.clickAddToCart();
cart.checkAddedToCartDialog(2);
cy.visit('/cart');
cart.checkProductInCart(cart.products[0]);
cart.checkProductInCart(cart.products[1]);
// cleanup
cart.registerCartRefreshRoute();
cart.removeCartItem(cart.products[0]);
cy.wait('@refresh_cart');
cart.removeCartItem(cart.products[1]);
cy.wait('@refresh_cart');
cart.validateEmptyCart();
});
// will fail right now, as this is not fixed yet
it.skip("shouldn't show added to cart dialog when entry couldn't be added", () => {
cy.visit(`/product/${cart.products[0].code}`);
cy.get('cx-breadcrumb h1').contains(cart.products[0].name);
cy.intercept(
{
method: 'POST',
pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env(
'BASE_SITE'
)}/users/anonymous/carts/*/entries`,
},
{
body: {
error: {},
},
statusCode: 400,
}
).as('addEntry');
cart.clickAddToCart();
cy.wait('@addEntry').its('response.statusCode').should('eq', 400);
cy.get('cx-added-to-cart-dialog .modal-header').should(
'not.contain',
'Item(s) added to your cart'
);
cart.checkAddedToCartDialog();
cy.visit('/cart');
cart.validateEmptyCart();
});
it('should have different cart on different base sites', () => {
cy.visit(`/product/${cart.products[0].code}`);
cart.clickAddToCart();
cart.checkAddedToCartDialog();
cart.closeAddedToCartDialog();
const apparelProduct = {
code: '300310300',
name: 'Wallet Dakine Agent Leather Wallet brown',
price: 33.96,
};
cy.visit(`/apparel-uk-spa/en/GBP/product/${apparelProduct.code}`);
cart.clickAddToCart();
cart.checkAddedToCartDialog();
cart.closeAddedToCartDialog();
cy.visit(`/${Cypress.env('BASE_SITE')}/en/USD/cart`);
cart.checkProductInCart(cart.products[0]);
cy.get('cx-global-message .alert-danger').should('not.exist');
cy.visit(`/apparel-uk-spa/en/GBP/cart`);
cart.checkProductInCart(apparelProduct, 1, 'GBP');
cy.get('cx-global-message .alert-danger').should('not.exist');
});
});
});
}); | the_stack |
import * as React from "react";
import styles from "./ManageProfileCardProperties.module.scss";
import { IManageProfileCardPropertiesProps } from "./IManageProfileCardPropertiesProps";
import { escape } from "@microsoft/sp-lodash-subset";
import { IManageProfileCardPropertiesState } from "./IManageProfileCardPropertiesState";
import { IListItem } from "../../Entities/IListItem";
import { MSGraphClient } from "@microsoft/sp-http";
import { ListCommandBar } from "../ListCommandBar/ListCommandBar";
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import {
loadTheme,
mergeStyleSets,
MessageBarType,
FontIcon,
Toggle,
CustomizerContext,
Customizer,
MessageBar,
Spinner,
SpinnerSize,
} from "office-ui-fabric-react";
import {
DetailsList,
DetailsListLayoutMode,
Selection,
SelectionMode,
IColumn,
} from "office-ui-fabric-react/lib/DetailsList";
import { useProfileCardProperties } from "../../hooks/useProfileCardProperties";
import { IProfileCardProperty } from "../../Entities/IProfileCardProperty";
import { AppContext, IAppContextProps } from "../../Common/AppContextProps";
import { AddProfileCardProperty } from "../AddProfileCardProperty/AddProfileCardProperty";
import { EditProfileCardProperty } from "../EditProfileCardProperty/EditProfileCardProperty";
import { DeleteProfileCardProperty } from "../DeleteProfileCardProperty/DeleteProfileCardProperty";
import strings from "ManageProfileCardPropertiesWebPartStrings";
// Style Component
const classNames = mergeStyleSets({
commandBar: {
marginTop: 15,
marginBottom: 15,
},
title: {
fontSize: 22,
},
fileIconHeaderIcon: {
padding: 0,
fontSize: "16px",
},
fileIconCell: {
textAlign: "center",
selectors: {
"&:before": {
content: ".",
display: "inline-block",
verticalAlign: "middle",
height: "100%",
width: "0px",
visibility: "hidden",
},
},
},
fileIconImg: {
verticalAlign: "middle",
maxHeight: "16px",
maxWidth: "16px",
height: "16px",
width: "16px",
fontSize: "16px",
},
fileIconImgHeader: {
maxHeight: "16px",
maxWidth: "16px",
height: "16px",
width: "16px",
fontSize: "16px",
},
controlWrapper: {
display: "flex",
flexWrap: "wrap",
},
centerColumn: { display: "flex", alignItems: "flex-start", height: "100%" },
});
export default class ManageProfileCardProperties extends React.Component<
IManageProfileCardPropertiesProps,
IManageProfileCardPropertiesState
> {
private listFields: IColumn[] = [];
private organizationId: string = undefined;
private _selection: Selection;
private msGrapClient: MSGraphClient;
private applicationContext: IAppContextProps;
constructor(props: IManageProfileCardPropertiesProps) {
super(props);
this.listFields = [
{
name: "",
fieldName: "icon",
isResizable: false,
iconName: "TaskManager",
isIconOnly: true,
styles: { iconClassName: classNames.fileIconImgHeader },
minWidth: 20,
maxWidth: 20,
key: "icon",
onRender: (item: IListItem) => {
return (
<>
<FontIcon
iconName="TaskManager"
className={classNames.fileIconImg}
style={{ color: this.props.themeVariant.palette.themePrimary }}
/>
</>
);
},
},
{
key: "displayAttribute",
name: "Directory Property Name",
fieldName: "displayAttribute",
isResizable: true,
maxWidth: 210,
minWidth: 150,
isSorted: true,
isSortedDescending: false,
onColumnClick: this._onColumnClick,
},
{
name: "Display Name",
fieldName: "displayName",
isResizable: true,
maxWidth: 160,
minWidth: 50,
key: "displayName",
onColumnClick: this._onColumnClick,
},
{
name: "Nr Localizations",
fieldName: "localizations",
isResizable: true,
maxWidth: 150,
minWidth: 50,
key: "loc",
onColumnClick: this._onColumnClick,
},
];
this.state = {
isLoading: true,
hasError: false,
errorMessage: undefined,
listItems: [],
listFields: this.listFields,
selectedItem: undefined,
displayDeletePanel: false,
displayEditPanel: false,
displayNewPanel: false,
};
this._selection = new Selection({
onSelectionChanged: () => {
this.setState({
selectedItem: this._getSelectedItem(),
});
},
});
}
//
// Get Selected Item
//
private _getSelectedItem = (): IListItem => {
const selectionCount = this._selection.getSelectedCount();
switch (selectionCount) {
case 0:
return null;
case 1:
return this._selection.getSelection()[0] as IListItem;
default:
return null;
}
}
//
// Component did mount
//
public componentDidMount = async (): Promise<void> => {
try {
this.msGrapClient = await this.props.webpartContext.msGraphClientFactory.getClient();
// const _aadclient = await this.props.webpartContext.aadTokenProviderFactory.getTokenProvider();
this.setState({
isLoading: true,
});
const { checkUserIsGlobalAdmin } = await useProfileCardProperties();
const _isAdmin: Boolean = await checkUserIsGlobalAdmin(this.msGrapClient);
if (!_isAdmin) {
throw new Error(
"To Manage Profile Card Properties the user must be Tenant Admin"
);
}
this.organizationId = this.props.webpartContext.pageContext.aadInfo.tenantId;
const _listItems = await this._getProfileCardProperties();
this.applicationContext = {
...this.props,
listItems: _listItems,
msGraphClient: this.msGrapClient,
organizationId: this.organizationId,
};
this.setState({
listItems: _listItems,
isLoading: false,
});
} catch (error) {
this.setState({
hasError: true,
errorMessage: error.message,
isLoading: false,
});
console.log(error);
}
}
// Get Profile Properties
//
private _getProfileCardProperties = async (): Promise<IListItem[]> => {
const _listItems: IListItem[] = [];
const { getProfileCardProperties } = await useProfileCardProperties();
const _profileCardProperties: IProfileCardProperty[] = await getProfileCardProperties(
this.msGrapClient,
this.organizationId
);
if (_profileCardProperties.length > 0) {
for (const profileCardProperty of _profileCardProperties) {
_listItems.push({
key: profileCardProperty.directoryPropertyName,
displayAttribute: profileCardProperty.directoryPropertyName,
displayName: profileCardProperty.annotations[0].displayName,
localizations: profileCardProperty.annotations[0].localizations.length.toString(),
});
}
}
return _listItems;
}
// On Column Click
private _onColumnClick = (
ev: React.MouseEvent<HTMLElement>,
column: IColumn
): void => {
const { listFields, listItems } = this.state;
const newlistFields: IColumn[] = listFields.slice();
const currColumn: IColumn = newlistFields.filter(
(currCol) => column.key === currCol.key
)[0];
newlistFields.forEach((newCol: IColumn) => {
if (newCol === currColumn) {
currColumn.isSortedDescending = !currColumn.isSortedDescending;
currColumn.isSorted = true;
} else {
newCol.isSorted = false;
newCol.isSortedDescending = true;
}
});
const newItems = this._copyAndSort(
listItems,
currColumn.fieldName!,
currColumn.isSortedDescending
);
this.setState({
listFields: newlistFields,
listItems: newItems,
});
}
private _copyAndSort<T>(
items: T[],
columnKey: string,
isSortedDescending?: boolean
): T[] {
const key = columnKey as keyof T;
return items
.slice(0)
.sort((a: T, b: T) =>
(isSortedDescending ? a[key] < b[key] : a[key] > b[key]) ? 1 : -1
);
}
// Callback from ListCommand
private _onActionSelected = (option: string) => {
switch (option) {
case "New":
this.setState({
displayNewPanel: true,
});
break;
case "Edit":
this.setState({
displayEditPanel: true,
});
break;
case "Delete":
this.setState({
displayDeletePanel: true,
});
break;
case "Refresh":
this._onRefresh();
break;
default:
break;
}
}
// Reset sort Order columns to default
private _resetSortOrder = () => {
const { listFields } = this.state;
let _copyListFields: IColumn[] = [];
// Reset Sorted Fields
for (const listField of listFields) {
if (listField.fieldName == "displayAttribute") {
_copyListFields.push({
...listField,
isSorted: true,
isSortedDescending: false,
});
} else {
_copyListFields.push({
...listField,
isSorted: false,
isSortedDescending: false,
});
}
}
this.setState({ listFields: _copyListFields });
}
// On Refresh List
private _onRefresh = async () => {
this._resetSortOrder();
this._selection.setAllSelected(false);
this.setState({ isLoading: true, hasError: false, errorMessage: null });
const _listItems = await this._getProfileCardProperties();
// update Application context
this.applicationContext = {
...this.applicationContext,
listItems: _listItems,
};
// update State
this.setState({
listItems: _listItems,
selectedItem: undefined,
isLoading: false,
});
}
// On Dismiss Panel
private _onPanelDismiss = async (refresh: boolean) => {
if (refresh) {
this.setState({
displayEditPanel: false,
displayNewPanel: false,
displayDeletePanel: false,
});
// refresh List
await this._onRefresh();
} else {
this.setState({
displayEditPanel: false,
displayNewPanel: false,
displayDeletePanel: false,
});
}
}
// Search List
private _onSearch = async (value: string) => {
const { listItems } = this.applicationContext; // gloabal Items store in Application Context
let _filteredList: IListItem[] = [];
// blank value refresh the list
if (!value) {
_filteredList = listItems.slice();
} else {
// Filter
_filteredList = listItems.filter((item: IListItem) => {
if (
item.displayAttribute
.toLocaleLowerCase()
.indexOf(value.toLowerCase()) !== -1
) {
return item;
} else {
if (
item.displayName.toLowerCase().indexOf(value.toLowerCase()) !== -1
) {
return item;
} else {
return; // don't exists
}
}
});
}
this._resetSortOrder();
this._selection.setAllSelected(false);
this.setState({ listItems: _filteredList });
}
// Render Component
public render(): React.ReactElement<IManageProfileCardPropertiesProps> {
const {
hasError,
errorMessage,
listItems,
listFields,
selectedItem,
displayDeletePanel,
displayEditPanel,
displayNewPanel,
isLoading,
} = this.state;
// Has Error
if (hasError) {
return (
<MessageBar messageBarType={MessageBarType.error}>
{errorMessage}
</MessageBar>
);
}
// Is loading
if (isLoading) {
return (
<div style={{ paddingTop: 40 }}>
<Spinner size={SpinnerSize.medium} label={strings.LoadingText} />
</div>
);
}
// Render
return (
<AppContext.Provider value={this.applicationContext}>
<Customizer settings={{ theme: this.props.themeVariant }}>
<WebPartTitle
displayMode={this.props.displayMode}
title={this.props.title}
updateProperty={this.props.updateProperty}
/>
<ListCommandBar
onSearch={this._onSearch}
onActionSelected={this._onActionSelected}
selectedItem={selectedItem}
></ListCommandBar>
<DetailsList
items={listItems}
selection={this._selection}
columns={listFields}
selectionMode={SelectionMode.single}
setKey="prf"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
/>
{displayNewPanel && (
<AddProfileCardProperty
displayPanel={displayNewPanel}
onDismiss={this._onPanelDismiss}
></AddProfileCardProperty>
)}
{displayEditPanel && (
<EditProfileCardProperty
displayPanel={displayEditPanel}
directoryPropertyName={selectedItem.key}
onDismiss={this._onPanelDismiss}
></EditProfileCardProperty>
)}
{displayDeletePanel && (
<DeleteProfileCardProperty
displayPanel={displayDeletePanel}
directoryPropertyName={selectedItem.key}
onDismiss={this._onPanelDismiss}
></DeleteProfileCardProperty>
)}
</Customizer>
</AppContext.Provider>
);
}
} | the_stack |
import {
IExecuteFunctions,
} from 'n8n-core';
import {
IDataObject,
ILoadOptionsFunctions,
INodeExecutionData,
INodeParameters,
INodePropertyOptions,
INodeType,
INodeTypeDescription,
NodeApiError,
NodeOperationError,
} from 'n8n-workflow';
import {
URL,
} from 'url';
import {
awsApiRequestSOAP,
} from '../GenericFunctions';
import {
pascalCase,
} from 'change-case';
export class AwsSqs implements INodeType {
description: INodeTypeDescription = {
displayName: 'AWS SQS',
name: 'awsSqs',
icon: 'file:sqs.svg',
group: ['output'],
version: 1,
subtitle: `={{$parameter["operation"]}}`,
description: 'Sends messages to AWS SQS',
defaults: {
name: 'AWS SQS',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'aws',
required: true,
},
],
properties: [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
options: [
{
name: 'Send message',
value: 'sendMessage',
description: 'Send a message to a queue.',
},
],
default: 'sendMessage',
description: 'The operation to perform.',
},
{
displayName: 'Queue',
name: 'queue',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getQueues',
},
displayOptions: {
show: {
operation: [
'sendMessage',
],
},
},
options: [],
default: '',
required: true,
description: 'Queue to send a message to.',
},
{
displayName: 'Queue Type',
name: 'queueType',
type: 'options',
options: [
{
name: 'FIFO',
value: 'fifo',
description: 'FIFO SQS queue.',
},
{
name: 'Standard',
value: 'standard',
description: 'Standard SQS queue.',
},
],
default: 'standard',
description: 'The operation to perform.',
},
{
displayName: 'Send Input Data',
name: 'sendInputData',
type: 'boolean',
default: true,
description: 'Send the data the node receives as JSON to SQS.',
},
{
displayName: 'Message',
name: 'message',
type: 'string',
displayOptions: {
show: {
operation: [
'sendMessage',
],
sendInputData: [
false,
],
},
},
required: true,
typeOptions: {
alwaysOpenEditWindow: true,
},
default: '',
description: 'Message to send to the queue.',
},
{
displayName: 'Message Group ID',
name: 'messageGroupId',
type: 'string',
default: '',
description: 'Tag that specifies that a message belongs to a specific message group. Applies only to FIFO (first-in-first-out) queues.',
displayOptions: {
show: {
queueType: [
'fifo',
],
},
},
required: true,
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
displayOptions: {
show: {
operation: [
'sendMessage',
],
},
},
default: {},
placeholder: 'Add Option',
options: [
{
displayName: 'Delay Seconds',
name: 'delaySeconds',
type: 'number',
displayOptions: {
show: {
'/queueType': [
'standard',
],
},
},
description: 'How long, in seconds, to delay a message for.',
default: 0,
typeOptions: {
minValue: 0,
maxValue: 900,
},
},
{
displayName: 'Message Attributes',
name: 'messageAttributes',
placeholder: 'Add Attribute',
type: 'fixedCollection',
typeOptions: {
multipleValues: true,
},
description: 'Attributes to set.',
default: {},
options: [
{
name: 'binary',
displayName: 'Binary',
values: [
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
description: 'Name of the attribute.',
},
{
displayName: 'Property Name',
name: 'dataPropertyName',
type: 'string',
default: 'data',
description: 'Name of the binary property which contains the data for the message attribute.',
},
],
},
{
name: 'number',
displayName: 'Number',
values: [
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
description: 'Name of the attribute.',
},
{
displayName: 'Value',
name: 'value',
type: 'number',
default: 0,
description: 'Number value of the attribute.',
},
],
},
{
name: 'string',
displayName: 'String',
values: [
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
description: 'Name of the attribute.',
},
{
displayName: 'Value',
name: 'value',
type: 'string',
default: '',
description: 'String value of attribute.',
},
],
},
],
},
{
displayName: 'Message Deduplication ID',
name: 'messageDeduplicationId',
type: 'string',
default: '',
description: 'Token used for deduplication of sent messages. Applies only to FIFO (first-in-first-out) queues.',
displayOptions: {
show: {
'/queueType': [
'fifo',
],
},
},
},
],
},
],
};
methods = {
loadOptions: {
// Get all the available queues to display them to user so that it can be selected easily
async getQueues(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
const params = [
'Version=2012-11-05',
`Action=ListQueues`,
];
let data;
try {
// loads first 1000 queues from SQS
data = await awsApiRequestSOAP.call(this, 'sqs', 'GET', `?${params.join('&')}`);
} catch (error) {
throw new NodeApiError(this.getNode(), error);
}
let queues = data.ListQueuesResponse.ListQueuesResult.QueueUrl;
if (!queues) {
return [];
}
if (!Array.isArray(queues)) {
// If user has only a single queue no array get returned so we make
// one manually to be able to process everything identically
queues = [queues];
}
return queues.map((queueUrl: string) => {
const urlParts = queueUrl.split('/');
const name = urlParts[urlParts.length - 1];
return {
name,
value: queueUrl,
};
});
},
},
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const returnData: IDataObject[] = [];
const operation = this.getNodeParameter('operation', 0) as string;
for (let i = 0; i < items.length; i++) {
try {
const queueUrl = this.getNodeParameter('queue', i) as string;
const queuePath = new URL(queueUrl).pathname;
const params = [
'Version=2012-11-05',
`Action=${pascalCase(operation)}`,
];
const options = this.getNodeParameter('options', i, {}) as IDataObject;
const sendInputData = this.getNodeParameter('sendInputData', i) as boolean;
const message = sendInputData ? JSON.stringify(items[i].json) : this.getNodeParameter('message', i) as string;
params.push(`MessageBody=${message}`);
if (options.delaySeconds) {
params.push(`DelaySeconds=${options.delaySeconds}`);
}
const queueType = this.getNodeParameter('queueType', i, {}) as string;
if (queueType === 'fifo') {
const messageDeduplicationId = this.getNodeParameter('options.messageDeduplicationId', i, '') as string;
if (messageDeduplicationId) {
params.push(`MessageDeduplicationId=${messageDeduplicationId}`);
}
const messageGroupId = this.getNodeParameter('messageGroupId', i) as string;
if (messageGroupId) {
params.push(`MessageGroupId=${messageGroupId}`);
}
}
let attributeCount = 0;
// Add string values
(this.getNodeParameter('options.messageAttributes.string', i, []) as INodeParameters[]).forEach((attribute) => {
attributeCount++;
params.push(`MessageAttribute.${attributeCount}.Name=${attribute.name}`);
params.push(`MessageAttribute.${attributeCount}.Value.StringValue=${attribute.value}`);
params.push(`MessageAttribute.${attributeCount}.Value.DataType=String`);
});
// Add binary values
(this.getNodeParameter('options.messageAttributes.binary', i, []) as INodeParameters[]).forEach((attribute) => {
attributeCount++;
const dataPropertyName = attribute.dataPropertyName as string;
const item = items[i];
if (item.binary === undefined) {
throw new NodeOperationError(this.getNode(), 'No binary data set. So message attribute cannot be added!');
}
if (item.binary[dataPropertyName] === undefined) {
throw new NodeOperationError(this.getNode(), `The binary property "${dataPropertyName}" does not exist. So message attribute cannot be added!`);
}
const binaryData = item.binary[dataPropertyName].data;
params.push(`MessageAttribute.${attributeCount}.Name=${attribute.name}`);
params.push(`MessageAttribute.${attributeCount}.Value.BinaryValue=${binaryData}`);
params.push(`MessageAttribute.${attributeCount}.Value.DataType=Binary`);
});
// Add number values
(this.getNodeParameter('options.messageAttributes.number', i, []) as INodeParameters[]).forEach((attribute) => {
attributeCount++;
params.push(`MessageAttribute.${attributeCount}.Name=${attribute.name}`);
params.push(`MessageAttribute.${attributeCount}.Value.StringValue=${attribute.value}`);
params.push(`MessageAttribute.${attributeCount}.Value.DataType=Number`);
});
let responseData;
try {
responseData = await awsApiRequestSOAP.call(this, 'sqs', 'GET', `${queuePath}?${params.join('&')}`);
} catch (error) {
throw new NodeApiError(this.getNode(), error);
}
const result = responseData.SendMessageResponse.SendMessageResult;
returnData.push(result as IDataObject);
} catch (error) {
if (this.continueOnFail()) {
returnData.push({ error: error.description });
continue;
}
throw error;
}
}
return [this.helpers.returnJsonArray(returnData)];
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/managersMappers";
import * as Parameters from "../models/parameters";
import { StorSimpleManagementClientContext } from "../storSimpleManagementClientContext";
/** Class representing a Managers. */
export class Managers {
private readonly client: StorSimpleManagementClientContext;
/**
* Create a Managers.
* @param {StorSimpleManagementClientContext} client Reference to the service client.
*/
constructor(client: StorSimpleManagementClientContext) {
this.client = client;
}
/**
* Retrieves all the managers in a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.ManagersListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.ManagersListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.ManagerList>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ManagerList>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ManagerList>, callback?: msRest.ServiceCallback<Models.ManagerList>): Promise<Models.ManagersListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ManagersListResponse>;
}
/**
* Retrieves all the managers in a resource group.
* @param resourceGroupName The resource group name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersListByResourceGroupResponse>;
/**
* @param resourceGroupName The resource group name
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ManagerList>): void;
/**
* @param resourceGroupName The resource group name
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ManagerList>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ManagerList>, callback?: msRest.ServiceCallback<Models.ManagerList>): Promise<Models.ManagersListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.ManagersListByResourceGroupResponse>;
}
/**
* Returns the properties of the specified manager name.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersGetResponse>
*/
get(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersGetResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
get(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.Manager>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Manager>): void;
get(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Manager>, callback?: msRest.ServiceCallback<Models.Manager>): Promise<Models.ManagersGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
getOperationSpec,
callback) as Promise<Models.ManagersGetResponse>;
}
/**
* Creates or updates the manager.
* @param manager The manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersCreateOrUpdateResponse>
*/
createOrUpdate(manager: Models.Manager, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersCreateOrUpdateResponse>;
/**
* @param manager The manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
createOrUpdate(manager: Models.Manager, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.Manager>): void;
/**
* @param manager The manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(manager: Models.Manager, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Manager>): void;
createOrUpdate(manager: Models.Manager, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Manager>, callback?: msRest.ServiceCallback<Models.Manager>): Promise<Models.ManagersCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
manager,
resourceGroupName,
managerName,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.ManagersCreateOrUpdateResponse>;
}
/**
* Deletes the manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Updates the StorSimple Manager.
* @param parameters The manager update parameters.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersUpdateResponse>
*/
update(parameters: Models.ManagerPatch, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersUpdateResponse>;
/**
* @param parameters The manager update parameters.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
update(parameters: Models.ManagerPatch, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.Manager>): void;
/**
* @param parameters The manager update parameters.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
update(parameters: Models.ManagerPatch, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Manager>): void;
update(parameters: Models.ManagerPatch, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Manager>, callback?: msRest.ServiceCallback<Models.Manager>): Promise<Models.ManagersUpdateResponse> {
return this.client.sendOperationRequest(
{
parameters,
resourceGroupName,
managerName,
options
},
updateOperationSpec,
callback) as Promise<Models.ManagersUpdateResponse>;
}
/**
* Upload Vault Cred Certificate.
* Returns UploadCertificateResponse
* @param certificateName Certificate Name
* @param uploadCertificateRequestrequest UploadCertificateRequest Request
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersUploadRegistrationCertificateResponse>
*/
uploadRegistrationCertificate(certificateName: string, uploadCertificateRequestrequest: Models.UploadCertificateRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersUploadRegistrationCertificateResponse>;
/**
* @param certificateName Certificate Name
* @param uploadCertificateRequestrequest UploadCertificateRequest Request
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
uploadRegistrationCertificate(certificateName: string, uploadCertificateRequestrequest: Models.UploadCertificateRequest, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.UploadCertificateResponse>): void;
/**
* @param certificateName Certificate Name
* @param uploadCertificateRequestrequest UploadCertificateRequest Request
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
uploadRegistrationCertificate(certificateName: string, uploadCertificateRequestrequest: Models.UploadCertificateRequest, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.UploadCertificateResponse>): void;
uploadRegistrationCertificate(certificateName: string, uploadCertificateRequestrequest: Models.UploadCertificateRequest, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.UploadCertificateResponse>, callback?: msRest.ServiceCallback<Models.UploadCertificateResponse>): Promise<Models.ManagersUploadRegistrationCertificateResponse> {
return this.client.sendOperationRequest(
{
certificateName,
uploadCertificateRequestrequest,
resourceGroupName,
managerName,
options
},
uploadRegistrationCertificateOperationSpec,
callback) as Promise<Models.ManagersUploadRegistrationCertificateResponse>;
}
/**
* Returns the encryption settings of the manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersGetEncryptionSettingsResponse>
*/
getEncryptionSettings(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersGetEncryptionSettingsResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
getEncryptionSettings(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.EncryptionSettings>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
getEncryptionSettings(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.EncryptionSettings>): void;
getEncryptionSettings(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.EncryptionSettings>, callback?: msRest.ServiceCallback<Models.EncryptionSettings>): Promise<Models.ManagersGetEncryptionSettingsResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
getEncryptionSettingsOperationSpec,
callback) as Promise<Models.ManagersGetEncryptionSettingsResponse>;
}
/**
* Returns the extended information of the specified manager name.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersGetExtendedInfoResponse>
*/
getExtendedInfo(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersGetExtendedInfoResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
getExtendedInfo(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
getExtendedInfo(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
getExtendedInfo(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ManagerExtendedInfo>, callback?: msRest.ServiceCallback<Models.ManagerExtendedInfo>): Promise<Models.ManagersGetExtendedInfoResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
getExtendedInfoOperationSpec,
callback) as Promise<Models.ManagersGetExtendedInfoResponse>;
}
/**
* Creates the extended info of the manager.
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersCreateExtendedInfoResponse>
*/
createExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersCreateExtendedInfoResponse>;
/**
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
createExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
/**
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
createExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
createExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ManagerExtendedInfo>, callback?: msRest.ServiceCallback<Models.ManagerExtendedInfo>): Promise<Models.ManagersCreateExtendedInfoResponse> {
return this.client.sendOperationRequest(
{
managerExtendedInfo,
resourceGroupName,
managerName,
options
},
createExtendedInfoOperationSpec,
callback) as Promise<Models.ManagersCreateExtendedInfoResponse>;
}
/**
* Deletes the extended info of the manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteExtendedInfo(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
deleteExtendedInfo(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
deleteExtendedInfo(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteExtendedInfo(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
deleteExtendedInfoOperationSpec,
callback);
}
/**
* Updates the extended info of the manager.
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param ifMatch Pass the ETag of ExtendedInfo fetched from GET call
* @param [options] The optional parameters
* @returns Promise<Models.ManagersUpdateExtendedInfoResponse>
*/
updateExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersUpdateExtendedInfoResponse>;
/**
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param ifMatch Pass the ETag of ExtendedInfo fetched from GET call
* @param callback The callback
*/
updateExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
/**
* @param managerExtendedInfo The manager extended information.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param ifMatch Pass the ETag of ExtendedInfo fetched from GET call
* @param options The optional parameters
* @param callback The callback
*/
updateExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ManagerExtendedInfo>): void;
updateExtendedInfo(managerExtendedInfo: Models.ManagerExtendedInfo, resourceGroupName: string, managerName: string, ifMatch: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ManagerExtendedInfo>, callback?: msRest.ServiceCallback<Models.ManagerExtendedInfo>): Promise<Models.ManagersUpdateExtendedInfoResponse> {
return this.client.sendOperationRequest(
{
managerExtendedInfo,
resourceGroupName,
managerName,
ifMatch,
options
},
updateExtendedInfoOperationSpec,
callback) as Promise<Models.ManagersUpdateExtendedInfoResponse>;
}
/**
* Returns the symmetric encryption key of the manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersGetEncryptionKeyResponse>
*/
getEncryptionKey(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersGetEncryptionKeyResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
getEncryptionKey(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.SymmetricEncryptedSecret>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
getEncryptionKey(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SymmetricEncryptedSecret>): void;
getEncryptionKey(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SymmetricEncryptedSecret>, callback?: msRest.ServiceCallback<Models.SymmetricEncryptedSecret>): Promise<Models.ManagersGetEncryptionKeyResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
getEncryptionKeyOperationSpec,
callback) as Promise<Models.ManagersGetEncryptionKeyResponse>;
}
/**
* Gets the manager metrics
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersListMetricsResponse>
*/
listMetrics(resourceGroupName: string, managerName: string, options?: Models.ManagersListMetricsOptionalParams): Promise<Models.ManagersListMetricsResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
listMetrics(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.MetricList>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
listMetrics(resourceGroupName: string, managerName: string, options: Models.ManagersListMetricsOptionalParams, callback: msRest.ServiceCallback<Models.MetricList>): void;
listMetrics(resourceGroupName: string, managerName: string, options?: Models.ManagersListMetricsOptionalParams | msRest.ServiceCallback<Models.MetricList>, callback?: msRest.ServiceCallback<Models.MetricList>): Promise<Models.ManagersListMetricsResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
listMetricsOperationSpec,
callback) as Promise<Models.ManagersListMetricsResponse>;
}
/**
* Retrieves metric definition of all metrics aggregated at manager.
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param [options] The optional parameters
* @returns Promise<Models.ManagersListMetricDefinitionResponse>
*/
listMetricDefinition(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.ManagersListMetricDefinitionResponse>;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param callback The callback
*/
listMetricDefinition(resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.MetricDefinitionList>): void;
/**
* @param resourceGroupName The resource group name
* @param managerName The manager name
* @param options The optional parameters
* @param callback The callback
*/
listMetricDefinition(resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.MetricDefinitionList>): void;
listMetricDefinition(resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.MetricDefinitionList>, callback?: msRest.ServiceCallback<Models.MetricDefinitionList>): Promise<Models.ManagersListMetricDefinitionResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
managerName,
options
},
listMetricDefinitionOperationSpec,
callback) as Promise<Models.ManagersListMetricDefinitionResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.StorSimple/managers",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ManagerList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ManagerList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Manager
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "manager",
mapper: {
...Mappers.Manager,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Manager
},
201: {
bodyMapper: Mappers.Manager
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ManagerPatch,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Manager
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const uploadRegistrationCertificateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/certificates/{certificateName}",
urlParameters: [
Parameters.certificateName,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "uploadCertificateRequestrequest",
mapper: {
...Mappers.UploadCertificateRequest,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.UploadCertificateResponse
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getEncryptionSettingsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/encryptionSettings/default",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.EncryptionSettings
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getExtendedInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.ManagerExtendedInfo
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const createExtendedInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "managerExtendedInfo",
mapper: {
...Mappers.ManagerExtendedInfo,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ManagerExtendedInfo
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const deleteExtendedInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
204: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const updateExtendedInfoOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "managerExtendedInfo",
mapper: {
...Mappers.ManagerExtendedInfo,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ManagerExtendedInfo
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const getEncryptionKeyOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/getEncryptionKey",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SymmetricEncryptedSecret
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listMetricsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/metrics",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MetricList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
};
const listMetricDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/metricsDefinitions",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.managerName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.MetricDefinitionList
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
serializer
}; | the_stack |
import * as fs from 'fs-extra'
import { readdir } from 'fs'
import { PassThrough } from 'stream'
import { BadPathError, InvalidInputError, DoesNotExist } from '../errors'
import * as Path from 'path'
import * as crypto from 'crypto'
import {
ListFilesResult, PerformWriteArgs, WriteResult, PerformDeleteArgs, PerformRenameArgs,
PerformStatArgs, StatResult, PerformReadArgs, ReadResult, PerformListFilesArgs,
ListFilesStatResult, ListFileStatResult, DriverStatics, DriverModel
} from '../driverModel'
import { pipelineAsync, logger, dateToUnixTimeSeconds } from '../utils'
export interface DISK_CONFIG_TYPE {
diskSettings: { storageRootDirectory?: string },
bucket?: string,
pageSize?: number,
readURL: string
}
const METADATA_DIRNAME = '.gaia-metadata'
class DiskDriver implements DriverModel {
storageRootDirectory: string
readURL: string
pageSize: number
initPromise: Promise<void>
supportsETagMatching = false;
static getConfigInformation() {
const envVars: any = {}
if (process.env['GAIA_DISK_STORAGE_ROOT_DIR']) {
const diskSettings = { storageRootDirectory: process.env['GAIA_DISK_STORAGE_ROOT_DIR'] }
envVars['diskSettings'] = diskSettings
}
return {
defaults: { diskSettings: { storageRootDirectory: undefined as any } },
envVars
}
}
constructor (config: DISK_CONFIG_TYPE) {
if (!config.readURL) {
throw new Error('Config is missing readURL')
}
if (!config.diskSettings.storageRootDirectory) {
throw new Error('Config is missing storageRootDirectory')
}
if (config.bucket) {
logger.warn(`The disk driver does not use the "config.bucket" variable. It is set to ${config.bucket}`)
}
this.storageRootDirectory = Path.resolve(Path.normalize(config.diskSettings.storageRootDirectory))
this.readURL = config.readURL
if (!this.readURL.endsWith('/')) {
// must end in /
this.readURL = `${this.readURL}/`
}
this.pageSize = config.pageSize ? config.pageSize : 100
this.initPromise = fs.ensureDir(this.storageRootDirectory)
}
ensureInitialized() {
return this.initPromise
}
dispose() {
return Promise.resolve()
}
static isPathValid(path: string){
if (path.includes('..')) {
return false
}
if (path.endsWith('/')) {
return false
}
return true
}
getReadURLPrefix () {
return this.readURL
}
async mkdirs(path: string) {
const normalizedPath = Path.normalize(path)
try {
// Ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p.
const wasCreated: any = await fs.ensureDir(normalizedPath)
if (wasCreated) {
logger.debug(`mkdir ${normalizedPath}`)
}
} catch (error) {
logger.error(`Error ensuring directory exists: ${error}`)
throw error
}
}
async findAllFiles(listPath: string): Promise<string[]> {
// returns a list of files prefixed by listPath
const dirEntries: fs.Dirent[] = await new Promise((resolve, reject) => {
readdir(listPath, {withFileTypes: true}, (err, files) => {
if (err) {
reject(err)
} else {
resolve(files)
}
})
})
const fileNames: string[] = []
for (const dirEntry of dirEntries) {
const fileOrDir = `${listPath}${Path.sep}${dirEntry.name}`
if (dirEntry.isDirectory()) {
const childEntries = await this.findAllFiles(fileOrDir)
fileNames.push(...childEntries)
} else {
fileNames.push(Path.posix.normalize(fileOrDir))
}
}
return fileNames
}
async listFilesInDirectory(listPath: string, pageNum: number, pageSize?: number): Promise<ListFilesResult> {
pageSize = pageSize || this.pageSize
const files = await this.findAllFiles(listPath)
const entries = files.map(file => file.slice(listPath.length + 1))
const sliced = entries.slice(pageNum * pageSize, (pageNum + 1) * pageSize)
const page = sliced.length === entries.length ? null : `${pageNum + 1}`
return {
entries: sliced,
page: page
}
}
async listFilesInternal(args: PerformListFilesArgs): Promise<ListFilesResult> {
// returns {'entries': [...], 'page': next_page}
let pageNum
const listPath = Path.normalize(`${this.storageRootDirectory}/${args.pathPrefix}`)
if (!await fs.pathExists(listPath)) {
// nope
const emptyResponse: ListFilesResult = {
entries: [],
page: null
}
return emptyResponse
}
try {
if (args.page) {
if (!(/^[0-9]+$/.exec(args.page))) {
throw new Error('Invalid page number')
}
pageNum = parseInt(args.page)
} else {
pageNum = 0
}
const stat = await fs.stat(listPath)
if (!stat.isDirectory()) {
// All the cloud drivers return a single empty entry in this situation
return { entries: [''], page: null }
}
} catch(e) {
throw new Error('Invalid arguments: invalid page or not a directory')
}
const listResult = await this.listFilesInDirectory(listPath, pageNum, args.pageSize)
return listResult
}
async listFiles(args: PerformListFilesArgs): Promise<ListFilesResult> {
return await this.listFilesInternal(args)
}
async listFilesStat(args: PerformListFilesArgs): Promise<ListFilesStatResult> {
const filePathResult = await this.listFilesInternal(args)
const fileStats: ListFileStatResult[] = []
for (const file of filePathResult.entries) {
const fileStat = await this.performStat({storageTopLevel: args.pathPrefix, path: file})
fileStats.push({
...fileStat,
name: file,
exists: true
})
}
return {
page: filePathResult.page,
entries: fileStats
}
}
getFullFilePathInfo(args: {storageTopLevel: string, path: string} ) {
if (!args.storageTopLevel) {
throw new BadPathError('Invalid Path')
}
if (!DiskDriver.isPathValid(args.path) || !DiskDriver.isPathValid(args.storageTopLevel)) {
throw new BadPathError('Invalid Path')
}
const abspath = Path.join(this.storageRootDirectory, args.storageTopLevel, args.path)
// too long?
if (abspath.length > 4096) {
throw new BadPathError('Path is too long')
}
const dirparts = abspath.split(Path.sep).filter((p) => p.length > 0)
// can't be too deep
if (dirparts.length > 100) {
throw new BadPathError('Path is too deep')
}
// remember content type in $storageRootDir/.gaia-metadata/$address/$path
// (i.e. these files are outside the address bucket, and are thus hidden)
const metaDataFilePath = Path.join(
this.storageRootDirectory, METADATA_DIRNAME, args.storageTopLevel, args.path)
return { absoluteFilePath: abspath, metaDataFilePath }
}
async performWrite(args: PerformWriteArgs): Promise<WriteResult> {
const contentType = args.contentType
if (contentType && contentType.length > 1024) {
// no way this is valid
throw new InvalidInputError('Invalid content-type')
}
const { absoluteFilePath, metaDataFilePath } = this.getFullFilePathInfo(args)
const absdirname = Path.dirname(absoluteFilePath)
await this.mkdirs(absdirname)
const hash = crypto.createHash('md5')
const hashMonitoredStream = new PassThrough({
transform: (chunk: Buffer, _encoding, callback) => {
hash.update(chunk)
// Pass the chunk Buffer through, untouched. This takes the fast
// path through the stream pipe lib.
callback(null, chunk)
}
})
const hashMonitorPipeline = pipelineAsync(args.stream, hashMonitoredStream)
const writePipe = fs.createWriteStream(absoluteFilePath, { mode: 0o600, flags: 'w' })
const fileStreamPipeline = pipelineAsync(hashMonitoredStream, writePipe)
await Promise.all([hashMonitorPipeline, fileStreamPipeline])
const etag = hash.digest('hex')
const metaDataDirPath = Path.dirname(metaDataFilePath)
await this.mkdirs(metaDataDirPath)
await fs.writeFile(
metaDataFilePath,
JSON.stringify({ 'content-type': contentType, etag }), { mode: 0o600 })
return {
publicURL: `${this.readURL}${args.storageTopLevel}/${args.path}`,
etag
}
}
async performDelete(args: PerformDeleteArgs): Promise<void> {
const { absoluteFilePath, metaDataFilePath } = this.getFullFilePathInfo(args)
let stat: fs.Stats
try {
stat = await fs.stat(absoluteFilePath)
} catch (error) {
if (error.code === 'ENOENT') {
throw new DoesNotExist('File does not exist')
}
/* istanbul ignore next */
throw error
}
if (!stat.isFile()) {
// Disk driver is special here in that it mirrors the behavior of cloud storage APIs.
// Directories are not first-class objects in blob storages, and so they will
// simply return 404s for the blob name even if the name happens to be a prefix
// (pseudo-directory) of existing blobs.
throw new DoesNotExist('Path is not a file')
}
await fs.unlink(absoluteFilePath)
await fs.unlink(metaDataFilePath)
}
static async parseFileStat(stat: fs.Stats, metaDataFilePath: string): Promise<StatResult> {
const metaDataJsonStr = await fs.readFile(metaDataFilePath, 'utf8')
const metaDataJson = JSON.parse(metaDataJsonStr)
const contentType = metaDataJson['content-type']
const etag = metaDataJson['etag']
const lastModified = dateToUnixTimeSeconds(stat.mtime)
const result: StatResult = {
exists: true,
etag,
contentLength: stat.size,
contentType,
lastModifiedDate: lastModified
}
return result
}
async performRead(args: PerformReadArgs): Promise<ReadResult> {
const { absoluteFilePath, metaDataFilePath } = this.getFullFilePathInfo(args)
let stat: fs.Stats
try {
stat = await fs.stat(absoluteFilePath)
} catch (error) {
if (error.code === 'ENOENT') {
throw new DoesNotExist('File does not exist')
}
/* istanbul ignore next */
throw error
}
if (!stat.isFile()) {
// Disk driver is special here in that it mirrors the behavior of cloud storage APIs.
// Directories are not first-class objects in blob storages, and so they will
// simply return 404s for the blob name even if the name happens to be a prefix
// (pseudo-directory) of existing blobs.
throw new DoesNotExist('File does not exist')
}
const fileStat = await DiskDriver.parseFileStat(stat, metaDataFilePath)
const dataStream = fs.createReadStream(absoluteFilePath)
const result: ReadResult = {
...fileStat,
exists: true,
data: dataStream
}
return result
}
async performStat(args: PerformStatArgs): Promise<StatResult> {
const { absoluteFilePath, metaDataFilePath } = this.getFullFilePathInfo(args)
let stat: fs.Stats
try {
stat = await fs.stat(absoluteFilePath)
} catch (error) {
if (error.code === 'ENOENT') {
const result = {
exists: false
} as StatResult
return result
}
/* istanbul ignore next */
throw error
}
if (!stat.isFile()) {
// Disk driver is special here in that it mirrors the behavior of cloud storage APIs.
// Directories are not first-class objects in blob storages, and so they will
// simply return 404s for the blob name even if the name happens to be a prefix
// (pseudo-directory) of existing blobs.
const result = {
exists: false
} as StatResult
return result
}
const result = await DiskDriver.parseFileStat(stat, metaDataFilePath)
return result
}
async performRename(args: PerformRenameArgs): Promise<void> {
const pathsOrig = this.getFullFilePathInfo(args)
const pathsNew = this.getFullFilePathInfo({
storageTopLevel: args.storageTopLevel,
path: args.newPath
})
let statOrig: fs.Stats
try {
statOrig = await fs.stat(pathsOrig.absoluteFilePath)
} catch (error) {
if (error.code === 'ENOENT') {
throw new DoesNotExist('File does not exist')
}
/* istanbul ignore next */
throw error
}
if (!statOrig.isFile()) {
throw new DoesNotExist('Path is not a file')
}
let statNew: fs.Stats
try {
statNew = await fs.stat(pathsNew.absoluteFilePath)
if (!statNew.isFile()) {
throw new DoesNotExist('New path exists and is not a file')
}
} catch (error) {
if (error.code !== 'ENOENT') {
throw new Error(`Unexpected new file location stat error: ${error}`)
}
}
await fs.move(pathsOrig.absoluteFilePath, pathsNew.absoluteFilePath, {overwrite: true})
await fs.move(pathsOrig.metaDataFilePath, pathsNew.metaDataFilePath, {overwrite: true})
}
}
const driver: typeof DiskDriver & DriverStatics = DiskDriver
export default driver | the_stack |
import { Duck } from '../index';
import Scene from './scene';
import Debug from './debug/debug';
import startup from '../helper/startup';
import dprScale from '../helper/dprScale';
import EventEmitter from './events/eventEmitter';
import EVENTS from './events/events';
import detectBrowser from '../utils/detectBrowser';
import smoothOut from '../utils/smoothArray';
import PluginManager from './misc/pluginManager';
import CacheManager from './storage/cacheManager';
/**
* @class Game
* @classdesc Creates a DuckEngine Game
* @description The Game Class. Stores many important methods and properties.
* @since 1.0.0-beta
*/
export default class Game {
/**
* @memberof Game
* @description Game Configuration
* @type Duck.Types.Game.Config
* @since 1.0.0-beta
*/
public readonly config: Duck.Types.Game.Config;
/**
* @memberof Game
* @description The Canvas that is used to render to
* @type HTMLCanvasElement
* @since 1.0.0-beta
*/
public canvas: HTMLCanvasElement;
/**
* @memberof Game
* @description The CanvasRenderingContext2D that is used
* @type CanvasRenderingContext2D
* @since 1.0.0-beta
*/
public ctx: CanvasRenderingContext2D;
/**
* @memberof Game
* @description The Game Stack, holds all Scenes, and the defaultScene key
* @type Duck.Types.Game.Stack
* @since 1.0.0-beta
*/
public stack: Duck.Types.Game.Stack;
/**
* @memberof Game
* @description A reference to the animationFrame
* @type number | undefined
* @since 1.0.0
*/
public animationFrame: number | undefined;
/**
* @memberof Game
* @description A CacheManager instance
* @type CacheManager
* @since 2.0.0
*/
public cacheManager: CacheManager;
/**
* @memberof Game
* @description An array of the last 100 deltaTimes, deltaTime = time since last frame
* @type number[]
* @since 2.0.0
*/
public deltaTimeArray: number[];
/**
* @memberof Game
* @description The time since the last frame
* @type number
* @since 1.0.0
*/
public deltaTime: number;
/**
* @memberof Game
* @description The time since the last frame averaged and smoothed out using Game.deltaTimeArray, applied to velocity of gameobjects
* @type number
* @since 2.0.0
*/
public smoothDeltaTime: number;
protected oldTime: number;
protected now: number;
/**
* @memberof Game
* @description The current fps (Frames per second) that the Game loop is running at
* @type number
* @since 2.0.0
*/
public fps: number;
/**
* @memberof Game
* @description The state of being in fullscreen, determines if the game is in fullscreen or not, changing this value does nothing
* use game.fullscreen and game.unfullscreen to effect this value
* @type boolean
* @since 1.0.0
*/
public isInFullscreen: boolean;
protected oldWidth: number;
protected oldHeight: number;
// methods
/**
* @memberof Game
* @description The scene manager, object that holds methods to add and remove scenes from the Game.stack
* @type{ add: (scenes: Scene[]) => void; remove: (scene: Scene) => void };
* @since 1.0.0-beta
*/
public scenes: {
add: (scenes: Scene[]) => void;
remove: (scene: Scene) => void;
};
/**
* @memberof Game
* @description The state of the game, if it is currently rendering
* @type boolean
* @since 2.0.0
*/
public isRendering: boolean;
/**
* @memberof Game
* @description The state of the game, if it is currently loading
* @type boolean
* @since 2.0.0
*/
public isLoaded: boolean;
/**
* @memberof Game
* @description The source to the splash screen image that is shown during loading
* @type string
* @since 2.0.0
*/
public splashScreen: string;
/**
* @memberof Game
* @description An EventEmitter, used by many classes other than the Game class (also used by Game class)
* @type EventEmitter
* @since 2.0.0
*/
public eventEmitter: EventEmitter;
/**
* @memberof Game
* @description A PluginManager, stores and manages plugins
* @type PluginManager
* @since 2.0.0
*/
public pluginManager: PluginManager;
/**
* @memberof Game
* @description The browser being used
* @type string
* @since 2.0.0
*/
public browser: string;
/**
* @constructor Game
* @description Creates a Game instance
* @param {Duck.Types.Game.Config} config Game Configuration
* @since 1.0.0-beta
*/
constructor(config: Duck.Types.Game.Config) {
console.log(startup);
this.config = config;
if (this.config.canvas === null) {
this.config.canvas = Duck.AutoCanvas();
}
if (!this.config.canvas) {
new Debug.Error(
'You must pass in an HTMLCanvasElement or pass in the return value of Duck.AutoCanvas()!'
);
}
if (this.config.canvas instanceof HTMLCanvasElement) {
this.canvas = this.config.canvas;
this.ctx = this.canvas.getContext('2d') || Duck.AutoCanvas().ctx;
} else {
this.canvas = this.config.canvas.canvas;
this.ctx = this.config.canvas.ctx;
}
this.deltaTimeArray = Array(100).fill(0.0016);
this.deltaTime = 0;
this.smoothDeltaTime = 0;
this.oldTime = 0;
this.now = 0;
this.fps = 0;
this.eventEmitter = new EventEmitter();
this.pluginManager = new PluginManager();
// set scale
if (this.config.scale) {
this.setScale(this.config.scale);
}
// set background
if (this.config.background) {
this.setBackground(this.config.background);
}
// mobile scaling / devicePixelRatio scaling
if (this.config.dprScale) {
dprScale(
this.canvas,
this.ctx,
this.config.scale?.width || this.canvas.width,
this.config.scale?.height || this.canvas.height
);
if (this.config.debug) {
new Debug.Log(
`Scaled with devicePixelRatio of ${window.devicePixelRatio}`
);
}
}
// fullscreen scale
this.isInFullscreen = false;
this.oldWidth = this.canvas.width;
this.oldHeight = this.canvas.height;
// resize listener & smartScale
window.onresize = () => {
if (this.isInFullscreen && this.canvas) {
this.scaleToWindow();
}
if (
this.canvas &&
this.config.smartScale &&
window.devicePixelRatio === 1
) {
if (window.innerWidth <= this.canvas.width) {
this.canvas.width = window.innerWidth;
}
if (window.innerHeight <= this.canvas.height) {
this.canvas.height = window.innerHeight;
}
if (window.innerWidth > this.canvas.width) {
this.canvas.width = this.oldWidth;
}
if (window.innerHeight > this.canvas.height) {
this.canvas.height = this.oldHeight;
}
}
};
this.isRendering = false;
this.isLoaded = false;
// blur and focus listener
window.onfocus = () => {
if (
this.config.pauseRenderingOnBlur &&
!this.config.debugRendering
) {
this.isRendering = true;
this.eventEmitter.emit(EVENTS.GAME.FOCUS);
if (this.config.onResumeRendering) {
this.config.onResumeRendering('windowFocus');
}
}
};
window.onblur = () => {
if (
this.config.pauseRenderingOnBlur &&
!this.config.debugRendering
) {
this.isRendering = false;
this.eventEmitter.emit(EVENTS.GAME.BLUR);
if (this.config.onPauseRendering) {
this.config.onPauseRendering('windowBlur');
}
}
};
if (this.config.focus) {
window.focus();
if (this.config.onResumeRendering) {
this.config.onResumeRendering('gameConfigFocus');
}
}
if (this.config.blur) {
window.blur();
if (this.config.onPauseRendering) {
this.config.onPauseRendering('gameConfigBlur');
}
}
this.splashScreen =
this.config.splashScreen?.img ||
'https://i.ibb.co/bdN4CCN/Logo-Splash.png';
if (this.config.splashScreen?.img === 'default') {
this.splashScreen = 'https://i.ibb.co/bdN4CCN/Logo-Splash.png';
}
// stack
this.stack = {
scenes: [],
defaultScene: this.config.defaultScene,
};
this.cacheManager = new CacheManager();
// browser
this.browser = detectBrowser() as string;
// animation frame
this.animationFrame;
// methods
this.scenes = {
/**
* @memberof Game#scenes
* @description Add a scenes to the Game stack
* @param {Scene[]} scenes Scenes to add to the Game stack
* @since 1.0.0-beta
*/
add: (scenes: Scene[]) => {
scenes.forEach((scene) => {
this.stack.scenes.push(scene);
this.eventEmitter.emit(EVENTS.GAME.SCENE_ADD, scene);
});
},
/**
* @memberof Game#scenes
* @description Removes a scene from the Game stack
* @param {Scene} scene Scene to remove from the Game stack
* @since 1.0.0-beta
*/
remove: (scene: Scene) => {
const f = this.stack.scenes.find(
(_scene) => _scene.key === scene.key
);
if (f) {
this.stack.scenes.splice(
this.stack.scenes.indexOf(scene),
1
);
this.eventEmitter.emit(EVENTS.GAME.SCENE_REMOVE, scene);
}
},
};
}
/**
* @memberof Game
* @description Starts the game loop
* @emits EVENTS.GAME.LOAD_BEGIN
* @emits EVENTS.GAME.DRAW_SPLASH
* @emits EVENTS.GAME.LOAD_SCENE
* @emits EVENTS.GAME.LOAD_FINISH
* @since 1.0.0-beta
*/
public async start() {
this.eventEmitter.emit(EVENTS.GAME.LOAD_BEGIN);
// show loading splash screen
this.eventEmitter.emit(EVENTS.GAME.DRAW_SPLASH);
await this.drawSplashScreen();
// load scenes
for await (const scene of this.stack.scenes) {
// preload assets
await scene.preload();
// create assets
scene.create();
this.eventEmitter.emit(EVENTS.GAME.LOAD_SCENE);
}
// set states
this.isRendering = true;
this.isLoaded = true;
await this.hideSplashScreen();
this.eventEmitter.emit(EVENTS.GAME.LOAD_FINISH);
if (this.config.debug) {
new Debug.Log('Game loaded.');
}
if (this.config.onResumeRendering && !this.config.debugRendering) {
this.config.onResumeRendering('gameStart');
}
this.loop(this);
if (this.config.debug) {
new Debug.Log('Started animation frame.');
}
}
/**
* @memberof Game
* @description Stops the game loop
* @emits EVENTS.GAME.STOP
* @since 1.0.0
*/
public stop() {
if (this.animationFrame) {
cancelAnimationFrame(this.animationFrame);
// set states
this.isRendering = false;
this.isLoaded = false;
if (this.config.onPauseRendering && !this.config.debugRendering) {
this.config.onPauseRendering('gameStop');
}
if (this.config.debug) {
new Debug.Log('Stopped animation frame.');
}
this.eventEmitter.emit(EVENTS.GAME.STOP);
} else {
if (this.config.debug) {
new Debug.Error(
'Cannot stop animation frame. You must start the game loop first.'
);
}
}
}
/**
* @memberof Game
* @description Core loop
* @since 1.0.0-beta
*/
protected loop(self: Game) {
self.clearFrame();
this.now = performance.now();
this.deltaTime = (this.now - this.oldTime) / 1000;
this.fps = 1 / this.deltaTime;
if (this.deltaTimeArray.length >= 100) {
this.deltaTimeArray.shift();
}
this.deltaTimeArray.push(this.deltaTime);
this.smoothDeltaTime = Number(
smoothOut(this.deltaTimeArray, 1).toPrecision(1)
);
if (this.isRendering) {
self.stack.scenes.forEach((scene) => {
if (scene.visible) {
if (scene.currentCamera) {
scene.currentCamera.begin();
}
scene.__tick();
scene.update(this.deltaTime);
// displayList
const depthSorted = scene.displayList.depthSort();
depthSorted.forEach((renderableObject) => {
if (renderableObject.visible) {
renderableObject._draw();
}
});
if (scene.currentCamera) {
scene.currentCamera.end();
}
}
});
}
this.oldTime = this.now;
this.animationFrame = requestAnimationFrame(() => {
self.loop(self);
});
}
/**
* @memberof Game
* @description Draws the splash screen to the canvas by setting the background image
* @since 2.0.0
*/
protected async drawSplashScreen() {
this.canvas.style.backgroundImage = `url('${this.splashScreen}')`;
await this.sleep(this.config.splashScreen?.extraDuration || 0);
}
/**
* @memberof Game
* @description Hides the splash screen to the canvas
* @since 2.0.0
*/
protected async hideSplashScreen() {
this.canvas.style.backgroundImage = 'none';
}
protected sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* @memberof Game
* @description Clears the current frame on the canvas
* @emits EVENTS.GAME.CLEAR_FRAME
* @since 1.0.0
*/
public clearFrame() {
if (this.canvas && this.ctx) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.eventEmitter.emit(EVENTS.GAME.CLEAR_FRAME);
} else {
new Debug.Error('Canvas is undefined');
}
}
/**
* @memberof Game
* @description Sets the scale of the canvas
* @param {Duck.Types.Misc.Scale} scale Scale to set the canvas to
* @emits EVENTS.GAME.SET_SCALE
* @since 1.0.0-beta
*/
public setScale(scale: Duck.Types.Misc.Scale) {
if (this.canvas) {
if (scale.width) {
this.canvas.width = scale.width;
}
if (scale.height) {
this.canvas.height = scale.height;
}
this.eventEmitter.emit(EVENTS.GAME.SET_SCALE, scale);
} else {
new Debug.Error('Cannot setScale to a canvas of undefined.');
}
}
/**
* @memberof Game
* @description Sets the style background color of the canvas
* @param {string} background Background color
* @emits EVENTS.GAME.SET_BACKGROUND
* @since 1.0.0-beta
*/
public setBackground(background: string) {
if (this.canvas) {
this.canvas.style.background = background;
this.eventEmitter.emit(EVENTS.GAME.SET_BACKGROUND, background);
} else {
new Debug.Error(
'Cannot set background of undefined. Canvas is undefined.'
);
}
}
/**
* @memberof Game
* @description Switches the current scene by the key
* @param {string} key Key of the scene to switch from
* @param {string} key2 Key of the scene to switch to
* @emits EVENTS.GAME.SWITCH_SCENE
* @since 1.0.0-beta
*/
public switchScene(key: string, key2: string) {
const f = this.stack.scenes.find((_scene) => _scene.key === key);
const f2 = this.stack.scenes.find((_scene) => _scene.key === key2);
if (f) {
if (f2) {
f.visible = false;
f2.visible = true;
f2.onChange();
this.eventEmitter.emit(EVENTS.GAME.SWITCH_SCENE);
} else {
new Debug.Error(
`Cannot switch to scene with scene key "${key2}. Scene not found."`
);
}
} else {
new Debug.Error(
`Cannot switch from scene from scene key "${key}. Scene not found."`
);
}
}
/**
* @memberof Game
* @description Sets a scene to visible. Keeps the current scene visible
* @param {string} key Key of the scene to show
* @emits EVENTS.GAME.SHOW_SCENE
* @since 1.0.0-beta
*/
public showScene(key: string) {
const f = this.stack.scenes.find((_scene) => _scene.key === key);
if (f) {
f.visible = true;
this.eventEmitter.emit(EVENTS.GAME.SHOW_SCENE);
} else {
new Debug.Error(
`Cannot switch to scene with key "${key}. Scene not found."`
);
}
}
/**
* @memberof Game
* @description Fullscreens the canvas and scales canvas
* @emits EVENTS.GAME.FULLSCREEN
* @since 1.0.0
*/
public fullscreen() {
if (this.canvas && document.fullscreenEnabled) {
this.canvas
.requestFullscreen()
.then(() => {
this.isInFullscreen = true;
if (this.canvas) {
this.scaleToWindow();
}
this.eventEmitter.emit(EVENTS.GAME.FULLSCREEN);
})
.catch(
() =>
new Debug.Error(
'User must interact with the page before fullscreen API can be used.'
)
);
// on un fullscreen
this.canvas.onfullscreenchange = () => {
if (!document.fullscreenElement) {
this.resetScale();
this.isInFullscreen = false;
if (this.config.debug) {
new Debug.Log('Unfullscreen, reset canvas scale.');
}
}
};
}
if (!document.fullscreenEnabled) {
new Debug.Warn(
'Fullscreen is not supported/enabled on this browser.'
);
}
}
/**
* @memberof Game
* @description Unfullscreens the canvas and scales canvas
* @emits EVENTS.GAME.UNFULLSCREEN
* @since 1.0.0
*/
public unfullscreen() {
if (document.fullscreenElement) {
document
.exitFullscreen()
.then(() => {
if (this.canvas) {
this.resetScale();
}
this.eventEmitter.emit(EVENTS.GAME.UNFULLSCREEN);
})
.catch((e) => new Debug.Error(e));
}
}
/**
* @memberof Game
* @description Locks the pointer on the canvas
* @emits EVENTS.GAME.LOCK_POINTER
* @since 1.0.0
*/
public lockPointer() {
if (this.canvas) {
this.canvas.requestPointerLock();
this.eventEmitter.emit(EVENTS.GAME.LOCK_POINTER);
}
}
/**
* @memberof Game
* @description Unlocks the pointer from the canvas
* @emits EVENTS.GAME.UNLOCK_POINTER
* @since 1.0.0
*/
public unlockPointer() {
if (document.pointerLockElement) {
document.exitPointerLock();
this.eventEmitter.emit(EVENTS.GAME.UNLOCK_POINTER);
}
}
/**
* @memberof Game
* @description Resets the canvas scale to before scaled
* @since 1.0.0
*/
public resetScale() {
if (this.canvas) {
if (window.devicePixelRatio === 1) {
this.canvas.width = this.oldWidth;
this.canvas.height = this.oldHeight;
this.canvas.style.width = this.oldWidth + 'px';
this.canvas.style.height = this.oldHeight + 'px';
} else {
this.canvas.width = this.oldWidth / 2;
this.canvas.height = this.oldHeight / 2;
this.canvas.style.width = this.oldWidth / 2 + 'px';
this.canvas.style.height = this.oldHeight / 2 + 'px';
}
if (this.config.dprScale && window.devicePixelRatio !== 1) {
dprScale(
this.canvas,
this.ctx,
this.canvas.width,
this.canvas.height
);
}
}
}
/**
* @memberof Game
* @description Scales the canvas to fit the whole window
* @emits EVENTS.GAME.SET_SCALE
* @since 1.0.0
*/
public scaleToWindow() {
if (this.canvas) {
if (window.devicePixelRatio === 1) {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
return;
}
if (this.config.dprScale && window.devicePixelRatio !== 1) {
dprScale(
this.canvas,
this.ctx,
window.innerWidth,
window.innerHeight
);
new Debug.Log(
`Scaled with devicePixelRatio of ${window.devicePixelRatio} while fullscreen.`
);
}
this.eventEmitter.emit(EVENTS.GAME.SET_SCALE, {
w: window.innerWidth,
h: window.innerHeight,
});
}
}
} | the_stack |
'use strict';
import * as React from 'react';
import {connect} from 'react-redux';
import {State} from '../../store';
import {ScaleInfo, MarkApplicationRecord, MarkApplication, InteractionSignal} from '../../store/factory/Interaction';
import {GroupRecord} from '../../store/factory/marks/Group';
import {setSelection, setApplication, removeApplication, setSignals} from '../../actions/widgetActions';
import {getScaleInfoForGroup, getNestedMarksOfGroup} from '../../ctrl/demonstrations';
import {DatasetRecord} from '../../store/factory/Dataset';
import {MarkRecord} from '../../store/factory/Mark';
import exportName from '../../util/exportName';
import {Map} from 'immutable';
import {WidgetSelectionRecord, WidgetRecord, WidgetSelection, WidgetComparator} from '../../store/factory/Widget';
import WidgetPreview from '../interactions/WidgetPreview';
import {WidgetMarkApplicationProperty} from './WidgetMarkApplication';
import {WidgetSignals} from './WidgetSignals';
const ctrl = require('../../ctrl');
const listeners = require('../../ctrl/listeners');
interface OwnProps {
primId: number;
}
interface DispatchProps {
setSelection: (record: WidgetSelectionRecord, id: number) => void;
setApplication: (record: MarkApplicationRecord, id: number) => void;
removeApplication: (record: MarkApplicationRecord, id: number) => void;
setSignals: (signals: InteractionSignal[], id: number) => void;
}
interface StateProps {
groups: Map<number, GroupRecord>;
widget: WidgetRecord;
scaleInfo: ScaleInfo;
datasets: Map<string, DatasetRecord>;
group: GroupRecord;
groupName: string;
marksOfGroups: Map<number, MarkRecord[]>; // map of group ids to array of mark specs
fieldsOfGroup: string[];
canDemonstrate: boolean;
selectionPreviews: WidgetSelectionRecord[];
applicationPreviews: MarkApplicationRecord[];
}
function mapStateToProps(state: State, ownProps: OwnProps): StateProps {
const widget: WidgetRecord = state.getIn(['vis', 'present', 'widgets', String(ownProps.primId)]);
const groupId = widget.get('groupId');
const scaleInfo: ScaleInfo = getScaleInfoForGroup(state, groupId);
const group: GroupRecord = state.getIn(['vis', 'present', 'marks', String(groupId)]);
const groupName = exportName(group.name);
const marks: Map<string, MarkRecord> = state.getIn(['vis', 'present', 'marks']);
const groups: Map<number, GroupRecord> = marks.filter((mark: MarkRecord) => {
return mark.type === 'group';
}).mapEntries(([k, v]) => {
return [Number(k), v as GroupRecord];
});
const marksOfGroups: Map<number, MarkRecord[]> = groups.map(group => {
return getNestedMarksOfGroup(state, group);
});
const marksOfGroup = marksOfGroups.get(groupId);
const datasets: Map<string, DatasetRecord> = state.getIn(['vis', 'present', 'datasets']);
let fieldsOfGroup = [];
if (marksOfGroup.length && marksOfGroup[0].from && marksOfGroup[0].from.data) {
const dsId = String(marksOfGroup[0].from.data);
const dataset: DatasetRecord = datasets.get(dsId);
const schema = dataset.get('_schema');
const fields = schema.keySeq().toArray();
fieldsOfGroup = fields;
}
const isParsing = state.getIn(['vega', 'isParsing']);
const canDemonstrate = Boolean(!isParsing && ctrl.view && (scaleInfo.xScaleName && scaleInfo.xFieldName || scaleInfo.yScaleName && scaleInfo.yFieldName));
const {
selectionPreviews,
applicationPreviews,
} = generatePreviews(groupId, marksOfGroups, widget);
return {
widget: widget,
groups,
scaleInfo,
group,
groupName,
datasets,
marksOfGroups,
fieldsOfGroup,
canDemonstrate,
selectionPreviews,
applicationPreviews
};
}
const actionCreators: DispatchProps = {setSelection, setApplication, removeApplication, setSignals};
function generatePreviews(groupId, marksOfGroups, widget): {
selectionPreviews: WidgetSelectionRecord[],
applicationPreviews: MarkApplicationRecord[]
} {
const marksOfGroup = marksOfGroups.get(groupId);
return { // TODO maybe memoize these calls or something? also memoize the signal setters
selectionPreviews: generateSelectionPreviews(widget),
applicationPreviews: generateApplicationPreviews(marksOfGroup)
};
};
function generateSelectionPreviews(widget: WidgetRecord): WidgetSelectionRecord[] {
if (widget.field.mtype === 'nominal' || widget.field.mtype === 'ordinal') {
return [
WidgetSelection({
type: 'radio',
id: 'radio',
label: 'Radio',
comparator: '=='
}),
WidgetSelection({
type: 'select',
id: 'select',
label: 'Select',
comparator: '=='
}),
]
}
else if (widget.field.mtype === 'temporal' || widget.field.mtype === 'quantitative') {
return [
WidgetSelection({
type: 'range',
id: 'range',
label: 'Range',
step: 1, // TODO
comparator: '=='
})
]
}
else {
// geojson?
}
}
function generateApplicationPreviews(marksOfGroup: MarkRecord[]): MarkApplicationRecord[] {
const defs: MarkApplicationRecord[] = [];
if (marksOfGroup.length) {
const mark = marksOfGroup[0];
defs.push(MarkApplication({
id: "color",
label: "Color",
targetMarkName: exportName(mark.name),
propertyName: mark.type === 'line' ? "stroke" : "fill",
unselectedValue: "#797979"
}));
defs.push(MarkApplication({
id: "opacity",
label: "Opacity",
targetMarkName: exportName(mark.name),
propertyName: "opacity",
unselectedValue: "0.2"
}));
if (mark.type === 'symbol') {
defs.push(MarkApplication({
id: "size",
label: "Size",
targetMarkName: exportName(mark.name),
propertyName: "size",
unselectedValue: 30
}));
}
}
return defs;
}
class BaseWidgetInspector extends React.Component<OwnProps & StateProps & DispatchProps> {
public componentDidMount() {
if (this.props.selectionPreviews && this.props.selectionPreviews.length) {
const selectionIds = this.props.selectionPreviews.map(s => s.id);
if (!this.props.widget.selection ||
selectionIds.every(id => id !== this.props.widget.selection.id)) {
this.props.setSelection(this.props.selectionPreviews[0], this.props.widget.id);
}
}
if (this.props.applicationPreviews && this.props.applicationPreviews.length) {
const applicationIds = this.props.applicationPreviews.map(a => a.id);
if (!this.props.widget.applications.length ||
applicationIds.every(id => this.props.widget.applications.map(a => a.id).includes(id))) {
this.props.setApplication(this.props.applicationPreviews[0], this.props.widget.id);
}
}
this.props.setSignals(this.getInteractionSignals(this.props.widget), this.props.widget.id);
this.restoreMainViewSignals();
this.restorePreviewSignals();
listeners.onSignal(`widget_${this.props.widget.id}`, (name, value) => this.onMainViewWidgetSignal(name, value));
}
public componentDidUpdate(prevProps: OwnProps & StateProps, prevState) {
if (!prevProps.canDemonstrate && this.props.canDemonstrate) {
this.restoreMainViewSignals();
this.restorePreviewSignals();
listeners.onSignal(`widget_${this.props.widget.id}`, (name, value) => this.onMainViewWidgetSignal(name, value));
}
}
private restoreMainViewSignals() {
const signalName = `widget_${this.props.widget.id}`;
if (this.mainViewSignalValues[signalName]) {
ctrl.view.signal(signalName, this.mainViewSignalValues[signalName]);
ctrl.view.runAsync();
}
}
private restorePreviewSignals() {
const signalName = `widget_${this.props.widget.id}`;
if (this.mainViewSignalValues[signalName]) {
setTimeout(() => {
this.updatePreviewSignals(signalName, this.mainViewSignalValues[signalName]);
}, 50);
// somehow it only works if you have both of these??? some kind of vega invalidation thing
this.updatePreviewSignals(signalName, this.mainViewSignalValues[signalName]);
}
}
private previewRefs = {}; // id -> ref
private mainViewSignalValues = {}; // name -> value
private updatePreviewSignals(name, value) {
this.props.applicationPreviews.forEach(preview => {
if (this.previewRefs[preview.id]) {
this.previewRefs[preview.id].setPreviewSignal(name, value);
}
});
}
private onMainViewWidgetSignal(name, value) {
if (this.mainViewSignalValues[name] !== value) {
this.mainViewSignalValues[name] = value;
this.updatePreviewSignals(name, value);
}
}
private onClickWidgetPreview(preview: WidgetSelectionRecord) {
if (this.props.widget) {
this.props.setSelection(preview, this.props.widget.id);
}
}
private onClickApplicationPreview(preview: MarkApplicationRecord) {
if (this.props.widget) {
if (this.widgetHasApplication(preview)) {
this.props.removeApplication(preview, this.props.widget.id);
}
else {
this.props.setApplication(preview, this.props.widget.id);
}
}
}
private widgetHasApplication(preview: MarkApplicationRecord) {
return this.props.widget.applications.some(application => application.id === preview.id);
}
private getComparatorOptions(preview: WidgetSelectionRecord) {
const options = ['==', '<', '>', '<=', '>='].map(comparator => <option key={comparator} value={comparator}>{comparator}</option>);
return (
<div className="property">
<label htmlFor='widget_comparator'>Comparator:</label>
<div className='control'>
<select name='widget_comparator' value={preview.comparator} onChange={e => this.onSelectComparator(preview, e.target.value as WidgetComparator)}>
{options}
</select>
</div>
</div>
);
}
private onSelectComparator(preview: WidgetSelectionRecord, comparator: WidgetComparator) {
const newPreview = preview.set('comparator', comparator);
this.props.setSelection(newPreview, this.props.widget.id);
}
private getTargetMarkOptions(preview: MarkApplicationRecord) {
const marksOfGroup = this.props.marksOfGroups.get(this.props.group._id);
if (marksOfGroup.length === 1) {
return null;
}
const options = marksOfGroup.map(mark => {
const markName = exportName(mark.name);
return <option key={markName} value={markName}>{markName}</option>
});
return (
<div className="property">
<label htmlFor='target_mark'>Target Mark:</label>
<div className='control'>
<select name='target_mark' value={preview.targetMarkName} onChange={e => this.onSelectTargetMarkName(preview, e.target.value)}>
{options}
</select>
</div>
</div>
);
}
private onSelectTargetMarkName(preview: MarkApplicationRecord, targetMarkName: string) {
let newPreview = preview.set('targetMarkName', targetMarkName);
if (preview.id.startsWith('color')) {
const marksOfGroup = this.props.marksOfGroups.get(this.props.group._id);
const targetMark = marksOfGroup.find(mark => exportName(mark.name) === targetMarkName);
newPreview = newPreview.set('propertyName', targetMark.type === 'line' ? "stroke" : "fill");
}
this.props.setApplication(newPreview, this.props.widget.id);
}
private getInteractionSignals(widget: WidgetRecord): InteractionSignal[] {
const widgetId = widget.id;
return [{
signal: `widget_${widgetId}`,
label: `widget_${widget.field.name}`
}];
}
public render() {
const widget = this.props.widget;
const applications = widget.applications;
return (
<div>
<div>
<div className={"preview-controller"}>
<div className='property-group'>
<h3>Selections</h3>
<div className="preview-scroll">
{
this.props.selectionPreviews.map((preview) => {
return (
<div key={preview.id} className={widget && widget.selection && widget.selection.id === preview.id ? 'selected' : ''}
onClick={() => this.onClickWidgetPreview(preview)}>
<div className="preview-label">{preview.label}</div>
<WidgetPreview id={`preview-${preview.id}`}
groupName={this.props.groupName}
widget={this.props.widget}
preview={preview}/>
</div>
)
})
}
</div>
{
(widget && widget.selection) ? (
this.getComparatorOptions(widget.selection)
) : null
}
</div>
<div className='property-group'>
<h3>Applications</h3>
<div className="preview-scroll">
{
this.props.applicationPreviews.map((preview) => {
return (
<div key={preview.id} className={widget && this.widgetHasApplication(preview) ? 'selected' : ''}>
<div onClick={() => this.onClickApplicationPreview(preview)}>
<div className="preview-label">{preview.label}</div>
<WidgetPreview ref={ref => this.previewRefs[preview.id] = ref}
id={`preview-${preview.id}`}
groupName={this.props.groupName}
widget={this.props.widget}
preview={preview}/>
</div>
</div>
)
})
}
</div>
{
applications.map(application => {
return application.type === 'mark' ? (
<div>
{this.getTargetMarkOptions(application as MarkApplicationRecord)}
<WidgetMarkApplicationProperty widgetId={widget.id} groupId={widget.groupId} markApplication={application}></WidgetMarkApplicationProperty>
</div>
) : null
})
}
</div>
</div>
<div className="property-group">
<h3>Signals</h3>
<WidgetSignals widgetId={this.props.widget.id} signals={this.props.widget.signals}></WidgetSignals>
</div>
</div>
</div>
);
}
};
export const WidgetInspector = connect(mapStateToProps, actionCreators)(BaseWidgetInspector); | the_stack |
import BitMatrix from '../../common/BitMatrix';
import WhiteRectangleDetector from '../../common/detector/WhiteRectangleDetector';
import DetectorResult from '../../common/DetectorResult';
import GridSamplerInstance from '../../common/GridSamplerInstance';
import NotFoundException from '../../NotFoundException';
import { float, int } from '../../../customTypings';
import ResultPoint from '../../ResultPoint';
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code
* is rotated or skewed, or partially obscured.</p>
*
* @author Sean Owen
*/
export default class Detector {
private image: BitMatrix;
private rectangleDetector: WhiteRectangleDetector;
constructor(image: BitMatrix) {
this.image = image;
this.rectangleDetector = new WhiteRectangleDetector(this.image);
}
/**
* <p>Detects a Data Matrix Code in an image.</p>
*
* @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code
* @throws NotFoundException if no Data Matrix Code can be found
*/
public detect(): DetectorResult {
const cornerPoints = this.rectangleDetector.detect();
let points = this.detectSolid1(cornerPoints);
points = this.detectSolid2(points);
points[3] = this.correctTopRight(points);
if (!points[3]) {
throw new NotFoundException();
}
points = this.shiftToModuleCenter(points);
const topLeft = points[0];
const bottomLeft = points[1];
const bottomRight = points[2];
const topRight = points[3];
let dimensionTop = this.transitionsBetween(topLeft, topRight) + 1;
let dimensionRight = this.transitionsBetween(bottomRight, topRight) + 1;
if ((dimensionTop & 0x01) === 1) {
dimensionTop += 1;
}
if ((dimensionRight & 0x01) === 1) {
dimensionRight += 1;
}
if (4 * dimensionTop < 7 * dimensionRight && 4 * dimensionRight < 7 * dimensionTop) {
// The matrix is square
dimensionTop = dimensionRight = Math.max(dimensionTop, dimensionRight);
}
let bits = Detector.sampleGrid(this.image,
topLeft,
bottomLeft,
bottomRight,
topRight,
dimensionTop,
dimensionRight);
return new DetectorResult(bits, [topLeft, bottomLeft, bottomRight, topRight]);
}
private static shiftPoint(point: ResultPoint, to: ResultPoint, div: float): ResultPoint {
let x = (to.getX() - point.getX()) / (div + 1);
let y = (to.getY() - point.getY()) / (div + 1);
return new ResultPoint(point.getX() + x, point.getY() + y);
}
private static moveAway(point: ResultPoint, fromX: float, fromY: float): ResultPoint {
let x = point.getX();
let y = point.getY();
if (x < fromX) {
x -= 1;
} else {
x += 1;
}
if (y < fromY) {
y -= 1;
} else {
y += 1;
}
return new ResultPoint(x, y);
}
/**
* Detect a solid side which has minimum transition.
*/
private detectSolid1(cornerPoints: ResultPoint[]): ResultPoint[] {
// 0 2
// 1 3
let pointA = cornerPoints[0];
let pointB = cornerPoints[1];
let pointC = cornerPoints[3];
let pointD = cornerPoints[2];
let trAB = this.transitionsBetween(pointA, pointB);
let trBC = this.transitionsBetween(pointB, pointC);
let trCD = this.transitionsBetween(pointC, pointD);
let trDA = this.transitionsBetween(pointD, pointA);
// 0..3
// : :
// 1--2
let min = trAB;
let points = [pointD, pointA, pointB, pointC];
if (min > trBC) {
min = trBC;
points[0] = pointA;
points[1] = pointB;
points[2] = pointC;
points[3] = pointD;
}
if (min > trCD) {
min = trCD;
points[0] = pointB;
points[1] = pointC;
points[2] = pointD;
points[3] = pointA;
}
if (min > trDA) {
points[0] = pointC;
points[1] = pointD;
points[2] = pointA;
points[3] = pointB;
}
return points;
}
/**
* Detect a second solid side next to first solid side.
*/
private detectSolid2(points: ResultPoint[]): ResultPoint[] {
// A..D
// : :
// B--C
let pointA = points[0];
let pointB = points[1];
let pointC = points[2];
let pointD = points[3];
// Transition detection on the edge is not stable.
// To safely detect, shift the points to the module center.
let tr = this.transitionsBetween(pointA, pointD);
let pointBs = Detector.shiftPoint(pointB, pointC, (tr + 1) * 4);
let pointCs = Detector.shiftPoint(pointC, pointB, (tr + 1) * 4);
let trBA = this.transitionsBetween(pointBs, pointA);
let trCD = this.transitionsBetween(pointCs, pointD);
// 0..3
// | :
// 1--2
if (trBA < trCD) {
// solid sides: A-B-C
points[0] = pointA;
points[1] = pointB;
points[2] = pointC;
points[3] = pointD;
} else {
// solid sides: B-C-D
points[0] = pointB;
points[1] = pointC;
points[2] = pointD;
points[3] = pointA;
}
return points;
}
/**
* Calculates the corner position of the white top right module.
*/
private correctTopRight(points: ResultPoint[]): ResultPoint {
// A..D
// | :
// B--C
let pointA = points[0];
let pointB = points[1];
let pointC = points[2];
let pointD = points[3];
// shift points for safe transition detection.
let trTop = this.transitionsBetween(pointA, pointD);
let trRight = this.transitionsBetween(pointB, pointD);
let pointAs = Detector.shiftPoint(pointA, pointB, (trRight + 1) * 4);
let pointCs = Detector.shiftPoint(pointC, pointB, (trTop + 1) * 4);
trTop = this.transitionsBetween(pointAs, pointD);
trRight = this.transitionsBetween(pointCs, pointD);
let candidate1 = new ResultPoint(
pointD.getX() + (pointC.getX() - pointB.getX()) / (trTop + 1),
pointD.getY() + (pointC.getY() - pointB.getY()) / (trTop + 1));
let candidate2 = new ResultPoint(
pointD.getX() + (pointA.getX() - pointB.getX()) / (trRight + 1),
pointD.getY() + (pointA.getY() - pointB.getY()) / (trRight + 1));
if (!this.isValid(candidate1)) {
if (this.isValid(candidate2)) {
return candidate2;
}
return null;
}
if (!this.isValid(candidate2)) {
return candidate1;
}
let sumc1 = this.transitionsBetween(pointAs, candidate1) + this.transitionsBetween(pointCs, candidate1);
let sumc2 = this.transitionsBetween(pointAs, candidate2) + this.transitionsBetween(pointCs, candidate2);
if (sumc1 > sumc2) {
return candidate1;
} else {
return candidate2;
}
}
/**
* Shift the edge points to the module center.
*/
private shiftToModuleCenter(points: ResultPoint[]): ResultPoint[] {
// A..D
// | :
// B--C
let pointA = points[0];
let pointB = points[1];
let pointC = points[2];
let pointD = points[3];
// calculate pseudo dimensions
let dimH = this.transitionsBetween(pointA, pointD) + 1;
let dimV = this.transitionsBetween(pointC, pointD) + 1;
// shift points for safe dimension detection
let pointAs = Detector.shiftPoint(pointA, pointB, dimV * 4);
let pointCs = Detector.shiftPoint(pointC, pointB, dimH * 4);
// calculate more precise dimensions
dimH = this.transitionsBetween(pointAs, pointD) + 1;
dimV = this.transitionsBetween(pointCs, pointD) + 1;
if ((dimH & 0x01) === 1) {
dimH += 1;
}
if ((dimV & 0x01) === 1) {
dimV += 1;
}
// WhiteRectangleDetector returns points inside of the rectangle.
// I want points on the edges.
let centerX = (pointA.getX() + pointB.getX() + pointC.getX() + pointD.getX()) / 4;
let centerY = (pointA.getY() + pointB.getY() + pointC.getY() + pointD.getY()) / 4;
pointA = Detector.moveAway(pointA, centerX, centerY);
pointB = Detector.moveAway(pointB, centerX, centerY);
pointC = Detector.moveAway(pointC, centerX, centerY);
pointD = Detector.moveAway(pointD, centerX, centerY);
let pointBs: ResultPoint;
let pointDs: ResultPoint;
// shift points to the center of each modules
pointAs = Detector.shiftPoint(pointA, pointB, dimV * 4);
pointAs = Detector.shiftPoint(pointAs, pointD, dimH * 4);
pointBs = Detector.shiftPoint(pointB, pointA, dimV * 4);
pointBs = Detector.shiftPoint(pointBs, pointC, dimH * 4);
pointCs = Detector.shiftPoint(pointC, pointD, dimV * 4);
pointCs = Detector.shiftPoint(pointCs, pointB, dimH * 4);
pointDs = Detector.shiftPoint(pointD, pointC, dimV * 4);
pointDs = Detector.shiftPoint(pointDs, pointA, dimH * 4);
return [pointAs, pointBs, pointCs, pointDs];
}
private isValid(p: ResultPoint): boolean {
return p.getX() >= 0 && p.getX() < this.image.getWidth() && p.getY() > 0 && p.getY() < this.image.getHeight();
}
private static sampleGrid(image: BitMatrix,
topLeft: ResultPoint,
bottomLeft: ResultPoint,
bottomRight: ResultPoint,
topRight: ResultPoint,
dimensionX: int,
dimensionY: int): BitMatrix {
const sampler = GridSamplerInstance.getInstance();
return sampler.sampleGrid(image,
dimensionX,
dimensionY,
0.5,
0.5,
dimensionX - 0.5,
0.5,
dimensionX - 0.5,
dimensionY - 0.5,
0.5,
dimensionY - 0.5,
topLeft.getX(),
topLeft.getY(),
topRight.getX(),
topRight.getY(),
bottomRight.getX(),
bottomRight.getY(),
bottomLeft.getX(),
bottomLeft.getY());
}
/**
* Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
*/
private transitionsBetween(from: ResultPoint, to: ResultPoint): int {
// See QR Code Detector, sizeOfBlackWhiteBlackRun()
let fromX = Math.trunc(from.getX());
let fromY = Math.trunc(from.getY());
let toX = Math.trunc(to.getX());
let toY = Math.trunc(to.getY());
let steep: boolean = Math.abs(toY - fromY) > Math.abs(toX - fromX);
if (steep) {
let temp = fromX;
fromX = fromY;
fromY = temp;
temp = toX;
toX = toY;
toY = temp;
}
let dx = Math.abs(toX - fromX);
let dy = Math.abs(toY - fromY);
let error = -dx / 2;
let ystep = fromY < toY ? 1 : -1;
let xstep = fromX < toX ? 1 : -1;
let transitions = 0;
let inBlack: boolean = this.image.get(steep ? fromY : fromX, steep ? fromX : fromY);
for (let x: int = fromX, y = fromY; x !== toX; x += xstep) {
let isBlack: boolean = this.image.get(steep ? y : x, steep ? x : y);
if (isBlack !== inBlack) {
transitions++;
inBlack = isBlack;
}
error += dy;
if (error > 0) {
if (y === toY) {
break;
}
y += ystep;
error -= dx;
}
}
return transitions;
}
} | the_stack |
import {
CharacteristicValue,
PlatformAccessory
} from "homebridge";
import {
PLATFORM_NAME,
PLUGIN_NAME
} from "./settings";
import {
ProtectCameraConfig,
ProtectNvrLiveviewConfig
} from "unifi-protect";
import { ProtectBase } from "./protect-accessory";
import { ProtectNvr } from "./protect-nvr";
import { ProtectSecuritySystem } from "./protect-securitysystem";
export class ProtectLiveviews extends ProtectBase {
private isMqttConfigured: boolean;
private liveviews: ProtectNvrLiveviewConfig[] | undefined;
private liveviewSwitches: PlatformAccessory[];
private securityAccessory: PlatformAccessory | null | undefined;
private securitySystem: ProtectSecuritySystem | null;
// Configure our liveviews capability.
constructor(nvr: ProtectNvr) {
// Let the base class get us set up.
super(nvr);
// Initialize the class.
this.isMqttConfigured = false;
this.liveviews = this.nvrApi?.bootstrap?.liveviews;
this.liveviewSwitches = [];
this.securityAccessory = null;
this.securitySystem = null;
}
// Update security system accessory.
public configureLiveviews(): void {
// Do we have controller access?
if(!this.nvrApi.bootstrap?.nvr) {
return;
}
this.liveviews = this.nvrApi.bootstrap.liveviews;
this.configureSecuritySystem();
this.configureSwitches();
this.configureMqtt();
}
// Configure the security system accessory.
private configureSecuritySystem(): void {
// If we don't have the bootstrap configuration, we're done here.
if(!this.nvrApi.bootstrap) {
return;
}
const regexSecuritySystemLiveview = /^Protect-(Away|Home|Night|Off)$/i;
const uuid = this.hap.uuid.generate(this.nvrApi.bootstrap.nvr.mac + ".Security");
// If the user removed the last Protect-centric liveview for the security system, we remove the security system accessory.
if(!this.liveviews?.some((x: ProtectNvrLiveviewConfig) => regexSecuritySystemLiveview.test(x.name))) {
if(this.securityAccessory) {
this.log.info("%s: No plugin-specific liveviews found. Disabling the security system accessory associated with this UniFi Protect controller.",
this.name());
// Unregister the accessory and delete it's remnants from HomeKit and the plugin.
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [this.securityAccessory]);
this.platform.accessories.splice(this.platform.accessories.indexOf(this.securityAccessory), 1);
}
this.securityAccessory = null;
this.securitySystem = null;
return;
}
// Create the security system accessory if it doesn't already exist.
if(!this.securityAccessory) {
// See if we already have this accessory defined.
if((this.securityAccessory = this.platform.accessories.find((x: PlatformAccessory) => x.UUID === uuid)) === undefined) {
// We will use the NVR MAC address + ".Security" to create our UUID. That should provide the guaranteed uniqueness we need.
this.securityAccessory = new this.api.platformAccessory(this.nvrApi.bootstrap.nvr.name, uuid);
// Register this accessory with homebridge and add it to the platform accessory array so we can track it.
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [this.securityAccessory]);
this.platform.accessories.push(this.securityAccessory);
}
if(!this.securityAccessory) {
this.log.error("%s: Unable to create the security system accessory.", this.name());
return;
}
this.log.info("%s: Plugin-specific liveviews have been detected. Enabling the security system accessory.", this.name());
}
// We have the security system accessory, now let's configure it.
if(!this.securitySystem) {
this.securitySystem = new ProtectSecuritySystem(this.nvr, this.securityAccessory);
if(!this.securitySystem) {
this.log.error("%s: Unable to configure the security system accessory.", this.name());
return;
}
}
// Update our NVR reference.
this.securityAccessory.context.nvr = this.nvrApi.bootstrap.nvr.mac;
}
// Configure any liveview-associated switches.
private configureSwitches(): void {
// If we don't have any liveviews or the bootstrap configuration, there's nothing to configure.
if(!this.liveviews || !this.nvrApi.bootstrap) {
return;
}
// Iterate through the list of switches and see if we still have matching liveviews.
for(const liveviewSwitch of this.liveviewSwitches) {
// We found a switch matching this liveview. Move along...
if(this.liveviews.some((x: ProtectNvrLiveviewConfig) => x.name.toUpperCase() === ("Protect-" + (liveviewSwitch.context?.liveview as string)).toUpperCase())) {
continue;
}
// The switch has no associated liveview - let's get rid of it.
this.log.info("%s: The plugin-specific liveview %s has been removed or renamed. Removing the switch associated with this liveview.",
this.name(), liveviewSwitch.context.liveview);
// Unregister the accessory and delete it's remnants from HomeKit and the plugin.
this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [liveviewSwitch]);
this.platform.accessories.splice(this.platform.accessories.indexOf(liveviewSwitch), 1);
this.liveviewSwitches.splice(this.liveviewSwitches.indexOf(liveviewSwitch), 1);
}
// Initialize the regular expression here so we don't have to reinitialize it in each iteration below.
const regexSecuritySystemLiveview = /^Protect-((?!Away$|Off$|Home$|Night$).+)$/i;
// Check for any new plugin-specific liveviews.
for(const liveview of this.liveviews) {
// Only match on views beginning with Protect- that are not reserved for the security system.
const viewMatch = regexSecuritySystemLiveview.exec(liveview.name);
// No match found, we're not interested in it.
if(!viewMatch) {
continue;
}
// Grab the name of our new switch for reference.
const viewName = viewMatch[1];
// See if we already have this accessory defined.
if(this.liveviewSwitches.some((x: PlatformAccessory) => (x.context?.liveview as string).toUpperCase() === viewName.toUpperCase())) {
continue;
}
// We use the NVR MAC address + ".Liveview." + viewname to create our unique UUID for our switches.
const uuid = this.hap.uuid.generate(this.nvrApi.bootstrap.nvr.mac + ".Liveview." + viewName.toUpperCase());
// Check to see if the accessory already exists before we create it.
let newAccessory;
if((newAccessory = this.platform.accessories.find((x: PlatformAccessory) => x.UUID === uuid)) === undefined) {
newAccessory = new this.api.platformAccessory(this.nvrApi.bootstrap.nvr.name + " " + viewName, uuid);
// Register this accessory with homebridge and add it to the platform accessory array so we can track it.
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [newAccessory]);
this.platform.accessories.push(newAccessory);
}
if(!newAccessory) {
this.log.error("%s: Unable to create the switch for liveview: %s.", this.name(), viewName);
return;
}
// Configure our accessory.
newAccessory.context.liveview = viewName;
newAccessory.context.nvr = this.nvrApi.bootstrap.nvr.mac;
newAccessory.context.switchState = false;
this.liveviewSwitches.push(newAccessory);
// Find the existing liveview switch, if we have one.
let switchService = newAccessory.getService(this.hap.Service.Switch);
// Add the liveview switch to the accessory.
if(!switchService) {
switchService = new this.hap.Service.Switch(newAccessory.displayName);
if(!switchService) {
this.log.error("%s: Unable to create the switch for liveview: %s.", this.name(), viewName);
return;
}
newAccessory.addService(switchService);
}
// Activate or deactivate motion detection.
switchService
.getCharacteristic(this.hap.Characteristic.On)
?.onGet(this.getSwitchState.bind(this, newAccessory))
.onSet(this.setSwitchState.bind(this, newAccessory));
// Initialize the switch.
switchService.updateCharacteristic(this.hap.Characteristic.On, newAccessory.context.switchState as boolean);
this.log.info("%s: Plugin-specific liveview %s has been detected. Configuring a switch accessory for it.", this.name(), viewName);
}
}
// Configure MQTT capabilities for the security system.
private configureMqtt(): void {
if(this.isMqttConfigured || !this.nvrApi.bootstrap?.nvr.mac) {
return;
}
this.isMqttConfigured = true;
// Return the current status of all the liveviews.
this.nvr.mqtt?.subscribe(this.nvrApi.bootstrap?.nvr.mac, "liveviews/get", (message: Buffer) => {
const value = message.toString().toLowerCase();
// When we get the right message, we return the list of liveviews.
if(value !== "true") {
return;
}
// Get the list of liveviews.
const liveviews = this.liveviewSwitches.map(x =>
({ name: x.context.liveview as string, state: x.getService(this.hap.Service.Switch)?.getCharacteristic(this.hap.Characteristic.On).value }));
this.nvr.mqtt?.publish(this.nvrApi.bootstrap?.nvr.mac ?? "", "liveviews", JSON.stringify(liveviews));
this.log.info("%s: Liveview scenes list published via MQTT.", this.name());
});
// Set the status of one or more liveviews.
this.nvr.mqtt?.subscribe(this.nvrApi.bootstrap?.nvr.mac, "liveviews/set", (message: Buffer) => {
interface mqttLiveviewJSON {
name: string,
state: boolean
}
let incomingPayload;
// Catch any errors in parsing what we get over MQTT.
try {
incomingPayload = JSON.parse(message.toString()) as mqttLiveviewJSON[];
// Sanity check what comes in from MQTT to make sure it's what we want.
if(!(incomingPayload instanceof Array)) {
throw new Error("The JSON object is not in the expected format");
}
} catch(error) {
if(error instanceof SyntaxError) {
this.log.error("%s: Unable to process MQTT liveview setting: \"%s\". Error: %s.", this.name(), message.toString(), error.message);
} else {
this.log.error("%s: Unknown error has occurred: %s.", this.name(), error);
}
// Errors mean that we're done now.
return;
}
// Update state on the liveviews.
for(const entry of incomingPayload) {
// Lookup this liveview.
const accessory = this.liveviewSwitches.find((x: PlatformAccessory) => ((x.context?.liveview as string) ?? "").toUpperCase() === entry.name?.toUpperCase());
// If we can't find it, move on.
if(!accessory) {
continue;
}
// Set the switch state and update the switch in HomeKit.
this.setSwitchState(accessory, entry.state);
accessory.getService(this.hap.Service.Switch)?.updateCharacteristic(this.hap.Characteristic.On, accessory.context.switchState as boolean);
this.log.info("%s: Liveview scene updated via MQTT: %s.", this.name(), accessory.context.liveview);
}
});
}
// Get the current liveview switch state.
private getSwitchState(accessory: PlatformAccessory): CharacteristicValue {
return accessory.context.switchState === true;
}
// Toggle the liveview switch state.
private setSwitchState(liveviewSwitch: PlatformAccessory, value: CharacteristicValue): void {
// We don't have any liveviews or we're already at this state - we're done.
if(!this.nvrApi.bootstrap || !this.liveviews || (liveviewSwitch.context.switchState === value)) {
return;
}
// Get the complete list of cameras in the liveview we're interested in.
// This cryptic line grabs the list of liveviews that have the name we're interested in
// (turns out, you can define multiple liveviews in Protect with the same name...who knew!),
// and then create a single list containing all of the cameras found.
const targetCameraIds = this.liveviews.filter(view => view.name.toUpperCase() === ("Protect-" + (liveviewSwitch.context.liveview as string)).toUpperCase())
.map(view => view.slots.map(slots => slots.cameras))
.flat(2);
// Nothing configured for this view. We're done.
if(!targetCameraIds.length) {
return;
}
// Iterate through the list of accessories and set the Protect scene.
for(const targetAccessory of this.platform.accessories) {
// We only want accessories associated with this Protect controller.
if(!targetAccessory.context?.device || targetAccessory.context.nvr !== this.nvrApi.bootstrap.nvr.mac) {
continue;
}
// Check to see if this is one of the cameras we want to toggle motion detection for and the state is changing.
if(targetCameraIds.some(thisCameraId =>
thisCameraId === (targetAccessory.context.device as ProtectCameraConfig).id) && (targetAccessory.context.detectMotion !== value)) {
targetAccessory.context.detectMotion = value;
// Update the switch service, if present.
const motionSwitch = targetAccessory.getService(this.hap.Service.Switch);
if(motionSwitch) {
motionSwitch.updateCharacteristic(this.hap.Characteristic.On, targetAccessory.context.detectMotion as boolean);
}
this.log.info("%s: %s -> %s: Motion detection %s.", this.name(), liveviewSwitch.context.liveview, targetAccessory.displayName,
targetAccessory.context.detectMotion === true ? "enabled" : "disabled");
}
}
liveviewSwitch.context.switchState = value === true;
// Publish to MQTT, if configured.
this.nvr.mqtt?.publish(this.nvrApi.bootstrap?.nvr.mac ?? "", "liveviews",
JSON.stringify([{name: liveviewSwitch.context.liveview as string, state: liveviewSwitch.context.switchState as boolean}]));
}
} | the_stack |
import { SDK, search } from '@getstation/sdk';
import { Credentials } from 'google-auth-library/build/src/auth/credentials';
import * as decode from 'jwt-decode';
import { compose, prop, reject } from 'ramda';
import { contained } from 'ramda-adjunct';
import { combineLatest, defer, from, Observable, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged, filter, map, tap } from 'rxjs/operators';
import { startActivityRecording, stopActivityRecording } from '../common/activity';
import { idExtractor, resourceExtractor } from './activity';
import { ElectronGDriveOAuth2, getGDriveFilesAsSearchResults } from './helpers';
import { startHistoryRecording, stopHistoryRecording } from './history';
import { addResourcesHandler, removeResourcesHandler } from './resources';
import { RemoveTokensAction, Tokens, UpdateTokensAction } from './types';
// ----------------------------------------------------------------------
// ⚠️ Disabled for now, as it needs a custom GOOGLE_CLIENT_ID
// and GOOGLE_CLIENT_SECRET.
//
// Once a solution is found, put back the following in 16.json manifest:
// "main": "gdrive/main",
// "renderer": "gdrive/renderer",
// ----------------------------------------------------------------------
const allResultsObservable = new Set<Observable<search.SearchResultWrapper>>();
let updateResultsObservableSubscription: Subscription | null = null;
let subscriptions: Subscription[];
/**
* Listen for search query updates to trigger GDrive search, and send back results
* @param {SDK} sdk
* @param {ElectronGDriveOAuth2} client
* @param {string?} email
* @returns {Observable<search.SearchResultWrapper>}
*/
function initBindQuery(sdk: SDK, client: ElectronGDriveOAuth2, email?: string): Observable<search.SearchResultWrapper> {
let cancelRunningQuery: (() => void) | null = null;
return defer<Observable<search.SearchResultWrapper>>(() => Observable.create(subscriber =>
sdk.search.query
.pipe(
tap((query) => {
if (cancelRunningQuery) {
cancelRunningQuery();
cancelRunningQuery = null;
}
if (query.value) {
subscriber.next({ loading: 'Google Drive' });
} else {
subscriber.next({ results: [] });
}
}),
filter(query => Boolean(query.value)), // ignore empty query
distinctUntilChanged(),
debounceTime(150)
)
.subscribe(async ({ value }) => {
let cancelled = false;
cancelRunningQuery = () => { cancelled = true; };
const files = await client.listFiles(value);
if (cancelled) return;
const searchResults = getGDriveFilesAsSearchResults(sdk, files, email);
const tabsAsResourceIds = sdk.tabs.getTabs()
.map(tab => idExtractor(tab.url) || '')
.filter(x => Boolean(x));
const isTabHasResourceId = compose(contained(tabsAsResourceIds), prop('resourceId'));
const rejectResultIfAvailableAsTab = reject<search.SearchResultItem>(isTabHasResourceId);
subscriber.next({
...searchResults,
results: rejectResultIfAvailableAsTab(searchResults.results || []),
});
})
));
}
/**
* Aggregate results from all GDrive accounts, and send them to browserX
* @param {SDK} sdk
* @param {Observable<search.SearchResultWrapper>[]} resultsObservable
* @returns {Subscription | null}
*/
function updateResultsObservable(sdk: SDK, resultsObservable: Observable<search.SearchResultWrapper>[]) {
if (updateResultsObservableSubscription) updateResultsObservableSubscription.unsubscribe();
if (resultsObservable.length === 0) {
sdk.search.results.next({});
} else {
// Keep only the last values of each of the consumers
updateResultsObservableSubscription = combineLatest(resultsObservable)
.pipe(map((resultsWrappers: search.SearchResultWrapper[]) => {
// A list of all results, whatever the consumer
const allResults: search.SearchResultItem[] = resultsWrappers.reduce(
(accumulator: search.SearchResultItem[], currentValue) => accumulator.concat(currentValue.results || []),
[]
);
// A Set of all categories that are in loading state
const allLoadingCategories: Set<string> = resultsWrappers.reduce(
(accumulator, currentValue) => currentValue.loading ? accumulator.add(currentValue.loading) : accumulator,
new Set<string>()
);
const ret: search.SearchResultWrapper = {
results: allResults,
};
if (allLoadingCategories.size > 0) {
ret.loading = Array.from(allLoadingCategories)[0];
}
return ret;
}))
.subscribe(sdk.search.results);
}
return updateResultsObservableSubscription;
}
function* initIpcListener(sdk: SDK) {
// Update storage on remove
yield from(sdk.ipc)
.pipe(filter(m => m.type === 'REMOVE_TOKENS'))
.subscribe(async (m: RemoveTokensAction) => {
const allTokens = await sdk.storage.getItem<Tokens>('tokens');
if (!allTokens) return;
if (!(m.key in allTokens)) return;
delete allTokens[m.key];
await sdk.storage.setItem('tokens', allTokens);
});
// Trigger Google Auth process and store resulting token
yield from(sdk.ipc)
.pipe(filter(m => m.type === 'REQUEST_ADD_TOKENS'))
.subscribe(async () => {
const client = initClient(sdk);
const token = await client.openAuthWindowAndGetTokens();
const { sub } = decode(token.id_token as string);
let allTokens = await sdk.storage.getItem<Tokens>('tokens');
if (!allTokens) allTokens = {};
allTokens[sub] = token;
await sdk.storage.setItem('tokens', allTokens);
});
}
/**
* Init GDrive client
*
* @param {SDK} sdk
* @param {Credentials} token
* @returns {ElectronGDriveOAuth2}
*/
function initClient(sdk: SDK, token?: Credentials) {
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
throw new Error('Missing GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET');
}
const client = new ElectronGDriveOAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET
);
if (token) {
client.setTokens(token);
client.oauth2Client.refreshAccessToken()
.catch(async () => {
const { sub } = decode(token.id_token as string);
const allTokens = await sdk.storage.getItem<Tokens>('tokens') || {};
if (allTokens[sub]) {
allTokens[sub].expired = true;
await sdk.storage.setItem('tokens', allTokens);
setTimeout(
() => {
// FIXME wait for renderer to be ready
sdk.ipc.publish({
type: 'UPDATE_TOKENS',
tokens: allTokens,
} as UpdateTokensAction);
},
3000);
}
});
}
return client;
}
/**
* Listen for updated tokens in order to store them
* @param {SDK} sdk
* @param {ElectronGDriveOAuth2} client
* @param {Credentials} token
*/
function initClientTokensListener(sdk: SDK, client: ElectronGDriveOAuth2, token: Credentials) {
let lastToken = token;
client.on('tokens', async (renewedToken: Credentials) => {
const { sub } = decode(renewedToken.id_token as string);
lastToken = { ...lastToken, ...renewedToken };
let allTokens = await sdk.storage.getItem<Tokens>('tokens');
if (!allTokens) allTokens = {};
allTokens[sub] = lastToken;
await sdk.storage.setItem('tokens', allTokens);
});
}
function tryGetEmail(token: Credentials) {
if (!token.id_token) return;
const { email } = decode(token.id_token);
return email;
}
/**
* Handle full initialization chain for a new GDrive account
* @param {SDK} sdk
* @param {Credentials} token
* @returns {() => void}
*/
function initClientFull(sdk: SDK, token: Credentials) {
const client = initClient(sdk, token);
initClientTokensListener(sdk, client, token);
const observable = initBindQuery(sdk, client, tryGetEmail(token));
allResultsObservable.add(observable);
startHistoryRecording(sdk, client, token, tryGetEmail(token));
updateResultsObservable(sdk, Array.from(allResultsObservable));
addResourcesHandler(sdk, token, client);
return () => {
client.removeAllListeners();
allResultsObservable.delete(observable);
updateResultsObservable(sdk, Array.from(allResultsObservable));
stopHistoryRecording(sdk, token);
removeResourcesHandler(sdk, token);
};
}
function subtract<T = any>(a: Set<T>, b: Set<T>): Set<T> {
return new Set([...a].filter(x => !b.has(x)));
}
async function initStorageListener(sdk: SDK) {
sdk.storage.onChanged.addListener((changes) => {
if (!('tokens' in changes)) return;
handleNewTokens(sdk, changes.tokens.oldValue, changes.tokens.newValue);
});
handleNewTokens(sdk, [], await sdk.storage.getItem<Tokens>('tokens'));
}
const unsubscriptionMap = new Map<string, Function>();
/**
* When tokens are updated, compute the diff, and call necessary initializers or unsubscriptions
* @param {SDK} sdk
* @param oldValue
* @param newValue
*/
function handleNewTokens(sdk: SDK, oldValue: any, newValue: any) {
const oldKeys = new Set(oldValue ? Object.keys(oldValue) : []);
const newKeys = new Set(newValue ? Object.keys(newValue) : []);
const deletedKeys = subtract(oldKeys, newKeys);
const addedKeys = subtract(newKeys, oldKeys);
for (const addedKey of addedKeys) {
const unsubscribe = initClientFull(sdk, newValue[addedKey]);
unsubscriptionMap.set(addedKey, unsubscribe);
}
for (const deletedKey of deletedKeys) {
// TODO revoke refresh_token ?
if (unsubscriptionMap.has(deletedKey)) {
unsubscriptionMap.get(deletedKey)!();
unsubscriptionMap.delete(deletedKey);
}
}
sdk.ipc.publish({
type: 'UPDATE_TOKENS',
tokens: newValue,
} as UpdateTokensAction);
}
/**
* Init all accounts on activation
* @param {SDK} sdk
* @returns {Promise<void>}
*/
async function initClients(sdk: SDK) {
let allTokens = await sdk.storage.getItem<Tokens>('tokens');
subscriptions = Array.from(initIpcListener(sdk));
if (!allTokens) return;
if ('access_token' in allTokens) {
allTokens = { expired: allTokens };
allTokens.expired.expired = true;
await sdk.storage.setItem('tokens', allTokens);
}
setTimeout(
() => {
// FIXME wait for renderer to be ready
sdk.ipc.publish({
type: 'UPDATE_TOKENS',
tokens: allTokens,
} as UpdateTokensAction);
},
3000);
}
export default {
activate: async (sdk: SDK): Promise<void> => {
const manifestURL = sdk.storage.id;
await initClients(sdk);
await initStorageListener(sdk);
await startActivityRecording(sdk, manifestURL, resourceExtractor);
},
deactivate: (sdk: SDK): void => {
subscriptions.forEach(s => s.unsubscribe());
stopActivityRecording(sdk);
stopHistoryRecording(sdk);
sdk.close();
},
}; | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* Common resource representation.
*
* @member {string} [id] Resource ID.
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
* @member {string} [location] Resource location.
* @member {object} [tags] Resource tags.
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location?: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the FrontDoor class.
* @constructor
* Front Door represents a collection of backend endpoints to route traffic to
* along with rules that specify how traffic is sent there.
*
* @member {string} [friendlyName] A friendly name for the frontDoor
* @member {array} [routingRules] Routing rules associated with this Front
* Door.
* @member {array} [loadBalancingSettings] Load balancing settings associated
* with this Front Door instance.
* @member {array} [healthProbeSettings] Health probe settings associated with
* this Front Door instance.
* @member {array} [backendPools] Backend pools available to routing rules.
* @member {array} [frontendEndpoints] Frontend endpoints available to routing
* rules.
* @member {string} [enabledState] Operational status of the Front Door load
* balancer. Permitted values are 'Enabled' or 'Disabled'. Possible values
* include: 'Enabled', 'Disabled'
* @member {string} [resourceState] Resource status of the Front Door. Possible
* values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled',
* 'Deleting'
* @member {string} [provisioningState] Provisioning state of the Front Door.
* @member {string} [cname] The host that each frontendEndpoint must CNAME to.
*/
export interface FrontDoor extends Resource {
friendlyName?: string;
routingRules?: RoutingRule[];
loadBalancingSettings?: LoadBalancingSettingsModel[];
healthProbeSettings?: HealthProbeSettingsModel[];
backendPools?: BackendPool[];
frontendEndpoints?: FrontendEndpoint[];
enabledState?: string;
resourceState?: string;
readonly provisioningState?: string;
readonly cname?: string;
}
/**
* @class
* Initializes a new instance of the SubResource class.
* @constructor
* Reference to another subresource.
*
* @member {string} [id] Resource ID.
*/
export interface SubResource extends BaseResource {
id?: string;
}
/**
* @class
* Initializes a new instance of the RoutingRule class.
* @constructor
* A routing rule represents a specification for traffic to treat and where to
* send it, along with health probe information.
*
* @member {array} [frontendEndpoints] Frontend endpoints associated with this
* rule
* @member {array} [acceptedProtocols] Protocol schemes to match for this rule
* @member {array} [patternsToMatch] The route patterns of the rule.
* @member {string} [customForwardingPath] A custom path used to rewrite
* resource paths matched by this rule. Leave empty to use incoming path.
* @member {string} [forwardingProtocol] Protocol this rule will use when
* forwarding traffic to backends. Possible values include: 'HttpOnly',
* 'HttpsOnly', 'MatchRequest'
* @member {object} [cacheConfiguration] The caching configuration associated
* with this rule.
* @member {string} [cacheConfiguration.queryParameterStripDirective] Treatment
* of URL query terms when forming the cache key. Possible values include:
* 'StripNone', 'StripAll'
* @member {string} [cacheConfiguration.dynamicCompression] Whether to use
* dynamic compression for cached content. Possible values include: 'Enabled',
* 'Disabled'
* @member {object} [backendPool] A reference to the BackendPool which this
* rule routes to.
* @member {string} [backendPool.id] Resource ID.
* @member {string} [enabledState] Whether to enable use of this rule.
* Permitted values are 'Enabled' or 'Disabled'. Possible values include:
* 'Enabled', 'Disabled'
* @member {string} [resourceState] Resource status. Possible values include:
* 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
*/
export interface RoutingRule extends SubResource {
frontendEndpoints?: SubResource[];
acceptedProtocols?: string[];
patternsToMatch?: string[];
customForwardingPath?: string;
forwardingProtocol?: string;
cacheConfiguration?: CacheConfiguration;
backendPool?: SubResource;
enabledState?: string;
resourceState?: string;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the LoadBalancingSettingsModel class.
* @constructor
* Load balancing settings for a backend pool
*
* @member {number} [sampleSize] The number of samples to consider for load
* balancing decisions
* @member {number} [successfulSamplesRequired] The number of samples within
* the sample period that must succeed
* @member {number} [additionalLatencyMilliseconds] The additional latency in
* milliseconds for probes to fall into the lowest latency bucket
* @member {string} [resourceState] Resource status. Possible values include:
* 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
*/
export interface LoadBalancingSettingsModel extends SubResource {
sampleSize?: number;
successfulSamplesRequired?: number;
additionalLatencyMilliseconds?: number;
resourceState?: string;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the HealthProbeSettingsModel class.
* @constructor
* Load balancing settings for a backend pool
*
* @member {string} [path] The path to use for the health probe. Default is /
* @member {string} [protocol] Protocol scheme to use for this probe. Possible
* values include: 'Http', 'Https'
* @member {number} [intervalInSeconds] The number of seconds between health
* probes.
* @member {string} [resourceState] Resource status. Possible values include:
* 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
*/
export interface HealthProbeSettingsModel extends SubResource {
path?: string;
protocol?: string;
intervalInSeconds?: number;
resourceState?: string;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the BackendPool class.
* @constructor
* A backend pool is a collection of backends that can be routed to.
*
* @member {array} [backends] The set of backends for this pool
* @member {object} [loadBalancingSettings] Load balancing settings for a
* backend pool
* @member {string} [loadBalancingSettings.id] Resource ID.
* @member {object} [healthProbeSettings] L7 health probe settings for a
* backend pool
* @member {string} [healthProbeSettings.id] Resource ID.
* @member {string} [resourceState] Resource status. Possible values include:
* 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
*/
export interface BackendPool extends SubResource {
backends?: Backend[];
loadBalancingSettings?: SubResource;
healthProbeSettings?: SubResource;
resourceState?: string;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the KeyVaultCertificateSourceParametersVault class.
* @constructor
* The Key Vault containing the SSL certificate
*
* @member {string} [id] Resource ID.
*/
export interface KeyVaultCertificateSourceParametersVault {
id?: string;
}
/**
* @class
* Initializes a new instance of the CustomHttpsConfiguration class.
* @constructor
* Https settings for a domain
*
* @member {string} [certificateSource] Defines the source of the SSL
* certificate. Possible values include: 'AzureKeyVault', 'FrontDoor'
* @member {string} [protocolType] Defines the TLS extension protocol that is
* used for secure delivery. Possible values include: 'ServerNameIndication'
* @member {object} [vault] The Key Vault containing the SSL certificate
* @member {string} [vault.id] Resource ID.
* @member {string} [secretName] The name of the Key Vault secret representing
* the full certificate PFX
* @member {string} [secretVersion] The version of the Key Vault secret
* representing the full certificate PFX
* @member {string} [certificateType] Defines the type of the certificate used
* for secure connections to a frontendEndpoint. Possible values include:
* 'Dedicated'
*/
export interface CustomHttpsConfiguration {
certificateSource?: string;
protocolType?: string;
vault?: KeyVaultCertificateSourceParametersVault;
secretName?: string;
secretVersion?: string;
certificateType?: string;
}
/**
* @class
* Initializes a new instance of the FrontendEndpoint class.
* @constructor
* A frontend endpoint used for routing.
*
* @member {string} [hostName] The host name of the frontendEndpoint. Must be a
* domain name.
* @member {string} [sessionAffinityEnabledState] Whether to allow session
* affinity on this host. Valid options are 'Enabled' or 'Disabled'. Possible
* values include: 'Enabled', 'Disabled'
* @member {number} [sessionAffinityTtlSeconds] UNUSED. This field will be
* ignored. The TTL to use in seconds for session affinity, if applicable.
* @member {object} [webApplicationFirewallPolicyLink] Defines the Web
* Application Firewall policy for each host (if applicable)
* @member {string} [webApplicationFirewallPolicyLink.id] Resource ID.
* @member {string} [resourceState] Resource status. Possible values include:
* 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled', 'Deleting'
* @member {string} [customHttpsProvisioningState] Provisioning status of
* Custom Https of the frontendEndpoint. Possible values include: 'Enabling',
* 'Enabled', 'Disabling', 'Disabled', 'Failed'
* @member {string} [customHttpsProvisioningSubstate] Provisioning substate
* shows the progress of custom HTTPS enabling/disabling process step by step.
* Possible values include: 'SubmittingDomainControlValidationRequest',
* 'PendingDomainControlValidationREquestApproval',
* 'DomainControlValidationRequestApproved',
* 'DomainControlValidationRequestRejected',
* 'DomainControlValidationRequestTimedOut', 'IssuingCertificate',
* 'DeployingCertificate', 'CertificateDeployed', 'DeletingCertificate',
* 'CertificateDeleted'
* @member {object} [customHttpsConfiguration] The configuration specifying how
* to enable HTTPS
* @member {string} [customHttpsConfiguration.certificateSource] Defines the
* source of the SSL certificate. Possible values include: 'AzureKeyVault',
* 'FrontDoor'
* @member {string} [customHttpsConfiguration.protocolType] Defines the TLS
* extension protocol that is used for secure delivery. Possible values
* include: 'ServerNameIndication'
* @member {object} [customHttpsConfiguration.vault] The Key Vault containing
* the SSL certificate
* @member {string} [customHttpsConfiguration.vault.id] Resource ID.
* @member {string} [customHttpsConfiguration.secretName] The name of the Key
* Vault secret representing the full certificate PFX
* @member {string} [customHttpsConfiguration.secretVersion] The version of the
* Key Vault secret representing the full certificate PFX
* @member {string} [customHttpsConfiguration.certificateType] Defines the type
* of the certificate used for secure connections to a frontendEndpoint.
* Possible values include: 'Dedicated'
* @member {string} [name] Resource name.
* @member {string} [type] Resource type.
*/
export interface FrontendEndpoint extends SubResource {
hostName?: string;
sessionAffinityEnabledState?: string;
sessionAffinityTtlSeconds?: number;
webApplicationFirewallPolicyLink?: FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink;
resourceState?: string;
readonly customHttpsProvisioningState?: string;
readonly customHttpsProvisioningSubstate?: string;
readonly customHttpsConfiguration?: CustomHttpsConfiguration;
name?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the FrontDoorUpdateParameters class.
* @constructor
* The properties needed to update a Front Door
*
* @member {string} [friendlyName] A friendly name for the frontDoor
* @member {array} [routingRules] Routing rules associated with this Front
* Door.
* @member {array} [loadBalancingSettings] Load balancing settings associated
* with this Front Door instance.
* @member {array} [healthProbeSettings] Health probe settings associated with
* this Front Door instance.
* @member {array} [backendPools] Backend pools available to routing rules.
* @member {array} [frontendEndpoints] Frontend endpoints available to routing
* rules.
* @member {string} [enabledState] Operational status of the Front Door load
* balancer. Permitted values are 'Enabled' or 'Disabled'. Possible values
* include: 'Enabled', 'Disabled'
*/
export interface FrontDoorUpdateParameters {
friendlyName?: string;
routingRules?: RoutingRule[];
loadBalancingSettings?: LoadBalancingSettingsModel[];
healthProbeSettings?: HealthProbeSettingsModel[];
backendPools?: BackendPool[];
frontendEndpoints?: FrontendEndpoint[];
enabledState?: string;
}
/**
* @class
* Initializes a new instance of the PurgeParameters class.
* @constructor
* Parameters required for content purge.
*
* @member {array} contentPaths The path to the content to be purged. Can
* describe a file path or a wild card directory.
*/
export interface PurgeParameters {
contentPaths: string[];
}
/**
* @class
* Initializes a new instance of the CacheConfiguration class.
* @constructor
* Caching settings for a caching-type route. To disable caching, do not
* provide a cacheConfiguration object.
*
* @member {string} [queryParameterStripDirective] Treatment of URL query terms
* when forming the cache key. Possible values include: 'StripNone', 'StripAll'
* @member {string} [dynamicCompression] Whether to use dynamic compression for
* cached content. Possible values include: 'Enabled', 'Disabled'
*/
export interface CacheConfiguration {
queryParameterStripDirective?: string;
dynamicCompression?: string;
}
/**
* @class
* Initializes a new instance of the RoutingRuleUpdateParameters class.
* @constructor
* Routing rules to apply to an endpoint
*
* @member {array} [frontendEndpoints] Frontend endpoints associated with this
* rule
* @member {array} [acceptedProtocols] Protocol schemes to match for this rule
* @member {array} [patternsToMatch] The route patterns of the rule.
* @member {string} [customForwardingPath] A custom path used to rewrite
* resource paths matched by this rule. Leave empty to use incoming path.
* @member {string} [forwardingProtocol] Protocol this rule will use when
* forwarding traffic to backends. Possible values include: 'HttpOnly',
* 'HttpsOnly', 'MatchRequest'
* @member {object} [cacheConfiguration] The caching configuration associated
* with this rule.
* @member {string} [cacheConfiguration.queryParameterStripDirective] Treatment
* of URL query terms when forming the cache key. Possible values include:
* 'StripNone', 'StripAll'
* @member {string} [cacheConfiguration.dynamicCompression] Whether to use
* dynamic compression for cached content. Possible values include: 'Enabled',
* 'Disabled'
* @member {object} [backendPool] A reference to the BackendPool which this
* rule routes to.
* @member {string} [backendPool.id] Resource ID.
* @member {string} [enabledState] Whether to enable use of this rule.
* Permitted values are 'Enabled' or 'Disabled'. Possible values include:
* 'Enabled', 'Disabled'
*/
export interface RoutingRuleUpdateParameters {
frontendEndpoints?: SubResource[];
acceptedProtocols?: string[];
patternsToMatch?: string[];
customForwardingPath?: string;
forwardingProtocol?: string;
cacheConfiguration?: CacheConfiguration;
backendPool?: SubResource;
enabledState?: string;
}
/**
* @class
* Initializes a new instance of the Backend class.
* @constructor
* Backend address of a frontDoor load balancer.
*
* @member {string} [address] Location of the backend (IP address or FQDN)
* @member {number} [httpPort] The HTTP TCP port number. Must be between 1 and
* 65535.
* @member {number} [httpsPort] The HTTPS TCP port number. Must be between 1
* and 65535.
* @member {string} [enabledState] Whether to enable use of this backend.
* Permitted values are 'Enabled' or 'Disabled'. Possible values include:
* 'Enabled', 'Disabled'
* @member {number} [priority] Priority to use for load balancing. Higher
* priorities will not be used for load balancing if any lower priority backend
* is healthy.
* @member {number} [weight] Weight of this endpoint for load balancing
* purposes.
* @member {string} [backendHostHeader] The value to use as the host header
* sent to the backend. If blank or unspecified, this defaults to the incoming
* host.
*/
export interface Backend {
address?: string;
httpPort?: number;
httpsPort?: number;
enabledState?: string;
priority?: number;
weight?: number;
backendHostHeader?: string;
}
/**
* @class
* Initializes a new instance of the LoadBalancingSettingsUpdateParameters class.
* @constructor
* Round-Robin load balancing settings for a backend pool
*
* @member {number} [sampleSize] The number of samples to consider for load
* balancing decisions
* @member {number} [successfulSamplesRequired] The number of samples within
* the sample period that must succeed
* @member {number} [additionalLatencyMilliseconds] The additional latency in
* milliseconds for probes to fall into the lowest latency bucket
*/
export interface LoadBalancingSettingsUpdateParameters {
sampleSize?: number;
successfulSamplesRequired?: number;
additionalLatencyMilliseconds?: number;
}
/**
* @class
* Initializes a new instance of the HealthProbeSettingsUpdateParameters class.
* @constructor
* L7 health probe settings for a backend pool
*
* @member {string} [path] The path to use for the health probe. Default is /
* @member {string} [protocol] Protocol scheme to use for this probe. Possible
* values include: 'Http', 'Https'
* @member {number} [intervalInSeconds] The number of seconds between health
* probes.
*/
export interface HealthProbeSettingsUpdateParameters {
path?: string;
protocol?: string;
intervalInSeconds?: number;
}
/**
* @class
* Initializes a new instance of the BackendPoolUpdateParameters class.
* @constructor
* A collection of backends that can be routed to.
*
* @member {array} [backends] The set of backends for this pool
* @member {object} [loadBalancingSettings] Load balancing settings for a
* backend pool
* @member {string} [loadBalancingSettings.id] Resource ID.
* @member {object} [healthProbeSettings] L7 health probe settings for a
* backend pool
* @member {string} [healthProbeSettings.id] Resource ID.
*/
export interface BackendPoolUpdateParameters {
backends?: Backend[];
loadBalancingSettings?: SubResource;
healthProbeSettings?: SubResource;
}
/**
* @class
* Initializes a new instance of the FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink class.
* @constructor
* Defines the Web Application Firewall policy for each host (if applicable)
*
* @member {string} [id] Resource ID.
*/
export interface FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink {
id?: string;
}
/**
* @class
* Initializes a new instance of the FrontendEndpointUpdateParameters class.
* @constructor
* Frontend endpoint used in routing rule
*
* @member {string} [hostName] The host name of the frontendEndpoint. Must be a
* domain name.
* @member {string} [sessionAffinityEnabledState] Whether to allow session
* affinity on this host. Valid options are 'Enabled' or 'Disabled'. Possible
* values include: 'Enabled', 'Disabled'
* @member {number} [sessionAffinityTtlSeconds] UNUSED. This field will be
* ignored. The TTL to use in seconds for session affinity, if applicable.
* @member {object} [webApplicationFirewallPolicyLink] Defines the Web
* Application Firewall policy for each host (if applicable)
* @member {string} [webApplicationFirewallPolicyLink.id] Resource ID.
*/
export interface FrontendEndpointUpdateParameters {
hostName?: string;
sessionAffinityEnabledState?: string;
sessionAffinityTtlSeconds?: number;
webApplicationFirewallPolicyLink?: FrontendEndpointUpdateParametersWebApplicationFirewallPolicyLink;
}
/**
* @class
* Initializes a new instance of the ValidateCustomDomainInput class.
* @constructor
* Input of the custom domain to be validated for DNS mapping.
*
* @member {string} hostName The host name of the custom domain. Must be a
* domain name.
*/
export interface ValidateCustomDomainInput {
hostName: string;
}
/**
* @class
* Initializes a new instance of the ValidateCustomDomainOutput class.
* @constructor
* Output of custom domain validation.
*
* @member {boolean} [customDomainValidated] Indicates whether the custom
* domain is valid or not.
* @member {string} [reason] The reason why the custom domain is not valid.
* @member {string} [message] Error message describing why the custom domain is
* not valid.
*/
export interface ValidateCustomDomainOutput {
readonly customDomainValidated?: boolean;
readonly reason?: string;
readonly message?: string;
}
/**
* @class
* Initializes a new instance of the ErrorResponse class.
* @constructor
* Error reponse indicates Front Door service is not able to process the
* incoming request. The reason is provided in the error message.
*
* @member {string} [code] Error code.
* @member {string} [message] Error message indicating why the operation
* failed.
*/
export interface ErrorResponse {
readonly code?: string;
readonly message?: string;
}
/**
* @class
* Initializes a new instance of the CheckNameAvailabilityInput class.
* @constructor
* Input of CheckNameAvailability API.
*
* @member {string} name The resource name to validate.
* @member {string} type The type of the resource whose name is to be
* validated. Possible values include: 'Microsoft.Network/frontDoors',
* 'Microsoft.Network/frontDoors/frontendEndpoints'
*/
export interface CheckNameAvailabilityInput {
name: string;
type: string;
}
/**
* @class
* Initializes a new instance of the CheckNameAvailabilityOutput class.
* @constructor
* Output of check name availability API.
*
* @member {string} [nameAvailability] Indicates whether the name is available.
* Possible values include: 'Available', 'Unavailable'
* @member {string} [reason] The reason why the name is not available.
* @member {string} [message] The detailed error message describing why the
* name is not available.
*/
export interface CheckNameAvailabilityOutput {
readonly nameAvailability?: string;
readonly reason?: string;
readonly message?: string;
}
/**
* @class
* Initializes a new instance of the ErrorDetails class.
* @constructor
* @member {string} [code]
* @member {string} [target]
* @member {string} [message]
*/
export interface ErrorDetails {
code?: string;
target?: string;
message?: string;
}
/**
* @class
* Initializes a new instance of the ErrorModel class.
* @constructor
* @member {string} [code]
* @member {string} [message]
* @member {string} [target]
* @member {array} [details]
* @member {string} [innerError]
*/
export interface ErrorModel {
code?: string;
message?: string;
target?: string;
details?: ErrorDetails[];
innerError?: string;
}
/**
* @class
* Initializes a new instance of the AzureAsyncOperationResult class.
* @constructor
* The response body contains the status of the specified asynchronous
* operation, indicating whether it has succeeded, is in progress, or has
* failed. Note that this status is distinct from the HTTP status code returned
* for the Get Operation Status operation itself. If the asynchronous operation
* succeeded, the response body includes the HTTP status code for the
* successful request. If the asynchronous operation failed, the response body
* includes the HTTP status code for the failed request and error information
* regarding the failure.
*
* @member {string} [status] Status of the Azure async operation. Possible
* values are: 'InProgress', 'Succeeded', and 'Failed'. Possible values
* include: 'InProgress', 'Succeeded', 'Failed'
* @member {object} [error]
* @member {string} [error.code]
* @member {string} [error.message]
* @member {string} [error.target]
* @member {array} [error.details]
* @member {string} [error.innerError]
*/
export interface AzureAsyncOperationResult {
status?: string;
error?: ErrorModel;
}
/**
* @class
* Initializes a new instance of the TagsObject class.
* @constructor
* Tags object for patch operations.
*
* @member {object} [tags] Resource tags.
*/
export interface TagsObject {
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the PolicySettings class.
* @constructor
* Defines contents of a web application firewall global configuration
*
* @member {string} [enabledState] describes if the policy is in enabled state
* or disabled state. Possible values include: 'Disabled', 'Enabled'
* @member {string} [mode] Describes if it is in detection mode or prevention
* mode at policy level. Possible values include: 'Prevention', 'Detection'
*/
export interface PolicySettings {
enabledState?: string;
mode?: string;
}
/**
* @class
* Initializes a new instance of the MatchCondition1 class.
* @constructor
* Define match conditions
*
* @member {string} matchVariable Match Variable. Possible values include:
* 'RemoteAddr', 'RequestMethod', 'QueryString', 'PostArgs', 'RequestUri',
* 'RequestHeader', 'RequestBody'
* @member {string} [selector] Name of selector in RequestHeader or RequestBody
* to be matched
* @member {string} operator Describes operator to be matched. Possible values
* include: 'Any', 'IPMatch', 'GeoMatch', 'Equal', 'Contains', 'LessThan',
* 'GreaterThan', 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith',
* 'EndsWith'
* @member {boolean} [negateCondition] Describes if this is negate condition or
* not
* @member {array} matchValue Match value
*/
export interface MatchCondition1 {
matchVariable: string;
selector?: string;
operator: string;
negateCondition?: boolean;
matchValue: string[];
}
/**
* @class
* Initializes a new instance of the CustomRule class.
* @constructor
* Defines contents of a web application rule
*
* @member {string} [name] Gets name of the resource that is unique within a
* policy. This name can be used to access the resource.
* @member {string} [etag] Gets a unique read-only string that changes whenever
* the resource is updated.
* @member {number} priority Describes priority of the rule. Rules with a lower
* value will be evaluated before rules with a higher value
* @member {string} ruleType Describes type of rule. Possible values include:
* 'MatchRule', 'RateLimitRule'
* @member {number} [rateLimitDurationInMinutes] Defines rate limit duration.
* Default - 1 minute
* @member {number} [rateLimitThreshold] Defines rate limit thresold
* @member {array} matchConditions List of match conditions
* @member {string} action Type of Actions. Possible values include: 'Allow',
* 'Block', 'Log'
* @member {array} [transforms] List of transforms
*/
export interface CustomRule {
name?: string;
readonly etag?: string;
priority: number;
ruleType: string;
rateLimitDurationInMinutes?: number;
rateLimitThreshold?: number;
matchConditions: MatchCondition1[];
action: string;
transforms?: string[];
}
/**
* @class
* Initializes a new instance of the CustomRules class.
* @constructor
* Defines contents of custom rules
*
* @member {array} [rules] List of rules
*/
export interface CustomRules {
rules?: CustomRule[];
}
/**
* @class
* Initializes a new instance of the ManagedRuleSet class.
* @constructor
* Base class for all types of ManagedRuleSet.
*
* @member {number} [priority] Describes priority of the rule
* @member {number} [version] defines version of the ruleset
* @member {string} ruleSetType Polymorphic Discriminator
*/
export interface ManagedRuleSet {
priority?: number;
version?: number;
ruleSetType: string;
}
/**
* @class
* Initializes a new instance of the ManagedRuleSets class.
* @constructor
* Defines ManagedRuleSets - array of managedRuleSet
*
* @member {array} [ruleSets] List of rules
*/
export interface ManagedRuleSets {
ruleSets?: ManagedRuleSet[];
}
/**
* @class
* Initializes a new instance of the WebApplicationFirewallPolicy1 class.
* @constructor
* Defines web application firewall policy.
*
* @member {object} [policySettings] Describes policySettings for policy
* @member {string} [policySettings.enabledState] describes if the policy is in
* enabled state or disabled state. Possible values include: 'Disabled',
* 'Enabled'
* @member {string} [policySettings.mode] Describes if it is in detection mode
* or prevention mode at policy level. Possible values include: 'Prevention',
* 'Detection'
* @member {object} [customRules] Describes custom rules inside the policy
* @member {array} [customRules.rules] List of rules
* @member {object} [managedRules] Describes managed rules inside the policy
* @member {array} [managedRules.ruleSets] List of rules
* @member {string} [provisioningState] Provisioning state of the
* WebApplicationFirewallPolicy.
* @member {string} [resourceState] Resource status of the policy. Possible
* values include: 'Creating', 'Enabling', 'Enabled', 'Disabling', 'Disabled',
* 'Deleting'
* @member {string} [etag] Gets a unique read-only string that changes whenever
* the resource is updated.
*/
export interface WebApplicationFirewallPolicy1 extends Resource {
policySettings?: PolicySettings;
customRules?: CustomRules;
managedRules?: ManagedRuleSets;
readonly provisioningState?: string;
readonly resourceState?: string;
etag?: string;
}
/**
* @class
* Initializes a new instance of the AzureManagedOverrideRuleGroup class.
* @constructor
* Defines contents of a web application rule
*
* @member {string} ruleGroupOverride Describes overrideruleGroup. Possible
* values include: 'SqlInjection', 'XSS'
* @member {string} action Type of Actions. Possible values include: 'Allow',
* 'Block', 'Log'
*/
export interface AzureManagedOverrideRuleGroup {
ruleGroupOverride: string;
action: string;
}
/**
* @class
* Initializes a new instance of the AzureManagedRuleSet class.
* @constructor
* Describes azure managed provider.
*
* @member {array} [ruleGroupOverrides] List of azure managed provider override
* configuration (optional)
*/
export interface AzureManagedRuleSet extends ManagedRuleSet {
ruleGroupOverrides?: AzureManagedOverrideRuleGroup[];
}
/**
* @class
* Initializes a new instance of the FrontDoorListResult class.
* @constructor
* Result of the request to list Front Doors. It contains a list of Front Door
* objects and a URL link to get the the next set of results.
*
* @member {string} [nextLink] URL to get the next set of Front Door objects if
* there are any.
*/
export interface FrontDoorListResult extends Array<FrontDoor> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the RoutingRuleListResult class.
* @constructor
* Result of the request to list Routing Rules. It contains a list of Routing
* Rule objects and a URL link to get the the next set of results.
*
* @member {string} [nextLink] URL to get the next set of RoutingRule objects
* if there are any.
*/
export interface RoutingRuleListResult extends Array<RoutingRule> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the HealthProbeSettingsListResult class.
* @constructor
* Result of the request to list HealthProbeSettings. It contains a list of
* HealthProbeSettings objects and a URL link to get the the next set of
* results.
*
* @member {string} [nextLink] URL to get the next set of HealthProbeSettings
* objects if there are any.
*/
export interface HealthProbeSettingsListResult extends Array<HealthProbeSettingsModel> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the LoadBalancingSettingsListResult class.
* @constructor
* Result of the request to list load balancing settings. It contains a list of
* load balancing settings objects and a URL link to get the the next set of
* results.
*
* @member {string} [nextLink] URL to get the next set of LoadBalancingSettings
* objects if there are any.
*/
export interface LoadBalancingSettingsListResult extends Array<LoadBalancingSettingsModel> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the BackendPoolListResult class.
* @constructor
* Result of the request to list Backend Pools. It contains a list of Backend
* Pools objects and a URL link to get the the next set of results.
*
* @member {string} [nextLink] URL to get the next set of BackendPool objects
* if there are any.
*/
export interface BackendPoolListResult extends Array<BackendPool> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the FrontendEndpointsListResult class.
* @constructor
* Result of the request to list frontend endpoints. It contains a list of
* Frontend endpoint objects and a URL link to get the the next set of results.
*
* @member {string} [nextLink] URL to get the next set of frontend endpoints if
* there are any.
*/
export interface FrontendEndpointsListResult extends Array<FrontendEndpoint> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the WebApplicationFirewallPolicyListResult class.
* @constructor
* Result of the request to list WebApplicationFirewallPolicies. It contains a
* list of WebApplicationFirewallPolicy objects and a URL link to get the the
* next set of results.
*
* @member {string} [nextLink] URL to get the next set of
* WebApplicationFirewallPolicy objects if there are any.
*/
export interface WebApplicationFirewallPolicyListResult extends Array<WebApplicationFirewallPolicy1> {
nextLink?: string;
} | the_stack |
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from "vscode";
import * as path from "path";
import { BoardProvider } from "./boardProvider";
import { ProjectInitializer } from "./projectInitializer";
import { DeviceOperator } from "./DeviceOperator";
import { AzureOperator } from "./AzureOperator";
import { IoTWorkbenchSettings } from "./IoTSettings";
import { ConfigHandler } from "./configHandler";
import { CodeGeneratorCore } from "./DigitalTwin/CodeGeneratorCore";
import { ConfigKey, EventNames, FileNames } from "./constants";
import { TelemetryContext, TelemetryWorker, TelemetryResult } from "./telemetry";
import { RemoteExtension } from "./Models/RemoteExtension";
import { constructAndLoadIoTProject } from "./utils";
import { ProjectEnvironmentConfiger } from "./ProjectEnvironmentConfiger";
import { WorkbenchExtension } from "./WorkbenchExtension";
import { WorkbenchCommands, VscodeCommands } from "./common/Commands";
import { ColorizedChannel } from "./DigitalTwin/pnp/src/common/colorizedChannel";
import { Constants } from "./DigitalTwin/pnp/src/common/constants";
import { DeviceModelManager, ModelType } from "./DigitalTwin/pnp/src/deviceModel/deviceModelManager";
import { ModelRepositoryManager } from "./DigitalTwin/pnp/src/modelRepository/modelRepositoryManager";
import { IntelliSenseUtility, ModelContent } from "./DigitalTwin/pnp/src/intelliSense/intelliSenseUtility";
import { DigitalTwinCompletionItemProvider } from "./DigitalTwin/pnp/src/intelliSense/digitalTwinCompletionItemProvider";
import { DigitalTwinHoverProvider } from "./DigitalTwin/pnp/src/intelliSense/digitalTwinHoverProvider";
import { DigitalTwinDiagnosticProvider } from "./DigitalTwin/pnp/src/intelliSense/digitalTwinDiagnosticProvider";
import { Command } from "./DigitalTwin/pnp/src/common/command";
import { UserCancelledError } from "./DigitalTwin/pnp/src/common/userCancelledError";
import { UI, MessageType } from "./DigitalTwin/pnp/src/view/ui";
import { ProcessError } from "./DigitalTwin/pnp/src/common/processError";
import { SearchResult } from "./DigitalTwin/pnp/src/modelRepository/modelRepositoryInterface";
import { NSAT } from "./nsat";
import { DigitalTwinUtility } from "./DigitalTwin/DigitalTwinUtility";
const importLazy = require("import-lazy");
const exampleExplorerModule = importLazy(() => require("./exampleExplorer"))();
const request = importLazy(() => require("request-promise"))();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let telemetryWorker: any = undefined;
function printHello(context: vscode.ExtensionContext): void {
const extension = WorkbenchExtension.getExtension(context);
if (!extension) {
return;
}
const extensionId = extension.id;
console.log(`Congratulations, your extension ${extensionId} is now active!`);
}
function initCommandWithTelemetry(
context: vscode.ExtensionContext,
telemetryWorker: TelemetryWorker,
outputChannel: vscode.OutputChannel,
command: WorkbenchCommands,
eventName: string,
enableSurvey: boolean,
callback: (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetrycontext: TelemetryContext,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...args: any[]
) => // eslint-disable-next-line @typescript-eslint/no-explicit-any
any,
additionalProperties?: { [key: string]: string }
): void {
context.subscriptions.push(
vscode.commands.registerCommand(command, async (...commandArgs) =>
telemetryWorker.callCommandWithTelemetry(
context,
outputChannel,
eventName,
enableSurvey,
callback,
additionalProperties,
...commandArgs
)
)
);
}
function initCommand(
context: vscode.ExtensionContext,
command: WorkbenchCommands,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (...args: any[]) => Promise<any>
): void {
context.subscriptions.push(vscode.commands.registerCommand(command, callback));
}
function initIntelliSense(context: vscode.ExtensionContext, telemetryWorker: TelemetryWorker): void {
// init DigitalTwin graph
IntelliSenseUtility.initGraph(context);
// register providers of completionItem and hover
const selector: vscode.DocumentSelector = {
language: "json",
scheme: "file"
};
context.subscriptions.push(
vscode.languages.registerCompletionItemProvider(
selector,
new DigitalTwinCompletionItemProvider(),
Constants.COMPLETION_TRIGGER
)
);
context.subscriptions.push(vscode.languages.registerHoverProvider(selector, new DigitalTwinHoverProvider()));
// register diagnostic
let pendingDiagnostic: NodeJS.Timer;
const diagnosticCollection: vscode.DiagnosticCollection = vscode.languages.createDiagnosticCollection(
Constants.CHANNEL_NAME
);
const diagnosticProvider = new DigitalTwinDiagnosticProvider();
const activeTextEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (activeTextEditor && IntelliSenseUtility.isJsonFile(activeTextEditor.document)) {
// delay it for DigitalTwin graph initialization
pendingDiagnostic = setTimeout(
() => diagnosticProvider.updateDiagnostics(activeTextEditor.document, diagnosticCollection),
Constants.DEFAULT_TIMER_MS
);
}
context.subscriptions.push(diagnosticCollection);
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(event => {
if (event && IntelliSenseUtility.isJsonFile(event.document)) {
diagnosticProvider.updateDiagnostics(event.document, diagnosticCollection);
}
})
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument(event => {
if (event && IntelliSenseUtility.isJsonFile(event.document)) {
if (pendingDiagnostic) {
clearTimeout(pendingDiagnostic);
}
pendingDiagnostic = setTimeout(
() => diagnosticProvider.updateDiagnostics(event.document, diagnosticCollection),
Constants.DEFAULT_TIMER_MS
);
}
})
);
context.subscriptions.push(
vscode.workspace.onDidCloseTextDocument(document => {
if (IntelliSenseUtility.isJsonFile(document)) {
diagnosticCollection.delete(document.uri);
}
})
);
// send DigitalTwin usage telemetry
context.subscriptions.push(
vscode.workspace.onDidOpenTextDocument(document => {
if (IntelliSenseUtility.isJsonFile(document)) {
const modelContent: ModelContent | undefined = IntelliSenseUtility.parseDigitalTwinModel(document.getText());
if (modelContent) {
const telemetryContext: TelemetryContext = telemetryWorker.createContext();
telemetryContext.properties.result = TelemetryResult.Succeeded;
telemetryContext.properties.dtdlVersion = modelContent.version.toString();
telemetryWorker.sendEvent(Command.OpenFile, telemetryContext);
}
}
})
);
}
function initDigitalTwinCommand(
context: vscode.ExtensionContext,
telemetryWorker: TelemetryWorker,
outputChannel: ColorizedChannel,
enableSurvey: boolean,
command: Command,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
callback: (...args: any[]) => Promise<any>
): void {
context.subscriptions.push(
vscode.commands.registerCommand(
command,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (...args: any[]) => {
const start: number = Date.now();
const telemetryContext: TelemetryContext = telemetryWorker.createContext();
args.push(telemetryContext);
try {
return await callback(...args);
} catch (error) {
telemetryContext.properties.errorType = error.name;
telemetryContext.properties.errorMessage = error.message;
if (error instanceof UserCancelledError) {
telemetryContext.properties.result = TelemetryResult.Cancelled;
outputChannel.warn(error.message);
} else {
telemetryContext.properties.result = TelemetryResult.Failed;
UI.showNotification(MessageType.Error, error.message);
if (error instanceof ProcessError) {
const message = `${error.message}\n${error.stack}`;
outputChannel.error(message, error.component);
} else {
outputChannel.error(error.message);
}
}
} finally {
telemetryContext.measurements.duration = (Date.now() - start) / 1000;
telemetryWorker.sendEvent(command, telemetryContext);
outputChannel.show();
if (enableSurvey) {
NSAT.takeSurvey(context);
}
}
}
)
);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function initDigitalTwin(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel): void {
const colorizedChannel = new ColorizedChannel(Constants.CHANNEL_NAME);
context.subscriptions.push(colorizedChannel);
const deviceModelManager = new DeviceModelManager(context, colorizedChannel);
const modelRepositoryManager = new ModelRepositoryManager(context, Constants.WEB_VIEW_PATH, colorizedChannel);
DigitalTwinUtility.init(modelRepositoryManager, outputChannel);
initIntelliSense(context, telemetryWorker);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
true,
Command.CreateInterface,
async (): Promise<void> => {
return deviceModelManager.createModel(ModelType.Interface);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
true,
Command.CreateCapabilityModel,
async (): Promise<void> => {
return deviceModelManager.createModel(ModelType.CapabilityModel);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
true,
Command.OpenRepository,
async (): Promise<void> => {
return modelRepositoryManager.signIn();
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
true,
Command.SignOutRepository,
async (): Promise<void> => {
return modelRepositoryManager.signOut();
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
true,
Command.SubmitFiles,
async (telemetryContext: TelemetryContext): Promise<void> => {
return modelRepositoryManager.submitFiles(telemetryContext);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
false,
Command.DeleteModels,
async (publicRepository: boolean, modelIds: string[]): Promise<void> => {
return modelRepositoryManager.deleteModels(publicRepository, modelIds);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
false,
Command.DownloadModels,
async (publicRepository: boolean, modelIds: string[]): Promise<void> => {
return modelRepositoryManager.downloadModels(publicRepository, modelIds);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
false,
Command.SearchInterface,
async (
publicRepository: boolean,
keyword?: string,
pageSize?: number,
continuationToken?: string
): Promise<SearchResult> => {
return modelRepositoryManager.searchModel(
ModelType.Interface,
publicRepository,
keyword,
pageSize,
continuationToken
);
}
);
initDigitalTwinCommand(
context,
telemetryWorker,
colorizedChannel,
false,
Command.SearchCapabilityModel,
async (
publicRepository: boolean,
keyword?: string,
pageSize?: number,
continuationToken?: string
): Promise<SearchResult> => {
return modelRepositoryManager.searchModel(
ModelType.CapabilityModel,
publicRepository,
keyword,
pageSize,
continuationToken
);
}
);
}
function enableUsbDetector(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel): void {
if (RemoteExtension.isRemote(context)) {
return;
}
// delay to detect usb
const usbDetectorModule = importLazy(() => require("./usbDetector"))();
const usbDetector = new usbDetectorModule.UsbDetector(context, outputChannel);
usbDetector.startListening(context);
}
export async function activate(context: vscode.ExtensionContext): Promise<void> {
printHello(context);
const channelName = "Azure IoT Device Workbench";
const outputChannel: vscode.OutputChannel = vscode.window.createOutputChannel(channelName);
telemetryWorker = TelemetryWorker.getInstance(context);
context.subscriptions.push(telemetryWorker);
// Load iot Project here and do not ask to new an iot project when no iot
// project open since no command has been triggered yet.
const telemetryContext = telemetryWorker.createContext();
await constructAndLoadIoTProject(context, outputChannel, telemetryContext, true);
const deviceOperator = new DeviceOperator();
const azureOperator = new AzureOperator();
const exampleExplorer = new exampleExplorerModule.ExampleExplorer();
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.InitializeProject,
EventNames.createNewProjectEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
const projectInitializer = new ProjectInitializer();
return projectInitializer.InitializeProject(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.ConfigureProjectEnvironment,
EventNames.configProjectEnvironmentEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
const projectEnvConfiger = new ProjectEnvironmentConfiger();
return projectEnvConfiger.configureCmakeProjectEnvironment(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.AzureProvision,
EventNames.azureProvisionEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return azureOperator.provision(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.AzureDeploy,
EventNames.azureDeployEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return azureOperator.deploy(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.DeviceCompile,
EventNames.deviceCompileEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return deviceOperator.compile(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.DeviceUpload,
EventNames.deviceUploadEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return deviceOperator.upload(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.ConfigureDevice,
EventNames.configDeviceSettingsEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return deviceOperator.configDeviceSettings(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.Examples,
EventNames.openExamplePageEvent,
true,
async (
context: vscode.ExtensionContext,
_outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
return exampleExplorer.selectBoard(context, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.ExampleInitialize,
EventNames.loadExampleEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext,
name?: string,
url?: string,
boardId?: string
): Promise<void> => {
return exampleExplorer.initializeExample(context, outputChannel, telemetryContext, name, url, boardId);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.SendTelemetry,
EventNames.openTutorial,
true,
async () => {
// Do nothing.
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.IotPnPGenerateCode,
EventNames.scaffoldDeviceStubEvent,
true,
async (
context: vscode.ExtensionContext,
outputChannel: vscode.OutputChannel,
telemetryContext: TelemetryContext
): Promise<void> => {
const codeGenerator = new CodeGeneratorCore();
return codeGenerator.generateDeviceCodeStub(context, outputChannel, telemetryContext);
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.Help,
EventNames.help,
true,
async () => {
const boardId = ConfigHandler.get<string>(ConfigKey.boardId);
if (boardId) {
const boardListFolderPath = context.asAbsolutePath(
path.join(FileNames.resourcesFolderName, FileNames.templatesFolderName)
);
const boardProvider = new BoardProvider(boardListFolderPath);
const board = boardProvider.find({ id: boardId });
if (board && board.helpUrl) {
await vscode.commands.executeCommand(VscodeCommands.VscodeOpen, vscode.Uri.parse(board.helpUrl));
return;
}
}
const workbenchHelpUrl = "https://github.com/microsoft/vscode-iot-workbench/blob/master/README.md";
await vscode.commands.executeCommand(VscodeCommands.VscodeOpen, vscode.Uri.parse(workbenchHelpUrl));
return;
}
);
initCommandWithTelemetry(
context,
telemetryWorker,
outputChannel,
WorkbenchCommands.Workbench,
EventNames.setProjectDefaultPath,
true,
async () => {
RemoteExtension.ensureLocalBeforeRunCommand("set default project path", context);
const settings = await IoTWorkbenchSettings.getInstance();
await settings.setWorkbenchPath();
return;
}
);
initCommand(context, WorkbenchCommands.OpenUri, async (uri: string) => {
vscode.commands.executeCommand(VscodeCommands.VscodeOpen, vscode.Uri.parse(uri));
});
initCommand(context, WorkbenchCommands.HttpRequest, async (uri: string) => {
const res = await request(uri);
return res;
});
// delay to detect usb
setTimeout(() => {
enableUsbDetector(context, outputChannel);
}, 200);
// init DigitalTwin part
// Deprecate digital twin feature in workbench.
// initDigitalTwin(context, outputChannel);
}
// this method is called when your extension is deactivated
export async function deactivate(): Promise<void> {
// Do nothing.
} | the_stack |
import SubscriptionManager from "../../../../../main/js/joynr/dispatching/subscription/SubscriptionManager";
import MessagingQos from "../../../../../main/js/joynr/messaging/MessagingQos";
import defaultMessagingSettings from "../../../../../main/js/joynr/start/settings/defaultMessagingSettings";
import MulticastSubscriptionRequest from "../../../../../main/js/joynr/dispatching/types/MulticastSubscriptionRequest";
import SubscriptionStop from "../../../../../main/js/joynr/dispatching/types/SubscriptionStop";
import OnChangeWithKeepAliveSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeWithKeepAliveSubscriptionQos";
import OnChangeSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeSubscriptionQos";
import SubscriptionQos from "../../../../../main/js/joynr/proxy/SubscriptionQos";
import * as SubscriptionPublication from "../../../../../main/js/joynr/dispatching/types/SubscriptionPublication";
import PublicationMissedException from "../../../../../main/js/joynr/exceptions/PublicationMissedException";
import SubscriptionException from "../../../../../main/js/joynr/exceptions/SubscriptionException";
import TestEnum from "../../../../generated/joynr/tests/testTypes/TestEnum";
import TypeRegistrySingleton from "../../../../../main/js/joynr/types/TypeRegistrySingleton";
import DiscoveryEntryWithMetaInfo from "../../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo";
import Version from "../../../../../main/js/generated/joynr/types/Version";
import ProviderQos from "../../../../../main/js/generated/joynr/types/ProviderQos";
import * as UtilInternal from "../../../../../main/js/joynr/util/UtilInternal";
import testUtil = require("../../../testUtil");
describe("libjoynr-js.joynr.dispatching.subscription.SubscriptionManager", () => {
let subscriptionManager: SubscriptionManager;
let subscriptionManagerOnError: any;
let fakeTime = 1371553100000;
let dispatcherSpy: any;
let dispatcherSpyOnError: any;
let storedSubscriptionId: any;
let providerDiscoveryEntry: any;
/**
* Called before each test.
*/
beforeEach(() => {
providerDiscoveryEntry = new DiscoveryEntryWithMetaInfo({
providerVersion: new Version({ majorVersion: 0, minorVersion: 23 }),
domain: "testProviderDomain",
interfaceName: "interfaceName",
participantId: "providerParticipantId",
qos: new ProviderQos({} as any),
lastSeenDateMs: Date.now(),
expiryDateMs: Date.now() + 60000,
publicKeyId: "publicKeyId",
isLocal: true
});
dispatcherSpy = {
sendSubscriptionRequest: jest.fn(),
sendBroadcastSubscriptionRequest: jest.fn(),
sendMulticastSubscriptionStop: jest.fn(),
sendSubscriptionStop: jest.fn()
};
dispatcherSpy.sendBroadcastSubscriptionRequest.mockImplementation((settings: any) => {
storedSubscriptionId = settings.subscriptionRequest.subscriptionId;
subscriptionManager.handleSubscriptionReply({
subscriptionId: settings.subscriptionRequest.subscriptionId
} as any);
return Promise.resolve();
});
dispatcherSpy.sendSubscriptionRequest.mockImplementation((settings: any) => {
storedSubscriptionId = settings.subscriptionRequest.subscriptionId;
subscriptionManager.handleSubscriptionReply({
subscriptionId: settings.subscriptionRequest.subscriptionId
} as any);
return Promise.resolve();
});
dispatcherSpy.sendSubscriptionStop.mockImplementation(() => {
return Promise.resolve();
});
subscriptionManager = new SubscriptionManager(dispatcherSpy);
dispatcherSpyOnError = {
sendSubscriptionRequest: jest.fn(),
sendBroadcastSubscriptionRequest: jest.fn(),
sendMulticastSubscriptionStop: jest.fn(),
sendSubscriptionStop: jest.fn()
};
dispatcherSpyOnError.sendBroadcastSubscriptionRequest.mockImplementation((settings: any) => {
storedSubscriptionId = settings.subscriptionRequest.subscriptionId;
subscriptionManagerOnError.handleSubscriptionReply({
_typeName: "",
subscriptionId: settings.subscriptionRequest.subscriptionId,
error: new SubscriptionException({
subscriptionId: settings.subscriptionRequest.subscriptionId,
detailMessage: ""
})
});
return Promise.resolve();
});
dispatcherSpyOnError.sendSubscriptionRequest.mockImplementation((settings: any) => {
storedSubscriptionId = settings.subscriptionRequest.subscriptionId;
subscriptionManagerOnError.handleSubscriptionReply({
_typeName: "",
subscriptionId: settings.subscriptionRequest.subscriptionId,
error: new SubscriptionException({
subscriptionId: settings.subscriptionRequest.subscriptionId,
detailMessage: ""
})
});
return Promise.resolve();
});
subscriptionManagerOnError = new SubscriptionManager(dispatcherSpyOnError);
jest.useFakeTimers();
jest.spyOn(Date, "now").mockImplementation(() => {
return fakeTime;
});
/*
* Make sure 'TestEnum' is properly registered as a type.
* Just requiring the module is insufficient since the
* automatically generated code called async methods.
* Execution might be still in progress.
*/
TypeRegistrySingleton.getInstance().addType(TestEnum);
});
afterEach(() => {
jest.useRealTimers();
});
async function increaseFakeTime(timeMs: number): Promise<void> {
fakeTime = fakeTime + timeMs;
jest.advanceTimersByTime(timeMs);
await testUtil.multipleSetImmediate();
}
it("is instantiable", () => {
expect(subscriptionManager).toBeDefined();
});
it("sends broadcast subscription requests", async () => {
const ttl = 250;
const parameters = {
proxyId: "subscriber",
providerDiscoveryEntry,
broadcastName: "broadcastName",
subscriptionQos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + ttl
})
};
let expectedDiscoveryEntry: any = UtilInternal.extendDeep({}, providerDiscoveryEntry);
expectedDiscoveryEntry.providerVersion = new Version(expectedDiscoveryEntry.providerVersion);
expectedDiscoveryEntry.qos = new ProviderQos(expectedDiscoveryEntry.qos);
expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(expectedDiscoveryEntry);
dispatcherSpy.sendBroadcastSubscriptionRequest.mockClear();
await subscriptionManager.registerBroadcastSubscription(parameters as any);
expect(dispatcherSpy.sendBroadcastSubscriptionRequest).toHaveBeenCalled();
expect(dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].messagingQos.ttl).toEqual(ttl);
expect(dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].toDiscoveryEntry).toEqual(
expectedDiscoveryEntry
);
expect(dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].from).toEqual(parameters.proxyId);
expect(
dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].subscriptionRequest.subscribedToName
).toEqual(parameters.broadcastName);
});
it("rejects broadcast subscription requests with ttl expired when no reply arrives", async () => {
const ttl = 250;
const parameters = {
proxyId: "subscriber",
providerDiscoveryEntry,
broadcastName: "broadcastName",
subscriptionQos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + ttl
})
};
dispatcherSpy.sendBroadcastSubscriptionRequest.mockReturnValue(Promise.resolve());
const promise = testUtil.reversePromise(subscriptionManager.registerBroadcastSubscription(parameters as any));
await increaseFakeTime(ttl + 1);
await promise;
});
it("alerts on missed publication and stops", async () => {
const publicationReceivedSpy = jest.fn();
const publicationMissedSpy = jest.fn();
const alertAfterIntervalMs = OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS;
const subscriptionId = await subscriptionManager.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeWithKeepAliveSubscriptionQos({
alertAfterIntervalMs,
expiryDateMs: Date.now() + 50 + 2 * alertAfterIntervalMs
}),
onReceive: publicationReceivedSpy,
onError: publicationMissedSpy
});
expect(publicationMissedSpy).not.toHaveBeenCalled();
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy).toHaveBeenCalled();
expect(publicationMissedSpy.mock.calls[0][0]).toBeInstanceOf(PublicationMissedException);
expect(publicationMissedSpy.mock.calls[0][0].subscriptionId).toEqual(subscriptionId);
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
// expiryDate should be reached, expect no more interactions
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
});
it("sets messagingQos.ttl correctly according to subscriptionQos.expiryDateMs", async () => {
const ttl = 250;
const subscriptionSettings = {
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeWithKeepAliveSubscriptionQos({
alertAfterIntervalMs: OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS,
expiryDateMs: Date.now() + ttl
}),
onReceive() {},
onError() {}
};
dispatcherSpy.sendSubscriptionRequest.mockClear();
await subscriptionManager.registerSubscription(subscriptionSettings);
await increaseFakeTime(1);
expect(dispatcherSpy.sendSubscriptionRequest.mock.calls[0][0].messagingQos.ttl).toEqual(ttl);
subscriptionSettings.qos.expiryDateMs = SubscriptionQos.NO_EXPIRY_DATE;
await subscriptionManager.registerSubscription(subscriptionSettings);
await increaseFakeTime(1);
expect(dispatcherSpy.sendSubscriptionRequest.mock.calls.length).toEqual(2);
expect(dispatcherSpy.sendSubscriptionRequest.mock.calls[1][0].messagingQos.ttl).toEqual(
defaultMessagingSettings.MAX_MESSAGING_TTL_MS
);
});
it("forwards publication payload", async () => {
const publicationReceivedSpy = jest.fn();
const publicationMissedSpy = jest.fn();
const alertAfterIntervalMs = OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS;
const resolveSpy = {
// called when the subscription is registered successfully (see below)
resolveMethod(subscriptionId: string) {
// increase time by 50ms and see if alert was triggered
increaseFakeTime(alertAfterIntervalMs / 2);
expect(publicationMissedSpy).not.toHaveBeenCalled();
const publication = SubscriptionPublication.create({
response: ["test"],
subscriptionId
});
// simulate incoming publication
subscriptionManager.handlePublication(publication);
// make sure publication payload is forwarded
expect(publicationReceivedSpy).toHaveBeenCalledWith(publication.response[0]);
increaseFakeTime(alertAfterIntervalMs / 2 + 1);
// make sure no alert is triggered if publication is received
expect(publicationMissedSpy).not.toHaveBeenCalled();
increaseFakeTime(alertAfterIntervalMs + 1);
// if no publications follow alert should be triggered again
expect(publicationMissedSpy).toHaveBeenCalled();
}
};
jest.spyOn(resolveSpy, "resolveMethod");
await subscriptionManager.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
messagingQos: new MessagingQos(undefined as any),
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeWithKeepAliveSubscriptionQos({
alertAfterIntervalMs,
expiryDateMs: Date.now() + 50 + 2 * alertAfterIntervalMs
}),
onReceive: publicationReceivedSpy,
onError: publicationMissedSpy
} as any);
});
it("augments incoming publications with information from the joynr type system", async () => {
const publicationReceivedSpy = jest.fn();
const publicationMissedSpy = jest.fn();
const resolveSpy = {
// called when the subscription is registered successfully (see below)
resolveMethod(subscriptionId: string) {
// increase time by 50ms and see if alert was triggered
increaseFakeTime(50);
expect(publicationMissedSpy).not.toHaveBeenCalled();
const publication = SubscriptionPublication.create({
response: ["ZERO"],
subscriptionId
});
// simulate incoming publication
subscriptionManager.handlePublication(publication);
// make sure publication payload is forwarded
expect(publicationReceivedSpy).toHaveBeenCalledWith(TestEnum.ZERO);
}
};
jest.spyOn(resolveSpy, "resolveMethod");
await subscriptionManager.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: TestEnum.ZERO._typeName,
qos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + 250
}),
onReceive: publicationReceivedSpy,
onError: publicationMissedSpy
});
});
it("augments incoming broadcasts with information from the joynr type system", async () => {
const publicationReceivedSpy = jest.fn();
const onErrorSpy = jest.fn();
const resolveSpy = {
// called when the subscription is registered successfully (see below)
resolveMethod(subscriptionId: string) {
const testString = "testString";
const testInt = 2;
const testEnum = TestEnum.ZERO;
expect(onErrorSpy).not.toHaveBeenCalled();
const publication = SubscriptionPublication.create({
response: [testString, testInt, testEnum.name],
subscriptionId
});
// simulate incoming publication
subscriptionManager.handlePublication(publication);
// make sure publication payload is forwarded
expect(publicationReceivedSpy).toHaveBeenCalledWith([testString, testInt, testEnum]);
}
};
jest.spyOn(resolveSpy, "resolveMethod");
await subscriptionManager.registerBroadcastSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
broadcastName: "broadcastName",
broadcastParameter: [
{
name: "param1",
type: "String"
},
{
name: "param2",
type: "Integer"
},
{
name: "param3",
type: TestEnum.ZERO._typeName
}
],
subscriptionQos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + 250
}),
onReceive: publicationReceivedSpy,
onError: onErrorSpy
} as any);
});
function createDummyBroadcastSubscriptionRequest(parameters: any) {
const onReceiveSpy = jest.fn();
const onErrorSpy = jest.fn();
return {
proxyId: "proxy",
providerDiscoveryEntry,
broadcastName: parameters.broadcastName,
broadcastParameter: [
{
name: "param1",
type: "String"
}
],
qos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + 250
}),
partitions: parameters.partitions,
selective: parameters.selective,
onReceive: onReceiveSpy,
onError: onErrorSpy
};
}
function createDummySubscriptionRequest() {
const onReceiveSpy = jest.fn();
const onErrorSpy = jest.fn();
return {
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + 250
}),
onReceive: onReceiveSpy,
onError: onErrorSpy
};
}
it("register multicast subscription request", async () => {
const request = createDummyBroadcastSubscriptionRequest({
broadcastName: "broadcastName",
selective: false
});
expect(subscriptionManager.hasMulticastSubscriptions()).toBe(false);
await subscriptionManager.registerBroadcastSubscription(request as any);
expect(dispatcherSpy.sendBroadcastSubscriptionRequest).toHaveBeenCalled();
const forwardedRequest = dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].subscriptionRequest;
expect(forwardedRequest).toBeInstanceOf(MulticastSubscriptionRequest);
expect(forwardedRequest.subscribedToName).toEqual(request.broadcastName);
expect(subscriptionManager.hasMulticastSubscriptions()).toBe(true);
});
it("register and unregisters multicast subscription request", async () => {
const request = createDummyBroadcastSubscriptionRequest({
broadcastName: "broadcastName",
selective: false
});
expect(subscriptionManager.hasMulticastSubscriptions()).toBe(false);
const subscriptionId = await subscriptionManager.registerBroadcastSubscription(request as any);
expect(subscriptionManager.hasMulticastSubscriptions()).toBe(true);
await subscriptionManager.unregisterSubscription({
subscriptionId
} as any);
expect(subscriptionManager.hasMulticastSubscriptions()).toBe(false);
expect(subscriptionManager.hasOpenSubscriptions()).toBe(false);
});
it("is able to handle multicast publications", async () => {
const request: any = createDummyBroadcastSubscriptionRequest({
broadcastName: "broadcastName",
selective: false
});
const response = ["response"];
request.subscriptionId = await subscriptionManager.registerBroadcastSubscription(request);
request.multicastId =
dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].subscriptionRequest.multicastId;
subscriptionManager.handleMulticastPublication({
multicastId: request.multicastId,
response
} as any);
expect(request.onReceive).toHaveBeenCalled();
expect(request.onReceive).toHaveBeenCalledWith(response);
//stop subscription
request.onReceive.mockClear();
await subscriptionManager.unregisterSubscription({
subscriptionId: request.subscriptionId
} as any);
//send another publication and do not expect calls
expect(subscriptionManager.hasOpenSubscriptions()).toBe(false);
expect(() => {
subscriptionManager.handleMulticastPublication({
multicastId: request.multicastId,
response
} as any);
}).toThrow();
expect(request.onReceive).not.toHaveBeenCalled();
});
it("sends out subscriptionStop and stops alerts on unsubscribe", async () => {
const publicationReceivedSpy = jest.fn();
const publicationMissedSpy = jest.fn();
const alertAfterIntervalMs = OnChangeWithKeepAliveSubscriptionQos.DEFAULT_MAX_INTERVAL_MS;
let expectedDiscoveryEntry: any = UtilInternal.extendDeep({}, providerDiscoveryEntry);
expectedDiscoveryEntry.providerVersion = new Version(expectedDiscoveryEntry.providerVersion);
expectedDiscoveryEntry.qos = new ProviderQos(expectedDiscoveryEntry.qos);
expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(expectedDiscoveryEntry);
const subscriptionId = await subscriptionManager.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeWithKeepAliveSubscriptionQos({
alertAfterIntervalMs,
expiryDateMs: Date.now() + 5 * alertAfterIntervalMs
}),
onReceive: publicationReceivedSpy,
onError: publicationMissedSpy
});
await increaseFakeTime(alertAfterIntervalMs / 2);
expect(publicationMissedSpy).not.toHaveBeenCalled();
await increaseFakeTime(alertAfterIntervalMs / 2 + 1);
expect(publicationMissedSpy).toHaveBeenCalled();
await increaseFakeTime(101);
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
// unsubscribe and expect no more missed publication alerts
const unsubscrMsgQos = new MessagingQos();
await subscriptionManager.unregisterSubscription({
subscriptionId,
messagingQos: unsubscrMsgQos
});
const subscriptionStop = new SubscriptionStop({
subscriptionId
});
expect(dispatcherSpy.sendSubscriptionStop).toHaveBeenCalledWith({
from: "subscriber",
toDiscoveryEntry: expectedDiscoveryEntry,
subscriptionStop,
messagingQos: unsubscrMsgQos
});
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
await increaseFakeTime(alertAfterIntervalMs + 1);
expect(publicationMissedSpy.mock.calls.length).toEqual(2);
});
it("sends out MulticastSubscriptionStop", async () => {
const request = createDummyBroadcastSubscriptionRequest({
broadcastName: "broadcastName",
selective: false
});
let expectedDiscoveryEntry: any = UtilInternal.extendDeep({}, providerDiscoveryEntry);
expectedDiscoveryEntry.providerVersion = new Version(expectedDiscoveryEntry.providerVersion);
expectedDiscoveryEntry.qos = new ProviderQos(expectedDiscoveryEntry.qos);
expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(expectedDiscoveryEntry);
const subscriptionId = await subscriptionManager.registerBroadcastSubscription(request as any);
expect(dispatcherSpy.sendBroadcastSubscriptionRequest).toHaveBeenCalled();
const multicastId =
dispatcherSpy.sendBroadcastSubscriptionRequest.mock.calls[0][0].subscriptionRequest.multicastId;
expect(multicastId).toBeDefined();
expect(multicastId).not.toEqual(null);
const unsubscrMsgQos = new MessagingQos();
await subscriptionManager.unregisterSubscription({
subscriptionId,
messagingQos: unsubscrMsgQos
});
const subscriptionStop = new SubscriptionStop({
subscriptionId
});
expect(dispatcherSpy.sendMulticastSubscriptionStop).toHaveBeenCalledWith({
from: request.proxyId,
toDiscoveryEntry: expectedDiscoveryEntry,
messagingQos: unsubscrMsgQos,
multicastId,
subscriptionStop
});
});
it("returns a rejected promise when unsubscribing with a non-existant subscriptionId", async () => {
const error = await testUtil.reversePromise(
subscriptionManager.unregisterSubscription({
subscriptionId: "non-existant"
} as any)
);
expect(error).toBeDefined();
const className = Object.prototype.toString.call(error).slice(8, -1);
expect(className).toMatch("Error");
});
it("registers subscription, resolves with subscriptionId and calls onSubscribed callback", async () => {
const publicationReceivedSpy = jest.fn();
const publicationErrorSpy = jest.fn();
const publicationSubscribedSpy = jest.fn();
dispatcherSpy.sendSubscriptionRequest.mockClear();
let expectedDiscoveryEntry: any = UtilInternal.extendDeep({}, providerDiscoveryEntry);
expectedDiscoveryEntry.providerVersion = new Version(providerDiscoveryEntry.providerVersion);
expectedDiscoveryEntry.qos = new ProviderQos(providerDiscoveryEntry.qos);
expectedDiscoveryEntry = new DiscoveryEntryWithMetaInfo(expectedDiscoveryEntry);
const receivedSubscriptionId = await subscriptionManager.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeSubscriptionQos(),
onReceive: publicationReceivedSpy,
onError: publicationErrorSpy,
onSubscribed: publicationSubscribedSpy
});
expect(receivedSubscriptionId).toBeDefined();
expect(receivedSubscriptionId).toEqual(storedSubscriptionId);
await testUtil.multipleSetImmediate();
expect(publicationReceivedSpy).not.toHaveBeenCalled();
expect(publicationErrorSpy).not.toHaveBeenCalled();
expect(publicationSubscribedSpy).toHaveBeenCalled();
expect(publicationSubscribedSpy.mock.calls[0][0]).toEqual(storedSubscriptionId);
expect(dispatcherSpy.sendSubscriptionRequest).toHaveBeenCalled();
expect(dispatcherSpy.sendSubscriptionRequest.mock.calls[0][0].toDiscoveryEntry).toEqual(expectedDiscoveryEntry);
});
it("rejects subscription requests with ttl expired when no reply arrives", async () => {
const ttl = 250;
const parameters = {
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeSubscriptionQos({
expiryDateMs: Date.now() + ttl
})
};
dispatcherSpy.sendSubscriptionRequest.mockResolvedValue(undefined);
const promise = testUtil.reversePromise(subscriptionManager.registerSubscription(parameters as any));
await increaseFakeTime(ttl + 1);
await promise;
});
it("registers broadcast subscription, resolves with subscriptionId and calls onSubscribed callback", async () => {
const publicationReceivedSpy = jest.fn();
const publicationErrorSpy = jest.fn();
const publicationSubscribedSpy = jest.fn();
const receivedSubscriptionId = await subscriptionManager.registerBroadcastSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
broadcastName: "broadcastName",
subscriptionQos: new OnChangeSubscriptionQos(),
onReceive: publicationReceivedSpy,
onError: publicationErrorSpy,
onSubscribed: publicationSubscribedSpy
} as any);
expect(receivedSubscriptionId).toBeDefined();
expect(receivedSubscriptionId).toEqual(storedSubscriptionId);
await testUtil.multipleSetImmediate();
expect(publicationReceivedSpy).not.toHaveBeenCalled();
expect(publicationErrorSpy).not.toHaveBeenCalled();
expect(publicationSubscribedSpy).toHaveBeenCalled();
expect(publicationSubscribedSpy.mock.calls[0][0]).toEqual(storedSubscriptionId);
});
it("rejects on subscription registration failures and calls onError callback", async () => {
const publicationReceivedSpy = jest.fn();
const publicationErrorSpy = jest.fn();
const publicationSubscribedSpy = jest.fn();
const error = await testUtil.reversePromise(
subscriptionManagerOnError.registerSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
attributeName: "testAttribute",
attributeType: "String",
qos: new OnChangeSubscriptionQos(),
onReceive: publicationReceivedSpy,
onError: publicationErrorSpy,
onSubscribed: publicationSubscribedSpy
})
);
expect(error).toBeInstanceOf(SubscriptionException);
expect(error.subscriptionId).toBeDefined();
expect(error.subscriptionId).toEqual(storedSubscriptionId);
await testUtil.multipleSetImmediate();
expect(publicationReceivedSpy).not.toHaveBeenCalled();
expect(publicationSubscribedSpy).not.toHaveBeenCalled();
expect(publicationErrorSpy).toHaveBeenCalled();
expect(publicationErrorSpy.mock.calls[0][0]).toBeInstanceOf(SubscriptionException);
expect(publicationErrorSpy.mock.calls[0][0].subscriptionId).toEqual(storedSubscriptionId);
});
it("rejects on broadcast subscription registration failures and calls onError callback", async () => {
const publicationReceivedSpy = jest.fn();
const publicationErrorSpy = jest.fn();
const publicationSubscribedSpy = jest.fn();
const error = await testUtil.reversePromise(
subscriptionManagerOnError.registerBroadcastSubscription({
proxyId: "subscriber",
providerDiscoveryEntry,
broadcastName: "broadcastName",
qos: new OnChangeSubscriptionQos(),
onReceive: publicationReceivedSpy,
onError: publicationErrorSpy,
onSubscribed: publicationSubscribedSpy
} as any)
);
expect(error).toBeInstanceOf(SubscriptionException);
expect(error.subscriptionId).toBeDefined();
expect(error.subscriptionId).toEqual(storedSubscriptionId);
await testUtil.multipleSetImmediate();
expect(publicationReceivedSpy).not.toHaveBeenCalled();
expect(publicationSubscribedSpy).not.toHaveBeenCalled();
expect(publicationErrorSpy).toHaveBeenCalled();
expect(publicationErrorSpy.mock.calls[0][0]).toBeInstanceOf(SubscriptionException);
expect(publicationErrorSpy.mock.calls[0][0].subscriptionId).toEqual(storedSubscriptionId);
});
it(" throws exception when called while shut down", async () => {
subscriptionManager.shutdown();
await testUtil.reversePromise(subscriptionManager.registerSubscription({} as any));
await testUtil.reversePromise(subscriptionManager.registerBroadcastSubscription({} as any));
expect(() => subscriptionManager.unregisterSubscription({} as any)).toThrow();
});
it(" it unsubscribes all Subscriptions when terminateSubscriptions is being called", async () => {
const subscriptionSettings = createDummySubscriptionRequest();
const broadcastSettings = createDummyBroadcastSubscriptionRequest({
broadcastName: "broadcastName",
selective: false
});
const clearSubscriptionsTimeoutMs = 1000;
const DEFAULT_TTL = 60000;
await subscriptionManager.registerSubscription(subscriptionSettings);
await subscriptionManager.registerBroadcastSubscription(broadcastSettings as any);
await subscriptionManager.terminateSubscriptions(clearSubscriptionsTimeoutMs);
subscriptionManager.shutdown();
expect(dispatcherSpy.sendSubscriptionStop).toHaveBeenCalled();
expect(dispatcherSpy.sendSubscriptionStop.mock.calls.length).toEqual(1);
expect(dispatcherSpy.sendSubscriptionStop.mock.calls[0][0].messagingQos).toEqual(
new MessagingQos({ ttl: DEFAULT_TTL })
);
expect(dispatcherSpy.sendMulticastSubscriptionStop.mock.calls[0][0].messagingQos).toEqual(
new MessagingQos({ ttl: DEFAULT_TTL })
);
expect(dispatcherSpy.sendMulticastSubscriptionStop.mock.calls.length).toEqual(1);
});
}); | the_stack |
import { Component, Element, Prop, Watch, Event, EventEmitter, h } from '@stencil/core';
import { select, event } from 'd3-selection';
import { min, max } from 'd3-array';
import { scaleBand, scaleQuantize } from 'd3-scale';
import { easeCircleIn } from 'd3-ease';
import { nest } from 'd3-collection';
import {
IBoxModelType,
IHoverStyleType,
IClickStyleType,
IAxisType,
IDataLabelType,
ITooltipLabelType,
IAccessibilityType,
IAnimationConfig,
ILegendType
} from '@visa/charts-types';
import { HeatMapDefaultValues } from './heat-map-default-values';
import 'd3-transition';
import { v4 as uuid } from 'uuid';
import Utils from '@visa/visa-charts-utils';
const {
calculateLuminance,
prepareStrokeColorsFromScheme,
verifyTextHasSpace,
checkAttributeTransitions,
createTextStrokeFilter,
drawHoverStrokes,
removeHoverStrokes,
buildStrokes,
convertColorsToTextures,
findTagLevel,
prepareRenderChange,
initializeDescriptionRoot,
initializeElementAccess,
setElementFocusHandler,
setElementAccessID,
setAccessibilityController,
hideNonessentialGroups,
setAccessTitle,
setAccessSubtitle,
setAccessLongDescription,
setAccessExecutiveSummary,
setAccessPurpose,
setAccessContext,
setAccessStatistics,
setAccessChartCounts,
setAccessXAxis,
setAccessYAxis,
setAccessStructure,
setAccessAnnotation,
retainAccessFocus,
checkAccessFocus,
setElementInteractionAccessState,
setAccessibilityDescriptionWidth,
autoTextColor,
annotate,
chartAccessors,
checkInteraction,
checkClicked,
checkHovered,
convertVisaColor,
drawAxis,
drawLegend,
drawTooltip,
formatStats,
formatDate,
getColors,
getLicenses,
getPadding,
getScopedData,
initTooltipStyle,
overrideTitleTooltip,
placeDataLabels,
scopeDataKeys,
transitionEndAll,
validateAccessibilityProps
} = Utils;
@Component({
tag: 'heat-map',
styleUrl: 'heat-map.scss'
})
export class HeatMap {
@Event() clickFunc: EventEmitter;
@Event() hoverFunc: EventEmitter;
@Event() mouseOutFunc: EventEmitter;
// Chart Attributes (1/7)
@Prop({ mutable: true }) mainTitle: string = HeatMapDefaultValues.mainTitle;
@Prop({ mutable: true }) subTitle: string = HeatMapDefaultValues.subTitle;
@Prop({ mutable: true }) height: number = HeatMapDefaultValues.height;
@Prop({ mutable: true }) width: number = HeatMapDefaultValues.width;
@Prop({ mutable: true }) highestHeadingLevel: string | number = HeatMapDefaultValues.highestHeadingLevel;
@Prop({ mutable: true }) margin: IBoxModelType = HeatMapDefaultValues.margin;
@Prop({ mutable: true }) padding: IBoxModelType = HeatMapDefaultValues.padding;
// Data (2/7)
@Prop() data: object[];
@Prop() uniqueID: string;
@Prop({ mutable: true }) xAccessor: string = HeatMapDefaultValues.xAccessor;
@Prop({ mutable: true }) yAccessor: string = HeatMapDefaultValues.yAccessor;
@Prop({ mutable: true }) valueAccessor: string = HeatMapDefaultValues.valueAccessor;
@Prop({ mutable: true }) xKeyOrder: string[];
@Prop({ mutable: true }) yKeyOrder: string[];
// Axis (3/7)
@Prop({ mutable: true }) xAxis: IAxisType = HeatMapDefaultValues.xAxis;
@Prop({ mutable: true }) yAxis: IAxisType = HeatMapDefaultValues.yAxis;
@Prop({ mutable: true }) wrapLabel: boolean = HeatMapDefaultValues.wrapLabel;
@Prop({ mutable: true }) hideAxisPath: boolean = HeatMapDefaultValues.hideAxisPath;
// Color & Shape (4/7)
@Prop({ mutable: true }) colorPalette: string = HeatMapDefaultValues.colorPalette;
@Prop({ mutable: true }) colors: string[];
@Prop({ mutable: true }) colorSteps: number = HeatMapDefaultValues.colorSteps;
@Prop({ mutable: true }) hoverStyle: IHoverStyleType = HeatMapDefaultValues.hoverStyle;
@Prop({ mutable: true }) clickStyle: IClickStyleType = HeatMapDefaultValues.clickStyle;
@Prop({ mutable: true }) cursor: string = HeatMapDefaultValues.cursor;
@Prop({ mutable: true }) shape: string = HeatMapDefaultValues.shape;
@Prop({ mutable: true }) hoverOpacity: number = HeatMapDefaultValues.hoverOpacity;
@Prop({ mutable: true }) animationConfig: IAnimationConfig = HeatMapDefaultValues.animationConfig;
@Prop({ mutable: true }) strokeWidth: number = HeatMapDefaultValues.strokeWidth;
// Data label (5/7)
@Prop({ mutable: true }) dataLabel: IDataLabelType = HeatMapDefaultValues.dataLabel;
@Prop({ mutable: true }) showTooltip: boolean = HeatMapDefaultValues.showTooltip;
@Prop({ mutable: true }) tooltipLabel: ITooltipLabelType = HeatMapDefaultValues.tooltipLabel;
@Prop({ mutable: true }) accessibility: IAccessibilityType = HeatMapDefaultValues.accessibility;
@Prop({ mutable: true }) legend: ILegendType = HeatMapDefaultValues.legend;
@Prop({ mutable: true }) annotations: object[] = HeatMapDefaultValues.annotations;
// Calculation (6/7)
@Prop({ mutable: true }) maxValueOverride: number;
@Prop({ mutable: true }) minValueOverride: number;
// Interactivity (7/7)
@Prop({ mutable: true }) hoverHighlight: object;
@Prop({ mutable: true }) clickHighlight: object[] = HeatMapDefaultValues.clickHighlight;
@Prop({ mutable: true }) interactionKeys: string[];
@Prop({ mutable: true }) suppressEvents: boolean = HeatMapDefaultValues.suppressEvents;
// Element
@Element()
heatMapEl: HTMLElement;
shouldValidateAccessibility: boolean = true;
svg: any;
root: any;
rootG: any;
tooltipG: any;
map: any;
row: any;
labelG: any;
labels: any;
references: any;
defaults: boolean;
current: any;
enter: any;
exit: any;
update: any;
enterRowWrappers: any;
updateRowWrappers: any;
exitRowWrappers: any;
enteringLabelGroups: any;
exitingLabelGroups: any;
updatingLabelGroups: any;
enterLabels: any;
updateLabels: any;
exitLabels: any;
heat: any;
rawHeat: any;
fillColors: any;
strokeColors: any;
y: any;
x: any;
innerHeight: number;
innerWidth: number;
innerPaddedHeight: number;
innerPaddedWidth: number;
nest: any = [];
datakeys: any = [];
colorArr: any;
preparedColors: any;
duration: number;
legendG: any;
preppedData: any;
interpolating: any;
tableData: any;
tableColumns: any;
updateCheck: any;
// these are added for accessibility
updated: boolean = true;
enterSize: number;
exitSize: number;
chartID: string;
xAxisElement: any;
innerInteractionKeys: any;
shouldValidate: boolean = false;
shouldUpdateData: boolean = false;
shouldSetDimensions: boolean = false;
shouldUpdateTableData: boolean = false;
shouldUpdateScales: boolean = false;
shouldResetRoot: boolean = false;
shouldSetColors: boolean = false;
shouldValidateInteractionKeys: boolean = false;
shouldFormatClickHighlight: boolean = false;
shouldFormatHoverHighlight: boolean = false;
shouldUpdateAnnotations: boolean = false;
shouldUpdateXAxis: boolean = false;
shouldUpdateYAxis: boolean = false;
shouldSetGlobalSelections: boolean = false;
shouldEnterUpdateExit: boolean = false;
shouldUpdateGeometries: boolean = false;
shouldSetSelectionClass: boolean = false;
shouldDrawInteractionState: boolean = false;
shouldUpdateLegend: boolean = false;
shouldUpdateCursor: boolean = false;
shouldBindInteractivity: boolean = false;
shouldUpdateLabels: boolean = false;
shouldSetLabelOpacity: boolean = false;
shouldSwapXAxis: boolean = false;
shouldSwapYAxis: boolean = false;
shouldUpdateDescriptionWrapper: boolean = false;
shouldSetChartAccessibilityTitle: boolean = false;
shouldSetChartAccessibilitySubtitle: boolean = false;
shouldSetChartAccessibilityLongDescription: boolean = false;
shouldSetChartAccessibilityExecutiveSummary: boolean = false;
shouldSetChartAccessibilityStatisticalNotes: boolean = false;
shouldSetChartAccessibilityStructureNotes: boolean = false;
shouldSetParentSVGAccessibility: boolean = false;
shouldSetGeometryAccessibilityAttributes: boolean = false;
shouldSetGeometryAriaLabels: boolean = false;
shouldSetGroupAccessibilityLabel: boolean = false;
shouldSetChartAccessibilityPurpose: boolean = false;
shouldSetChartAccessibilityContext: boolean = false;
shouldRedrawWrapper: boolean = false;
shouldSetTagLevels: boolean = false;
shouldSetChartAccessibilityCount: boolean = false;
shouldSetYAxisAccessibility: boolean = false;
shouldSetXAxisAccessibility: boolean = false;
shouldSetAnnotationAccessibility: boolean = false;
shouldSetTextures: boolean = false;
shouldSetStrokes: boolean = false;
strokes: any = {};
topLevel: string = 'h2';
bottomLevel: string = 'p';
@Watch('data')
dataWatcher(_newData, _oldData) {
this.updated = true;
this.shouldUpdateData = true;
this.shouldSetColors = true;
this.shouldSetGlobalSelections = true;
this.shouldUpdateScales = true;
this.shouldEnterUpdateExit = true;
this.shouldUpdateTableData = true;
this.shouldValidate = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateXAxis = true;
this.shouldUpdateYAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldDrawInteractionState = true;
this.shouldUpdateAnnotations = true;
this.shouldSetGeometryAccessibilityAttributes = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetXAxisAccessibility = true;
this.shouldSetYAxisAccessibility = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
this.shouldSetLabelOpacity = true;
}
@Watch('uniqueID')
idWatcher(newID, _oldID) {
this.chartID = newID;
this.heatMapEl.id = this.chartID;
this.shouldValidate = true;
this.shouldUpdateDescriptionWrapper = true;
this.shouldSetParentSVGAccessibility = true;
this.shouldUpdateLegend = true;
this.shouldSetTextures = true;
this.shouldDrawInteractionState = true;
this.shouldSetStrokes = true;
}
@Watch('highestHeadingLevel')
headingWatcher(_newVal, _oldVal) {
this.shouldRedrawWrapper = true;
this.shouldSetTagLevels = true;
this.shouldSetChartAccessibilityCount = true;
this.shouldSetYAxisAccessibility = true;
this.shouldSetXAxisAccessibility = true;
this.shouldUpdateDescriptionWrapper = true;
this.shouldSetAnnotationAccessibility = true;
this.shouldSetChartAccessibilityTitle = true;
this.shouldSetChartAccessibilitySubtitle = true;
this.shouldSetChartAccessibilityLongDescription = true;
this.shouldSetChartAccessibilityContext = true;
this.shouldSetChartAccessibilityExecutiveSummary = true;
this.shouldSetChartAccessibilityPurpose = true;
this.shouldSetChartAccessibilityStatisticalNotes = true;
this.shouldSetChartAccessibilityStructureNotes = true;
}
@Watch('mainTitle')
titleWatcher(_newVal, _oldVal) {
this.shouldValidate = true;
this.shouldUpdateDescriptionWrapper = true;
this.shouldSetChartAccessibilityTitle = true;
this.shouldSetParentSVGAccessibility = true;
}
@Watch('subTitle')
subtitleWatcher(_newVal, _oldVal) {
this.shouldSetChartAccessibilitySubtitle = true;
this.shouldSetParentSVGAccessibility = true;
}
@Watch('height')
@Watch('width')
@Watch('padding')
@Watch('margin')
layoutWatcher(_newVal, _oldVal) {
this.shouldSetDimensions = true;
this.shouldUpdateScales = true;
this.shouldSetTextures = true;
this.shouldResetRoot = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateXAxis = true;
this.shouldUpdateYAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetLabelOpacity = true;
}
@Watch('xAccessor')
xAccessorWatcher(_newVal, _oldVal) {
this.shouldUpdateData = true;
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldSetGlobalSelections = true;
this.shouldFormatClickHighlight = true;
this.shouldFormatHoverHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldEnterUpdateExit = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateXAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetXAxisAccessibility = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
this.shouldSetLabelOpacity = true;
}
@Watch('yAccessor')
yAccessorWatcher(_newVal, _oldVal) {
this.shouldUpdateData = true;
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldSetGlobalSelections = true;
this.shouldFormatClickHighlight = true;
this.shouldFormatHoverHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldEnterUpdateExit = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateYAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetYAxisAccessibility = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
this.shouldSetLabelOpacity = true;
}
@Watch('valueAccessor')
groupAccessorWatcher(_newVal, _oldVal) {
this.shouldUpdateData = true;
this.shouldUpdateTableData = true;
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldSetGlobalSelections = true;
this.shouldUpdateGeometries = true;
this.shouldDrawInteractionState = true;
this.shouldUpdateLegend = true;
this.shouldSetLabelOpacity = true;
this.shouldUpdateLabels = true;
this.shouldSetGeometryAriaLabels = true;
if (!(this.interactionKeys && this.interactionKeys.length)) {
this.shouldValidateInteractionKeys = true;
this.shouldSetSelectionClass = true;
}
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
}
@Watch('xKeyOrder')
xKeyOrderWatcher(_newVal, _oldVal) {
this.shouldUpdateData = true;
this.shouldUpdateScales = true;
this.shouldSetGlobalSelections = true;
this.shouldDrawInteractionState = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateXAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetGeometryAccessibilityAttributes = true;
this.shouldSetXAxisAccessibility = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
}
@Watch('yKeyOrder')
yKeyOrderWatcher(_newVal, _oldVal) {
this.shouldUpdateData = true;
this.shouldUpdateScales = true;
this.shouldSetGlobalSelections = true;
this.shouldDrawInteractionState = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateYAxis = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetGeometryAccessibilityAttributes = true;
this.shouldSetYAxisAccessibility = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
}
@Watch('xAxis')
xAxisWatcher(_newVal, _oldVal) {
const newFormatVal = _newVal && _newVal.format ? _newVal.format : false;
const oldFormatVal = _oldVal && _oldVal.format ? _oldVal.format : false;
const newPlacementVal = _newVal && _newVal.placement ? _newVal.placement : false;
const oldPlacementVal = _oldVal && _oldVal.placement ? _oldVal.placement : false;
if (newFormatVal !== oldFormatVal) {
this.shouldUpdateData = true;
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldSetTextures = true;
this.shouldSetGlobalSelections = true;
this.shouldFormatClickHighlight = true;
this.shouldFormatHoverHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldEnterUpdateExit = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
}
if (newPlacementVal !== oldPlacementVal) {
this.shouldSwapXAxis = true;
}
this.shouldUpdateXAxis = true;
this.shouldSetXAxisAccessibility = true;
}
@Watch('yAxis')
yAxisWatcher(_newVal, _oldVal) {
const newFormatVal = _newVal && _newVal.format ? _newVal.format : false;
const oldFormatVal = _oldVal && _oldVal.format ? _oldVal.format : false;
const newPlacementVal = _newVal && _newVal.placement ? _newVal.placement : false;
const oldPlacementVal = _oldVal && _oldVal.placement ? _oldVal.placement : false;
if (newFormatVal !== oldFormatVal) {
this.shouldUpdateData = true;
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldSetTextures = true;
this.shouldSetGlobalSelections = true;
this.shouldFormatClickHighlight = true;
this.shouldFormatHoverHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldEnterUpdateExit = true;
this.shouldUpdateTableData = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
}
if (newPlacementVal !== oldPlacementVal) {
this.shouldSwapYAxis = true;
}
this.shouldUpdateYAxis = true;
this.shouldSetYAxisAccessibility = true;
}
@Watch('wrapLabel')
wrapLabelWatcher(_newVal, _oldVal) {
this.shouldUpdateXAxis = true;
this.shouldUpdateYAxis = true;
}
@Watch('hideAxisPath')
hideAxisPathWatcher(_newVal, _oldVal) {
this.shouldUpdateXAxis = true;
this.shouldUpdateYAxis = true;
}
@Watch('colorPalette')
@Watch('colors')
@Watch('colorSteps')
colorsWatcher(_newVal, _oldVal) {
this.shouldSetColors = true;
this.shouldUpdateScales = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateLegend = true;
this.shouldDrawInteractionState = true;
this.shouldSetTextures = true;
this.shouldSetStrokes = true;
}
@Watch('hoverStyle')
hoverStyleWatcher(_newVal, _oldVal) {
this.shouldDrawInteractionState = true;
this.shouldSetLabelOpacity = true;
this.shouldSetStrokes = true;
}
@Watch('clickStyle')
clickStyleWatcher(_newVal, _oldVal) {
this.shouldDrawInteractionState = true;
this.shouldSetLabelOpacity = true;
this.shouldSetStrokes = true;
}
@Watch('shape')
shapeWatcher(_newVal, _oldVal) {
this.shouldUpdateGeometries = true;
}
@Watch('cursor')
cursorWatcher(_newVal, _oldVal) {
this.shouldUpdateCursor = true;
}
@Watch('strokeWidth')
strokeWidthWatcher(_newVal, _oldVal) {
this.shouldUpdateGeometries = true;
this.shouldUpdateScales = true;
this.shouldSetTextures = true;
this.shouldUpdateGeometries = true;
this.shouldSetStrokes = true;
}
@Watch('hoverOpacity')
hoverOpacityWatcher(_newVal, _oldVal) {
this.shouldSetLabelOpacity = true;
this.shouldDrawInteractionState = true;
}
@Watch('dataLabel')
labelWatcher(_newVal, _oldVal) {
this.shouldUpdateLabels = true;
this.shouldUpdateTableData = true;
const newVisibleVal = _newVal && _newVal.visible;
const oldVisibleVal = _oldVal && _oldVal.visible;
if (newVisibleVal !== oldVisibleVal) {
this.shouldSetLabelOpacity = true;
}
}
@Watch('showTooltip')
showTooltipWatcher(_newVal, _oldVal) {
// this.shouldDrawInteractionState = true;
}
@Watch('tooltipLabel')
tooltipLabelWatcher(_newVal, _oldVal) {
this.shouldUpdateTableData = true;
}
@Watch('legend')
legendWatcher(_newVal, _oldVal) {
this.shouldUpdateLegend = true;
}
@Watch('suppressEvents')
suppressWatcher(_newVal, _oldVal) {
this.shouldBindInteractivity = true;
this.shouldUpdateCursor = true;
this.shouldSetGeometryAriaLabels = true;
this.shouldSetParentSVGAccessibility = true;
this.shouldUpdateDescriptionWrapper = true;
this.shouldRedrawWrapper = true;
this.shouldValidate = true;
this.shouldSetChartAccessibilityTitle = true;
this.shouldSetChartAccessibilitySubtitle = true;
this.shouldSetChartAccessibilityLongDescription = true;
this.shouldSetChartAccessibilityContext = true;
this.shouldSetChartAccessibilityExecutiveSummary = true;
this.shouldSetChartAccessibilityPurpose = true;
this.shouldSetChartAccessibilityStatisticalNotes = true;
this.shouldSetChartAccessibilityStructureNotes = true;
}
@Watch('annotations')
annotationsWatcher(_newVal, _oldVal) {
this.shouldValidate = true;
this.shouldUpdateAnnotations = true;
this.shouldSetAnnotationAccessibility = true;
}
@Watch('accessibility')
accessibilityWatcher(_newVal, _oldVal) {
this.shouldValidate = true;
const newTitle = _newVal && _newVal.title ? _newVal.title : false;
const oldTitle = _oldVal && _oldVal.title ? _oldVal.title : false;
if (newTitle !== oldTitle) {
this.shouldUpdateDescriptionWrapper = true;
this.shouldSetChartAccessibilityTitle = true;
this.shouldSetParentSVGAccessibility = true;
}
const newExecutiveSummary = _newVal && _newVal.executiveSummary ? _newVal.executiveSummary : false;
const oldExecutiveSummary = _oldVal && _oldVal.executiveSummary ? _oldVal.executiveSummary : false;
if (newExecutiveSummary !== oldExecutiveSummary) {
this.shouldSetChartAccessibilityExecutiveSummary = true;
}
const newPurpose = _newVal && _newVal.purpose ? _newVal.purpose : false;
const oldPurpose = _oldVal && _oldVal.purpose ? _oldVal.purpose : false;
if (newPurpose !== oldPurpose) {
this.shouldSetChartAccessibilityPurpose = true;
}
const newLongDescription = _newVal && _newVal.longDescription ? _newVal.longDescription : false;
const oldLongDescription = _oldVal && _oldVal.longDescription ? _oldVal.longDescription : false;
if (newLongDescription !== oldLongDescription) {
this.shouldSetChartAccessibilityLongDescription = true;
}
const newContext = _newVal && _newVal.contextExplanation ? _newVal.contextExplanation : false;
const oldContext = _oldVal && _oldVal.contextExplanation ? _oldVal.contextExplanation : false;
if (newContext !== oldContext) {
this.shouldSetChartAccessibilityContext = true;
}
const newStatisticalNotes = _newVal && _newVal.statisticalNotes ? _newVal.statisticalNotes : false;
const oldStatisticalNotes = _oldVal && _oldVal.statisticalNotes ? _oldVal.statisticalNotes : false;
if (newStatisticalNotes !== oldStatisticalNotes) {
this.shouldSetChartAccessibilityStatisticalNotes = true;
}
const newStructureNotes = _newVal && _newVal.structureNotes ? _newVal.structureNotes : false;
const oldStructureNotes = _oldVal && _oldVal.structureNotes ? _oldVal.structureNotes : false;
if (newStructureNotes !== oldStructureNotes) {
this.shouldSetChartAccessibilityStructureNotes = true;
}
const newincludeDataKeyNames = _newVal && _newVal.includeDataKeyNames;
const oldincludeDataKeyNames = _oldVal && _oldVal.includeDataKeyNames;
const newElementDescriptionAccessor =
_newVal && _newVal.elementDescriptionAccessor ? _newVal.elementDescriptionAccessor : false;
const oldElementDescriptionAccessor =
_oldVal && _oldVal.elementDescriptionAccessor ? _oldVal.elementDescriptionAccessor : false;
if (
newincludeDataKeyNames !== oldincludeDataKeyNames ||
newElementDescriptionAccessor !== oldElementDescriptionAccessor
) {
if (newincludeDataKeyNames !== oldincludeDataKeyNames) {
// this one is tricky because it needs to run after the lifecycle
// AND it could run in the off-chance this prop is changed
this.shouldSetGroupAccessibilityLabel = true;
}
this.shouldSetGeometryAriaLabels = true;
this.shouldSetParentSVGAccessibility = true;
}
const newTextures = _newVal && _newVal.hideTextures ? _newVal.hideTextures : false;
const oldTextures = _oldVal && _oldVal.hideTextures ? _oldVal.hideTextures : false;
const newExTextures = _newVal && _newVal.showExperimentalTextures ? _newVal.showExperimentalTextures : false;
const oldExTextures = _oldVal && _oldVal.showExperimentalTextures ? _oldVal.showExperimentalTextures : false;
if (newTextures !== oldTextures || newExTextures !== oldExTextures) {
this.shouldSetTextures = true;
this.shouldUpdateLegend = true;
this.shouldSetStrokes = true;
this.shouldDrawInteractionState = true;
}
const newSmallValue = _newVal && _newVal.showSmallLabels ? _newVal.showSmallLabels : false;
const oldSmallValue = _oldVal && _oldVal.showSmallLabels ? _oldVal.showSmallLabels : false;
if (newSmallValue !== oldSmallValue) {
this.shouldSetLabelOpacity = true;
}
const newStrokes = _newVal && _newVal.hideStrokes ? _newVal.hideStrokes : false;
const oldStrokes = _oldVal && _oldVal.hideStrokes ? _oldVal.hideStrokes : false;
if (newStrokes !== oldStrokes) {
this.shouldUpdateLegend = true;
this.shouldSetStrokes = true;
this.shouldDrawInteractionState = true;
}
const newKeyNav =
_newVal && _newVal.keyboardNavConfig && _newVal.keyboardNavConfig.disabled
? _newVal.keyboardNavConfig.disabled
: false;
const oldKeyNav =
_oldVal && _oldVal.keyboardNavConfig && _oldVal.keyboardNavConfig.disabled
? _oldVal.keyboardNavConfig.disabled
: false;
const newInterface = _newVal && _newVal.elementsAreInterface ? _newVal.elementsAreInterface : false;
const oldInterface = _oldVal && _oldVal.elementsAreInterface ? _oldVal.elementsAreInterface : false;
if (newKeyNav !== oldKeyNav || newInterface !== oldInterface) {
this.shouldSetGeometryAriaLabels = true;
this.shouldSetParentSVGAccessibility = true;
this.shouldUpdateDescriptionWrapper = true;
this.shouldRedrawWrapper = true;
this.shouldSetChartAccessibilityTitle = true;
this.shouldSetChartAccessibilitySubtitle = true;
this.shouldSetChartAccessibilityLongDescription = true;
this.shouldSetChartAccessibilityContext = true;
this.shouldSetChartAccessibilityExecutiveSummary = true;
this.shouldSetChartAccessibilityPurpose = true;
this.shouldSetChartAccessibilityStatisticalNotes = true;
this.shouldSetChartAccessibilityStructureNotes = true;
}
if (newInterface !== oldInterface) {
this.shouldSetSelectionClass = true;
}
}
@Watch('maxValueOverride')
@Watch('minValueOverride')
valueOverrideWatcher(_newVal, _oldVal) {
this.shouldUpdateScales = true;
this.shouldUpdateGeometries = true;
this.shouldUpdateLabels = true;
this.shouldUpdateLegend = true;
this.shouldUpdateAnnotations = true;
this.shouldSetTextures = true;
}
@Watch('clickHighlight')
clickWatcher(_newVal, _oldVal) {
this.shouldFormatClickHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldSetLabelOpacity = true;
this.shouldSetSelectionClass = true;
}
@Watch('hoverHighlight')
hoverWatcher(_newVal, _oldVal) {
this.shouldFormatHoverHighlight = true;
this.shouldDrawInteractionState = true;
this.shouldSetLabelOpacity = true;
}
@Watch('interactionKeys')
interactionWatcher(_newVal, _oldVal) {
this.shouldValidateInteractionKeys = true;
this.shouldDrawInteractionState = true;
this.shouldSetLabelOpacity = true;
this.shouldSetSelectionClass = true;
this.shouldUpdateTableData = true;
this.shouldSetGeometryAriaLabels = true;
}
componentWillLoad() {
// contrary to componentWillUpdate, this method appears safe to use for
// any calculations we need. Keeping them here reduces future refactor,
// since componentWillUpdate should eventually mirror this method
return new Promise(resolve => {
this.duration = 0;
this.defaults = true;
this.chartID = this.uniqueID || 'heat-map-' + uuid();
this.heatMapEl.id = this.chartID;
this.setTagLevels();
this.prepareData();
this.setDimensions();
this.setColors();
this.prepareScales();
this.validateInteractionKeys();
this.setTableData();
this.shouldValidateAccessibilityProps();
this.formatClickHighlight();
this.formatHoverHighlight();
resolve('component will load');
});
}
componentWillUpdate() {
// NEVER put items in this method that rely on props (until stencil bug is resolved)
// All items that belong here are currently at the top of render
// see: https://github.com/ionic-team/stencil/issues/2061#issuecomment-578282178
return new Promise(resolve => {
resolve('component will update');
});
}
componentDidLoad() {
return new Promise(resolve => {
this.renderRootElements();
this.setTooltipInitialStyle();
this.setChartDescriptionWrapper();
this.setChartAccessibilityTitle();
this.setChartAccessibilitySubtitle();
this.setChartAccessibilityLongDescription();
this.setChartAccessibilityExecutiveSummary();
this.setChartAccessibilityPurpose();
this.setChartAccessibilityContext();
this.setChartAccessibilityStatisticalNotes();
this.setChartAccessibilityStructureNotes();
this.setParentSVGAccessibility();
this.reSetRoot();
this.setTextures();
this.setStrokes();
this.setGlobalSelections();
this.enterGeometries();
this.updateGeometries();
this.exitGeometries();
this.enterDataLabels();
this.updateDataLabels();
this.exitDataLabels();
this.drawGeometries();
this.setChartCountAccessibility();
this.setGeometryAccessibilityAttributes();
this.setGeometryAriaLabels();
this.drawDataLabels();
this.drawLegendElements();
this.setSelectedClass();
this.updateInteractionState();
this.bindInteractivity();
this.drawAnnotations();
this.setAnnotationAccessibility();
this.drawXAxis();
this.setXAxisAccessibility();
this.drawYAxis();
this.setYAxisAccessibility();
// we want to hide all child <g> of this.root BUT we want to make sure not to hide the
// parent<g> that contains our geometries! In a subGroup chart (like stacked bars),
// we want to pass the PARENT of all the <g>s that contain bars
hideNonessentialGroups(this.root.node(), this.map.node());
this.setGroupAccessibilityID();
this.onChangeHandler();
this.defaults = false;
resolve('component did load');
});
}
componentDidUpdate() {
return new Promise(resolve => {
this.duration = !this.animationConfig || !this.animationConfig.disabled ? 750 : 0;
if (this.shouldUpdateDescriptionWrapper) {
this.setChartDescriptionWrapper();
this.shouldUpdateDescriptionWrapper = false;
}
if (this.shouldSetChartAccessibilityCount) {
this.setChartCountAccessibility();
this.shouldSetChartAccessibilityCount = false;
}
if (this.shouldSetChartAccessibilityTitle) {
this.setChartAccessibilityTitle();
this.shouldSetChartAccessibilityTitle = false;
}
if (this.shouldSetChartAccessibilitySubtitle) {
this.setChartAccessibilitySubtitle();
this.shouldSetChartAccessibilitySubtitle = false;
}
if (this.shouldSetChartAccessibilityLongDescription) {
this.setChartAccessibilityLongDescription();
this.shouldSetChartAccessibilityLongDescription = false;
}
if (this.shouldSetChartAccessibilityExecutiveSummary) {
this.setChartAccessibilityExecutiveSummary();
this.shouldSetChartAccessibilityExecutiveSummary = false;
}
if (this.shouldSetChartAccessibilityPurpose) {
this.setChartAccessibilityPurpose();
this.shouldSetChartAccessibilityPurpose = false;
}
if (this.shouldSetChartAccessibilityContext) {
this.setChartAccessibilityContext();
this.shouldSetChartAccessibilityContext = false;
}
if (this.shouldSetChartAccessibilityStatisticalNotes) {
this.setChartAccessibilityStatisticalNotes();
this.shouldSetChartAccessibilityStatisticalNotes = false;
}
if (this.shouldSetChartAccessibilityStructureNotes) {
this.setChartAccessibilityStructureNotes();
this.shouldSetChartAccessibilityStructureNotes = false;
}
if (this.shouldSetParentSVGAccessibility) {
this.setParentSVGAccessibility();
this.shouldSetParentSVGAccessibility = false;
}
if (this.shouldResetRoot) {
this.reSetRoot();
this.shouldResetRoot = false;
}
if (this.shouldSetTextures) {
this.setTextures();
this.shouldSetTextures = false;
}
if (this.shouldSetStrokes) {
this.setStrokes();
this.shouldSetStrokes = false;
}
if (this.shouldSetGlobalSelections) {
this.setGlobalSelections();
this.shouldSetGlobalSelections = false;
}
if (this.shouldEnterUpdateExit) {
this.enterGeometries();
this.updateGeometries();
this.exitGeometries();
this.enterDataLabels();
this.updateDataLabels();
this.exitDataLabels();
this.shouldEnterUpdateExit = false;
}
if (this.shouldUpdateGeometries) {
this.drawGeometries();
this.shouldUpdateGeometries = false;
}
if (this.shouldSetGeometryAccessibilityAttributes) {
this.setGeometryAccessibilityAttributes();
this.shouldSetGeometryAccessibilityAttributes = false;
}
if (this.shouldSetGeometryAriaLabels) {
this.setGeometryAriaLabels();
this.shouldSetGeometryAriaLabels = false;
}
if (this.shouldSetGroupAccessibilityLabel) {
this.setGroupAccessibilityID();
this.shouldSetGroupAccessibilityLabel = false;
}
if (this.shouldUpdateLegend) {
this.drawLegendElements();
this.shouldUpdateLegend = false;
}
if (this.shouldUpdateLabels) {
this.drawDataLabels();
this.shouldUpdateLabels = false;
}
if (this.shouldDrawInteractionState) {
this.updateInteractionState();
this.shouldDrawInteractionState = false;
}
if (this.shouldSetLabelOpacity) {
this.setLabelOpacity();
this.shouldSetLabelOpacity = false;
}
if (this.shouldSetSelectionClass) {
this.setSelectedClass();
this.shouldSetSelectionClass = false;
}
if (this.shouldUpdateCursor) {
this.updateCursor();
this.shouldUpdateCursor = false;
}
if (this.shouldBindInteractivity) {
this.bindInteractivity();
this.shouldBindInteractivity = false;
}
if (this.shouldUpdateAnnotations) {
this.drawAnnotations();
this.shouldUpdateAnnotations = false;
}
if (this.shouldSetAnnotationAccessibility) {
this.setAnnotationAccessibility();
this.shouldSetAnnotationAccessibility = false;
}
if (this.shouldSwapXAxis) {
this.drawXAxis(true);
this.shouldSwapXAxis = false;
}
if (this.shouldSwapYAxis) {
this.drawYAxis(true);
this.shouldSwapYAxis = false;
}
if (this.shouldUpdateXAxis) {
this.drawXAxis();
this.shouldUpdateXAxis = false;
}
if (this.shouldSetXAxisAccessibility) {
this.setXAxisAccessibility();
this.shouldSetXAxisAccessibility = false;
}
if (this.shouldUpdateYAxis) {
this.drawYAxis();
this.shouldUpdateYAxis = false;
}
if (this.shouldSetYAxisAccessibility) {
this.setYAxisAccessibility();
this.shouldSetYAxisAccessibility = false;
}
this.onChangeHandler();
resolve('component did update');
});
}
shouldValidateAccessibilityProps() {
if (this.shouldValidateAccessibility && !this.accessibility.disableValidation) {
this.shouldValidateAccessibility = false;
validateAccessibilityProps(
this.chartID,
{ ...this.accessibility },
{
annotations: this.annotations,
data: this.data,
uniqueID: this.uniqueID,
context: {
mainTitle: this.mainTitle,
onClickFunc: !this.suppressEvents ? this.clickFunc.emit : undefined
}
}
);
}
}
formatClickHighlight() {
if (this.clickHighlight) {
this.clickHighlight.map(d => {
if (!d['xAccessor'] || !d['yAccessor']) {
d['xAccessor'] =
d[this.xAccessor] instanceof Date
? formatDate({
date: d[this.xAccessor],
format: this.xAxis.format,
offsetTimezone: true
})
: d[this.xAccessor];
d['yAccessor'] =
d[this.yAccessor] instanceof Date
? formatDate({
date: d[this.yAccessor],
format: this.yAxis.format,
offsetTimezone: true
})
: d[this.yAccessor];
}
});
}
}
formatHoverHighlight() {
if (this.hoverHighlight) {
if (!this.hoverHighlight['xAccessor'] || !this.hoverHighlight['yAccessor']) {
this.hoverHighlight['xAccessor'] =
this.hoverHighlight[this.xAccessor] instanceof Date
? formatDate({
date: this.hoverHighlight[this.xAccessor],
format: this.xAxis.format,
offsetTimezone: true
})
: this.hoverHighlight[this.xAccessor];
this.hoverHighlight['yAccessor'] =
this.hoverHighlight[this.yAccessor] instanceof Date
? formatDate({
date: this.hoverHighlight[this.yAccessor],
format: this.yAxis.format,
offsetTimezone: true
})
: this.hoverHighlight[this.yAccessor];
}
}
}
setDimensions() {
this.padding = typeof this.padding === 'string' ? getPadding(this.padding) : this.padding;
// before we render/load we need to set our height and width based on props
this.innerHeight = this.height - this.margin.top - this.margin.bottom;
this.innerWidth = this.width - this.margin.left - this.margin.right;
this.innerPaddedHeight = this.innerHeight - this.padding.top - this.padding.bottom;
this.innerPaddedWidth = this.innerWidth - this.padding.left - this.padding.right;
}
validateInteractionKeys() {
if (this.interactionKeys && this.interactionKeys.length) {
if (this.interactionKeys.includes(this.xAccessor) || this.interactionKeys.includes(this.yAccessor)) {
const checkInteractionKeys = [];
this.interactionKeys.map(k => {
const newKey = k === this.xAccessor ? 'xAccessor' : k === this.yAccessor ? 'yAccessor' : k;
checkInteractionKeys.push(newKey);
});
this.innerInteractionKeys = checkInteractionKeys;
}
} else {
// initialize interacrtionKeys prop
this.innerInteractionKeys = ['xAccessor', 'yAccessor'];
}
}
prepareScales() {
const minMapValue =
(this.minValueOverride || this.minValueOverride === 0) &&
this.minValueOverride < min(this.preppedData, d => d.valueAccessor)
? this.minValueOverride
: min(this.preppedData, d => d.valueAccessor);
const maxMapValue =
(this.maxValueOverride || this.maxValueOverride === 0) &&
this.maxValueOverride > max(this.preppedData, d => d.valueAccessor)
? this.maxValueOverride
: max(this.preppedData, d => d.valueAccessor);
this.x = scaleBand()
.domain(this.xKeyOrder ? this.xKeyOrder : this.preppedData.map(d => d.xAccessor))
.range([0, this.innerPaddedWidth]);
this.x.padding(this.strokeWidth ? this.strokeWidth / this.x.bandwidth() : 0);
this.y = scaleBand()
.domain(this.yKeyOrder ? this.yKeyOrder : this.preppedData.map(d => d.yAccessor))
.range([0, this.innerPaddedHeight]);
this.y.padding(this.strokeWidth ? this.strokeWidth / this.y.bandwidth() : 0);
this.heat = scaleQuantize().domain([minMapValue, maxMapValue]);
const strokeColors = [];
const backgroundColors = [];
let i = 0;
const half = Math.ceil(this.preparedColors.length / 2);
const isDiverging = this.colorPalette && this.colorPalette.includes('diverging');
const isDark = this.colorPalette && this.colorPalette.includes('dark');
this.preparedColors.forEach(color => {
const colorsMatchingScheme = prepareStrokeColorsFromScheme(
color,
i,
this.preparedColors,
isDiverging ? 'diverging' : 'sequential'
);
if (isDiverging) {
const fillLuminance = calculateLuminance(colorsMatchingScheme.fillColor);
const strokeLuminance = calculateLuminance(colorsMatchingScheme.textureColor);
const darkerColor =
fillLuminance > strokeLuminance ? colorsMatchingScheme.textureColor : colorsMatchingScheme.fillColor;
const lighterColor =
fillLuminance < strokeLuminance ? colorsMatchingScheme.textureColor : colorsMatchingScheme.fillColor;
if (this.preparedColors.length % 2 && i === (this.preparedColors.length - 1) / 2) {
backgroundColors.push(isDark ? darkerColor : lighterColor);
strokeColors.push(isDark ? lighterColor : darkerColor);
} else {
strokeColors.push(isDark ? darkerColor : lighterColor);
backgroundColors.push(isDark ? lighterColor : darkerColor);
}
} else {
if (i + 1 < half) {
backgroundColors.push(this.preparedColors[0]);
strokeColors.push(this.preparedColors[this.preparedColors.length - 1]);
} else {
strokeColors.push(this.preparedColors[0]);
backgroundColors.push(this.preparedColors[this.preparedColors.length - 1]);
}
}
i++;
});
this.fillColors = scaleQuantize()
.domain([minMapValue, maxMapValue])
.range(backgroundColors);
this.strokeColors = scaleQuantize()
.domain([minMapValue, maxMapValue])
.range(strokeColors);
this.rawHeat = scaleQuantize()
.domain([minMapValue, maxMapValue])
.range(this.preparedColors);
this.updateCheck = true;
}
setColors() {
this.preparedColors = this.colors ? convertVisaColor(this.colors) : getColors(this.colorPalette, this.colorSteps);
}
setTextures() {
const scheme = this.colorPalette && this.colorPalette.includes('diverging') ? 'diverging' : 'sequential';
const limit = scheme === 'diverging' ? 11 : 9;
if (this.accessibility.hideTextures || this.colorSteps > limit || !this.accessibility.showExperimentalTextures) {
this.colorArr = this.preparedColors;
} else {
const textures = convertColorsToTextures({
colors: this.preparedColors,
rootSVG: this.svg.node(),
id: this.chartID,
scheme,
disableTransitions: !this.duration
});
this.colorArr = textures;
}
this.heat.range(this.colorArr);
}
setStrokes() {
// technically the user could pass hoverstyle/clickstyle.color and we want to make sure that we intercept that
// heatmap does not use this prop, since color is bound intrinsically to value in the data
const clickStyle = { ...this.clickStyle, color: undefined };
const hoverStyle = { ...this.hoverStyle, color: undefined };
this.strokes = buildStrokes({
root: this.svg.node(),
id: this.chartID,
colors:
!this.accessibility.hideTextures && this.accessibility.showExperimentalTextures
? this.fillColors.range()
: this.preparedColors, // this.fillColors.range(), // this.divergingColors && this.divergingColors.fills.length && !this.accessibility.hideTextures ? this.divergingColors.fills : this.preparedColors,
clickStyle,
hoverStyle,
strokeOverride:
!this.accessibility.hideTextures && this.accessibility.showExperimentalTextures
? this.strokeColors.range()
: undefined
});
}
setTableData() {
// generate scoped and formatted data for data-table component
const keys = scopeDataKeys(this, chartAccessors, 'heat-map');
this.tableData = getScopedData(this.data, keys);
this.tableColumns = Object.keys(keys);
}
prepareData() {
// copy data to preppedData for data manipulation
// check data format & offset time object, create new keys for modified xAccessor, yAccessor, valueAccessor values
// this allows heatmap to share same data entries across different dimensions
if (this.updateCheck) {
this.interpolating = this.preppedData;
const oldXDomain = this.x.domain();
const oldXRange = this.x.range();
const oldYDomain = this.y.domain();
const oldYRange = this.y.range();
this.interpolating.x = scaleBand()
.domain(oldXDomain)
.range(oldXRange);
this.interpolating.y = scaleBand()
.domain(oldYDomain)
.range(oldYRange);
}
this.preppedData = this.data.map(d => {
const newRow = { ...d };
newRow['valueAccessor'] = parseFloat(d[this.valueAccessor]);
newRow['xAccessor'] =
d[this.xAccessor] instanceof Date
? formatDate({
date: d[this.xAccessor],
format: this.xAxis.format,
offsetTimezone: true
})
: d[this.xAccessor];
newRow['yAccessor'] =
d[this.yAccessor] instanceof Date
? formatDate({
date: d[this.yAccessor],
format: this.yAxis.format,
offsetTimezone: true
})
: d[this.yAccessor];
return newRow;
});
// groups each row of the heatmap to make keyboard navigation easier for accessibility
this.nest = nest()
.key(d => d[this.yAccessor])
.entries(this.preppedData);
// Get all item categories
this.datakeys = this.nest.map(d => d.key);
}
// reset graph size based on window size
reSetRoot() {
const changeSvg = prepareRenderChange({
selection: this.svg,
duration: this.duration,
namespace: 'root_reset',
easing: easeCircleIn
});
changeSvg
.attr('width', this.width)
.attr('height', this.height)
.attr('viewBox', '0 0 ' + this.width + ' ' + this.height);
const changeRoot = prepareRenderChange({
selection: this.root,
duration: this.duration,
namespace: 'root_reset',
easing: easeCircleIn
});
changeRoot.attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);
const changeRootG = prepareRenderChange({
selection: this.rootG,
duration: this.duration,
namespace: 'root_reset',
easing: easeCircleIn
});
changeRootG.attr('transform', `translate(${this.padding.left}, ${this.padding.top})`);
setAccessibilityDescriptionWidth(this.chartID, this.width);
}
drawXAxis(swapping?: boolean) {
// draw axes
drawAxis({
root: this.rootG,
height: this.innerPaddedHeight,
width: this.innerPaddedWidth,
axisScale: this.x,
top: this.xAxis.placement === 'top',
wrapLabel: this.wrapLabel ? this.x.bandwidth() : '',
format: this.xAxis.format,
tickInterval: this.xAxis.tickInterval,
label: this.xAxis.label,
padding: this.padding,
hide: swapping || !this.xAxis.visible,
duration: this.duration,
hidePath: this.hideAxisPath
});
}
drawYAxis(swapping?: boolean) {
drawAxis({
root: this.rootG,
height: this.innerPaddedHeight,
width: this.innerPaddedWidth,
axisScale: this.y,
left: this.yAxis.placement !== 'right',
right: this.yAxis.placement === 'right',
format: this.yAxis.format,
wrapLabel: this.wrapLabel ? this.padding.left || 100 : '',
tickInterval: this.yAxis.tickInterval,
label: this.yAxis.label,
padding: this.padding,
hide: swapping || !this.yAxis.visible,
duration: this.duration,
hidePath: this.hideAxisPath
});
}
setXAxisAccessibility() {
setAccessXAxis({
rootEle: this.heatMapEl,
hasXAxis: this.xAxis ? this.xAxis.visible : false,
xAxis: this.x || false, // this is optional for some charts, if hasXAxis is always false
xAxisLabel: this.xAxis ? this.xAxis.label || '' : '' // this is optional for some charts, if hasXAxis is always false
});
}
setYAxisAccessibility() {
setAccessYAxis({
rootEle: this.heatMapEl,
hasYAxis: this.yAxis ? this.yAxis.visible : false,
yAxis: this.y || false, // this is optional for some charts, if hasXAxis is always false
yAxisLabel: this.yAxis ? this.yAxis.label || '' : '' // this is optional for some charts, if hasYAxis is always false
});
}
renderRootElements() {
this.svg = select(this.heatMapEl)
.select('.visa-viz-d3-heat-map-container')
.append('svg')
.attr('width', this.width)
.attr('height', this.height)
.attr('viewBox', '0 0 ' + this.width + ' ' + this.height);
this.root = this.svg.append('g').attr('id', 'visa-viz-margin-container-g-' + this.chartID);
this.rootG = this.root.append('g').attr('id', 'visa-viz-padding-container-g-' + this.chartID);
this.map = this.rootG.append('g').attr('class', 'map-group');
this.labelG = this.rootG.append('g').attr('class', 'heat-map-dataLabel-group');
this.legendG = select(this.heatMapEl)
.select('.heat-map-legend')
.append('svg');
this.tooltipG = select(this.heatMapEl).select('.heat-map-tooltip');
}
setGlobalSelections() {
this.xAxisElement = this.rootG.selectAll('.bottom');
const dataBoundToGroups = this.map.selectAll('.row').data(this.nest, d => d.key);
this.enterRowWrappers = dataBoundToGroups.enter().append('g');
this.exitRowWrappers = dataBoundToGroups.exit();
this.updateRowWrappers = dataBoundToGroups.merge(this.enterRowWrappers);
const dataBoundToGeometries = this.updateRowWrappers
.selectAll('.grid')
.data(d => d.values, d => d.xAccessor + d.yAccessor);
this.enter = dataBoundToGeometries.enter().append('rect');
this.exit = dataBoundToGeometries.exit();
this.update = dataBoundToGeometries.merge(this.enter);
this.exitSize = this.exit.size();
this.enterSize = this.enter.size();
this.exitSize += this.exitRowWrappers.selectAll('.grid').size();
const dataBoundToLabelGroups = this.labelG.selectAll('g').data(this.nest, d => d.key);
this.enteringLabelGroups = dataBoundToLabelGroups.enter().append('g');
this.exitingLabelGroups = dataBoundToLabelGroups.exit();
this.updatingLabelGroups = dataBoundToLabelGroups.merge(this.enteringLabelGroups);
const dataBoundToLabels = this.updatingLabelGroups
.selectAll('text')
.data(d => d.values, d => d.xAccessor + d.yAccessor);
this.enterLabels = dataBoundToLabels.enter().append('text');
this.exitLabels = dataBoundToLabels.exit();
this.updateLabels = dataBoundToLabels.merge(this.enterLabels);
}
// draw heat map
enterGeometries() {
this.enter.interrupt();
this.enterRowWrappers
.attr('class', 'row')
.classed('entering', true)
.attr('cursor', !this.suppressEvents ? this.cursor : null)
.each((_, i, n) => {
// we bind accessible interactivity and semantics here (role, tabindex, etc)
initializeElementAccess(n[i]);
});
this.enter
.attr('class', 'grid')
.each((_d, i, n) => {
initializeElementAccess(n[i]);
})
.on(
'click',
!this.suppressEvents
? d => {
this.onClickHandler(d);
}
: null
)
.on(
'mouseover',
!this.suppressEvents
? d => {
this.onHoverHandler(d);
}
: null
)
.on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null)
.attr('opacity', 0)
.attr('y', d => {
if (this.interpolating && this.interpolating.y(d.yAccessor) === undefined) {
let shift = this.y(d.yAccessor);
shift = shift + this.y.bandwidth() * (shift / this.y(this.y.domain()[0]));
return shift;
} else if (this.interpolating) {
return this.interpolating.y(d.yAccessor);
}
return this.y(d.yAccessor);
})
.attr('height', d => {
if (this.interpolating && this.interpolating.y(d.yAccessor) === undefined) {
return 0;
} else if (this.interpolating) {
return this.interpolating.y.bandwidth();
}
return this.y.bandwidth();
})
.attr('x', d => {
if (this.interpolating && this.interpolating.x(d.xAccessor) === undefined) {
let shift = this.x(d.xAccessor);
shift = shift + this.x.bandwidth() * (shift / this.x(this.x.domain()[this.x.domain().length - 1]));
return shift;
} else if (this.interpolating) {
return this.interpolating.x(d.xAccessor);
}
return this.x(d.xAccessor);
})
.attr('width', d => {
if (this.interpolating && this.interpolating.x(d.xAccessor) === undefined) {
return 0;
} else if (this.interpolating) {
return this.interpolating.x.bandwidth();
}
return this.x.bandwidth();
})
.attr('rx', this.shape === 'circle' ? this.x.bandwidth() : 0)
.attr('ry', this.shape === 'circle' ? this.y.bandwidth() : 0);
this.update.order();
this.enterRowWrappers.order();
}
updateGeometries() {
this.update.interrupt();
this.update
.transition('opacity')
.duration((_, i, n) => {
if (select(n[i]).classed('entering')) {
select(n[i]).classed('entering', false);
return this.duration;
}
return 0;
})
.ease(easeCircleIn)
.attr('opacity', d => {
return checkInteraction(
d,
1,
this.hoverOpacity,
this.hoverHighlight,
this.clickHighlight,
this.innerInteractionKeys
);
});
}
exitGeometries() {
this.exit.interrupt();
this.exit
.transition('exit')
.duration(this.duration)
.ease(easeCircleIn)
.attr('opacity', 0)
.attr('y', (d, i, n) => {
if (this.y(d.yAccessor) === undefined) {
const self = select(n[i]);
let shift = +self.attr('y');
shift = shift + +self.attr('height') * (shift / this.y(this.y.domain()[0]));
return shift;
}
return this.y(d.yAccessor);
})
.attr('height', d => {
if (this.y(d.yAccessor) === undefined) {
return 0;
}
return this.y.bandwidth();
})
.attr('x', (d, i, n) => {
if (this.x(d.xAccessor) === undefined) {
const self = select(n[i]);
let shift = +self.attr('x');
shift = shift + +self.attr('width') * (shift / this.x(this.x.domain()[this.x.domain().length - 1]));
return shift;
}
return this.x(d.xAccessor);
})
.attr('width', d => {
if (this.x(d.xAccessor) === undefined) {
return 0;
}
return this.x.bandwidth();
});
this.exitRowWrappers
.selectAll('.grid')
.transition('exit')
.duration(this.duration)
.ease(easeCircleIn)
.attr('opacity', 0)
.attr('y', (_, i, n) => {
const self = select(n[i]);
let shift = +self.attr('y');
shift = shift + +self.attr('height') * (shift / this.y(this.y.domain()[0]));
return shift;
})
.attr('height', 0)
.attr('x', (d, i, n) => {
if (this.x(d.xAccessor) === undefined) {
const self = select(n[i]);
let shift = +self.attr('x');
shift = shift + +self.attr('width') * (shift / this.x(this.x.domain()[this.x.domain().length - 1]));
return shift;
}
return this.x(d.xAccessor);
})
.attr('width', d => {
if (this.x(d.xAccessor) === undefined) {
return 0;
}
return this.x.bandwidth();
});
// this new transtition ensures that the chart counts and all labels
// correctly reflect the newest information
this.update
.transition('accessibilityAfterExit')
.duration(this.duration)
.ease(easeCircleIn)
.call(transitionEndAll, () => {
// before we exit geometries, we need to check if a focus exists or not
const focusDidExist = checkAccessFocus(this.rootG.node());
// then we must remove the exiting elements
this.exit.remove();
this.exitRowWrappers.remove();
// then our util can count geometries
this.setChartCountAccessibility();
// our group's label should update with new counts too
this.setGroupAccessibilityID();
// since items exited, labels must receive updated values
this.setGeometryAriaLabels();
// and also make sure the user's focus isn't lost
retainAccessFocus({
parentGNode: this.rootG.node(),
focusDidExist
});
});
}
drawGeometries() {
this.updateRowWrappers
.transition('update')
.duration(this.duration)
.ease(easeCircleIn)
.call(transitionEndAll, () => {
this.updateRowWrappers.classed('entering', false);
});
const updateTransition = this.update
.classed('geometryIsMoving', (d, i, n) => {
const geometryIsUpdating = checkAttributeTransitions(select(n[i]), [
{
attr: 'y',
numeric: true,
newValue: this.y(d.yAccessor)
},
{
attr: 'height',
numeric: true,
newValue: this.y.bandwidth()
},
{
attr: 'x',
numeric: true,
newValue: this.x(d.xAccessor)
},
{
attr: 'width',
numeric: true,
newValue: this.x.bandwidth()
},
{
attr: 'rx',
numeric: true,
newValue: this.shape === 'circle' ? this.x.bandwidth() : 0
},
{
attr: 'ry',
numeric: true,
newValue: this.shape === 'circle' ? this.y.bandwidth() : 0
}
]);
return geometryIsUpdating;
})
.transition('update')
.duration(this.duration)
.ease(easeCircleIn)
.attr('y', d => this.y(d.yAccessor))
.attr('height', this.y.bandwidth())
.attr('x', d => this.x(d.xAccessor))
.attr('width', this.x.bandwidth())
.attr('rx', this.shape === 'circle' ? this.x.bandwidth() : 0)
.attr('ry', this.shape === 'circle' ? this.y.bandwidth() : 0);
if (this.accessibility.hideTextures || !this.accessibility.showExperimentalTextures) {
updateTransition.attr('fill', d => {
return this.heat(d[this.valueAccessor]);
});
}
updateTransition.call(transitionEndAll, () => {
this.update.classed('geometryIsMoving', false);
this.updateInteractionState();
// we must make sure if geometries move, that our focus indicator does too
retainAccessFocus({
parentGNode: this.rootG.node()
});
});
}
updateInteractionState() {
removeHoverStrokes(this.svg.node());
// we use this.update and this.labelCurrent from setGlobalSelection here
// the lifecycle state does not matter (enter/update/exit)
// since interaction state can happen at any time
this.update
.attr('fill', d => {
return this.heat(d[this.valueAccessor]);
})
.attr('opacity', d => {
return checkInteraction(
d,
1,
this.hoverOpacity,
this.hoverHighlight,
this.clickHighlight,
this.innerInteractionKeys
);
})
.attr('filter', (d, i, n) => {
if (!this.accessibility.hideStrokes && !select(n[i]).classed('geometryIsMoving')) {
const clicked =
this.clickHighlight &&
this.clickHighlight.length > 0 &&
checkClicked(d, this.clickHighlight, this.innerInteractionKeys);
const hovered = this.hoverHighlight && checkHovered(d, this.hoverHighlight, this.innerInteractionKeys);
const baseColor =
!this.accessibility.hideTextures && this.accessibility.showExperimentalTextures
? this.fillColors(d[this.valueAccessor])
: this.rawHeat(d[this.valueAccessor]);
const strokeOverride =
!this.accessibility.hideTextures && this.accessibility.showExperimentalTextures
? this.strokeColors(d[this.valueAccessor])
: undefined;
const state = clicked ? 'click' : hovered && !select(n[i]).classed('geometryIsMoving') ? 'hover' : 'rest';
if (state === 'hover') {
drawHoverStrokes({
inputElement: n[i],
id: this.chartID,
key: d[this.xAccessor] + d[this.yAccessor],
strokeWidth: this.hoverStyle.strokeWidth,
fill: baseColor,
strokeOverride
});
}
return this.strokes[state + baseColor];
}
return null;
});
// in case the fill/stroke contents change, we want to update our focus indicator to match
// (the focus indicator copies the whole element being focused to place it on top)
retainAccessFocus({
parentGNode: this.rootG.node()
});
// since elements may have changed fill, we update labels to match
this.updateLabels.attr('fill', this.textTreatmentHandler);
}
setLabelOpacity() {
this.processLabelOpacity(this.updateLabels);
}
processLabelOpacity(selection, isATransition?) {
const opacity = this.dataLabel.visible ? 1 : 0;
const dimensions = {
width: this.x.bandwidth(),
height: this.y.bandwidth()
};
const parseText = d => {
let text = this.dataLabel.labelAccessor ? d[this.dataLabel.labelAccessor] : d.valueAccessor;
text =
text instanceof Date
? formatDate({
date: text,
format: this.dataLabel.format,
offsetTimezone: true
})
: formatStats(text, this.dataLabel.format);
const hasRoom =
this.accessibility.showSmallLabels ||
verifyTextHasSpace({
text,
dimensions,
fontSize: 14
});
return hasRoom
? checkInteraction(
d,
opacity,
this.hoverOpacity,
this.hoverHighlight,
this.clickHighlight,
this.innerInteractionKeys
) < 1
? 0
: 1
: 0;
};
if (isATransition) {
selection.attr('opacity', parseText);
} else {
selection.each((d, i, n) => {
if (!select(n[i]).classed('entering')) {
select(n[i]).attr('opacity', () => parseText(d));
}
});
}
}
textTreatmentHandler = (d, i, n) => {
const bgColor =
!this.accessibility.hideTextures && this.accessibility.showExperimentalTextures
? this.fillColors(d.valueAccessor)
: this.rawHeat(d.valueAccessor);
const color = autoTextColor(bgColor);
const me = select(n[i]);
me.attr(
'filter',
!me.classed('textIsMoving')
? createTextStrokeFilter({
root: this.svg.node(),
id: this.chartID,
color: bgColor
})
: null
);
return color;
};
setSelectedClass() {
this.update.classed('highlight', (d, i, n) => {
let selected = checkInteraction(d, true, false, '', this.clickHighlight, this.innerInteractionKeys);
selected = this.clickHighlight && this.clickHighlight.length ? selected : false;
const selectable = this.accessibility.elementsAreInterface;
setElementInteractionAccessState(n[i], selected, selectable);
return selected;
});
}
updateCursor() {
this.update.attr('cursor', !this.suppressEvents ? this.cursor : null);
this.updateLabels.attr('cursor', !this.suppressEvents ? this.cursor : null);
}
bindInteractivity() {
this.update
.on(
'click',
!this.suppressEvents
? d => {
this.onClickHandler(d);
}
: null
)
.on(
'mouseover',
!this.suppressEvents
? d => {
this.onHoverHandler(d);
}
: null
)
.on('mouseout', !this.suppressEvents ? () => this.onMouseOutHandler() : null);
this.updateLabels
.on('click', this.dataLabel.visible && !this.suppressEvents ? d => this.onClickHandler(d) : null)
.on('mouseover', this.dataLabel.visible && !this.suppressEvents ? d => this.onHoverHandler(d) : null)
.on('mouseout', this.dataLabel.visible && !this.suppressEvents ? () => this.onMouseOutHandler() : null);
}
enterDataLabels() {
this.enteringLabelGroups.attr('class', 'heat-map-label-wrapper');
this.enterLabels
.attr('class', 'heat-map-dataLabel entering')
.attr('opacity', 0)
.attr('fill', this.textTreatmentHandler)
.attr('cursor', !this.suppressEvents ? this.cursor : null)
.on('click', this.dataLabel.visible && !this.suppressEvents ? d => this.onClickHandler(d) : null)
.on('mouseover', this.dataLabel.visible && !this.suppressEvents ? d => this.onHoverHandler(d) : null)
.on('mouseout', this.dataLabel.visible && !this.suppressEvents ? () => this.onMouseOutHandler() : null);
placeDataLabels({
root: this.enterLabels,
xScale: this.x,
yScale: this.y,
ordinalAccessor: 'xAccessor',
valueAccessor: 'yAccessor',
chartType: 'heat-map'
});
}
updateDataLabels() {
const updateTransition = this.updateLabels
.transition('opacity')
.ease(easeCircleIn)
.duration((_, i, n) => {
if (select(n[i]).classed('entering')) {
return this.duration / 2;
}
return 0;
})
.delay((_, i, n) => {
if (select(n[i]).classed('entering')) {
return this.duration / 2;
}
return 0;
});
this.processLabelOpacity(updateTransition, true);
updateTransition.call(transitionEndAll, () => {
this.updateLabels.classed('entering', false);
});
// this.updatingLabelGroups
// .transition('opacity')
// .duration(this.duration)
// .ease(easeCircleIn)
// .attr('opacity', d => {
// return checkInteraction(
// d,
// this.dataLabel.visible ? 1 : 0,
// this.hoverOpacity,
// this.hoverHighlight,
// this.clickHighlight,
// this.innerInteractionKeys
// ) < 1
// ? 0
// : 1;
// })
// .call(transitionEndAll, () => {
// this.updatingLabelGroups.classed('entering', false);
// });
}
exitDataLabels() {
this.exitLabels
.transition('exit')
.ease(easeCircleIn)
.duration(this.duration / 2)
.attr('opacity', 0)
.remove();
this.exitingLabelGroups
.selectAll('text')
.transition('exit')
.ease(easeCircleIn)
.duration(this.duration / 2)
.attr('opacity', 0)
.call(transitionEndAll, () => {
this.exitingLabelGroups.remove();
});
}
drawDataLabels() {
this.updateLabels.attr('fill', this.textTreatmentHandler).text(d => {
const text = this.dataLabel.labelAccessor ? d[this.dataLabel.labelAccessor] : d.valueAccessor;
return text instanceof Date
? formatDate({
date: text,
format: this.dataLabel.format,
offsetTimezone: true
})
: formatStats(text, this.dataLabel.format);
});
const placeLabels = this.updateLabels
.transition('update')
.ease(easeCircleIn)
.duration(this.duration);
placeDataLabels({
root: placeLabels,
xScale: this.x,
yScale: this.y,
ordinalAccessor: 'xAccessor',
valueAccessor: 'yAccessor',
chartType: 'heat-map'
});
}
drawLegendElements() {
drawLegend({
root: this.legendG,
uniqueID: this.chartID,
width: this.innerPaddedWidth,
height: this.margin.bottom + 60,
colorArr: this.legend && this.legend.type !== 'gradient' ? this.colorArr : this.preparedColors,
baseColorArr: !(this.colorPalette && this.colorPalette.includes('diverging'))
? [this.preparedColors[this.preparedColors.length - 1]]
: this.strokeColors.range(),
hideStrokes: this.accessibility.hideStrokes,
scale: this.heat,
steps: this.colorSteps,
margin: this.margin,
padding: this.padding,
duration: this.duration,
type: this.legend.type,
fontSize: 12,
label: this.legend.labels,
format: this.legend.format,
hide: !this.legend.visible
});
}
drawAnnotations() {
annotate({
source: this.rootG.node(),
data: this.annotations,
xScale: this.x,
xAccessor: this.xAccessor,
yScale: this.y,
yAccessor: this.yAccessor
});
}
setAnnotationAccessibility() {
setAccessAnnotation(this.heatMapEl, this.annotations);
}
// new accessibility functions added here
setTagLevels() {
this.topLevel = findTagLevel(this.highestHeadingLevel);
this.bottomLevel = findTagLevel(this.highestHeadingLevel, 3);
}
setChartDescriptionWrapper() {
// this initializes the accessibility description section of the chart
initializeDescriptionRoot({
rootEle: this.heatMapEl,
title: this.accessibility.title || this.mainTitle,
chartTag: 'heat-map',
uniqueID: this.chartID,
highestHeadingLevel: this.highestHeadingLevel,
redraw: this.shouldRedrawWrapper,
disableKeyNav:
this.suppressEvents &&
this.accessibility.elementsAreInterface === false &&
this.accessibility.keyboardNavConfig &&
this.accessibility.keyboardNavConfig.disabled
});
this.shouldRedrawWrapper = false;
}
setParentSVGAccessibility() {
// this sets the accessibility features of the root SVG element
setAccessibilityController({
node: this.svg.node(),
chartTag: 'heat-map',
title: this.accessibility.title || this.mainTitle,
description: this.subTitle,
uniqueID: this.chartID,
geomType: 'cell',
includeKeyNames: this.accessibility.includeDataKeyNames,
dataKeys: scopeDataKeys(this, chartAccessors, 'heat-map'),
groupAccessor: this.yAccessor,
groupName: 'row',
disableKeyNav:
this.suppressEvents &&
this.accessibility.elementsAreInterface === false &&
this.accessibility.keyboardNavConfig &&
this.accessibility.keyboardNavConfig.disabled
});
}
setGeometryAccessibilityAttributes() {
// this makes sure every geom element has correct event handlers + semantics (role, tabindex, etc)
this.update.each((_d, i, n) => {
initializeElementAccess(n[i]);
});
}
setGeometryAriaLabels() {
// this adds an ARIA label to each geom (a description read by screen readers)
const keys = scopeDataKeys(this, chartAccessors, 'heat-map');
this.update.each((_d, i, n) => {
setElementFocusHandler({
node: n[i],
geomType: 'cell',
includeKeyNames: this.accessibility.includeDataKeyNames,
dataKeys: keys,
groupName: 'row',
uniqueID: this.chartID,
disableKeyNav:
this.suppressEvents &&
this.accessibility.elementsAreInterface === false &&
this.accessibility.keyboardNavConfig &&
this.accessibility.keyboardNavConfig.disabled
});
setElementAccessID({
node: n[i],
uniqueID: this.chartID
});
});
}
setGroupAccessibilityID() {
// this sets an ARIA label on all the g elements in the chart
this.updateRowWrappers.each((_, i, n) => {
setElementAccessID({
node: n[i],
uniqueID: this.chartID
});
});
}
setChartAccessibilityTitle() {
setAccessTitle(this.heatMapEl, this.accessibility.title || this.mainTitle);
}
setChartAccessibilitySubtitle() {
setAccessSubtitle(this.heatMapEl, this.subTitle);
}
setChartAccessibilityLongDescription() {
setAccessLongDescription(this.heatMapEl, this.accessibility.longDescription);
}
setChartAccessibilityExecutiveSummary() {
setAccessExecutiveSummary(this.heatMapEl, this.accessibility.executiveSummary);
}
setChartAccessibilityPurpose() {
setAccessPurpose(this.heatMapEl, this.accessibility.purpose);
}
setChartAccessibilityContext() {
setAccessContext(this.heatMapEl, this.accessibility.contextExplanation);
}
setChartAccessibilityStatisticalNotes() {
setAccessStatistics(this.heatMapEl, this.accessibility.statisticalNotes);
}
setChartCountAccessibility() {
// this is our automated section that describes the chart contents
// (like geometry and group counts, etc)
setAccessChartCounts({
rootEle: this.heatMapEl,
parentGNode: this.map.node(), // pass the wrapper to <g> or geometries here, should be single node selection
chartTag: 'heat-map',
geomType: 'cell',
groupName: 'row'
});
}
setChartAccessibilityStructureNotes() {
setAccessStructure(this.heatMapEl, this.accessibility.structureNotes);
}
// new accessibility stuff ends here
onChangeHandler() {
if (this.accessibility && typeof this.accessibility.onChangeFunc === 'function') {
const d = {
updated: this.updated,
added: this.enterSize,
removed: this.exitSize
};
this.accessibility.onChangeFunc(d);
}
this.updated = false;
this.enterSize = 0;
this.exitSize = 0;
}
onClickHandler(d) {
this.clickFunc.emit(d);
}
onHoverHandler(d) {
overrideTitleTooltip(this.chartID, true);
this.hoverFunc.emit(d);
if (this.showTooltip) {
this.eventsTooltip({ data: d, evt: event, isToShow: true });
}
}
onMouseOutHandler() {
overrideTitleTooltip(this.chartID, false);
this.mouseOutFunc.emit();
if (this.showTooltip) {
this.eventsTooltip({ isToShow: false });
}
}
// set initial style (instead of copying css class across the lib)
setTooltipInitialStyle() {
initTooltipStyle(this.tooltipG);
}
// tooltip
eventsTooltip({ data, evt, isToShow }: { data?: any; evt?: any; isToShow: boolean }) {
drawTooltip({
root: this.tooltipG,
data,
event: evt,
isToShow,
tooltipLabel: this.tooltipLabel,
xAxis: this.xAxis,
yAxis: this.yAxis,
dataLabel: this.dataLabel,
valueAccessor: this.valueAccessor,
xAccessor: this.xAccessor,
yAccessor: this.yAccessor,
chartType: 'heat-map'
});
}
render() {
// everything between this comment and the third should eventually
// be moved into componentWillUpdate (if the stenicl bug is fixed)
this.init();
if (this.shouldSetTagLevels) {
this.setTagLevels();
this.shouldSetTagLevels = false;
}
if (this.shouldUpdateData) {
this.prepareData();
this.shouldUpdateData = false;
}
if (this.shouldSetDimensions) {
this.setDimensions();
this.shouldSetDimensions = false;
}
if (this.shouldSetColors) {
this.setColors();
this.shouldSetColors = false;
}
if (this.shouldUpdateScales) {
this.prepareScales();
this.shouldUpdateScales = false;
}
if (this.shouldFormatClickHighlight) {
this.formatClickHighlight();
this.shouldFormatClickHighlight = false;
}
if (this.shouldFormatHoverHighlight) {
this.formatHoverHighlight();
this.shouldFormatHoverHighlight = false;
}
if (this.shouldValidateInteractionKeys) {
this.validateInteractionKeys();
this.shouldValidateInteractionKeys = false;
}
if (this.shouldUpdateTableData) {
this.setTableData();
this.shouldUpdateTableData = false;
}
if (this.shouldValidate) {
this.shouldValidateAccessibilityProps();
this.shouldValidate = false;
}
// Everything between this comment and the first should eventually
// be moved into componentWillUpdate (if the stenicl bug is fixed)
return (
<div class={`o-layout`}>
<div class="o-layout--chart">
<this.topLevel data-testid="main-title">{this.mainTitle}</this.topLevel>
<this.bottomLevel class="visa-ui-text--instructions" data-testid="sub-title">
{this.subTitle}
</this.bottomLevel>
<div class="heat-map-legend vcl-legend" style={{ display: this.legend.visible ? 'block' : 'none' }} />
<keyboard-instructions
uniqueID={this.chartID}
geomType={'cell'}
groupName={'row'} // taken from initializeDescriptionRoot, on bar this should be "bar group", stacked bar is "stack", and clustered is "cluster"
chartTag={'heat-map'}
width={this.width - (this.margin ? this.margin.right || 0 : 0)}
isInteractive={this.accessibility.elementsAreInterface}
hasCousinNavigation
disabled={
this.suppressEvents &&
this.accessibility.elementsAreInterface === false &&
this.accessibility.keyboardNavConfig &&
this.accessibility.keyboardNavConfig.disabled
} // the chart is "simple"
/>
<div class="visa-viz-d3-heat-map-container" />
<div class="heat-map-tooltip vcl-tooltip" style={{ display: this.showTooltip ? 'block' : 'none' }} />
<data-table
uniqueID={this.chartID}
isCompact
tableColumns={this.tableColumns}
data={this.tableData}
padding={this.padding}
margin={this.margin}
hideDataTable={this.accessibility.hideDataTableButton}
/>
</div>
</div>
);
}
private init() {
// reading properties
const keys = Object.keys(HeatMapDefaultValues);
let i = 0;
// accept 0 or false as default value
const exceptions = {
strokeWidth: {
exception: 0
},
showTooltip: {
exception: false
},
mainTitle: {
exception: ''
},
subTitle: {
exception: ''
},
wrapLabel: {
exception: false
},
hoverOpacity: {
exception: 0
}
};
for (i = 0; i < keys.length; i++) {
const exception = !exceptions[keys[i]] ? false : this[keys[i]] === exceptions[keys[i]].exception;
this[keys[i]] = this[keys[i]] || exception ? this[keys[i]] : HeatMapDefaultValues[keys[i]];
}
}
}
// incorporate OSS licenses into build
window['VisaChartsLibOSSLicenses'] = getLicenses(); // tslint:disable-line no-string-literal | the_stack |
import { Utils } from '@rpgjs/common'
import { RpgPlayer } from './Player'
import {
MAXHP,
MAXSP,
} from '../presets'
const {
isString
} = Utils
export class ParameterManager {
private _paramsModifier: {
[key: string]: {
value?: number,
rate?: number
}
} = {}
private _parameters: Map<string, {
start: number,
end: number
}>
private _hp = 0
private _sp = 0
private _exp: number = 0
private _level: number = 0
/**
* ```ts
* player.initialLevel = 5
* ```
*
* @title Set initial level
* @prop {number} player.initialLevel
* @default 1
* @memberof ParameterManager
* */
public initialLevel:number = 1
/**
* ```ts
* player.finalLevel = 50
* ```
*
* @title Set final level
* @prop {number} player.finalLevel
* @default 99
* @memberof ParameterManager
* */
public finalLevel:number = 99
/**
* With Object-based syntax, you can use following options:
* - `basis: number`
* - `extra: number`
* - `accelerationA: number`
* - `accelerationB: number`
* @title Change Experience Curve
* @prop {object} player.expCurve
* @default
* ```ts
* {
* basis: 30,
* extra: 20,
* accelerationA: 30,
* accelerationB: 30
* }
* ```
* @memberof ParameterManager
* */
public expCurve: {
basis: number,
extra: number,
accelerationA: number
accelerationB: number
}
/**
* Changes the health points
* - Cannot exceed the MaxHP parameter
* - Cannot have a negative value
* - If the value is 0, a hook named `onDead()` is called in the RpgPlayer class.
*
* ```ts
* player.hp = 100
* ```
* @title Change HP
* @prop {number} player.hp
* @default MaxHPValue
* @memberof ParameterManager
* */
set hp(val: number) {
if (val > this.param[MAXHP]) {
val = this.param[MAXHP]
}
else if (val <= 0) {
this['_triggerHook']('onDead')
val = 0
}
this._hp = val
}
get hp(): number {
return this._hp
}
/**
* Changes the skill points
* - Cannot exceed the MaxSP parameter
* - Cannot have a negative value
*
* ```ts
* player.sp = 200
* ```
* @title Change SP
* @prop {number} player.sp
* @default MaxSPValue
* @memberof ParameterManager
* */
set sp(val: number) {
if (val > this.param[MAXSP]) {
val = this.param[MAXSP]
}
this._sp = val
}
get sp(): number {
return this._sp
}
/**
* Changing the player's experience.
* ```ts
* player.exp += 100
* ```
*
* Levels are based on the experience curve.
*
* ```ts
* console.log(player.level) // 1
* console.log(player.expForNextlevel) // 150
* player.exp += 160
* console.log(player.level) // 2
* ```
*
* @title Change Experience
* @prop {number} player.exp
* @default 0
* @memberof ParameterManager
* */
set exp(val: number) {
this._exp = val
const lastLevel = this.level
while (this.expForNextlevel < this._exp) {
this.level += 1
}
//const hasNewLevel = player.level - lastLevel
}
get exp(): number {
return this._exp
}
/**
* Changing the player's level.
*
* ```ts
* player.level += 1
* ```
*
* The level will be between the initial level given by the `initialLevel` and final level given by `finalLevel`
*
* ```ts
* player.finalLevel = 50
* player.level = 60
* console.log(player.level) // 50
* ```
*
* @title Change Level
* @prop {number} player.level
* @default 1
* @memberof ParameterManager
* */
set level(val: number) {
const lastLevel = this._level
if (this.finalLevel && this._level > this.finalLevel) {
val = this.finalLevel
}
if (this._class) {
for (let i = this._level ; i <= val; i++) {
for (let skill of this._class.skillsToLearn) {
if (skill.level == i) {
this['learnSkill'](skill.skill)
}
}
}
}
const hasNewLevel = val - lastLevel
if (hasNewLevel > 0) this['_triggerHook']('onLevelUp', hasNewLevel)
this._level = val
}
get level(): number {
return this._level
}
/**
* ```ts
* console.log(player.expForNextlevel) // 150
* ```
* @title Experience for next level ?
* @prop {number} player.expForNextlevel
* @readonly
* @memberof ParameterManager
* */
get expForNextlevel(): number {
return this._expForLevel(this.level + 1)
}
/**
* Read the value of a parameter. Put the name of the parameter.
*
* ```ts
* import { Presets } from '@rpgjs/server'
*
* const { MAXHP } = Presets
*
* console.log(player.param[MAXHP])
* ```
*
* > Possible to use the `player.getParamValue(name)` method instead
* @title Get Param Value
* @prop {object} player.param
* @readonly
* @memberof ParameterManager
* */
get param() {
const obj = {}
this._parameters.forEach((val, name) => {
obj[name] = this.getParamValue(name)
})
return obj
}
get paramsModifier() {
const params = {}
const paramsAvg = {}
const changeParam = (paramsModifier) => {
for (let key in paramsModifier) {
const { rate, value } = paramsModifier[key]
if (!params[key]) params[key] = { rate: 0, value: 0 }
if (!paramsAvg[key]) paramsAvg[key] = 0
if (value) params[key].value += value
if (rate !== undefined) params[key].rate += rate
paramsAvg[key]++
}
}
const getModifier = (prop) => {
if (!isString(prop)) {
changeParam(prop)
return
}
for (let el of this[prop]) {
if (!el.paramsModifier) continue
changeParam(el.paramsModifier)
}
}
getModifier(this._paramsModifier)
getModifier('states')
getModifier('equipments')
for (let key in params) {
params[key].rate /= paramsAvg[key]
}
return params
}
/**
* Changes the values of some parameters
*
* > It is important that these parameters have been created beforehand with the `addParameter()` method.
* > By default, the following settings have been created:
* - maxhp
* - maxsp
* - str
* - int
* - dex
* - agi
*
* **Object Key**
*
* The key of the object is the name of the parameter
*
* > The good practice is to retrieve the name coming from a constant
*
* **Object Value**
*
* The value of the key is an object containing:
* ```
* {
* value: number,
* rate: number
* }
* ```
*
* - value: Adds a number to the parameter
* - rate: Adds a rate to the parameter
*
* > Note that you can put both (value and rate)
*
* In the case of a state or the equipment of a weapon or armor, the parameters will be changed but if the state disappears or the armor/weapon is de-equipped, then the parameters will return to the initial state.
*
* @prop {Object} [paramsModifier]
* @example
*
* ```ts
* import { Presets } from '@rpgjs/server'
*
* const { MAXHP } = Presets
*
* player.paramsModifier = {
* [MAXHP]: {
* value: 100
* }
* }
* ```
*
* 1. Player has 741 MaxHp
* 2. After changing the parameter, he will have 841 MaxHp
*
* @title Set Parameters Modifier
* @prop {number} paramsModifier
* @memberof ParameterManager
* */
set paramsModifier(val: {
[key: string]: {
value?: number,
rate?: number
}
}) {
this._paramsModifier = val
}
get parameters() {
return this._parameters
}
set parameters(val) {
this._parameters = val
}
private _expForLevel(level: number): number {
const {
basis,
extra,
accelerationA,
accelerationB
} = this.expCurve
return Math.round(basis * (Math.pow(level - 1, 0.9 + accelerationA / 250)) * level * (level + 1) / (6 + Math.pow(level, 2) / 50 / accelerationB) + (level - 1) * extra)
}
private getParam(name: string) {
const features = this._parameters.get(name)
if (!features) {
throw `Parameter ${name} not exists. Please use addParameter() before`
}
return features
}
getParamValue(name: string): number {
const features = this.getParam(name)
let curveVal = Math.floor((features.end - features.start) * ((this.level-1) / (this.finalLevel - this.initialLevel))) + features.start
const modifier = this.paramsModifier[name]
if (modifier) {
if (modifier.rate) curveVal *= modifier.rate
if (modifier.value) curveVal += modifier.value
}
return curveVal
}
/**
* Give a new parameter. Give a start value and an end value.
* The start value will be set to the level set at `player.initialLevel` and the end value will be linked to the level set at `player.finalLevel`.
*
* ```ts
* const SPEED = 'speed'
*
* player.addParameter(SPEED, {
* start: 10,
* end: 100
* })
*
* player.param[SPEED] // 10
* player.level += 5
* player.param[SPEED] // 14
* ```
*
* @title Add custom parameters
* @method player.addParameter(name,curve)
* @param {name} name
* @param {object} curve Scheme of the object: { start: number, end: number }
* @returns {void}
* @memberof ParameterManager
* */
addParameter(name: string, { start, end }: { start: number, end: number }): void {
this._parameters.set(name, {
start,
end
})
}
/**
* Gives back in percentage of health points to skill points
*
* ```ts
* import { Presets } from '@rpgjs/server'
*
* const { MAXHP } = Presets
*
* console.log(player.param[MAXHP]) // 800
* player.hp = 100
* player.recovery({ hp: 0.5 }) // = 800 * 0.5
* console.log(player.hp) // 400
* ```
*
* @title Recovery HP and/or SP
* @method player.recovery(params)
* @param {object} params Scheme of the object: { hp: number, sp: number }. The values of the numbers must be in 0 and 1
* @returns {void}
* @memberof ParameterManager
* */
recovery({ hp, sp }: { hp?: number, sp?: number }) {
if (hp) this.hp = this.param[MAXHP] * hp
if (sp) this.sp = this.param[MAXSP] * sp
}
/**
* restores all HP and SP
*
* ```ts
* import { Presets } from '@rpgjs/server'
*
* const { MAXHP, MAXSP } = Presets
*
* console.log(player.param[MAXHP], player.param[MAXSP]) // 800, 230
* player.hp = 100
* player.sp = 0
* player.allRecovery()
* console.log(player.hp, player.sp) // 800, 230
* ```
*
* @title All Recovery
* @method player.allRecovery()
* @returns {void}
* @memberof ParameterManager
* */
allRecovery(): void {
this.recovery({ hp: 1, sp: 1 })
}
}
export interface ParameterManager {
_class,
$schema
} | the_stack |
import { Component, OnInit, Input } from '@angular/core';
import { CloudGemMetricApi } from './api-handler.class';
import { AwsService } from 'app/aws/aws.service';
import { Http } from '@angular/http';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Observable';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
@Component({
selector: 'metric-partitions',
template: `
<h2> Required </h2>
<ng-container [ngSwitch]="isLoadingPredefinedPartitions">
<p> Partitions are used by Athena as indexes for your data. They are effectively <a target="s3" href="https://s3.console.aws.amazon.com/s3/home?region=us-east-1#">S3 key</a> paths. Querying based on partitions will increase performance and decrease costs. When Athena uses partitions it only has to scan a subset of the entire dataset. The Cloud Gem Metric gives you some default partitions out of the box. </p>
<div *ngSwitchCase="true">
<loading-spinner> </loading-spinner>
</div>
<div *ngSwitchCase="false">
<div class="row">
<div class="col-lg-3">
<label> ATTRIBUTE NAME </label>
</div>
<div class="col-lg-3">
<label> TYPE </label>
</div>
<div class="col-lg-3">
<label> PARTS </label>
</div>
</div>
<div class="row partition" *ngFor="let partition of predefinedPartitions">
<div class="col-lg-3">
<label >{{partition.key}}</label>
<tooltip placement="right" [tooltip]="partition.description"> </tooltip>
</div>
<div class="col-lg-3">
{{partition.type}}
</div>
<div class="col-lg-3">
{{partition.parts}}
</div>
</div>
</div>
</ng-container>
<h2> Custom </h2>
<ng-container [ngSwitch]="isLoadingCustomPartitions">
<div *ngSwitchCase="true">
<loading-spinner> </loading-spinner>
</div>
<div *ngSwitchCase="false">
<p>ADVANCED USER AREA</p>
<p>Create your own custom partitions. Remember that the more partitions you have the smaller the partition files will be. Too many partitions can decrease performance.<br />Changing the order after data has been written can cause random tables to appear in Athena.</p>
<div class="row">
<div class="col-lg-3">
<label> ATTRIBUTE NAME <tooltip placement="right" tooltip="The short event attribute name being sent from your game."> </tooltip></label>
</div>
<div class="col-lg-3">
<label> TYPE <tooltip placement="right" tooltip="The attribute value type. Currently there is only support int, str, float, datetime.datetime.utcfromtimestamp, and dictionary"> </tooltip> </label>
</div>
<div class="col-lg-3">
<label> PARTS <tooltip placement="right" tooltip="A type of function to call on the casted type. Example. My type is datetime.datetime.utcfromtimestamp so I can call .year, .month, .day, or .hour."> </tooltip></label>
</div>
</div>
<div class="row partition" *ngFor="let customPartition of customPartitions">
<div class="col-lg-3">
<input type="text" class="form-control" [(ngModel)]="customPartition.key" [ngbTypeahead]="searchKeys" />
</div>
<div class="col-lg-3">
<input type="text" class="form-control" [(ngModel)]="customPartition.type" [ngbTypeahead]="searchTypes" />
</div>
<div class="col-lg-3">
<input type="text" class="form-control" [(ngModel)]="customPartition.parts" [ngbTypeahead]="searchParts" />
</div>
<i (click)="removeCustomPartition(customPartition)" class="fa fa-trash-o"></i>
</div>
<div class="row partition">
<div class="col-lg-3">
<input type="text" class="custom-partition form-control" [(ngModel)]="newCustomPartition.key" [ngbTypeahead]="searchKeys" />
</div>
<div class="col-lg-3">
<dropdown class="custom-partition" (dropdownChanged)="changeDropdown($event)" [options]="chartTypeOptions" placeholderText="String"> </dropdown>
</div>
<div class="col-lg-3">
<input type="text" class="custom-partition form-control" [(ngModel)]="newCustomPartition.parts" [ngbTypeahead]="searchParts" />
</div>
</div>
<div class="add-partition">
<button (click)="addCustomPartition(newCustomPartition)" class="btn btn-outline-primary"> + Add Option </button>
</div>
<div class="update-partitions">
<button (click)="updateCustomPartitions(customPartitions)" class="form-control l-primary btn"> Update Custom Partitions </button>
</div>
</div>
</ng-container>
`,
styles: [`
th {
width: 20%;
}
.row.partition {
margin-bottom: 15px;
}
.partition i {
line-height: 35px;
}
.add-partition {
margin-bottom: 30px;
}
.update-partitions {
margin-bottom: 15px;
}
`]
})
export class MetricPartitionsComponent implements OnInit {
@Input() context: any;
private _apiHandler: CloudGemMetricApi;
private predefinedPartitions: Array<Partition>;
private customPartitions: Array<Partition>;
private newCustomPartition: Partition;
private isLoadingPredefinedPartitions: boolean = true;
private isLoadingCustomPartitions: boolean = true;
private chartTypeOptions = [
{ text: "Dictionary", type: "map" },
{ text: "Float", type: "float" },
{ text: "Integer", type: "int" },
{ text: "String", type: "str" },
{ text: "UTCDatetime", type: "datetime.datetime.utcfromtimestamp" },
]
constructor(private http: Http, private aws: AwsService, private toastr: ToastsManager) { }
// TODO: This is an example list - needs updated and perhaps better filtering prior to release
keys = [];
types = ['string', 'int', 'datetime', 'float'];
parts = ['split("/")[0]']
ngOnInit() {
this._apiHandler = new CloudGemMetricApi(this.context.ServiceUrl, this.http, this.aws);
this.initPartitionsFacet();
}
initPartitionsFacet = () => {
this.predefinedPartitions = new Array<Partition>();
this.newCustomPartition = Partition.default();
this._apiHandler.getPredefinedPartitions().subscribe( (res) => {
let partitions = JSON.parse(res.body.text()).result;
this.isLoadingPredefinedPartitions = false;
if (partitions) {
for (let partition of partitions) {
this.predefinedPartitions.push(new Partition(partition.parts, partition.type, partition.key, partition.description));
}
}
});
this.initCustomPartitions();
}
changeDropdown = (current) => {
this.newCustomPartition.type = current.type;
}
initCustomPartitions = () => {
this.customPartitions = new Array<Partition>();
this._apiHandler.getCustomPartitions().subscribe( (res) => {
let partitions = JSON.parse(res.body.text()).result;
this.isLoadingCustomPartitions = false;
if (partitions) {
for (let partition of partitions) {
this.customPartitions.push(new Partition(partition.parts, partition.type, partition.key, partition.description));
}
}
});
}
searchKeys = (text$: Observable<string>) =>
text$.debounceTime(200)
.distinctUntilChanged()
.map(term =>
this.keys.filter(v => v.toLocaleLowerCase().indexOf(term.toLocaleLowerCase()) > -1).slice(0, 10));
searchTypes = (text$: Observable<string>) =>
text$.debounceTime(200)
.distinctUntilChanged()
.map(term =>
this.types.filter(v => v.toLocaleLowerCase().indexOf(term.toLocaleLowerCase()) > -1).slice(0, 10));
searchParts = (text$: Observable<string>) =>
text$.debounceTime(200)
.distinctUntilChanged()
.map(term =>
this.parts.filter(v => v.toLocaleLowerCase().indexOf(term.toLocaleLowerCase()) > -1).slice(0, 10));
/** Add a partition to the list of custom partitions. This is only locally shown until the button is clicked to send the update to the server */
addCustomPartition = () => {
this.customPartitions.push(this.newCustomPartition)
this.newCustomPartition = Partition.default();
}
/** Remove a partition from the list of custom partitions */
removeCustomPartition = partition => this.customPartitions.splice(this.customPartitions.indexOf(partition), 1);
/** Update the current partition list on the server and then reload the response from the server */
updateCustomPartitions = (partitions: Array<Partition>) => {
this.isLoadingCustomPartitions = true;
var partitionsObj = {
"partitions": partitions
}
if (this.newCustomPartition.key && this.newCustomPartition.key !== "") {
partitionsObj['partitions'].push(this.newCustomPartition);
this.newCustomPartition = Partition.default();
}
for (let partition in partitions) {
console.log(partitions[partition].parts)
if (!partitions[partition].parts || partitions[partition].parts.length == 0)
delete partitions[partition].parts
delete partitions[partition].description
}
this._apiHandler.updatePartitions(partitionsObj).subscribe( (res) => {
this.toastr.success("Updated custom partitions");
this.initCustomPartitions();
}, (err) => {
this.toastr.error("Unable to update custom partitions", err);
this.initCustomPartitions();
});
}
}
/** Partition model */
export class Partition {
parts: string[];
type: string;
key: string;
description: string;
constructor( parts: string[], type: string, key: string, description: string) {
this.parts = parts;
this.type = type;
this.key = key;
this.description = description;
}
/** Default partition impl */
static default = () => new Partition([], "string", "", "");
} | the_stack |
module BABYLON {
/**
* This class describe a rectangle that were added to the map.
* You have access to its coordinates either in pixel or normalized (UV)
*/
export class PackedRect {
constructor(root: RectPackingMap, parent: PackedRect, pos: Vector2, size: Size) {
this._pos = pos;
this._size = size;
this._root = root;
this._parent = parent;
this._contentSize = null;
this._bottomNode = null;
this._leftNode = null;
this._initialSize = null;
this._rightNode = null;
}
/**
* @returns the position of this node into the map
*/
public get pos(): Vector2 {
return this._pos;
}
/**
* @returns the size of the rectangle this node handles
*/
public get contentSize(): Size {
return this._contentSize;
}
/**
* Retrieve the inner position (considering the margin) and stores it into the res object
* @param res must be a valid Vector2 that will contain the inner position after this call
*/
public getInnerPosToRef(res: Vector2) {
let m = this._root._margin;
res.x = this._pos.x + m;
res.y = this._pos.y + m;
}
/**
* Retrieve the inner size (considering the margin) and stores it into the res object
* @param res must be a valid Size that will contain the inner size after this call
*/
public getInnerSizeToRef(res: Size) {
let m = this._root._margin;
res.width = this._contentSize.width - (m*2);
res.height = this._contentSize.height - (m*2);
}
/**
* Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
* @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
*/
public get UVs(): Vector2[] {
if (!this._contentSize) {
throw new Error("Can't compute UVs for this object because it's nor allocated");
}
return this.getUVsForCustomSize(this._contentSize);
}
/**
* You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
* and then using only a part of the PackRect.
* This method will return the UVs for this part by given the custom size of what you really use
* @param customSize must be less/equal to the allocated size, UV will be compute from this
*/
public getUVsForCustomSize(customSize: Size): Vector2[] {
var mainWidth = this._root._size.width;
var mainHeight = this._root._size.height;
let margin = this._root._margin;
var topLeft = new Vector2((this._pos.x+margin) / mainWidth, (this._pos.y+margin) / mainHeight);
var rightBottom = new Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
var uvs = new Array<Vector2>();
uvs.push(topLeft);
uvs.push(new Vector2(rightBottom.x, topLeft.y));
uvs.push(rightBottom);
uvs.push(new Vector2(topLeft.x, rightBottom.y));
return uvs;
}
/**
* Free this rectangle from the map.
* Call this method when you no longer need the rectangle to be in the map.
*/
public freeContent() {
if (!this.contentSize) {
return;
}
this._contentSize = null;
// If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
this.attemptDefrag();
}
protected get isUsed(): boolean {
return this._contentSize != null || this._leftNode != null;
}
protected findAndSplitNode(contentSize: Size): PackedRect {
var node = this.findNode(contentSize);
// Not enough space...
if (!node) {
return null;
}
node.splitNode(contentSize);
return node;
}
private findNode(size: Size): PackedRect {
var resNode: PackedRect = null;
let margin = this._root._margin * 2;
// If this node is used, recurse to each of his subNodes to find an available one in its branch
if (this.isUsed) {
if (this._leftNode) {
resNode = this._leftNode.findNode(size);
}
if (!resNode && this._rightNode) {
resNode = this._rightNode.findNode(size);
}
if (!resNode && this._bottomNode) {
resNode = this._bottomNode.findNode(size);
}
}
// The node is free, but was previously allocated (_initialSize is set), rely on initialSize to make the test as it's the space we have
else if (this._initialSize) {
if (((size.width+margin) <= this._initialSize.width) && ((size.height+margin) <= this._initialSize.height))
{
resNode = this;
} else {
return null;
}
}
// The node is free and empty, rely on its size for the test
else if (((size.width+margin) <= this._size.width) && ((size.height+margin) <= this._size.height)) {
resNode = this;
}
return resNode;
}
private static TpsSize = Size.Zero();
private splitNode(contentSize: Size): PackedRect {
let cs = PackedRect.TpsSize;
let margin = this._root._margin*2;
cs.copyFrom(contentSize);
cs.width += margin;
cs.height += margin;
// If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
if (!this._contentSize && this._initialSize) {
this._contentSize = cs.clone();
this._leftNode = new PackedRect(this._root, this, new Vector2(this._pos.x, this._pos.y), new Size(this._initialSize.width, this._initialSize.height));
return this._leftNode.splitNode(contentSize);
} else {
this._contentSize = cs.clone();
this._initialSize = cs.clone();
if (cs.width !== this._size.width) {
this._rightNode = new PackedRect(this._root, this, new Vector2(this._pos.x + cs.width, this._pos.y), new Size(this._size.width - cs.width, cs.height));
}
if (cs.height !== this._size.height) {
this._bottomNode = new PackedRect(this._root, this, new Vector2(this._pos.x, this._pos.y + cs.height), new Size(this._size.width, this._size.height - cs.height));
}
return this;
}
}
private attemptDefrag() {
if (!this.isUsed && this.isRecursiveFree) {
this.clearNode();
if (this._parent) {
this._parent.attemptDefrag();
}
}
}
private clearNode() {
this._initialSize = null;
this._rightNode = null;
this._bottomNode = null;
}
private get isRecursiveFree(): boolean {
return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
}
protected evalFreeSize(size: number): number {
var levelSize = 0;
if (!this.isUsed) {
let margin = this._root._margin;
let is = this._initialSize;
if (is) {
levelSize = is.surface - (is.width*margin) - (is.height*margin);
} else {
let size = this._size;
levelSize = size.surface - (size.width*margin) - (size.height*margin);
}
}
if (this._rightNode) {
levelSize += this._rightNode.evalFreeSize(0);
}
if (this._bottomNode) {
levelSize += this._bottomNode.evalFreeSize(0);
}
return levelSize + size;
}
protected _root: RectPackingMap;
protected _parent: PackedRect;
private _contentSize: Size;
private _initialSize: Size;
private _leftNode: PackedRect;
private _rightNode: PackedRect;
private _bottomNode: PackedRect;
private _pos: Vector2;
protected _size: Size;
}
/**
* The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
* This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
* Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
* In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
* In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
*/
export class RectPackingMap extends PackedRect {
/**
* Create an instance of the object with a dimension using the given size
* @param size The dimension of the rectangle that will contain all the sub ones.
* @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
*/
constructor(size: Size, margin=0) {
super(null, null, Vector2.Zero(), size);
this._margin = margin;
this._root = this;
}
/**
* Add a rectangle, finding the best location to store it into the map
* @param size the dimension of the rectangle to store
* @return the Node containing the rectangle information, or null if we couldn't find a free spot
*/
public addRect(size: Size): PackedRect {
var node = this.findAndSplitNode(size);
return node;
}
/**
* Return the current space free normalized between [0;1]
* @returns {}
*/
public get freeSpace(): number {
var freeSize = 0;
freeSize = this.evalFreeSize(freeSize);
return freeSize / (this._size.width * this._size.height);
}
public _margin: number;
}
} | the_stack |
import {
AfterContentInit,
AfterViewInit,
Component,
ChangeDetectionStrategy,
ChangeDetectorRef,
EventEmitter,
ViewChild,
ViewChildren,
Input,
Output,
Optional,
QueryList,
ElementRef,
OnDestroy,
NgZone
} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/takeUntil';
import 'rxjs/add/operator/first';
import {
ChessBoard,
ChessEngine,
ChessBoardController,
BaseBlock,
Block,
Piece,
GAME_STATE,
PieceColor,
PieceType,
BoardDialogService,
BoardDialogMessage
} from 'ngx-chess';
import { SVGChessBlock } from '../svg-chess-block/svg-chess-block.component';
import { SVGChessPiece } from '../svg-chess-piece/svg-chess-piece.component';
//const log = 'development' === ENV ? (msg) => console.log(msg) : (msg) => {};
const log = (msg) => {};
export interface BlockDropEvent {
block: SVGChessBlock,
event: MouseEvent
}
export interface PieceDragEvent {
piece: SVGChessPiece,
event: MouseEvent
}
export interface BoardSizeChangeEvent {
height: number;
width: number;
clientHeight: number;
clientWidth: number;
xOffset: number;
yOffset: number;
}
@Component({
selector: 'chess-board',
styleUrls: [ 'svg-chess-board.styles.scss' ],
templateUrl: 'svg-chess-board.template.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SVGChessBoard extends ChessBoard implements AfterViewInit, AfterContentInit, OnDestroy {
blockSize: number;
dragPiece: SVGChessPiece;
/** @internal */
height: number;
/** @internal */
width: number;
/** @internal */
viewBox: string;
/** @internal */
isBusy: boolean;
/** @internal */
banner: BoardDialogMessage;
/** @internal */
highlighted: Block[];
/** @internal */
lastSizeEvent: BoardSizeChangeEvent;
@Input() minLandscapeMargin: number;
get isPortrait(): boolean {
return this._isPortrait;
}
private isDisabled: boolean;
private rxWaste: Subscription[] = [];
private onWindowResize: any;
private onDocumentTouchMove: (event: TouchEvent) => any;
private _isPortrait: boolean;
@ViewChild('board') private boardElRef: ElementRef;
@ViewChildren(SVGChessBlock) private blocks: QueryList<SVGChessBlock>;
@ViewChildren(SVGChessPiece) private pieces: QueryList<SVGChessPiece>;
@Output() onBoardResize = new EventEmitter<BoardSizeChangeEvent>();
constructor(public engine: ChessEngine,
private cdr: ChangeDetectorRef,
private zone: NgZone,
@Optional() private boardDialogService?: BoardDialogService) {
super(ChessBoardController, engine);
Object.defineProperty(this, 'height', {value: 600});
Object.defineProperty(this, 'width', {value: 600});
Object.defineProperty(this, 'viewBox', {value: `0 0 ${this.width} ${this.height}`});
this.blockSize = this.height / engine.rowCount;
if (document) {
// prevent scrolling when interacting with board.
this.onDocumentTouchMove = (event: TouchEvent): any => {
if ( (event.target as any).ownerSVGElement === this.boardElRef.nativeElement) {
event.preventDefault();
}
return;
};
document.addEventListener('touchmove', this.onDocumentTouchMove, <any>{ passive: false } );
}
if (window) {
this.onWindowResize = (event$: any) => {
const oldIsPortrait = this._isPortrait;
this.updateLastSizeEvent();
this._isPortrait = window.innerHeight > window.innerWidth;
// this._isPortrait = this.lastSizeEvent.yOffset > 0;
// if (!this._isPortrait && this.minLandscapeMargin && this.minLandscapeMargin > 0 && this.minLandscapeMargin > this.lastSizeEvent.xOffset) {
// this._isPortrait = false;
// }
this.onBoardResize.emit(this.lastSizeEvent);
// on mobile, moving to landscape from portrait require another calc/redraw
// 2nd time with proper board size
if (oldIsPortrait === true && this._isPortrait === false) {
setTimeout(() => this.onWindowResize(), 16);
}
};
window.addEventListener("resize", this.onWindowResize);
}
}
ngAfterViewInit(): void {
this.updateLastSizeEvent();
// engine.destroy should clean these up.
this.engine.boardSynced.subscribe( () => this.syncPiecesToBlocks() );
this.engine.stateChanged.subscribe(newState => this.onStateChanged(newState) );
this.registerDragAndDrop();
}
ngAfterContentInit(): void {
const u = this.zone.onStable.subscribe( () => {
this.onWindowResize(null);
u.unsubscribe();
});
}
onStateChanged(newState: GAME_STATE): void {
let banner: BoardDialogMessage;
if (this.ctrl.isGameOver(newState)) {
const winner = this.ctrl.winner === PieceColor.BLACK ? 'Black' : 'White';
banner = newState === GAME_STATE.CHECKMATE
? { title: "GAME OVER", message: `${winner} wins!` }
: { title: "GAME OVER", message: `It's a draw!` }
;
}
if (banner) {
if (this.boardDialogService) {
const boundingRect = this.boardElRef.nativeElement.getBoundingClientRect();
const s = this.lastSizeEvent;
const rect: ClientRect = {
bottom: boundingRect.top + s.clientHeight + s.yOffset,
height: s.clientHeight,
left: boundingRect.left + s.xOffset,
right: boundingRect.left + s.clientWidth + s.xOffset,
top: boundingRect.top + s.yOffset,
width: s.clientWidth
};
this.boardDialogService.showMessage(banner, rect);
} else {
this.banner = banner;
this.cdr.markForCheck();
}
}
log('STATE CHANGE: ' + GAME_STATE[newState]);
}
onPieceDrag($event: PieceDragEvent): void {
this.dragPiece = $event.piece;
}
ngOnDestroy() {
this.clearSubscriptions();
if (this.onDocumentTouchMove) {
document.removeEventListener("touchmove", this.onDocumentTouchMove);
}
if (this.onWindowResize) {
window.removeEventListener("resize", this.onWindowResize);
}
}
newGame(): Promise<void> {
this.busy(false);
this.blockUi(false);
this.banner = undefined;
this.cdr.markForCheck();
return Promise.resolve();
}
private clearSubscriptions() {
while(this.rxWaste.length > 0) {
this.rxWaste.pop().unsubscribe();
}
}
/**
* Enable / Disable user interaction with the board
*/
blockUi(value: boolean): void {
this.isDisabled = value;
this.cdr.markForCheck();
}
/**
* Toggle busy indicator
* @param value
*/
busy(value: boolean): void {
this.isBusy = value;
this.cdr.markForCheck();
}
highlight(blocks: Block[]): void {
this.highlighted = blocks;
this.cdr.markForCheck();
}
/**
* Returns the ratio between the current SVG width (X) to the original width.
* This is to go from current element width to original width.
* @returns {number}
*/
private get ratioX(): number {
return this.width / this.lastSizeEvent.clientHeight;
}
/**
* Returns the ratio between the current SVG width (Y) to the original width.
* This is to go from current element width to original width.
* Note: a board is a square so ratioX === ratioY, it's here for consistency
* @returns {number}
*/
private get ratioY(): number {
return this.height / this.lastSizeEvent.clientWidth
}
private registerDragAndDrop() {
let svgElement: SVGSVGElement = this.boardElRef.nativeElement;
let mousedown = Observable.fromEvent(svgElement, 'mousedown', { passive: false });
let touchstart = Observable.fromEvent(svgElement, 'touchstart', { passive: false });
let mousemove = Observable.fromEvent(svgElement, 'mousemove', { passive: false });
let touchmove = Observable.fromEvent(svgElement, 'touchmove', { passive: false });
// TODO: maybe catch mouseup on root component, get root via appRef boot event.
let mouseup = Observable.fromEvent(document, 'mouseup'); // catch drops everywhere
let touchend = Observable.fromEvent(document, 'touchend'); // catch drops everywhere
let mousedrag = mousedown.mergeMap((md: MouseEvent) => {
if (this.isDisabled || !this.dragPiece) return []; // only track when piece is clicked, nothing else.
// only drag when it's the piece turn.
if (this.dragPiece.piece.color !== this.engine.turn()) return [];
// since SVG is responsive 1 mouse px != 1 svg px
// we get SVG px and we need a conversion ratio, from SVG to mouse px:
const viewPortRatioX = this.ratioX,
viewPortRatioY = this.ratioY;
this.dragPiece.dragStart();
let lastX = md.pageX;
let lastY = md.pageY;
// get all blocks that are a legal move for the current dragged piece
// TODO: Move to Controller
this.highlight(this.engine.moves(this.dragPiece.piece));
// Calculate delta with mousemove until mouseup
return mousemove.map((mm: MouseEvent) => {
mm.preventDefault();
let newScale = svgElement.currentScale,
translation = svgElement.currentTranslate,
x = (mm.pageX - translation.x) / newScale,
y = (mm.pageY - translation.y) / newScale;
let res = {
x: x - lastX,
y: y - lastY
};
lastX = mm.pageX;
lastY = mm.pageY;
res.x *= viewPortRatioX;
res.y *= viewPortRatioY;
return res;
}).takeUntil(mouseup); // stop moving when mouse is up
});
let touchdrag = touchstart.mergeMap((md: TouchEvent) => {
this.updateLastSizeEvent();
if (this.isDisabled) return []; // only track when piece is clicked, nothing else.
if (md.touches.length < 1) return [];
// Accurate piece selection won't do in mobile, we select a piece if it's block was touched.
let { left, top } = svgElement.getBoundingClientRect();
left += this.lastSizeEvent.xOffset;
top += this.lastSizeEvent.yOffset;
const getPoint = (touchEvent: TouchEvent) => ({
x: touchEvent.touches[0].pageX - left,
y: touchEvent.touches[0].pageY - top
});
const lastPoint = getPoint(md);
const dropBlockIndex = BaseBlock.pointToIndex(lastPoint.x * this.ratioX, lastPoint.y * this.ratioY);
this.dragPiece = this.pieces.toArray().filter(p => p.piece.block.index === dropBlockIndex)[0];
if (!this.dragPiece) return [];
// only drag when it's the piece turn.
if (this.dragPiece.piece.color !== this.engine.turn()) return [];
// since SVG is responsive 1 mouse px != 1 svg px
// we get SVG px and we need a conversion ratio, from SVG to mouse px:
const viewPortRatioX = this.ratioX,
viewPortRatioY = this.ratioY;
this.dragPiece.dragStart();
// get all blocks that are a legal move for the current dragged piece
// TODO: Move to Controller
this.highlight(this.engine.moves(this.dragPiece.piece));
// Calculate delta with mousemove until mouseup
return touchmove.map((mm: TouchEvent) => {
mm.preventDefault();
const pnt = getPoint(mm);
let newScale = svgElement.currentScale,
translation = svgElement.currentTranslate;
pnt.x = (pnt.x - translation.x) / newScale;
pnt.y = (pnt.y - translation.y) / newScale;
const res = {
x: (pnt.x - lastPoint.x) * viewPortRatioX,
y: (pnt.y - lastPoint.y) * viewPortRatioY
};
lastPoint.x = pnt.x;
lastPoint.y = pnt.y;
return res;
}).takeUntil(touchend); // stop moving when mouse is up
});
// Update coordinates of the dragged piece
let subscription = mousedrag.subscribe(pos => pos && this.dragPiece.setCoordinates(pos.x, pos.y));
this.rxWaste.push(subscription);
subscription = touchdrag.subscribe(pos => pos && this.dragPiece.setCoordinates(pos.x, pos.y));
this.rxWaste.push(subscription);
// take action when a piece is dropped
subscription = mouseup.subscribe(mu => this.dragPiece && this.dropPiece(mu));
this.rxWaste.push(subscription);
subscription = touchend.subscribe(mu => this.dragPiece && this.dropPiece(mu));
this.rxWaste.push(subscription);
}
/**
* A user made a move that requires a promotion, this is the place to diplay a prompt.
* @returns {Promise<PieceType>}
*/
askPromotionType(): Promise<PieceType> {
return Promise.resolve(PieceType.QUEEN);
}
/**
* Reflects a logical move on the board, this is a simple UI move operation, no logic
* You can use this function to move UI elements so they will be illegal!
* Note that moving a piece to an occupied block will remove the tenant from the UI.
* @param piece
*/
move(piece: Piece): void {
const pieceCmp = this.pieces.toArray().filter(p => p.piece === piece)[0];
if (pieceCmp) {
const toBlockCmp = this.blocks.toArray()[piece.block.index];
pieceCmp.block = toBlockCmp;
pieceCmp.reset(150);
} else if (this.engine.pieces.indexOf(piece) > -1) {
// item in collection but not kicked in by CD
// we need to let the VM turn end for CD to kick it.
setTimeout( () => this.move(piece) );
}
}
private updateLastSizeEvent(): void {
const e = this.boardElRef.nativeElement;
this.lastSizeEvent = {
height: e.clientHeight,
width: e.clientWidth,
clientHeight: Math.min((e.clientHeight || e.parentNode.clientHeight), (e.clientWidth || e.parentNode.clientWidth)),
clientWidth: Math.min((e.clientWidth || e.parentNode.clientWidth), (e.clientHeight || e.parentNode.clientHeight)),
xOffset: e.clientWidth > e.clientHeight ? (e.clientWidth / 2) - (e.clientHeight / 2) : 0,
yOffset: e.clientHeight > e.clientWidth ? (e.clientHeight / 2) - (e.clientWidth / 2) : 0
};
}
private dropPiece(mu): void {
if (this.isDisabled) return;
// TODO: Clicks outside SVG will still yield an even with coordinates relative to the parent
// of the SVG, this might resolve to a valid block!
// need to have 2 observables for document and for SVG element and merge them to one. (SVG should preventDefault)
// the document observables should emit value that this function can identify then cancel the drop.
let x = mu.clientX, y = mu.clientY;
if ( x === undefined || y === undefined ) {
x = mu.changedTouches[0].clientX;
y = mu.changedTouches[0].clientY;
}
const rect = this.boardElRef.nativeElement.getBoundingClientRect();
x -= rect.left;
y -= rect.top;
// getting the X when preserveAspectRation is xMid and SVG parents have no width so it's auto calculated
if (rect.width > rect.height) {
x -= (rect.width / 2) - (rect.height / 2);
} else {
y -= (rect.height / 2) - (rect.width / 2);
}
const dropBlockIndex = BaseBlock.pointToIndex(x * this.ratioX, y * this.ratioY);
const dropBlock = this.blocks.toArray()[dropBlockIndex];
// take action only when user dropped on a block
if (dropBlock) {
this.ctrl.move(this.dragPiece.piece, dropBlock.block)
.then(move => {
if (move.invalid) {
// the controller didn't do a move, we need to reset back to place.
this.dragPiece.reset(150);
} else { // the controller did the move
// this.dragPiece.block = dropBlock;
if (move.isCastlingMove()) {
// castling is special, it moves a piece (rook) from a block not related to the action.
// In most cases the logic change in the engine will propagate via angular's CD, not this case.
// User clicked on the king's block and we also need to handle the rook's block.
// On regular move's we pair block with pieces at the piece component on drag end, the
// piece will trigger CDR internally for itself only, which is fine.
// On any capture including en-passant we remove the piece from the logical piece array
// which affect the QueryList and thus the dom elements.
// However, on castling we don't remove the rook, we don't even change it's location (index)
// in the array so nothing about the rook trigger it's piece CDR.
// this means we need to run a sync operation
// this will resync all block components with piece components.
// TODO: Refactor, we know all piece's involved we can only change them instead of complete sweep.
this.syncPiecesToBlocks();
}
log(move);
}
this.endDragAndDrop();
});
}
else {
this.dragPiece.reset(150);
this.endDragAndDrop();
}
}
private endDragAndDrop() {
this.dragPiece.dragEnd(); // let the piece set itself inside the block and trigger CD.
this.dragPiece = undefined; // reset drag placeholders.
this.highlighted = [];
}
/**
* Clear all block/piece component pairing and re-pair them according to the current state of
* the block/piece models.
*/
private syncPiecesToBlocks() {
const pieces = this.pieces.toArray(),
blocks = this.blocks.toArray();
blocks.forEach(b => {
let found: boolean;
for (let i = 0, len = pieces.length; i < len; i++) {
if ( b.block === pieces[i].piece.block ) {
found = true;
pieces[i].block = b;
pieces[i].reset(150);
break;
}
}
// when settings a block component on a piece the setter will also set the piece on a block.
// i.e: piece.block = block will do block.piece = piece.
// if we didn't find a piece (i.e the block is empty) we need to clear it)
if (!found) b.piece = undefined;
});
}
} | the_stack |
import * as Oni from "oni-api"
import * as Log from "oni-core-logging"
import { Event } from "oni-types"
import * as React from "react"
import { getMetadata } from "./../../Services/Metadata"
import { ISession, SessionManager } from "./../../Services/Sessions"
import styled, {
boxShadowInset,
Css,
css,
enableMouse,
getSelectedBorder,
keyframes,
lighten,
} from "./../../UI/components/common"
import { Icon } from "./../../UI/Icon"
// const entrance = keyframes`
// 0% { opacity: 0; transform: translateY(2px); }
// 100% { opacity: 0.5; transform: translateY(0px); }
// `
// const enterLeft = keyframes`
// 0% { opacity: 0; transform: translateX(-4px); }
// 100% { opacity: 1; transform: translateX(0px); }
// `
// const enterRight = keyframes`
// 0% { opacity: 0; transform: translateX(4px); }
// 100% { opacity: 1; transform: translateX(0px); }
// `
const entranceFull = keyframes`
0% {
opacity: 0;
transform: translateY(8px);
}
100% {
opacity: 1;
transform: translateY(0px);
}
`
const WelcomeWrapper = styled.div`
background-color: ${p => p.theme["editor.background"]};
color: ${p => p.theme["editor.foreground"]};
overflow-y: hidden;
user-select: none;
pointer-events: all;
width: 100%;
height: 100%;
opacity: 0;
animation: ${entranceFull} 0.25s ease-in 0.1s forwards ${enableMouse};
`
interface IColumnProps {
alignment?: string
justify?: string
flex?: string
height?: string
extension?: Css
}
const Column = styled<IColumnProps, "div">("div")`
background: inherit;
display: flex;
justify-content: ${({ justify }) => justify || `center`};
align-items: ${({ alignment }) => alignment || "center"};
flex-direction: column;
width: 100%;
flex: ${({ flex }) => flex || "1"};
height: ${({ height }) => height || `auto`};
${({ extension }) => extension};
`
const sectionStyles = css`
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
height: 90%;
overflow-y: hidden;
direction: rtl;
&:hover {
overflow-y: overlay;
}
& > * {
direction: ltr;
}
`
const LeftColumn = styled.div`
${sectionStyles};
padding: 0;
padding-left: 1rem;
overflow-y: hidden;
width: 60%;
`
const RightColumn = styled.div`
${sectionStyles};
width: 30%;
border-left: 1px solid ${({ theme }) => theme["editor.background"]};
`
const Row = styled<{ extension?: Css }, "div">("div")`
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
opacity: 0;
${({ extension }) => extension};
`
const TitleText = styled.div`
font-size: 2em;
text-align: right;
`
const SubtitleText = styled.div`
font-size: 1.2em;
text-align: right;
`
const HeroImage = styled.img`
width: 192px;
height: 192px;
opacity: 0.4;
`
export const SectionHeader = styled.div`
margin-top: 1em;
margin-bottom: 1em;
font-size: 1.2em;
font-weight: bold;
text-align: left;
width: 100%;
`
const WelcomeButtonHoverStyled = `
transform: translateY(-1px);
box-shadow: 0 4px 8px 2px rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
`
export interface WelcomeButtonWrapperProps {
isSelected: boolean
borderSize: string
}
const WelcomeButtonWrapper = styled<WelcomeButtonWrapperProps, "button">("button")`
box-sizing: border-box;
font-size: inherit;
font-family: inherit;
border: 0px solid ${props => props.theme.foreground};
border-left: ${getSelectedBorder};
border-right: 4px solid transparent;
cursor: pointer;
color: ${({ theme }) => theme.foreground};
background-color: ${({ theme }) => lighten(theme.background)};
transform: ${({ isSelected }) => (isSelected ? "translateX(-4px)" : "translateX(0px)")};
transition: transform 0.25s;
width: 100%;
margin: 0.8em 0;
padding: 0.8em;
display: flex;
flex-direction: row;
&:hover {
${WelcomeButtonHoverStyled};
}
`
const AnimatedContainer = styled<{ duration: string }, "div">("div")`
width: 100%;
animation: ${entranceFull} ${p => p.duration} ease-in 1s both;
`
const WelcomeButtonTitle = styled.span`
font-size: 1em;
font-weight: bold;
margin: 0.4em;
width: 100%;
text-align: left;
`
const WelcomeButtonDescription = styled.span`
font-size: 0.8em;
opacity: 0.75;
margin: 4px;
width: 100%;
text-align: right;
`
const boxStyling = css`
width: 60%;
height: 60%;
padding: 0 1em;
opacity: 1;
margin-top: 64px;
box-sizing: border-box;
border: 1px solid ${p => p.theme["editor.hover.contents.background"]};
border-radius: 4px;
overflow: hidden;
justify-content: space-around;
background-color: ${p => p.theme["editor.hover.contents.codeblock.background"]};
${boxShadowInset};
`
const titleRow = css`
width: 100%;
padding-top: 32px;
animation: ${entranceFull} 0.25s ease-in 0.25s forwards};
`
const selectedSectionItem = css`
${({ theme }) => `
text-decoration: underline;
color: ${theme["highlight.mode.normal.background"]};
`};
`
export const SectionItem = styled<{ isSelected?: boolean }, "li">("li")`
width: 100%;
margin: 0.2em;
text-align: left;
height: auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
${({ isSelected }) => isSelected && selectedSectionItem};
&:hover {
text-decoration: underline;
}
`
export const SessionsList = styled.ul`
width: 70%;
margin: 0;
list-style-type: none;
border-radius: 4px;
padding: 0 1em;
border: 1px solid ${p => p.theme["editor.hover.contents.codeblock.background"]};
`
export interface WelcomeButtonProps {
title: string
description: string
command: string
selected: boolean
onClick: () => void
}
interface IChromeDiv extends HTMLButtonElement {
scrollIntoViewIfNeeded: () => void
}
export class WelcomeButton extends React.PureComponent<WelcomeButtonProps> {
private _button = React.createRef<IChromeDiv>()
public componentDidUpdate(prevProps: WelcomeButtonProps) {
if (!prevProps.selected && this.props.selected) {
this._button.current.scrollIntoViewIfNeeded()
}
}
public render() {
return (
<WelcomeButtonWrapper
borderSize="4px"
innerRef={this._button}
isSelected={this.props.selected}
onClick={this.props.onClick}
>
<WelcomeButtonTitle>{this.props.title}</WelcomeButtonTitle>
<WelcomeButtonDescription>{this.props.description}</WelcomeButtonDescription>
</WelcomeButtonWrapper>
)
}
}
export interface WelcomeHeaderState {
version: string
}
export interface OniWithActiveSection extends Oni.Plugin.Api {
sessions: SessionManager
getActiveSection(): string
}
type ExecuteCommand = <T>(command: string, args?: T) => void
export interface IWelcomeInputEvent {
select: boolean
vertical: number
horizontal?: number
}
interface ICommandMetadata {
execute: <T = undefined>(args?: T) => void
command: string
}
export interface IWelcomeCommandsDictionary {
openFile: ICommandMetadata
openTutor: ICommandMetadata
openDocs: ICommandMetadata
openConfig: ICommandMetadata
openThemes: ICommandMetadata
openWorkspaceFolder: ICommandMetadata
commandPalette: ICommandMetadata
commandline: ICommandMetadata
restoreSession: (sessionName: string) => Promise<void>
}
export class WelcomeBufferLayer implements Oni.BufferLayer {
public inputEvent = new Event<IWelcomeInputEvent>()
constructor(private _oni: OniWithActiveSection) {}
public showCommandline = async () => {
const remapping: string = await this._oni.editors.activeEditor.neovim.callFunction(
"mapcheck",
[":", "n"],
)
const mapping = remapping || ":"
this._oni.automation.sendKeys(mapping)
}
public executeCommand: ExecuteCommand = (cmd, args) => {
this._oni.commands.executeCommand(cmd, args)
}
public restoreSession = async (name: string) => {
await this._oni.sessions.restoreSession(name)
}
// tslint:disable-next-line
public readonly welcomeCommands: IWelcomeCommandsDictionary = {
openFile: {
execute: args => this.executeCommand("oni.editor.newFile", args),
command: "oni.editor.newFile",
},
openWorkspaceFolder: {
execute: args => this.executeCommand("workspace.openFolder", args),
command: "workspace.openFolder",
},
commandPalette: {
execute: args => this.executeCommand("commands.show", args),
command: "commands.show",
},
commandline: {
execute: this.showCommandline,
command: "editor.executeVimCommand",
},
openTutor: {
execute: args => this.executeCommand("oni.tutor.open", args),
command: "oni.tutor.open",
},
openDocs: {
execute: args => this.executeCommand("oni.docs.open", args),
command: "oni.docs.open",
},
openConfig: {
execute: args => this.executeCommand("oni.config.openUserConfig", args),
command: "oni.config.openUserConfig",
},
openThemes: {
execute: args => this.executeCommand("oni.themes.choose", args),
command: "oni.themes.open",
},
restoreSession: args => this.restoreSession(args),
}
public get id() {
return "oni.welcome"
}
public get friendlyName() {
return "Welcome"
}
public isActive(): boolean {
const activeSection = this._oni.getActiveSection()
return activeSection === "editor"
}
public handleInput(key: string) {
Log.info(`ONI WELCOME INPUT KEY: ${key}`)
switch (key) {
case "j":
this.inputEvent.dispatch({ vertical: 1, select: false })
break
case "k":
this.inputEvent.dispatch({ vertical: -1, select: false })
break
case "l":
this.inputEvent.dispatch({ vertical: 0, select: false, horizontal: 1 })
break
case "h":
this.inputEvent.dispatch({ vertical: 0, select: false, horizontal: -1 })
break
case "<enter>":
this.inputEvent.dispatch({ vertical: 0, select: true })
break
default:
this.inputEvent.dispatch({ vertical: 0, select: false })
}
}
public getProps() {
const active = this._oni.getActiveSection() === "editor"
const commandIds = Object.values(this.welcomeCommands)
.map(({ command }) => command)
.filter(Boolean)
const sessions = this._oni.sessions ? this._oni.sessions.allSessions : ([] as ISession[])
const sessionIds = sessions.map(({ id }) => id)
const ids = [...commandIds, ...sessionIds]
const sections = [commandIds.length, sessionIds.length].filter(Boolean)
return { active, ids, sections, sessions }
}
public render(context: Oni.BufferLayerRenderContext) {
const props = this.getProps()
return (
<WelcomeWrapper>
<WelcomeView
{...props}
getMetadata={getMetadata}
inputEvent={this.inputEvent}
commands={this.welcomeCommands}
restoreSession={this.restoreSession}
executeCommand={this.executeCommand}
/>
</WelcomeWrapper>
)
}
}
export interface WelcomeViewProps {
active: boolean
sessions: ISession[]
sections: number[]
ids: string[]
inputEvent: Event<IWelcomeInputEvent>
commands: IWelcomeCommandsDictionary
getMetadata: () => Promise<{ version: string }>
restoreSession: (name: string) => Promise<void>
executeCommand: ExecuteCommand
}
export interface WelcomeViewState {
version: string
selectedId: string
currentIndex: number
}
export class WelcomeView extends React.PureComponent<WelcomeViewProps, WelcomeViewState> {
public state: WelcomeViewState = {
version: null,
currentIndex: 0,
selectedId: this.props.ids[0],
}
private _welcomeElement = React.createRef<HTMLDivElement>()
public async componentDidMount() {
const metadata = await this.props.getMetadata()
this.setState({ version: metadata.version })
this.props.inputEvent.subscribe(this.handleInput)
}
public handleInput = async ({ vertical, select, horizontal }: IWelcomeInputEvent) => {
const { currentIndex } = this.state
const { sections, ids, active } = this.props
const newIndex = this.getNextIndex(currentIndex, vertical, horizontal, sections)
const selectedId = ids[newIndex]
this.setState({ currentIndex: newIndex, selectedId })
const selectedSession = this.props.sessions.find(session => session.id === selectedId)
if (select && active) {
if (selectedSession) {
await this.props.commands.restoreSession(selectedSession.name)
} else {
const currentCommand = this.getCurrentCommand(selectedId)
currentCommand.execute()
}
}
}
public getCurrentCommand(selectedId: string): ICommandMetadata {
const { commands } = this.props
const currentCommand = Object.values(commands).find(({ command }) => command === selectedId)
return currentCommand
}
public getNextIndex(
currentIndex: number,
vertical: number,
horizontal: number,
sections: number[],
) {
const nextPosition = currentIndex + vertical
const numberOfItems = this.props.ids.length
const multipleSections = sections.length > 1
// TODO: this currently handles *TWO* sections if more sections
// are to be added will need to rethink how to allow navigation across multiple sections
switch (true) {
case multipleSections && horizontal === 1:
return sections[0]
case multipleSections && horizontal === -1:
return 0
case nextPosition < 0:
return numberOfItems - 1
case nextPosition === numberOfItems:
return 0
default:
return nextPosition
}
}
public componentDidUpdate() {
if (this.props.active && this._welcomeElement && this._welcomeElement.current) {
this._welcomeElement.current.focus()
}
}
public render() {
const { version, selectedId } = this.state
return (
<Column innerRef={this._welcomeElement} height="100%" data-id="welcome-screen">
<Row extension={titleRow}>
<Column />
<Column alignment="flex-end">
<TitleText>Oni</TitleText>
<SubtitleText>Modern Modal Editing</SubtitleText>
</Column>
<Column flex="0 0">
<HeroImage src="images/oni-icon-no-border.svg" />
</Column>
<Column alignment="flex-start">
{version && <SubtitleText>{`v${version}`}</SubtitleText>}
<div>{"https://onivim.io"}</div>
</Column>
<Column />
</Row>
<Row extension={boxStyling}>
<WelcomeCommandsView
commands={this.props.commands}
selectedId={selectedId}
executeCommand={this.props.executeCommand}
/>
<RightColumn>
<SessionsList>
<SectionHeader>Sessions</SectionHeader>
{this.props.sessions.length ? (
this.props.sessions.map(session => (
<SectionItem
isSelected={session.id === selectedId}
onClick={() => this.props.restoreSession(session.name)}
key={session.id}
>
<Icon name="file" style={{ marginRight: "0.3em" }} />{" "}
{session.name}
</SectionItem>
))
) : (
<SectionItem>No Sessions Available</SectionItem>
)}
</SessionsList>
</RightColumn>
</Row>
</Column>
)
}
}
export interface IWelcomeCommandsViewProps extends Partial<WelcomeViewProps> {
selectedId: string
}
export const WelcomeCommandsView: React.SFC<IWelcomeCommandsViewProps> = props => {
const isSelected = (command: string) => command === props.selectedId
const { commands } = props
return (
<LeftColumn>
<AnimatedContainer duration="0.25s">
<SectionHeader>Quick Commands</SectionHeader>
<WelcomeButton
title="New File"
onClick={() => commands.openFile.execute()}
description="Control + N"
command={commands.openFile.command}
selected={isSelected(commands.openFile.command)}
/>
<WelcomeButton
title="Open File / Folder"
description="Control + O"
onClick={() => commands.openWorkspaceFolder.execute()}
command={commands.openWorkspaceFolder.command}
selected={isSelected(commands.openWorkspaceFolder.command)}
/>
<WelcomeButton
title="Command Palette"
onClick={() => commands.commandPalette.execute()}
description="Control + Shift + P"
command={commands.commandPalette.command}
selected={isSelected(commands.commandPalette.command)}
/>
<WelcomeButton
title="Vim Ex Commands"
description=":"
command="editor.openExCommands"
onClick={() => commands.commandline.execute()}
selected={isSelected(commands.commandline.command)}
/>
</AnimatedContainer>
<AnimatedContainer duration="0.25s">
<SectionHeader>Learn</SectionHeader>
<WelcomeButton
title="Tutor"
onClick={() => commands.openTutor.execute()}
description="Learn modal editing with an interactive tutorial."
command={commands.openTutor.command}
selected={isSelected(commands.openTutor.command)}
/>
<WelcomeButton
title="Documentation"
onClick={() => commands.openDocs.execute()}
description="Discover what Oni can do for you."
command={commands.openDocs.command}
selected={isSelected(commands.openDocs.command)}
/>
</AnimatedContainer>
<AnimatedContainer duration="0.25s">
<SectionHeader>Customize</SectionHeader>
<WelcomeButton
title="Configure"
onClick={() => commands.openConfig.execute()}
description="Make Oni work the way you want."
command={commands.openConfig.command}
selected={isSelected(commands.openConfig.command)}
/>
<WelcomeButton
title="Themes"
onClick={() => commands.openThemes.execute()}
description="Choose a theme that works for you."
command={commands.openThemes.command}
selected={isSelected(commands.openThemes.command)}
/>
</AnimatedContainer>
</LeftColumn>
)
} | the_stack |
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as _ from 'lodash';
import * as moment from 'moment';
import fileSaver from 'file-saver';
//let fileSaver = require('file-saver');
import { AdminService } from '../admin.service';
import { AuthService } from '../auth.service';
import { DatePipe } from '../date.pipe';
import { FileService } from '../file.service';
import { SpeakerService } from '../speaker.service';
import { TransitionService } from '../transition.service';
import { ToastComponent } from '../toast.component';
import { Session } from '../session.model';
import { Speaker } from '../speaker.model';
@Component({
selector: 'speaker',
templateUrl: './speaker.component.html',
styleUrls: ['./speaker.component.scss']
})
export class SpeakerComponent implements OnInit, OnDestroy {
@ViewChild('toast') toast: ToastComponent;
private paramsub: any;
model: Speaker;
speakerSessions: Session[] = [];
leadPresId: string = null;
defaultFileString = 'Choose a file...';
adminUploadString = '';
selectedAdminFile: File;
incompleteFields: string[] = [];
viewArrangeIndex: number;
costsCovered = [
{
name: 'travel',
covered: false
},
{
name: 'lodging',
covered: false
}
];
constructor(private transitionService: TransitionService,
private adminService: AdminService,
private authService: AuthService,
private fileService: FileService,
private speakerService: SpeakerService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
this.transitionService.transition();
this.adminUploadString = this.defaultFileString;
// Check for params
this.paramsub = this.route.params.subscribe(params => {
// Initialize fields for brand new speakers
if (!params['id']) {
this.model = <Speaker>{
costsCoveredByOrg: this.costsCovered
};
this.model.address2 = '';
this.model.assistantOrCC = '';
} else {
this.model = this.speakerService.getSpeaker(params['id']);
if (this.model.sessions.length > 0) {
this.speakerSessions = this.speakerService.getSpeakerSessions(this.model.sessions);
}
}
if (params['leadPresId']) {
this.leadPresId = params['leadPresId'];
}
if (params['msg']) {
this.toast.success(params['msg']);
}
if (this.authService.user.getValue().admin) {
// To enable historic viewing, display data based on viewing conf (not default)
let viewingConf = this.adminService.activeConference.getValue().title;
if (this.model.arrangements && this.model.arrangements.length > 0) {
this.viewArrangeIndex = _.findIndex(this.model.arrangements,
arrange => arrange.associatedConf === viewingConf);
if (this.viewArrangeIndex < 0) {
this.model.arrangements.push(<any>{associatedConf: viewingConf});
this.viewArrangeIndex = this.model.arrangements.length - 1;
}
} else {
if (!this.model.arrangements) {
this.model.arrangements = [];
}
this.model.arrangements.push(<any>{associatedConf: viewingConf});
this.viewArrangeIndex = 0;
}
}
});
}
ngOnDestroy() {
this.paramsub.unsubscribe();
}
archive(archive: boolean) {
this.model.archived = archive;
this.speakerService
.updateSpeaker(this.model)
.then(res => {
let text = archive ? 'archived' : 'unarchived';
this.toast.success(`Speaker ${text}!`);
});
}
capitalize(word: string): string {
return word.charAt(0).toUpperCase() + word.slice(1);
}
changeCostCovered(isChecked: boolean, costChecked) {
let cost = _.find(this.model.costsCoveredByOrg, cost => cost.name === costChecked.name);
cost.covered = isChecked;
}
checkRecentExp() {
return typeof this.model.hasPresentedAtCCAWInPast2years === 'boolean' && !this.model.hasPresentedAtCCAWInPast2years;
}
getNights(dateArrival: string, dateDeparture: string): number {
let arrivalMom = moment(dateArrival);
let departureMom = moment(dateDeparture);
return departureMom.diff(arrivalMom, 'days');
}
updateSpeaker(form: any) {
let complete = this.checkProfile(form);
this.model.profileComplete = complete
if (this.leadPresId) {
// If the lead pres is making a copresenter, create account and email
if (this.speakerService.findSpeakerByEmail(this.model.email)) {
this.toast.error('A speaker with that email already exists');
return;
}
let leadPres = this.speakerService.getSpeaker(this.leadPresId);
let signupData = {
email: this.model.email,
firstName: this.model.nameFirst,
lastName: this.model.nameLast
};
this.authService
.signUpForCopres(leadPres, signupData)
.then(res => {
// We need to sync the mongoose ID before udating remaining fields
this.model._id = res.userId;
this.speakerService
.updateSpeaker(this.model)
.then(res => {
this.router.navigate(['/dashboard', { msg: 'Copresenter account created and emailed!' }]);
});
// .then(res => {
// this.toast.success('Copresenter account created and emailed!')
// });
});
} else if (this.authService.user.getValue().admin && !this.model._id) {
// If an admin is making a speaker, create account
if (this.speakerService.findSpeakerByEmail(this.model.email)) {
this.toast.error('A speaker with that email already exists');
return
}
let signupData = {
email: this.model.email,
firstName: this.model.nameFirst,
lastName: this.model.nameLast,
password: 'ccawspeakerpassword' // Placeholder pass, change on first login
}
this.authService
.signup(signupData)
.then(res => {
// We need to sync the mongoose ID before udating remaining fields
this.model._id = res.userId;
this.speakerService
.updateSpeaker(this.model)
.then(res => {
this.toast.success('Speaker created, account generated.')
});
});
} else {
this.speakerService
// Must user model here rather than form, not all fields are
// 2-way data bound and are only updated via model (costsCovered)
.updateSpeaker(this.model, complete)
.then(res => {
// Only navigate for speakers, admins have too many partial fields bound to this function
if (!this.authService.user.getValue().admin) {
this.router.navigate(['/dashboard', { msg: 'Profile form saved!' }]);
} else {
this.toast.success('Speaker updated!');
}
});
}
}
checkProfile(form: any) {
let flag = true;
let expReq = !form['hasPresentedAtCCAWInPast2years'];
let refSpeaker = this.genRefSpeaker();
for (let field in refSpeaker) {
if (form.hasOwnProperty(field)) {
if (!expReq) {
// Experience fields not required if has presented at ccaw
if (field !== 'recentSpeakingExp' && field !== 'speakingReferences') {
if (typeof form[field] !== undefined) {
// If type is boolean, form item is completed
if (typeof form[field] !== 'boolean') {
if (!form[field] && field !== 'headshot') {
flag = false;
}
}
} else {
flag = false;
}
}
} else {
if (typeof form[field] !== undefined) {
// If type is boolean, form item is completed
if (typeof form[field] !== 'boolean') {
if (!form[field] && field !== 'salutation') {
flag = false;
}
}
} else {
flag = false;
}
}
}
}
return flag;
}
genRefSpeaker() {
let refSpeaker = {
salutation: '', nameFirst: '', nameLast: '', email: '',
title: '', organization: '', address1: '',
city: '', state: '', zip: '', phoneWork: '', phoneCell: '',
bioWebsite: '', bioProgram: '', headshot: '',
mediaWilling: false, speakingFees: '',
hasPresentedAtCCAWInPast2years: false, recentSpeakingExp: '',
speakingReferences: ''
};
return refSpeaker;
}
fileSelected(files: FileList, whichFile: string) {
if (!files[0]) return;
this.selectedAdminFile = files[0];
this.adminUploadString = this.selectedAdminFile.name;
}
upload(uploadTitle: string) {
if (!this.selectedAdminFile) return;
if (!uploadTitle) {
this.toast.error('Please enter a title for this upload.');
return;
}
let ext = this.selectedAdminFile.name.split('.').pop();
let userFilename = `${this.model.nameLast}_${this.model.email}_${uploadTitle}.${ext}`;
this.transitionService.setLoading(true);
let data = new FormData();
data.append('userFilename', userFilename);
data.append('file', this.selectedAdminFile);
let speakerName = this.model.nameFirst + ' ' + this.model.nameLast;
this.fileService
.uploadToServer(data)
.then(res => {
this.speakerService
.sendToDropbox(userFilename, 'adminUploads', speakerName)
.then(dbxRes => {
if (dbxRes.status) {
this.toast.error('Upload unsuccessful. Please try again!');
} else {
if (!this.model.adminUploads) this.model.adminUploads = [];
let upload = {
title: uploadTitle,
url: dbxRes
};
this.model.adminUploads.push(upload);
this.speakerService
.updateSpeaker(this.model)
.then(res => {
this.toast.success('Upload successful!');
this.transitionService.setLoading(false);
});
}
});
});
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/accountsMappers";
import * as Parameters from "../models/parameters";
import { MLTeamAccountManagementClientContext } from "../mLTeamAccountManagementClientContext";
/** Class representing a Accounts. */
export class Accounts {
private readonly client: MLTeamAccountManagementClientContext;
/**
* Create a Accounts.
* @param {MLTeamAccountManagementClientContext} client Reference to the service client.
*/
constructor(client: MLTeamAccountManagementClientContext) {
this.client = client;
}
/**
* Gets the properties of the specified machine learning team account.
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsGetResponse>
*/
get(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsGetResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param callback The callback
*/
get(resourceGroupName: string, accountName: string, callback: msRest.ServiceCallback<Models.Account>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, accountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Account>): void;
get(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Account>, callback?: msRest.ServiceCallback<Models.Account>): Promise<Models.AccountsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
options
},
getOperationSpec,
callback) as Promise<Models.AccountsGetResponse>;
}
/**
* Creates or updates a team account with the specified parameters.
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for creating or updating a machine learning team account.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, accountName: string, parameters: Models.Account, options?: msRest.RequestOptionsBase): Promise<Models.AccountsCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for creating or updating a machine learning team account.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, accountName: string, parameters: Models.Account, callback: msRest.ServiceCallback<Models.Account>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for creating or updating a machine learning team account.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, accountName: string, parameters: Models.Account, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Account>): void;
createOrUpdate(resourceGroupName: string, accountName: string, parameters: Models.Account, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Account>, callback?: msRest.ServiceCallback<Models.Account>): Promise<Models.AccountsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
parameters,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.AccountsCreateOrUpdateResponse>;
}
/**
* Deletes a machine learning team account.
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, accountName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, accountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, accountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Updates a machine learning team account with the specified parameters.
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for updating a machine learning team account.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsUpdateResponse>
*/
update(resourceGroupName: string, accountName: string, parameters: Models.AccountUpdateParameters, options?: msRest.RequestOptionsBase): Promise<Models.AccountsUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for updating a machine learning team account.
* @param callback The callback
*/
update(resourceGroupName: string, accountName: string, parameters: Models.AccountUpdateParameters, callback: msRest.ServiceCallback<Models.Account>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param accountName The name of the machine learning team account.
* @param parameters The parameters for updating a machine learning team account.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, accountName: string, parameters: Models.AccountUpdateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Account>): void;
update(resourceGroupName: string, accountName: string, parameters: Models.AccountUpdateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Account>, callback?: msRest.ServiceCallback<Models.Account>): Promise<Models.AccountsUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
accountName,
parameters,
options
},
updateOperationSpec,
callback) as Promise<Models.AccountsUpdateResponse>;
}
/**
* Lists all the available machine learning team accounts under the specified resource group.
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.AccountListResult>): void;
/**
* @param resourceGroupName The name of the resource group to which the machine learning team
* account belongs.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AccountListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccountListResult>, callback?: msRest.ServiceCallback<Models.AccountListResult>): Promise<Models.AccountsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.AccountsListByResourceGroupResponse>;
}
/**
* Lists all the available machine learning team accounts under the specified subscription.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.AccountsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.AccountListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AccountListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccountListResult>, callback?: msRest.ServiceCallback<Models.AccountListResult>): Promise<Models.AccountsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.AccountsListResponse>;
}
/**
* Lists all the available machine learning team accounts under the specified resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AccountListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AccountListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccountListResult>, callback?: msRest.ServiceCallback<Models.AccountListResult>): Promise<Models.AccountsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.AccountsListByResourceGroupNextResponse>;
}
/**
* Lists all the available machine learning team accounts under the specified subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.AccountsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.AccountsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.AccountListResult>): 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.AccountListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AccountListResult>, callback?: msRest.ServiceCallback<Models.AccountListResult>): Promise<Models.AccountsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.AccountsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Account
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Account,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Account
},
201: {
bodyMapper: Mappers.Account
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts/{accountName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.accountName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.AccountUpdateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Account
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningExperimentation/accounts",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.MachineLearningExperimentation/accounts",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.AccountListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import { DateTime, Interval } from 'luxon'
import { Shift } from './sharedUtils'
import {
getCoverageGapItems,
getSubheaderItems,
getOutOfBoundsItems,
} from './shiftsListUtil'
import { Chance } from 'chance'
import * as _ from 'lodash'
const c = new Chance()
const chicago = 'America/Chicago'
const newYork = 'America/New_York'
interface TestConfig {
name: string
schedIntervalISO: string
shifts: Shift[]
// expected is an array of start times for each coverage gap
expected: string[]
zone: string
}
describe('getSubheaderItems', () => {
function check(tc: TestConfig): void {
it(tc.name, () => {
const schedInterval = Interval.fromISO(tc.schedIntervalISO, {
zone: tc.zone,
})
const result = getSubheaderItems(schedInterval, tc.shifts, tc.zone)
expect(result).toHaveLength(tc.expected.length)
expect(_.uniq(result.map((r) => r.id))).toHaveLength(tc.expected.length)
result.forEach((r, i) => {
expect(r.at.zoneName).toEqual(tc.zone)
expect(r.at).toEqual(r.at.startOf('day'))
expect(r.subHeader).toBe(tc.expected[i])
})
})
}
check({
name: '0 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T00:00:00.000-05:00'}`,
shifts: [],
expected: [],
zone: chicago,
})
check({
name: '1 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T01:00:00.000-05:00'}`,
shifts: [],
expected: ['Friday, August 13'],
zone: chicago,
})
check({
name: '1 hr sched interval; no shifts; alternate zone',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T01:00:00.000-05:00'}`,
shifts: [],
expected: ['Friday, August 13'],
zone: newYork,
})
check({
name: '24 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [],
expected: ['Friday, August 13'],
zone: chicago,
})
check({
name: '25 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T01:00:00.000-05:00'}`,
shifts: [],
expected: ['Friday, August 13', 'Saturday, August 14'],
zone: chicago,
})
check({
name: '50 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-15T02:00:00.000-05:00'}`,
shifts: [],
expected: ['Friday, August 13', 'Saturday, August 14', 'Sunday, August 15'],
zone: chicago,
})
check({
name: '24 hr sched interval; 1 shift before sched start',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-12T00:00:00.000-05:00',
end: '2021-08-13T05:00:00.000-05:00',
},
],
expected: ['Thursday, August 12', 'Friday, August 13'],
zone: chicago,
})
check({
name: '24 hr sched interval; 1 shift inside sched interval',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-13T02:00:00.000-05:00',
end: '2021-08-13T03:00:00.000-05:00',
},
],
expected: ['Friday, August 13'],
zone: chicago,
})
check({
name: '24 hr sched interval; 1 shift after sched interval',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-15T02:00:00.000-05:00',
end: '2021-08-16T04:00:00.000-05:00',
},
],
expected: [
'Friday, August 13',
'Saturday, August 14',
'Sunday, August 15',
'Monday, August 16',
],
zone: chicago,
})
check({
name: '30 hr sched interval; 3 random shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T06:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-13T01:00:00.000-05:00',
end: '2021-08-13T03:00:00.000-05:00',
},
{
userID: c.guid(),
start: '2021-08-13T02:00:00.000-05:00',
end: '2021-08-13T04:00:00.000-05:00',
},
{
userID: c.guid(),
start: '2021-08-15T02:00:00.000-05:00',
end: '2021-08-15T08:00:00.000-05:00',
},
],
expected: ['Friday, August 13', 'Saturday, August 14', 'Sunday, August 15'],
zone: chicago,
})
})
describe('getCoverageGapItems', () => {
function check(tc: TestConfig): void {
it(tc.name, () => {
const schedInterval = Interval.fromISO(tc.schedIntervalISO, {
zone: tc.zone,
})
const result = getCoverageGapItems(
schedInterval,
tc.shifts,
tc.zone,
() => {},
)
expect(result).toHaveLength(tc.expected.length)
expect(_.uniq(result.map((r) => r.id))).toHaveLength(tc.expected.length)
result.forEach((r, i) => {
expect(r.at.zoneName).toEqual(tc.zone)
expect(r.at).toEqual(
DateTime.fromISO(tc.expected[i], { zone: tc.zone }),
)
})
})
}
check({
name: '0 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T00:00:00.000-05:00'}`,
shifts: [],
expected: [],
zone: chicago,
})
check({
name: '1 hr sched interval; no shifts; alternate zone',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T01:00:00.000-05:00'}`,
shifts: [],
expected: ['2021-08-13T00:00:00.000-05:00'],
zone: newYork,
})
check({
name: '3 hr sched interval; 1 shift; 2 gaps',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T03:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-13T01:00:00.000-05:00',
end: '2021-08-13T02:00:00.000-05:00',
},
],
expected: [
'2021-08-13T00:00:00.000-05:00',
'2021-08-13T02:00:00.000-05:00',
],
zone: chicago,
})
check({
name: '3 hr sched interval; 1 shift; 1 gap before',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T03:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-13T01:00:00.000-05:00',
end: '2021-08-13T03:00:00.000-05:00',
},
],
expected: ['2021-08-13T00:00:00.000-05:00'],
zone: chicago,
})
check({
name: '3 hr sched interval; 1 shift; 1 gap after',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T03:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-13T00:00:00.000-05:00',
end: '2021-08-13T01:00:00.000-05:00',
},
],
expected: ['2021-08-13T01:00:00.000-05:00'],
zone: chicago,
})
})
describe('getOutOfBoundsItems', () => {
function check(tc: TestConfig): void {
it(tc.name, () => {
const schedInterval = Interval.fromISO(tc.schedIntervalISO, {
zone: tc.zone,
})
const result = getOutOfBoundsItems(schedInterval, tc.shifts, tc.zone)
expect(result).toHaveLength(tc.expected.length)
expect(_.uniq(result.map((r) => r.id))).toHaveLength(tc.expected.length)
// expect to see start time of each out of bounds day
result.forEach((r, i) => {
expect(r.at.zoneName).toEqual(tc.zone)
expect(r.at.toISO()).toEqual(tc.expected[i])
})
})
}
check({
name: '0 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T00:00:00.000-05:00'}`,
shifts: [],
expected: [],
zone: chicago,
})
check({
name: '1 hr sched interval; no shifts',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-13T01:00:00.000-05:00'}`,
shifts: [],
expected: [],
zone: chicago,
})
check({
name: '24 hr sched interval; shift 1 day before sched start',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-12T00:00:00.000-05:00',
end: '2021-08-13T05:00:00.000-05:00',
},
],
expected: ['2021-08-12T00:00:00.000-05:00'],
zone: chicago,
})
check({
name: '24 hr sched interval; shift the day the sched ends',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-14T00:00:00.000-05:00',
end: '2021-08-14T05:00:00.000-05:00',
},
],
expected: [],
zone: chicago,
})
check({
name: '24 hr sched interval; shift 3 days before sched start',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-10T00:00:00.000-05:00',
end: '2021-08-10T05:00:00.000-05:00',
},
],
expected: [
'2021-08-10T00:00:00.000-05:00',
'2021-08-11T00:00:00.000-05:00',
'2021-08-12T00:00:00.000-05:00',
],
zone: chicago,
})
check({
name: '24 hr sched interval; shift 3 days after sched end',
schedIntervalISO: `${'2021-08-13T00:00:00.000-05:00'}/${'2021-08-14T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-08-16T00:00:00.000-05:00',
end: '2021-08-16T05:00:00.000-05:00',
},
],
expected: [
'2021-08-15T00:00:00.000-05:00',
'2021-08-16T00:00:00.000-05:00',
],
zone: chicago,
})
check({
name: 'sched interval ends at midnight; 1 shift starts and ends on same day as schedule start',
schedIntervalISO: `${'2021-10-12T01:00:00.000-05:00'}/${'2021-10-13T00:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-10-12T00:00:00.000-05:00',
end: '2021-10-12T06:00:00.000-05:00',
},
],
expected: [],
zone: chicago,
})
check({
name: 'sched interval ends at 1am; 1 shift starts and ends on same day as schedule end',
schedIntervalISO: `${'2021-10-12T00:00:00.000-05:00'}/${'2021-10-13T01:00:00.000-05:00'}`,
shifts: [
{
userID: c.guid(),
start: '2021-10-13T00:00:00.000-05:00',
end: '2021-10-13T06:00:00.000-05:00',
},
],
expected: [],
zone: chicago,
})
}) | the_stack |
import { splitPath, foreach, decodeVarint } from "./utils";
//import { StatusCodes, TransportStatusError } from "@ledgerhq/errors";
import type Transport from "@ledgerhq/hw-transport";
const remapTransactionRelatedErrors = (e) => {
if (e && e.statusCode === 0x6a80) {
// TODO:
}
return e;
};
const PATH_SIZE = 4;
const PATHS_LENGTH_SIZE = 1;
const CLA = 0xe0;
const ADDRESS = 0x02;
const SIGN = 0x04;
const SIGN_HASH = 0x05;
const SIGN_MESSAGE = 0x08;
const ECDH_SECRET = 0x0a;
const VERSION = 0x06;
const CHUNK_SIZE = 250;
/**
* Tron API
*
* @example
* import Trx from "@ledgerhq/hw-app-trx";
* const trx = new Trx(transport)
*/
export default class Trx {
transport: Transport;
constructor(transport: Transport, scrambleKey = "TRX") {
this.transport = transport;
transport.decorateAppAPIMethods(
this,
[
"getAddress",
"getECDHPairKey",
"signTransaction",
"signTransactionHash",
"signPersonalMessage",
"getAppConfiguration",
],
scrambleKey
);
}
/**
* get Tron address for a given BIP 32 path.
* @param path a path in BIP 32 format
* @option boolDisplay optionally enable or not the display
* @return an object with a publicKey and address
* @example
* const address = await tron.getAddress("44'/195'/0'/0/0").then(o => o.address)
*/
getAddress(
path: string,
boolDisplay?: boolean
): Promise<{
publicKey: string;
address: string;
}> {
const paths = splitPath(path);
const buffer = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
return this.transport
.send(CLA, ADDRESS, boolDisplay ? 0x01 : 0x00, 0x00, buffer)
.then((response) => {
const publicKeyLength = response[0];
const addressLength = response[1 + publicKeyLength];
return {
publicKey: response.slice(1, 1 + publicKeyLength).toString("hex"),
address: response
.slice(
1 + publicKeyLength + 1,
1 + publicKeyLength + 1 + addressLength
)
.toString("ascii"),
};
});
}
getNextLength(tx: Buffer): number {
const field = decodeVarint(tx, 0);
const data = decodeVarint(tx, field.pos);
if ((field.value & 0x07) === 0) return data.pos;
return data.value + data.pos;
}
/**
* sign a Tron transaction with a given BIP 32 path and Token Names
*
* @param path a path in BIP 32 format
* @param rawTxHex a raw transaction hex string
* @param tokenSignatures Tokens Signatures array
* @option version pack message based on ledger firmware version
* @option smartContract boolean hack to set limit buffer on ledger device
* @return a signature as hex string
* @example
* const signature = await tron.signTransaction("44'/195'/0'/0/0", "0a02f5942208704dda506d59dceb40f0f4978f802e5a69080112650a2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e747261637412340a1541978dbd103cfe59c35e753d09dd44ae1ae64621c7121541e2ae49db6a70b9b4757d2137a43b69b24a445780188ef8b5ba0470cbb5948f802e", [], 105);
*/
signTransaction(
path: string,
rawTxHex: string,
tokenSignatures: string[]
): Promise<string> {
const paths = splitPath(path);
let rawTx = Buffer.from(rawTxHex, "hex");
const toSend: Buffer[] = [];
let data = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
// write path for first chuck only
data[0] = paths.length;
paths.forEach((element, index) => {
data.writeUInt32BE(element, 1 + 4 * index);
});
while (rawTx.length > 0) {
// get next message field
const newpos = this.getNextLength(rawTx);
if (newpos > CHUNK_SIZE) throw new Error("Too many bytes to encode.");
if (data.length + newpos > CHUNK_SIZE) {
toSend.push(data);
data = Buffer.alloc(0);
continue;
}
// append data
data = Buffer.concat([data, rawTx.slice(0, newpos)]);
rawTx = rawTx.slice(newpos, rawTx.length);
}
toSend.push(data);
const startBytes: number[] = [];
let response;
const tokenPos = toSend.length;
if (tokenSignatures !== undefined) {
for (let i = 0; i < tokenSignatures.length; i += 1) {
const buffer = Buffer.from(tokenSignatures[i], "hex");
toSend.push(buffer);
}
}
// get startBytes
if (toSend.length === 1) {
startBytes.push(0x10);
} else {
startBytes.push(0x00);
for (let i = 1; i < toSend.length - 1; i += 1) {
if (i >= tokenPos) {
startBytes.push(0xa0 | 0x00 | (i - tokenPos)); // eslint-disable-line no-bitwise
} else {
startBytes.push(0x80);
}
}
if (tokenSignatures !== undefined && tokenSignatures.length) {
startBytes.push(0xa0 | 0x08 | (tokenSignatures.length - 1)); // eslint-disable-line no-bitwise
} else {
startBytes.push(0x90);
}
}
return foreach(toSend, (data, i) => {
return this.transport
.send(CLA, SIGN, startBytes[i], 0x00, data)
.then((apduResponse) => {
response = apduResponse;
});
}).then(
() => {
return response.slice(0, 65).toString("hex");
},
(e) => {
throw remapTransactionRelatedErrors(e);
}
);
}
/**
* sign a Tron transaction hash with a given BIP 32 path
*
* @param path a path in BIP 32 format
* @param rawTxHex a raw transaction hex string
* @return a signature as hex string
* @example
* const signature = await tron.signTransactionHash("44'/195'/0'/0/0", "25b18a55f86afb10e7aca38d0073d04c80397c6636069193953fdefaea0b8369");
*/
signTransactionHash(path: string, rawTxHashHex: string): Promise<string> {
const paths = splitPath(path);
let data = Buffer.alloc(PATHS_LENGTH_SIZE + paths.length * PATH_SIZE);
data[0] = paths.length;
paths.forEach((element, index) => {
data.writeUInt32BE(element, 1 + 4 * index);
});
data = Buffer.concat([data, Buffer.from(rawTxHashHex, "hex")]);
return this.transport
.send(CLA, SIGN_HASH, 0x00, 0x00, data)
.then((response) => {
return response.slice(0, 65).toString("hex");
});
}
/**
* get the version of the Tron app installed on the hardware device
*
* @return an object with a version
* @example
* const result = await tron.getAppConfiguration();
* {
* "version": "0.1.5",
* "versionN": "105".
* "allowData": false,
* "allowContract": false,
* "truncateAddress": false,
* "signByHash": false
* }
*/
getAppConfiguration(): Promise<{
allowContract: boolean;
truncateAddress: boolean;
allowData: boolean;
signByHash: boolean;
version: string;
versionN: number;
}> {
return this.transport.send(CLA, VERSION, 0x00, 0x00).then((response) => {
// eslint-disable-next-line no-bitwise
const signByHash = (response[0] & (1 << 3)) > 0;
// eslint-disable-next-line no-bitwise
let truncateAddress = (response[0] & (1 << 2)) > 0;
// eslint-disable-next-line no-bitwise
let allowContract = (response[0] & (1 << 1)) > 0;
// eslint-disable-next-line no-bitwise
let allowData = (response[0] & (1 << 0)) > 0;
if (response[1] === 0 && response[2] === 1 && response[3] < 2) {
allowData = true;
allowContract = false;
}
if (response[1] === 0 && response[2] === 1 && response[3] < 5) {
truncateAddress = false;
}
const result = {
version: `${response[1]}.${response[2]}.${response[3]}`,
versionN: response[1] * 10000 + response[2] * 100 + response[3],
allowData,
allowContract,
truncateAddress,
signByHash,
};
return result;
});
}
/**
* sign a Tron Message with a given BIP 32 path
*
* @param path a path in BIP 32 format
* @param message hex string to sign
* @return a signature as hex string
* @example
* const signature = await tron.signPersonalMessage("44'/195'/0'/0/0", "43727970746f436861696e2d54726f6e5352204c6564676572205472616e73616374696f6e73205465737473");
*/
signPersonalMessage(path: string, messageHex: string): Promise<string> {
const paths = splitPath(path);
const message = Buffer.from(messageHex, "hex");
let offset = 0;
const toSend: Buffer[] = [];
const size = message.length.toString(16);
const sizePack = "00000000".substr(size.length) + size;
const packed = Buffer.concat([Buffer.from(sizePack, "hex"), message]);
while (offset < packed.length) {
// Use small buffer to be compatible with old and new protocol
const maxChunkSize =
offset === 0 ? CHUNK_SIZE - 1 - paths.length * 4 : CHUNK_SIZE;
const chunkSize =
offset + maxChunkSize > packed.length
? packed.length - offset
: maxChunkSize;
const buffer = Buffer.alloc(
offset === 0 ? 1 + paths.length * 4 + chunkSize : chunkSize
);
if (offset === 0) {
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
packed.copy(buffer, 1 + 4 * paths.length, offset, offset + chunkSize);
} else {
packed.copy(buffer, 0, offset, offset + chunkSize);
}
toSend.push(buffer);
offset += chunkSize;
}
let response;
return foreach(toSend, (data, i) => {
return this.transport
.send(CLA, SIGN_MESSAGE, i === 0 ? 0x00 : 0x80, 0x00, data)
.then((apduResponse) => {
response = apduResponse;
});
}).then(() => {
return response.slice(0, 65).toString("hex");
});
}
/**
* get Tron address for a given BIP 32 path.
* @param path a path in BIP 32 format
* @param publicKey address public key to generate pair key
* @return shared key hex string,
* @example
* const signature = await tron.getECDHPairKey("44'/195'/0'/0/0", "04ff21f8e64d3a3c0198edfbb7afdc79be959432e92e2f8a1984bb436a414b8edcec0345aad0c1bf7da04fd036dd7f9f617e30669224283d950fab9dd84831dc83");
*/
getECDHPairKey(path: string, publicKey: string): Promise<string> {
const paths = splitPath(path);
const data = Buffer.from(publicKey, "hex");
const buffer = Buffer.alloc(1 + paths.length * 4 + data.length);
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
data.copy(buffer, 1 + 4 * paths.length, 0, data.length);
return this.transport
.send(CLA, ECDH_SECRET, 0x00, 0x01, buffer)
.then((response) => response.slice(0, 65).toString("hex"));
}
} | the_stack |
import {CloudPrintInterfaceImpl, Destination, DestinationConnectionStatus, DestinationErrorType, DestinationOrigin, DestinationState, DestinationStoreEventType, DestinationType, Error, GooglePromotedDestinationId, LocalDestinationInfo, makeRecentDestination, NativeLayerImpl, NUM_PERSISTED_DESTINATIONS, PrintPreviewDestinationSettingsElement, RecentDestination, State} from 'chrome://print/print_preview.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, fakeDataBind, waitBeforeNextRender} from 'chrome://webui-test/test_util.js';
import {CloudPrintInterfaceStub} from './cloud_print_interface_stub.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {NativeLayerCrosStub, setNativeLayerCrosInstance} from './native_layer_cros_stub.js';
// </if>
import {NativeLayerStub} from './native_layer_stub.js';
import {getDestinations, getGoogleDriveDestination, getSaveAsPdfDestination, setupTestListenerElement} from './print_preview_test_utils.js';
const destination_settings_test = {
suiteName: 'DestinationSettingsTest',
TestNames: {
ChangeDropdownState: 'change dropdown state',
NoRecentDestinations: 'no recent destinations',
RecentDestinations: 'recent destinations',
RecentDestinationsMissing: 'recent destinations missing',
SaveAsPdfRecent: 'save as pdf recent',
GoogleDriveRecent: 'google drive recent',
GoogleDriveAutoselect: 'google drive autoselect',
SelectSaveAsPdf: 'select save as pdf',
SelectGoogleDrive: 'select google drive',
SelectRecentDestination: 'select recent destination',
OpenDialog: 'open dialog',
TwoAccountsRecentDestinations: 'two accounts recent destinations',
UpdateRecentDestinations: 'update recent destinations',
DisabledSaveAsPdf: 'disabled save as pdf',
NoDestinations: 'no destinations',
// <if expr="chromeos_ash or chromeos_lacros">
EulaIsRetrieved: 'eula is retrieved',
DriveIsNotMounted: 'drive is not mounted',
// </if>
},
};
Object.assign(window, {destination_settings_test: destination_settings_test});
suite(destination_settings_test.suiteName, function() {
let destinationSettings: PrintPreviewDestinationSettingsElement;
let nativeLayer: NativeLayerStub;
let cloudPrintInterface: CloudPrintInterfaceStub;
// <if expr="chromeos_ash or chromeos_lacros">
let nativeLayerCros: NativeLayerCrosStub;
// </if>
let recentDestinations: RecentDestination[] = [];
let localDestinations: LocalDestinationInfo[] = [];
let destinations: Destination[] = [];
const extraDestinations: Destination[] = [];
let pdfPrinterDisabled: boolean = false;
let isDriveMounted: boolean = true;
const defaultUser: string = 'foo@chromium.org';
const driveDestinationKey: string =
// <if expr="chromeos_ash or chromeos_lacros">
'Save to Drive CrOS/local/';
// </if>
// <if expr="not chromeos and not lacros">
'__google__docs/cookies/foo@chromium.org';
// </if>
suiteSetup(function() {
setupTestListenerElement();
});
setup(function() {
document.body.innerHTML = '';
// Stub out native layer and cloud print interface.
nativeLayer = new NativeLayerStub();
NativeLayerImpl.setInstance(nativeLayer);
// <if expr="chromeos_ash or chromeos_lacros">
nativeLayerCros = setNativeLayerCrosInstance();
// </if>
localDestinations = [];
destinations = getDestinations(localDestinations);
// Add some extra destinations.
for (let i = 0; i < NUM_PERSISTED_DESTINATIONS; i++) {
const id = `e${i}`;
const name = `n${i}`;
localDestinations.push({deviceName: id, printerName: name});
extraDestinations.push(new Destination(
id, DestinationType.LOCAL, getLocalOrigin(), name,
DestinationConnectionStatus.ONLINE));
}
nativeLayer.setLocalDestinations(localDestinations);
cloudPrintInterface = new CloudPrintInterfaceStub();
CloudPrintInterfaceImpl.setInstance(cloudPrintInterface);
cloudPrintInterface.configure();
const model = document.createElement('print-preview-model');
document.body.appendChild(model);
destinationSettings =
document.createElement('print-preview-destination-settings');
destinationSettings.settings = model.settings;
destinationSettings.state = State.NOT_READY;
destinationSettings.disabled = true;
fakeDataBind(model, destinationSettings, 'settings');
document.body.appendChild(destinationSettings);
});
// Tests that the dropdown is enabled or disabled correctly based on
// the state.
test(
assert(destination_settings_test.TestNames.ChangeDropdownState),
function() {
const dropdown = destinationSettings.$.destinationSelect;
// Initial state: No destination store means that there is no
// destination yet.
assertFalse(dropdown.loaded);
// Set up the destination store, but no destination yet. Dropdown is
// still not loaded.
destinationSettings.init(
'FooDevice' /* printerName */, false /* pdfPrinterDisabled */,
isDriveMounted,
'' /* serializedDefaultDestinationSelectionRulesStr */);
assertFalse(dropdown.loaded);
return eventToPromise(
DestinationStoreEventType
.SELECTED_DESTINATION_CAPABILITIES_READY,
destinationSettings.getDestinationStoreForTest())
.then(() => {
// The capabilities ready event results in |destinationState|
// changing to SELECTED, which enables and shows the dropdown even
// though |state| has not yet transitioned to READY. This is to
// prevent brief losses of focus when the destination changes.
assertFalse(dropdown.disabled);
assertTrue(dropdown.loaded);
destinationSettings.state = State.READY;
destinationSettings.disabled = false;
// Simulate setting a setting to an invalid value. Dropdown is
// disabled due to validation error on another control.
destinationSettings.state = State.ERROR;
destinationSettings.disabled = true;
assertTrue(dropdown.disabled);
// Simulate the user fixing the validation error, and then
// selecting an invalid printer. Dropdown is enabled, so that the
// user can fix the error.
destinationSettings.state = State.READY;
destinationSettings.disabled = false;
destinationSettings.getDestinationStoreForTest().dispatchEvent(
new CustomEvent(
DestinationStoreEventType.ERROR,
{detail: DestinationErrorType.INVALID}));
flush();
assertEquals(
DestinationState.ERROR, destinationSettings.destinationState);
assertEquals(Error.INVALID_PRINTER, destinationSettings.error);
destinationSettings.state = State.ERROR;
destinationSettings.disabled = true;
assertFalse(dropdown.disabled);
// Simulate the user having no printers.
destinationSettings.getDestinationStoreForTest().dispatchEvent(
new CustomEvent(
DestinationStoreEventType.ERROR,
{detail: DestinationErrorType.NO_DESTINATIONS}));
flush();
assertEquals(
DestinationState.ERROR, destinationSettings.destinationState);
assertEquals(Error.NO_DESTINATIONS, destinationSettings.error);
destinationSettings.state = State.FATAL_ERROR;
destinationSettings.disabled = true;
assertTrue(dropdown.disabled);
});
});
function getLocalOrigin(): DestinationOrigin {
// <if expr="chromeos_ash or chromeos_lacros">
return DestinationOrigin.CROS;
// </if>
// <if expr="not chromeos and not lacros">
return DestinationOrigin.LOCAL;
// </if>
}
function assertGoogleDrive() {
// <if expr="chromeos_ash or chromeos_lacros">
assertEquals(
GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS,
destinationSettings.destination.id);
// </if>
// <if expr="not chromeos and not lacros">
assertEquals(
GooglePromotedDestinationId.DOCS, destinationSettings.destination.id);
// </if>
}
/**
* Initializes the destination store and destination settings using
* |destinations| and |recentDestinations|.
*/
function initialize() {
// Initialize destination settings.
destinationSettings.setSetting('recentDestinations', recentDestinations);
destinationSettings.init(
'' /* printerName */, pdfPrinterDisabled, isDriveMounted,
'' /* serializedDefaultDestinationSelectionRulesStr */);
destinationSettings.state = State.READY;
destinationSettings.disabled = false;
}
/**
* @param id The id of the local destination.
* @return The key corresponding to the local destination, with the
* origin set correctly based on the platform.
*/
function makeLocalDestinationKey(id: string): string {
return id + '/' + getLocalOrigin() + '/';
}
/**
* @param expectedDestinations An array of the expected
* destinations in the dropdown.
*/
function assertDropdownItems(expectedDestinations: string[]) {
const options =
destinationSettings.$.destinationSelect.getVisibleItemsForTest();
assertEquals(expectedDestinations.length + 1, options.length);
expectedDestinations.forEach((expectedValue, index) => {
assertEquals(expectedValue, options[index]!.value);
});
assertEquals('seeMore', options[expectedDestinations.length]!.value);
}
// Tests that the dropdown contains the appropriate destinations when there
// are no recent destinations.
test(
assert(destination_settings_test.TestNames.NoRecentDestinations),
function() {
initialize();
return nativeLayer.whenCalled('getPrinterCapabilities').then(() => {
// This will result in the destination store setting the Save as
// PDF destination.
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationSettings.destination.id);
assertFalse(destinationSettings.$.destinationSelect.disabled);
const dropdownItems = [
'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
});
});
// Tests that the dropdown contains the appropriate destinations when there
// are 5 recent destinations.
test(
assert(destination_settings_test.TestNames.RecentDestinations),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
// Wait for the destinations to be inserted into the store.
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(destinationSettings.$.destinationSelect.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID2'),
makeLocalDestinationKey('ID3'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
});
});
// Tests that the dropdown contains the appropriate destinations when one of
// the destinations can no longer be found.
test(
assert(destination_settings_test.TestNames.RecentDestinationsMissing),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
localDestinations.splice(1, 1);
nativeLayer.setLocalDestinations(localDestinations);
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
// Wait for the destinations to be inserted into the store.
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(destinationSettings.$.destinationSelect.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID3'),
'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
});
});
// Tests that the dropdown contains the appropriate destinations when Save
// as PDF is one of the recent destinations.
test(assert(destination_settings_test.TestNames.SaveAsPdfRecent), function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
recentDestinations.splice(
1, 1, makeRecentDestination(getSaveAsPdfDestination()));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most recent
// destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(destinationSettings.$.destinationSelect.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID3'),
makeLocalDestinationKey('ID4'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
});
});
// Tests that the dropdown contains the appropriate destinations when
// Google Drive is in the recent destinations.
test(
assert(destination_settings_test.TestNames.GoogleDriveRecent),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
recentDestinations.splice(
1, 1,
makeRecentDestination(getGoogleDriveDestination(defaultUser)));
cloudPrintInterface.setPrinter(getGoogleDriveDestination(defaultUser));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(destinationSettings.$.destinationSelect.disabled);
// <if expr="chromeos_ash or chromeos_lacros">
const dropdownItems = [
makeLocalDestinationKey('ID1'),
makeLocalDestinationKey('ID3'),
makeLocalDestinationKey('ID4'),
'Save as PDF/local/',
driveDestinationKey,
];
// </if>
// <if expr="not chromeos and not lacros">
const dropdownItems = [
makeLocalDestinationKey('ID1'),
driveDestinationKey,
makeLocalDestinationKey('ID3'),
'Save as PDF/local/',
];
// </if>
assertDropdownItems(dropdownItems);
});
});
// Tests that the dropdown contains the appropriate destinations and loads
// correctly when Google Drive is the most recent destination. Regression test
// for https://crbug.com/1038645.
test(
assert(destination_settings_test.TestNames.GoogleDriveAutoselect),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
recentDestinations.splice(
0, 1,
makeRecentDestination(getGoogleDriveDestination(defaultUser)));
const whenSelected = eventToPromise(
DestinationStoreEventType.DESTINATION_SELECT,
destinationSettings.getDestinationStoreForTest());
cloudPrintInterface.setPrinter(getGoogleDriveDestination(defaultUser));
initialize();
return whenSelected
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertGoogleDrive();
assertFalse(destinationSettings.$.destinationSelect.disabled);
// <if expr="chromeos_ash or chromeos_lacros">
const dropdownItems = [
makeLocalDestinationKey('ID2'),
makeLocalDestinationKey('ID3'),
makeLocalDestinationKey('ID4'),
'Save as PDF/local/',
driveDestinationKey,
];
// </if>
// <if expr="not chromeos and not lacros">
const dropdownItems = [
driveDestinationKey,
makeLocalDestinationKey('ID2'),
makeLocalDestinationKey('ID3'),
'Save as PDF/local/',
];
// </if>
assertDropdownItems(dropdownItems);
});
});
// Tests that selecting the Save as PDF destination results in the
// DESTINATION_SELECT event firing, with Save as PDF set as the current
// destination.
test(assert(destination_settings_test.TestNames.SelectSaveAsPdf), function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
recentDestinations.splice(
1, 1, makeRecentDestination(getSaveAsPdfDestination()));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
const dropdown = destinationSettings.$.destinationSelect;
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most recent
// destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(dropdown.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID3'),
makeLocalDestinationKey('ID4'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
// Most recent destination is selected by default.
assertEquals('ID1', destinationSettings.destination.id);
// Simulate selection of Save as PDF printer.
const whenDestinationSelect = eventToPromise(
DestinationStoreEventType.DESTINATION_SELECT,
destinationSettings.getDestinationStoreForTest());
dropdown.dispatchEvent(new CustomEvent(
'selected-option-change',
{bubbles: true, composed: true, detail: 'Save as PDF/local/'}));
// Ensure this fires the destination select event.
return whenDestinationSelect;
})
.then(() => {
assertEquals(
GooglePromotedDestinationId.SAVE_AS_PDF,
destinationSettings.destination.id);
});
});
// Tests that selecting the Google Drive destination results in the
// DESTINATION_SELECT event firing, with Google Drive set as the current
// destination.
test(
assert(destination_settings_test.TestNames.SelectGoogleDrive),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
recentDestinations.splice(
1, 1,
makeRecentDestination(getGoogleDriveDestination(defaultUser)));
cloudPrintInterface.setPrinter(getGoogleDriveDestination(defaultUser));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
const dropdown = destinationSettings.$.destinationSelect;
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('ID1', destinationSettings.destination.id);
// <if expr="chromeos_ash or chromeos_lacros">
const dropdownItems = [
makeLocalDestinationKey('ID1'),
makeLocalDestinationKey('ID3'),
makeLocalDestinationKey('ID4'),
'Save as PDF/local/',
driveDestinationKey,
];
// </if>
// <if expr="not chromeos and not lacros">
const dropdownItems = [
makeLocalDestinationKey('ID1'),
driveDestinationKey,
makeLocalDestinationKey('ID3'),
'Save as PDF/local/',
];
// </if>
assertDropdownItems(dropdownItems);
assertFalse(dropdown.disabled);
// Simulate selection of Google Drive printer.
const whenDestinationSelect = eventToPromise(
DestinationStoreEventType.DESTINATION_SELECT,
destinationSettings.getDestinationStoreForTest());
dropdown.dispatchEvent(new CustomEvent('selected-option-change', {
bubbles: true,
composed: true,
detail: driveDestinationKey,
}));
return whenDestinationSelect;
})
.then(() => {
assertGoogleDrive();
});
});
// Tests that selecting a recent destination results in the
// DESTINATION_SELECT event firing, with the recent destination set as the
// current destination.
test(
assert(destination_settings_test.TestNames.SelectRecentDestination),
function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
const dropdown = destinationSettings.$.destinationSelect;
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(dropdown.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID2'),
makeLocalDestinationKey('ID3'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
// Simulate selection of Save as PDF printer.
const whenDestinationSelect = eventToPromise(
DestinationStoreEventType.DESTINATION_SELECT,
destinationSettings.getDestinationStoreForTest());
dropdown.dispatchEvent(new CustomEvent('selected-option-change', {
bubbles: true,
composed: true,
detail: makeLocalDestinationKey('ID2'),
}));
return whenDestinationSelect;
})
.then(() => {
assertEquals('ID2', destinationSettings.destination.id);
});
});
// Tests that selecting the 'see more' option opens the dialog.
test(assert(destination_settings_test.TestNames.OpenDialog), function() {
recentDestinations = destinations.slice(0, 5).map(
destination => makeRecentDestination(destination));
const whenCapabilitiesDone =
nativeLayer.whenCalled('getPrinterCapabilities');
initialize();
const dropdown = destinationSettings.$.destinationSelect;
return whenCapabilitiesDone
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most recent
// destination.
assertEquals('ID1', destinationSettings.destination.id);
assertFalse(dropdown.disabled);
const dropdownItems = [
makeLocalDestinationKey('ID1'), makeLocalDestinationKey('ID2'),
makeLocalDestinationKey('ID3'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
dropdown.dispatchEvent(new CustomEvent(
'selected-option-change',
{bubbles: true, composed: true, detail: 'seeMore'}));
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
assertTrue(destinationSettings.$.destinationDialog.get().isOpen());
});
});
test(
assert(destination_settings_test.TestNames.TwoAccountsRecentDestinations),
function() {
const account2 = 'bar@chromium.org';
const cloudPrinterUser1 = new Destination(
'FooCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'FooCloudName', DestinationConnectionStatus.ONLINE,
{account: defaultUser});
const cloudPrinterUser2 = new Destination(
'BarCloud', DestinationType.GOOGLE, DestinationOrigin.COOKIES,
'BarCloudName', DestinationConnectionStatus.ONLINE,
{account: account2});
// <if expr="not chromeos and not lacros">
cloudPrintInterface.setPrinter(getGoogleDriveDestination(defaultUser));
const driveUser2 = getGoogleDriveDestination(account2);
cloudPrintInterface.setPrinter(driveUser2);
// </if>
cloudPrintInterface.setPrinter(cloudPrinterUser1);
cloudPrintInterface.setPrinter(cloudPrinterUser2);
recentDestinations =
[cloudPrinterUser1, cloudPrinterUser2, destinations[0]!
].map(destination => makeRecentDestination(destination));
const whenPrinter = cloudPrintInterface.whenCalled('printer');
initialize();
flush();
const dropdown = destinationSettings.$.destinationSelect;
return whenPrinter
.then(() => {
// Wait for the drive destination to be displayed.
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// This will result in the destination store setting the most
// recent destination.
assertEquals('FooCloud', destinationSettings.destination.id);
assertFalse(dropdown.disabled);
const dropdownItems = [
'FooCloud/cookies/foo@chromium.org',
makeLocalDestinationKey('ID1'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
dropdown.dispatchEvent(new CustomEvent(
'selected-option-change',
{bubbles: true, composed: true, detail: 'seeMore'}));
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
const dialog = destinationSettings.$.destinationDialog.get();
assertTrue(dialog.isOpen());
const whenAdded = eventToPromise(
DestinationStoreEventType.DESTINATIONS_INSERTED,
destinationSettings.getDestinationStoreForTest());
// Simulate setting a new account.
dialog.dispatchEvent(new CustomEvent(
'account-change',
{bubbles: true, composed: true, detail: account2}));
flush();
return whenAdded;
})
.then(() => {
const dropdownItems = [
'BarCloud/cookies/bar@chromium.org',
makeLocalDestinationKey('ID1'), 'Save as PDF/local/',
// <if expr="chromeos_ash or chromeos_lacros">
driveDestinationKey,
// </if>
];
assertDropdownItems(dropdownItems);
});
});
/**
* @param expectedDestinationIds An array of the expected
* recent destination ids.
*/
function assertRecentDestinations(expectedDestinationIds: string[]) {
const recentDestinations =
destinationSettings.getSettingValue('recentDestinations');
assertEquals(expectedDestinationIds.length, recentDestinations.length);
expectedDestinationIds.forEach((expectedId, index) => {
assertEquals(expectedId, recentDestinations[index].id);
});
}
function selectDestination(destination: Destination) {
const storeDestination =
destinationSettings.getDestinationStoreForTest().destinations().find(
d => d.key === destination.key);
destinationSettings.getDestinationStoreForTest().selectDestination(
assert(storeDestination!));
flush();
}
/**
* Tests that the destination being set correctly updates the recent
* destinations array.
*/
test(
assert(destination_settings_test.TestNames.UpdateRecentDestinations),
function() {
// Recent destinations start out empty.
assertRecentDestinations([]);
assertEquals(0, nativeLayer.getCallCount('getPrinterCapabilities'));
initialize();
return nativeLayer.whenCalled('getPrinterCapabilities')
.then(() => {
assertRecentDestinations(['Save as PDF']);
assertEquals(
1, nativeLayer.getCallCount('getPrinterCapabilities'));
// Add printers to store.
nativeLayer.resetResolver('getPrinterCapabilities');
destinationSettings.getDestinationStoreForTest()
.startLoadAllDestinations();
return nativeLayer.whenCalled('getPrinters');
})
.then(() => {
// Simulate setting a destination from the dialog.
selectDestination(destinations[0]!);
return nativeLayer.whenCalled('getPrinterCapabilities');
})
.then(() => {
assertRecentDestinations(['ID1', 'Save as PDF']);
assertEquals(
1, nativeLayer.getCallCount('getPrinterCapabilities'));
// Reselect a recent destination. Still 2 destinations, but in a
// different order.
nativeLayer.resetResolver('getPrinterCapabilities');
destinationSettings.$.destinationSelect.dispatchEvent(
new CustomEvent('selected-option-change', {
bubbles: true,
composed: true,
detail: 'Save as PDF/local/',
}));
flush();
assertRecentDestinations(['Save as PDF', 'ID1']);
// No additional capabilities call, since the destination was
// previously selected.
assertEquals(
0, nativeLayer.getCallCount('getPrinterCapabilities'));
// Select a third destination.
selectDestination(destinations[1]!);
return nativeLayer.whenCalled('getPrinterCapabilities');
})
.then(() => {
assertRecentDestinations(['ID2', 'Save as PDF', 'ID1']);
assertEquals(
1, nativeLayer.getCallCount('getPrinterCapabilities'));
nativeLayer.resetResolver('getPrinterCapabilities');
// Fill recent destinations up to the cap, then add a couple
// more destinations. Make sure the length of the list does not
// exceed NUM_PERSISTED_DESTINATIONS.
const whenCapabilitiesDone =
nativeLayer.waitForMultipleCapabilities(
NUM_PERSISTED_DESTINATIONS);
for (const destination of extraDestinations) {
selectDestination(destination);
}
return whenCapabilitiesDone;
})
.then(() => {
assertRecentDestinations(
extraDestinations.map(dest => dest.id).reverse());
assertEquals(
NUM_PERSISTED_DESTINATIONS,
nativeLayer.getCallCount('getPrinterCapabilities'));
});
});
// Tests that disabling the Save as PDF destination hides the corresponding
// dropdown item.
test(
assert(destination_settings_test.TestNames.DisabledSaveAsPdf),
function() {
// Initialize destination settings with the PDF printer disabled.
pdfPrinterDisabled = true;
initialize();
return nativeLayer.whenCalled('getPrinterCapabilities')
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
// Because the 'Save as PDF' fallback is unavailable, the first
// destination is selected.
const expectedDestination =
// <if expr="chromeos_ash or chromeos_lacros">
'Save to Drive CrOS/local/';
// </if>
// <if expr="not chromeos and not lacros">
makeLocalDestinationKey('ID1');
// </if>
assertDropdownItems([expectedDestination]);
});
});
// Tests that disabling the 'Save as PDF' destination and exposing no
// printers to the native layer results in a 'No destinations' option in the
// dropdown.
test(assert(destination_settings_test.TestNames.NoDestinations), function() {
nativeLayer.setLocalDestinations([]);
// Initialize destination settings with the PDF printer disabled.
pdfPrinterDisabled = true;
isDriveMounted = false;
initialize();
// 'getPrinters' will be called because there are no printers known to
// the destination store and the 'Save as PDF' fallback is
// unavailable.
return Promise
.all([
nativeLayer.whenCalled('getPrinters'),
// TODO (rbpotter): remove this wait once user manager is fully
// removed.
waitBeforeNextRender(destinationSettings),
])
.then(() => assertDropdownItems(['noDestinations']));
});
// <if expr="chromeos_ash or chromeos_lacros">
/**
* Tests that destinations with a EULA will fetch the EULA URL when
* selected.
*/
test(assert(destination_settings_test.TestNames.EulaIsRetrieved), function() {
// Recent destinations start out empty.
assertRecentDestinations([]);
const expectedUrl = 'chrome://os-credits/eula';
assertEquals(0, nativeLayerCros.getCallCount('getEulaUrl'));
initialize();
return nativeLayerCros.whenCalled('getEulaUrl')
.then(() => {
assertEquals(1, nativeLayerCros.getCallCount('getEulaUrl'));
nativeLayerCros.resetResolver('getEulaUrl');
// Add printers to the store.
destinationSettings.getDestinationStoreForTest()
.startLoadAllDestinations();
return nativeLayer.whenCalled('getPrinters');
})
.then(() => {
nativeLayerCros.setEulaUrl('chrome://os-credits/eula');
// Simulate selecting a destination that has a EULA URL from the
// dialog.
selectDestination(destinations[0]!);
return nativeLayerCros.whenCalled('getEulaUrl');
})
.then(() => {
assertEquals(1, nativeLayerCros.getCallCount('getEulaUrl'));
nativeLayerCros.resetResolver('getEulaUrl');
assertEquals(expectedUrl, destinationSettings.destination.eulaUrl);
nativeLayerCros.setEulaUrl('');
// Select a destination without a EULA URL.
selectDestination(destinations[1]!);
return nativeLayerCros.whenCalled('getEulaUrl');
})
.then(() => {
assertEquals(1, nativeLayerCros.getCallCount('getEulaUrl'));
nativeLayerCros.resetResolver('getEulaUrl');
assertEquals('', destinationSettings.destination.eulaUrl);
// Reselect a destination with a EULA URL. This destination
// already had its EULA URL set, so expect that it still retains
// it. Since capabilities for this destination are already set,
// we don't try to fetch the license again.
nativeLayer.resetResolver('getPrinterCapabilities');
destinationSettings.$.destinationSelect.dispatchEvent(
new CustomEvent('selected-option-change', {
bubbles: true,
composed: true,
detail: 'ID1/chrome_os/',
}));
})
.then(() => {
assertEquals(0, nativeLayer.getCallCount('getPrinterCapabilities'));
assertEquals(0, nativeLayerCros.getCallCount('getEulaUrl'));
assertRecentDestinations(['ID1', 'ID2', 'Save as PDF']);
assertEquals(expectedUrl, destinationSettings.destination.eulaUrl);
});
});
// Tests that disabling Google Drive on Chrome OS hides the Save to Drive
// destination.
test(
assert(destination_settings_test.TestNames.DriveIsNotMounted),
function() {
isDriveMounted = false;
initialize();
return nativeLayer.whenCalled('getPrinterCapabilities')
.then(() => {
return waitBeforeNextRender(destinationSettings);
})
.then(() => {
const options = destinationSettings.$.destinationSelect
.getVisibleItemsForTest();
assertEquals(2, options.length);
assertEquals('Save as PDF/local/', options[0]!.value);
});
});
// </if>
}); | the_stack |
import {
BoxGeometry,
DoubleSide,
Mesh,
MeshBasicMaterial,
PlaneBufferGeometry,
Line,
BufferGeometry,
Vector3,
} from 'three';
import { Pane } from 'tweakpane';
// import { AxesHelper, GridHelper, Vector3 } from 'three';
import { Coords3 } from '../libs/types';
import { Helper } from '../utils';
import { Engine } from '.';
type FormatterType = (input: any) => string;
class Debug {
public gui: Pane;
public dataWrapper: HTMLDivElement;
public audioWrapper: HTMLDivElement;
public dataEntries: {
ele: HTMLParagraphElement;
obj: any;
attribute: string;
name: string;
formatter: FormatterType;
}[] = [];
public chunkHighlight: Mesh;
public atlasTest: Mesh;
public inputOptions = {
changeRadius: 3,
minChangeRadius: 1,
maxChangeRadius: 6,
};
public highlights = new Line(
new BufferGeometry(),
new MeshBasicMaterial({
color: 'yellow',
}),
);
public biome = 'Unkonwn';
public savedSettings: { [key: string]: any } = {};
constructor(public engine: Engine) {
// dat.gui
this.gui = new Pane();
const {
world: { chunkSize, dimension, maxHeight },
} = engine.config;
const width = chunkSize * dimension;
this.chunkHighlight = new Mesh(
new BoxGeometry(width, maxHeight * dimension, width),
new MeshBasicMaterial({ wireframe: true, side: DoubleSide }),
);
// move dat.gui panel to the top
const parentElement = this.gui.element;
if (parentElement) {
parentElement.parentNode.removeChild(parentElement);
}
engine.on('ready', () => {
this.chunkHighlight.visible = false;
this.highlights.frustumCulled = false;
engine.rendering.scene.add(this.chunkHighlight);
engine.rendering.scene.add(this.highlights);
engine.inputs.bind('j', this.toggle, '*');
});
engine.on('assets-loaded', () => {
this.makeDOM();
this.setupAll();
this.setupInputs();
this.mount();
// textureTest
const testBlock = new PlaneBufferGeometry(4, 4);
const testMat = new MeshBasicMaterial({
map: this.engine.registry.atlasUniform.value,
side: DoubleSide,
transparent: true,
depthTest: false,
alphaTest: 0.5,
});
this.atlasTest = new Mesh(testBlock, testMat);
this.atlasTest.position.set(0, 0, -5);
this.atlasTest.visible = false;
this.atlasTest.renderOrder = 10000000000;
this.engine.camera.threeCamera.add(this.atlasTest);
});
}
makeDataEntry = (newline = false) => {
const dataEntry = document.createElement('p');
Helper.applyStyle(dataEntry, {
fontSize: '13.3333px',
margin: '0',
...(newline ? { height: '16px' } : {}),
});
return dataEntry;
};
makeDOM = () => {
this.dataWrapper = document.createElement('div');
this.dataWrapper.id = 'data-wrapper';
Helper.applyStyle(this.dataWrapper, {
position: 'fixed',
top: '10px',
left: '10px',
color: '#eee',
background: '#00000022',
padding: '4px',
display: 'flex',
flexDirection: 'column-reverse',
alignItems: 'flex-start',
justifyContent: 'flex-start',
});
Helper.applyStyle(this.gui.element, {
position: 'fixed',
top: '10px',
right: '10px',
zIndex: '1000000000000',
});
this.audioWrapper = document.createElement('div');
this.audioWrapper.id = 'audio-wrapper';
Helper.applyStyle(this.audioWrapper, {
position: 'fixed',
right: '0',
bottom: '20px',
background: '#2C2E43',
color: '#EEEEEE',
content: '0',
});
};
mount = () => {
const { domElement } = this.engine.container;
domElement.appendChild(this.dataWrapper);
domElement.appendChild(this.audioWrapper);
domElement.appendChild(this.gui.element);
};
setupAll = () => {
// RENDERING
const { registry, player, world, camera, rendering, sounds } = this.engine;
/* -------------------------------------------------------------------------- */
/* TEMPORARY OPTIONS */
/* -------------------------------------------------------------------------- */
const sessionFolder = this.gui.addFolder({ title: 'Session (Temporary)', expanded: false });
// ENGINE
const engineFolder = sessionFolder.addFolder({ title: 'Engine', expanded: false });
engineFolder
.addInput(this.engine, 'tickSpeed', {
min: 0,
max: 100,
step: 0.01,
label: 'tick speed',
})
.on('change', (ev) => this.engine.setTick(ev.value));
const worldFolder = sessionFolder.addFolder({ title: 'World', expanded: false });
const worldDebugConfigs = { time: world.sky.tracker.time };
worldFolder
.addInput(world.options, 'renderRadius', {
min: 1,
max: 20,
step: 1,
label: 'render radius',
})
.on('change', (ev) => {
world.updateRenderRadius(ev.value);
});
worldFolder.addInput(world.options, 'requestRadius', {
min: 1,
max: 20,
step: 1,
label: 'request radius',
});
worldFolder
.addInput(worldDebugConfigs, 'time', { min: 0, max: 2400, step: 10, label: 'time value' })
.on('change', (ev) => world.setTime(ev.value));
const aoFolder = worldFolder.addFolder({ title: 'AO' });
aoFolder.addInput(registry.aoUniform, 'value', {
x: { min: 0, max: 255, step: 1 },
y: { min: 0, max: 255, step: 1 },
z: { min: 0, max: 255, step: 1 },
w: { min: 0, max: 255, step: 1 },
});
// PLAYER
const playerFolder = sessionFolder.addFolder({ title: 'Player', expanded: false });
playerFolder.addInput(player.options, 'acceleration', {
min: 0,
max: 5,
step: 0.01,
label: 'acceleration',
});
playerFolder.addInput(player.options, 'flyingInertia', { min: 0, max: 5, step: 0.01, label: 'flying inertia' });
// const cameraFolder = this.gui.addFolder('camera');
this.displayTitle('MineJS beta-0.1.0');
this.registerDisplay('', this, 'fps');
this.displayNewline();
this.registerDisplay('Mem', this, 'memoryUsage');
this.registerDisplay('Time', world.sky.tracker, 'time', (num) => num.toFixed(0));
this.registerDisplay('Biome', this, 'biome');
this.registerDisplay('Scene object', rendering.scene.children, 'length');
this.displayNewline();
this.registerDisplay('XYZ', player, 'voxelPositionStr');
this.registerDisplay('Block', player, 'lookBlockStr');
this.registerDisplay('Chunk', world, 'camChunkPosStr');
this.registerDisplay('Chunks loaded', world, 'chunksLoaded');
this.displayNewline();
this.displayTitle('/help for a tutorial');
// REGISTRY
const registryFolder = sessionFolder.addFolder({ title: 'Registry', expanded: false });
registryFolder.addButton({ title: 'Toggle', label: 'atlas' }).on('click', () => {
this.atlasTest.visible = !this.atlasTest.visible;
});
registryFolder.addButton({ title: 'Toggle', label: 'wireframe' }).on('click', () => {
registry.opaqueChunkMaterial.wireframe = !registry.opaqueChunkMaterial.wireframe;
registry.transparentChunkMaterials.forEach((m) => (m.wireframe = !m.wireframe));
});
// DEBUG
const debugFolder = sessionFolder.addFolder({ title: 'Debug', expanded: false });
debugFolder.addButton({ title: 'Toggle', label: 'chunk highlight' }).on('click', () => {
this.chunkHighlight.visible = !this.chunkHighlight.visible;
});
/* -------------------------------------------------------------------------- */
/* SAVED OPTIONS */
/* -------------------------------------------------------------------------- */
const { config } = this.engine;
const packs = this.engine.registry.options.packs;
const packsObject = {};
packs.forEach((p) => (packsObject[p] = p));
const saved = this.gui.addFolder({ title: 'Local (Saved)', expanded: true });
const savedPlayerFolder = saved.addFolder({ title: 'Player', expanded: true });
const sensitivitySaver = this.registerSaver(
'sensitivity',
config.player.sensitivity,
(val) => (player.controls.sensitivity = val),
);
savedPlayerFolder.addInput(this.savedSettings, 'sensitivity', { min: 10, max: 150, step: 1 }).on('change', (ev) => {
sensitivitySaver(ev.value);
});
const fovSaver = this.registerSaver('fov', config.camera.fov, (val) => camera.setFOV(val));
savedPlayerFolder
.addInput(this.savedSettings, 'fov', {
min: 40,
max: 120,
step: 1,
label: 'FOV',
})
.on('change', (ev) => fovSaver(ev.value));
const soundSaver = this.registerSaver('mute', false, (val) => camera.audioListener.setMasterVolume(val ? 0 : 1));
savedPlayerFolder.addInput(this.savedSettings, 'mute').on('change', (ev) => soundSaver(ev.value));
const savedRegistryFolder = saved.addFolder({ title: 'Registry', expanded: true });
const texturePackSaver = this.registerSaver('texturePack', this.engine.registry.texturePack, (val) => {
registry.setTexturePack(val);
});
savedRegistryFolder
.addInput(this.savedSettings, 'texturePack', {
options: packsObject,
label: 'texture pack',
})
.on('change', (ev) => {
texturePackSaver(ev.value);
});
/* -------------------------------------------------------------------------- */
/* SOUNDS DISPLAY */
/* -------------------------------------------------------------------------- */
const createAudioNode = (name) => {
const node = document.createElement('div');
Helper.applyStyle(node, {
padding: '5px 20px',
textAlign: 'center',
});
node.innerHTML = name;
return node;
};
const playing = new Map();
sounds.on('started', (name) => {
if (playing.has(name)) return;
const node = createAudioNode(name);
this.audioWrapper.appendChild(node);
playing.set(name, node);
});
sounds.on('stopped', (name) => {
const node = playing.get(name);
if (node) {
this.audioWrapper.removeChild(node);
playing.delete(name);
}
});
};
setupInputs = () => {
const { inputs, player, inventory, world, camera } = this.engine;
const bulkPlace = (type?: number) => {
return () => {
const updates = [];
const t = type === undefined ? inventory.hand : 0;
const r = this.inputOptions.changeRadius;
if (!player.targetBlock) return;
const {
voxel: [vx, vy, vz],
rotation,
yRotation,
} = player.targetBlock;
for (let x = -r; x <= r; x++) {
for (let y = -r; y <= r; y++) {
for (let z = -r; z <= r; z++) {
if (x ** 2 + y ** 2 + z ** 2 > r * r) continue;
if (world.getVoxelByVoxel([vx + x, vy + y, vz + z]) === t) continue;
updates.push({ target: { voxel: [vx + x, vy + y, vz + z], rotation, yRotation }, type: t });
}
}
}
world.setManyVoxels(updates);
};
};
inputs.bind('x', bulkPlace(0), 'in-game');
inputs.bind('z', bulkPlace(), 'in-game');
inputs.bind(
'=',
() =>
(this.inputOptions.changeRadius = Math.max(
Math.min(this.inputOptions.changeRadius + 1, this.inputOptions.maxChangeRadius),
this.inputOptions.minChangeRadius,
)),
'in-game',
);
inputs.bind(
'-',
() =>
(this.inputOptions.changeRadius = Math.max(
Math.min(--this.inputOptions.changeRadius - 1, this.inputOptions.maxChangeRadius),
this.inputOptions.minChangeRadius,
)),
'in-game',
);
inputs.bind(
'v',
() => {
camera.setZoom(3);
},
'in-game',
{
occasion: 'keydown',
},
);
inputs.bind(
'v',
() => {
camera.setZoom(1);
},
'in-game',
{
occasion: 'keyup',
},
);
};
tick = () => {
for (const { ele, name, attribute, obj, formatter } of this.dataEntries) {
const newValue = obj[attribute];
ele.innerHTML = `${name ? `${name}: ` : ''}${formatter(newValue)}`;
}
if (this.chunkHighlight.visible) {
const { camChunkPosStr } = this.engine.world;
const [cx, cz] = Helper.parseChunkName(camChunkPosStr, ' ');
const { chunkSize, maxHeight, dimension } = this.engine.world.options;
this.chunkHighlight.position.set(
(cx + 0.5) * chunkSize * dimension,
0.5 * maxHeight * dimension,
(cz + 0.5) * chunkSize * dimension,
);
}
};
addHighlights = (points: Coords3[]) => {
const vectors = [];
const dimension = this.engine.config.world.dimension;
points.forEach(([x, y, z]) =>
vectors.push(new Vector3((x + 0.5) * dimension, (y + 0.5) * dimension, (z + 0.5) * dimension)),
);
this.highlights.geometry.setFromPoints(vectors);
};
toggle = () => {
const display = this.dataWrapper.style.display;
const newDisplay = display === 'none' ? 'inline' : 'none';
this.dataWrapper.style.display = newDisplay;
this.gui.element.style.display = newDisplay;
this.audioWrapper.style.display = newDisplay;
};
registerSaver = (name: string, value: any, func?: (value: any) => void) => {
const key = `mine.js-debug-${name}`;
const local = localStorage.getItem(key);
const stored = typeof value === 'number' ? +local : typeof value === 'boolean' ? local === 'true' : local;
const actualValue = stored || value;
this.savedSettings[name] = actualValue;
const saver = (newValue: any) => {
if (func) func(newValue);
this.savedSettings[name] = newValue;
localStorage.setItem(key, newValue);
};
saver(actualValue);
return saver;
};
registerDisplay = (name: string, object?: any, attribute?: string, formatter: FormatterType = (str) => str) => {
const wrapper = this.makeDataEntry();
const newEntry = {
ele: wrapper,
obj: object,
name,
formatter,
attribute,
};
this.dataEntries.push(newEntry);
this.dataWrapper.insertBefore(wrapper, this.dataWrapper.firstChild);
};
displayTitle = (title: string) => {
const newline = this.makeDataEntry(true);
newline.innerHTML = title;
this.dataWrapper.insertBefore(newline, this.dataWrapper.firstChild);
};
displayNewline = () => {
const newline = this.makeDataEntry(true);
this.dataWrapper.insertBefore(newline, this.dataWrapper.firstChild);
};
calculateFPS = (function () {
const sampleSize = 60;
let value = 0;
const sample = [];
let index = 0;
let lastTick = 0;
let min: number;
let max: number;
return function () {
// if is first tick, just set tick timestamp and return
if (!lastTick) {
lastTick = performance.now();
return 0;
}
// calculate necessary values to obtain current tick FPS
const now = performance.now();
const delta = (now - lastTick) / 1000;
const fps = 1 / delta;
// add to fps samples, current tick fps value
sample[index] = Math.round(fps);
// iterate samples to obtain the average
let average = 0;
for (let i = 0; i < sample.length; i++) average += sample[i];
average = Math.round(average / sample.length);
// set new FPS
value = average;
// store current timestamp
lastTick = now;
// increase sample index counter, and reset it
// to 0 if exceded maximum sampleSize limit
index++;
if (index === sampleSize) index = 0;
if (!min || min > value) min = value;
if (!max || max < value) max = value;
return `${value} fps (${min}, ${max})`;
};
})();
get fps() {
return this.calculateFPS();
}
get memoryUsage() {
// @ts-ignore
const info = window.performance.memory;
if (!info) return 'unknown';
const { usedJSHeapSize, jsHeapSizeLimit } = info;
return `${Helper.round(usedJSHeapSize / jsHeapSizeLimit, 2)}%`;
}
}
export { Debug }; | the_stack |
* Bitbucket API
* Code against the Bitbucket API to automate simple tasks, embed Bitbucket data into your own site, build mobile or desktop apps, or even add custom UI add-ons into Bitbucket itself using the Connect framework.
*
* The version of the OpenAPI document: 2.0
* Contact: support@bitbucket.org
*
* NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/** @public */
export namespace Models {
/**
* An account object.
* @public
*/
export interface Account extends ModelObject {
/**
* The status of the account. Currently the only possible value is "active", but more values may be added in the future.
*/
account_status?: string;
created_on?: string;
display_name?: string;
has_2fa_enabled?: boolean;
links?: AccountLinks;
/**
* Account name defined by the owner. Should be used instead of the "username" field. Note that "nickname" cannot be used in place of "username" in URLs and queries, as "nickname" is not guaranteed to be unique.
*/
nickname?: string;
username?: string;
uuid?: string;
website?: string;
}
/**
* @public
*/
export interface AccountLinks {
avatar?: Link;
followers?: Link;
following?: Link;
html?: Link;
repositories?: Link;
self?: Link;
}
/**
* The author of a change in a repository
* @public
*/
export interface Author extends ModelObject {
/**
* The raw author value from the repository. This may be the only value available if the author does not match a user in Bitbucket.
*/
raw?: string;
user?: Account;
}
/**
* The common base type for both repository and snippet commits.
* @public
*/
export interface BaseCommit extends ModelObject {
author?: Author;
date?: string;
hash?: string;
message?: string;
parents?: Array<BaseCommit>;
summary?: BaseCommitSummary;
}
/**
* @public
*/
export interface BaseCommitSummary {
/**
* The user's content rendered as HTML.
*/
html?: string;
/**
* The type of markup language the raw content is to be interpreted in.
*/
markup?: BaseCommitSummaryMarkupEnum;
/**
* The text as it was typed by a user.
*/
raw?: string;
}
/**
* The type of markup language the raw content is to be interpreted in.
* @public
*/
export const BaseCommitSummaryMarkupEnum = {
Markdown: 'markdown',
Creole: 'creole',
Plaintext: 'plaintext',
} as const;
/**
* The type of markup language the raw content is to be interpreted in.
* @public
*/
export type BaseCommitSummaryMarkupEnum =
typeof BaseCommitSummaryMarkupEnum[keyof typeof BaseCommitSummaryMarkupEnum];
/**
* A branch object, representing a branch in a repository.
* @public
*/
export interface Branch {
links?: RefLinks;
/**
* The name of the ref.
*/
name?: string;
target?: Commit;
type: string;
/**
* The default merge strategy for pull requests targeting this branch.
*/
default_merge_strategy?: string;
/**
* Available merge strategies for pull requests targeting this branch.
*/
merge_strategies?: Array<BranchMergeStrategiesEnum>;
}
/**
* Available merge strategies for pull requests targeting this branch.
* @public
*/
export const BranchMergeStrategiesEnum = {
MergeCommit: 'merge_commit',
Squash: 'squash',
FastForward: 'fast_forward',
} as const;
/**
* Available merge strategies for pull requests targeting this branch.
* @public
*/
export type BranchMergeStrategiesEnum =
typeof BranchMergeStrategiesEnum[keyof typeof BranchMergeStrategiesEnum];
/**
* A repository commit object.
* @public
*/
export interface Commit extends BaseCommit {
participants?: Array<Participant>;
repository?: Repository;
}
/**
* A file object, representing a file at a commit in a repository
* @public
*/
export interface CommitFile {
[key: string]: unknown;
attributes?: CommitFileAttributesEnum;
commit?: Commit;
/**
* The escaped version of the path as it appears in a diff. If the path does not require escaping this will be the same as path.
*/
escaped_path?: string;
/**
* The path in the repository
*/
path?: string;
type: string;
}
/**
* @public
*/
export const CommitFileAttributesEnum = {
Link: 'link',
Executable: 'executable',
Subrepository: 'subrepository',
Binary: 'binary',
Lfs: 'lfs',
} as const;
/**
* @public
*/
export type CommitFileAttributesEnum =
typeof CommitFileAttributesEnum[keyof typeof CommitFileAttributesEnum];
/**
* A link to a resource related to this object.
* @public
*/
export interface Link {
href?: string;
name?: string;
}
/**
* Base type for most resource objects. It defines the common `type` element that identifies an object's type. It also identifies the element as Swagger's `discriminator`.
* @public
*/
export interface ModelObject {
[key: string]: unknown;
type: string;
}
/**
* A generic paginated list.
* @public
*/
export interface Paginated<TResultItem> {
/**
* Link to the next page if it exists. The last page of a collection does not have this value. Use this link to navigate the result set and refrain from constructing your own URLs.
*/
next?: string;
/**
* Page number of the current results. This is an optional element that is not provided in all responses.
*/
page?: number;
/**
* Current number of objects on the existing page. The default value is 10 with 100 being the maximum allowed value. Individual APIs may enforce different values.
*/
pagelen?: number;
/**
* Link to previous page if it exists. A collections first page does not have this value. This is an optional element that is not provided in all responses. Some result sets strictly support forward navigation and never provide previous links. Clients must anticipate that backwards navigation is not always available. Use this link to navigate the result set and refrain from constructing your own URLs.
*/
previous?: string;
/**
* Total number of objects in the response. This is an optional element that is not provided in all responses, as it can be expensive to compute.
*/
size?: number;
/**
* The values of the current page.
*/
values?: Array<TResultItem> | Set<TResultItem>;
}
/**
* A paginated list of repositories.
* @public
*/
export interface PaginatedRepositories extends Paginated<Repository> {
/**
* The values of the current page.
*/
values?: Set<Repository>;
}
/**
* Object describing a user's role on resources like commits or pull requests.
* @public
*/
export interface Participant extends ModelObject {
approved?: boolean;
/**
* The ISO8601 timestamp of the participant's action. For approvers, this is the time of their approval. For commenters and pull request reviewers who are not approvers, this is the time they last commented, or null if they have not commented.
*/
participated_on?: string;
role?: ParticipantRoleEnum;
state?: ParticipantStateEnum;
user?: User;
}
/**
* @public
*/
export const ParticipantRoleEnum = {
Participant: 'PARTICIPANT',
Reviewer: 'REVIEWER',
} as const;
/**
* @public
*/
export type ParticipantRoleEnum =
typeof ParticipantRoleEnum[keyof typeof ParticipantRoleEnum];
/**
* @public
*/
export const ParticipantStateEnum = {
Approved: 'approved',
ChangesRequested: 'changes_requested',
Null: 'null',
} as const;
/**
* @public
*/
export type ParticipantStateEnum =
typeof ParticipantStateEnum[keyof typeof ParticipantStateEnum];
/**
* A Bitbucket project.
* Projects are used by teams to organize repositories.
* @public
*/
export interface Project extends ModelObject {
created_on?: string;
description?: string;
/**
*
* Indicates whether the project contains publicly visible repositories.
* Note that private projects cannot contain public repositories.
*/
has_publicly_visible_repos?: boolean;
/**
*
* Indicates whether the project is publicly accessible, or whether it is
* private to the team and consequently only visible to team members.
* Note that private projects cannot contain public repositories.
*/
is_private?: boolean;
/**
* The project's key.
*/
key?: string;
links?: ProjectLinks;
/**
* The name of the project.
*/
name?: string;
owner?: Team;
updated_on?: string;
/**
* The project's immutable id.
*/
uuid?: string;
}
/**
* @public
*/
export interface ProjectLinks {
avatar?: Link;
html?: Link;
}
/**
* @public
*/
export interface RefLinks {
commits?: Link;
html?: Link;
self?: Link;
}
/**
* A Bitbucket repository.
* @public
*/
export interface Repository extends ModelObject {
created_on?: string;
description?: string;
/**
*
* Controls the rules for forking this repository.
*
* * **allow_forks**: unrestricted forking
* * **no_public_forks**: restrict forking to private forks (forks cannot
* be made public later)
* * **no_forks**: deny all forking
*/
fork_policy?: RepositoryForkPolicyEnum;
/**
* The concatenation of the repository owner's username and the slugified name, e.g. "evzijst/interruptingcow". This is the same string used in Bitbucket URLs.
*/
full_name?: string;
has_issues?: boolean;
has_wiki?: boolean;
is_private?: boolean;
language?: string;
links?: RepositoryLinks;
mainbranch?: Branch;
name?: string;
owner?: Account;
parent?: Repository;
project?: Project;
scm?: RepositoryScmEnum;
size?: number;
/**
* The "sluggified" version of the repository's name. This contains only ASCII characters and can therefore be slightly different than the name
*/
slug?: string;
updated_on?: string;
/**
* The repository's immutable id. This can be used as a substitute for the slug segment in URLs. Doing this guarantees your URLs will survive renaming of the repository by its owner, or even transfer of the repository to a different user.
*/
uuid?: string;
}
/**
*
* Controls the rules for forking this repository.
*
* * **allow_forks**: unrestricted forking
* * **no_public_forks**: restrict forking to private forks (forks cannot
* be made public later)
* * **no_forks**: deny all forking
* @public
*/
export const RepositoryForkPolicyEnum = {
AllowForks: 'allow_forks',
NoPublicForks: 'no_public_forks',
NoForks: 'no_forks',
} as const;
/**
*
* Controls the rules for forking this repository.
*
* * **allow_forks**: unrestricted forking
* * **no_public_forks**: restrict forking to private forks (forks cannot
* be made public later)
* * **no_forks**: deny all forking
* @public
*/
export type RepositoryForkPolicyEnum =
typeof RepositoryForkPolicyEnum[keyof typeof RepositoryForkPolicyEnum];
/**
* @public
*/
export const RepositoryScmEnum = {
Git: 'git',
} as const;
/**
* @public
*/
export type RepositoryScmEnum =
typeof RepositoryScmEnum[keyof typeof RepositoryScmEnum];
/**
* @public
*/
export interface RepositoryLinks {
avatar?: Link;
clone?: Array<Link>;
commits?: Link;
downloads?: Link;
forks?: Link;
hooks?: Link;
html?: Link;
pullrequests?: Link;
self?: Link;
watchers?: Link;
}
/**
* @public
*/
export interface SearchCodeSearchResult {
readonly content_match_count?: number;
readonly content_matches?: Array<SearchContentMatch>;
file?: CommitFile;
readonly path_matches?: Array<SearchSegment>;
readonly type?: string;
}
/**
* @public
*/
export interface SearchContentMatch {
readonly lines?: Array<SearchLine>;
}
/**
* @public
*/
export interface SearchLine {
readonly line?: number;
readonly segments?: Array<SearchSegment>;
}
/**
* @public
*/
export interface SearchResultPage extends Paginated<SearchCodeSearchResult> {
readonly query_substituted?: boolean;
/**
* The values of the current page.
*/
readonly values?: Array<SearchCodeSearchResult>;
}
/**
* @public
*/
export interface SearchSegment {
readonly match?: boolean;
readonly text?: string;
}
/**
* A team object.
* @public
*/
export interface Team extends Account {}
/**
* A user object.
* @public
*/
export interface User extends Account {
/**
* The user's Atlassian account ID.
*/
account_id?: string;
is_staff?: boolean;
}
} | the_stack |
import { inspect } from 'util'
import { toFileKey } from './utils/id-utils'
import { enumerablizeWithPrototypeGetters } from './utils/object-utils'
import { createLayerEntitySelector } from './utils/selector-utils'
import { LayerCollectionFacade } from './layer-collection-facade'
import type { CancelToken } from '@avocode/cancel-token'
import type {
ArtboardId,
DesignLayerSelector,
IBitmap,
IBitmapMask,
IEffects,
ILayer,
IShape,
IText,
LayerId,
LayerOctopusData as LayerOctopusDataType,
LayerSelector,
TextFontDescriptor as FontDescriptor,
} from '@opendesign/octopus-reader'
import type { BlendingMode, Bounds, LayerBounds } from '@opendesign/rendering'
import type { ArtboardFacade } from './artboard-facade'
import type { DesignFacade } from './design-facade'
import type { BitmapAssetDescriptor } from './local/local-design'
export type { FontDescriptor }
type LayerType = LayerOctopusDataType['type']
export type LayerAttributes = {
blendingMode: BlendingMode
opacity: number
visible: boolean
}
export type LayerOctopusAttributesConfig = {
/** Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied. */
includeEffects?: boolean
/** Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results. */
clip?: boolean
/** The blending mode to use for rendering the layer instead of its default blending mode. */
blendingMode?: BlendingMode
/** The opacity to use for the layer instead of its default opacity. */
opacity?: number
}
// HACK: This makes TypeDoc not inline the whole type in the documentation.
/**
* @octopusschema Layer
*/
type LayerOctopusData = LayerOctopusDataType & {
type: LayerType
}
export class LayerFacade {
private _layerEntity: ILayer
private _designFacade: DesignFacade
/** @internal */
constructor(layerEntity: ILayer, params: { designFacade: DesignFacade }) {
this._layerEntity = layerEntity
this._designFacade = params.designFacade
enumerablizeWithPrototypeGetters(this)
}
/**
* The ID of the layer.
*
* Beware that this value may not be safely usable for naming files in the file system and the {@link fileKey} value should be instead.
*
* @category Identification
*/
get id(): LayerId {
return this._layerEntity.id
}
/**
* The key which can be used to name files in the file system. It SHOULD be unique within an artboard.
*
* IDs can include characters invalid for use in file names (such as `:`).
*
* @category Identification
*
* @example
* ```typescript
* // Safe:
* layer.renderToFile(`./layers/${layer.fileKey}.png`)
*
* // Unsafe:
* layer.renderToFile(`./layers/${layer.id}.png`)
* ```
*/
get fileKey(): string {
return toFileKey(this.id)
}
/**
* The name of the layer.
* @category Data
*/
get name(): string | null {
return this._layerEntity.name
}
/**
* The type of the layer.
* @category Data
*/
get type(): LayerType {
return this._layerEntity.type
}
/**
* Octopus data of the layer.
*
* This data can be used for accessing details about the layer.
*
* See the [Octopus Format](https://opendesign.dev/docs/octopus-format) documentation page for more info.
*
* @category Data
*
* @example
* ```typescript
* const blendMode = layer.octopus['blendMode']
* const opacity = layer.octopus['opacity']
* const visible = layer.octopus['visible']
* const overrides = layer.octopus['overrides']
* ```
*/
get octopus(): LayerOctopusData {
return this._layerEntity.octopus
}
/**
* The ID of the artboard in which the layer is placed.
* @category Reference
*/
get artboardId(): ArtboardId | null {
return this._layerEntity.artboardId
}
/** @internal */
toString(): string {
const layerInfo = this.toJSON()
return `Layer ${inspect(layerInfo)}`
}
/** @internal */
[inspect.custom](): string {
return this.toString()
}
/** @internal */
toJSON(): unknown {
return { ...this }
}
/** @internal */
getOctopusForAttributes(
attrs: LayerOctopusAttributesConfig & { visible?: boolean }
): LayerOctopusData {
const originalOctopus = this.octopus
return {
...originalOctopus,
'blendMode':
attrs.blendingMode == null
? originalOctopus['blendMode']
: attrs.blendingMode,
'opacity':
attrs.opacity == null ? originalOctopus['opacity'] : attrs.opacity,
'visible':
attrs.visible == null ? originalOctopus['visible'] : attrs.visible,
'effects': attrs.includeEffects == null ? originalOctopus['effects'] : {},
...(attrs.clip === false
? {
'clipped': Boolean(attrs.clip),
'maskedBy': undefined,
}
: {}),
}
}
/**
* Returns the artboard object associated with the layer object.
*
* @category Reference
* @returns An artboard object.
*
* @example
* ```typescript
* const artboard = layer.getArtboard()
* ```
*/
getArtboard(): ArtboardFacade | null {
const artboardId = this.artboardId
return artboardId ? this._designFacade.getArtboardById(artboardId) : null
}
/** @internal */
getLayerEntity(): ILayer {
return this._layerEntity
}
/**
* Returns whether the layer is located at the first level within the layer tree of the artboard (i.e. it does not have a parent layer).
*
* @category Layer Context
* @returns Whether the layer is a root layer.
*
* @example
* ```typescript
* const root = layer.isRootLayer()
* ```
*/
isRootLayer(): boolean {
return this._layerEntity.isRootLayer()
}
/**
* The nesting level at which the layer is contained within the layer tree of the artboard.
*
* Root (first-level) layers have depth of 1.
*
* @category Layer Context
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* console.log(rootLayer.depth) // 1
*
* const nestedLayer = rootLayer.getNestedLayers()[0]
* console.log(nestedLayer.depth) // 2
*
* const deeperNestedLayer = nestedLayer.getNestedLayers()[0]
* console.log(deeperNestedLayer.depth) // 3
* ```
*/
get depth(): number {
return this._layerEntity.getDepth()
}
/**
* Returns the immediate parent layer object which contains the layer.
*
* @category Layer Lookup
* @returns A parent layer object.
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* rootLayer.getParentLayer() // null
*
* const nestedLayer = rootLayer.getNestedLayers()[0]
* nestedLayer.getParentLayer() // rootLayer
*
* const deeperNestedLayer = nestedLayer.getNestedLayers()[0]
* deeperNestedLayer.getParentLayer() // nestedLayer
* ```
*/
getParentLayer(): LayerFacade | null {
const layerEntity = this._layerEntity.getParentLayer()
return layerEntity
? new LayerFacade(layerEntity, { designFacade: this._designFacade })
: null
}
/**
* Returns all parent layer objects which contain the layer sorted from the immediate parent layer to the first-level (root) layer.
*
* @category Layer Lookup
* @returns A collection of parent layer objects.
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* rootLayer.getParentLayers() // DesignLayerCollection []
*
* const nestedLayer = rootLayer.getNestedLayers()[0]
* nestedLayer.getParentLayers() // DesignLayerCollection [rootLayer]
*
* const deeperNestedLayer = nestedLayer.getNestedLayers()[0]
* deeperNestedLayer.getParentLayers() // DesignLayerCollection [nestedLayer, rootLayer]
* ```
*/
getParentLayers(): LayerCollectionFacade {
const layerEntities = this._layerEntity.getParentLayers()
return new LayerCollectionFacade(layerEntities, {
designFacade: this._designFacade,
})
}
/**
* Returns the IDs of all parent layers which contain the layer sorted from the immediate parent layer to the first-level (root) layer.
*
* @category Layer Lookup
* @returns A list of parent layer IDs.
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* rootLayer.getParentLayerIds() // []
*
* const nestedLayer = rootLayer.getNestedLayers()[0]
* nestedLayer.getParentLayerIds() // [rootLayer.id]
*
* const deeperNestedLayer = nestedLayer.getNestedLayers()[0]
* deeperNestedLayer.getParentLayerIds() // [nestedLayer.id, rootLayer.id]
* ```
*/
getParentLayerIds(): Array<LayerId> {
return this._layerEntity.getParentLayerIds()
}
/**
* Returns the deepest parent layer objects which contains the layer and matches the provided criteria.
*
* @category Layer Lookup
* @param selector A parent layer selector.
* @returns A matched parent layer object.
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* // Layer { id: 'x', type: 'groupLayer', name: 'A' }
*
* const nestedLayer1 = rootLayer.getNestedLayers()[0]
* // Layer { id: 'y', type: 'groupLayer', name: 'B' }
*
* const nestedLayer2 = nestedLayer1.getNestedLayers()[0]
* // Layer { id: 'z', type: 'groupLayer', name: 'A' }
*
* console.log(nestedLayer2.findParentLayer({ name: 'A' })) // Layer { id: 'z' }
* ```
*/
findParentLayer(selector: LayerSelector): LayerFacade | null {
const layerEntity = this._layerEntity.findParentLayer(selector)
return layerEntity
? new LayerFacade(layerEntity, { designFacade: this._designFacade })
: null
}
/**
* Returns all parent layer objects which contain the layer and match the provided criteria sorted from the immediate parent layer to the first-level (root) layer.
*
* @category Layer Lookup
* @param selector A parent layer selector.
* @returns A collection of matched parent layer objects.
*
* @example
* ```typescript
* const rootLayer = artboard.getRootLayers()[0]
* // Layer { id: 'x', type: 'groupLayer', name: 'A' }
*
* const nestedLayer1 = rootLayer.getNestedLayers()[0]
* // Layer { id: 'y', type: 'groupLayer', name: 'B' }
*
* const nestedLayer2 = nestedLayer1.getNestedLayers()[0]
* // Layer { id: 'z', type: 'groupLayer', name: 'A' }
*
* console.log(nestedLayer2.findParentLayers({ name: 'A' }))
* // DesignLayerCollection [ Layer { id: 'z' }, Layer { id: 'x' } ]
* ```
*/
findParentLayers(selector: LayerSelector): LayerCollectionFacade {
const layerEntities = this._layerEntity.findParentLayers(selector)
return new LayerCollectionFacade(layerEntities, {
designFacade: this._designFacade,
})
}
/**
* Returns whether there are any layers nested within the layer (i.e. the layer is the parent layer of other layers).
*
* This usually applies to group layers and expanded/inlined component layers. Empty group layers return `false`.
*
* @category Layer Lookup
* @returns Whether the layer has nested layers.
*
* @example
* ```typescript
* if (layer.hasNestedLayers()) {
* console.log(layer.getNestedLayers()) // DesignLayerCollection [ ...(layers)... ]
* } else {
* console.log(layer.getNestedLayers()) // DesignLayerCollection []
* }
* ```
*/
hasNestedLayers(): boolean {
return this._layerEntity.hasNestedLayers()
}
/**
* Returns a collection of layer objects nested within the layer (i.e. the layer is either the immediate parent layer of other layers or one of their parent layers), optionally down to a specific layer nesting level.
*
* This usually applies to group layers and expanded/inlined component layers. Empty group layers return an empty nested layer collection.
*
* Note that, in case of `depth` other than 1, the subtree is flattened in *document order*, not level by level, which means that nested layers of a layer are included before sibling layers of the layer.
*
* @category Layer Lookup
* @param options Options
* @param options.depth The maximum nesting level within the layer to include in the collection. By default, only the immediate nesting level is included. `Infinity` can be specified to get all nesting levels.
* @returns A collection of nested layers.
*
* @example
* ```typescript
* // Layer tree:
* // a {
* // b1 { c1, c2 },
* // b2 { c3 }
* // }
*
* const layerA = artboard.getLayerById('a')
*
* // Immediate nesting level
* console.log(layerA.getNestedLayers())
* // DesignLayerCollection [ Layer { id: 'b1' }, Layer { id: 'b2' } ]
*
* // All nesting levels
* console.log(layerA.getNestedLayers({ depth: 0 }))
* // DesignLayerCollection [
* // Layer { id: 'b1' },
* // Layer { id: 'c1' },
* // Layer { id: 'c2' },
* // Layer { id: 'b2' },
* // Layer { id: 'c3' },
* // ]
* ```
*/
getNestedLayers(options: { depth?: number } = {}): LayerCollectionFacade {
const layerEntities = this._layerEntity.getNestedLayers(options)
return new LayerCollectionFacade(layerEntities, {
designFacade: this._designFacade,
})
}
/**
* Returns the first layer object nested within the layer (i.e. the layer is either the immediate parent layer of other layers or one of their parent layers), optionally down to a specific layer nesting level, which matches the specific criteria.
*
* Note that the subtree is walked in *document order*, not level by level, which means that nested layers of a layer are searched before searching sibling layers of the layer.
*
* @category Layer Lookup
* @param selector A layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the layer to search. By default, all levels are searched. `0` also means "no limit"; `1` means only layers nested directly in the layer should be searched.
* @returns A matched layer object.
*
* @example
* ```typescript
* // Layer tree:
* // a {
* // b1 { c1, c2 },
* // b2 { c3 }
* // }
*
* const layerA = artboard.getLayerById('a')
*
* // All nesting levels
* console.log(layerA.findNestedLayer({ id: 'c1' }))
* // Layer { id: 'c1' },
*
* // Immediate nesting level
* console.log(layerA.findNestedLayer({ id: 'c1', depth: 0 }))
* // null
*
* // Function selectors
* console.log(layerA.findNestedLayer((layer) => {
* return layer.id === 'c1'
* }))
* // Layer { id: 'c1' },
* ```
*/
findNestedLayer(
selector: LayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number } = {}
): LayerFacade | null {
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerEntity = this._layerEntity.findNestedLayer(
entitySelector,
options
)
return layerEntity
? new LayerFacade(layerEntity, { designFacade: this._designFacade })
: null
}
/**
* Returns a collection of layer objects nested within the layer (i.e. the layer is either the immediate parent layer of other layers or one of their parent layers), optionally down to a specific layer nesting level, which match the specific criteria.
*
* Note that the results are sorted in *document order*, not level by level, which means that matching nested layers of a layer are included before matching sibling layers of the layer.
*
* @category Layer Lookup
* @param selector A layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within the layer to search. By default, all levels are searched. `0` also means "no limit"; `1` means only layers nested directly in the layer should be searched.
* @returns A collection of matched layers.
*
* @example
* ```typescript
* // Layer tree:
* // a {
* // b1 { c1, c2 },
* // b2 { c3 }
* // }
*
* const layerA = artboard.getLayerById('a')
*
* // All nesting levels
* console.log(layerA.findNestedLayers({ id: ['b1', 'c1', 'c3'] }))
* // DesignLayerCollection [
* // Layer { id: 'b1' },
* // Layer { id: 'c1' },
* // Layer { id: 'c3' },
* // ]
*
* // Immediate nesting level
* console.log(layerA.findNestedLayers({ id: ['b1', 'c1', 'c3'], depth: 0 }))
* // DesignLayerCollection [ Layer { id: 'b1' } ]
*
* // Function selectors
* console.log(layerA.findNestedLayers((layer) => {
* return layer.id === 'b1' || layer.id === 'c1'
* }))
* // DesignLayerCollection [ Layer { id: 'b1' }, Layer { id: 'c1' } ]
* ```
*/
findNestedLayers(
selector: LayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number } = {}
): LayerCollectionFacade {
const entitySelector = createLayerEntitySelector(
this._designFacade,
selector
)
const layerEntities = this._layerEntity.findNestedLayers(
entitySelector,
options
)
return new LayerCollectionFacade(layerEntities, {
designFacade: this._designFacade,
})
}
/**
* Returns whether the layer matches the provided selector.
*
* @category Layer Lookup
* @param selector The selector against which to test the layer.
* @returns Whether the layer matches.
*
* @example
* ```typescript
* console.log(layer.name) // A
* layer.matches({ name: 'A' }) // true
*
* console.log(layer.getText().getTextContent()) // This is text.
* layer.matches({ text: 'This is text.' }) // true
* ```
*/
matches(selector: DesignLayerSelector): boolean {
return this._layerEntity.matches(selector)
}
/**
* Returns whether the layer is masked/clipped by another layer.
*
* @category Layer Context
* @returns Whether the layer is masked.
*
* @example
* ```typescript
* if (layer.isMasked()) {
* layer.getMaskLayerId() // <MASK_ID>
* layer.getMaskLayer() // Layer { id: '<MASK_ID>' }
* } else {
* layer.getMaskLayerId() // null
* layer.getMaskLayer() // null
* }
* ```
*/
isMasked(): boolean {
return this._layerEntity.isMasked()
}
/**
* Returns the layer which masks/clips the layer if there is one.
*
* @category Layer Lookup
* @returns A mask layer object.
*
* @example
* ```typescript
* layer.getMaskLayer() // Layer { id: '<MASK_ID>' }
* layer.getMaskLayerId() // <MASK_ID>
* ```
*/
getMaskLayer(): LayerFacade | null {
const layerEntity = this._layerEntity.getMaskLayer()
return layerEntity
? new LayerFacade(layerEntity, { designFacade: this._designFacade })
: null
}
/**
* Returns the ID of the layer which masks/clips the layer if there is one.
*
* @category Layer Lookup
* @returns The ID of the mask layer.
*
* @example
* ```typescript
* const maskLayerId = layer.getMaskLayerId()
* ```
*/
getMaskLayerId(): LayerId | null {
return this._layerEntity.getMaskLayerId()
}
/**
* Returns whether the layer represents an "inline artboard" (which is a feature used in Photoshop design files only).
*
* @category Layer Context
* @returns Whether the layer is an inline artboard group layer.
*
* @example
* ```typescript
* const isInline = layer.isInlineArtboard()
* ```
*/
isInlineArtboard(): boolean {
return this._layerEntity.isInlineArtboard()
}
/**
* Returns whether the layer is a component (instance of a main/master component).
*
* @category Layer Context
* @returns Whether the layer is an instance of a component.
*
* @example
* ```typescript
* if (layer.isComponentInstance()) {
* console.log(layer.getComponentArtboard()) // Artboard
* }
* ```
*/
isComponentInstance(): boolean {
return this._layerEntity.isComponentInstance()
}
/**
* Returns whether there are any overrides on this component (instance) which override main/master component values.
*
* The specific overrides can be obtained from the octopus data (`octopus.overrides`).
*
* Layers which do not represent a component (instance), see {@link LayerFacade.isComponentInstance}, return `false`.
*
* @category Layer Context
* @returns Whether the layer is an instance of a component with overrides.
*
* @example
* ```typescript
* if (layer.hasComponentOverrides()) {
* const overrides = layer.octopus['overrides']
* }
* ```
*/
hasComponentOverrides(): boolean {
return this._layerEntity.hasComponentOverrides()
}
/**
* Returns the artboard which represents the main/master component of which this layer is and instance.
*
* Nothing is returned from layers which do not represent a component (instance), see {@link LayerFacade.isComponentInstance}.
*
* @category Reference
* @returns An artboard instance.
*
* @example
* ```typescript
* const componentArtboard = layer.getComponentArtboard()
* ```
*/
getComponentArtboard(): ArtboardFacade | null {
const componentArtboardEntity = this._layerEntity.getComponentArtboard()
return componentArtboardEntity
? this._designFacade.getArtboardById(componentArtboardEntity.id)
: null
}
/**
* Returns a list of bitmap assets used by the layer and layers nested within the layer (optionally down to a specific nesting level).
*
* Note that this method aggregates results of the more granular bitmap asset-related methods of {@link LayerFacade.getBitmap}, {@link LayerFacade.getBitmapMask} and pattern fill bitmap assets discoverable via {@link LayerFacade.getEffects}.
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within the layer to search for bitmap asset usage. By default, all levels are searched. Specifying the depth of `0` leads to nested layer bitmap assets being omitted altogether.
* @param options.includePrerendered Whether to also include "pre-rendered" bitmap assets. These assets can be produced by the rendering engine (if configured; future functionality) but are available as assets for either performance reasons or due to the some required data (such as font files) potentially not being available. By default, pre-rendered assets are included.
* @returns A list of bitmap assets.
*
* @example
* ```typescript
* // Bitmap assets from the layer and all its nested layers
* const bitmapAssetDescs = await layer.getBitmapAssets()
* ```
*/
getBitmapAssets(
options: { depth?: number; includePrerendered?: boolean } = {}
): Array<BitmapAssetDescriptor & { layerIds: Array<LayerId> }> {
return this._layerEntity.getBitmapAssets(options)
}
/**
* Returns a list of fonts used by the layer and layers nested within the layer (optionally down to a specific nesting level).
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search for font usage. By default, all levels are searched. Specifying the depth of `0` leads to fonts used by nested layers being omitted altogether.
* @returns A list of fonts.
*
* @example
* ```typescript
* // Fonts from the layer and all its nested layers
* const fontDescs = await layer.getFonts()
* ```
*/
getFonts(
options: { depth?: number } = {}
): Array<FontDescriptor & { layerIds: Array<LayerId> }> {
return this._layerEntity.getFonts(options)
}
/**
* Returns the bitmap asset of the layer if there is one.
*
* @category Asset
* @returns The bitmap of the layer.
*
* @example
* ```typescript
* const bitmap = layer.getBitmap()
* const bitmapAssetName = bitmap?.getBitmapAssetName()
* ```
*/
getBitmap(): IBitmap | null {
return (
this._layerEntity.getBitmap() || this._layerEntity.getPrerenderedBitmap()
)
}
/**
* Returns the bitmap mask of the layer if there is one.
*
* @category Asset
* @returns The bitmap mask of the layer.
*
* @example
* ```typescript
* const bitmapMask = layer.getBitmapMask()
* const bitmapMaskAssetName = bitmapMask?.getBitmap().getBitmapAssetName()
* ```
*/
getBitmapMask(): IBitmapMask | null {
return this._layerEntity.getBitmapMask()
}
/**
* Returns whether the bitmap asset is "pre-rendered".
*
* Only non-bitmap layers (`type!=layer`) have prerendered assets. Bitmap assets of bitmap layers are not considered "pre-rendered".
*
* @category Asset
* @returns Whether the layer bitmap is "pre-rendered".
*
* @example
* ```typescript
* const prerendered = layer.isBitmapPrerendered()
* const originalBitmap = prerendered ? null : layer.getBitmap()
* ```
*/
isBitmapPrerendered(): boolean {
return Boolean(this._layerEntity.getPrerenderedBitmap())
}
/**
* Returns a vector shape object of the layer if there is one.
*
* For non-shape layers (`type!=shapeLayer`), the returned shape acts as a vector mask.
*
* @internal
* @category Data
*/
getShape(): IShape | null {
return this._layerEntity.getShape()
}
/**
* Returns a text object of the layer if there is one.
*
* Only text layers (`type=textLayer`) return text objects here.
*
* @category Data
* @returns A text object of the layer.
*
* @example
* ```typescript
* const text = layer.getText()
* const textValue = text ? text.getTextContent() : null
* ```
*/
getText(): IText | null {
return this._layerEntity.getText()
}
/**
* Returns the text value of the layer if there is one.
*
* Only text layers (`type=textLayer`) return text objects here. This is a shortcut for `.getText()?.getTextContent()`
*
* @category Data
* @returns The text content string of the layer.
*
* @example
* ```typescript
* const textValue = layer.getTextContent()
* ```
*/
getTextContent(): string | null {
const text = this.getText()
return text ? text.getTextContent() : null
}
/**
* Returns a layer effect aggregation object.
*
* Any layer can have various effects (such as shadows, borders or fills) applied to it.
*
* Note that there can be bitmap assets in case of pattern fill effects being applied.
*
* @category Data
* @returns A layer effect object.
*
* @example
* ```typescript
* const effects = layer.getEffects()
* const shadows = effects.octopus['shadows']
* ```
*/
getEffects(): IEffects {
return this._layerEntity.getEffects()
}
/**
* Renders the layer as an PNG image file.
*
* In case the layer is a group layer, all visible nested layers are also included.
*
* Uncached items (bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.blendingMode The blending mode to use for rendering the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeComponentBackground Whether to render the component background from the main/master component. By default, the configuration from the main/master component is used. Note that this configuration has no effect when the artboard background is not included via explicit `includeComponentBackground=true` nor the main/master component configuration as there is nothing with which to blend the layer.
* @param options.includeEffects Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.bounds The area to include. This can be used to either crop or expand (add empty space to) the default layer area.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x, whole layer area)
* ```typescript
* await layer.renderToFile(
* './rendered/layer.png'
* )
* ```
*
* @example With custom scale and crop and using the component background color
* ```typescript
* await layer.renderToFile(
* './rendered/layer.png',
* {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* includeComponentBackground: true,
* }
* )
* ```
*/
async renderToFile(
filePath: string,
options: {
includeEffects?: boolean
clip?: boolean
includeComponentBackground?: boolean
blendingMode?: BlendingMode
opacity?: number
bounds?: Bounds
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const artboardId = this.artboardId
if (!artboardId) {
throw new Error('Detached layers cannot be rendered')
}
await this._designFacade.renderArtboardLayerToFile(
artboardId,
this.id,
filePath,
options
)
}
/**
* Returns an SVG document string of the layer.
*
* In case the layer is a group layer, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (bitmap assets of rendered layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG export
* @param options Export options
* @param options.blendingMode The blending mode to use for rendering the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeEffects Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
* @returns An SVG document string.
*
* @example With default options (1x)
* ```typescript
* const svg = await layer.exportToSvgCode()
* ```
*
* @example With custom scale and opacity
* ```typescript
* const svg = await layer.exportToSvgCode({
* opacity: 0.6,
* scale: 2,
* })
* ```
*/
async exportToSvgCode(
options: {
includeEffects?: boolean
clip?: boolean
blendingMode?: BlendingMode
opacity?: number
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<string> {
const artboardId = this.artboardId
if (!artboardId) {
throw new Error('Detached layers cannot be exported')
}
return this._designFacade.exportArtboardLayerToSvgCode(
artboardId,
this.id,
options
)
}
/**
* Export the layer as an SVG file.
*
* In case the layer is a group layer, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (bitmap assets of rendered layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG export
* @param filePath The target location of the produced SVG file.
* @param options Export options
* @param options.blendingMode The blending mode to use for rendering the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeEffects Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created image file is not deleted when cancelled during actual rendering). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x)
* ```typescript
* await layer.exportToSvgFile('./layer.svg')
* ```
*
* @example With custom scale and opacity
* ```typescript
* await layer.exportToSvgFile('./layer.svg', {
* opacity: 0.6,
* scale: 2,
* })
* ```
*/
async exportToSvgFile(
filePath: string,
options: {
includeEffects?: boolean
clip?: boolean
blendingMode?: BlendingMode
opacity?: number
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const artboardId = this.artboardId
if (!artboardId) {
throw new Error('Detached layers cannot be exported')
}
await this._designFacade.exportArtboardLayerToSvgFile(
artboardId,
this.id,
filePath,
options
)
}
/**
* Returns various bounds of the layer.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Data
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the artboards is not uncached when newly cached). A cancellation token can be created via {@link createCancelToken}.
* @returns Various layer bounds.
*
* @example
* ```typescript
* const layerBounds = await layer.getBounds()
* const boundsWithEffects = layerBounds.fullBounds
* ```
*/
async getBounds(
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerBounds> {
const artboardId = this.artboardId
if (!artboardId) {
throw new Error('Detached layers cannot be rendered')
}
return this._designFacade.getArtboardLayerBounds(
artboardId,
this.id,
options
)
}
/**
* Returns the attributes of the layer.
*
* @category Data
* @returns Layer attributes.
*
* @example
* ```typescript
* const { blendingMode, opacity, visible } = await layer.getAttributes()
* ```
*/
async getAttributes(): Promise<LayerAttributes> {
const octopus = this.octopus
return {
blendingMode:
octopus['blendMode'] ||
(this.type === 'groupLayer' ? 'PASS_THROUGH' : 'NORMAL'),
opacity: octopus['opacity'] == null ? 1 : octopus['opacity'],
visible: octopus['visible'] !== false,
}
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_incidenttype_Information {
interface tab__C6408E85_49E7_4216_BF96_986A20C64ECB_Sections {
_2405DB6B_E18C_49E5_A76B_505837745C84: DevKit.Controls.Section;
_AA02FBB3_348E_4F8C_BC8E_1FE3F9BD7D90: DevKit.Controls.Section;
_C6408E85_49E7_4216_BF96_986A20C64ECB_SECTION_2: DevKit.Controls.Section;
}
interface tab_f1tab_details_Sections {
KnowledgeArticleSection: DevKit.Controls.Section;
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_Incident_Type_Resolutions_Sections {
tab_8_section_1: DevKit.Controls.Section;
}
interface tab_tab_4_Sections {
tab_4_section_1: DevKit.Controls.Section;
}
interface tab_tab_5_Sections {
tab_5_section_1: DevKit.Controls.Section;
}
interface tab_tab_6_Sections {
tab_6_section_1: DevKit.Controls.Section;
}
interface tab_tab_7_Sections {
tab_7_section_1: DevKit.Controls.Section;
}
interface tab__C6408E85_49E7_4216_BF96_986A20C64ECB extends DevKit.Controls.ITab {
Section: tab__C6408E85_49E7_4216_BF96_986A20C64ECB_Sections;
}
interface tab_f1tab_details extends DevKit.Controls.ITab {
Section: tab_f1tab_details_Sections;
}
interface tab_Incident_Type_Resolutions extends DevKit.Controls.ITab {
Section: tab_Incident_Type_Resolutions_Sections;
}
interface tab_tab_4 extends DevKit.Controls.ITab {
Section: tab_tab_4_Sections;
}
interface tab_tab_5 extends DevKit.Controls.ITab {
Section: tab_tab_5_Sections;
}
interface tab_tab_6 extends DevKit.Controls.ITab {
Section: tab_tab_6_Sections;
}
interface tab_tab_7 extends DevKit.Controls.ITab {
Section: tab_tab_7_Sections;
}
interface Tabs {
_C6408E85_49E7_4216_BF96_986A20C64ECB: tab__C6408E85_49E7_4216_BF96_986A20C64ECB;
f1tab_details: tab_f1tab_details;
Incident_Type_Resolutions: tab_Incident_Type_Resolutions;
tab_4: tab_tab_4;
tab_5: tab_tab_5;
tab_6: tab_tab_6;
tab_7: tab_tab_7;
}
interface Body {
Tab: Tabs;
msdyn_CopyIncidentItemstoAgreement: DevKit.Controls.Boolean;
/** Unique identifier for Work Order Type associated with Incident Type. */
msdyn_DefaultWorkOrderType: DevKit.Controls.Lookup;
/** Incident Type description. This will be the default description shown on the work order */
msdyn_Description: DevKit.Controls.String;
msdyn_EstimatedDuration: DevKit.Controls.Integer;
/** Shows date and time when the Suggested Duration value was updated. */
msdyn_LastCalculatedTime: DevKit.Controls.DateTime;
/** Incident Type name */
msdyn_name: DevKit.Controls.String;
/** Suggested duration is average of actual duration of historical bookings with the same incident type */
msdyn_SuggestedDuration: DevKit.Controls.Integer;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Incident Type */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
nav_msdyn_incidenttype_requirementgroup_incident: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_incident_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_agreementbookingincident_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_incidenttypecharacteristic_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_incidenttypeproduct_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_incidenttyperesolution_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_incidenttypeservice_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_incidenttypeservicetask_IncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_workorder_PrimaryIncidentType: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_incidenttype_msdyn_workorderincident_IncidentType: DevKit.Controls.NavigationItem,
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
KnowledgeArticle_IncidentType: DevKit.Controls.Grid;
incidentproductssubgrid: DevKit.Controls.Grid;
incidentservicessubgrid: DevKit.Controls.Grid;
servicetasksgrid: DevKit.Controls.Grid;
Characteristics: DevKit.Controls.Grid;
Incident_Type_Resolutions: DevKit.Controls.Grid;
}
}
class Formmsdyn_incidenttype_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_incidenttype_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_incidenttype_Information */
Body: DevKit.Formmsdyn_incidenttype_Information.Body;
/** The Footer section of form msdyn_incidenttype_Information */
Footer: DevKit.Formmsdyn_incidenttype_Information.Footer;
/** The Navigation of form msdyn_incidenttype_Information */
Navigation: DevKit.Formmsdyn_incidenttype_Information.Navigation;
/** The Grid of form msdyn_incidenttype_Information */
Grid: DevKit.Formmsdyn_incidenttype_Information.Grid;
}
class msdyn_incidenttypeApi {
/**
* DynamicsCrm.DevKit msdyn_incidenttypeApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
msdyn_CopyIncidentItemstoAgreement: DevKit.WebApi.BooleanValue;
/** Unique identifier for Work Order Type associated with Incident Type. */
msdyn_DefaultWorkOrderType: DevKit.WebApi.LookupValue;
/** Incident Type description. This will be the default description shown on the work order */
msdyn_Description: DevKit.WebApi.StringValue;
msdyn_EstimatedDuration: DevKit.WebApi.IntegerValue;
/** Shows the entity instances. */
msdyn_incidenttypeId: DevKit.WebApi.GuidValue;
/** Shows date and time when the Suggested Duration value was updated. */
msdyn_LastCalculatedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Incident Type name */
msdyn_name: DevKit.WebApi.StringValue;
msdyn_ResolutionRequiredonWOCompletion: DevKit.WebApi.BooleanValue;
/** Suggested duration is average of actual duration of historical bookings with the same incident type */
msdyn_SuggestedDuration: DevKit.WebApi.IntegerValue;
/** Shows the date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Incident Type */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Incident Type */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_incidenttype {
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.